blob: 07b865e66cdca6de6a51e4340fdfcd2321c9cbe7 [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
Nabin Haitdb030d12014-09-10 17:11:30 +05308from frappe import _, msgprint, scrub
Chillar Anand915b3432021-09-02 16:44:59 +05309from frappe.contacts.doctype.address.address import (
10 get_address_display,
11 get_company_address,
12 get_default_address,
13)
14from frappe.contacts.doctype.contact.contact import get_contact_details
Suraj Shetty7ed37ae2018-12-19 19:56:42 +053015from frappe.core.doctype.user_permission.user_permission import get_permitted_documents
Rushabh Mehta919a74a2017-06-22 16:37:04 +053016from frappe.model.utils import get_fetch_values
Chillar Anand915b3432021-09-02 16:44:59 +053017from frappe.utils import (
18 add_days,
19 add_months,
20 add_years,
21 cint,
22 cstr,
23 date_diff,
24 flt,
25 formatdate,
26 get_last_day,
27 get_timestamp,
28 getdate,
29 nowdate,
30)
tunde4a263c72017-08-02 22:20:35 +010031
Chillar Anand915b3432021-09-02 16:44:59 +053032import erpnext
33from erpnext import get_company_currency
34from erpnext.accounts.utils import get_fiscal_year
35from erpnext.exceptions import InvalidAccountCurrency, PartyDisabled, PartyFrozen
36
Sagar Vora5c066202023-03-13 14:02:50 +000037PURCHASE_TRANSACTION_TYPES = {"Purchase Order", "Purchase Receipt", "Purchase Invoice"}
38SALES_TRANSACTION_TYPES = {
39 "Quotation",
40 "Sales Order",
41 "Delivery Note",
42 "Sales Invoice",
43 "POS Invoice",
44}
45TRANSACTION_TYPES = PURCHASE_TRANSACTION_TYPES | SALES_TRANSACTION_TYPES
46
Rushabh Mehta49dd7be2014-01-28 17:43:10 +053047
Ankush Menat494bd9e2022-03-28 18:52:46 +053048class DuplicatePartyAccountError(frappe.ValidationError):
49 pass
50
Nabin Hait16099332015-09-03 16:03:07 +053051
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053052@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +053053def get_party_details(
54 party=None,
55 account=None,
56 party_type="Customer",
57 company=None,
58 posting_date=None,
59 bill_date=None,
60 price_list=None,
61 currency=None,
62 doctype=None,
63 ignore_permissions=False,
64 fetch_payment_terms_template=True,
65 party_address=None,
66 company_address=None,
67 shipping_address=None,
68 pos_profile=None,
69):
Anand Doshi201dbbd2014-02-20 15:21:53 +053070
Rushabh Mehtad7a5b732015-04-01 23:38:13 +053071 if not party:
72 return {}
Nabin Hait5ef121b2015-06-08 12:26:52 +053073 if not frappe.db.exists(party_type, party):
74 frappe.throw(_("{0}: {1} does not exists").format(party_type, party))
Ankush Menat494bd9e2022-03-28 18:52:46 +053075 return _get_party_details(
76 party,
77 account,
78 party_type,
79 company,
80 posting_date,
81 bill_date,
82 price_list,
83 currency,
84 doctype,
85 ignore_permissions,
86 fetch_payment_terms_template,
87 party_address,
88 company_address,
89 shipping_address,
90 pos_profile,
91 )
Anand Doshi201dbbd2014-02-20 15:21:53 +053092
Ankush Menat494bd9e2022-03-28 18:52:46 +053093
94def _get_party_details(
95 party=None,
96 account=None,
97 party_type="Customer",
98 company=None,
99 posting_date=None,
100 bill_date=None,
101 price_list=None,
102 currency=None,
103 doctype=None,
104 ignore_permissions=False,
105 fetch_payment_terms_template=True,
106 party_address=None,
107 company_address=None,
108 shipping_address=None,
109 pos_profile=None,
110):
111 party_details = frappe._dict(
112 set_account_and_due_date(party, account, party_type, company, posting_date, bill_date, doctype)
113 )
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530114 party = party_details[party_type.lower()]
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530115
Ankush Menat494bd9e2022-03-28 18:52:46 +0530116 if not ignore_permissions and not (
117 frappe.has_permission(party_type, "read", party)
118 or frappe.has_permission(party_type, "select", party)
119 ):
Rushabh Mehta2d708872015-11-27 11:35:35 +0530120 frappe.throw(_("Not permitted for {0}").format(party), frappe.PermissionError)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530121
Nabin Hait365ae272014-04-03 17:38:54 +0530122 party = frappe.get_doc(party_type, party)
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,
134 )
Deepesh Gargcf9347d2020-03-31 17:28:43 +0530135 set_contact_details(party_details, party, party_type)
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530136 set_other_values(party_details, party, party_type)
137 set_price_list(party_details, party, party_type, price_list, pos_profile)
Anand Doshi13ae5482014-04-10 18:40:57 +0530138
Ankush Menat494bd9e2022-03-28 18:52:46 +0530139 tax_template = set_taxes(
140 party.name,
141 party_type,
142 posting_date,
143 company,
144 customer_group=party_details.customer_group,
145 supplier_group=party_details.supplier_group,
146 tax_category=party_details.tax_category,
147 billing_address=party_address,
148 shipping_address=shipping_address,
149 )
Deepesh Gargf12be302021-11-30 20:34:53 +0530150
151 if tax_template:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530152 party_details["taxes_and_charges"] = tax_template
rohitwaghchaure3ffe8962018-07-13 17:40:48 +0530153
Deepesh Gargbcf56e62021-08-06 23:53:16 +0530154 if cint(fetch_payment_terms_template):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530155 party_details["payment_terms_template"] = get_payment_terms_template(
156 party.name, party_type, company
157 )
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530158
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530159 if not party_details.get("currency"):
160 party_details["currency"] = currency
Anand Doshi13ae5482014-04-10 18:40:57 +0530161
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530162 # sales team
Ankush Menat494bd9e2022-03-28 18:52:46 +0530163 if party_type == "Customer":
164 party_details["sales_team"] = [
165 {
166 "sales_person": d.sales_person,
167 "allocated_percentage": d.allocated_percentage or None,
168 "commission_rate": d.commission_rate,
169 }
170 for d in party.get("sales_team")
171 ]
Anand Doshi13ae5482014-04-10 18:40:57 +0530172
Zarrar7f8024c2018-08-01 17:45:05 +0530173 # supplier tax withholding category
174 if party_type == "Supplier" and party:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530175 party_details["supplier_tds"] = frappe.get_value(
176 party_type, party.name, "tax_withholding_category"
177 )
Zarrar7f8024c2018-08-01 17:45:05 +0530178
Vishal Dhayagude7aafc902023-03-28 16:48:03 +0530179 if not party_details.get("tax_category") and pos_profile:
180 party_details["tax_category"] = frappe.get_value("POS Profile", pos_profile, "tax_category")
181
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530182 return party_details
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530183
Ankush Menat494bd9e2022-03-28 18:52:46 +0530184
185def set_address_details(
186 party_details,
187 party,
188 party_type,
189 doctype=None,
190 company=None,
191 party_address=None,
192 company_address=None,
193 shipping_address=None,
194):
195 billing_address_field = (
196 "customer_address" if party_type == "Lead" else party_type.lower() + "_address"
197 )
198 party_details[billing_address_field] = party_address or get_default_address(
199 party_type, party.name
200 )
Nabin Hait7eba1a32017-10-02 15:59:27 +0530201 if doctype:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530202 party_details.update(
203 get_fetch_values(doctype, billing_address_field, party_details[billing_address_field])
204 )
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530205 # address display
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530206 party_details.address_display = get_address_display(party_details[billing_address_field])
Nabin Hait9d1f0772014-02-19 17:43:24 +0530207 # shipping address
208 if party_type in ["Customer", "Lead"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530209 party_details.shipping_address_name = shipping_address or get_party_shipping_address(
210 party_type, party.name
211 )
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530212 party_details.shipping_address = get_address_display(party_details["shipping_address_name"])
Nabin Hait7eba1a32017-10-02 15:59:27 +0530213 if doctype:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530214 party_details.update(
215 get_fetch_values(doctype, "shipping_address_name", party_details.shipping_address_name)
216 )
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530217
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530218 if company_address:
Sagar Voraa3625b32022-07-29 12:41:40 +0530219 party_details.company_address = company_address
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530220 else:
221 party_details.update(get_company_address(company))
Shreya Shah4fa600a2018-06-05 11:27:53 +0530222
Sagar Vora5c066202023-03-13 14:02:50 +0000223 if doctype in SALES_TRANSACTION_TYPES and party_details.company_address:
224 party_details.update(get_fetch_values(doctype, "company_address", party_details.company_address))
Shreya Shah4fa600a2018-06-05 11:27:53 +0530225
Sagar Vora5c066202023-03-13 14:02:50 +0000226 if doctype in PURCHASE_TRANSACTION_TYPES:
Sagar Voraa3625b32022-07-29 12:41:40 +0530227 if shipping_address:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530228 party_details.update(
Sagar Voraa3625b32022-07-29 12:41:40 +0530229 shipping_address=shipping_address,
230 shipping_address_display=get_address_display(shipping_address),
231 **get_fetch_values(doctype, "shipping_address", shipping_address)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530232 )
Sagar Voraa3625b32022-07-29 12:41:40 +0530233
234 if party_details.company_address:
235 # billing address
236 party_details.update(
237 billing_address=party_details.company_address,
238 billing_address_display=(
239 party_details.company_address_display or get_address_display(party_details.company_address)
240 ),
241 **get_fetch_values(doctype, "billing_address", party_details.company_address)
242 )
243
244 # shipping address - if not already set
245 if not party_details.shipping_address:
246 party_details.update(
247 shipping_address=party_details.billing_address,
248 shipping_address_display=party_details.billing_address_display,
249 **get_fetch_values(doctype, "shipping_address", party_details.billing_address)
250 )
251
Sagar Vora5c066202023-03-13 14:02:50 +0000252 party_address, shipping_address = (
253 party_details.get(billing_address_field),
254 party_details.shipping_address_name,
255 )
256
257 party_details["tax_category"] = get_address_tax_category(
258 party.get("tax_category"),
259 party_address,
260 shipping_address if party_type != "Supplier" else party_address,
261 )
262
263 if doctype in TRANSACTION_TYPES:
Sagar Vora17ef3c92023-04-04 17:49:50 +0530264 # required to set correct region
265 frappe.flags.company = company
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530266 get_regional_address_details(party_details, doctype, company)
267
Sagar Vora5c066202023-03-13 14:02:50 +0000268 return party_address, shipping_address
Saif Ur Rehman67786682018-12-27 02:11:07 +0500269
Ankush Menat494bd9e2022-03-28 18:52:46 +0530270
Shreya Shah4fa600a2018-06-05 11:27:53 +0530271@erpnext.allow_regional
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530272def get_regional_address_details(party_details, doctype, company):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530273 pass
Anand Doshi13ae5482014-04-10 18:40:57 +0530274
Ankush Menat494bd9e2022-03-28 18:52:46 +0530275
Deepesh Gargcf9347d2020-03-31 17:28:43 +0530276def set_contact_details(party_details, party, party_type):
277 party_details.contact_person = get_default_contact(party_type, party.name)
Anand Doshi13ae5482014-04-10 18:40:57 +0530278
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530279 if not party_details.contact_person:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530280 party_details.update(
281 {
282 "contact_person": None,
283 "contact_display": None,
284 "contact_email": None,
285 "contact_mobile": None,
286 "contact_phone": None,
287 "contact_designation": None,
288 "contact_department": None,
289 }
290 )
Neil Trini Lasradofe2ffae2015-07-08 18:16:51 +0530291 else:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530292 party_details.update(get_contact_details(party_details.contact_person))
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530293
Ankush Menat494bd9e2022-03-28 18:52:46 +0530294
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530295def set_other_values(party_details, party, party_type):
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530296 # copy
ChillarAnand9ace7d62022-03-07 16:53:59 +0530297 if party_type == "Customer":
saurabh8e499512016-02-19 11:08:45 +0530298 to_copy = ["customer_name", "customer_group", "territory", "language"]
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530299 else:
Zlash6589070782018-04-19 18:37:29 +0530300 to_copy = ["supplier_name", "supplier_group", "language"]
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530301 for f in to_copy:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530302 party_details[f] = party.get(f)
Anand Doshi13ae5482014-04-10 18:40:57 +0530303
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530304 # fields prepended with default in Customer doctype
Ankush Menat494bd9e2022-03-28 18:52:46 +0530305 for f in ["currency"] + (
306 ["sales_partner", "commission_rate"] if party_type == "Customer" else []
307 ):
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530308 if party.get("default_" + f):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530309 party_details[f] = party.get("default_" + f)
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530310
Ankush Menat494bd9e2022-03-28 18:52:46 +0530311
Rushabh Mehta72fbf902015-09-17 18:29:44 +0530312def get_default_price_list(party):
313 """Return default price list for party (Document object)"""
Nabin Hait34c551d2019-07-03 10:34:31 +0530314 if party.get("default_price_list"):
Rushabh Mehta72fbf902015-09-17 18:29:44 +0530315 return party.default_price_list
316
317 if party.doctype == "Customer":
Daizy Modi27df4552022-11-03 13:38:48 +0530318 return frappe.get_cached_value("Customer Group", party.customer_group, "default_price_list")
Rushabh Mehta72fbf902015-09-17 18:29:44 +0530319
Rushabh Mehta72fbf902015-09-17 18:29:44 +0530320
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530321def set_price_list(party_details, party, party_type, given_price_list, pos=None):
Anand Doshi13ae5482014-04-10 18:40:57 +0530322 # price list
Ankush Menat494bd9e2022-03-28 18:52:46 +0530323 price_list = get_permitted_documents("Price List")
rohitwaghchaure52107612020-05-05 12:12:33 +0530324
Faris Ansari64f01bd2020-04-14 11:51:48 +0530325 # if there is only one permitted document based on user permissions, set it
326 if price_list and len(price_list) == 1:
Suraj Shettydcc90e32018-05-04 17:52:57 +0530327 price_list = price_list[0]
Ankush Menat494bd9e2022-03-28 18:52:46 +0530328 elif pos and party_type == "Customer":
329 customer_price_list = frappe.get_value("Customer", party.name, "default_price_list")
deepeshgarg007c48efab2019-01-24 17:15:38 +0530330
331 if customer_price_list:
332 price_list = customer_price_list
333 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530334 pos_price_list = frappe.get_value("POS Profile", pos, "selling_price_list")
deepeshgarg0071f9a6fe2019-01-25 11:53:55 +0530335 price_list = pos_price_list or given_price_list
Suraj Shettydcc90e32018-05-04 17:52:57 +0530336 else:
337 price_list = get_default_price_list(party) or given_price_list
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530338
339 if price_list:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530340 party_details.price_list_currency = frappe.db.get_value(
341 "Price List", price_list, "currency", cache=True
342 )
Anand Doshi13ae5482014-04-10 18:40:57 +0530343
Ankush Menat494bd9e2022-03-28 18:52:46 +0530344 party_details[
345 "selling_price_list" if party.doctype == "Customer" else "buying_price_list"
346 ] = price_list
Anand Doshi13ae5482014-04-10 18:40:57 +0530347
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530348
Ankush Menat494bd9e2022-03-28 18:52:46 +0530349def set_account_and_due_date(
350 party, account, party_type, company, posting_date, bill_date, doctype
351):
Saqiba6f98d42020-07-23 18:51:26 +0530352 if doctype not in ["POS Invoice", "Sales Invoice", "Purchase Invoice"]:
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530353 # not an invoice
Ankush Menat494bd9e2022-03-28 18:52:46 +0530354 return {party_type.lower(): party}
Anand Doshi13ae5482014-04-10 18:40:57 +0530355
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530356 if party:
Anand Doshib20baf82015-09-25 16:17:50 +0530357 account = get_party_account(party_type, party, company)
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530358
Ankush Menat494bd9e2022-03-28 18:52:46 +0530359 account_fieldname = "debit_to" if party_type == "Customer" else "credit_to"
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530360 out = {
361 party_type.lower(): party,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530362 account_fieldname: account,
363 "due_date": get_due_date(posting_date, party_type, party, company, bill_date),
Rushabh Mehtacc008cc2014-02-03 16:14:56 +0530364 }
Shreya Shah3a9eec22018-02-16 13:05:21 +0530365
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530366 return out
Rushabh Mehta361df892015-09-18 12:59:51 +0530367
Ankush Menat494bd9e2022-03-28 18:52:46 +0530368
Nabin Haitdb030d12014-09-10 17:11:30 +0530369@frappe.whitelist()
Deepesh Garg88648572021-11-12 12:39:30 +0530370def get_party_account(party_type, party=None, company=None):
Rushabh Mehta364054a2015-02-21 14:39:35 +0530371 """Returns the account for the given `party`.
Ankush Menat494bd9e2022-03-28 18:52:46 +0530372 Will first search in party (Customer / Supplier) record, if not found,
373 will search in group (Customer Group / Supplier Group),
374 finally will return default."""
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530375 if not company:
Anand Doshib20baf82015-09-25 16:17:50 +0530376 frappe.throw(_("Please select a Company"))
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530377
Ankush Menat494bd9e2022-03-28 18:52:46 +0530378 if not party and party_type in ["Customer", "Supplier"]:
379 default_account_name = (
380 "default_receivable_account" if party_type == "Customer" else "default_payable_account"
381 )
Deepesh Garg88648572021-11-12 12:39:30 +0530382
Ankush Menat494bd9e2022-03-28 18:52:46 +0530383 return frappe.get_cached_value("Company", company, default_account_name)
Saurabh0f86d862017-11-10 19:21:09 +0530384
Ankush Menat494bd9e2022-03-28 18:52:46 +0530385 account = frappe.db.get_value(
386 "Party Account", {"parenttype": party_type, "parent": party, "company": company}, "account"
387 )
Saurabh0f86d862017-11-10 19:21:09 +0530388
Ankush Menat494bd9e2022-03-28 18:52:46 +0530389 if not account and party_type in ["Customer", "Supplier"]:
390 party_group_doctype = "Customer Group" if party_type == "Customer" else "Supplier Group"
Nabin Hait9a33bc62018-08-09 10:47:09 +0530391 group = frappe.get_cached_value(party_type, party, scrub(party_group_doctype))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530392 account = frappe.db.get_value(
393 "Party Account",
394 {"parenttype": party_group_doctype, "parent": group, "company": company},
395 "account",
396 )
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530397
Ankush Menat494bd9e2022-03-28 18:52:46 +0530398 if not account and party_type in ["Customer", "Supplier"]:
399 default_account_name = (
400 "default_receivable_account" if party_type == "Customer" else "default_payable_account"
401 )
402 account = frappe.get_cached_value("Company", company, default_account_name)
Rushabh Mehta364054a2015-02-21 14:39:35 +0530403
Saurabh0f86d862017-11-10 19:21:09 +0530404 existing_gle_currency = get_party_gle_currency(party_type, party, company)
405 if existing_gle_currency:
406 if account:
Daizy Modi010bd9c2022-11-03 14:36:48 +0530407 account_currency = frappe.get_cached_value("Account", account, "account_currency")
Saurabh0f86d862017-11-10 19:21:09 +0530408 if (account and account_currency != existing_gle_currency) or not account:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530409 account = get_party_gle_account(party_type, party, company)
Rushabh Mehtab92087c2017-01-13 18:53:11 +0530410
Saurabh0f86d862017-11-10 19:21:09 +0530411 return account
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530412
Ankush Menat494bd9e2022-03-28 18:52:46 +0530413
rohitwaghchaure713cfc72018-09-11 17:40:37 +0530414@frappe.whitelist()
415def get_party_bank_account(party_type, party):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530416 return frappe.db.get_value(
417 "Bank Account", {"party_type": party_type, "party": party, "is_default": 1}
418 )
419
rohitwaghchaure713cfc72018-09-11 17:40:37 +0530420
Anand Doshib20baf82015-09-25 16:17:50 +0530421def get_party_account_currency(party_type, party, company):
422 def generator():
423 party_account = get_party_account(party_type, party, company)
Daizy Modi010bd9c2022-11-03 14:36:48 +0530424 return frappe.get_cached_value("Account", party_account, "account_currency")
Anand Doshib20baf82015-09-25 16:17:50 +0530425
426 return frappe.local_cache("party_account_currency", (party_type, party, company), generator)
427
Ankush Menat494bd9e2022-03-28 18:52:46 +0530428
Anand Doshi4945b942015-09-30 16:41:15 +0530429def get_party_gle_currency(party_type, party, company):
430 def generator():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530431 existing_gle_currency = frappe.db.sql(
432 """select account_currency from `tabGL Entry`
Anand Doshi4945b942015-09-30 16:41:15 +0530433 where docstatus=1 and company=%(company)s and party_type=%(party_type)s and party=%(party)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530434 limit 1""",
435 {"company": company, "party_type": party_type, "party": party},
436 )
Anand Doshi4945b942015-09-30 16:41:15 +0530437
438 return existing_gle_currency[0][0] if existing_gle_currency else None
439
Ankush Menat494bd9e2022-03-28 18:52:46 +0530440 return frappe.local_cache(
441 "party_gle_currency", (party_type, party, company), generator, regenerate_if_none=True
442 )
443
Rushabh Mehtab92087c2017-01-13 18:53:11 +0530444
Nabin Hait16d69592016-06-28 16:15:58 +0530445def get_party_gle_account(party_type, party, company):
446 def generator():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530447 existing_gle_account = frappe.db.sql(
448 """select account from `tabGL Entry`
Nabin Hait16d69592016-06-28 16:15:58 +0530449 where docstatus=1 and company=%(company)s and party_type=%(party_type)s and party=%(party)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530450 limit 1""",
451 {"company": company, "party_type": party_type, "party": party},
452 )
Nabin Hait16d69592016-06-28 16:15:58 +0530453
454 return existing_gle_account[0][0] if existing_gle_account else None
455
Ankush Menat494bd9e2022-03-28 18:52:46 +0530456 return frappe.local_cache(
457 "party_gle_account", (party_type, party, company), generator, regenerate_if_none=True
458 )
459
Anand Doshi4945b942015-09-30 16:41:15 +0530460
Anand Doshid8bc40d2015-10-22 17:54:50 +0530461def validate_party_gle_currency(party_type, party, company, party_account_currency=None):
Anand Doshi4945b942015-09-30 16:41:15 +0530462 """Validate party account currency with existing GL Entry's currency"""
Anand Doshid8bc40d2015-10-22 17:54:50 +0530463 if not party_account_currency:
464 party_account_currency = get_party_account_currency(party_type, party, company)
465
Anand Doshi4945b942015-09-30 16:41:15 +0530466 existing_gle_currency = get_party_gle_currency(party_type, party, company)
467
468 if existing_gle_currency and party_account_currency != existing_gle_currency:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530469 frappe.throw(
470 _(
471 "{0} {1} has accounting entries in currency {2} for company {3}. Please select a receivable or payable account with currency {2}."
472 ).format(
473 frappe.bold(party_type),
474 frappe.bold(party),
475 frappe.bold(existing_gle_currency),
476 frappe.bold(company),
477 ),
478 InvalidAccountCurrency,
479 )
480
Anand Doshi4945b942015-09-30 16:41:15 +0530481
Anand Doshida98ab62015-09-28 15:13:38 +0530482def validate_party_accounts(doc):
Deepesh Garg5a2b5712022-02-18 20:05:49 +0530483 from erpnext.controllers.accounts_controller import validate_account_head
Ankush Menat494bd9e2022-03-28 18:52:46 +0530484
Anand Doshida98ab62015-09-28 15:13:38 +0530485 companies = []
486
487 for account in doc.get("accounts"):
488 if account.company in companies:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530489 frappe.throw(
490 _("There can only be 1 Account per Company in {0} {1}").format(doc.doctype, doc.name),
491 DuplicatePartyAccountError,
492 )
Anand Doshida98ab62015-09-28 15:13:38 +0530493 else:
494 companies.append(account.company)
Anand Doshid8bc40d2015-10-22 17:54:50 +0530495
Daizy Modi010bd9c2022-11-03 14:36:48 +0530496 party_account_currency = frappe.get_cached_value("Account", account.account, "account_currency")
hendrikc257ce82019-09-05 16:44:09 +0700497 if frappe.db.get_default("Company"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530498 company_default_currency = frappe.get_cached_value(
499 "Company", frappe.db.get_default("Company"), "default_currency"
500 )
hendrikc257ce82019-09-05 16:44:09 +0700501 else:
Daizy Modi27df4552022-11-03 13:38:48 +0530502 company_default_currency = frappe.get_cached_value(
503 "Company", account.company, "default_currency"
504 )
Anand Doshid8bc40d2015-10-22 17:54:50 +0530505
Deepesh Garg1a2cf5c2020-03-28 21:26:16 +0530506 validate_party_gle_currency(doc.doctype, doc.name, account.company, party_account_currency)
Anand Doshida98ab62015-09-28 15:13:38 +0530507
rohitwaghchaureea092a72017-02-01 12:02:08 +0530508 if doc.get("default_currency") and party_account_currency and company_default_currency:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530509 if (
510 doc.default_currency != party_account_currency
511 and doc.default_currency != company_default_currency
512 ):
513 frappe.throw(
514 _(
515 "Billing currency must be equal to either default company's currency or party account currency"
516 )
517 )
tunde3b4bd372017-08-31 16:28:47 +0100518
Deepesh Garg5a2b5712022-02-18 20:05:49 +0530519 # validate if account is mapped for same company
520 validate_account_head(account.idx, account.account, account.company)
521
rohitwaghchaure62fea032016-03-30 13:24:42 +0530522
Nabin Hait4770a1a2015-07-09 16:35:46 +0530523@frappe.whitelist()
Shreya Shah3a9eec22018-02-16 13:05:21 +0530524def get_due_date(posting_date, party_type, party, company=None, bill_date=None):
tunde3b4bd372017-08-31 16:28:47 +0100525 """Get due date from `Payment Terms Template`"""
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530526 due_date = None
Shreya Shah3a9eec22018-02-16 13:05:21 +0530527 if (bill_date or posting_date) and party:
528 due_date = bill_date or posting_date
marinationfa085d72020-10-27 13:18:30 +0530529 template_name = get_payment_terms_template(party, party_type, company)
rohitwaghchaure3ffe8962018-07-13 17:40:48 +0530530
tunde3b4bd372017-08-31 16:28:47 +0100531 if template_name:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530532 due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime(
533 "%Y-%m-%d"
534 )
tundeed86efb2017-09-05 01:15:31 +0100535 else:
536 if party_type == "Supplier":
Nabin Hait9a33bc62018-08-09 10:47:09 +0530537 supplier_group = frappe.get_cached_value(party_type, party, "supplier_group")
538 template_name = frappe.get_cached_value("Supplier Group", supplier_group, "payment_terms")
tundee5973e42017-09-05 18:11:58 +0100539 if template_name:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530540 due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime(
541 "%Y-%m-%d"
542 )
Shreya Shah3a9eec22018-02-16 13:05:21 +0530543 # If due date is calculated from bill_date, check this condition
544 if getdate(due_date) < getdate(posting_date):
545 due_date = posting_date
Anand Doshi13ae5482014-04-10 18:40:57 +0530546 return due_date
Rushabh Mehta49dd7be2014-01-28 17:43:10 +0530547
Ankush Menat494bd9e2022-03-28 18:52:46 +0530548
Shreya Shah3a9eec22018-02-16 13:05:21 +0530549def get_due_date_from_template(template_name, posting_date, bill_date):
tunde3b4bd372017-08-31 16:28:47 +0100550 """
551 Inspects all `Payment Term`s from the a `Payment Terms Template` and returns the due
552 date after considering all the `Payment Term`s requirements.
553 :param template_name: Name of the `Payment Terms Template`
554 :return: String representing the calculated due date
555 """
Shreya Shah3a9eec22018-02-16 13:05:21 +0530556 due_date = getdate(bill_date or posting_date)
557
Ankush Menat494bd9e2022-03-28 18:52:46 +0530558 template = frappe.get_doc("Payment Terms Template", template_name)
tunde3b4bd372017-08-31 16:28:47 +0100559
560 for term in template.terms:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530561 if term.due_date_based_on == "Day(s) after invoice date":
tunde3b4bd372017-08-31 16:28:47 +0100562 due_date = max(due_date, add_days(due_date, term.credit_days))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530563 elif term.due_date_based_on == "Day(s) after the end of the invoice month":
tunde3b4bd372017-08-31 16:28:47 +0100564 due_date = max(due_date, add_days(get_last_day(due_date), term.credit_days))
565 else:
developsessionsce8a1082023-02-03 11:30:29 +0100566 due_date = max(due_date, get_last_day(add_months(due_date, term.credit_months)))
tunde3b4bd372017-08-31 16:28:47 +0100567 return due_date
568
Ankush Menat494bd9e2022-03-28 18:52:46 +0530569
570def validate_due_date(
571 posting_date, due_date, party_type, party, company=None, bill_date=None, template_name=None
572):
Nabin Hait4770a1a2015-07-09 16:35:46 +0530573 if getdate(due_date) < getdate(posting_date):
Rohit Waghchaured1a85a32018-11-26 18:42:29 +0530574 frappe.throw(_("Due Date cannot be before Posting / Supplier Invoice Date"))
Nabin Hait4770a1a2015-07-09 16:35:46 +0530575 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530576 if not template_name:
577 return
rohitwaghchaure3ffe8962018-07-13 17:40:48 +0530578
Ankush Menat494bd9e2022-03-28 18:52:46 +0530579 default_due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime(
580 "%Y-%m-%d"
581 )
Saurabhd7897f12018-07-18 17:08:16 +0530582
Anand Doshi0ca587e2015-09-25 16:32:14 +0530583 if not default_due_date:
584 return
585
Nabin Hait93d3c822015-07-10 17:11:58 +0530586 if default_due_date != posting_date and getdate(due_date) > getdate(default_due_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530587 is_credit_controller = (
588 frappe.db.get_single_value("Accounts Settings", "credit_controller") in frappe.get_roles()
589 )
Nabin Hait4770a1a2015-07-09 16:35:46 +0530590 if is_credit_controller:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530591 msgprint(
592 _("Note: Due / Reference Date exceeds allowed customer credit days by {0} day(s)").format(
593 date_diff(due_date, default_due_date)
594 )
595 )
Nabin Hait4770a1a2015-07-09 16:35:46 +0530596 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530597 frappe.throw(
598 _("Due / Reference Date cannot be after {0}").format(formatdate(default_due_date))
599 )
600
Rushabh Mehta361df892015-09-18 12:59:51 +0530601
Neil Trini Lasrado09f9c962015-08-26 10:41:31 +0530602@frappe.whitelist()
Nabin Hait16a7ec92019-09-05 13:01:15 +0530603def get_address_tax_category(tax_category=None, billing_address=None, shipping_address=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530604 addr_tax_category_from = frappe.db.get_single_value(
605 "Accounts Settings", "determine_address_tax_category_from"
606 )
Saif Ur Rehmanfd531a62018-12-29 01:49:11 +0500607 if addr_tax_category_from == "Shipping Address":
608 if shipping_address:
609 tax_category = frappe.db.get_value("Address", shipping_address, "tax_category") or tax_category
610 else:
611 if billing_address:
612 tax_category = frappe.db.get_value("Address", billing_address, "tax_category") or tax_category
613
614 return cstr(tax_category)
Saif Ur Rehman67786682018-12-27 02:11:07 +0500615
Ankush Menat494bd9e2022-03-28 18:52:46 +0530616
Neil Trini Lasrado09f9c962015-08-26 10:41:31 +0530617@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530618def set_taxes(
619 party,
620 party_type,
621 posting_date,
622 company,
623 customer_group=None,
624 supplier_group=None,
625 tax_category=None,
626 billing_address=None,
627 shipping_address=None,
628 use_for_shopping_cart=None,
629):
Chillar Anand915b3432021-09-02 16:44:59 +0530630 from erpnext.accounts.doctype.tax_rule.tax_rule import get_party_details, get_tax_template
Ankush Menat494bd9e2022-03-28 18:52:46 +0530631
632 args = {party_type.lower(): party, "company": company}
Rushabh Mehta361df892015-09-18 12:59:51 +0530633
Saif Ur Rehman67786682018-12-27 02:11:07 +0500634 if tax_category:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530635 args["tax_category"] = tax_category
Saif Ur Rehman67786682018-12-27 02:11:07 +0500636
Rushabh Mehta3c14c5a2017-09-29 13:21:22 +0530637 if customer_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530638 args["customer_group"] = customer_group
Rushabh Mehta3c14c5a2017-09-29 13:21:22 +0530639
Zlash6589070782018-04-19 18:37:29 +0530640 if supplier_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530641 args["supplier_group"] = supplier_group
Rushabh Mehta3c14c5a2017-09-29 13:21:22 +0530642
Neil Trini Lasrado09f9c962015-08-26 10:41:31 +0530643 if billing_address or shipping_address:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530644 args.update(
645 get_party_details(
646 party, party_type, {"billing_address": billing_address, "shipping_address": shipping_address}
647 )
648 )
Neil Trini Lasrado09f9c962015-08-26 10:41:31 +0530649 else:
650 args.update(get_party_details(party, party_type))
Rushabh Mehta361df892015-09-18 12:59:51 +0530651
Nabin Hait47ce6de2023-06-06 15:19:04 +0530652 if party_type in ("Customer", "Lead", "Prospect"):
Neil Trini Lasrado810bd352015-08-21 15:04:57 +0530653 args.update({"tax_type": "Sales"})
Anand Doshi2f957f22016-04-08 17:36:10 +0530654
Nabin Hait47ce6de2023-06-06 15:19:04 +0530655 if party_type in ["Lead", "Prospect"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530656 args["customer"] = None
Nabin Hait47ce6de2023-06-06 15:19:04 +0530657 del args[frappe.scrub(party_type)]
Neil Trini Lasrado810bd352015-08-21 15:04:57 +0530658 else:
659 args.update({"tax_type": "Purchase"})
Rushabh Mehta361df892015-09-18 12:59:51 +0530660
Saurabh957e7a32015-09-11 15:44:06 +0530661 if use_for_shopping_cart:
Saurabh957e7a32015-09-11 15:44:06 +0530662 args.update({"use_for_shopping_cart": use_for_shopping_cart})
Rushabh Mehta361df892015-09-18 12:59:51 +0530663
664 return get_tax_template(posting_date, args)
shreyas29b565f2016-01-25 17:30:49 +0530665
tunde400d0462017-08-31 13:44:57 +0100666
667@frappe.whitelist()
marinationfa085d72020-10-27 13:18:30 +0530668def get_payment_terms_template(party_name, party_type, company=None):
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530669 if party_type not in ("Customer", "Supplier"):
670 return
tunde400d0462017-08-31 13:44:57 +0100671 template = None
Ankush Menat494bd9e2022-03-28 18:52:46 +0530672 if party_type == "Customer":
673 customer = frappe.get_cached_value(
674 "Customer", party_name, fieldname=["payment_terms", "customer_group"], as_dict=1
675 )
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530676 template = customer.payment_terms
677
678 if not template and customer.customer_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530679 template = frappe.get_cached_value("Customer Group", customer.customer_group, "payment_terms")
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530680 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530681 supplier = frappe.get_cached_value(
682 "Supplier", party_name, fieldname=["payment_terms", "supplier_group"], as_dict=1
683 )
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530684 template = supplier.payment_terms
Zlash6589070782018-04-19 18:37:29 +0530685 if not template and supplier.supplier_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530686 template = frappe.get_cached_value("Supplier Group", supplier.supplier_group, "payment_terms")
Nabin Haitcfa9d1a2018-01-29 16:07:21 +0530687
688 if not template and company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530689 template = frappe.get_cached_value("Company", company, fieldname="payment_terms")
tunde400d0462017-08-31 13:44:57 +0100690 return template
691
Ankush Menat494bd9e2022-03-28 18:52:46 +0530692
shreyaseba9ca42016-01-26 14:56:52 +0530693def validate_party_frozen_disabled(party_type, party_name):
Subin Tomb8845b92021-07-30 16:30:18 +0530694
695 if frappe.flags.ignore_party_validation:
696 return
697
shreyas79872bf2016-01-26 13:57:06 +0530698 if party_type and party_name:
KanchanChauhanfbaa6192017-01-30 15:15:58 +0530699 if party_type in ("Customer", "Supplier"):
Nabin Hait9a33bc62018-08-09 10:47:09 +0530700 party = frappe.get_cached_value(party_type, party_name, ["is_frozen", "disabled"], as_dict=True)
deepeshgarg007737ec6b2019-10-20 17:36:36 +0530701 if party.disabled:
702 frappe.throw(_("{0} {1} is disabled").format(party_type, party_name), PartyDisabled)
703 elif party.get("is_frozen"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530704 frozen_accounts_modifier = frappe.db.get_single_value(
705 "Accounts Settings", "frozen_accounts_modifier"
706 )
KanchanChauhanfbaa6192017-01-30 15:15:58 +0530707 if not frozen_accounts_modifier in frappe.get_roles():
708 frappe.throw(_("{0} {1} is frozen").format(party_type, party_name), PartyFrozen)
709
710 elif party_type == "Employee":
Rucha Mahabala38147a2021-06-12 13:33:21 +0530711 if frappe.db.get_value("Employee", party_name, "status") != "Active":
Kanchan Chauhan95108ac2017-04-11 15:55:34 +0530712 frappe.msgprint(_("{0} {1} is not active").format(party_type, party_name), alert=True)
Rushabh Mehta15a7f212016-04-14 17:30:40 +0530713
Ankush Menat494bd9e2022-03-28 18:52:46 +0530714
Rushabh Mehta15a7f212016-04-14 17:30:40 +0530715def get_timeline_data(doctype, name):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530716 """returns timeline data for the past one year"""
Rushabh Mehta15a7f212016-04-14 17:30:40 +0530717 from frappe.desk.form.load import get_communication_data
mbauskare7b87ad2017-02-16 13:12:29 +0530718
719 out = {}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530720 fields = "creation, count(*)"
721 after = add_years(None, -1).strftime("%Y-%m-%d")
722 group_by = "group by Date(creation)"
Zarrar58200182018-05-30 11:56:23 +0530723
Ankush Menat494bd9e2022-03-28 18:52:46 +0530724 data = get_communication_data(
725 doctype,
726 name,
727 after=after,
728 group_by="group by creation",
729 fields="C.creation as creation, count(C.name)",
730 as_dict=False,
731 )
Zarrar58200182018-05-30 11:56:23 +0530732
733 # fetch and append data from Activity Log
Ankush Menat494bd9e2022-03-28 18:52:46 +0530734 data += frappe.db.sql(
735 """select {fields}
Zarrar58200182018-05-30 11:56:23 +0530736 from `tabActivity Log`
rohitwaghchaure52107612020-05-05 12:12:33 +0530737 where (reference_doctype=%(doctype)s and reference_name=%(name)s)
738 or (timeline_doctype in (%(doctype)s) and timeline_name=%(name)s)
739 or (reference_doctype in ("Quotation", "Opportunity") and timeline_name=%(name)s)
Zarrar58200182018-05-30 11:56:23 +0530740 and status!='Success' and creation > {after}
741 {group_by} order by creation desc
Ankush Menat494bd9e2022-03-28 18:52:46 +0530742 """.format(
743 fields=fields, group_by=group_by, after=after
744 ),
745 {"doctype": doctype, "name": name},
746 as_dict=False,
747 )
mbauskare7b87ad2017-02-16 13:12:29 +0530748
749 timeline_items = dict(data)
750
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530751 for date, count in timeline_items.items():
mbauskare7b87ad2017-02-16 13:12:29 +0530752 timestamp = get_timestamp(date)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530753 out.update({timestamp: count})
mbauskare7b87ad2017-02-16 13:12:29 +0530754
Nabin Hait2d79a642017-05-24 12:41:14 +0530755 return out
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530756
Ankush Menat494bd9e2022-03-28 18:52:46 +0530757
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530758def get_dashboard_info(party_type, party, loyalty_program=None):
Nabin Hait2d79a642017-05-24 12:41:14 +0530759 current_fiscal_year = get_fiscal_year(nowdate(), as_dict=True)
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530760
Ankush Menat494bd9e2022-03-28 18:52:46 +0530761 doctype = "Sales Invoice" if party_type == "Customer" else "Purchase Invoice"
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530762
Ankush Menat494bd9e2022-03-28 18:52:46 +0530763 companies = frappe.get_all(
764 doctype, filters={"docstatus": 1, party_type.lower(): party}, distinct=1, fields=["company"]
765 )
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530766
deepeshgarg007920dc142018-11-23 10:17:28 +0530767 company_wise_info = []
768
Ankush Menat494bd9e2022-03-28 18:52:46 +0530769 company_wise_grand_total = frappe.get_all(
770 doctype,
deepeshgarg007ee05e352018-11-29 16:24:28 +0530771 filters={
Ankush Menat494bd9e2022-03-28 18:52:46 +0530772 "docstatus": 1,
deepeshgarg007ee05e352018-11-29 16:24:28 +0530773 party_type.lower(): party,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530774 "posting_date": (
775 "between",
776 [current_fiscal_year.year_start_date, current_fiscal_year.year_end_date],
777 ),
778 },
779 group_by="company",
780 fields=[
781 "company",
782 "sum(grand_total) as grand_total",
783 "sum(base_grand_total) as base_grand_total",
784 ],
785 )
deepeshgarg007920dc142018-11-23 10:17:28 +0530786
deepeshgarg007a1d015c2018-12-26 11:01:02 +0530787 loyalty_point_details = []
788
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530789 if party_type == "Customer":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530790 loyalty_point_details = frappe._dict(
791 frappe.get_all(
792 "Loyalty Point Entry",
793 filters={
794 "customer": party,
795 "expiry_date": (">=", getdate()),
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530796 },
797 group_by="company",
798 fields=["company", "sum(loyalty_points) as loyalty_points"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530799 as_list=1,
800 )
801 )
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530802
deepeshgarg007f31caff2018-11-27 15:04:12 +0530803 company_wise_billing_this_year = frappe._dict()
804
805 for d in company_wise_grand_total:
806 company_wise_billing_this_year.setdefault(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530807 d.company, {"grand_total": d.grand_total, "base_grand_total": d.base_grand_total}
808 )
deepeshgarg007f31caff2018-11-27 15:04:12 +0530809
Ankush Menat494bd9e2022-03-28 18:52:46 +0530810 company_wise_total_unpaid = frappe._dict(
811 frappe.db.sql(
812 """
deepeshgarg007920dc142018-11-23 10:17:28 +0530813 select company, sum(debit_in_account_currency) - sum(credit_in_account_currency)
Nabin Hait24f0b132017-05-24 13:01:26 +0530814 from `tabGL Entry`
deepeshgarg007920dc142018-11-23 10:17:28 +0530815 where party_type = %s and party=%s
Deepesh Garg802e63a2021-06-28 11:24:32 +0530816 and is_cancelled = 0
Ankush Menat494bd9e2022-03-28 18:52:46 +0530817 group by company""",
818 (party_type, party),
819 )
820 )
Nabin Hait2d79a642017-05-24 12:41:14 +0530821
deepeshgarg007920dc142018-11-23 10:17:28 +0530822 for d in companies:
Daizy Modi27df4552022-11-03 13:38:48 +0530823 company_default_currency = frappe.get_cached_value("Company", d.company, "default_currency")
deepeshgarg007920dc142018-11-23 10:17:28 +0530824 party_account_currency = get_party_account_currency(party_type, party, d.company)
Rushabh Mehta919a74a2017-06-22 16:37:04 +0530825
Ankush Menat494bd9e2022-03-28 18:52:46 +0530826 if party_account_currency == company_default_currency:
827 billing_this_year = flt(
828 company_wise_billing_this_year.get(d.company, {}).get("base_grand_total")
829 )
deepeshgarg007920dc142018-11-23 10:17:28 +0530830 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530831 billing_this_year = flt(company_wise_billing_this_year.get(d.company, {}).get("grand_total"))
deepeshgarg007920dc142018-11-23 10:17:28 +0530832
833 total_unpaid = flt(company_wise_total_unpaid.get(d.company))
834
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530835 if loyalty_point_details:
836 loyalty_points = loyalty_point_details.get(d.company)
837
deepeshgarg007920dc142018-11-23 10:17:28 +0530838 info = {}
839 info["billing_this_year"] = flt(billing_this_year) if billing_this_year else 0
840 info["currency"] = party_account_currency
841 info["total_unpaid"] = flt(total_unpaid) if total_unpaid else 0
842 info["company"] = d.company
843
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530844 if party_type == "Customer" and loyalty_point_details:
845 info["loyalty_points"] = loyalty_points
846
deepeshgarg007920dc142018-11-23 10:17:28 +0530847 if party_type == "Supplier":
848 info["total_unpaid"] = -1 * info["total_unpaid"]
849
850 company_wise_info.append(info)
851
852 return company_wise_info
tundebabzy40a02762017-10-25 07:54:34 +0100853
Ankush Menat494bd9e2022-03-28 18:52:46 +0530854
Raffael Meyerb91bb172023-06-08 16:19:09 +0200855def get_party_shipping_address(doctype: str, name: str) -> Optional[str]:
tundebabzy40a02762017-10-25 07:54:34 +0100856 """
857 Returns an Address name (best guess) for the given doctype and name for which `address_type == 'Shipping'` is true.
858 and/or `is_shipping_address = 1`.
859
860 It returns an empty string if there is no matching record.
861
862 :param doctype: Party Doctype
863 :param name: Party name
864 :return: String
865 """
Raffael Meyerb91bb172023-06-08 16:19:09 +0200866 shipping_addresses = frappe.get_all(
867 "Address",
868 filters=[
869 ["Dynamic Link", "link_doctype", "=", doctype],
870 ["Dynamic Link", "link_name", "=", name],
871 ["disabled", "=", 0],
872 ],
873 or_filters=[
874 ["is_shipping_address", "=", 1],
875 ["address_type", "=", "Shipping"],
876 ],
877 pluck="name",
878 limit=1,
879 order_by="is_shipping_address DESC",
tundebabzy40a02762017-10-25 07:54:34 +0100880 )
Raffael Meyerb91bb172023-06-08 16:19:09 +0200881
882 return shipping_addresses[0] if shipping_addresses else None
Rohit Waghchaureaffeb3d2019-01-15 17:38:31 +0530883
Ankush Menat494bd9e2022-03-28 18:52:46 +0530884
885def get_partywise_advanced_payment_amount(
Nabin Hait3504bf72023-05-29 09:23:40 +0530886 party_type, posting_date=None, future_payment=0, company=None, party=None
Ankush Menat494bd9e2022-03-28 18:52:46 +0530887):
Rohit Waghchaure4ed7d032019-03-25 15:37:25 +0530888 cond = "1=1"
889 if posting_date:
Deepesh Garged2c1802020-05-27 12:46:12 +0530890 if future_payment:
Nabin Hait3504bf72023-05-29 09:23:40 +0530891 cond = "(posting_date <= '{0}' OR DATE(creation) <= '{0}')" "".format(posting_date)
Deepesh Garged2c1802020-05-27 12:46:12 +0530892 else:
UrvashiKishnani810a3612021-03-02 08:20:03 +0400893 cond = "posting_date <= '{0}'".format(posting_date)
Deepesh Garged2c1802020-05-27 12:46:12 +0530894
Saqib39805912020-05-01 18:15:13 +0530895 if company:
UrvashiKishnani810a3612021-03-02 08:20:03 +0400896 cond += "and company = {0}".format(frappe.db.escape(company))
Rohit Waghchaure4ed7d032019-03-25 15:37:25 +0530897
Nabin Hait3504bf72023-05-29 09:23:40 +0530898 if party:
899 cond += "and party = {0}".format(frappe.db.escape(party))
900
Ankush Menat494bd9e2022-03-28 18:52:46 +0530901 data = frappe.db.sql(
902 """ SELECT party, sum({0}) as amount
UrvashiKishnani810a3612021-03-02 08:20:03 +0400903 FROM `tabGL Entry`
Rohit Waghchaure1a6e0152019-03-19 15:06:01 +0530904 WHERE
UrvashiKishnani810a3612021-03-02 08:20:03 +0400905 party_type = %s and against_voucher is null
906 and is_cancelled = 0
Ankush Menat494bd9e2022-03-28 18:52:46 +0530907 and {1} GROUP BY party""".format(
908 ("credit") if party_type == "Customer" else "debit", cond
909 ),
910 party_type,
911 )
Rohit Waghchaureaffeb3d2019-01-15 17:38:31 +0530912 if data:
hendrikc257ce82019-09-05 16:44:09 +0700913 return frappe._dict(data)
Ronel Cabrerafcb54762019-11-18 17:00:07 +0800914
Ankush Menat494bd9e2022-03-28 18:52:46 +0530915
Raffael Meyerb91bb172023-06-08 16:19:09 +0200916def get_default_contact(doctype: str, name: str) -> Optional[str]:
Deepesh Gargcf9347d2020-03-31 17:28:43 +0530917 """
Raffael Meyerb91bb172023-06-08 16:19:09 +0200918 Returns contact name only if there is a primary contact for given doctype and name.
919
920 Else returns None
921
922 :param doctype: Party Doctype
923 :param name: Party name
924 :return: String
Ronel Cabrerafcb54762019-11-18 17:00:07 +0800925 """
Raffael Meyerb91bb172023-06-08 16:19:09 +0200926 contacts = frappe.get_all(
927 "Contact",
928 filters=[
929 ["Dynamic Link", "link_doctype", "=", doctype],
930 ["Dynamic Link", "link_name", "=", name],
931 ],
932 or_filters=[
933 ["is_primary_contact", "=", 1],
934 ["is_billing_contact", "=", 1],
935 ],
936 pluck="name",
937 limit=1,
938 order_by="is_primary_contact DESC, is_billing_contact DESC",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530939 )
Raffael Meyerb91bb172023-06-08 16:19:09 +0200940
941 return contacts[0] if contacts else None
Deepesh Gargbc347372022-05-25 15:42:47 +0530942
943
944def add_party_account(party_type, party, company, account):
945 doc = frappe.get_doc(party_type, party)
946 account_exists = False
947 for d in doc.get("accounts"):
948 if d.account == account:
949 account_exists = True
950
951 if not account_exists:
952 accounts = {"company": company, "account": account}
953
954 doc.append("accounts", accounts)
955
956 doc.save()