blob: d7fe12374e646d351b9549b89e47afbd67fd1dce [file] [log] [blame]
Anand Doshi885e0742015-03-03 14:55:30 +05301# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
Rushabh Mehta49dd7be2014-01-28 17:43:10 +05302# License: GNU General Public License v3. See license.txt
3
4from __future__ import unicode_literals
5
Shreya Shah4fa600a2018-06-05 11:27:53 +05306import frappe, erpnext
Nabin Haitdb030d12014-09-10 17:11:30 +05307from frappe import _, msgprint, scrub
Anand Doshifab09042014-05-27 08:39:35 +05308from frappe.defaults import get_user_permissions
Rushabh Mehta919a74a2017-06-22 16:37:04 +05309from frappe.model.utils import get_fetch_values
Nabin Hait89346962018-03-13 16:01:11 +053010from frappe.utils import (add_days, getdate, formatdate, date_diff,
11 add_years, get_timestamp, nowdate, flt, add_months, get_last_day)
Nabin Hait0a32b7a2017-07-12 15:45:32 +053012from frappe.contacts.doctype.address.address import (get_address_display,
13 get_default_address, get_company_address)
KanchanChauhan1dc26b12017-06-13 15:26:35 +053014from frappe.contacts.doctype.contact.contact import get_contact_details, get_default_contact
Rushabh Mehta919a74a2017-06-22 16:37:04 +053015from erpnext.exceptions import PartyFrozen, PartyDisabled, InvalidAccountCurrency
Nabin Hait2d79a642017-05-24 12:41:14 +053016from erpnext.accounts.utils import get_fiscal_year
tunde4a263c72017-08-02 22:20:35 +010017from erpnext import get_default_currency, get_company_currency
18
Achilles Rasquinha56b2e122018-02-13 14:42:40 +053019from six import iteritems
Rushabh Mehta49dd7be2014-01-28 17:43:10 +053020
Anand Doshi248c8672015-09-28 15:24:00 +053021class DuplicatePartyAccountError(frappe.ValidationError): pass
Nabin Hait16099332015-09-03 16:03:07 +053022
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053023@frappe.whitelist()
rohitwaghchaure3ffe8962018-07-13 17:40:48 +053024def get_party_details(party=None, account=None, party_type="Customer", company=None, posting_date=None,
Saurabhd7897f12018-07-18 17:08:16 +053025 bill_date=None, price_list=None, currency=None, doctype=None, ignore_permissions=False, fetch_payment_terms_template=True):
Anand Doshi201dbbd2014-02-20 15:21:53 +053026
Rushabh Mehtad7a5b732015-04-01 23:38:13 +053027 if not party:
28 return {}
Nabin Hait5ef121b2015-06-08 12:26:52 +053029 if not frappe.db.exists(party_type, party):
30 frappe.throw(_("{0}: {1} does not exists").format(party_type, party))
Nabin Hait4d7c4fc2014-06-18 16:40:27 +053031 return _get_party_details(party, account, party_type,
Saurabhd7897f12018-07-18 17:08:16 +053032 company, posting_date, bill_date, price_list, currency, doctype, ignore_permissions, fetch_payment_terms_template)
Anand Doshi201dbbd2014-02-20 15:21:53 +053033
rohitwaghchaure3ffe8962018-07-13 17:40:48 +053034def _get_party_details(party=None, account=None, party_type="Customer", company=None, posting_date=None,
Saurabhd7897f12018-07-18 17:08:16 +053035 bill_date=None, price_list=None, currency=None, doctype=None, ignore_permissions=False, fetch_payment_terms_template=True):
Rushabh Mehta361df892015-09-18 12:59:51 +053036
Shreya Shah3a9eec22018-02-16 13:05:21 +053037 out = frappe._dict(set_account_and_due_date(party, account, party_type, company, posting_date, bill_date, doctype))
Rushabh Mehtacc008cc2014-02-03 16:14:56 +053038 party = out[party_type.lower()]
39
Anand Doshi201dbbd2014-02-20 15:21:53 +053040 if not ignore_permissions and not frappe.has_permission(party_type, "read", party):
Rushabh Mehta2d708872015-11-27 11:35:35 +053041 frappe.throw(_("Not permitted for {0}").format(party), frappe.PermissionError)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +053042
Nabin Hait365ae272014-04-03 17:38:54 +053043 party = frappe.get_doc(party_type, party)
tunde4a263c72017-08-02 22:20:35 +010044 currency = party.default_currency if party.default_currency else get_company_currency(company)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +053045
Shreya Shah4fa600a2018-06-05 11:27:53 +053046 out["taxes_and_charges"] = set_taxes(party.name, party_type, posting_date, company, out.customer_group, out.supplier_group)
47 out["payment_terms_template"] = get_pyt_term_template(party.name, party_type, company)
Rushabh Mehta919a74a2017-06-22 16:37:04 +053048 set_address_details(out, party, party_type, doctype, company)
Nabin Hait9d1f0772014-02-19 17:43:24 +053049 set_contact_details(out, party, party_type)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +053050 set_other_values(out, party, party_type)
Nabin Hait365ae272014-04-03 17:38:54 +053051 set_price_list(out, party, party_type, price_list)
Anand Doshi13ae5482014-04-10 18:40:57 +053052
Rushabh Mehtacc008cc2014-02-03 16:14:56 +053053 out["taxes_and_charges"] = set_taxes(party.name, party_type, posting_date, company, out.customer_group, out.supplier_type)
rohitwaghchaure3ffe8962018-07-13 17:40:48 +053054
55 if fetch_payment_terms_template:
56 out["payment_terms_template"] = get_pyt_term_template(party.name, party_type, company)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +053057
58 if not out.get("currency"):
59 out["currency"] = currency
Anand Doshi13ae5482014-04-10 18:40:57 +053060
Rushabh Mehtacc008cc2014-02-03 16:14:56 +053061 # sales team
Rushabh Mehta49dd7be2014-01-28 17:43:10 +053062 if party_type=="Customer":
Rushabh Mehtacc008cc2014-02-03 16:14:56 +053063 out["sales_team"] = [{
Anand Doshi4b72d052015-10-12 16:15:52 +053064 "sales_person": d.sales_person,
65 "allocated_percentage": d.allocated_percentage or None
Nabin Hait365ae272014-04-03 17:38:54 +053066 } for d in party.get("sales_team")]
Anand Doshi13ae5482014-04-10 18:40:57 +053067
Rushabh Mehtacc008cc2014-02-03 16:14:56 +053068 return out
69
Rushabh Mehta919a74a2017-06-22 16:37:04 +053070def set_address_details(out, party, party_type, doctype=None, company=None):
Nabin Hait9d1f0772014-02-19 17:43:24 +053071 billing_address_field = "customer_address" if party_type == "Lead" \
72 else party_type.lower() + "_address"
Rushabh Mehtab92087c2017-01-13 18:53:11 +053073 out[billing_address_field] = get_default_address(party_type, party.name)
Nabin Hait7eba1a32017-10-02 15:59:27 +053074 if doctype:
75 out.update(get_fetch_values(doctype, billing_address_field, out[billing_address_field]))
Anand Doshi13ae5482014-04-10 18:40:57 +053076
Rushabh Mehtacc008cc2014-02-03 16:14:56 +053077 # address display
Nabin Hait9d1f0772014-02-19 17:43:24 +053078 out.address_display = get_address_display(out[billing_address_field])
Anand Doshi13ae5482014-04-10 18:40:57 +053079
Nabin Hait9d1f0772014-02-19 17:43:24 +053080 # shipping address
81 if party_type in ["Customer", "Lead"]:
tundebabzy40a02762017-10-25 07:54:34 +010082 out.shipping_address_name = get_party_shipping_address(party_type, party.name)
Nabin Hait9d1f0772014-02-19 17:43:24 +053083 out.shipping_address = get_address_display(out["shipping_address_name"])
Nabin Hait7eba1a32017-10-02 15:59:27 +053084 if doctype:
85 out.update(get_fetch_values(doctype, 'shipping_address_name', out.shipping_address_name))
Rushabh Mehta919a74a2017-06-22 16:37:04 +053086
Nabin Hait879e1622017-08-21 08:28:55 +053087 if doctype and doctype in ['Delivery Note', 'Sales Invoice']:
Nabin Hait0a32b7a2017-07-12 15:45:32 +053088 out.update(get_company_address(company))
89 if out.company_address:
90 out.update(get_fetch_values(doctype, 'company_address', out.company_address))
Shreya Shah4fa600a2018-06-05 11:27:53 +053091 get_regional_address_details(out, doctype, company)
92
93 elif doctype and doctype == "Purchase Invoice":
94 out.update(get_company_address(company))
95 if out.company_address:
96 out["shipping_address"] = out["company_address"]
97 out.update(get_fetch_values(doctype, 'shipping_address', out.shipping_address))
98 get_regional_address_details(out, doctype, company)
99
100@erpnext.allow_regional
101def get_regional_address_details(out, doctype, company):
102 pass
Anand Doshi13ae5482014-04-10 18:40:57 +0530103
Nabin Hait9d1f0772014-02-19 17:43:24 +0530104def set_contact_details(out, party, party_type):
Rushabh Mehtab92087c2017-01-13 18:53:11 +0530105 out.contact_person = get_default_contact(party_type, party.name)
Anand Doshi13ae5482014-04-10 18:40:57 +0530106
107 if not out.contact_person:
Neil Trini Lasrado09a66c42015-07-07 16:41:37 +0530108 out.update({
109 "contact_person": None,
110 "contact_display": None,
111 "contact_email": None,
112 "contact_mobile": None,
113 "contact_phone": None,
114 "contact_designation": None,
115 "contact_department": None
116 })
Neil Trini Lasradofe2ffae2015-07-08 18:16:51 +0530117 else:
118 out.update(get_contact_details(out.contact_person))
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530119
120def set_other_values(out, party, party_type):
121 # copy
122 if party_type=="Customer":
saurabh8e499512016-02-19 11:08:45 +0530123 to_copy = ["customer_name", "customer_group", "territory", "language"]
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530124 else:
Zlash6589070782018-04-19 18:37:29 +0530125 to_copy = ["supplier_name", "supplier_group", "language"]
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530126 for f in to_copy:
127 out[f] = party.get(f)
Anand Doshi13ae5482014-04-10 18:40:57 +0530128
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530129 # fields prepended with default in Customer doctype
Neil Trini Lasrado810bd352015-08-21 15:04:57 +0530130 for f in ['currency'] \
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530131 + (['sales_partner', 'commission_rate'] if party_type=="Customer" else []):
132 if party.get("default_" + f):
133 out[f] = party.get("default_" + f)
134
Rushabh Mehta72fbf902015-09-17 18:29:44 +0530135def get_default_price_list(party):
136 """Return default price list for party (Document object)"""
137 if party.default_price_list:
138 return party.default_price_list
139
140 if party.doctype == "Customer":
141 price_list = frappe.db.get_value("Customer Group",
142 party.customer_group, "default_price_list")
143 if price_list:
144 return price_list
145
146 return None
147
Nabin Hait365ae272014-04-03 17:38:54 +0530148def set_price_list(out, party, party_type, given_price_list):
Anand Doshi13ae5482014-04-10 18:40:57 +0530149 # price list
Suraj Shettydcc90e32018-05-04 17:52:57 +0530150 price_list = filter(None, get_user_permissions()
151 .get("Price List", {})
152 .get("docs", []))
153 price_list = list(price_list)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530154
Suraj Shettydcc90e32018-05-04 17:52:57 +0530155 if price_list:
156 price_list = price_list[0]
157 else:
158 price_list = get_default_price_list(party) or given_price_list
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530159
160 if price_list:
Anand Doshie9baaa62014-02-26 12:35:33 +0530161 out.price_list_currency = frappe.db.get_value("Price List", price_list, "currency")
Anand Doshi13ae5482014-04-10 18:40:57 +0530162
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530163 out["selling_price_list" if party.doctype=="Customer" else "buying_price_list"] = price_list
Anand Doshi13ae5482014-04-10 18:40:57 +0530164
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530165
Shreya Shah3a9eec22018-02-16 13:05:21 +0530166def set_account_and_due_date(party, account, party_type, company, posting_date, bill_date, doctype):
Nabin Hait4d7c4fc2014-06-18 16:40:27 +0530167 if doctype not in ["Sales Invoice", "Purchase Invoice"]:
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530168 # not an invoice
169 return {
170 party_type.lower(): party
171 }
Anand Doshi13ae5482014-04-10 18:40:57 +0530172
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530173 if party:
Anand Doshib20baf82015-09-25 16:17:50 +0530174 account = get_party_account(party_type, party, company)
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530175
Anand Doshi13ae5482014-04-10 18:40:57 +0530176 account_fieldname = "debit_to" if party_type=="Customer" else "credit_to"
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530177 out = {
178 party_type.lower(): party,
179 account_fieldname : account,
Shreya Shah3a9eec22018-02-16 13:05:21 +0530180 "due_date": get_due_date(posting_date, party_type, party, company, bill_date)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530181 }
Shreya Shah3a9eec22018-02-16 13:05:21 +0530182
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530183 return out
Rushabh Mehta361df892015-09-18 12:59:51 +0530184
Nabin Haitdb030d12014-09-10 17:11:30 +0530185@frappe.whitelist()
Anand Doshib20baf82015-09-25 16:17:50 +0530186def get_party_account(party_type, party, company):
Rushabh Mehta364054a2015-02-21 14:39:35 +0530187 """Returns the account for the given `party`.
188 Will first search in party (Customer / Supplier) record, if not found,
Zlash6589070782018-04-19 18:37:29 +0530189 will search in group (Customer Group / Supplier Group),
Rushabh Mehta364054a2015-02-21 14:39:35 +0530190 finally will return default."""
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530191 if not company:
Anand Doshib20baf82015-09-25 16:17:50 +0530192 frappe.throw(_("Please select a Company"))
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530193
Saurabh0f86d862017-11-10 19:21:09 +0530194 if not party:
Nabin Hait66059192017-11-13 15:06:35 +0530195 return
Saurabh0f86d862017-11-10 19:21:09 +0530196
197 account = frappe.db.get_value("Party Account",
198 {"parenttype": party_type, "parent": party, "company": company}, "account")
199
200 if not account and party_type in ['Customer', 'Supplier']:
Zlash6589070782018-04-19 18:37:29 +0530201 party_group_doctype = "Customer Group" if party_type=="Customer" else "Supplier Group"
Saurabh0f86d862017-11-10 19:21:09 +0530202 group = frappe.db.get_value(party_type, party, scrub(party_group_doctype))
Rushabh Mehta364054a2015-02-21 14:39:35 +0530203 account = frappe.db.get_value("Party Account",
Saurabh0f86d862017-11-10 19:21:09 +0530204 {"parenttype": party_group_doctype, "parent": group, "company": company}, "account")
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530205
Saurabh0f86d862017-11-10 19:21:09 +0530206 if not account and party_type in ['Customer', 'Supplier']:
207 default_account_name = "default_receivable_account" \
208 if party_type=="Customer" else "default_payable_account"
209 account = frappe.db.get_value("Company", company, default_account_name)
Rushabh Mehta364054a2015-02-21 14:39:35 +0530210
Saurabh0f86d862017-11-10 19:21:09 +0530211 existing_gle_currency = get_party_gle_currency(party_type, party, company)
212 if existing_gle_currency:
213 if account:
214 account_currency = frappe.db.get_value("Account", account, "account_currency")
215 if (account and account_currency != existing_gle_currency) or not account:
216 account = get_party_gle_account(party_type, party, company)
Rushabh Mehtab92087c2017-01-13 18:53:11 +0530217
Saurabh0f86d862017-11-10 19:21:09 +0530218 return account
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530219
Anand Doshib20baf82015-09-25 16:17:50 +0530220def get_party_account_currency(party_type, party, company):
221 def generator():
222 party_account = get_party_account(party_type, party, company)
223 return frappe.db.get_value("Account", party_account, "account_currency")
224
225 return frappe.local_cache("party_account_currency", (party_type, party, company), generator)
226
Anand Doshi4945b942015-09-30 16:41:15 +0530227def get_party_gle_currency(party_type, party, company):
228 def generator():
229 existing_gle_currency = frappe.db.sql("""select account_currency from `tabGL Entry`
230 where docstatus=1 and company=%(company)s and party_type=%(party_type)s and party=%(party)s
231 limit 1""", { "company": company, "party_type": party_type, "party": party })
232
233 return existing_gle_currency[0][0] if existing_gle_currency else None
234
Anand Doshi0b93bdc2015-10-22 19:32:56 +0530235 return frappe.local_cache("party_gle_currency", (party_type, party, company), generator,
236 regenerate_if_none=True)
Rushabh Mehtab92087c2017-01-13 18:53:11 +0530237
Nabin Hait16d69592016-06-28 16:15:58 +0530238def get_party_gle_account(party_type, party, company):
239 def generator():
240 existing_gle_account = frappe.db.sql("""select account from `tabGL Entry`
241 where docstatus=1 and company=%(company)s and party_type=%(party_type)s and party=%(party)s
242 limit 1""", { "company": company, "party_type": party_type, "party": party })
243
244 return existing_gle_account[0][0] if existing_gle_account else None
245
246 return frappe.local_cache("party_gle_account", (party_type, party, company), generator,
247 regenerate_if_none=True)
Anand Doshi4945b942015-09-30 16:41:15 +0530248
Anand Doshid8bc40d2015-10-22 17:54:50 +0530249def validate_party_gle_currency(party_type, party, company, party_account_currency=None):
Anand Doshi4945b942015-09-30 16:41:15 +0530250 """Validate party account currency with existing GL Entry's currency"""
Anand Doshid8bc40d2015-10-22 17:54:50 +0530251 if not party_account_currency:
252 party_account_currency = get_party_account_currency(party_type, party, company)
253
Anand Doshi4945b942015-09-30 16:41:15 +0530254 existing_gle_currency = get_party_gle_currency(party_type, party, company)
255
256 if existing_gle_currency and party_account_currency != existing_gle_currency:
257 frappe.throw(_("Accounting Entry for {0}: {1} can only be made in currency: {2}")
258 .format(party_type, party, existing_gle_currency), InvalidAccountCurrency)
259
Anand Doshida98ab62015-09-28 15:13:38 +0530260def validate_party_accounts(doc):
261 companies = []
262
263 for account in doc.get("accounts"):
264 if account.company in companies:
Nabin Hait2873f2e2015-10-16 13:07:45 +0530265 frappe.throw(_("There can only be 1 Account per Company in {0} {1}")
266 .format(doc.doctype, doc.name), DuplicatePartyAccountError)
Anand Doshida98ab62015-09-28 15:13:38 +0530267 else:
268 companies.append(account.company)
Anand Doshid8bc40d2015-10-22 17:54:50 +0530269
Nabin Hait2873f2e2015-10-16 13:07:45 +0530270 party_account_currency = frappe.db.get_value("Account", account.account, "account_currency")
271 existing_gle_currency = get_party_gle_currency(doc.doctype, doc.name, account.company)
rohitwaghchaure62fea032016-03-30 13:24:42 +0530272 company_default_currency = frappe.db.get_value("Company",
273 frappe.db.get_default("Company"), "default_currency", cache=True)
Anand Doshid8bc40d2015-10-22 17:54:50 +0530274
Nabin Haitaa015902015-10-16 13:08:33 +0530275 if existing_gle_currency and party_account_currency != existing_gle_currency:
276 frappe.throw(_("Accounting entries have already been made in currency {0} for company {1}. Please select a receivable or payable account with currency {0}.").format(existing_gle_currency, account.company))
Anand Doshida98ab62015-09-28 15:13:38 +0530277
rohitwaghchaureea092a72017-02-01 12:02:08 +0530278 if doc.get("default_currency") and party_account_currency and company_default_currency:
rohitwaghchaure62fea032016-03-30 13:24:42 +0530279 if doc.default_currency != party_account_currency and doc.default_currency != company_default_currency:
tunde3b4bd372017-08-31 16:28:47 +0100280 frappe.throw(_("Billing currency must be equal to either default company's currency or party account currency"))
281
rohitwaghchaure62fea032016-03-30 13:24:42 +0530282
Nabin Hait4770a1a2015-07-09 16:35:46 +0530283@frappe.whitelist()
Shreya Shah3a9eec22018-02-16 13:05:21 +0530284def get_due_date(posting_date, party_type, party, company=None, bill_date=None):
tunde3b4bd372017-08-31 16:28:47 +0100285 """Get due date from `Payment Terms Template`"""
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530286 due_date = None
Shreya Shah3a9eec22018-02-16 13:05:21 +0530287 if (bill_date or posting_date) and party:
288 due_date = bill_date or posting_date
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530289 template_name = get_pyt_term_template(party, party_type, company)
rohitwaghchaure3ffe8962018-07-13 17:40:48 +0530290
tunde3b4bd372017-08-31 16:28:47 +0100291 if template_name:
Shreya Shah3a9eec22018-02-16 13:05:21 +0530292 due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime("%Y-%m-%d")
tundeed86efb2017-09-05 01:15:31 +0100293 else:
294 if party_type == "Supplier":
Zlash6589070782018-04-19 18:37:29 +0530295 supplier_group = frappe.db.get_value(party_type, party, fieldname="supplier_group")
296 template_name = frappe.db.get_value("Supplier Group", supplier_group, fieldname="payment_terms")
tundee5973e42017-09-05 18:11:58 +0100297 if template_name:
Shreya Shah3a9eec22018-02-16 13:05:21 +0530298 due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime("%Y-%m-%d")
299 # If due date is calculated from bill_date, check this condition
300 if getdate(due_date) < getdate(posting_date):
301 due_date = posting_date
Anand Doshi13ae5482014-04-10 18:40:57 +0530302 return due_date
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530303
Shreya Shah3a9eec22018-02-16 13:05:21 +0530304def get_due_date_from_template(template_name, posting_date, bill_date):
tunde3b4bd372017-08-31 16:28:47 +0100305 """
306 Inspects all `Payment Term`s from the a `Payment Terms Template` and returns the due
307 date after considering all the `Payment Term`s requirements.
308 :param template_name: Name of the `Payment Terms Template`
309 :return: String representing the calculated due date
310 """
Shreya Shah3a9eec22018-02-16 13:05:21 +0530311 due_date = getdate(bill_date or posting_date)
312
tunde3b4bd372017-08-31 16:28:47 +0100313 template = frappe.get_doc('Payment Terms Template', template_name)
314
315 for term in template.terms:
316 if term.due_date_based_on == 'Day(s) after invoice date':
317 due_date = max(due_date, add_days(due_date, term.credit_days))
318 elif term.due_date_based_on == 'Day(s) after the end of the invoice month':
319 due_date = max(due_date, add_days(get_last_day(due_date), term.credit_days))
320 else:
321 due_date = max(due_date, add_months(get_last_day(due_date), term.credit_months))
tunde3b4bd372017-08-31 16:28:47 +0100322 return due_date
323
Saurabhd7897f12018-07-18 17:08:16 +0530324def validate_due_date(posting_date, due_date, party_type, party, company=None, bill_date=None, template_name=None):
Nabin Hait4770a1a2015-07-09 16:35:46 +0530325 if getdate(due_date) < getdate(posting_date):
326 frappe.throw(_("Due Date cannot be before Posting Date"))
327 else:
rohitwaghchaure3ffe8962018-07-13 17:40:48 +0530328 if not template_name: return
329
Saurabhd7897f12018-07-18 17:08:16 +0530330 default_due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime("%Y-%m-%d")
331
Anand Doshi0ca587e2015-09-25 16:32:14 +0530332 if not default_due_date:
333 return
334
Nabin Hait93d3c822015-07-10 17:11:58 +0530335 if default_due_date != posting_date and getdate(due_date) > getdate(default_due_date):
Nabin Hait4770a1a2015-07-09 16:35:46 +0530336 is_credit_controller = frappe.db.get_single_value("Accounts Settings", "credit_controller") in frappe.get_roles()
337 if is_credit_controller:
338 msgprint(_("Note: Due / Reference Date exceeds allowed customer credit days by {0} day(s)")
339 .format(date_diff(due_date, default_due_date)))
340 else:
Nabin Hait0551f7b2017-11-21 19:58:16 +0530341 frappe.throw(_("Due / Reference Date cannot be after {0}")
342 .format(formatdate(default_due_date)))
Rushabh Mehta361df892015-09-18 12:59:51 +0530343
Neil Trini Lasrado09f9c962015-08-26 10:41:31 +0530344@frappe.whitelist()
Zlash6589070782018-04-19 18:37:29 +0530345def set_taxes(party, party_type, posting_date, company, customer_group=None, supplier_group=None,
Saurabh957e7a32015-09-11 15:44:06 +0530346 billing_address=None, shipping_address=None, use_for_shopping_cart=None):
Neil Trini Lasrado810bd352015-08-21 15:04:57 +0530347 from erpnext.accounts.doctype.tax_rule.tax_rule import get_tax_template, get_party_details
348 args = {
Rushabh Mehta307978f2015-09-23 15:43:09 +0530349 party_type.lower(): party,
Neil Trini Lasrado810bd352015-08-21 15:04:57 +0530350 "company": company
351 }
Rushabh Mehta361df892015-09-18 12:59:51 +0530352
Rushabh Mehta3c14c5a2017-09-29 13:21:22 +0530353 if customer_group:
354 args['customer_group'] = customer_group
355
Zlash6589070782018-04-19 18:37:29 +0530356 if supplier_group:
357 args['supplier_group'] = supplier_group
Rushabh Mehta3c14c5a2017-09-29 13:21:22 +0530358
Neil Trini Lasrado09f9c962015-08-26 10:41:31 +0530359 if billing_address or shipping_address:
Saurabh957e7a32015-09-11 15:44:06 +0530360 args.update(get_party_details(party, party_type, {"billing_address": billing_address, \
361 "shipping_address": shipping_address }))
Neil Trini Lasrado09f9c962015-08-26 10:41:31 +0530362 else:
363 args.update(get_party_details(party, party_type))
Rushabh Mehta361df892015-09-18 12:59:51 +0530364
Anand Doshi2f957f22016-04-08 17:36:10 +0530365 if party_type in ("Customer", "Lead"):
Neil Trini Lasrado810bd352015-08-21 15:04:57 +0530366 args.update({"tax_type": "Sales"})
Anand Doshi2f957f22016-04-08 17:36:10 +0530367
368 if party_type=='Lead':
369 args['customer'] = None
370 del args['lead']
Neil Trini Lasrado810bd352015-08-21 15:04:57 +0530371 else:
372 args.update({"tax_type": "Purchase"})
Rushabh Mehta361df892015-09-18 12:59:51 +0530373
Saurabh957e7a32015-09-11 15:44:06 +0530374 if use_for_shopping_cart:
Saurabh957e7a32015-09-11 15:44:06 +0530375 args.update({"use_for_shopping_cart": use_for_shopping_cart})
Rushabh Mehta361df892015-09-18 12:59:51 +0530376
377 return get_tax_template(posting_date, args)
shreyas29b565f2016-01-25 17:30:49 +0530378
tunde400d0462017-08-31 13:44:57 +0100379
380@frappe.whitelist()
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530381def get_pyt_term_template(party_name, party_type, company=None):
382 if party_type not in ("Customer", "Supplier"):
383 return
tunde400d0462017-08-31 13:44:57 +0100384 template = None
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530385 if party_type == 'Customer':
386 customer = frappe.db.get_value("Customer", party_name,
387 fieldname=['payment_terms', "customer_group"], as_dict=1)
388 template = customer.payment_terms
389
390 if not template and customer.customer_group:
391 template = frappe.db.get_value("Customer Group",
392 customer.customer_group, fieldname='payment_terms')
393 else:
394 supplier = frappe.db.get_value("Supplier", party_name,
Zlash6589070782018-04-19 18:37:29 +0530395 fieldname=['payment_terms', "supplier_group"], as_dict=1)
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530396 template = supplier.payment_terms
Zlash6589070782018-04-19 18:37:29 +0530397 if not template and supplier.supplier_group:
398 template = frappe.db.get_value("Supplier Group", supplier.supplier_group, fieldname='payment_terms')
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530399
400 if not template and company:
401 template = frappe.db.get_value("Company", company, fieldname='payment_terms')
tunde400d0462017-08-31 13:44:57 +0100402 return template
403
shreyaseba9ca42016-01-26 14:56:52 +0530404def validate_party_frozen_disabled(party_type, party_name):
shreyas79872bf2016-01-26 13:57:06 +0530405 if party_type and party_name:
KanchanChauhanfbaa6192017-01-30 15:15:58 +0530406 if party_type in ("Customer", "Supplier"):
407 party = frappe.db.get_value(party_type, party_name, ["is_frozen", "disabled"], as_dict=True)
408 if party.disabled:
409 frappe.throw(_("{0} {1} is disabled").format(party_type, party_name), PartyDisabled)
410 elif party.get("is_frozen"):
411 frozen_accounts_modifier = frappe.db.get_value( 'Accounts Settings', None,'frozen_accounts_modifier')
412 if not frozen_accounts_modifier in frappe.get_roles():
413 frappe.throw(_("{0} {1} is frozen").format(party_type, party_name), PartyFrozen)
414
415 elif party_type == "Employee":
416 if frappe.db.get_value("Employee", party_name, "status") == "Left":
Kanchan Chauhan95108ac2017-04-11 15:55:34 +0530417 frappe.msgprint(_("{0} {1} is not active").format(party_type, party_name), alert=True)
Rushabh Mehta15a7f212016-04-14 17:30:40 +0530418
419def get_timeline_data(doctype, name):
420 '''returns timeline data for the past one year'''
421 from frappe.desk.form.load import get_communication_data
mbauskare7b87ad2017-02-16 13:12:29 +0530422
423 out = {}
Zarrar58200182018-05-30 11:56:23 +0530424 fields = 'date(creation), count(name)'
425 after = add_years(None, -1).strftime('%Y-%m-%d')
426 group_by='group by date(creation)'
427
Rushabh Mehta40b3a5b2016-05-20 11:20:59 +0530428 data = get_communication_data(doctype, name,
Zarrar58200182018-05-30 11:56:23 +0530429 fields=fields, after=after, group_by=group_by, as_dict=False)
430
431 # fetch and append data from Activity Log
432 data += frappe.db.sql("""select {fields}
433 from `tabActivity Log`
Zarrar8cd0f672018-06-07 16:48:31 +0530434 where reference_doctype="{doctype}" and reference_name="{name}"
Zarrar58200182018-05-30 11:56:23 +0530435 and status!='Success' and creation > {after}
436 {group_by} order by creation desc
Zarrar8cd0f672018-06-07 16:48:31 +0530437 """.format(doctype=frappe.db.escape(doctype), name=frappe.db.escape(name), fields=fields,
Zarrar58200182018-05-30 11:56:23 +0530438 group_by=group_by, after=after), as_dict=False)
mbauskare7b87ad2017-02-16 13:12:29 +0530439
440 timeline_items = dict(data)
441
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530442 for date, count in iteritems(timeline_items):
mbauskare7b87ad2017-02-16 13:12:29 +0530443 timestamp = get_timestamp(date)
444 out.update({ timestamp: count })
445
Nabin Hait2d79a642017-05-24 12:41:14 +0530446 return out
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530447
Nabin Hait2d79a642017-05-24 12:41:14 +0530448def get_dashboard_info(party_type, party):
449 current_fiscal_year = get_fiscal_year(nowdate(), as_dict=True)
Nabin Hait4b128962017-05-26 21:25:36 +0530450 company = frappe.db.get_default("company") or frappe.get_all("Company")[0].name
451 party_account_currency = get_party_account_currency(party_type, party, company)
452 company_default_currency = get_default_currency() \
453 or frappe.db.get_value('Company', company, 'default_currency')
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530454
Nabin Hait2d79a642017-05-24 12:41:14 +0530455 if party_account_currency==company_default_currency:
456 total_field = "base_grand_total"
457 else:
458 total_field = "grand_total"
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530459
Nabin Hait2d79a642017-05-24 12:41:14 +0530460 doctype = "Sales Invoice" if party_type=="Customer" else "Purchase Invoice"
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530461
Nabin Hait2d79a642017-05-24 12:41:14 +0530462 billing_this_year = frappe.db.sql("""
463 select sum({0})
464 from `tab{1}`
465 where {2}=%s and docstatus=1 and posting_date between %s and %s
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530466 """.format(total_field, doctype, party_type.lower()),
Nabin Hait2d79a642017-05-24 12:41:14 +0530467 (party, current_fiscal_year.year_start_date, current_fiscal_year.year_end_date))
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530468
Nabin Hait24f0b132017-05-24 13:01:26 +0530469 total_unpaid = frappe.db.sql("""
470 select sum(debit_in_account_currency) - sum(credit_in_account_currency)
471 from `tabGL Entry`
472 where party_type = %s and party=%s""", (party_type, party))
Nabin Hait2d79a642017-05-24 12:41:14 +0530473
474 info = {}
Nabin Hait7e7dc0f2017-05-25 14:18:20 +0530475 info["billing_this_year"] = flt(billing_this_year[0][0]) if billing_this_year else 0
Nabin Hait2d79a642017-05-24 12:41:14 +0530476 info["currency"] = party_account_currency
Nabin Hait7e7dc0f2017-05-25 14:18:20 +0530477 info["total_unpaid"] = flt(total_unpaid[0][0]) if total_unpaid else 0
Nabin Hait24f0b132017-05-24 13:01:26 +0530478 if party_type == "Supplier":
479 info["total_unpaid"] = -1 * info["total_unpaid"]
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530480
Nabin Hait7e7dc0f2017-05-25 14:18:20 +0530481 return info
tundebabzy40a02762017-10-25 07:54:34 +0100482
tundebabzy40a02762017-10-25 07:54:34 +0100483def get_party_shipping_address(doctype, name):
484 """
485 Returns an Address name (best guess) for the given doctype and name for which `address_type == 'Shipping'` is true.
486 and/or `is_shipping_address = 1`.
487
488 It returns an empty string if there is no matching record.
489
490 :param doctype: Party Doctype
491 :param name: Party name
492 :return: String
493 """
494 out = frappe.db.sql(
495 'SELECT dl.parent '
496 'from `tabDynamic Link` dl join `tabAddress` ta on dl.parent=ta.name '
497 'where '
498 'dl.link_doctype=%s '
499 'and dl.link_name=%s '
500 'and dl.parenttype="Address" '
501 'and '
502 '(ta.address_type="Shipping" or ta.is_shipping_address=1) '
503 'order by ta.is_shipping_address desc, ta.address_type desc limit 1',
504 (doctype, name)
505 )
506 if out:
507 return out[0][0]
508 else:
509 return ''
Saurabhb9d33852018-05-12 17:42:20 +0530510
511def get_patry_tax_withholding_details(ref_doc):
512 supplier = frappe.get_doc("Supplier", ref_doc.supplier)
Saurabhf3f438a2018-05-14 20:19:39 +0530513 tax_withholding_details = []
Saurabhb9d33852018-05-12 17:42:20 +0530514 for tax in supplier.tax_withholding_config:
515 tax_mapper = get_tax_mapper()
516
517 set_tax_withholding_details(tax_mapper, ref_doc, tax_withholding_category=tax.tax_withholding_category)
518
519 if tax.valid_till and date_diff(tax.valid_till, ref_doc.posting_date) > 0:
520 tax_mapper.update({
Rohit Waghchaurea9176572018-05-16 23:13:02 +0530521 "rate": tax.applicable_percent
Saurabhb9d33852018-05-12 17:42:20 +0530522 })
523
524 prepare_tax_withholding_details(tax_mapper, tax_withholding_details)
525
Saurabhb9d33852018-05-12 17:42:20 +0530526 return tax_withholding_details
527
528def prepare_tax_withholding_details(tax_mapper, tax_withholding_details):
529 if tax_mapper.get('account_head'):
Saurabhf3f438a2018-05-14 20:19:39 +0530530
531 tax_withholding_details.append({
Saurabhb9d33852018-05-12 17:42:20 +0530532 "threshold": tax_mapper['threshold'],
Saurabhf3f438a2018-05-14 20:19:39 +0530533 "tax": tax_mapper
Saurabhb9d33852018-05-12 17:42:20 +0530534 })
Saurabhf3f438a2018-05-14 20:19:39 +0530535
Saurabhb9d33852018-05-12 17:42:20 +0530536 del tax_mapper['threshold']
537
538def set_tax_withholding_details(tax_mapper, ref_doc, tax_withholding_category=None, use_default=0):
539 if tax_withholding_category:
540 tax_withholding = frappe.get_doc("Tax Withholding Category", tax_withholding_category)
Saurabhb9d33852018-05-12 17:42:20 +0530541
542 if tax_withholding.book_on_invoice and ref_doc.doctype=='Purchase Invoice' \
Shreya Shah97124e92018-06-19 10:46:41 +0530543 or ref_doc.doctype in ('Payment Entry', 'Journal Entry'):
Saurabhb9d33852018-05-12 17:42:20 +0530544
545 for account_detail in tax_withholding.accounts:
546 if ref_doc.company == account_detail.company:
547 tax_mapper.update({
548 "account_head": account_detail.account,
549 "rate": tax_withholding.percent_of_tax_withheld,
550 "threshold": tax_withholding.threshold,
551 "description": tax_withholding.name
552 })
553
554def get_tax_mapper():
555 return {
556 "category": "Total",
557 "add_deduct_tax": "Deduct",
558 "charge_type": "On Net Total",
559 "rate": 0,
560 "description": '',
561 "account_head": '',
562 "threshold": 0.0
Saurabhf3f438a2018-05-14 20:19:39 +0530563 }