blob: b44385271581559f68c2004372c77b67ad53eb26 [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
Rushabh Mehta49dd7be2014-01-28 17:43:10 +05304
Chillar Anand915b3432021-09-02 16:44:59 +05305import frappe
Nabin Haitdb030d12014-09-10 17:11:30 +05306from frappe import _, msgprint, scrub
Chillar Anand915b3432021-09-02 16:44:59 +05307from frappe.contacts.doctype.address.address import (
8 get_address_display,
9 get_company_address,
10 get_default_address,
11)
12from frappe.contacts.doctype.contact.contact import get_contact_details
Suraj Shetty7ed37ae2018-12-19 19:56:42 +053013from frappe.core.doctype.user_permission.user_permission import get_permitted_documents
Rushabh Mehta919a74a2017-06-22 16:37:04 +053014from frappe.model.utils import get_fetch_values
Chillar Anand915b3432021-09-02 16:44:59 +053015from frappe.utils import (
16 add_days,
17 add_months,
18 add_years,
19 cint,
20 cstr,
21 date_diff,
22 flt,
23 formatdate,
24 get_last_day,
25 get_timestamp,
26 getdate,
27 nowdate,
28)
tunde4a263c72017-08-02 22:20:35 +010029
Chillar Anand915b3432021-09-02 16:44:59 +053030import erpnext
31from erpnext import get_company_currency
32from erpnext.accounts.utils import get_fiscal_year
33from erpnext.exceptions import InvalidAccountCurrency, PartyDisabled, PartyFrozen
34
Rushabh Mehta49dd7be2014-01-28 17:43:10 +053035
Anand Doshi248c8672015-09-28 15:24:00 +053036class DuplicatePartyAccountError(frappe.ValidationError): pass
Nabin Hait16099332015-09-03 16:03:07 +053037
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053038@frappe.whitelist()
rohitwaghchaure3ffe8962018-07-13 17:40:48 +053039def get_party_details(party=None, account=None, party_type="Customer", company=None, posting_date=None,
deepeshgarg007c48efab2019-01-24 17:15:38 +053040 bill_date=None, price_list=None, currency=None, doctype=None, ignore_permissions=False, fetch_payment_terms_template=True,
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053041 party_address=None, company_address=None, shipping_address=None, pos_profile=None):
Anand Doshi201dbbd2014-02-20 15:21:53 +053042
Rushabh Mehtad7a5b732015-04-01 23:38:13 +053043 if not party:
44 return {}
Nabin Hait5ef121b2015-06-08 12:26:52 +053045 if not frappe.db.exists(party_type, party):
46 frappe.throw(_("{0}: {1} does not exists").format(party_type, party))
Nabin Hait4d7c4fc2014-06-18 16:40:27 +053047 return _get_party_details(party, account, party_type,
deepeshgarg007c48efab2019-01-24 17:15:38 +053048 company, posting_date, bill_date, price_list, currency, doctype, ignore_permissions,
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053049 fetch_payment_terms_template, party_address, company_address, shipping_address, pos_profile)
Anand Doshi201dbbd2014-02-20 15:21:53 +053050
rohitwaghchaure3ffe8962018-07-13 17:40:48 +053051def _get_party_details(party=None, account=None, party_type="Customer", company=None, posting_date=None,
Shreya Shah5615cb42018-10-07 11:42:07 +053052 bill_date=None, price_list=None, currency=None, doctype=None, ignore_permissions=False,
Deepesh Garg15ff6a52020-02-18 12:28:41 +053053 fetch_payment_terms_template=True, party_address=None, company_address=None, shipping_address=None, pos_profile=None):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053054 party_details = frappe._dict(set_account_and_due_date(party, account, party_type, company, posting_date, bill_date, doctype))
55 party = party_details[party_type.lower()]
Rushabh Mehtacc008cc2014-02-03 16:14:56 +053056
Saurabh9dcb2862021-02-01 20:36:15 +053057 if not ignore_permissions and not (frappe.has_permission(party_type, "read", party) or frappe.has_permission(party_type, "select", party)):
Rushabh Mehta2d708872015-11-27 11:35:35 +053058 frappe.throw(_("Not permitted for {0}").format(party), frappe.PermissionError)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +053059
Nabin Hait365ae272014-04-03 17:38:54 +053060 party = frappe.get_doc(party_type, party)
Deepesh Gargb72cdb42022-01-21 18:00:35 +053061 currency = party.get("default_currency") or currency or get_company_currency(company)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +053062
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053063 party_address, shipping_address = set_address_details(party_details, party, party_type, doctype, company, party_address, company_address, shipping_address)
Deepesh Gargcf9347d2020-03-31 17:28:43 +053064 set_contact_details(party_details, party, party_type)
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053065 set_other_values(party_details, party, party_type)
66 set_price_list(party_details, party, party_type, price_list, pos_profile)
Anand Doshi13ae5482014-04-10 18:40:57 +053067
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053068 party_details["tax_category"] = get_address_tax_category(party.get("tax_category"),
Saif Ur Rehmanfd531a62018-12-29 01:49:11 +050069 party_address, shipping_address if party_type != "Supplier" else party_address)
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053070
Deepesh Gargf12be302021-11-30 20:34:53 +053071 tax_template = set_taxes(party.name, party_type, posting_date, company,
72 customer_group=party_details.customer_group, supplier_group=party_details.supplier_group, tax_category=party_details.tax_category,
73 billing_address=party_address, shipping_address=shipping_address)
74
75 if tax_template:
76 party_details['taxes_and_charges'] = tax_template
rohitwaghchaure3ffe8962018-07-13 17:40:48 +053077
Deepesh Gargbcf56e62021-08-06 23:53:16 +053078 if cint(fetch_payment_terms_template):
marinationfa085d72020-10-27 13:18:30 +053079 party_details["payment_terms_template"] = get_payment_terms_template(party.name, party_type, company)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +053080
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053081 if not party_details.get("currency"):
82 party_details["currency"] = currency
Anand Doshi13ae5482014-04-10 18:40:57 +053083
Rushabh Mehtacc008cc2014-02-03 16:14:56 +053084 # sales team
Rushabh Mehta49dd7be2014-01-28 17:43:10 +053085 if party_type=="Customer":
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053086 party_details["sales_team"] = [{
Anand Doshi4b72d052015-10-12 16:15:52 +053087 "sales_person": d.sales_person,
Rohit Waghchaure4d4bfa22021-11-10 00:00:38 +053088 "allocated_percentage": d.allocated_percentage or None,
89 "commission_rate": d.commission_rate
Nabin Hait365ae272014-04-03 17:38:54 +053090 } for d in party.get("sales_team")]
Anand Doshi13ae5482014-04-10 18:40:57 +053091
Zarrar7f8024c2018-08-01 17:45:05 +053092 # supplier tax withholding category
93 if party_type == "Supplier" and party:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053094 party_details["supplier_tds"] = frappe.get_value(party_type, party.name, "tax_withholding_category")
Zarrar7f8024c2018-08-01 17:45:05 +053095
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053096 return party_details
Rushabh Mehtacc008cc2014-02-03 16:14:56 +053097
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053098def set_address_details(party_details, party, party_type, doctype=None, company=None, party_address=None, company_address=None, shipping_address=None):
Nabin Hait9d1f0772014-02-19 17:43:24 +053099 billing_address_field = "customer_address" if party_type == "Lead" \
100 else party_type.lower() + "_address"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530101 party_details[billing_address_field] = party_address or get_default_address(party_type, party.name)
Nabin Hait7eba1a32017-10-02 15:59:27 +0530102 if doctype:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530103 party_details.update(get_fetch_values(doctype, billing_address_field, party_details[billing_address_field]))
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530104 # address display
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530105 party_details.address_display = get_address_display(party_details[billing_address_field])
Nabin Hait9d1f0772014-02-19 17:43:24 +0530106 # shipping address
107 if party_type in ["Customer", "Lead"]:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530108 party_details.shipping_address_name = shipping_address or get_party_shipping_address(party_type, party.name)
109 party_details.shipping_address = get_address_display(party_details["shipping_address_name"])
Nabin Hait7eba1a32017-10-02 15:59:27 +0530110 if doctype:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530111 party_details.update(get_fetch_values(doctype, 'shipping_address_name', party_details.shipping_address_name))
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530112
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530113 if company_address:
114 party_details.update({'company_address': company_address})
115 else:
116 party_details.update(get_company_address(company))
Shreya Shah4fa600a2018-06-05 11:27:53 +0530117
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530118 if doctype and doctype in ['Delivery Note', 'Sales Invoice', 'Sales Order']:
119 if party_details.company_address:
120 party_details.update(get_fetch_values(doctype, 'company_address', party_details.company_address))
121 get_regional_address_details(party_details, doctype, company)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530122
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530123 elif doctype and doctype in ["Purchase Invoice", "Purchase Order", "Purchase Receipt"]:
124 if party_details.company_address:
125 party_details["shipping_address"] = shipping_address or party_details["company_address"]
126 party_details.shipping_address_display = get_address_display(party_details["shipping_address"])
127 party_details.update(get_fetch_values(doctype, 'shipping_address', party_details.shipping_address))
128 get_regional_address_details(party_details, doctype, company)
129
130 return party_details.get(billing_address_field), party_details.shipping_address_name
Saif Ur Rehman67786682018-12-27 02:11:07 +0500131
Shreya Shah4fa600a2018-06-05 11:27:53 +0530132@erpnext.allow_regional
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530133def get_regional_address_details(party_details, doctype, company):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530134 pass
Anand Doshi13ae5482014-04-10 18:40:57 +0530135
Deepesh Gargcf9347d2020-03-31 17:28:43 +0530136def set_contact_details(party_details, party, party_type):
137 party_details.contact_person = get_default_contact(party_type, party.name)
Anand Doshi13ae5482014-04-10 18:40:57 +0530138
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530139 if not party_details.contact_person:
140 party_details.update({
Neil Trini Lasrado09a66c42015-07-07 16:41:37 +0530141 "contact_person": None,
142 "contact_display": None,
143 "contact_email": None,
144 "contact_mobile": None,
145 "contact_phone": None,
146 "contact_designation": None,
147 "contact_department": None
148 })
Neil Trini Lasradofe2ffae2015-07-08 18:16:51 +0530149 else:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530150 party_details.update(get_contact_details(party_details.contact_person))
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530151
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530152def set_other_values(party_details, party, party_type):
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530153 # copy
ChillarAnand9ace7d62022-03-07 16:53:59 +0530154 if party_type == "Customer":
saurabh8e499512016-02-19 11:08:45 +0530155 to_copy = ["customer_name", "customer_group", "territory", "language"]
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530156 else:
Zlash6589070782018-04-19 18:37:29 +0530157 to_copy = ["supplier_name", "supplier_group", "language"]
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530158 for f in to_copy:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530159 party_details[f] = party.get(f)
Anand Doshi13ae5482014-04-10 18:40:57 +0530160
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530161 # fields prepended with default in Customer doctype
Neil Trini Lasrado810bd352015-08-21 15:04:57 +0530162 for f in ['currency'] \
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530163 + (['sales_partner', 'commission_rate'] if party_type=="Customer" else []):
164 if party.get("default_" + f):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530165 party_details[f] = party.get("default_" + f)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530166
Rushabh Mehta72fbf902015-09-17 18:29:44 +0530167def get_default_price_list(party):
168 """Return default price list for party (Document object)"""
Nabin Hait34c551d2019-07-03 10:34:31 +0530169 if party.get("default_price_list"):
Rushabh Mehta72fbf902015-09-17 18:29:44 +0530170 return party.default_price_list
171
172 if party.doctype == "Customer":
ChillarAnand9ace7d62022-03-07 16:53:59 +0530173 try:
174 return frappe.get_cached_value("Customer Group", party.customer_group, "default_price_list")
175 except frappe.exceptions.DoesNotExistError:
176 return
Rushabh Mehta72fbf902015-09-17 18:29:44 +0530177
Rushabh Mehta72fbf902015-09-17 18:29:44 +0530178
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530179def set_price_list(party_details, party, party_type, given_price_list, pos=None):
Anand Doshi13ae5482014-04-10 18:40:57 +0530180 # price list
Suraj Shetty7ed37ae2018-12-19 19:56:42 +0530181 price_list = get_permitted_documents('Price List')
rohitwaghchaure52107612020-05-05 12:12:33 +0530182
Faris Ansari64f01bd2020-04-14 11:51:48 +0530183 # if there is only one permitted document based on user permissions, set it
184 if price_list and len(price_list) == 1:
Suraj Shettydcc90e32018-05-04 17:52:57 +0530185 price_list = price_list[0]
deepeshgarg007c48efab2019-01-24 17:15:38 +0530186 elif pos and party_type == 'Customer':
187 customer_price_list = frappe.get_value('Customer', party.name, 'default_price_list')
188
189 if customer_price_list:
190 price_list = customer_price_list
191 else:
deepeshgarg0078c84b7b2019-01-25 16:44:45 +0530192 pos_price_list = frappe.get_value('POS Profile', pos, 'selling_price_list')
deepeshgarg0071f9a6fe2019-01-25 11:53:55 +0530193 price_list = pos_price_list or given_price_list
Suraj Shettydcc90e32018-05-04 17:52:57 +0530194 else:
195 price_list = get_default_price_list(party) or given_price_list
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530196
197 if price_list:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530198 party_details.price_list_currency = frappe.db.get_value("Price List", price_list, "currency", cache=True)
Anand Doshi13ae5482014-04-10 18:40:57 +0530199
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530200 party_details["selling_price_list" if party.doctype=="Customer" else "buying_price_list"] = price_list
Anand Doshi13ae5482014-04-10 18:40:57 +0530201
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530202
Shreya Shah3a9eec22018-02-16 13:05:21 +0530203def set_account_and_due_date(party, account, party_type, company, posting_date, bill_date, doctype):
Saqiba6f98d42020-07-23 18:51:26 +0530204 if doctype not in ["POS Invoice", "Sales Invoice", "Purchase Invoice"]:
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530205 # not an invoice
206 return {
207 party_type.lower(): party
208 }
Anand Doshi13ae5482014-04-10 18:40:57 +0530209
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530210 if party:
Anand Doshib20baf82015-09-25 16:17:50 +0530211 account = get_party_account(party_type, party, company)
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530212
Anand Doshi13ae5482014-04-10 18:40:57 +0530213 account_fieldname = "debit_to" if party_type=="Customer" else "credit_to"
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530214 out = {
215 party_type.lower(): party,
216 account_fieldname : account,
Shreya Shah3a9eec22018-02-16 13:05:21 +0530217 "due_date": get_due_date(posting_date, party_type, party, company, bill_date)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530218 }
Shreya Shah3a9eec22018-02-16 13:05:21 +0530219
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530220 return out
Rushabh Mehta361df892015-09-18 12:59:51 +0530221
Nabin Haitdb030d12014-09-10 17:11:30 +0530222@frappe.whitelist()
Deepesh Garg88648572021-11-12 12:39:30 +0530223def get_party_account(party_type, party=None, company=None):
Rushabh Mehta364054a2015-02-21 14:39:35 +0530224 """Returns the account for the given `party`.
225 Will first search in party (Customer / Supplier) record, if not found,
Zlash6589070782018-04-19 18:37:29 +0530226 will search in group (Customer Group / Supplier Group),
Rushabh Mehta364054a2015-02-21 14:39:35 +0530227 finally will return default."""
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530228 if not company:
Anand Doshib20baf82015-09-25 16:17:50 +0530229 frappe.throw(_("Please select a Company"))
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530230
Deepesh Garg88648572021-11-12 12:39:30 +0530231 if not party and party_type in ['Customer', 'Supplier']:
232 default_account_name = "default_receivable_account" \
233 if party_type=="Customer" else "default_payable_account"
234
235 return frappe.get_cached_value('Company', company, default_account_name)
Saurabh0f86d862017-11-10 19:21:09 +0530236
237 account = frappe.db.get_value("Party Account",
238 {"parenttype": party_type, "parent": party, "company": company}, "account")
239
240 if not account and party_type in ['Customer', 'Supplier']:
Zlash6589070782018-04-19 18:37:29 +0530241 party_group_doctype = "Customer Group" if party_type=="Customer" else "Supplier Group"
Nabin Hait9a33bc62018-08-09 10:47:09 +0530242 group = frappe.get_cached_value(party_type, party, scrub(party_group_doctype))
Rushabh Mehta364054a2015-02-21 14:39:35 +0530243 account = frappe.db.get_value("Party Account",
Saurabh0f86d862017-11-10 19:21:09 +0530244 {"parenttype": party_group_doctype, "parent": group, "company": company}, "account")
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530245
Saurabh0f86d862017-11-10 19:21:09 +0530246 if not account and party_type in ['Customer', 'Supplier']:
247 default_account_name = "default_receivable_account" \
248 if party_type=="Customer" else "default_payable_account"
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530249 account = frappe.get_cached_value('Company', company, default_account_name)
Rushabh Mehta364054a2015-02-21 14:39:35 +0530250
Saurabh0f86d862017-11-10 19:21:09 +0530251 existing_gle_currency = get_party_gle_currency(party_type, party, company)
252 if existing_gle_currency:
253 if account:
Nabin Hait9a33bc62018-08-09 10:47:09 +0530254 account_currency = frappe.db.get_value("Account", account, "account_currency", cache=True)
Saurabh0f86d862017-11-10 19:21:09 +0530255 if (account and account_currency != existing_gle_currency) or not account:
256 account = get_party_gle_account(party_type, party, company)
Rushabh Mehtab92087c2017-01-13 18:53:11 +0530257
Saurabh0f86d862017-11-10 19:21:09 +0530258 return account
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530259
rohitwaghchaure713cfc72018-09-11 17:40:37 +0530260@frappe.whitelist()
261def get_party_bank_account(party_type, party):
262 return frappe.db.get_value('Bank Account', {
263 'party_type': party_type,
264 'party': party,
265 'is_default': 1
266 })
267
Anand Doshib20baf82015-09-25 16:17:50 +0530268def get_party_account_currency(party_type, party, company):
269 def generator():
270 party_account = get_party_account(party_type, party, company)
Nabin Hait9a33bc62018-08-09 10:47:09 +0530271 return frappe.db.get_value("Account", party_account, "account_currency", cache=True)
Anand Doshib20baf82015-09-25 16:17:50 +0530272
273 return frappe.local_cache("party_account_currency", (party_type, party, company), generator)
274
Anand Doshi4945b942015-09-30 16:41:15 +0530275def get_party_gle_currency(party_type, party, company):
276 def generator():
277 existing_gle_currency = frappe.db.sql("""select account_currency from `tabGL Entry`
278 where docstatus=1 and company=%(company)s and party_type=%(party_type)s and party=%(party)s
279 limit 1""", { "company": company, "party_type": party_type, "party": party })
280
281 return existing_gle_currency[0][0] if existing_gle_currency else None
282
Anand Doshi0b93bdc2015-10-22 19:32:56 +0530283 return frappe.local_cache("party_gle_currency", (party_type, party, company), generator,
284 regenerate_if_none=True)
Rushabh Mehtab92087c2017-01-13 18:53:11 +0530285
Nabin Hait16d69592016-06-28 16:15:58 +0530286def get_party_gle_account(party_type, party, company):
287 def generator():
288 existing_gle_account = frappe.db.sql("""select account from `tabGL Entry`
289 where docstatus=1 and company=%(company)s and party_type=%(party_type)s and party=%(party)s
290 limit 1""", { "company": company, "party_type": party_type, "party": party })
291
292 return existing_gle_account[0][0] if existing_gle_account else None
293
294 return frappe.local_cache("party_gle_account", (party_type, party, company), generator,
295 regenerate_if_none=True)
Anand Doshi4945b942015-09-30 16:41:15 +0530296
Anand Doshid8bc40d2015-10-22 17:54:50 +0530297def validate_party_gle_currency(party_type, party, company, party_account_currency=None):
Anand Doshi4945b942015-09-30 16:41:15 +0530298 """Validate party account currency with existing GL Entry's currency"""
Anand Doshid8bc40d2015-10-22 17:54:50 +0530299 if not party_account_currency:
300 party_account_currency = get_party_account_currency(party_type, party, company)
301
Anand Doshi4945b942015-09-30 16:41:15 +0530302 existing_gle_currency = get_party_gle_currency(party_type, party, company)
303
304 if existing_gle_currency and party_account_currency != existing_gle_currency:
Deepesh Gargc6b850e2020-03-28 21:17:58 +0530305 frappe.throw(_("{0} {1} has accounting entries in currency {2} for company {3}. Please select a receivable or payable account with currency {2}.")
Deepesh Garg56bc36f2020-03-30 15:05:20 +0530306 .format(frappe.bold(party_type), frappe.bold(party), frappe.bold(existing_gle_currency), frappe.bold(company)), InvalidAccountCurrency)
Anand Doshi4945b942015-09-30 16:41:15 +0530307
Anand Doshida98ab62015-09-28 15:13:38 +0530308def validate_party_accounts(doc):
Deepesh Garg5a2b5712022-02-18 20:05:49 +0530309 from erpnext.controllers.accounts_controller import validate_account_head
Anand Doshida98ab62015-09-28 15:13:38 +0530310 companies = []
311
312 for account in doc.get("accounts"):
313 if account.company in companies:
Nabin Hait2873f2e2015-10-16 13:07:45 +0530314 frappe.throw(_("There can only be 1 Account per Company in {0} {1}")
315 .format(doc.doctype, doc.name), DuplicatePartyAccountError)
Anand Doshida98ab62015-09-28 15:13:38 +0530316 else:
317 companies.append(account.company)
Anand Doshid8bc40d2015-10-22 17:54:50 +0530318
Nabin Hait9a33bc62018-08-09 10:47:09 +0530319 party_account_currency = frappe.db.get_value("Account", account.account, "account_currency", cache=True)
hendrikc257ce82019-09-05 16:44:09 +0700320 if frappe.db.get_default("Company"):
321 company_default_currency = frappe.get_cached_value('Company',
322 frappe.db.get_default("Company"), "default_currency")
323 else:
324 company_default_currency = frappe.db.get_value('Company', account.company, "default_currency")
Anand Doshid8bc40d2015-10-22 17:54:50 +0530325
Deepesh Garg1a2cf5c2020-03-28 21:26:16 +0530326 validate_party_gle_currency(doc.doctype, doc.name, account.company, party_account_currency)
Anand Doshida98ab62015-09-28 15:13:38 +0530327
rohitwaghchaureea092a72017-02-01 12:02:08 +0530328 if doc.get("default_currency") and party_account_currency and company_default_currency:
rohitwaghchaure62fea032016-03-30 13:24:42 +0530329 if doc.default_currency != party_account_currency and doc.default_currency != company_default_currency:
tunde3b4bd372017-08-31 16:28:47 +0100330 frappe.throw(_("Billing currency must be equal to either default company's currency or party account currency"))
331
Deepesh Garg5a2b5712022-02-18 20:05:49 +0530332 # validate if account is mapped for same company
333 validate_account_head(account.idx, account.account, account.company)
334
rohitwaghchaure62fea032016-03-30 13:24:42 +0530335
Nabin Hait4770a1a2015-07-09 16:35:46 +0530336@frappe.whitelist()
Shreya Shah3a9eec22018-02-16 13:05:21 +0530337def get_due_date(posting_date, party_type, party, company=None, bill_date=None):
tunde3b4bd372017-08-31 16:28:47 +0100338 """Get due date from `Payment Terms Template`"""
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530339 due_date = None
Shreya Shah3a9eec22018-02-16 13:05:21 +0530340 if (bill_date or posting_date) and party:
341 due_date = bill_date or posting_date
marinationfa085d72020-10-27 13:18:30 +0530342 template_name = get_payment_terms_template(party, party_type, company)
rohitwaghchaure3ffe8962018-07-13 17:40:48 +0530343
tunde3b4bd372017-08-31 16:28:47 +0100344 if template_name:
Shreya Shah3a9eec22018-02-16 13:05:21 +0530345 due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime("%Y-%m-%d")
tundeed86efb2017-09-05 01:15:31 +0100346 else:
347 if party_type == "Supplier":
Nabin Hait9a33bc62018-08-09 10:47:09 +0530348 supplier_group = frappe.get_cached_value(party_type, party, "supplier_group")
349 template_name = frappe.get_cached_value("Supplier Group", supplier_group, "payment_terms")
tundee5973e42017-09-05 18:11:58 +0100350 if template_name:
Shreya Shah3a9eec22018-02-16 13:05:21 +0530351 due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime("%Y-%m-%d")
352 # If due date is calculated from bill_date, check this condition
353 if getdate(due_date) < getdate(posting_date):
354 due_date = posting_date
Anand Doshi13ae5482014-04-10 18:40:57 +0530355 return due_date
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530356
Shreya Shah3a9eec22018-02-16 13:05:21 +0530357def get_due_date_from_template(template_name, posting_date, bill_date):
tunde3b4bd372017-08-31 16:28:47 +0100358 """
359 Inspects all `Payment Term`s from the a `Payment Terms Template` and returns the due
360 date after considering all the `Payment Term`s requirements.
361 :param template_name: Name of the `Payment Terms Template`
362 :return: String representing the calculated due date
363 """
Shreya Shah3a9eec22018-02-16 13:05:21 +0530364 due_date = getdate(bill_date or posting_date)
365
tunde3b4bd372017-08-31 16:28:47 +0100366 template = frappe.get_doc('Payment Terms Template', template_name)
367
368 for term in template.terms:
369 if term.due_date_based_on == 'Day(s) after invoice date':
370 due_date = max(due_date, add_days(due_date, term.credit_days))
371 elif term.due_date_based_on == 'Day(s) after the end of the invoice month':
372 due_date = max(due_date, add_days(get_last_day(due_date), term.credit_days))
373 else:
374 due_date = max(due_date, add_months(get_last_day(due_date), term.credit_months))
tunde3b4bd372017-08-31 16:28:47 +0100375 return due_date
376
Saurabhd7897f12018-07-18 17:08:16 +0530377def 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 +0530378 if getdate(due_date) < getdate(posting_date):
Rohit Waghchaured1a85a32018-11-26 18:42:29 +0530379 frappe.throw(_("Due Date cannot be before Posting / Supplier Invoice Date"))
Nabin Hait4770a1a2015-07-09 16:35:46 +0530380 else:
rohitwaghchaure3ffe8962018-07-13 17:40:48 +0530381 if not template_name: return
382
Saurabhd7897f12018-07-18 17:08:16 +0530383 default_due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime("%Y-%m-%d")
384
Anand Doshi0ca587e2015-09-25 16:32:14 +0530385 if not default_due_date:
386 return
387
Nabin Hait93d3c822015-07-10 17:11:58 +0530388 if default_due_date != posting_date and getdate(due_date) > getdate(default_due_date):
Nabin Hait4770a1a2015-07-09 16:35:46 +0530389 is_credit_controller = frappe.db.get_single_value("Accounts Settings", "credit_controller") in frappe.get_roles()
390 if is_credit_controller:
391 msgprint(_("Note: Due / Reference Date exceeds allowed customer credit days by {0} day(s)")
392 .format(date_diff(due_date, default_due_date)))
393 else:
Nabin Hait0551f7b2017-11-21 19:58:16 +0530394 frappe.throw(_("Due / Reference Date cannot be after {0}")
395 .format(formatdate(default_due_date)))
Rushabh Mehta361df892015-09-18 12:59:51 +0530396
Neil Trini Lasrado09f9c962015-08-26 10:41:31 +0530397@frappe.whitelist()
Nabin Hait16a7ec92019-09-05 13:01:15 +0530398def get_address_tax_category(tax_category=None, billing_address=None, shipping_address=None):
Saif Ur Rehmanfd531a62018-12-29 01:49:11 +0500399 addr_tax_category_from = frappe.db.get_single_value("Accounts Settings", "determine_address_tax_category_from")
400 if addr_tax_category_from == "Shipping Address":
401 if shipping_address:
402 tax_category = frappe.db.get_value("Address", shipping_address, "tax_category") or tax_category
403 else:
404 if billing_address:
405 tax_category = frappe.db.get_value("Address", billing_address, "tax_category") or tax_category
406
407 return cstr(tax_category)
Saif Ur Rehman67786682018-12-27 02:11:07 +0500408
Neil Trini Lasrado09f9c962015-08-26 10:41:31 +0530409@frappe.whitelist()
Saif Ur Rehman67786682018-12-27 02:11:07 +0500410def set_taxes(party, party_type, posting_date, company, customer_group=None, supplier_group=None, tax_category=None,
Saurabh957e7a32015-09-11 15:44:06 +0530411 billing_address=None, shipping_address=None, use_for_shopping_cart=None):
Chillar Anand915b3432021-09-02 16:44:59 +0530412 from erpnext.accounts.doctype.tax_rule.tax_rule import get_party_details, get_tax_template
Neil Trini Lasrado810bd352015-08-21 15:04:57 +0530413 args = {
Rushabh Mehta307978f2015-09-23 15:43:09 +0530414 party_type.lower(): party,
marinatione27b9962020-07-03 22:03:25 +0530415 "company": company
Neil Trini Lasrado810bd352015-08-21 15:04:57 +0530416 }
Rushabh Mehta361df892015-09-18 12:59:51 +0530417
Saif Ur Rehman67786682018-12-27 02:11:07 +0500418 if tax_category:
419 args['tax_category'] = tax_category
420
Rushabh Mehta3c14c5a2017-09-29 13:21:22 +0530421 if customer_group:
422 args['customer_group'] = customer_group
423
Zlash6589070782018-04-19 18:37:29 +0530424 if supplier_group:
425 args['supplier_group'] = supplier_group
Rushabh Mehta3c14c5a2017-09-29 13:21:22 +0530426
Neil Trini Lasrado09f9c962015-08-26 10:41:31 +0530427 if billing_address or shipping_address:
Saurabh957e7a32015-09-11 15:44:06 +0530428 args.update(get_party_details(party, party_type, {"billing_address": billing_address, \
429 "shipping_address": shipping_address }))
Neil Trini Lasrado09f9c962015-08-26 10:41:31 +0530430 else:
431 args.update(get_party_details(party, party_type))
Rushabh Mehta361df892015-09-18 12:59:51 +0530432
Anand Doshi2f957f22016-04-08 17:36:10 +0530433 if party_type in ("Customer", "Lead"):
Neil Trini Lasrado810bd352015-08-21 15:04:57 +0530434 args.update({"tax_type": "Sales"})
Anand Doshi2f957f22016-04-08 17:36:10 +0530435
436 if party_type=='Lead':
437 args['customer'] = None
438 del args['lead']
Neil Trini Lasrado810bd352015-08-21 15:04:57 +0530439 else:
440 args.update({"tax_type": "Purchase"})
Rushabh Mehta361df892015-09-18 12:59:51 +0530441
Saurabh957e7a32015-09-11 15:44:06 +0530442 if use_for_shopping_cart:
Saurabh957e7a32015-09-11 15:44:06 +0530443 args.update({"use_for_shopping_cart": use_for_shopping_cart})
Rushabh Mehta361df892015-09-18 12:59:51 +0530444
445 return get_tax_template(posting_date, args)
shreyas29b565f2016-01-25 17:30:49 +0530446
tunde400d0462017-08-31 13:44:57 +0100447
448@frappe.whitelist()
marinationfa085d72020-10-27 13:18:30 +0530449def get_payment_terms_template(party_name, party_type, company=None):
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530450 if party_type not in ("Customer", "Supplier"):
451 return
tunde400d0462017-08-31 13:44:57 +0100452 template = None
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530453 if party_type == 'Customer':
Nabin Hait9a33bc62018-08-09 10:47:09 +0530454 customer = frappe.get_cached_value("Customer", party_name,
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530455 fieldname=['payment_terms', "customer_group"], as_dict=1)
456 template = customer.payment_terms
457
458 if not template and customer.customer_group:
Nabin Hait9a33bc62018-08-09 10:47:09 +0530459 template = frappe.get_cached_value("Customer Group",
460 customer.customer_group, 'payment_terms')
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530461 else:
Nabin Hait9a33bc62018-08-09 10:47:09 +0530462 supplier = frappe.get_cached_value("Supplier", party_name,
Zlash6589070782018-04-19 18:37:29 +0530463 fieldname=['payment_terms', "supplier_group"], as_dict=1)
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530464 template = supplier.payment_terms
Zlash6589070782018-04-19 18:37:29 +0530465 if not template and supplier.supplier_group:
Nabin Hait9a33bc62018-08-09 10:47:09 +0530466 template = frappe.get_cached_value("Supplier Group", supplier.supplier_group, 'payment_terms')
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530467
468 if not template and company:
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530469 template = frappe.get_cached_value('Company', company, fieldname='payment_terms')
tunde400d0462017-08-31 13:44:57 +0100470 return template
471
shreyaseba9ca42016-01-26 14:56:52 +0530472def validate_party_frozen_disabled(party_type, party_name):
Subin Tomb8845b92021-07-30 16:30:18 +0530473
474 if frappe.flags.ignore_party_validation:
475 return
476
shreyas79872bf2016-01-26 13:57:06 +0530477 if party_type and party_name:
KanchanChauhanfbaa6192017-01-30 15:15:58 +0530478 if party_type in ("Customer", "Supplier"):
Nabin Hait9a33bc62018-08-09 10:47:09 +0530479 party = frappe.get_cached_value(party_type, party_name, ["is_frozen", "disabled"], as_dict=True)
deepeshgarg007737ec6b2019-10-20 17:36:36 +0530480 if party.disabled:
481 frappe.throw(_("{0} {1} is disabled").format(party_type, party_name), PartyDisabled)
482 elif party.get("is_frozen"):
Nabin Hait9a33bc62018-08-09 10:47:09 +0530483 frozen_accounts_modifier = frappe.db.get_single_value( 'Accounts Settings', 'frozen_accounts_modifier')
KanchanChauhanfbaa6192017-01-30 15:15:58 +0530484 if not frozen_accounts_modifier in frappe.get_roles():
485 frappe.throw(_("{0} {1} is frozen").format(party_type, party_name), PartyFrozen)
486
487 elif party_type == "Employee":
Rucha Mahabala38147a2021-06-12 13:33:21 +0530488 if frappe.db.get_value("Employee", party_name, "status") != "Active":
Kanchan Chauhan95108ac2017-04-11 15:55:34 +0530489 frappe.msgprint(_("{0} {1} is not active").format(party_type, party_name), alert=True)
Rushabh Mehta15a7f212016-04-14 17:30:40 +0530490
491def get_timeline_data(doctype, name):
492 '''returns timeline data for the past one year'''
493 from frappe.desk.form.load import get_communication_data
mbauskare7b87ad2017-02-16 13:12:29 +0530494
495 out = {}
rohitwaghchaure52107612020-05-05 12:12:33 +0530496 fields = 'creation, count(*)'
Zarrar58200182018-05-30 11:56:23 +0530497 after = add_years(None, -1).strftime('%Y-%m-%d')
rohitwaghchaure52107612020-05-05 12:12:33 +0530498 group_by='group by Date(creation)'
Zarrar58200182018-05-30 11:56:23 +0530499
rohitwaghchaure52107612020-05-05 12:12:33 +0530500 data = get_communication_data(doctype, name, after=after, group_by='group by creation',
501 fields='C.creation as creation, count(C.name)',as_dict=False)
Zarrar58200182018-05-30 11:56:23 +0530502
503 # fetch and append data from Activity Log
504 data += frappe.db.sql("""select {fields}
505 from `tabActivity Log`
rohitwaghchaure52107612020-05-05 12:12:33 +0530506 where (reference_doctype=%(doctype)s and reference_name=%(name)s)
507 or (timeline_doctype in (%(doctype)s) and timeline_name=%(name)s)
508 or (reference_doctype in ("Quotation", "Opportunity") and timeline_name=%(name)s)
Zarrar58200182018-05-30 11:56:23 +0530509 and status!='Success' and creation > {after}
510 {group_by} order by creation desc
rohitwaghchaure52107612020-05-05 12:12:33 +0530511 """.format(fields=fields, group_by=group_by, after=after), {
512 "doctype": doctype,
513 "name": name
514 }, as_dict=False)
mbauskare7b87ad2017-02-16 13:12:29 +0530515
516 timeline_items = dict(data)
517
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530518 for date, count in timeline_items.items():
mbauskare7b87ad2017-02-16 13:12:29 +0530519 timestamp = get_timestamp(date)
520 out.update({ timestamp: count })
521
Nabin Hait2d79a642017-05-24 12:41:14 +0530522 return out
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530523
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530524def get_dashboard_info(party_type, party, loyalty_program=None):
Nabin Hait2d79a642017-05-24 12:41:14 +0530525 current_fiscal_year = get_fiscal_year(nowdate(), as_dict=True)
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530526
Nabin Hait2d79a642017-05-24 12:41:14 +0530527 doctype = "Sales Invoice" if party_type=="Customer" else "Purchase Invoice"
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530528
deepeshgarg007ee05e352018-11-29 16:24:28 +0530529 companies = frappe.get_all(doctype, filters={
530 'docstatus': 1,
531 party_type.lower(): party
532 }, distinct=1, fields=['company'])
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530533
deepeshgarg007920dc142018-11-23 10:17:28 +0530534 company_wise_info = []
535
deepeshgarg007ee05e352018-11-29 16:24:28 +0530536 company_wise_grand_total = frappe.get_all(doctype,
537 filters={
538 'docstatus': 1,
539 party_type.lower(): party,
540 'posting_date': ('between', [current_fiscal_year.year_start_date, current_fiscal_year.year_end_date])
541 },
542 group_by="company",
543 fields=["company", "sum(grand_total) as grand_total", "sum(base_grand_total) as base_grand_total"]
544 )
deepeshgarg007920dc142018-11-23 10:17:28 +0530545
deepeshgarg007a1d015c2018-12-26 11:01:02 +0530546 loyalty_point_details = []
547
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530548 if party_type == "Customer":
549 loyalty_point_details = frappe._dict(frappe.get_all("Loyalty Point Entry",
550 filters={
551 'customer': party,
552 'expiry_date': ('>=', getdate()),
553 },
554 group_by="company",
555 fields=["company", "sum(loyalty_points) as loyalty_points"],
556 as_list =1
557 ))
558
deepeshgarg007f31caff2018-11-27 15:04:12 +0530559 company_wise_billing_this_year = frappe._dict()
560
561 for d in company_wise_grand_total:
562 company_wise_billing_this_year.setdefault(
563 d.company,{
564 "grand_total": d.grand_total,
565 "base_grand_total": d.base_grand_total
566 })
567
deepeshgarg007920dc142018-11-23 10:17:28 +0530568
569 company_wise_total_unpaid = frappe._dict(frappe.db.sql("""
570 select company, sum(debit_in_account_currency) - sum(credit_in_account_currency)
Nabin Hait24f0b132017-05-24 13:01:26 +0530571 from `tabGL Entry`
deepeshgarg007920dc142018-11-23 10:17:28 +0530572 where party_type = %s and party=%s
Deepesh Garg802e63a2021-06-28 11:24:32 +0530573 and is_cancelled = 0
deepeshgarg007920dc142018-11-23 10:17:28 +0530574 group by company""", (party_type, party)))
Nabin Hait2d79a642017-05-24 12:41:14 +0530575
deepeshgarg007920dc142018-11-23 10:17:28 +0530576 for d in companies:
577 company_default_currency = frappe.db.get_value("Company", d.company, 'default_currency')
578 party_account_currency = get_party_account_currency(party_type, party, d.company)
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530579
deepeshgarg007920dc142018-11-23 10:17:28 +0530580 if party_account_currency==company_default_currency:
deepeshgarg007f31caff2018-11-27 15:04:12 +0530581 billing_this_year = flt(company_wise_billing_this_year.get(d.company,{}).get("base_grand_total"))
deepeshgarg007920dc142018-11-23 10:17:28 +0530582 else:
deepeshgarg007f31caff2018-11-27 15:04:12 +0530583 billing_this_year = flt(company_wise_billing_this_year.get(d.company,{}).get("grand_total"))
deepeshgarg007920dc142018-11-23 10:17:28 +0530584
585 total_unpaid = flt(company_wise_total_unpaid.get(d.company))
586
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530587 if loyalty_point_details:
588 loyalty_points = loyalty_point_details.get(d.company)
589
deepeshgarg007920dc142018-11-23 10:17:28 +0530590 info = {}
591 info["billing_this_year"] = flt(billing_this_year) if billing_this_year else 0
592 info["currency"] = party_account_currency
593 info["total_unpaid"] = flt(total_unpaid) if total_unpaid else 0
594 info["company"] = d.company
595
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530596 if party_type == "Customer" and loyalty_point_details:
597 info["loyalty_points"] = loyalty_points
598
deepeshgarg007920dc142018-11-23 10:17:28 +0530599 if party_type == "Supplier":
600 info["total_unpaid"] = -1 * info["total_unpaid"]
601
602 company_wise_info.append(info)
603
604 return company_wise_info
tundebabzy40a02762017-10-25 07:54:34 +0100605
tundebabzy40a02762017-10-25 07:54:34 +0100606def get_party_shipping_address(doctype, name):
607 """
608 Returns an Address name (best guess) for the given doctype and name for which `address_type == 'Shipping'` is true.
609 and/or `is_shipping_address = 1`.
610
611 It returns an empty string if there is no matching record.
612
613 :param doctype: Party Doctype
614 :param name: Party name
615 :return: String
616 """
617 out = frappe.db.sql(
618 'SELECT dl.parent '
619 'from `tabDynamic Link` dl join `tabAddress` ta on dl.parent=ta.name '
620 'where '
621 'dl.link_doctype=%s '
622 'and dl.link_name=%s '
623 'and dl.parenttype="Address" '
rohitwaghchaure5472fff2018-12-10 17:45:39 +0530624 'and ifnull(ta.disabled, 0) = 0 and'
tundebabzy40a02762017-10-25 07:54:34 +0100625 '(ta.address_type="Shipping" or ta.is_shipping_address=1) '
626 'order by ta.is_shipping_address desc, ta.address_type desc limit 1',
627 (doctype, name)
628 )
629 if out:
630 return out[0][0]
631 else:
632 return ''
Rohit Waghchaureaffeb3d2019-01-15 17:38:31 +0530633
Deepesh Garged2c1802020-05-27 12:46:12 +0530634def get_partywise_advanced_payment_amount(party_type, posting_date = None, future_payment=0, company=None):
Rohit Waghchaure4ed7d032019-03-25 15:37:25 +0530635 cond = "1=1"
636 if posting_date:
Deepesh Garged2c1802020-05-27 12:46:12 +0530637 if future_payment:
UrvashiKishnani810a3612021-03-02 08:20:03 +0400638 cond = "posting_date <= '{0}' OR DATE(creation) <= '{0}' """.format(posting_date)
Deepesh Garged2c1802020-05-27 12:46:12 +0530639 else:
UrvashiKishnani810a3612021-03-02 08:20:03 +0400640 cond = "posting_date <= '{0}'".format(posting_date)
Deepesh Garged2c1802020-05-27 12:46:12 +0530641
Saqib39805912020-05-01 18:15:13 +0530642 if company:
UrvashiKishnani810a3612021-03-02 08:20:03 +0400643 cond += "and company = {0}".format(frappe.db.escape(company))
Rohit Waghchaure4ed7d032019-03-25 15:37:25 +0530644
UrvashiKishnani810a3612021-03-02 08:20:03 +0400645 data = frappe.db.sql(""" SELECT party, sum({0}) as amount
646 FROM `tabGL Entry`
Rohit Waghchaure1a6e0152019-03-19 15:06:01 +0530647 WHERE
UrvashiKishnani810a3612021-03-02 08:20:03 +0400648 party_type = %s and against_voucher is null
649 and is_cancelled = 0
650 and {1} GROUP BY party"""
Rohit Waghchaure4ed7d032019-03-25 15:37:25 +0530651 .format(("credit") if party_type == "Customer" else "debit", cond) , party_type)
Rohit Waghchaureaffeb3d2019-01-15 17:38:31 +0530652
653 if data:
hendrikc257ce82019-09-05 16:44:09 +0700654 return frappe._dict(data)
Ronel Cabrerafcb54762019-11-18 17:00:07 +0800655
Deepesh Gargcf9347d2020-03-31 17:28:43 +0530656def get_default_contact(doctype, name):
657 """
Ronel Cabrerafcb54762019-11-18 17:00:07 +0800658 Returns default contact for the given doctype and name.
659 Can be ordered by `contact_type` to either is_primary_contact or is_billing_contact.
660 """
661 out = frappe.db.sql("""
662 SELECT dl.parent, c.is_primary_contact, c.is_billing_contact
663 FROM `tabDynamic Link` dl
664 INNER JOIN tabContact c ON c.name = dl.parent
Deepesh Gargcf9347d2020-03-31 17:28:43 +0530665 WHERE
Ronel Cabrerafcb54762019-11-18 17:00:07 +0800666 dl.link_doctype=%s AND
667 dl.link_name=%s AND
668 dl.parenttype = "Contact"
Deepesh Gargcf9347d2020-03-31 17:28:43 +0530669 ORDER BY is_primary_contact DESC, is_billing_contact DESC
Ronel Cabrerafcb54762019-11-18 17:00:07 +0800670 """, (doctype, name))
671 if out:
672 try:
673 return out[0][0]
Ankush Menat694ae812021-09-01 14:40:56 +0530674 except Exception:
Ronel Cabrerafcb54762019-11-18 17:00:07 +0800675 return None
676 else:
Faris Ansari64f01bd2020-04-14 11:51:48 +0530677 return None