Merge branch 'develop' into global_search_modules

This commit is contained in:
Himanshu 2019-10-02 16:36:19 +05:30 committed by GitHub
commit 2985cffc52
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
36 changed files with 1052 additions and 2834 deletions

View File

@ -3,7 +3,7 @@
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe import _, scrub
from frappe.utils import flt, cint
from erpnext.accounts.party import get_partywise_advanced_payment_amount
from erpnext.accounts.report.accounts_receivable.accounts_receivable import ReceivablePayableReport
@ -40,7 +40,7 @@ class AccountsReceivableSummary(ReceivablePayableReport):
row.party = party
if self.party_naming_by == "Naming Series":
row.party_name = frappe.get_cached_value(self.party_type, party, [self.party_type + "_name"])
row.party_name = frappe.get_cached_value(self.party_type, party, scrub(self.party_type) + "_name")
row.update(party_dict)

View File

@ -0,0 +1,30 @@
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
/* eslint-disable */
frappe.query_reports["Fixed Asset Register"] = {
"filters": [
{
fieldname:"company",
label: __("Company"),
fieldtype: "Link",
options: "Company",
default: frappe.defaults.get_user_default("Company"),
reqd: 1
},
{
fieldname:"status",
label: __("Status"),
fieldtype: "Select",
options: "In Store\nDisposed",
default: 'In Store',
reqd: 1
},
{
fieldname:"finance_book",
label: __("Finance Book"),
fieldtype: "Link",
options: "Finance Book"
},
]
};

View File

@ -0,0 +1,27 @@
{
"add_total_row": 0,
"creation": "2019-09-23 16:35:02.836134",
"disable_prepared_report": 0,
"disabled": 0,
"docstatus": 0,
"doctype": "Report",
"idx": 0,
"is_standard": "Yes",
"modified": "2019-09-23 16:35:02.836134",
"modified_by": "Administrator",
"module": "Assets",
"name": "Fixed Asset Register",
"owner": "Administrator",
"prepared_report": 0,
"ref_doctype": "Asset",
"report_name": "Fixed Asset Register",
"report_type": "Script Report",
"roles": [
{
"role": "Accounts User"
},
{
"role": "Quality Manager"
}
]
}

View File

@ -0,0 +1,172 @@
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None):
filters = frappe._dict(filters or {})
columns = get_columns(filters)
data = get_data(filters)
return columns, data
def get_columns(filters):
return [
{
"label": _("Asset Id"),
"fieldtype": "Link",
"fieldname": "asset_id",
"options": "Asset",
"width": 100
},
{
"label": _("Asset Name"),
"fieldtype": "Data",
"fieldname": "asset_name",
"width": 140
},
{
"label": _("Asset Category"),
"fieldtype": "Link",
"fieldname": "asset_category",
"options": "Asset Category",
"width": 100
},
{
"label": _("Status"),
"fieldtype": "Data",
"fieldname": "status",
"width": 90
},
{
"label": _("Cost Center"),
"fieldtype": "Link",
"fieldname": "cost_center",
"options": "Cost Center",
"width": 100
},
{
"label": _("Department"),
"fieldtype": "Link",
"fieldname": "department",
"options": "Department",
"width": 100
},
{
"label": _("Location"),
"fieldtype": "Link",
"fieldname": "location",
"options": "Location",
"width": 100
},
{
"label": _("Purchase Date"),
"fieldtype": "Date",
"fieldname": "purchase_date",
"width": 90
},
{
"label": _("Gross Purchase Amount"),
"fieldname": "gross_purchase_amount",
"options": "Currency",
"width": 90
},
{
"label": _("Vendor Name"),
"fieldtype": "Data",
"fieldname": "vendor_name",
"width": 100
},
{
"label": _("Available For Use Date"),
"fieldtype": "Date",
"fieldname": "available_for_use_date",
"width": 90
},
{
"label": _("Current Value"),
"fieldname": "current_value",
"options": "Currency",
"width": 90
},
]
def get_conditions(filters):
conditions = {'docstatus': 1}
status = filters.status
if filters.company:
conditions["company"] = filters.company
# In Store assets are those that are not sold or scrapped
operand = 'not in'
if status not in 'In Store':
operand = 'in'
conditions['status'] = (operand, ['Sold', 'Scrapped'])
return conditions
def get_data(filters):
data = []
conditions = get_conditions(filters)
current_value_map = get_finance_book_value_map(filters.finance_book)
pr_supplier_map = get_purchase_receipt_supplier_map()
pi_supplier_map = get_purchase_invoice_supplier_map()
assets_record = frappe.db.get_all("Asset",
filters=conditions,
fields=["name", "asset_name", "department", "cost_center", "purchase_receipt",
"asset_category", "purchase_date", "gross_purchase_amount", "location",
"available_for_use_date", "status", "purchase_invoice"])
for asset in assets_record:
if current_value_map.get(asset.name) is not None:
row = {
"asset_id": asset.name,
"asset_name": asset.asset_name,
"status": asset.status,
"department": asset.department,
"cost_center": asset.cost_center,
"vendor_name": pr_supplier_map.get(asset.purchase_receipt) or pi_supplier_map.get(asset.purchase_invoice),
"gross_purchase_amount": asset.gross_purchase_amount,
"available_for_use_date": asset.available_for_use_date,
"location": asset.location,
"asset_category": asset.asset_category,
"purchase_date": asset.purchase_date,
"current_value": current_value_map.get(asset.name)
}
data.append(row)
return data
def get_finance_book_value_map(finance_book=''):
return frappe._dict(frappe.db.sql(''' Select
parent, value_after_depreciation
FROM `tabAsset Finance Book`
WHERE
parentfield='finance_books'
AND finance_book=%s''', (finance_book)))
def get_purchase_receipt_supplier_map():
return frappe._dict(frappe.db.sql(''' Select
pr.name, pr.supplier
FROM `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pri
WHERE
pri.parent = pr.name
AND pri.is_fixed_asset=1
AND pr.docstatus=1
AND pr.is_return=0'''))
def get_purchase_invoice_supplier_map():
return frappe._dict(frappe.db.sql(''' Select
pi.name, pi.supplier
FROM `tabPurchase Invoice` pi, `tabPurchase Invoice Item` pii
WHERE
pii.parent = pi.name
AND pii.is_fixed_asset=1
AND pi.docstatus=1
AND pi.is_return=0'''))

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,6 @@
{
"allow_import": 1,
"allow_rename": 1,
"autoname": "naming_series:",
"creation": "2013-03-07 18:50:30",
"description": "Potential Sales Deal",
@ -411,7 +412,7 @@
],
"icon": "fa fa-info-sign",
"idx": 195,
"modified": "2019-09-12 09:37:30.127901",
"modified": "2019-09-30 12:58:37.385400",
"modified_by": "Administrator",
"module": "CRM",
"name": "Opportunity",

View File

@ -19,6 +19,7 @@ def store_request_data(order=None, event=None):
dump_request_data(order, event)
def sync_sales_order(order, request_id=None):
frappe.set_user('Administrator')
shopify_settings = frappe.get_doc("Shopify Settings")
frappe.flags.request_id = request_id
@ -33,6 +34,7 @@ def sync_sales_order(order, request_id=None):
make_shopify_log(status="Success")
def prepare_sales_invoice(order, request_id=None):
frappe.set_user('Administrator')
shopify_settings = frappe.get_doc("Shopify Settings")
frappe.flags.request_id = request_id
@ -45,6 +47,7 @@ def prepare_sales_invoice(order, request_id=None):
make_shopify_log(status="Error", exception=True)
def prepare_delivery_note(order, request_id=None):
frappe.set_user('Administrator')
shopify_settings = frappe.get_doc("Shopify Settings")
frappe.flags.request_id = request_id
@ -137,6 +140,7 @@ def create_sales_invoice(shopify_order, shopify_settings, so):
si.naming_series = shopify_settings.sales_invoice_series or "SI-Shopify-"
si.flags.ignore_mandatory = True
set_cost_center(si.items, shopify_settings.cost_center)
si.insert(ignore_mandatory=True)
si.submit()
make_payament_entry_against_sales_invoice(si, shopify_settings)
frappe.db.commit()
@ -151,6 +155,7 @@ def make_payament_entry_against_sales_invoice(doc, shopify_settings):
payemnt_entry.flags.ignore_mandatory = True
payemnt_entry.reference_no = doc.name
payemnt_entry.reference_date = nowdate()
payemnt_entry.insert(ignore_permissions=True)
payemnt_entry.submit()
def create_delivery_note(shopify_order, shopify_settings, so):
@ -168,6 +173,7 @@ def create_delivery_note(shopify_order, shopify_settings, so):
dn.items = get_fulfillment_items(dn.items, fulfillment.get("line_items"), shopify_settings)
dn.flags.ignore_mandatory = True
dn.save()
dn.submit()
frappe.db.commit()
def get_fulfillment_items(dn_items, fulfillment_items, shopify_settings):
@ -200,7 +206,7 @@ def get_order_items(order_items, shopify_settings):
"rate": shopify_item.get("price"),
"delivery_date": nowdate(),
"qty": shopify_item.get("quantity"),
"stock_uom": shopify_item.get("sku"),
"stock_uom": shopify_item.get("uom") or _("Nos"),
"warehouse": shopify_settings.warehouse
})
else:

View File

@ -4,10 +4,7 @@
from __future__ import unicode_literals
import frappe, time, dateutil, math, csv
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from six import StringIO
import erpnext.erpnext_integrations.doctype.amazon_mws_settings.amazon_mws_api as mws
from frappe import _
@ -26,7 +23,7 @@ def get_products_details():
listings_response = reports.get_report(report_id=report_id)
#Get ASIN Codes
string_io = StringIO(listings_response.original)
string_io = StringIO(frappe.safe_decode(listings_response.original))
csv_rows = list(csv.reader(string_io, delimiter=str('\t')))
asin_list = list(set([row[1] for row in csv_rows[1:]]))
#break into chunks of 10
@ -294,7 +291,8 @@ def create_sales_order(order_json,after_date):
so.submit()
except Exception as e:
frappe.log_error(message=e, title="Create Sales Order")
import traceback
frappe.log_error(message=traceback.format_exc(), title="Create Sales Order")
def create_customer(order_json):
order_customer_name = ""
@ -451,7 +449,7 @@ def get_charges_and_fees(market_place_order_id):
shipment_item_list = return_as_list(shipment_event.ShipmentEvent.ShipmentItemList.ShipmentItem)
for shipment_item in shipment_item_list:
charges, fees = []
charges, fees = [], []
if 'ItemChargeList' in shipment_item.keys():
charges = return_as_list(shipment_item.ItemChargeList.ChargeComponent)

View File

@ -65,7 +65,8 @@ def calc_md5(string):
"""
md = hashlib.md5()
md.update(string)
return base64.encodestring(md.digest()).strip('\n')
return base64.encodestring(md.digest()).strip('\n') if six.PY2 \
else base64.encodebytes(md.digest()).decode().strip()
def remove_empty(d):
"""
@ -87,8 +88,7 @@ class DictWrapper(object):
self.original = xml
self._rootkey = rootkey
self._mydict = xml_utils.xml2dict().fromstring(remove_namespace(xml))
self._response_dict = self._mydict.get(self._mydict.keys()[0],
self._mydict)
self._response_dict = self._mydict.get(list(self._mydict)[0], self._mydict)
@property
def parsed(self):

View File

@ -21,33 +21,22 @@ class ShopifySettings(Document):
else:
self.unregister_webhooks()
self.validate_app_type()
def validate_access_credentials(self):
if self.app_type == "Private":
if not (self.get_password(raise_exception=False) and self.api_key and self.shopify_url):
frappe.msgprint(_("Missing value for Password, API Key or Shopify URL"), raise_exception=frappe.ValidationError)
else:
if not (self.access_token and self.shopify_url):
frappe.msgprint(_("Access token or Shopify URL missing"), raise_exception=frappe.ValidationError)
def validate_app_type(self):
if self.app_type == "Public":
frappe.throw(_("Support for public app is deprecated. Please setup private app, for more details refer user manual"))
if not (self.get_password(raise_exception=False) and self.api_key and self.shopify_url):
frappe.msgprint(_("Missing value for Password, API Key or Shopify URL"), raise_exception=frappe.ValidationError)
def register_webhooks(self):
webhooks = ["orders/create", "orders/paid", "orders/fulfilled"]
url = get_shopify_url('admin/webhooks.json', self)
# url = get_shopify_url('admin/webhooks.json', self)
created_webhooks = [d.method for d in self.webhooks]
url = get_shopify_url('admin/api/2019-04/webhooks.json', self)
print('url', url)
for method in webhooks:
if method in created_webhooks:
continue
print('method', method)
session = get_request_session()
print('session', session)
try:
print(get_header(self))
d = session.post(url, data=json.dumps({
"webhook": {
"topic": method,
@ -55,6 +44,7 @@ class ShopifySettings(Document):
"format": "json"
}
}), headers=get_header(self))
print('d', d.json())
d.raise_for_status()
self.update_webhook_table(method, d.json())
except Exception as e:
@ -65,7 +55,7 @@ class ShopifySettings(Document):
deleted_webhooks = []
for d in self.webhooks:
url = get_shopify_url('admin/webhooks/{0}.json'.format(d.webhook_id), self)
url = get_shopify_url('admin/api/2019-04/webhooks.json'.format(d.webhook_id), self)
try:
res = session.delete(url, headers=get_header(self))
res.raise_for_status()
@ -77,6 +67,7 @@ class ShopifySettings(Document):
self.remove(d)
def update_webhook_table(self, method, res):
print('update')
self.append("webhooks", {
"webhook_id": res['webhook']['id'],
"method": method
@ -84,6 +75,7 @@ class ShopifySettings(Document):
def get_shopify_url(path, settings):
if settings.app_type == "Private":
print(settings.api_key, settings.get_password('password'), settings.shopify_url, path)
return 'https://{}:{}@{}/{}'.format(settings.api_key, settings.get_password('password'), settings.shopify_url, path)
else:
return 'https://{}/{}'.format(settings.shopify_url, path)
@ -91,11 +83,7 @@ def get_shopify_url(path, settings):
def get_header(settings):
header = {'Content-Type': 'application/json'}
if settings.app_type == "Private":
return header
else:
header["X-Shopify-Access-Token"] = settings.access_token
return header
return header;
@frappe.whitelist()
def get_series():

View File

@ -21,7 +21,7 @@ def create_customer(shopify_customer, shopify_settings):
"customer_type": _("Individual")
})
customer.flags.ignore_mandatory = True
customer.insert()
customer.insert(ignore_permissions=True)
if customer:
create_customer_address(customer, shopify_customer)

View File

@ -1,13 +1,14 @@
from __future__ import unicode_literals
import frappe
from frappe import _
from erpnext import get_default_company
from frappe.utils import cstr, cint, get_request_session
from erpnext.erpnext_integrations.doctype.shopify_settings.shopify_settings import get_shopify_url, get_header
shopify_variants_attr_list = ["option1", "option2", "option3"]
def sync_item_from_shopify(shopify_settings, item):
url = get_shopify_url("/admin/products/{0}.json".format(item.get("product_id")), shopify_settings)
url = get_shopify_url("admin/api/2019-04/products/{0}.json".format(item.get("product_id")), shopify_settings)
session = get_request_session()
try:
@ -107,7 +108,12 @@ def create_item(shopify_item, warehouse, has_variant=0, attributes=None,variant_
"image": get_item_image(shopify_item),
"weight_uom": shopify_item.get("weight_unit"),
"weight_per_unit": shopify_item.get("weight"),
"default_supplier": get_supplier(shopify_item)
"default_supplier": get_supplier(shopify_item),
"item_defaults": [
{
"company": get_default_company()
}
]
}
if not is_item_exists(item_dict, attributes, variant_of=variant_of):
@ -116,7 +122,7 @@ def create_item(shopify_item, warehouse, has_variant=0, attributes=None,variant_
if not item_details:
new_item = frappe.get_doc(item_dict)
new_item.insert()
new_item.insert(ignore_permissions=True, ignore_mandatory=True)
name = new_item.name
if not name:

View File

@ -40,6 +40,7 @@ class ShopifySettings(unittest.TestCase):
"price_list": "_Test Price List",
"warehouse": "_Test Warehouse - _TC",
"cash_bank_account": "Cash - _TC",
"account": "Cash - _TC",
"customer_group": "_Test Customer Group",
"cost_center": "Main - _TC",
"taxes": [

View File

@ -40,4 +40,4 @@ def get_webhook_address(connector_name, method, exclude_uri=False):
server_url = '{uri.scheme}://{uri.netloc}/api/method/{endpoint}'.format(uri=urlparse(url), endpoint=endpoint)
return server_url
return server_url

View File

@ -347,13 +347,25 @@
"icon": "fa fa-user",
"image_field": "image",
"max_attachments": 50,
"modified": "2019-09-23 16:01:39.811633",
"modified": "2019-09-25 23:30:49.905893",
"modified_by": "Administrator",
"module": "Healthcare",
"name": "Patient",
"name_case": "Title Case",
"owner": "Administrator",
"permissions": [
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "System Manager",
"share": 1,
"write": 1
},
{
"create": 1,
"delete": 1,

View File

@ -42,6 +42,8 @@ notification_config = "erpnext.startup.notifications.get_notification_config"
get_help_messages = "erpnext.utilities.activation.get_help_messages"
get_user_progress_slides = "erpnext.utilities.user_progress.get_user_progress_slides"
update_and_get_user_progress = "erpnext.utilities.user_progress_utils.update_default_domain_actions_and_get_state"
leaderboards = "erpnext.startup.leaderboard.get_leaderboards"
on_session_creation = "erpnext.shopping_cart.utils.set_cart_count"
on_logout = "erpnext.shopping_cart.utils.clear_cart_count"

View File

@ -60,7 +60,10 @@ def get_data(filters, leave_types):
data = []
for employee in active_employees:
leave_approvers = department_approver_map.get(employee.department_name, []).append(employee.leave_approver)
leave_approvers = department_approver_map.get(employee.department_name, [])
if employee.leave_approver:
leave_approvers.append(employee.leave_approver)
if (len(leave_approvers) and user in leave_approvers) or (user in ["Administrator", employee.user_id]) or ("HR Manager" in frappe.get_roles(user)):
row = [employee.name, employee.employee_name, employee.department]

View File

@ -195,6 +195,7 @@ class ProductionPlan(Document):
for data in self.po_items:
if data.name == production_plan_item:
data.produced_qty = produced_qty
data.pending_qty = data.planned_qty - data.produced_qty
data.db_update()
self.calculate_total_produced_qty()

View File

@ -545,11 +545,14 @@ erpnext.work_order = {
get_max_transferable_qty: (frm, purpose) => {
let max = 0;
if (frm.doc.skip_transfer) return max;
if (purpose === 'Manufacture') {
max = flt(frm.doc.material_transferred_for_manufacturing) - flt(frm.doc.produced_qty);
if (frm.doc.skip_transfer) {
max = flt(frm.doc.qty) - flt(frm.doc.produced_qty);
} else {
max = flt(frm.doc.qty) - flt(frm.doc.material_transferred_for_manufacturing);
if (purpose === 'Manufacture') {
max = flt(frm.doc.material_transferred_for_manufacturing) - flt(frm.doc.produced_qty);
} else {
max = flt(frm.doc.qty) - flt(frm.doc.material_transferred_for_manufacturing);
}
}
return flt(max, precision('qty'));
},

View File

@ -638,3 +638,5 @@ erpnext.patches.v12_0.add_variant_of_in_item_attribute_table
erpnext.patches.v12_0.rename_bank_account_field_in_journal_entry_account
erpnext.patches.v12_0.create_default_energy_point_rules
erpnext.patches.v12_0.set_produced_qty_field_in_sales_order_for_work_order
erpnext.patches.v12_0.generate_leave_ledger_entries
erpnext.patches.v12_0.set_default_shopify_app_type

View File

@ -0,0 +1,6 @@
from __future__ import unicode_literals
import frappe
def execute():
frappe.reload_doc('erpnext_integrations', 'doctype', 'shopify_settings')
frappe.db.set_value('Shopify Settings', None, 'app_type', 'Private')

View File

@ -108,7 +108,7 @@
"fieldname": "percent_complete_method",
"fieldtype": "Select",
"label": "% Complete Method",
"options": "Task Completion\nTask Progress\nTask Weight"
"options": "Manual\nTask Completion\nTask Progress\nTask Weight"
},
{
"bold": 1,

View File

@ -87,6 +87,11 @@ class Project(Document):
frappe.db.set_value("Sales Order", self.sales_order, "project", self.name)
def update_percent_complete(self):
if self.percent_complete_method == "Manual":
if self.status == "Completed":
self.percent_complete = 100
return
total = frappe.db.count('Task', dict(project=self.name))
if not total:

View File

@ -19,6 +19,9 @@
{% if(contact_list[i].phone) { %}
{%= __("Phone") %}: {%= contact_list[i].phone %}<span class="text-muted"> ({%= __("Primary") %})</span><br>
{% endif %}
{% if(contact_list[i].mobile_no) { %}
{%= __("Mobile No") %}: {%= contact_list[i].mobile_no %}<span class="text-muted"> ({%= __("Primary") %})</span><br>
{% endif %}
{% if(contact_list[i].phone_nos) { %}
{% for(var j=0, k=contact_list[i].phone_nos.length; j<k; j++) { %}
{%= __("Phone") %}: {%= contact_list[i].phone_nos[j].phone %}<br>

View File

@ -64,16 +64,19 @@ class Company(NestedSet):
})
def validate_default_accounts(self):
for field in ["default_bank_account", "default_cash_account",
accounts = [
"default_bank_account", "default_cash_account",
"default_receivable_account", "default_payable_account",
"default_expense_account", "default_income_account",
"stock_received_but_not_billed", "stock_adjustment_account",
"expenses_included_in_valuation", "default_payroll_payable_account"]:
if self.get(field):
for_company = frappe.db.get_value("Account", self.get(field), "company")
if for_company != self.name:
frappe.throw(_("Account {0} does not belong to company: {1}")
.format(self.get(field), self.name))
"expenses_included_in_valuation", "default_payroll_payable_account"
]
for field in accounts:
if self.get(field):
for_company = frappe.db.get_value("Account", self.get(field), "company")
if for_company != self.name:
frappe.throw(_("Account {0} does not belong to company: {1}").format(self.get(field), self.name))
def validate_currency(self):
if self.is_new():
@ -180,21 +183,29 @@ class Company(NestedSet):
self.existing_company = self.parent_company
def set_default_accounts(self):
self._set_default_account("default_cash_account", "Cash")
self._set_default_account("default_bank_account", "Bank")
self._set_default_account("round_off_account", "Round Off")
self._set_default_account("accumulated_depreciation_account", "Accumulated Depreciation")
self._set_default_account("depreciation_expense_account", "Depreciation")
self._set_default_account("capital_work_in_progress_account", "Capital Work in Progress")
self._set_default_account("asset_received_but_not_billed", "Asset Received But Not Billed")
self._set_default_account("expenses_included_in_asset_valuation", "Expenses Included In Asset Valuation")
default_accounts = {
"default_cash_account": "Cash",
"default_bank_account": "Bank",
"round_off_account": "Round Off",
"accumulated_depreciation_account": "Accumulated Depreciation",
"depreciation_expense_account": "Depreciation",
"capital_work_in_progress_account": "Capital Work in Progress",
"asset_received_but_not_billed": "Asset Received But Not Billed",
"expenses_included_in_asset_valuation": "Expenses Included In Asset Valuation"
}
if self.enable_perpetual_inventory:
self._set_default_account("stock_received_but_not_billed", "Stock Received But Not Billed")
self._set_default_account("default_inventory_account", "Stock")
self._set_default_account("stock_adjustment_account", "Stock Adjustment")
self._set_default_account("expenses_included_in_valuation", "Expenses Included In Valuation")
self._set_default_account("default_expense_account", "Cost of Goods Sold")
default_accounts.update({
"stock_received_but_not_billed": "Stock Received But Not Billed",
"default_inventory_account": "Stock",
"stock_adjustment_account": "Stock Adjustment",
"expenses_included_in_valuation": "Expenses Included In Valuation",
"default_expense_account": "Cost of Goods Sold"
})
for default_account in default_accounts:
if self.is_new() or frappe.flags.in_test:
self._set_default_account(default_account, default_accounts.get(default_account))
if not self.default_income_account:
income_account = frappe.db.get_value("Account",
@ -243,8 +254,7 @@ class Company(NestedSet):
if self.get(fieldname):
return
account = frappe.db.get_value("Account", {"account_type": account_type,
"is_group": 0, "company": self.name})
account = frappe.db.get_value("Account", {"account_type": account_type, "is_group": 0, "company": self.name})
if account:
self.db_set(fieldname, account)

View File

@ -0,0 +1,177 @@
from __future__ import unicode_literals, print_function
import frappe
from frappe.utils import cint
def get_leaderboards():
leaderboards = {
"Customer": {
"fields": [
{'fieldname': 'total_sales_amount', 'fieldtype': 'Currency'},
'total_qty_sold',
{'fieldname': 'outstanding_amount', 'fieldtype': 'Currency'}
],
"method": "erpnext.startup.leaderboard.get_all_customers",
},
"Item": {
"fields": [
{'fieldname': 'total_sales_amount', 'fieldtype': 'Currency'},
'total_qty_sold',
{'fieldname': 'total_purchase_amount', 'fieldtype': 'Currency'},
'total_qty_purchased',
'available_stock_qty',
{'fieldname': 'available_stock_value', 'fieldtype': 'Currency'}
],
"method": "erpnext.startup.leaderboard.get_all_items",
},
"Supplier": {
"fields": [
{'fieldname': 'total_purchase_amount', 'fieldtype': 'Currency'},
'total_qty_purchased',
{'fieldname': 'outstanding_amount', 'fieldtype': 'Currency'}
],
"method": "erpnext.startup.leaderboard.get_all_suppliers",
},
"Sales Partner": {
"fields": [
{'fieldname': 'total_sales_amount', 'fieldtype': 'Currency'},
{'fieldname': 'total_commission', 'fieldtype': 'Currency'}
],
"method": "erpnext.startup.leaderboard.get_all_sales_partner",
},
"Sales Person": {
"fields": [
{'fieldname': 'total_sales_amount', 'fieldtype': 'Currency'}
],
"method": "erpnext.startup.leaderboard.get_all_sales_person",
}
}
return leaderboards
@frappe.whitelist()
def get_all_customers(from_date, company, field, limit = None):
if field == "outstanding_amount":
filters = [['docstatus', '=', '1'], ['company', '=', company]]
if from_date:
filters.append(['posting_date', '>=', from_date])
return frappe.db.get_all('Sales Invoice',
fields = ['customer as name', 'sum(outstanding_amount) as value'],
filters = filters,
group_by = 'customer',
order_by = 'value desc',
limit = limit
)
else:
if field == "total_sales_amount":
select_field = "sum(so_item.base_net_amount)"
elif field == "total_qty_sold":
select_field = "sum(so_item.stock_qty)"
return frappe.db.sql("""
select so.customer as name, {0} as value
FROM `tabSales Order` as so JOIN `tabSales Order Item` as so_item
ON so.name = so_item.parent
where so.docstatus = 1 and so.transaction_date >= %s and so.company = %s
group by so.customer
order by value DESC
limit %s
""".format(select_field), (from_date, company, cint(limit)), as_dict=1) #nosec
@frappe.whitelist()
def get_all_items(from_date, company, field, limit = None):
if field in ("available_stock_qty", "available_stock_value"):
select_field = "sum(actual_qty)" if field=="available_stock_qty" else "sum(stock_value)"
return frappe.db.get_all('Bin',
fields = ['item_code as name', '{0} as value'.format(select_field)],
group_by = 'item_code',
order_by = 'value desc',
limit = limit
)
else:
if field == "total_sales_amount":
select_field = "sum(order_item.base_net_amount)"
select_doctype = "Sales Order"
elif field == "total_purchase_amount":
select_field = "sum(order_item.base_net_amount)"
select_doctype = "Purchase Order"
elif field == "total_qty_sold":
select_field = "sum(order_item.stock_qty)"
select_doctype = "Sales Order"
elif field == "total_qty_purchased":
select_field = "sum(order_item.stock_qty)"
select_doctype = "Purchase Order"
return frappe.db.sql("""
select order_item.item_code as name, {0} as value
from `tab{1}` sales_order join `tab{1} Item` as order_item
on sales_order.name = order_item.parent
where sales_order.docstatus = 1
and sales_order.company = %s and sales_order.transaction_date >= %s
group by order_item.item_code
order by value desc
limit %s
""".format(select_field, select_doctype), (company, from_date, cint(limit)), as_dict=1) #nosec
@frappe.whitelist()
def get_all_suppliers(from_date, company, field, limit = None):
if field == "outstanding_amount":
filters = [['docstatus', '=', '1'], ['company', '=', company]]
if from_date:
filters.append(['posting_date', '>=', from_date])
return frappe.db.get_all('Purchase Invoice',
fields = ['supplier as name', 'sum(outstanding_amount) as value'],
filters = filters,
group_by = 'supplier',
order_by = 'value desc',
limit = limit
)
else:
if field == "total_purchase_amount":
select_field = "sum(purchase_order_item.base_net_amount)"
elif field == "total_qty_purchased":
select_field = "sum(purchase_order_item.stock_qty)"
return frappe.db.sql("""
select purchase_order.supplier as name, {0} as value
FROM `tabPurchase Order` as purchase_order LEFT JOIN `tabPurchase Order Item`
as purchase_order_item ON purchase_order.name = purchase_order_item.parent
where purchase_order.docstatus = 1 and purchase_order.modified >= %s
and purchase_order.company = %s
group by purchase_order.supplier
order by value DESC
limit %s""".format(select_field), (from_date, company, cint(limit)), as_dict=1) #nosec
@frappe.whitelist()
def get_all_sales_partner(from_date, company, field, limit = None):
if field == "total_sales_amount":
select_field = "sum(`base_net_total`)"
elif field == "total_commission":
select_field = "sum(`total_commission`)"
filters = {
'sales_partner': ['!=', ''],
'docstatus': 1,
'company': company
}
if from_date:
filters['transaction_date'] = ['>=', from_date]
return frappe.get_list('Sales Order', fields=[
'`sales_partner` as name',
'{} as value'.format(select_field),
], filters=filters, group_by='sales_partner', order_by='value DESC', limit=limit)
@frappe.whitelist()
def get_all_sales_person(from_date, company, field = None, limit = 0):
return frappe.db.sql("""
select sales_team.sales_person as name, sum(sales_order.base_net_total) as value
from `tabSales Order` as sales_order join `tabSales Team` as sales_team
on sales_order.name = sales_team.parent and sales_team.parenttype = 'Sales Order'
where sales_order.docstatus = 1
and sales_order.transaction_date >= %s
and sales_order.company = %s
group by sales_team.sales_person
order by value DESC
limit %s
""", (from_date, company, cint(limit)), as_dict=1)

View File

@ -115,12 +115,12 @@ erpnext.stock.PurchaseReceiptController = erpnext.buying.BuyingController.extend
cur_frm.add_custom_button(__("Close"), this.close_purchase_receipt, __("Status"))
}
cur_frm.add_custom_button(__('Return'), this.make_purchase_return, __('Create'));
cur_frm.add_custom_button(__('Purchase Return'), this.make_purchase_return, __('Create'));
cur_frm.add_custom_button(__('Make Stock Entry'), cur_frm.cscript['Make Stock Entry'], __('Create'));
if(flt(this.frm.doc.per_billed) < 100) {
cur_frm.add_custom_button(__('Invoice'), this.make_purchase_invoice, __('Create'));
cur_frm.add_custom_button(__('Purchase Invoice'), this.make_purchase_invoice, __('Create'));
}
cur_frm.add_custom_button(__('Retention Stock Entry'), this.make_retention_stock_entry, __('Create'));

View File

@ -107,7 +107,7 @@ def get_item_details(items, sl_entries, include_uom):
if include_uom:
cf_field = ", ucd.conversion_factor"
cf_join = "left join `tabUOM Conversion Detail` ucd on ucd.parent=item.name and ucd.uom='%s'" \
% frappe.db.escape(include_uom)
% (include_uom)
res = frappe.db.sql("""
select

View File

@ -253,31 +253,40 @@ def update_included_uom_in_report(columns, result, include_uom, conversion_facto
return
convertible_cols = {}
for col_idx in reversed(range(0, len(columns))):
col = columns[col_idx]
if isinstance(col, dict) and col.get("convertible") in ['rate', 'qty']:
convertible_cols[col_idx] = col['convertible']
columns.insert(col_idx+1, col.copy())
columns[col_idx+1]['fieldname'] += "_alt"
if convertible_cols[col_idx] == 'rate':
columns[col_idx+1]['label'] += " (per {})".format(include_uom)
else:
columns[col_idx+1]['label'] += " ({})".format(include_uom)
is_dict_obj = False
if isinstance(result[0], dict):
is_dict_obj = True
convertible_columns = {}
for idx, d in enumerate(columns):
key = d.get("fieldname") if is_dict_obj else idx
if d.get("convertible"):
convertible_columns.setdefault(key, d.get("convertible"))
# Add new column to show qty/rate as per the selected UOM
columns.insert(idx+1, {
'label': "{0} (per {1})".format(d.get("label"), include_uom),
'fieldname': "{0}_{1}".format(d.get("fieldname"), frappe.scrub(include_uom)),
'fieldtype': 'Currency' if d.get("convertible") == 'rate' else 'Float'
})
for row_idx, row in enumerate(result):
new_row = []
for col_idx, d in enumerate(row):
new_row.append(d)
if col_idx in convertible_cols:
if conversion_factors[row_idx]:
if convertible_cols[col_idx] == 'rate':
new_row.append(flt(d) * conversion_factors[row_idx])
else:
new_row.append(flt(d) / conversion_factors[row_idx])
else:
new_row.append(None)
data = row.items() if is_dict_obj else enumerate(row)
for key, value in data:
if not key in convertible_columns or not conversion_factors[row_idx]:
continue
result[row_idx] = new_row
if convertible_columns.get(key) == 'rate':
new_value = flt(value) * conversion_factors[row_idx]
else:
new_value = flt(value) / conversion_factors[row_idx]
if not is_dict_obj:
row.insert(key+1, new_value)
else:
new_key = "{0}_{1}".format(key, frappe.scrub(include_uom))
row[new_key] = new_value
def get_available_serial_nos(item_code, warehouse):
return frappe.get_all("Serial No", filters = {'item_code': item_code,

View File

@ -1,54 +0,0 @@
.list-filters {
overflow-y: hidden;
padding: 5px
}
.list-filter-item {
min-width: 150px;
float: left;
margin:5px;
}
.list-item_content{
flex: 1;
padding-right: 15px;
align-items: center;
}
.select-time, .select-doctype, .select-filter, .select-sort {
background: #f0f4f7;
}
.select-time:focus, .select-doctype:focus, .select-filter:focus, .select-sort:focus {
background: #f0f4f7;
}
.header-btn-base{
border:none;
outline:0;
vertical-align:middle;
overflow:hidden;
text-decoration:none;
color:inherit;
background-color:inherit;
cursor:pointer;
white-space:nowrap;
}
.header-btn-grey,.header-btn-grey:hover{
color:#000!important;
background-color:#bbb!important
}
.header-btn-round{
border-radius:4px
}
.item-title-bold{
font-weight: bold;
}
/*
.header-btn-base:hover {
box-shadow:0 8px 16px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19)
}*/

View File

@ -1,307 +0,0 @@
frappe.pages["leaderboard"].on_page_load = function (wrapper) {
frappe.leaderboard = new frappe.Leaderboard(wrapper);
}
frappe.Leaderboard = Class.extend({
init: function (parent) {
frappe.ui.make_app_page({
parent: parent,
title: "Leaderboard",
single_column: false
});
this.parent = parent;
this.page = this.parent.page;
this.page.sidebar.html(`<ul class="module-sidebar-nav overlay-sidebar nav nav-pills nav-stacked"></ul>`);
this.$sidebar_list = this.page.sidebar.find('ul');
// const list of doctypes
this.doctypes = ["Customer", "Item", "Supplier", "Sales Partner","Sales Person"];
this.timespans = ["Week", "Month", "Quarter", "Year"];
this.filters = {
"Customer": ["total_sales_amount", "total_qty_sold", "outstanding_amount", ],
"Item": ["total_sales_amount", "total_qty_sold", "total_purchase_amount",
"total_qty_purchased", "available_stock_qty", "available_stock_value"],
"Supplier": ["total_purchase_amount", "total_qty_purchased", "outstanding_amount"],
"Sales Partner": ["total_sales_amount", "total_commission"],
"Sales Person": ["total_sales_amount"],
};
// for saving current selected filters
// TODO: revert to 0 index for doctype and timespan, and remove preset down
const _initial_doctype = this.doctypes[0];
const _initial_timespan = this.timespans[0];
const _initial_filter = this.filters[_initial_doctype];
this.options = {
selected_doctype: _initial_doctype,
selected_filter: _initial_filter,
selected_filter_item: _initial_filter[0],
selected_timespan: _initial_timespan,
};
this.message = null;
this.make();
},
make: function () {
var me = this;
var $container = $(`<div class="leaderboard page-main-content">
<div class="leaderboard-graph"></div>
<div class="leaderboard-list"></div>
</div>`).appendTo(this.page.main);
this.$graph_area = $container.find('.leaderboard-graph');
this.doctypes.map(doctype => {
this.get_sidebar_item(doctype).appendTo(this.$sidebar_list);
});
this.company_select = this.page.add_field({
fieldname: 'company',
label: __('Company'),
fieldtype:'Link',
options:'Company',
default:frappe.defaults.get_default('company'),
reqd: 1,
change: function() {
me.options.selected_company = this.value;
me.make_request($container);
}
});
this.timespan_select = this.page.add_select(__("Timespan"),
this.timespans.map(d => {
return {"label": __(d), value: d }
})
);
this.type_select = this.page.add_select(__("Type"),
me.options.selected_filter.map(d => {
return {"label": __(frappe.model.unscrub(d)), value: d }
})
);
this.$sidebar_list.on('click', 'li', function(e) {
let $li = $(this);
let doctype = $li.find('span').attr("doctype-value");
me.options.selected_company = frappe.defaults.get_default('company');
me.options.selected_doctype = doctype;
me.options.selected_filter = me.filters[doctype];
me.options.selected_filter_item = me.filters[doctype][0];
me.type_select.empty().add_options(
me.options.selected_filter.map(d => {
return {"label": __(frappe.model.unscrub(d)), value: d }
})
);
me.$sidebar_list.find('li').removeClass('active');
$li.addClass('active');
me.make_request($container);
});
this.timespan_select.on("change", function() {
me.options.selected_timespan = this.value;
me.make_request($container);
});
this.type_select.on("change", function() {
me.options.selected_filter_item = this.value
me.make_request($container);
});
// now get leaderboard
this.$sidebar_list.find('li:first').trigger('click');
},
make_request: function ($container) {
var me = this;
frappe.model.with_doctype(me.options.selected_doctype, function () {
me.get_leaderboard(me.get_leaderboard_data, $container);
});
},
get_leaderboard: function (notify, $container) {
var me = this;
if(!me.options.selected_company) {
frappe.throw(__("Please select Company"));
}
frappe.call({
method: "erpnext.utilities.page.leaderboard.leaderboard.get_leaderboard",
args: {
doctype: me.options.selected_doctype,
timespan: me.options.selected_timespan,
company: me.options.selected_company,
field: me.options.selected_filter_item,
},
callback: function (r) {
let results = r.message || [];
let graph_items = results.slice(0, 10);
me.$graph_area.show().empty();
let args = {
data: {
datasets: [
{
values: graph_items.map(d=>d.value)
}
],
labels: graph_items.map(d=>d.name)
},
colors: ['light-green'],
format_tooltip_x: d=>d[me.options.selected_filter_item],
type: 'bar',
height: 140
};
new frappe.Chart('.leaderboard-graph', args);
notify(me, r, $container);
}
});
},
get_leaderboard_data: function (me, res, $container) {
if (res && res.message) {
me.message = null;
$container.find(".leaderboard-list").html(me.render_list_view(res.message));
} else {
me.$graph_area.hide();
me.message = __("No items found.");
$container.find(".leaderboard-list").html(me.render_list_view());
}
},
render_list_view: function (items = []) {
var me = this;
var html =
`${me.render_message()}
<div class="result" style="${me.message ? "display:none;" : ""}">
${me.render_result(items)}
</div>`;
return $(html);
},
render_result: function (items) {
var me = this;
var html =
`${me.render_list_header()}
${me.render_list_result(items)}`;
return html;
},
render_list_header: function () {
var me = this;
const _selected_filter = me.options.selected_filter
.map(i => frappe.model.unscrub(i));
const fields = ['name', me.options.selected_filter_item];
const html =
`<div class="list-headers">
<div class="list-item list-item--head" data-list-renderer="${"List"}">
${
fields.map(filter => {
const col = frappe.model.unscrub(filter);
return (
`<div class="leaderboard-item list-item_content ellipsis text-muted list-item__content--flex-2
header-btn-base
${(col && _selected_filter.indexOf(col) !== -1) ? "text-right" : ""}">
<span class="list-col-title ellipsis">
${col}
</span>
</div>`);
}).join("")
}
</div>
</div>`;
return html;
},
render_list_result: function (items) {
var me = this;
let _html = items.map((item, index) => {
const $value = $(me.get_item_html(item));
let item_class = "";
if(index == 0) {
item_class = "first";
} else if (index == 1) {
item_class = "second";
} else if(index == 2) {
item_class = "third";
}
const $item_container = $(`<div class="list-item-container ${item_class}">`).append($value);
return $item_container[0].outerHTML;
}).join("");
let html =
`<div class="result-list">
<div class="list-items">
${_html}
</div>
</div>`;
return html;
},
render_message: function () {
var me = this;
let html =
`<div class="no-result text-center" style="${me.message ? "" : "display:none;"}">
<div class="msg-box no-border">
<p>No Item found</p>
</div>
</div>`;
return html;
},
get_item_html: function (item) {
var me = this;
const company = me.options.selected_company;
const currency = frappe.get_doc(":Company", company).default_currency;
const fields = ['name','value'];
const html =
`<div class="list-item">
${
fields.map(col => {
let val = item[col];
if(col=="name") {
var formatted_value = `<a class="grey list-id ellipsis"
href="#Form/${me.options.selected_doctype}/${item["name"]}"> ${val} </a>`
} else {
var formatted_value = `<span class="text-muted ellipsis">
${(me.options.selected_filter_item.indexOf('qty') == -1) ? format_currency(val, currency) : val}</span>`
}
return (
`<div class="list-item_content ellipsis list-item__content--flex-2
${(col == "value") ? "text-right" : ""}">
${formatted_value}
</div>`);
}).join("")
}
</div>`;
return html;
},
get_sidebar_item: function(item) {
return $(`<li class="strong module-sidebar-item">
<a class="module-link">
<span doctype-value="${item}">${ __(item) }</span></a>
</li>`);
}
});

View File

@ -1,19 +0,0 @@
{
"content": null,
"creation": "2017-06-06 02:54:24.785360",
"docstatus": 0,
"doctype": "Page",
"idx": 0,
"modified": "2017-09-12 14:05:26.422064",
"modified_by": "Administrator",
"module": "Utilities",
"name": "leaderboard",
"owner": "Administrator",
"page_name": "leaderboard",
"roles": [],
"script": null,
"standard": "Yes",
"style": null,
"system_page": 0,
"title": "Leaderboard"
}

View File

@ -1,153 +0,0 @@
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals, print_function
import frappe
from frappe.utils import add_to_date
@frappe.whitelist()
def get_leaderboard(doctype, timespan, company, field):
"""return top 10 items for that doctype based on conditions"""
from_date = get_from_date(timespan)
records = []
if doctype == "Customer":
records = get_all_customers(from_date, company, field)
elif doctype == "Item":
records = get_all_items(from_date, company, field)
elif doctype == "Supplier":
records = get_all_suppliers(from_date, company, field)
elif doctype == "Sales Partner":
records = get_all_sales_partner(from_date, company, field)
elif doctype == "Sales Person":
records = get_all_sales_person(from_date, company)
return records
def get_all_customers(from_date, company, field):
if field == "outstanding_amount":
return frappe.db.sql("""
select customer as name, sum(outstanding_amount) as value
FROM `tabSales Invoice`
where docstatus = 1 and posting_date >= %s and company = %s
group by customer
order by value DESC
limit 20
""", (from_date, company), as_dict=1)
else:
if field == "total_sales_amount":
select_field = "sum(so_item.base_net_amount)"
elif field == "total_qty_sold":
select_field = "sum(so_item.stock_qty)"
return frappe.db.sql("""
select so.customer as name, {0} as value
FROM `tabSales Order` as so JOIN `tabSales Order Item` as so_item
ON so.name = so_item.parent
where so.docstatus = 1 and so.transaction_date >= %s and so.company = %s
group by so.customer
order by value DESC
limit 20
""".format(select_field), (from_date, company), as_dict=1)
def get_all_items(from_date, company, field):
if field in ("available_stock_qty", "available_stock_value"):
return frappe.db.sql("""
select item_code as name, {0} as value
from tabBin
group by item_code
order by value desc
limit 20
""".format("sum(actual_qty)" if field=="available_stock_qty" else "sum(stock_value)"), as_dict=1)
else:
if field == "total_sales_amount":
select_field = "sum(order_item.base_net_amount)"
select_doctype = "Sales Order"
elif field == "total_purchase_amount":
select_field = "sum(order_item.base_net_amount)"
select_doctype = "Purchase Order"
elif field == "total_qty_sold":
select_field = "sum(order_item.stock_qty)"
select_doctype = "Sales Order"
elif field == "total_qty_purchased":
select_field = "sum(order_item.stock_qty)"
select_doctype = "Purchase Order"
return frappe.db.sql("""
select order_item.item_code as name, {0} as value
from `tab{1}` sales_order join `tab{1} Item` as order_item
on sales_order.name = order_item.parent
where sales_order.docstatus = 1
and sales_order.company = %s and sales_order.transaction_date >= %s
group by order_item.item_code
order by value desc
limit 20
""".format(select_field, select_doctype), (company, from_date), as_dict=1)
def get_all_suppliers(from_date, company, field):
if field == "outstanding_amount":
return frappe.db.sql("""
select supplier as name, sum(outstanding_amount) as value
FROM `tabPurchase Invoice`
where docstatus = 1 and posting_date >= %s and company = %s
group by supplier
order by value DESC
limit 20""", (from_date, company), as_dict=1)
else:
if field == "total_purchase_amount":
select_field = "sum(purchase_order_item.base_net_amount)"
elif field == "total_qty_purchased":
select_field = "sum(purchase_order_item.stock_qty)"
return frappe.db.sql("""
select purchase_order.supplier as name, {0} as value
FROM `tabPurchase Order` as purchase_order LEFT JOIN `tabPurchase Order Item`
as purchase_order_item ON purchase_order.name = purchase_order_item.parent
where purchase_order.docstatus = 1 and purchase_order.modified >= %s
and purchase_order.company = %s
group by purchase_order.supplier
order by value DESC
limit 20""".format(select_field), (from_date, company), as_dict=1)
def get_all_sales_partner(from_date, company, field):
if field == "total_sales_amount":
select_field = "sum(base_net_total)"
elif field == "total_commission":
select_field = "sum(total_commission)"
return frappe.db.sql("""
select sales_partner as name, {0} as value
from `tabSales Order`
where ifnull(sales_partner, '') != '' and docstatus = 1
and transaction_date >= %s and company = %s
group by sales_partner
order by value DESC
limit 20
""".format(select_field), (from_date, company), as_dict=1)
def get_all_sales_person(from_date, company):
return frappe.db.sql("""
select sales_team.sales_person as name, sum(sales_order.base_net_total) as value
from `tabSales Order` as sales_order join `tabSales Team` as sales_team
on sales_order.name = sales_team.parent and sales_team.parenttype = 'Sales Order'
where sales_order.docstatus = 1
and sales_order.transaction_date >= %s
and sales_order.company = %s
group by sales_team.sales_person
order by value DESC
limit 20
""", (from_date, company), as_dict=1)
def get_from_date(seleted_timespan):
"""return string for ex:this week as date:string"""
days = months = years = 0
if "month" == seleted_timespan.lower():
months = -1
elif "quarter" == seleted_timespan.lower():
months = -3
elif "year" == seleted_timespan.lower():
years = -1
else:
days = -7
return add_to_date(None, years=years, months=months, days=days,
as_string=True, as_datetime=True)