blob: d8ae2a43b5bdd355c5032b33e20db21c4983b057 [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
Raffael Meyerb91bb172023-06-08 16:19:09 +02005from typing import Optional
6
Chillar Anand915b3432021-09-02 16:44:59 +05307import frappe
ruthra kumar8d9b90f2023-10-27 12:37:37 +05308from frappe import _, msgprint, qb, scrub
Ankush Menatf4d74992023-10-17 22:11:56 +05309from frappe.contacts.doctype.address.address import get_company_address, get_default_address
Suraj Shetty7ed37ae2018-12-19 19:56:42 +053010from frappe.core.doctype.user_permission.user_permission import get_permitted_documents
Rushabh Mehta919a74a2017-06-22 16:37:04 +053011from frappe.model.utils import get_fetch_values
Gursheen Anand87df7ff2024-02-21 18:44:29 +053012from frappe.query_builder.functions import Abs, Count, Date, Sum
Chillar Anand915b3432021-09-02 16:44:59 +053013from frappe.utils import (
14 add_days,
15 add_months,
16 add_years,
17 cint,
18 cstr,
19 date_diff,
20 flt,
21 formatdate,
22 get_last_day,
23 get_timestamp,
24 getdate,
25 nowdate,
26)
tunde4a263c72017-08-02 22:20:35 +010027
Chillar Anand915b3432021-09-02 16:44:59 +053028import erpnext
29from erpnext import get_company_currency
30from erpnext.accounts.utils import get_fiscal_year
31from erpnext.exceptions import InvalidAccountCurrency, PartyDisabled, PartyFrozen
Sagar Vora4205f562023-07-24 18:37:36 +053032from erpnext.utilities.regional import temporary_flag
Chillar Anand915b3432021-09-02 16:44:59 +053033
Vishakh Desaic2bda2c2023-11-09 18:26:34 +053034PURCHASE_TRANSACTION_TYPES = {
35 "Supplier Quotation",
36 "Purchase Order",
37 "Purchase Receipt",
38 "Purchase Invoice",
39}
Sagar Vora5c066202023-03-13 14:02:50 +000040SALES_TRANSACTION_TYPES = {
41 "Quotation",
42 "Sales Order",
43 "Delivery Note",
44 "Sales Invoice",
45 "POS Invoice",
46}
47TRANSACTION_TYPES = PURCHASE_TRANSACTION_TYPES | SALES_TRANSACTION_TYPES
48
Rushabh Mehta49dd7be2014-01-28 17:43:10 +053049
Ankush Menat494bd9e2022-03-28 18:52:46 +053050class DuplicatePartyAccountError(frappe.ValidationError):
51 pass
52
Nabin Hait16099332015-09-03 16:03:07 +053053
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053054@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +053055def get_party_details(
56 party=None,
57 account=None,
58 party_type="Customer",
59 company=None,
60 posting_date=None,
61 bill_date=None,
62 price_list=None,
63 currency=None,
64 doctype=None,
65 ignore_permissions=False,
66 fetch_payment_terms_template=True,
67 party_address=None,
68 company_address=None,
69 shipping_address=None,
70 pos_profile=None,
71):
Anand Doshi201dbbd2014-02-20 15:21:53 +053072
Rushabh Mehtad7a5b732015-04-01 23:38:13 +053073 if not party:
74 return {}
Nabin Hait5ef121b2015-06-08 12:26:52 +053075 if not frappe.db.exists(party_type, party):
76 frappe.throw(_("{0}: {1} does not exists").format(party_type, party))
Ankush Menat494bd9e2022-03-28 18:52:46 +053077 return _get_party_details(
78 party,
79 account,
80 party_type,
81 company,
82 posting_date,
83 bill_date,
84 price_list,
85 currency,
86 doctype,
87 ignore_permissions,
88 fetch_payment_terms_template,
89 party_address,
90 company_address,
91 shipping_address,
92 pos_profile,
93 )
Anand Doshi201dbbd2014-02-20 15:21:53 +053094
Ankush Menat494bd9e2022-03-28 18:52:46 +053095
96def _get_party_details(
97 party=None,
98 account=None,
99 party_type="Customer",
100 company=None,
101 posting_date=None,
102 bill_date=None,
103 price_list=None,
104 currency=None,
105 doctype=None,
106 ignore_permissions=False,
107 fetch_payment_terms_template=True,
108 party_address=None,
109 company_address=None,
110 shipping_address=None,
111 pos_profile=None,
112):
113 party_details = frappe._dict(
114 set_account_and_due_date(party, account, party_type, company, posting_date, bill_date, doctype)
115 )
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530116 party = party_details[party_type.lower()]
Nabin Hait365ae272014-04-03 17:38:54 +0530117 party = frappe.get_doc(party_type, party)
Ankush Menate84c9f72024-01-03 20:10:19 +0530118
119 if not ignore_permissions:
120 ptype = "select" if frappe.only_has_select_perm(party_type) else "read"
121 frappe.has_permission(party_type, ptype, party, throw=True)
122
Deepesh Gargb72cdb42022-01-21 18:00:35 +0530123 currency = party.get("default_currency") or currency or get_company_currency(company)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530124
Ankush Menat494bd9e2022-03-28 18:52:46 +0530125 party_address, shipping_address = set_address_details(
126 party_details,
127 party,
128 party_type,
129 doctype,
130 company,
131 party_address,
132 company_address,
133 shipping_address,
Ankush Menatf4d74992023-10-17 22:11:56 +0530134 ignore_permissions=ignore_permissions,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530135 )
Deepesh Gargcf9347d2020-03-31 17:28:43 +0530136 set_contact_details(party_details, party, party_type)
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530137 set_other_values(party_details, party, party_type)
138 set_price_list(party_details, party, party_type, price_list, pos_profile)
Anand Doshi13ae5482014-04-10 18:40:57 +0530139
Ankush Menat494bd9e2022-03-28 18:52:46 +0530140 tax_template = set_taxes(
141 party.name,
142 party_type,
143 posting_date,
144 company,
145 customer_group=party_details.customer_group,
146 supplier_group=party_details.supplier_group,
147 tax_category=party_details.tax_category,
148 billing_address=party_address,
149 shipping_address=shipping_address,
150 )
Deepesh Gargf12be302021-11-30 20:34:53 +0530151
152 if tax_template:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530153 party_details["taxes_and_charges"] = tax_template
rohitwaghchaure3ffe8962018-07-13 17:40:48 +0530154
Deepesh Gargbcf56e62021-08-06 23:53:16 +0530155 if cint(fetch_payment_terms_template):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530156 party_details["payment_terms_template"] = get_payment_terms_template(
157 party.name, party_type, company
158 )
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530159
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530160 if not party_details.get("currency"):
161 party_details["currency"] = currency
Anand Doshi13ae5482014-04-10 18:40:57 +0530162
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530163 # sales team
Ankush Menat494bd9e2022-03-28 18:52:46 +0530164 if party_type == "Customer":
165 party_details["sales_team"] = [
166 {
167 "sales_person": d.sales_person,
168 "allocated_percentage": d.allocated_percentage or None,
169 "commission_rate": d.commission_rate,
170 }
171 for d in party.get("sales_team")
172 ]
Anand Doshi13ae5482014-04-10 18:40:57 +0530173
Zarrar7f8024c2018-08-01 17:45:05 +0530174 # supplier tax withholding category
175 if party_type == "Supplier" and party:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530176 party_details["supplier_tds"] = frappe.get_value(
177 party_type, party.name, "tax_withholding_category"
178 )
Zarrar7f8024c2018-08-01 17:45:05 +0530179
Vishal Dhayagude7aafc902023-03-28 16:48:03 +0530180 if not party_details.get("tax_category") and pos_profile:
181 party_details["tax_category"] = frappe.get_value("POS Profile", pos_profile, "tax_category")
182
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530183 return party_details
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530184
Ankush Menat494bd9e2022-03-28 18:52:46 +0530185
186def set_address_details(
187 party_details,
188 party,
189 party_type,
190 doctype=None,
191 company=None,
192 party_address=None,
193 company_address=None,
194 shipping_address=None,
Ankush Menatf4d74992023-10-17 22:11:56 +0530195 *,
Dany Robertf34ffc22023-11-20 11:10:56 +0000196 ignore_permissions=False,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530197):
198 billing_address_field = (
199 "customer_address" if party_type == "Lead" else party_type.lower() + "_address"
200 )
201 party_details[billing_address_field] = party_address or get_default_address(
202 party_type, party.name
203 )
Nabin Hait7eba1a32017-10-02 15:59:27 +0530204 if doctype:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530205 party_details.update(
206 get_fetch_values(doctype, billing_address_field, party_details[billing_address_field])
207 )
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530208 # address display
Ankush Menatf4d74992023-10-17 22:11:56 +0530209 party_details.address_display = render_address(
210 party_details[billing_address_field], check_permissions=not ignore_permissions
211 )
Nabin Hait9d1f0772014-02-19 17:43:24 +0530212 # shipping address
213 if party_type in ["Customer", "Lead"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530214 party_details.shipping_address_name = shipping_address or get_party_shipping_address(
215 party_type, party.name
216 )
Ankush Menatf4d74992023-10-17 22:11:56 +0530217 party_details.shipping_address = render_address(
218 party_details["shipping_address_name"], check_permissions=not ignore_permissions
219 )
Nabin Hait7eba1a32017-10-02 15:59:27 +0530220 if doctype:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530221 party_details.update(
222 get_fetch_values(doctype, "shipping_address_name", party_details.shipping_address_name)
223 )
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530224
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530225 if company_address:
Sagar Voraa3625b32022-07-29 12:41:40 +0530226 party_details.company_address = company_address
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530227 else:
228 party_details.update(get_company_address(company))
Shreya Shah4fa600a2018-06-05 11:27:53 +0530229
Sagar Vora5c066202023-03-13 14:02:50 +0000230 if doctype in SALES_TRANSACTION_TYPES and party_details.company_address:
231 party_details.update(get_fetch_values(doctype, "company_address", party_details.company_address))
Shreya Shah4fa600a2018-06-05 11:27:53 +0530232
Sagar Vora5c066202023-03-13 14:02:50 +0000233 if doctype in PURCHASE_TRANSACTION_TYPES:
Sagar Voraa3625b32022-07-29 12:41:40 +0530234 if shipping_address:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530235 party_details.update(
Sagar Voraa3625b32022-07-29 12:41:40 +0530236 shipping_address=shipping_address,
Vishakh Desai45299fe2023-11-18 17:10:01 +0530237 shipping_address_display=render_address(
238 shipping_address, check_permissions=not ignore_permissions
239 ),
Dany Robertf34ffc22023-11-20 11:10:56 +0000240 **get_fetch_values(doctype, "shipping_address", shipping_address),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530241 )
Sagar Voraa3625b32022-07-29 12:41:40 +0530242
243 if party_details.company_address:
244 # billing address
245 party_details.update(
246 billing_address=party_details.company_address,
247 billing_address_display=(
Ankush Menatf4d74992023-10-17 22:11:56 +0530248 party_details.company_address_display
249 or render_address(party_details.company_address, check_permissions=False)
Sagar Voraa3625b32022-07-29 12:41:40 +0530250 ),
Dany Robertf34ffc22023-11-20 11:10:56 +0000251 **get_fetch_values(doctype, "billing_address", party_details.company_address),
Sagar Voraa3625b32022-07-29 12:41:40 +0530252 )
253
254 # shipping address - if not already set
255 if not party_details.shipping_address:
256 party_details.update(
257 shipping_address=party_details.billing_address,
258 shipping_address_display=party_details.billing_address_display,
Dany Robertf34ffc22023-11-20 11:10:56 +0000259 **get_fetch_values(doctype, "shipping_address", party_details.billing_address),
Sagar Voraa3625b32022-07-29 12:41:40 +0530260 )
261
Sagar Vora5c066202023-03-13 14:02:50 +0000262 party_address, shipping_address = (
263 party_details.get(billing_address_field),
264 party_details.shipping_address_name,
265 )
266
267 party_details["tax_category"] = get_address_tax_category(
268 party.get("tax_category"),
269 party_address,
270 shipping_address if party_type != "Supplier" else party_address,
271 )
272
273 if doctype in TRANSACTION_TYPES:
Sagar Vora4205f562023-07-24 18:37:36 +0530274 with temporary_flag("company", company):
275 get_regional_address_details(party_details, doctype, company)
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530276
Sagar Vora5c066202023-03-13 14:02:50 +0000277 return party_address, shipping_address
Saif Ur Rehman67786682018-12-27 02:11:07 +0500278
Ankush Menat494bd9e2022-03-28 18:52:46 +0530279
Shreya Shah4fa600a2018-06-05 11:27:53 +0530280@erpnext.allow_regional
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530281def get_regional_address_details(party_details, doctype, company):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530282 pass
Anand Doshi13ae5482014-04-10 18:40:57 +0530283
Ankush Menat494bd9e2022-03-28 18:52:46 +0530284
Deepesh Gargcf9347d2020-03-31 17:28:43 +0530285def set_contact_details(party_details, party, party_type):
286 party_details.contact_person = get_default_contact(party_type, party.name)
Anand Doshi13ae5482014-04-10 18:40:57 +0530287
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530288 if not party_details.contact_person:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530289 party_details.update(
290 {
291 "contact_person": None,
292 "contact_display": None,
293 "contact_email": None,
294 "contact_mobile": None,
295 "contact_phone": None,
296 "contact_designation": None,
297 "contact_department": None,
298 }
299 )
Neil Trini Lasradofe2ffae2015-07-08 18:16:51 +0530300 else:
rohitwaghchaure2851a412023-10-18 16:31:35 +0530301 fields = [
302 "name as contact_person",
303 "full_name as contact_display",
304 "email_id as contact_email",
305 "mobile_no as contact_mobile",
306 "phone as contact_phone",
307 "designation as contact_designation",
308 "department as contact_department",
309 ]
310
311 contact_details = frappe.db.get_value(
312 "Contact", party_details.contact_person, fields, as_dict=True
313 )
314
315 party_details.update(contact_details)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530316
Ankush Menat494bd9e2022-03-28 18:52:46 +0530317
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530318def set_other_values(party_details, party, party_type):
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530319 # copy
ChillarAnand9ace7d62022-03-07 16:53:59 +0530320 if party_type == "Customer":
saurabh8e499512016-02-19 11:08:45 +0530321 to_copy = ["customer_name", "customer_group", "territory", "language"]
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530322 else:
Zlash6589070782018-04-19 18:37:29 +0530323 to_copy = ["supplier_name", "supplier_group", "language"]
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530324 for f in to_copy:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530325 party_details[f] = party.get(f)
Anand Doshi13ae5482014-04-10 18:40:57 +0530326
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530327 # fields prepended with default in Customer doctype
Ankush Menat494bd9e2022-03-28 18:52:46 +0530328 for f in ["currency"] + (
329 ["sales_partner", "commission_rate"] if party_type == "Customer" else []
330 ):
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530331 if party.get("default_" + f):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530332 party_details[f] = party.get("default_" + f)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530333
Ankush Menat494bd9e2022-03-28 18:52:46 +0530334
Rushabh Mehta72fbf902015-09-17 18:29:44 +0530335def get_default_price_list(party):
336 """Return default price list for party (Document object)"""
Nabin Hait34c551d2019-07-03 10:34:31 +0530337 if party.get("default_price_list"):
Rushabh Mehta72fbf902015-09-17 18:29:44 +0530338 return party.default_price_list
339
340 if party.doctype == "Customer":
Daizy Modi27df4552022-11-03 13:38:48 +0530341 return frappe.get_cached_value("Customer Group", party.customer_group, "default_price_list")
Rushabh Mehta72fbf902015-09-17 18:29:44 +0530342
Rushabh Mehta72fbf902015-09-17 18:29:44 +0530343
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530344def set_price_list(party_details, party, party_type, given_price_list, pos=None):
Anand Doshi13ae5482014-04-10 18:40:57 +0530345 # price list
Ankush Menat494bd9e2022-03-28 18:52:46 +0530346 price_list = get_permitted_documents("Price List")
rohitwaghchaure52107612020-05-05 12:12:33 +0530347
Faris Ansari64f01bd2020-04-14 11:51:48 +0530348 # if there is only one permitted document based on user permissions, set it
349 if price_list and len(price_list) == 1:
Suraj Shettydcc90e32018-05-04 17:52:57 +0530350 price_list = price_list[0]
Ankush Menat494bd9e2022-03-28 18:52:46 +0530351 elif pos and party_type == "Customer":
352 customer_price_list = frappe.get_value("Customer", party.name, "default_price_list")
deepeshgarg007c48efab2019-01-24 17:15:38 +0530353
354 if customer_price_list:
355 price_list = customer_price_list
356 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530357 pos_price_list = frappe.get_value("POS Profile", pos, "selling_price_list")
deepeshgarg0071f9a6fe2019-01-25 11:53:55 +0530358 price_list = pos_price_list or given_price_list
Suraj Shettydcc90e32018-05-04 17:52:57 +0530359 else:
360 price_list = get_default_price_list(party) or given_price_list
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530361
362 if price_list:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530363 party_details.price_list_currency = frappe.db.get_value(
364 "Price List", price_list, "currency", cache=True
365 )
Anand Doshi13ae5482014-04-10 18:40:57 +0530366
Ankush Menat494bd9e2022-03-28 18:52:46 +0530367 party_details[
368 "selling_price_list" if party.doctype == "Customer" else "buying_price_list"
369 ] = price_list
Anand Doshi13ae5482014-04-10 18:40:57 +0530370
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530371
Ankush Menat494bd9e2022-03-28 18:52:46 +0530372def set_account_and_due_date(
373 party, account, party_type, company, posting_date, bill_date, doctype
374):
Saqiba6f98d42020-07-23 18:51:26 +0530375 if doctype not in ["POS Invoice", "Sales Invoice", "Purchase Invoice"]:
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530376 # not an invoice
Ankush Menat494bd9e2022-03-28 18:52:46 +0530377 return {party_type.lower(): party}
Anand Doshi13ae5482014-04-10 18:40:57 +0530378
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530379 if party:
Anand Doshib20baf82015-09-25 16:17:50 +0530380 account = get_party_account(party_type, party, company)
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530381
Ankush Menat494bd9e2022-03-28 18:52:46 +0530382 account_fieldname = "debit_to" if party_type == "Customer" else "credit_to"
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530383 out = {
384 party_type.lower(): party,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530385 account_fieldname: account,
386 "due_date": get_due_date(posting_date, party_type, party, company, bill_date),
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530387 }
Shreya Shah3a9eec22018-02-16 13:05:21 +0530388
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530389 return out
Rushabh Mehta361df892015-09-18 12:59:51 +0530390
Ankush Menat494bd9e2022-03-28 18:52:46 +0530391
Nabin Haitdb030d12014-09-10 17:11:30 +0530392@frappe.whitelist()
Gursheen Anand7591f102023-06-12 11:06:03 +0530393def get_party_account(party_type, party=None, company=None, include_advance=False):
Rushabh Mehta364054a2015-02-21 14:39:35 +0530394 """Returns the account for the given `party`.
Ankush Menat494bd9e2022-03-28 18:52:46 +0530395 Will first search in party (Customer / Supplier) record, if not found,
396 will search in group (Customer Group / Supplier Group),
397 finally will return default."""
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530398 if not company:
Anand Doshib20baf82015-09-25 16:17:50 +0530399 frappe.throw(_("Please select a Company"))
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530400
Ankush Menat494bd9e2022-03-28 18:52:46 +0530401 if not party and party_type in ["Customer", "Supplier"]:
402 default_account_name = (
403 "default_receivable_account" if party_type == "Customer" else "default_payable_account"
404 )
Deepesh Garg88648572021-11-12 12:39:30 +0530405
Ankush Menat494bd9e2022-03-28 18:52:46 +0530406 return frappe.get_cached_value("Company", company, default_account_name)
Saurabh0f86d862017-11-10 19:21:09 +0530407
Ankush Menat494bd9e2022-03-28 18:52:46 +0530408 account = frappe.db.get_value(
409 "Party Account", {"parenttype": party_type, "parent": party, "company": company}, "account"
410 )
Saurabh0f86d862017-11-10 19:21:09 +0530411
Ankush Menat494bd9e2022-03-28 18:52:46 +0530412 if not account and party_type in ["Customer", "Supplier"]:
413 party_group_doctype = "Customer Group" if party_type == "Customer" else "Supplier Group"
Nabin Hait9a33bc62018-08-09 10:47:09 +0530414 group = frappe.get_cached_value(party_type, party, scrub(party_group_doctype))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530415 account = frappe.db.get_value(
416 "Party Account",
417 {"parenttype": party_group_doctype, "parent": group, "company": company},
418 "account",
419 )
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530420
Ankush Menat494bd9e2022-03-28 18:52:46 +0530421 if not account and party_type in ["Customer", "Supplier"]:
422 default_account_name = (
423 "default_receivable_account" if party_type == "Customer" else "default_payable_account"
424 )
425 account = frappe.get_cached_value("Company", company, default_account_name)
Rushabh Mehta364054a2015-02-21 14:39:35 +0530426
Saurabh0f86d862017-11-10 19:21:09 +0530427 existing_gle_currency = get_party_gle_currency(party_type, party, company)
428 if existing_gle_currency:
429 if account:
Daizy Modi010bd9c2022-11-03 14:36:48 +0530430 account_currency = frappe.get_cached_value("Account", account, "account_currency")
Saurabh0f86d862017-11-10 19:21:09 +0530431 if (account and account_currency != existing_gle_currency) or not account:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530432 account = get_party_gle_account(party_type, party, company)
Rushabh Mehtab92087c2017-01-13 18:53:11 +0530433
RitvikSardanad2f03c82023-09-05 12:00:54 +0530434 if include_advance and party_type in ["Customer", "Supplier", "Student"]:
Gursheen Anand7591f102023-06-12 11:06:03 +0530435 advance_account = get_party_advance_account(party_type, party, company)
Deepesh Garg92f845c2023-06-21 12:21:19 +0530436 if advance_account:
437 return [account, advance_account]
438 else:
439 return [account]
440
Saurabh0f86d862017-11-10 19:21:09 +0530441 return account
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530442
Ankush Menat494bd9e2022-03-28 18:52:46 +0530443
Gursheen Anand74619262023-06-02 17:13:51 +0530444def get_party_advance_account(party_type, party, company):
Gursheen Anand74619262023-06-02 17:13:51 +0530445 account = frappe.db.get_value(
Gursheen Anand4ee16372023-06-08 13:15:23 +0530446 "Party Account",
447 {"parenttype": party_type, "parent": party, "company": company},
448 "advance_account",
Gursheen Anand74619262023-06-02 17:13:51 +0530449 )
450
451 if not account:
452 party_group_doctype = "Customer Group" if party_type == "Customer" else "Supplier Group"
453 group = frappe.get_cached_value(party_type, party, scrub(party_group_doctype))
454 account = frappe.db.get_value(
455 "Party Account",
456 {"parenttype": party_group_doctype, "parent": group, "company": company},
Gursheen Anand4ee16372023-06-08 13:15:23 +0530457 "advance_account",
Gursheen Anand74619262023-06-02 17:13:51 +0530458 )
Gursheen Anand4ee16372023-06-08 13:15:23 +0530459
Gursheen Anand74619262023-06-02 17:13:51 +0530460 if not account:
Gursheen Ananda06017c2023-06-12 15:24:53 +0530461 account_name = (
462 "default_advance_received_account"
463 if party_type == "Customer"
464 else "default_advance_paid_account"
465 )
466 account = frappe.get_cached_value("Company", company, account_name)
Gursheen Anand74619262023-06-02 17:13:51 +0530467
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530468 return account
Anand Doshib20baf82015-09-25 16:17:50 +0530469
470
rohitwaghchaure713cfc72018-09-11 17:40:37 +0530471@frappe.whitelist()
472def get_party_bank_account(party_type, party):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530473 return frappe.db.get_value(
474 "Bank Account", {"party_type": party_type, "party": party, "is_default": 1}
475 )
476
rohitwaghchaure713cfc72018-09-11 17:40:37 +0530477
Anand Doshib20baf82015-09-25 16:17:50 +0530478def get_party_account_currency(party_type, party, company):
479 def generator():
480 party_account = get_party_account(party_type, party, company)
Daizy Modi010bd9c2022-11-03 14:36:48 +0530481 return frappe.get_cached_value("Account", party_account, "account_currency")
Anand Doshib20baf82015-09-25 16:17:50 +0530482
483 return frappe.local_cache("party_account_currency", (party_type, party, company), generator)
484
Ankush Menat494bd9e2022-03-28 18:52:46 +0530485
Anand Doshi4945b942015-09-30 16:41:15 +0530486def get_party_gle_currency(party_type, party, company):
487 def generator():
ruthra kumar8d9b90f2023-10-27 12:37:37 +0530488 gl = qb.DocType("GL Entry")
489 existing_gle_currency = (
490 qb.from_(gl)
491 .select(gl.account_currency)
492 .where(
493 (gl.docstatus == 1)
494 & (gl.company == company)
495 & (gl.party_type == party_type)
496 & (gl.party == party)
497 & (gl.is_cancelled == 0)
498 )
499 .limit(1)
500 .run()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530501 )
Anand Doshi4945b942015-09-30 16:41:15 +0530502
503 return existing_gle_currency[0][0] if existing_gle_currency else None
504
Ankush Menat494bd9e2022-03-28 18:52:46 +0530505 return frappe.local_cache(
506 "party_gle_currency", (party_type, party, company), generator, regenerate_if_none=True
507 )
508
Rushabh Mehtab92087c2017-01-13 18:53:11 +0530509
Nabin Hait16d69592016-06-28 16:15:58 +0530510def get_party_gle_account(party_type, party, company):
511 def generator():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530512 existing_gle_account = frappe.db.sql(
513 """select account from `tabGL Entry`
Nabin Hait16d69592016-06-28 16:15:58 +0530514 where docstatus=1 and company=%(company)s and party_type=%(party_type)s and party=%(party)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530515 limit 1""",
516 {"company": company, "party_type": party_type, "party": party},
517 )
Nabin Hait16d69592016-06-28 16:15:58 +0530518
519 return existing_gle_account[0][0] if existing_gle_account else None
520
Ankush Menat494bd9e2022-03-28 18:52:46 +0530521 return frappe.local_cache(
522 "party_gle_account", (party_type, party, company), generator, regenerate_if_none=True
523 )
524
Anand Doshi4945b942015-09-30 16:41:15 +0530525
Anand Doshid8bc40d2015-10-22 17:54:50 +0530526def validate_party_gle_currency(party_type, party, company, party_account_currency=None):
Anand Doshi4945b942015-09-30 16:41:15 +0530527 """Validate party account currency with existing GL Entry's currency"""
Anand Doshid8bc40d2015-10-22 17:54:50 +0530528 if not party_account_currency:
529 party_account_currency = get_party_account_currency(party_type, party, company)
530
Anand Doshi4945b942015-09-30 16:41:15 +0530531 existing_gle_currency = get_party_gle_currency(party_type, party, company)
532
533 if existing_gle_currency and party_account_currency != existing_gle_currency:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530534 frappe.throw(
535 _(
536 "{0} {1} has accounting entries in currency {2} for company {3}. Please select a receivable or payable account with currency {2}."
537 ).format(
538 frappe.bold(party_type),
539 frappe.bold(party),
540 frappe.bold(existing_gle_currency),
541 frappe.bold(company),
542 ),
543 InvalidAccountCurrency,
544 )
545
Anand Doshi4945b942015-09-30 16:41:15 +0530546
Anand Doshida98ab62015-09-28 15:13:38 +0530547def validate_party_accounts(doc):
Deepesh Garg5a2b5712022-02-18 20:05:49 +0530548 from erpnext.controllers.accounts_controller import validate_account_head
Ankush Menat494bd9e2022-03-28 18:52:46 +0530549
Anand Doshida98ab62015-09-28 15:13:38 +0530550 companies = []
551
552 for account in doc.get("accounts"):
553 if account.company in companies:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530554 frappe.throw(
555 _("There can only be 1 Account per Company in {0} {1}").format(doc.doctype, doc.name),
556 DuplicatePartyAccountError,
557 )
Anand Doshida98ab62015-09-28 15:13:38 +0530558 else:
559 companies.append(account.company)
Anand Doshid8bc40d2015-10-22 17:54:50 +0530560
Daizy Modi010bd9c2022-11-03 14:36:48 +0530561 party_account_currency = frappe.get_cached_value("Account", account.account, "account_currency")
hendrikc257ce82019-09-05 16:44:09 +0700562 if frappe.db.get_default("Company"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530563 company_default_currency = frappe.get_cached_value(
564 "Company", frappe.db.get_default("Company"), "default_currency"
565 )
hendrikc257ce82019-09-05 16:44:09 +0700566 else:
Daizy Modi27df4552022-11-03 13:38:48 +0530567 company_default_currency = frappe.get_cached_value(
568 "Company", account.company, "default_currency"
569 )
Anand Doshid8bc40d2015-10-22 17:54:50 +0530570
Deepesh Garg1a2cf5c2020-03-28 21:26:16 +0530571 validate_party_gle_currency(doc.doctype, doc.name, account.company, party_account_currency)
Anand Doshida98ab62015-09-28 15:13:38 +0530572
rohitwaghchaureea092a72017-02-01 12:02:08 +0530573 if doc.get("default_currency") and party_account_currency and company_default_currency:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530574 if (
575 doc.default_currency != party_account_currency
576 and doc.default_currency != company_default_currency
577 ):
578 frappe.throw(
579 _(
580 "Billing currency must be equal to either default company's currency or party account currency"
581 )
582 )
tunde3b4bd372017-08-31 16:28:47 +0100583
Deepesh Garg5a2b5712022-02-18 20:05:49 +0530584 # validate if account is mapped for same company
Gursheen Anand74619262023-06-02 17:13:51 +0530585 if account.account:
586 validate_account_head(account.idx, account.account, account.company)
587 if account.advance_account:
588 validate_account_head(account.idx, account.advance_account, account.company)
Deepesh Garg5a2b5712022-02-18 20:05:49 +0530589
rohitwaghchaure62fea032016-03-30 13:24:42 +0530590
Nabin Hait4770a1a2015-07-09 16:35:46 +0530591@frappe.whitelist()
Shreya Shah3a9eec22018-02-16 13:05:21 +0530592def get_due_date(posting_date, party_type, party, company=None, bill_date=None):
tunde3b4bd372017-08-31 16:28:47 +0100593 """Get due date from `Payment Terms Template`"""
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530594 due_date = None
Shreya Shah3a9eec22018-02-16 13:05:21 +0530595 if (bill_date or posting_date) and party:
596 due_date = bill_date or posting_date
marinationfa085d72020-10-27 13:18:30 +0530597 template_name = get_payment_terms_template(party, party_type, company)
rohitwaghchaure3ffe8962018-07-13 17:40:48 +0530598
tunde3b4bd372017-08-31 16:28:47 +0100599 if template_name:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530600 due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime(
601 "%Y-%m-%d"
602 )
tundeed86efb2017-09-05 01:15:31 +0100603 else:
604 if party_type == "Supplier":
Nabin Hait9a33bc62018-08-09 10:47:09 +0530605 supplier_group = frappe.get_cached_value(party_type, party, "supplier_group")
606 template_name = frappe.get_cached_value("Supplier Group", supplier_group, "payment_terms")
tundee5973e42017-09-05 18:11:58 +0100607 if template_name:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530608 due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime(
609 "%Y-%m-%d"
610 )
Shreya Shah3a9eec22018-02-16 13:05:21 +0530611 # If due date is calculated from bill_date, check this condition
612 if getdate(due_date) < getdate(posting_date):
613 due_date = posting_date
Anand Doshi13ae5482014-04-10 18:40:57 +0530614 return due_date
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530615
Ankush Menat494bd9e2022-03-28 18:52:46 +0530616
Shreya Shah3a9eec22018-02-16 13:05:21 +0530617def get_due_date_from_template(template_name, posting_date, bill_date):
tunde3b4bd372017-08-31 16:28:47 +0100618 """
619 Inspects all `Payment Term`s from the a `Payment Terms Template` and returns the due
620 date after considering all the `Payment Term`s requirements.
621 :param template_name: Name of the `Payment Terms Template`
622 :return: String representing the calculated due date
623 """
Shreya Shah3a9eec22018-02-16 13:05:21 +0530624 due_date = getdate(bill_date or posting_date)
625
Ankush Menat494bd9e2022-03-28 18:52:46 +0530626 template = frappe.get_doc("Payment Terms Template", template_name)
tunde3b4bd372017-08-31 16:28:47 +0100627
628 for term in template.terms:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530629 if term.due_date_based_on == "Day(s) after invoice date":
tunde3b4bd372017-08-31 16:28:47 +0100630 due_date = max(due_date, add_days(due_date, term.credit_days))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530631 elif term.due_date_based_on == "Day(s) after the end of the invoice month":
tunde3b4bd372017-08-31 16:28:47 +0100632 due_date = max(due_date, add_days(get_last_day(due_date), term.credit_days))
633 else:
developsessionsce8a1082023-02-03 11:30:29 +0100634 due_date = max(due_date, get_last_day(add_months(due_date, term.credit_months)))
tunde3b4bd372017-08-31 16:28:47 +0100635 return due_date
636
Ankush Menat494bd9e2022-03-28 18:52:46 +0530637
Deepesh Garg5b157182024-01-04 10:48:01 +0530638def validate_due_date(posting_date, due_date, bill_date=None, template_name=None):
Nabin Hait4770a1a2015-07-09 16:35:46 +0530639 if getdate(due_date) < getdate(posting_date):
Rohit Waghchaured1a85a32018-11-26 18:42:29 +0530640 frappe.throw(_("Due Date cannot be before Posting / Supplier Invoice Date"))
Nabin Hait4770a1a2015-07-09 16:35:46 +0530641 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530642 if not template_name:
643 return
rohitwaghchaure3ffe8962018-07-13 17:40:48 +0530644
Ankush Menat494bd9e2022-03-28 18:52:46 +0530645 default_due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime(
646 "%Y-%m-%d"
647 )
Saurabhd7897f12018-07-18 17:08:16 +0530648
Anand Doshi0ca587e2015-09-25 16:32:14 +0530649 if not default_due_date:
650 return
651
Nabin Hait93d3c822015-07-10 17:11:58 +0530652 if default_due_date != posting_date and getdate(due_date) > getdate(default_due_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530653 is_credit_controller = (
654 frappe.db.get_single_value("Accounts Settings", "credit_controller") in frappe.get_roles()
655 )
Nabin Hait4770a1a2015-07-09 16:35:46 +0530656 if is_credit_controller:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530657 msgprint(
658 _("Note: Due / Reference Date exceeds allowed customer credit days by {0} day(s)").format(
659 date_diff(due_date, default_due_date)
660 )
661 )
Nabin Hait4770a1a2015-07-09 16:35:46 +0530662 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530663 frappe.throw(
664 _("Due / Reference Date cannot be after {0}").format(formatdate(default_due_date))
665 )
666
Rushabh Mehta361df892015-09-18 12:59:51 +0530667
Neil Trini Lasrado09f9c962015-08-26 10:41:31 +0530668@frappe.whitelist()
Nabin Hait16a7ec92019-09-05 13:01:15 +0530669def get_address_tax_category(tax_category=None, billing_address=None, shipping_address=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530670 addr_tax_category_from = frappe.db.get_single_value(
671 "Accounts Settings", "determine_address_tax_category_from"
672 )
Saif Ur Rehmanfd531a62018-12-29 01:49:11 +0500673 if addr_tax_category_from == "Shipping Address":
674 if shipping_address:
675 tax_category = frappe.db.get_value("Address", shipping_address, "tax_category") or tax_category
676 else:
677 if billing_address:
678 tax_category = frappe.db.get_value("Address", billing_address, "tax_category") or tax_category
679
680 return cstr(tax_category)
Saif Ur Rehman67786682018-12-27 02:11:07 +0500681
Ankush Menat494bd9e2022-03-28 18:52:46 +0530682
Neil Trini Lasrado09f9c962015-08-26 10:41:31 +0530683@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530684def set_taxes(
685 party,
686 party_type,
687 posting_date,
688 company,
689 customer_group=None,
690 supplier_group=None,
691 tax_category=None,
692 billing_address=None,
693 shipping_address=None,
694 use_for_shopping_cart=None,
695):
Chillar Anand915b3432021-09-02 16:44:59 +0530696 from erpnext.accounts.doctype.tax_rule.tax_rule import get_party_details, get_tax_template
Ankush Menat494bd9e2022-03-28 18:52:46 +0530697
698 args = {party_type.lower(): party, "company": company}
Rushabh Mehta361df892015-09-18 12:59:51 +0530699
Saif Ur Rehman67786682018-12-27 02:11:07 +0500700 if tax_category:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530701 args["tax_category"] = tax_category
Saif Ur Rehman67786682018-12-27 02:11:07 +0500702
Rushabh Mehta3c14c5a2017-09-29 13:21:22 +0530703 if customer_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530704 args["customer_group"] = customer_group
Rushabh Mehta3c14c5a2017-09-29 13:21:22 +0530705
Zlash6589070782018-04-19 18:37:29 +0530706 if supplier_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530707 args["supplier_group"] = supplier_group
Rushabh Mehta3c14c5a2017-09-29 13:21:22 +0530708
Neil Trini Lasrado09f9c962015-08-26 10:41:31 +0530709 if billing_address or shipping_address:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530710 args.update(
711 get_party_details(
712 party, party_type, {"billing_address": billing_address, "shipping_address": shipping_address}
713 )
714 )
Neil Trini Lasrado09f9c962015-08-26 10:41:31 +0530715 else:
716 args.update(get_party_details(party, party_type))
Rushabh Mehta361df892015-09-18 12:59:51 +0530717
Nabin Hait47ce6de2023-06-06 15:19:04 +0530718 if party_type in ("Customer", "Lead", "Prospect"):
Neil Trini Lasrado810bd352015-08-21 15:04:57 +0530719 args.update({"tax_type": "Sales"})
Anand Doshi2f957f22016-04-08 17:36:10 +0530720
Nabin Hait47ce6de2023-06-06 15:19:04 +0530721 if party_type in ["Lead", "Prospect"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530722 args["customer"] = None
Nabin Hait47ce6de2023-06-06 15:19:04 +0530723 del args[frappe.scrub(party_type)]
Neil Trini Lasrado810bd352015-08-21 15:04:57 +0530724 else:
725 args.update({"tax_type": "Purchase"})
Rushabh Mehta361df892015-09-18 12:59:51 +0530726
Saurabh957e7a32015-09-11 15:44:06 +0530727 if use_for_shopping_cart:
Saurabh957e7a32015-09-11 15:44:06 +0530728 args.update({"use_for_shopping_cart": use_for_shopping_cart})
Rushabh Mehta361df892015-09-18 12:59:51 +0530729
730 return get_tax_template(posting_date, args)
shreyas29b565f2016-01-25 17:30:49 +0530731
tunde400d0462017-08-31 13:44:57 +0100732
733@frappe.whitelist()
marinationfa085d72020-10-27 13:18:30 +0530734def get_payment_terms_template(party_name, party_type, company=None):
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530735 if party_type not in ("Customer", "Supplier"):
736 return
tunde400d0462017-08-31 13:44:57 +0100737 template = None
Deepesh Garg5b6a9fc2023-06-17 13:08:18 +0530738
Ankush Menat494bd9e2022-03-28 18:52:46 +0530739 if party_type == "Customer":
740 customer = frappe.get_cached_value(
741 "Customer", party_name, fieldname=["payment_terms", "customer_group"], as_dict=1
742 )
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530743 template = customer.payment_terms
744
745 if not template and customer.customer_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530746 template = frappe.get_cached_value("Customer Group", customer.customer_group, "payment_terms")
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530747 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530748 supplier = frappe.get_cached_value(
749 "Supplier", party_name, fieldname=["payment_terms", "supplier_group"], as_dict=1
750 )
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530751 template = supplier.payment_terms
Zlash6589070782018-04-19 18:37:29 +0530752 if not template and supplier.supplier_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530753 template = frappe.get_cached_value("Supplier Group", supplier.supplier_group, "payment_terms")
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530754
755 if not template and company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530756 template = frappe.get_cached_value("Company", company, fieldname="payment_terms")
tunde400d0462017-08-31 13:44:57 +0100757 return template
758
Ankush Menat494bd9e2022-03-28 18:52:46 +0530759
shreyaseba9ca42016-01-26 14:56:52 +0530760def validate_party_frozen_disabled(party_type, party_name):
Subin Tomb8845b92021-07-30 16:30:18 +0530761
762 if frappe.flags.ignore_party_validation:
763 return
764
shreyas79872bf2016-01-26 13:57:06 +0530765 if party_type and party_name:
KanchanChauhanfbaa6192017-01-30 15:15:58 +0530766 if party_type in ("Customer", "Supplier"):
Nabin Hait9a33bc62018-08-09 10:47:09 +0530767 party = frappe.get_cached_value(party_type, party_name, ["is_frozen", "disabled"], as_dict=True)
deepeshgarg007737ec6b2019-10-20 17:36:36 +0530768 if party.disabled:
769 frappe.throw(_("{0} {1} is disabled").format(party_type, party_name), PartyDisabled)
770 elif party.get("is_frozen"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530771 frozen_accounts_modifier = frappe.db.get_single_value(
772 "Accounts Settings", "frozen_accounts_modifier"
773 )
barredterraeb9ee3f2023-12-05 11:22:55 +0100774 if frozen_accounts_modifier not in frappe.get_roles():
KanchanChauhanfbaa6192017-01-30 15:15:58 +0530775 frappe.throw(_("{0} {1} is frozen").format(party_type, party_name), PartyFrozen)
776
777 elif party_type == "Employee":
Rucha Mahabala38147a2021-06-12 13:33:21 +0530778 if frappe.db.get_value("Employee", party_name, "status") != "Active":
Kanchan Chauhan95108ac2017-04-11 15:55:34 +0530779 frappe.msgprint(_("{0} {1} is not active").format(party_type, party_name), alert=True)
Rushabh Mehta15a7f212016-04-14 17:30:40 +0530780
Ankush Menat494bd9e2022-03-28 18:52:46 +0530781
Rushabh Mehta15a7f212016-04-14 17:30:40 +0530782def get_timeline_data(doctype, name):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530783 """returns timeline data for the past one year"""
Rushabh Mehta15a7f212016-04-14 17:30:40 +0530784 from frappe.desk.form.load import get_communication_data
mbauskare7b87ad2017-02-16 13:12:29 +0530785
786 out = {}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530787 after = add_years(None, -1).strftime("%Y-%m-%d")
Zarrar58200182018-05-30 11:56:23 +0530788
Ankush Menat494bd9e2022-03-28 18:52:46 +0530789 data = get_communication_data(
790 doctype,
791 name,
792 after=after,
Gursheen Anand87df7ff2024-02-21 18:44:29 +0530793 group_by="group by communication_date",
794 fields="C.communication_date as communication_date, count(C.name)",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530795 as_dict=False,
796 )
Zarrar58200182018-05-30 11:56:23 +0530797
798 # fetch and append data from Activity Log
Gursheen Anand87df7ff2024-02-21 18:44:29 +0530799 activity_log = frappe.qb.DocType("Activity Log")
800 data += (
801 frappe.qb.from_(activity_log)
802 .select(activity_log.communication_date, Count(activity_log.name))
803 .where(
804 (
805 ((activity_log.reference_doctype == doctype) & (activity_log.reference_name == name))
806 | ((activity_log.timeline_doctype == doctype) & (activity_log.timeline_name == name))
807 | (
808 (activity_log.reference_doctype.isin(["Quotation", "Opportunity"]))
809 & (activity_log.timeline_name == name)
810 )
811 )
812 & (activity_log.status != "Success")
813 & (activity_log.creation > after)
814 )
815 .groupby(activity_log.communication_date)
816 .orderby(activity_log.communication_date, order=frappe.qb.desc)
817 ).run()
mbauskare7b87ad2017-02-16 13:12:29 +0530818
819 timeline_items = dict(data)
820
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530821 for date, count in timeline_items.items():
mbauskare7b87ad2017-02-16 13:12:29 +0530822 timestamp = get_timestamp(date)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530823 out.update({timestamp: count})
mbauskare7b87ad2017-02-16 13:12:29 +0530824
Nabin Hait2d79a642017-05-24 12:41:14 +0530825 return out
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530826
Ankush Menat494bd9e2022-03-28 18:52:46 +0530827
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530828def get_dashboard_info(party_type, party, loyalty_program=None):
Nabin Hait2d79a642017-05-24 12:41:14 +0530829 current_fiscal_year = get_fiscal_year(nowdate(), as_dict=True)
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530830
Ankush Menat494bd9e2022-03-28 18:52:46 +0530831 doctype = "Sales Invoice" if party_type == "Customer" else "Purchase Invoice"
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530832
Ankush Menat494bd9e2022-03-28 18:52:46 +0530833 companies = frappe.get_all(
834 doctype, filters={"docstatus": 1, party_type.lower(): party}, distinct=1, fields=["company"]
835 )
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530836
deepeshgarg007920dc142018-11-23 10:17:28 +0530837 company_wise_info = []
838
Ankush Menat494bd9e2022-03-28 18:52:46 +0530839 company_wise_grand_total = frappe.get_all(
840 doctype,
deepeshgarg007ee05e352018-11-29 16:24:28 +0530841 filters={
Ankush Menat494bd9e2022-03-28 18:52:46 +0530842 "docstatus": 1,
deepeshgarg007ee05e352018-11-29 16:24:28 +0530843 party_type.lower(): party,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530844 "posting_date": (
845 "between",
846 [current_fiscal_year.year_start_date, current_fiscal_year.year_end_date],
847 ),
848 },
849 group_by="company",
850 fields=[
851 "company",
852 "sum(grand_total) as grand_total",
853 "sum(base_grand_total) as base_grand_total",
854 ],
855 )
deepeshgarg007920dc142018-11-23 10:17:28 +0530856
deepeshgarg007a1d015c2018-12-26 11:01:02 +0530857 loyalty_point_details = []
858
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530859 if party_type == "Customer":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530860 loyalty_point_details = frappe._dict(
861 frappe.get_all(
862 "Loyalty Point Entry",
863 filters={
864 "customer": party,
865 "expiry_date": (">=", getdate()),
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530866 },
867 group_by="company",
868 fields=["company", "sum(loyalty_points) as loyalty_points"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530869 as_list=1,
870 )
871 )
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530872
deepeshgarg007f31caff2018-11-27 15:04:12 +0530873 company_wise_billing_this_year = frappe._dict()
874
875 for d in company_wise_grand_total:
876 company_wise_billing_this_year.setdefault(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530877 d.company, {"grand_total": d.grand_total, "base_grand_total": d.base_grand_total}
878 )
deepeshgarg007f31caff2018-11-27 15:04:12 +0530879
Ankush Menat494bd9e2022-03-28 18:52:46 +0530880 company_wise_total_unpaid = frappe._dict(
881 frappe.db.sql(
882 """
deepeshgarg007920dc142018-11-23 10:17:28 +0530883 select company, sum(debit_in_account_currency) - sum(credit_in_account_currency)
Nabin Hait24f0b132017-05-24 13:01:26 +0530884 from `tabGL Entry`
deepeshgarg007920dc142018-11-23 10:17:28 +0530885 where party_type = %s and party=%s
Deepesh Garg802e63a2021-06-28 11:24:32 +0530886 and is_cancelled = 0
Ankush Menat494bd9e2022-03-28 18:52:46 +0530887 group by company""",
888 (party_type, party),
889 )
890 )
Nabin Hait2d79a642017-05-24 12:41:14 +0530891
deepeshgarg007920dc142018-11-23 10:17:28 +0530892 for d in companies:
Daizy Modi27df4552022-11-03 13:38:48 +0530893 company_default_currency = frappe.get_cached_value("Company", d.company, "default_currency")
deepeshgarg007920dc142018-11-23 10:17:28 +0530894 party_account_currency = get_party_account_currency(party_type, party, d.company)
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530895
Ankush Menat494bd9e2022-03-28 18:52:46 +0530896 if party_account_currency == company_default_currency:
897 billing_this_year = flt(
898 company_wise_billing_this_year.get(d.company, {}).get("base_grand_total")
899 )
deepeshgarg007920dc142018-11-23 10:17:28 +0530900 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530901 billing_this_year = flt(company_wise_billing_this_year.get(d.company, {}).get("grand_total"))
deepeshgarg007920dc142018-11-23 10:17:28 +0530902
903 total_unpaid = flt(company_wise_total_unpaid.get(d.company))
904
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530905 if loyalty_point_details:
906 loyalty_points = loyalty_point_details.get(d.company)
907
deepeshgarg007920dc142018-11-23 10:17:28 +0530908 info = {}
909 info["billing_this_year"] = flt(billing_this_year) if billing_this_year else 0
910 info["currency"] = party_account_currency
911 info["total_unpaid"] = flt(total_unpaid) if total_unpaid else 0
912 info["company"] = d.company
913
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530914 if party_type == "Customer" and loyalty_point_details:
915 info["loyalty_points"] = loyalty_points
916
deepeshgarg007920dc142018-11-23 10:17:28 +0530917 if party_type == "Supplier":
918 info["total_unpaid"] = -1 * info["total_unpaid"]
919
920 company_wise_info.append(info)
921
922 return company_wise_info
tundebabzy40a02762017-10-25 07:54:34 +0100923
Ankush Menat494bd9e2022-03-28 18:52:46 +0530924
Raffael Meyerb91bb172023-06-08 16:19:09 +0200925def get_party_shipping_address(doctype: str, name: str) -> Optional[str]:
tundebabzy40a02762017-10-25 07:54:34 +0100926 """
927 Returns an Address name (best guess) for the given doctype and name for which `address_type == 'Shipping'` is true.
928 and/or `is_shipping_address = 1`.
929
930 It returns an empty string if there is no matching record.
931
932 :param doctype: Party Doctype
933 :param name: Party name
934 :return: String
935 """
Raffael Meyerb91bb172023-06-08 16:19:09 +0200936 shipping_addresses = frappe.get_all(
937 "Address",
938 filters=[
939 ["Dynamic Link", "link_doctype", "=", doctype],
940 ["Dynamic Link", "link_name", "=", name],
941 ["disabled", "=", 0],
942 ],
943 or_filters=[
944 ["is_shipping_address", "=", 1],
945 ["address_type", "=", "Shipping"],
946 ],
947 pluck="name",
948 limit=1,
949 order_by="is_shipping_address DESC",
tundebabzy40a02762017-10-25 07:54:34 +0100950 )
Raffael Meyerb91bb172023-06-08 16:19:09 +0200951
952 return shipping_addresses[0] if shipping_addresses else None
Rohit Waghchaureaffeb3d2019-01-15 17:38:31 +0530953
Ankush Menat494bd9e2022-03-28 18:52:46 +0530954
955def get_partywise_advanced_payment_amount(
ruthra kumar0dc5e5c2023-08-21 08:46:55 +0530956 party_type, posting_date=None, future_payment=0, company=None, party=None
Ankush Menat494bd9e2022-03-28 18:52:46 +0530957):
ruthra kumar0dc5e5c2023-08-21 08:46:55 +0530958 ple = frappe.qb.DocType("Payment Ledger Entry")
Gursheen Anande355dea2023-07-28 14:51:28 +0530959 query = (
ruthra kumar0dc5e5c2023-08-21 08:46:55 +0530960 frappe.qb.from_(ple)
961 .select(ple.party, Abs(Sum(ple.amount).as_("amount")))
Gursheen Anande355dea2023-07-28 14:51:28 +0530962 .where(
ruthra kumar0dc5e5c2023-08-21 08:46:55 +0530963 (ple.party_type.isin(party_type))
964 & (ple.amount < 0)
965 & (ple.against_voucher_no == ple.voucher_no)
966 & (ple.delinked == 0)
Gursheen Anande355dea2023-07-28 14:51:28 +0530967 )
ruthra kumar0dc5e5c2023-08-21 08:46:55 +0530968 .groupby(ple.party)
Gursheen Anande355dea2023-07-28 14:51:28 +0530969 )
Gursheen Anande355dea2023-07-28 14:51:28 +0530970
Rohit Waghchaure4ed7d032019-03-25 15:37:25 +0530971 if posting_date:
Deepesh Garged2c1802020-05-27 12:46:12 +0530972 if future_payment:
ruthra kumar0dc5e5c2023-08-21 08:46:55 +0530973 query = query.where((ple.posting_date <= posting_date) | (Date(ple.creation) <= posting_date))
Deepesh Garged2c1802020-05-27 12:46:12 +0530974 else:
ruthra kumar0dc5e5c2023-08-21 08:46:55 +0530975 query = query.where(ple.posting_date <= posting_date)
Deepesh Garged2c1802020-05-27 12:46:12 +0530976
Saqib39805912020-05-01 18:15:13 +0530977 if company:
ruthra kumar0dc5e5c2023-08-21 08:46:55 +0530978 query = query.where(ple.company == company)
Rohit Waghchaure4ed7d032019-03-25 15:37:25 +0530979
Nabin Hait3504bf72023-05-29 09:23:40 +0530980 if party:
ruthra kumar0dc5e5c2023-08-21 08:46:55 +0530981 query = query.where(ple.party == party)
Nabin Hait3504bf72023-05-29 09:23:40 +0530982
Dany Robertf34ffc22023-11-20 11:10:56 +0000983 if invoice_doctypes := frappe.get_hooks("invoice_doctypes"):
984 query = query.where(ple.voucher_type.notin(invoice_doctypes))
985
ruthra kumar896b1232023-08-20 21:17:27 +0530986 data = query.run()
Rohit Waghchaureaffeb3d2019-01-15 17:38:31 +0530987 if data:
hendrikc257ce82019-09-05 16:44:09 +0700988 return frappe._dict(data)
Ronel Cabrerafcb54762019-11-18 17:00:07 +0800989
Ankush Menat494bd9e2022-03-28 18:52:46 +0530990
Raffael Meyerb91bb172023-06-08 16:19:09 +0200991def get_default_contact(doctype: str, name: str) -> Optional[str]:
Deepesh Gargcf9347d2020-03-31 17:28:43 +0530992 """
Raffael Meyerb91bb172023-06-08 16:19:09 +0200993 Returns contact name only if there is a primary contact for given doctype and name.
994
995 Else returns None
996
997 :param doctype: Party Doctype
998 :param name: Party name
999 :return: String
Ronel Cabrerafcb54762019-11-18 17:00:07 +08001000 """
Raffael Meyerb91bb172023-06-08 16:19:09 +02001001 contacts = frappe.get_all(
1002 "Contact",
1003 filters=[
1004 ["Dynamic Link", "link_doctype", "=", doctype],
1005 ["Dynamic Link", "link_name", "=", name],
1006 ],
1007 or_filters=[
1008 ["is_primary_contact", "=", 1],
1009 ["is_billing_contact", "=", 1],
1010 ],
1011 pluck="name",
1012 limit=1,
1013 order_by="is_primary_contact DESC, is_billing_contact DESC",
Ankush Menat494bd9e2022-03-28 18:52:46 +05301014 )
Raffael Meyerb91bb172023-06-08 16:19:09 +02001015
1016 return contacts[0] if contacts else None
Deepesh Gargbc347372022-05-25 15:42:47 +05301017
1018
1019def add_party_account(party_type, party, company, account):
1020 doc = frappe.get_doc(party_type, party)
1021 account_exists = False
1022 for d in doc.get("accounts"):
1023 if d.account == account:
1024 account_exists = True
1025
1026 if not account_exists:
1027 accounts = {"company": company, "account": account}
1028
1029 doc.append("accounts", accounts)
1030
1031 doc.save()
Ankush Menatf4d74992023-10-17 22:11:56 +05301032
1033
1034def render_address(address, check_permissions=True):
1035 try:
1036 from frappe.contacts.doctype.address.address import render_address as _render
1037 except ImportError:
1038 # Older frappe versions where this function is not available
1039 from frappe.contacts.doctype.address.address import get_address_display as _render
1040
1041 return frappe.call(_render, address, check_permissions=check_permissions)