blob: 1efe35c206b51326f3febaf130f24874ce08fef6 [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
ruthra kumar0dc5e5c2023-08-21 08:46:55 +053012from frappe.query_builder.functions import Abs, 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()]
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530117
Ankush Menat494bd9e2022-03-28 18:52:46 +0530118 if not ignore_permissions and not (
119 frappe.has_permission(party_type, "read", party)
120 or frappe.has_permission(party_type, "select", party)
121 ):
Rushabh Mehta2d708872015-11-27 11:35:35 +0530122 frappe.throw(_("Not permitted for {0}").format(party), frappe.PermissionError)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530123
Nabin Hait365ae272014-04-03 17:38:54 +0530124 party = frappe.get_doc(party_type, party)
Deepesh Gargb72cdb42022-01-21 18:00:35 +0530125 currency = party.get("default_currency") or currency or get_company_currency(company)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530126
Ankush Menat494bd9e2022-03-28 18:52:46 +0530127 party_address, shipping_address = set_address_details(
128 party_details,
129 party,
130 party_type,
131 doctype,
132 company,
133 party_address,
134 company_address,
135 shipping_address,
Ankush Menatf4d74992023-10-17 22:11:56 +0530136 ignore_permissions=ignore_permissions,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530137 )
Deepesh Gargcf9347d2020-03-31 17:28:43 +0530138 set_contact_details(party_details, party, party_type)
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530139 set_other_values(party_details, party, party_type)
140 set_price_list(party_details, party, party_type, price_list, pos_profile)
Anand Doshi13ae5482014-04-10 18:40:57 +0530141
Ankush Menat494bd9e2022-03-28 18:52:46 +0530142 tax_template = set_taxes(
143 party.name,
144 party_type,
145 posting_date,
146 company,
147 customer_group=party_details.customer_group,
148 supplier_group=party_details.supplier_group,
149 tax_category=party_details.tax_category,
150 billing_address=party_address,
151 shipping_address=shipping_address,
152 )
Deepesh Gargf12be302021-11-30 20:34:53 +0530153
154 if tax_template:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530155 party_details["taxes_and_charges"] = tax_template
rohitwaghchaure3ffe8962018-07-13 17:40:48 +0530156
Deepesh Gargbcf56e62021-08-06 23:53:16 +0530157 if cint(fetch_payment_terms_template):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530158 party_details["payment_terms_template"] = get_payment_terms_template(
159 party.name, party_type, company
160 )
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530161
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530162 if not party_details.get("currency"):
163 party_details["currency"] = currency
Anand Doshi13ae5482014-04-10 18:40:57 +0530164
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530165 # sales team
Ankush Menat494bd9e2022-03-28 18:52:46 +0530166 if party_type == "Customer":
167 party_details["sales_team"] = [
168 {
169 "sales_person": d.sales_person,
170 "allocated_percentage": d.allocated_percentage or None,
171 "commission_rate": d.commission_rate,
172 }
173 for d in party.get("sales_team")
174 ]
Anand Doshi13ae5482014-04-10 18:40:57 +0530175
Zarrar7f8024c2018-08-01 17:45:05 +0530176 # supplier tax withholding category
177 if party_type == "Supplier" and party:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530178 party_details["supplier_tds"] = frappe.get_value(
179 party_type, party.name, "tax_withholding_category"
180 )
Zarrar7f8024c2018-08-01 17:45:05 +0530181
Vishal Dhayagude7aafc902023-03-28 16:48:03 +0530182 if not party_details.get("tax_category") and pos_profile:
183 party_details["tax_category"] = frappe.get_value("POS Profile", pos_profile, "tax_category")
184
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530185 return party_details
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530186
Ankush Menat494bd9e2022-03-28 18:52:46 +0530187
188def set_address_details(
189 party_details,
190 party,
191 party_type,
192 doctype=None,
193 company=None,
194 party_address=None,
195 company_address=None,
196 shipping_address=None,
Ankush Menatf4d74992023-10-17 22:11:56 +0530197 *,
Dany Robertf34ffc22023-11-20 11:10:56 +0000198 ignore_permissions=False,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530199):
200 billing_address_field = (
201 "customer_address" if party_type == "Lead" else party_type.lower() + "_address"
202 )
203 party_details[billing_address_field] = party_address or get_default_address(
204 party_type, party.name
205 )
Nabin Hait7eba1a32017-10-02 15:59:27 +0530206 if doctype:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530207 party_details.update(
208 get_fetch_values(doctype, billing_address_field, party_details[billing_address_field])
209 )
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530210 # address display
Ankush Menatf4d74992023-10-17 22:11:56 +0530211 party_details.address_display = render_address(
212 party_details[billing_address_field], check_permissions=not ignore_permissions
213 )
Nabin Hait9d1f0772014-02-19 17:43:24 +0530214 # shipping address
215 if party_type in ["Customer", "Lead"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530216 party_details.shipping_address_name = shipping_address or get_party_shipping_address(
217 party_type, party.name
218 )
Ankush Menatf4d74992023-10-17 22:11:56 +0530219 party_details.shipping_address = render_address(
220 party_details["shipping_address_name"], check_permissions=not ignore_permissions
221 )
Nabin Hait7eba1a32017-10-02 15:59:27 +0530222 if doctype:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530223 party_details.update(
224 get_fetch_values(doctype, "shipping_address_name", party_details.shipping_address_name)
225 )
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530226
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530227 if company_address:
Sagar Voraa3625b32022-07-29 12:41:40 +0530228 party_details.company_address = company_address
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530229 else:
230 party_details.update(get_company_address(company))
Shreya Shah4fa600a2018-06-05 11:27:53 +0530231
Sagar Vora5c066202023-03-13 14:02:50 +0000232 if doctype in SALES_TRANSACTION_TYPES and party_details.company_address:
233 party_details.update(get_fetch_values(doctype, "company_address", party_details.company_address))
Shreya Shah4fa600a2018-06-05 11:27:53 +0530234
Sagar Vora5c066202023-03-13 14:02:50 +0000235 if doctype in PURCHASE_TRANSACTION_TYPES:
Sagar Voraa3625b32022-07-29 12:41:40 +0530236 if shipping_address:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530237 party_details.update(
Sagar Voraa3625b32022-07-29 12:41:40 +0530238 shipping_address=shipping_address,
Vishakh Desai45299fe2023-11-18 17:10:01 +0530239 shipping_address_display=render_address(
240 shipping_address, check_permissions=not ignore_permissions
241 ),
Dany Robertf34ffc22023-11-20 11:10:56 +0000242 **get_fetch_values(doctype, "shipping_address", shipping_address),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530243 )
Sagar Voraa3625b32022-07-29 12:41:40 +0530244
245 if party_details.company_address:
246 # billing address
247 party_details.update(
248 billing_address=party_details.company_address,
249 billing_address_display=(
Ankush Menatf4d74992023-10-17 22:11:56 +0530250 party_details.company_address_display
251 or render_address(party_details.company_address, check_permissions=False)
Sagar Voraa3625b32022-07-29 12:41:40 +0530252 ),
Dany Robertf34ffc22023-11-20 11:10:56 +0000253 **get_fetch_values(doctype, "billing_address", party_details.company_address),
Sagar Voraa3625b32022-07-29 12:41:40 +0530254 )
255
256 # shipping address - if not already set
257 if not party_details.shipping_address:
258 party_details.update(
259 shipping_address=party_details.billing_address,
260 shipping_address_display=party_details.billing_address_display,
Dany Robertf34ffc22023-11-20 11:10:56 +0000261 **get_fetch_values(doctype, "shipping_address", party_details.billing_address),
Sagar Voraa3625b32022-07-29 12:41:40 +0530262 )
263
Sagar Vora5c066202023-03-13 14:02:50 +0000264 party_address, shipping_address = (
265 party_details.get(billing_address_field),
266 party_details.shipping_address_name,
267 )
268
269 party_details["tax_category"] = get_address_tax_category(
270 party.get("tax_category"),
271 party_address,
272 shipping_address if party_type != "Supplier" else party_address,
273 )
274
275 if doctype in TRANSACTION_TYPES:
Sagar Vora4205f562023-07-24 18:37:36 +0530276 with temporary_flag("company", company):
277 get_regional_address_details(party_details, doctype, company)
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530278
Sagar Vora5c066202023-03-13 14:02:50 +0000279 return party_address, shipping_address
Saif Ur Rehman67786682018-12-27 02:11:07 +0500280
Ankush Menat494bd9e2022-03-28 18:52:46 +0530281
Shreya Shah4fa600a2018-06-05 11:27:53 +0530282@erpnext.allow_regional
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530283def get_regional_address_details(party_details, doctype, company):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530284 pass
Anand Doshi13ae5482014-04-10 18:40:57 +0530285
Ankush Menat494bd9e2022-03-28 18:52:46 +0530286
Deepesh Gargcf9347d2020-03-31 17:28:43 +0530287def set_contact_details(party_details, party, party_type):
288 party_details.contact_person = get_default_contact(party_type, party.name)
Anand Doshi13ae5482014-04-10 18:40:57 +0530289
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530290 if not party_details.contact_person:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530291 party_details.update(
292 {
293 "contact_person": None,
294 "contact_display": None,
295 "contact_email": None,
296 "contact_mobile": None,
297 "contact_phone": None,
298 "contact_designation": None,
299 "contact_department": None,
300 }
301 )
Neil Trini Lasradofe2ffae2015-07-08 18:16:51 +0530302 else:
rohitwaghchaure2851a412023-10-18 16:31:35 +0530303 fields = [
304 "name as contact_person",
305 "full_name as contact_display",
306 "email_id as contact_email",
307 "mobile_no as contact_mobile",
308 "phone as contact_phone",
309 "designation as contact_designation",
310 "department as contact_department",
311 ]
312
313 contact_details = frappe.db.get_value(
314 "Contact", party_details.contact_person, fields, as_dict=True
315 )
316
317 party_details.update(contact_details)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530318
Ankush Menat494bd9e2022-03-28 18:52:46 +0530319
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530320def set_other_values(party_details, party, party_type):
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530321 # copy
ChillarAnand9ace7d62022-03-07 16:53:59 +0530322 if party_type == "Customer":
saurabh8e499512016-02-19 11:08:45 +0530323 to_copy = ["customer_name", "customer_group", "territory", "language"]
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530324 else:
Zlash6589070782018-04-19 18:37:29 +0530325 to_copy = ["supplier_name", "supplier_group", "language"]
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530326 for f in to_copy:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530327 party_details[f] = party.get(f)
Anand Doshi13ae5482014-04-10 18:40:57 +0530328
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530329 # fields prepended with default in Customer doctype
Ankush Menat494bd9e2022-03-28 18:52:46 +0530330 for f in ["currency"] + (
331 ["sales_partner", "commission_rate"] if party_type == "Customer" else []
332 ):
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530333 if party.get("default_" + f):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530334 party_details[f] = party.get("default_" + f)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530335
Ankush Menat494bd9e2022-03-28 18:52:46 +0530336
Rushabh Mehta72fbf902015-09-17 18:29:44 +0530337def get_default_price_list(party):
338 """Return default price list for party (Document object)"""
Nabin Hait34c551d2019-07-03 10:34:31 +0530339 if party.get("default_price_list"):
Rushabh Mehta72fbf902015-09-17 18:29:44 +0530340 return party.default_price_list
341
342 if party.doctype == "Customer":
Daizy Modi27df4552022-11-03 13:38:48 +0530343 return frappe.get_cached_value("Customer Group", party.customer_group, "default_price_list")
Rushabh Mehta72fbf902015-09-17 18:29:44 +0530344
Rushabh Mehta72fbf902015-09-17 18:29:44 +0530345
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530346def set_price_list(party_details, party, party_type, given_price_list, pos=None):
Anand Doshi13ae5482014-04-10 18:40:57 +0530347 # price list
Ankush Menat494bd9e2022-03-28 18:52:46 +0530348 price_list = get_permitted_documents("Price List")
rohitwaghchaure52107612020-05-05 12:12:33 +0530349
Faris Ansari64f01bd2020-04-14 11:51:48 +0530350 # if there is only one permitted document based on user permissions, set it
351 if price_list and len(price_list) == 1:
Suraj Shettydcc90e32018-05-04 17:52:57 +0530352 price_list = price_list[0]
Ankush Menat494bd9e2022-03-28 18:52:46 +0530353 elif pos and party_type == "Customer":
354 customer_price_list = frappe.get_value("Customer", party.name, "default_price_list")
deepeshgarg007c48efab2019-01-24 17:15:38 +0530355
356 if customer_price_list:
357 price_list = customer_price_list
358 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530359 pos_price_list = frappe.get_value("POS Profile", pos, "selling_price_list")
deepeshgarg0071f9a6fe2019-01-25 11:53:55 +0530360 price_list = pos_price_list or given_price_list
Suraj Shettydcc90e32018-05-04 17:52:57 +0530361 else:
362 price_list = get_default_price_list(party) or given_price_list
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530363
364 if price_list:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530365 party_details.price_list_currency = frappe.db.get_value(
366 "Price List", price_list, "currency", cache=True
367 )
Anand Doshi13ae5482014-04-10 18:40:57 +0530368
Ankush Menat494bd9e2022-03-28 18:52:46 +0530369 party_details[
370 "selling_price_list" if party.doctype == "Customer" else "buying_price_list"
371 ] = price_list
Anand Doshi13ae5482014-04-10 18:40:57 +0530372
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530373
Ankush Menat494bd9e2022-03-28 18:52:46 +0530374def set_account_and_due_date(
375 party, account, party_type, company, posting_date, bill_date, doctype
376):
Saqiba6f98d42020-07-23 18:51:26 +0530377 if doctype not in ["POS Invoice", "Sales Invoice", "Purchase Invoice"]:
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530378 # not an invoice
Ankush Menat494bd9e2022-03-28 18:52:46 +0530379 return {party_type.lower(): party}
Anand Doshi13ae5482014-04-10 18:40:57 +0530380
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530381 if party:
Anand Doshib20baf82015-09-25 16:17:50 +0530382 account = get_party_account(party_type, party, company)
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530383
Ankush Menat494bd9e2022-03-28 18:52:46 +0530384 account_fieldname = "debit_to" if party_type == "Customer" else "credit_to"
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530385 out = {
386 party_type.lower(): party,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530387 account_fieldname: account,
388 "due_date": get_due_date(posting_date, party_type, party, company, bill_date),
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530389 }
Shreya Shah3a9eec22018-02-16 13:05:21 +0530390
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530391 return out
Rushabh Mehta361df892015-09-18 12:59:51 +0530392
Ankush Menat494bd9e2022-03-28 18:52:46 +0530393
Nabin Haitdb030d12014-09-10 17:11:30 +0530394@frappe.whitelist()
Gursheen Anand7591f102023-06-12 11:06:03 +0530395def get_party_account(party_type, party=None, company=None, include_advance=False):
Rushabh Mehta364054a2015-02-21 14:39:35 +0530396 """Returns the account for the given `party`.
Ankush Menat494bd9e2022-03-28 18:52:46 +0530397 Will first search in party (Customer / Supplier) record, if not found,
398 will search in group (Customer Group / Supplier Group),
399 finally will return default."""
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530400 if not company:
Anand Doshib20baf82015-09-25 16:17:50 +0530401 frappe.throw(_("Please select a Company"))
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530402
Ankush Menat494bd9e2022-03-28 18:52:46 +0530403 if not party and party_type in ["Customer", "Supplier"]:
404 default_account_name = (
405 "default_receivable_account" if party_type == "Customer" else "default_payable_account"
406 )
Deepesh Garg88648572021-11-12 12:39:30 +0530407
Ankush Menat494bd9e2022-03-28 18:52:46 +0530408 return frappe.get_cached_value("Company", company, default_account_name)
Saurabh0f86d862017-11-10 19:21:09 +0530409
Ankush Menat494bd9e2022-03-28 18:52:46 +0530410 account = frappe.db.get_value(
411 "Party Account", {"parenttype": party_type, "parent": party, "company": company}, "account"
412 )
Saurabh0f86d862017-11-10 19:21:09 +0530413
Ankush Menat494bd9e2022-03-28 18:52:46 +0530414 if not account and party_type in ["Customer", "Supplier"]:
415 party_group_doctype = "Customer Group" if party_type == "Customer" else "Supplier Group"
Nabin Hait9a33bc62018-08-09 10:47:09 +0530416 group = frappe.get_cached_value(party_type, party, scrub(party_group_doctype))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530417 account = frappe.db.get_value(
418 "Party Account",
419 {"parenttype": party_group_doctype, "parent": group, "company": company},
420 "account",
421 )
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530422
Ankush Menat494bd9e2022-03-28 18:52:46 +0530423 if not account and party_type in ["Customer", "Supplier"]:
424 default_account_name = (
425 "default_receivable_account" if party_type == "Customer" else "default_payable_account"
426 )
427 account = frappe.get_cached_value("Company", company, default_account_name)
Rushabh Mehta364054a2015-02-21 14:39:35 +0530428
Saurabh0f86d862017-11-10 19:21:09 +0530429 existing_gle_currency = get_party_gle_currency(party_type, party, company)
430 if existing_gle_currency:
431 if account:
Daizy Modi010bd9c2022-11-03 14:36:48 +0530432 account_currency = frappe.get_cached_value("Account", account, "account_currency")
Saurabh0f86d862017-11-10 19:21:09 +0530433 if (account and account_currency != existing_gle_currency) or not account:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530434 account = get_party_gle_account(party_type, party, company)
Rushabh Mehtab92087c2017-01-13 18:53:11 +0530435
RitvikSardanad2f03c82023-09-05 12:00:54 +0530436 if include_advance and party_type in ["Customer", "Supplier", "Student"]:
Gursheen Anand7591f102023-06-12 11:06:03 +0530437 advance_account = get_party_advance_account(party_type, party, company)
Deepesh Garg92f845c2023-06-21 12:21:19 +0530438 if advance_account:
439 return [account, advance_account]
440 else:
441 return [account]
442
Saurabh0f86d862017-11-10 19:21:09 +0530443 return account
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530444
Ankush Menat494bd9e2022-03-28 18:52:46 +0530445
Gursheen Anand74619262023-06-02 17:13:51 +0530446def get_party_advance_account(party_type, party, company):
Gursheen Anand74619262023-06-02 17:13:51 +0530447 account = frappe.db.get_value(
Gursheen Anand4ee16372023-06-08 13:15:23 +0530448 "Party Account",
449 {"parenttype": party_type, "parent": party, "company": company},
450 "advance_account",
Gursheen Anand74619262023-06-02 17:13:51 +0530451 )
452
453 if not account:
454 party_group_doctype = "Customer Group" if party_type == "Customer" else "Supplier Group"
455 group = frappe.get_cached_value(party_type, party, scrub(party_group_doctype))
456 account = frappe.db.get_value(
457 "Party Account",
458 {"parenttype": party_group_doctype, "parent": group, "company": company},
Gursheen Anand4ee16372023-06-08 13:15:23 +0530459 "advance_account",
Gursheen Anand74619262023-06-02 17:13:51 +0530460 )
Gursheen Anand4ee16372023-06-08 13:15:23 +0530461
Gursheen Anand74619262023-06-02 17:13:51 +0530462 if not account:
Gursheen Ananda06017c2023-06-12 15:24:53 +0530463 account_name = (
464 "default_advance_received_account"
465 if party_type == "Customer"
466 else "default_advance_paid_account"
467 )
468 account = frappe.get_cached_value("Company", company, account_name)
Gursheen Anand74619262023-06-02 17:13:51 +0530469
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530470 return account
Anand Doshib20baf82015-09-25 16:17:50 +0530471
472
rohitwaghchaure713cfc72018-09-11 17:40:37 +0530473@frappe.whitelist()
474def get_party_bank_account(party_type, party):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530475 return frappe.db.get_value(
476 "Bank Account", {"party_type": party_type, "party": party, "is_default": 1}
477 )
478
rohitwaghchaure713cfc72018-09-11 17:40:37 +0530479
Anand Doshib20baf82015-09-25 16:17:50 +0530480def get_party_account_currency(party_type, party, company):
481 def generator():
482 party_account = get_party_account(party_type, party, company)
Daizy Modi010bd9c2022-11-03 14:36:48 +0530483 return frappe.get_cached_value("Account", party_account, "account_currency")
Anand Doshib20baf82015-09-25 16:17:50 +0530484
485 return frappe.local_cache("party_account_currency", (party_type, party, company), generator)
486
Ankush Menat494bd9e2022-03-28 18:52:46 +0530487
Anand Doshi4945b942015-09-30 16:41:15 +0530488def get_party_gle_currency(party_type, party, company):
489 def generator():
ruthra kumar8d9b90f2023-10-27 12:37:37 +0530490 gl = qb.DocType("GL Entry")
491 existing_gle_currency = (
492 qb.from_(gl)
493 .select(gl.account_currency)
494 .where(
495 (gl.docstatus == 1)
496 & (gl.company == company)
497 & (gl.party_type == party_type)
498 & (gl.party == party)
499 & (gl.is_cancelled == 0)
500 )
501 .limit(1)
502 .run()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530503 )
Anand Doshi4945b942015-09-30 16:41:15 +0530504
505 return existing_gle_currency[0][0] if existing_gle_currency else None
506
Ankush Menat494bd9e2022-03-28 18:52:46 +0530507 return frappe.local_cache(
508 "party_gle_currency", (party_type, party, company), generator, regenerate_if_none=True
509 )
510
Rushabh Mehtab92087c2017-01-13 18:53:11 +0530511
Nabin Hait16d69592016-06-28 16:15:58 +0530512def get_party_gle_account(party_type, party, company):
513 def generator():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530514 existing_gle_account = frappe.db.sql(
515 """select account from `tabGL Entry`
Nabin Hait16d69592016-06-28 16:15:58 +0530516 where docstatus=1 and company=%(company)s and party_type=%(party_type)s and party=%(party)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530517 limit 1""",
518 {"company": company, "party_type": party_type, "party": party},
519 )
Nabin Hait16d69592016-06-28 16:15:58 +0530520
521 return existing_gle_account[0][0] if existing_gle_account else None
522
Ankush Menat494bd9e2022-03-28 18:52:46 +0530523 return frappe.local_cache(
524 "party_gle_account", (party_type, party, company), generator, regenerate_if_none=True
525 )
526
Anand Doshi4945b942015-09-30 16:41:15 +0530527
Anand Doshid8bc40d2015-10-22 17:54:50 +0530528def validate_party_gle_currency(party_type, party, company, party_account_currency=None):
Anand Doshi4945b942015-09-30 16:41:15 +0530529 """Validate party account currency with existing GL Entry's currency"""
Anand Doshid8bc40d2015-10-22 17:54:50 +0530530 if not party_account_currency:
531 party_account_currency = get_party_account_currency(party_type, party, company)
532
Anand Doshi4945b942015-09-30 16:41:15 +0530533 existing_gle_currency = get_party_gle_currency(party_type, party, company)
534
535 if existing_gle_currency and party_account_currency != existing_gle_currency:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530536 frappe.throw(
537 _(
538 "{0} {1} has accounting entries in currency {2} for company {3}. Please select a receivable or payable account with currency {2}."
539 ).format(
540 frappe.bold(party_type),
541 frappe.bold(party),
542 frappe.bold(existing_gle_currency),
543 frappe.bold(company),
544 ),
545 InvalidAccountCurrency,
546 )
547
Anand Doshi4945b942015-09-30 16:41:15 +0530548
Anand Doshida98ab62015-09-28 15:13:38 +0530549def validate_party_accounts(doc):
Deepesh Garg5a2b5712022-02-18 20:05:49 +0530550 from erpnext.controllers.accounts_controller import validate_account_head
Ankush Menat494bd9e2022-03-28 18:52:46 +0530551
Anand Doshida98ab62015-09-28 15:13:38 +0530552 companies = []
553
554 for account in doc.get("accounts"):
555 if account.company in companies:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530556 frappe.throw(
557 _("There can only be 1 Account per Company in {0} {1}").format(doc.doctype, doc.name),
558 DuplicatePartyAccountError,
559 )
Anand Doshida98ab62015-09-28 15:13:38 +0530560 else:
561 companies.append(account.company)
Anand Doshid8bc40d2015-10-22 17:54:50 +0530562
Daizy Modi010bd9c2022-11-03 14:36:48 +0530563 party_account_currency = frappe.get_cached_value("Account", account.account, "account_currency")
hendrikc257ce82019-09-05 16:44:09 +0700564 if frappe.db.get_default("Company"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530565 company_default_currency = frappe.get_cached_value(
566 "Company", frappe.db.get_default("Company"), "default_currency"
567 )
hendrikc257ce82019-09-05 16:44:09 +0700568 else:
Daizy Modi27df4552022-11-03 13:38:48 +0530569 company_default_currency = frappe.get_cached_value(
570 "Company", account.company, "default_currency"
571 )
Anand Doshid8bc40d2015-10-22 17:54:50 +0530572
Deepesh Garg1a2cf5c2020-03-28 21:26:16 +0530573 validate_party_gle_currency(doc.doctype, doc.name, account.company, party_account_currency)
Anand Doshida98ab62015-09-28 15:13:38 +0530574
rohitwaghchaureea092a72017-02-01 12:02:08 +0530575 if doc.get("default_currency") and party_account_currency and company_default_currency:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530576 if (
577 doc.default_currency != party_account_currency
578 and doc.default_currency != company_default_currency
579 ):
580 frappe.throw(
581 _(
582 "Billing currency must be equal to either default company's currency or party account currency"
583 )
584 )
tunde3b4bd372017-08-31 16:28:47 +0100585
Deepesh Garg5a2b5712022-02-18 20:05:49 +0530586 # validate if account is mapped for same company
Gursheen Anand74619262023-06-02 17:13:51 +0530587 if account.account:
588 validate_account_head(account.idx, account.account, account.company)
589 if account.advance_account:
590 validate_account_head(account.idx, account.advance_account, account.company)
Deepesh Garg5a2b5712022-02-18 20:05:49 +0530591
rohitwaghchaure62fea032016-03-30 13:24:42 +0530592
Nabin Hait4770a1a2015-07-09 16:35:46 +0530593@frappe.whitelist()
Shreya Shah3a9eec22018-02-16 13:05:21 +0530594def get_due_date(posting_date, party_type, party, company=None, bill_date=None):
tunde3b4bd372017-08-31 16:28:47 +0100595 """Get due date from `Payment Terms Template`"""
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530596 due_date = None
Shreya Shah3a9eec22018-02-16 13:05:21 +0530597 if (bill_date or posting_date) and party:
598 due_date = bill_date or posting_date
marinationfa085d72020-10-27 13:18:30 +0530599 template_name = get_payment_terms_template(party, party_type, company)
rohitwaghchaure3ffe8962018-07-13 17:40:48 +0530600
tunde3b4bd372017-08-31 16:28:47 +0100601 if template_name:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530602 due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime(
603 "%Y-%m-%d"
604 )
tundeed86efb2017-09-05 01:15:31 +0100605 else:
606 if party_type == "Supplier":
Nabin Hait9a33bc62018-08-09 10:47:09 +0530607 supplier_group = frappe.get_cached_value(party_type, party, "supplier_group")
608 template_name = frappe.get_cached_value("Supplier Group", supplier_group, "payment_terms")
tundee5973e42017-09-05 18:11:58 +0100609 if template_name:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530610 due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime(
611 "%Y-%m-%d"
612 )
Shreya Shah3a9eec22018-02-16 13:05:21 +0530613 # If due date is calculated from bill_date, check this condition
614 if getdate(due_date) < getdate(posting_date):
615 due_date = posting_date
Anand Doshi13ae5482014-04-10 18:40:57 +0530616 return due_date
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530617
Ankush Menat494bd9e2022-03-28 18:52:46 +0530618
Shreya Shah3a9eec22018-02-16 13:05:21 +0530619def get_due_date_from_template(template_name, posting_date, bill_date):
tunde3b4bd372017-08-31 16:28:47 +0100620 """
621 Inspects all `Payment Term`s from the a `Payment Terms Template` and returns the due
622 date after considering all the `Payment Term`s requirements.
623 :param template_name: Name of the `Payment Terms Template`
624 :return: String representing the calculated due date
625 """
Shreya Shah3a9eec22018-02-16 13:05:21 +0530626 due_date = getdate(bill_date or posting_date)
627
Ankush Menat494bd9e2022-03-28 18:52:46 +0530628 template = frappe.get_doc("Payment Terms Template", template_name)
tunde3b4bd372017-08-31 16:28:47 +0100629
630 for term in template.terms:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530631 if term.due_date_based_on == "Day(s) after invoice date":
tunde3b4bd372017-08-31 16:28:47 +0100632 due_date = max(due_date, add_days(due_date, term.credit_days))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530633 elif term.due_date_based_on == "Day(s) after the end of the invoice month":
tunde3b4bd372017-08-31 16:28:47 +0100634 due_date = max(due_date, add_days(get_last_day(due_date), term.credit_days))
635 else:
developsessionsce8a1082023-02-03 11:30:29 +0100636 due_date = max(due_date, get_last_day(add_months(due_date, term.credit_months)))
tunde3b4bd372017-08-31 16:28:47 +0100637 return due_date
638
Ankush Menat494bd9e2022-03-28 18:52:46 +0530639
640def validate_due_date(
641 posting_date, due_date, party_type, party, company=None, bill_date=None, template_name=None
642):
Nabin Hait4770a1a2015-07-09 16:35:46 +0530643 if getdate(due_date) < getdate(posting_date):
Rohit Waghchaured1a85a32018-11-26 18:42:29 +0530644 frappe.throw(_("Due Date cannot be before Posting / Supplier Invoice Date"))
Nabin Hait4770a1a2015-07-09 16:35:46 +0530645 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530646 if not template_name:
647 return
rohitwaghchaure3ffe8962018-07-13 17:40:48 +0530648
Ankush Menat494bd9e2022-03-28 18:52:46 +0530649 default_due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime(
650 "%Y-%m-%d"
651 )
Saurabhd7897f12018-07-18 17:08:16 +0530652
Anand Doshi0ca587e2015-09-25 16:32:14 +0530653 if not default_due_date:
654 return
655
Nabin Hait93d3c822015-07-10 17:11:58 +0530656 if default_due_date != posting_date and getdate(due_date) > getdate(default_due_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530657 is_credit_controller = (
658 frappe.db.get_single_value("Accounts Settings", "credit_controller") in frappe.get_roles()
659 )
Nabin Hait4770a1a2015-07-09 16:35:46 +0530660 if is_credit_controller:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530661 msgprint(
662 _("Note: Due / Reference Date exceeds allowed customer credit days by {0} day(s)").format(
663 date_diff(due_date, default_due_date)
664 )
665 )
Nabin Hait4770a1a2015-07-09 16:35:46 +0530666 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530667 frappe.throw(
668 _("Due / Reference Date cannot be after {0}").format(formatdate(default_due_date))
669 )
670
Rushabh Mehta361df892015-09-18 12:59:51 +0530671
Neil Trini Lasrado09f9c962015-08-26 10:41:31 +0530672@frappe.whitelist()
Nabin Hait16a7ec92019-09-05 13:01:15 +0530673def get_address_tax_category(tax_category=None, billing_address=None, shipping_address=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530674 addr_tax_category_from = frappe.db.get_single_value(
675 "Accounts Settings", "determine_address_tax_category_from"
676 )
Saif Ur Rehmanfd531a62018-12-29 01:49:11 +0500677 if addr_tax_category_from == "Shipping Address":
678 if shipping_address:
679 tax_category = frappe.db.get_value("Address", shipping_address, "tax_category") or tax_category
680 else:
681 if billing_address:
682 tax_category = frappe.db.get_value("Address", billing_address, "tax_category") or tax_category
683
684 return cstr(tax_category)
Saif Ur Rehman67786682018-12-27 02:11:07 +0500685
Ankush Menat494bd9e2022-03-28 18:52:46 +0530686
Neil Trini Lasrado09f9c962015-08-26 10:41:31 +0530687@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530688def set_taxes(
689 party,
690 party_type,
691 posting_date,
692 company,
693 customer_group=None,
694 supplier_group=None,
695 tax_category=None,
696 billing_address=None,
697 shipping_address=None,
698 use_for_shopping_cart=None,
699):
Chillar Anand915b3432021-09-02 16:44:59 +0530700 from erpnext.accounts.doctype.tax_rule.tax_rule import get_party_details, get_tax_template
Ankush Menat494bd9e2022-03-28 18:52:46 +0530701
702 args = {party_type.lower(): party, "company": company}
Rushabh Mehta361df892015-09-18 12:59:51 +0530703
Saif Ur Rehman67786682018-12-27 02:11:07 +0500704 if tax_category:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530705 args["tax_category"] = tax_category
Saif Ur Rehman67786682018-12-27 02:11:07 +0500706
Rushabh Mehta3c14c5a2017-09-29 13:21:22 +0530707 if customer_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530708 args["customer_group"] = customer_group
Rushabh Mehta3c14c5a2017-09-29 13:21:22 +0530709
Zlash6589070782018-04-19 18:37:29 +0530710 if supplier_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530711 args["supplier_group"] = supplier_group
Rushabh Mehta3c14c5a2017-09-29 13:21:22 +0530712
Neil Trini Lasrado09f9c962015-08-26 10:41:31 +0530713 if billing_address or shipping_address:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530714 args.update(
715 get_party_details(
716 party, party_type, {"billing_address": billing_address, "shipping_address": shipping_address}
717 )
718 )
Neil Trini Lasrado09f9c962015-08-26 10:41:31 +0530719 else:
720 args.update(get_party_details(party, party_type))
Rushabh Mehta361df892015-09-18 12:59:51 +0530721
Nabin Hait47ce6de2023-06-06 15:19:04 +0530722 if party_type in ("Customer", "Lead", "Prospect"):
Neil Trini Lasrado810bd352015-08-21 15:04:57 +0530723 args.update({"tax_type": "Sales"})
Anand Doshi2f957f22016-04-08 17:36:10 +0530724
Nabin Hait47ce6de2023-06-06 15:19:04 +0530725 if party_type in ["Lead", "Prospect"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530726 args["customer"] = None
Nabin Hait47ce6de2023-06-06 15:19:04 +0530727 del args[frappe.scrub(party_type)]
Neil Trini Lasrado810bd352015-08-21 15:04:57 +0530728 else:
729 args.update({"tax_type": "Purchase"})
Rushabh Mehta361df892015-09-18 12:59:51 +0530730
Saurabh957e7a32015-09-11 15:44:06 +0530731 if use_for_shopping_cart:
Saurabh957e7a32015-09-11 15:44:06 +0530732 args.update({"use_for_shopping_cart": use_for_shopping_cart})
Rushabh Mehta361df892015-09-18 12:59:51 +0530733
734 return get_tax_template(posting_date, args)
shreyas29b565f2016-01-25 17:30:49 +0530735
tunde400d0462017-08-31 13:44:57 +0100736
737@frappe.whitelist()
marinationfa085d72020-10-27 13:18:30 +0530738def get_payment_terms_template(party_name, party_type, company=None):
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530739 if party_type not in ("Customer", "Supplier"):
740 return
tunde400d0462017-08-31 13:44:57 +0100741 template = None
Deepesh Garg5b6a9fc2023-06-17 13:08:18 +0530742
Ankush Menat494bd9e2022-03-28 18:52:46 +0530743 if party_type == "Customer":
744 customer = frappe.get_cached_value(
745 "Customer", party_name, fieldname=["payment_terms", "customer_group"], as_dict=1
746 )
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530747 template = customer.payment_terms
748
749 if not template and customer.customer_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530750 template = frappe.get_cached_value("Customer Group", customer.customer_group, "payment_terms")
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530751 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530752 supplier = frappe.get_cached_value(
753 "Supplier", party_name, fieldname=["payment_terms", "supplier_group"], as_dict=1
754 )
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530755 template = supplier.payment_terms
Zlash6589070782018-04-19 18:37:29 +0530756 if not template and supplier.supplier_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530757 template = frappe.get_cached_value("Supplier Group", supplier.supplier_group, "payment_terms")
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530758
759 if not template and company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530760 template = frappe.get_cached_value("Company", company, fieldname="payment_terms")
tunde400d0462017-08-31 13:44:57 +0100761 return template
762
Ankush Menat494bd9e2022-03-28 18:52:46 +0530763
shreyaseba9ca42016-01-26 14:56:52 +0530764def validate_party_frozen_disabled(party_type, party_name):
Subin Tomb8845b92021-07-30 16:30:18 +0530765
766 if frappe.flags.ignore_party_validation:
767 return
768
shreyas79872bf2016-01-26 13:57:06 +0530769 if party_type and party_name:
KanchanChauhanfbaa6192017-01-30 15:15:58 +0530770 if party_type in ("Customer", "Supplier"):
Nabin Hait9a33bc62018-08-09 10:47:09 +0530771 party = frappe.get_cached_value(party_type, party_name, ["is_frozen", "disabled"], as_dict=True)
deepeshgarg007737ec6b2019-10-20 17:36:36 +0530772 if party.disabled:
773 frappe.throw(_("{0} {1} is disabled").format(party_type, party_name), PartyDisabled)
774 elif party.get("is_frozen"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530775 frozen_accounts_modifier = frappe.db.get_single_value(
776 "Accounts Settings", "frozen_accounts_modifier"
777 )
KanchanChauhanfbaa6192017-01-30 15:15:58 +0530778 if not frozen_accounts_modifier in frappe.get_roles():
779 frappe.throw(_("{0} {1} is frozen").format(party_type, party_name), PartyFrozen)
780
781 elif party_type == "Employee":
Rucha Mahabala38147a2021-06-12 13:33:21 +0530782 if frappe.db.get_value("Employee", party_name, "status") != "Active":
Kanchan Chauhan95108ac2017-04-11 15:55:34 +0530783 frappe.msgprint(_("{0} {1} is not active").format(party_type, party_name), alert=True)
Rushabh Mehta15a7f212016-04-14 17:30:40 +0530784
Ankush Menat494bd9e2022-03-28 18:52:46 +0530785
Rushabh Mehta15a7f212016-04-14 17:30:40 +0530786def get_timeline_data(doctype, name):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530787 """returns timeline data for the past one year"""
Rushabh Mehta15a7f212016-04-14 17:30:40 +0530788 from frappe.desk.form.load import get_communication_data
mbauskare7b87ad2017-02-16 13:12:29 +0530789
790 out = {}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530791 fields = "creation, count(*)"
792 after = add_years(None, -1).strftime("%Y-%m-%d")
793 group_by = "group by Date(creation)"
Zarrar58200182018-05-30 11:56:23 +0530794
Ankush Menat494bd9e2022-03-28 18:52:46 +0530795 data = get_communication_data(
796 doctype,
797 name,
798 after=after,
799 group_by="group by creation",
800 fields="C.creation as creation, count(C.name)",
801 as_dict=False,
802 )
Zarrar58200182018-05-30 11:56:23 +0530803
804 # fetch and append data from Activity Log
Ankush Menat494bd9e2022-03-28 18:52:46 +0530805 data += frappe.db.sql(
806 """select {fields}
Zarrar58200182018-05-30 11:56:23 +0530807 from `tabActivity Log`
rohitwaghchaure52107612020-05-05 12:12:33 +0530808 where (reference_doctype=%(doctype)s and reference_name=%(name)s)
809 or (timeline_doctype in (%(doctype)s) and timeline_name=%(name)s)
810 or (reference_doctype in ("Quotation", "Opportunity") and timeline_name=%(name)s)
Zarrar58200182018-05-30 11:56:23 +0530811 and status!='Success' and creation > {after}
812 {group_by} order by creation desc
Ankush Menat494bd9e2022-03-28 18:52:46 +0530813 """.format(
814 fields=fields, group_by=group_by, after=after
815 ),
816 {"doctype": doctype, "name": name},
817 as_dict=False,
818 )
mbauskare7b87ad2017-02-16 13:12:29 +0530819
820 timeline_items = dict(data)
821
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530822 for date, count in timeline_items.items():
mbauskare7b87ad2017-02-16 13:12:29 +0530823 timestamp = get_timestamp(date)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530824 out.update({timestamp: count})
mbauskare7b87ad2017-02-16 13:12:29 +0530825
Nabin Hait2d79a642017-05-24 12:41:14 +0530826 return out
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530827
Ankush Menat494bd9e2022-03-28 18:52:46 +0530828
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530829def get_dashboard_info(party_type, party, loyalty_program=None):
Nabin Hait2d79a642017-05-24 12:41:14 +0530830 current_fiscal_year = get_fiscal_year(nowdate(), as_dict=True)
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530831
Ankush Menat494bd9e2022-03-28 18:52:46 +0530832 doctype = "Sales Invoice" if party_type == "Customer" else "Purchase Invoice"
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530833
Ankush Menat494bd9e2022-03-28 18:52:46 +0530834 companies = frappe.get_all(
835 doctype, filters={"docstatus": 1, party_type.lower(): party}, distinct=1, fields=["company"]
836 )
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530837
deepeshgarg007920dc142018-11-23 10:17:28 +0530838 company_wise_info = []
839
Ankush Menat494bd9e2022-03-28 18:52:46 +0530840 company_wise_grand_total = frappe.get_all(
841 doctype,
deepeshgarg007ee05e352018-11-29 16:24:28 +0530842 filters={
Ankush Menat494bd9e2022-03-28 18:52:46 +0530843 "docstatus": 1,
deepeshgarg007ee05e352018-11-29 16:24:28 +0530844 party_type.lower(): party,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530845 "posting_date": (
846 "between",
847 [current_fiscal_year.year_start_date, current_fiscal_year.year_end_date],
848 ),
849 },
850 group_by="company",
851 fields=[
852 "company",
853 "sum(grand_total) as grand_total",
854 "sum(base_grand_total) as base_grand_total",
855 ],
856 )
deepeshgarg007920dc142018-11-23 10:17:28 +0530857
deepeshgarg007a1d015c2018-12-26 11:01:02 +0530858 loyalty_point_details = []
859
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530860 if party_type == "Customer":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530861 loyalty_point_details = frappe._dict(
862 frappe.get_all(
863 "Loyalty Point Entry",
864 filters={
865 "customer": party,
866 "expiry_date": (">=", getdate()),
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530867 },
868 group_by="company",
869 fields=["company", "sum(loyalty_points) as loyalty_points"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530870 as_list=1,
871 )
872 )
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530873
deepeshgarg007f31caff2018-11-27 15:04:12 +0530874 company_wise_billing_this_year = frappe._dict()
875
876 for d in company_wise_grand_total:
877 company_wise_billing_this_year.setdefault(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530878 d.company, {"grand_total": d.grand_total, "base_grand_total": d.base_grand_total}
879 )
deepeshgarg007f31caff2018-11-27 15:04:12 +0530880
Ankush Menat494bd9e2022-03-28 18:52:46 +0530881 company_wise_total_unpaid = frappe._dict(
882 frappe.db.sql(
883 """
deepeshgarg007920dc142018-11-23 10:17:28 +0530884 select company, sum(debit_in_account_currency) - sum(credit_in_account_currency)
Nabin Hait24f0b132017-05-24 13:01:26 +0530885 from `tabGL Entry`
deepeshgarg007920dc142018-11-23 10:17:28 +0530886 where party_type = %s and party=%s
Deepesh Garg802e63a2021-06-28 11:24:32 +0530887 and is_cancelled = 0
Ankush Menat494bd9e2022-03-28 18:52:46 +0530888 group by company""",
889 (party_type, party),
890 )
891 )
Nabin Hait2d79a642017-05-24 12:41:14 +0530892
deepeshgarg007920dc142018-11-23 10:17:28 +0530893 for d in companies:
Daizy Modi27df4552022-11-03 13:38:48 +0530894 company_default_currency = frappe.get_cached_value("Company", d.company, "default_currency")
deepeshgarg007920dc142018-11-23 10:17:28 +0530895 party_account_currency = get_party_account_currency(party_type, party, d.company)
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530896
Ankush Menat494bd9e2022-03-28 18:52:46 +0530897 if party_account_currency == company_default_currency:
898 billing_this_year = flt(
899 company_wise_billing_this_year.get(d.company, {}).get("base_grand_total")
900 )
deepeshgarg007920dc142018-11-23 10:17:28 +0530901 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530902 billing_this_year = flt(company_wise_billing_this_year.get(d.company, {}).get("grand_total"))
deepeshgarg007920dc142018-11-23 10:17:28 +0530903
904 total_unpaid = flt(company_wise_total_unpaid.get(d.company))
905
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530906 if loyalty_point_details:
907 loyalty_points = loyalty_point_details.get(d.company)
908
deepeshgarg007920dc142018-11-23 10:17:28 +0530909 info = {}
910 info["billing_this_year"] = flt(billing_this_year) if billing_this_year else 0
911 info["currency"] = party_account_currency
912 info["total_unpaid"] = flt(total_unpaid) if total_unpaid else 0
913 info["company"] = d.company
914
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530915 if party_type == "Customer" and loyalty_point_details:
916 info["loyalty_points"] = loyalty_points
917
deepeshgarg007920dc142018-11-23 10:17:28 +0530918 if party_type == "Supplier":
919 info["total_unpaid"] = -1 * info["total_unpaid"]
920
921 company_wise_info.append(info)
922
923 return company_wise_info
tundebabzy40a02762017-10-25 07:54:34 +0100924
Ankush Menat494bd9e2022-03-28 18:52:46 +0530925
Raffael Meyerb91bb172023-06-08 16:19:09 +0200926def get_party_shipping_address(doctype: str, name: str) -> Optional[str]:
tundebabzy40a02762017-10-25 07:54:34 +0100927 """
928 Returns an Address name (best guess) for the given doctype and name for which `address_type == 'Shipping'` is true.
929 and/or `is_shipping_address = 1`.
930
931 It returns an empty string if there is no matching record.
932
933 :param doctype: Party Doctype
934 :param name: Party name
935 :return: String
936 """
Raffael Meyerb91bb172023-06-08 16:19:09 +0200937 shipping_addresses = frappe.get_all(
938 "Address",
939 filters=[
940 ["Dynamic Link", "link_doctype", "=", doctype],
941 ["Dynamic Link", "link_name", "=", name],
942 ["disabled", "=", 0],
943 ],
944 or_filters=[
945 ["is_shipping_address", "=", 1],
946 ["address_type", "=", "Shipping"],
947 ],
948 pluck="name",
949 limit=1,
950 order_by="is_shipping_address DESC",
tundebabzy40a02762017-10-25 07:54:34 +0100951 )
Raffael Meyerb91bb172023-06-08 16:19:09 +0200952
953 return shipping_addresses[0] if shipping_addresses else None
Rohit Waghchaureaffeb3d2019-01-15 17:38:31 +0530954
Ankush Menat494bd9e2022-03-28 18:52:46 +0530955
956def get_partywise_advanced_payment_amount(
ruthra kumar0dc5e5c2023-08-21 08:46:55 +0530957 party_type, posting_date=None, future_payment=0, company=None, party=None
Ankush Menat494bd9e2022-03-28 18:52:46 +0530958):
ruthra kumar0dc5e5c2023-08-21 08:46:55 +0530959 ple = frappe.qb.DocType("Payment Ledger Entry")
Gursheen Anande355dea2023-07-28 14:51:28 +0530960 query = (
ruthra kumar0dc5e5c2023-08-21 08:46:55 +0530961 frappe.qb.from_(ple)
962 .select(ple.party, Abs(Sum(ple.amount).as_("amount")))
Gursheen Anande355dea2023-07-28 14:51:28 +0530963 .where(
ruthra kumar0dc5e5c2023-08-21 08:46:55 +0530964 (ple.party_type.isin(party_type))
965 & (ple.amount < 0)
966 & (ple.against_voucher_no == ple.voucher_no)
967 & (ple.delinked == 0)
Gursheen Anande355dea2023-07-28 14:51:28 +0530968 )
ruthra kumar0dc5e5c2023-08-21 08:46:55 +0530969 .groupby(ple.party)
Gursheen Anande355dea2023-07-28 14:51:28 +0530970 )
Gursheen Anande355dea2023-07-28 14:51:28 +0530971
Rohit Waghchaure4ed7d032019-03-25 15:37:25 +0530972 if posting_date:
Deepesh Garged2c1802020-05-27 12:46:12 +0530973 if future_payment:
ruthra kumar0dc5e5c2023-08-21 08:46:55 +0530974 query = query.where((ple.posting_date <= posting_date) | (Date(ple.creation) <= posting_date))
Deepesh Garged2c1802020-05-27 12:46:12 +0530975 else:
ruthra kumar0dc5e5c2023-08-21 08:46:55 +0530976 query = query.where(ple.posting_date <= posting_date)
Deepesh Garged2c1802020-05-27 12:46:12 +0530977
Saqib39805912020-05-01 18:15:13 +0530978 if company:
ruthra kumar0dc5e5c2023-08-21 08:46:55 +0530979 query = query.where(ple.company == company)
Rohit Waghchaure4ed7d032019-03-25 15:37:25 +0530980
Nabin Hait3504bf72023-05-29 09:23:40 +0530981 if party:
ruthra kumar0dc5e5c2023-08-21 08:46:55 +0530982 query = query.where(ple.party == party)
Nabin Hait3504bf72023-05-29 09:23:40 +0530983
Dany Robertf34ffc22023-11-20 11:10:56 +0000984 if invoice_doctypes := frappe.get_hooks("invoice_doctypes"):
985 query = query.where(ple.voucher_type.notin(invoice_doctypes))
986
ruthra kumar896b1232023-08-20 21:17:27 +0530987 data = query.run()
Rohit Waghchaureaffeb3d2019-01-15 17:38:31 +0530988 if data:
hendrikc257ce82019-09-05 16:44:09 +0700989 return frappe._dict(data)
Ronel Cabrerafcb54762019-11-18 17:00:07 +0800990
Ankush Menat494bd9e2022-03-28 18:52:46 +0530991
Raffael Meyerb91bb172023-06-08 16:19:09 +0200992def get_default_contact(doctype: str, name: str) -> Optional[str]:
Deepesh Gargcf9347d2020-03-31 17:28:43 +0530993 """
Raffael Meyerb91bb172023-06-08 16:19:09 +0200994 Returns contact name only if there is a primary contact for given doctype and name.
995
996 Else returns None
997
998 :param doctype: Party Doctype
999 :param name: Party name
1000 :return: String
Ronel Cabrerafcb54762019-11-18 17:00:07 +08001001 """
Raffael Meyerb91bb172023-06-08 16:19:09 +02001002 contacts = frappe.get_all(
1003 "Contact",
1004 filters=[
1005 ["Dynamic Link", "link_doctype", "=", doctype],
1006 ["Dynamic Link", "link_name", "=", name],
1007 ],
1008 or_filters=[
1009 ["is_primary_contact", "=", 1],
1010 ["is_billing_contact", "=", 1],
1011 ],
1012 pluck="name",
1013 limit=1,
1014 order_by="is_primary_contact DESC, is_billing_contact DESC",
Ankush Menat494bd9e2022-03-28 18:52:46 +05301015 )
Raffael Meyerb91bb172023-06-08 16:19:09 +02001016
1017 return contacts[0] if contacts else None
Deepesh Gargbc347372022-05-25 15:42:47 +05301018
1019
1020def add_party_account(party_type, party, company, account):
1021 doc = frappe.get_doc(party_type, party)
1022 account_exists = False
1023 for d in doc.get("accounts"):
1024 if d.account == account:
1025 account_exists = True
1026
1027 if not account_exists:
1028 accounts = {"company": company, "account": account}
1029
1030 doc.append("accounts", accounts)
1031
1032 doc.save()
Ankush Menatf4d74992023-10-17 22:11:56 +05301033
1034
1035def render_address(address, check_permissions=True):
1036 try:
1037 from frappe.contacts.doctype.address.address import render_address as _render
1038 except ImportError:
1039 # Older frappe versions where this function is not available
1040 from frappe.contacts.doctype.address.address import get_address_display as _render
1041
1042 return frappe.call(_render, address, check_permissions=check_permissions)