blob: 37a18d80e94a28648548e148cc59384fb460fa85 [file] [log] [blame]
Anand Doshi885e0742015-03-03 14:55:30 +05301# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05302# License: GNU General Public License v3. See license.txt
Nabin Hait2df4d542013-01-29 11:34:39 +05303
Chillar Anand915b3432021-09-02 16:44:59 +05304
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08005import json
Chillar Anand915b3432021-09-02 16:44:59 +05306
7import frappe
ruthra kumar81cd7872023-04-27 09:46:54 +05308from frappe import _, bold, qb, throw
Chillar Anand915b3432021-09-02 16:44:59 +05309from frappe.model.workflow import get_workflow_name, is_transition_condition_satisfied
Gursheen Anand74619262023-06-02 17:13:51 +053010from frappe.query_builder.custom import ConstantColumn
Gursheen Anand4ee16372023-06-08 13:15:23 +053011from frappe.query_builder.functions import Abs, Sum
Chillar Anand915b3432021-09-02 16:44:59 +053012from frappe.utils import (
13 add_days,
14 add_months,
15 cint,
16 flt,
17 fmt_money,
18 formatdate,
19 get_last_day,
20 get_link_to_form,
21 getdate,
22 nowdate,
GangaManojd24cfff2021-10-28 20:06:48 +053023 today,
Chillar Anand915b3432021-09-02 16:44:59 +053024)
Chillar Anand915b3432021-09-02 16:44:59 +053025
26import erpnext
27from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import (
28 get_accounting_dimensions,
29)
30from erpnext.accounts.doctype.pricing_rule.utils import (
31 apply_pricing_rule_for_free_items,
32 apply_pricing_rule_on_transaction,
33 get_applied_pricing_rules,
34)
35from erpnext.accounts.party import (
36 get_party_account,
37 get_party_account_currency,
Deepesh Garga7f15a02021-12-12 21:09:11 +053038 get_party_gle_currency,
Chillar Anand915b3432021-09-02 16:44:59 +053039 validate_party_frozen_disabled,
40)
ruthra kumar1ea1bfe2023-07-26 16:19:38 +053041from erpnext.accounts.utils import (
42 create_gain_loss_journal,
43 get_account_currency,
44 get_fiscal_years,
45 validate_fiscal_year,
46)
Chillar Anand915b3432021-09-02 16:44:59 +053047from erpnext.buying.utils import update_last_purchase_rate
48from erpnext.controllers.print_settings import (
49 set_print_templates_for_item_table,
50 set_print_templates_for_taxes,
51)
52from erpnext.controllers.sales_and_purchase_return import validate_return
53from erpnext.exceptions import InvalidCurrency
54from erpnext.setup.utils import get_exchange_rate
Ankush Menat10583eb2022-06-17 12:13:27 +053055from erpnext.stock.doctype.item.item import get_uom_conv_factor
Marica3dee5272020-06-23 10:33:47 +053056from erpnext.stock.doctype.packed_item.packed_item import make_packing_list
Chillar Anand915b3432021-09-02 16:44:59 +053057from erpnext.stock.get_item_details import (
58 _get_item_tax_template,
59 get_conversion_factor,
60 get_item_details,
61 get_item_tax_map,
62 get_item_warehouse,
63)
Sagar Vora4205f562023-07-24 18:37:36 +053064from erpnext.utilities.regional import temporary_flag
Chillar Anand915b3432021-09-02 16:44:59 +053065from erpnext.utilities.transaction_base import TransactionBase
66
Nabin Hait1d218422015-07-17 15:19:02 +053067
Ankush Menat494bd9e2022-03-28 18:52:46 +053068class AccountMissingError(frappe.ValidationError):
69 pass
marination53b1a9a2020-11-03 15:45:25 +053070
Ankush Menat494bd9e2022-03-28 18:52:46 +053071
72force_item_fields = (
73 "item_group",
74 "brand",
75 "stock_uom",
76 "is_fixed_asset",
77 "item_tax_rate",
78 "pricing_rules",
79 "weight_per_unit",
80 "weight_uom",
81 "total_weight",
82)
83
Doridel Cahanap6f06cc22018-05-17 16:28:58 +080084
Nabin Haitbf495c92013-01-30 12:49:08 +053085class AccountsController(TransactionBase):
Nabin Hait7eba1a32017-10-02 15:59:27 +053086 def __init__(self, *args, **kwargs):
87 super(AccountsController, self).__init__(*args, **kwargs)
Anand Doshi979326b2015-09-11 16:22:37 +053088
prssanna71e5b602020-10-29 14:19:34 +053089 def get_print_settings(self):
90 print_setting_fields = []
Ankush Menat494bd9e2022-03-28 18:52:46 +053091 items_field = self.meta.get_field("items")
prssanna71e5b602020-10-29 14:19:34 +053092
Ankush Menat494bd9e2022-03-28 18:52:46 +053093 if items_field and items_field.fieldtype == "Table":
94 print_setting_fields += ["compact_item_print", "print_uom_after_quantity"]
prssanna71e5b602020-10-29 14:19:34 +053095
Ankush Menat494bd9e2022-03-28 18:52:46 +053096 taxes_field = self.meta.get_field("taxes")
97 if taxes_field and taxes_field.fieldtype == "Table":
98 print_setting_fields += ["print_taxes_with_zero_amount"]
prssanna71e5b602020-10-29 14:19:34 +053099
100 return print_setting_fields
101
Nabin Hait4ffd7f32015-08-27 12:28:36 +0530102 @property
103 def company_currency(self):
104 if not hasattr(self, "__company_currency"):
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530105 self.__company_currency = erpnext.get_company_currency(self.company)
Anand Doshi979326b2015-09-11 16:22:37 +0530106
Nabin Hait4ffd7f32015-08-27 12:28:36 +0530107 return self.__company_currency
Anand Doshi979326b2015-09-11 16:22:37 +0530108
Rohit Waghchaure7d529892016-10-06 14:35:04 +0530109 def onload(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530110 self.set_onload(
111 "make_payment_via_journal_entry",
112 frappe.db.get_single_value("Accounts Settings", "make_payment_via_journal_entry"),
113 )
Nabin Hait0551f7b2017-11-21 19:58:16 +0530114
tundee52bb822017-09-25 09:02:23 +0100115 if self.is_new():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530116 relevant_docs = (
117 "Quotation",
118 "Purchase Order",
119 "Sales Order",
120 "Purchase Invoice",
121 "Sales Invoice",
122 )
tundee52bb822017-09-25 09:02:23 +0100123 if self.doctype in relevant_docs:
124 self.set_payment_schedule()
Rohit Waghchaure7d529892016-10-06 14:35:04 +0530125
tundebabzyad08d4c2018-05-16 07:01:41 +0100126 def ensure_supplier_is_not_blocked(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530127 is_supplier_payment = self.doctype == "Payment Entry" and self.party_type == "Supplier"
128 is_buying_invoice = self.doctype in ["Purchase Invoice", "Purchase Order"]
tundebabzyad08d4c2018-05-16 07:01:41 +0100129 supplier = None
130 supplier_name = None
131
132 if is_buying_invoice or is_supplier_payment:
133 supplier_name = self.supplier if is_buying_invoice else self.party
Ankush Menat494bd9e2022-03-28 18:52:46 +0530134 supplier = frappe.get_doc("Supplier", supplier_name)
tundebabzyad08d4c2018-05-16 07:01:41 +0100135
136 if supplier and supplier_name and supplier.on_hold:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530137 if (is_buying_invoice and supplier.hold_type in ["All", "Invoices"]) or (
138 is_supplier_payment and supplier.hold_type in ["All", "Payments"]
139 ):
tundebabzyad08d4c2018-05-16 07:01:41 +0100140 if not supplier.release_date or getdate(nowdate()) <= supplier.release_date:
141 frappe.msgprint(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530142 _("{0} is blocked so this transaction cannot proceed").format(supplier_name),
143 raise_exception=1,
144 )
tundebabzyad08d4c2018-05-16 07:01:41 +0100145
Saurabh6f753182013-03-20 12:55:28 +0530146 def validate(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530147 if not self.get("is_return") and not self.get("is_debit_note"):
Deepesh Gargd301d262019-07-31 15:58:19 +0530148 self.validate_qty_is_not_zero()
149
nabinhait23cce732014-07-03 12:25:06 +0530150 if self.get("_action") and self._action != "update_after_submit":
Nabin Hait704a4532014-06-05 16:55:31 +0530151 self.set_missing_values(for_validate=True)
tunde62af5c52017-09-22 15:16:38 +0100152
tundebabzyad08d4c2018-05-16 07:01:41 +0100153 self.ensure_supplier_is_not_blocked()
154
Nabin Haitcfecd2b2013-07-11 17:49:18 +0530155 self.validate_date_with_fiscal_year()
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530156 self.validate_party_accounts()
157
Deepesh Gargb4be2922021-01-28 13:09:56 +0530158 self.validate_inter_company_reference()
159
Ankush Menat3714e362022-05-16 18:09:14 +0530160 self.disable_pricing_rule_on_internal_transfer()
Deepesh Garg8d30ebb2022-11-05 20:51:15 +0530161 self.disable_tax_included_prices_for_internal_transfer()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530162 self.set_incoming_rate()
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530163
Anand Doshi3543f302013-05-24 19:25:01 +0530164 if self.meta.get_field("currency"):
Anand Doshi923d41d2013-05-28 17:23:36 +0530165 self.calculate_taxes_and_totals()
Rohit Waghchaure6087fe12016-04-09 14:31:09 +0530166
Nabin Hait1d218422015-07-17 15:19:02 +0530167 if not self.meta.get_field("is_return") or not self.is_return:
168 self.validate_value("base_grand_total", ">=", 0)
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530169
Nabin Hait3cf67a42015-07-24 13:26:36 +0530170 validate_return(self)
Anand Doshi3543f302013-05-24 19:25:01 +0530171 self.set_total_in_words()
Anand Doshid2946502014-04-08 20:10:03 +0530172
tunde62af5c52017-09-22 15:16:38 +0100173 self.validate_all_documents_schedule()
Anand Doshid2946502014-04-08 20:10:03 +0530174
ankitjavalkarwork6c29d872014-10-06 13:20:53 +0530175 if self.meta.get_field("taxes_and_charges"):
176 self.validate_enabled_taxes_and_charges()
Nabin Haita2426fc2018-01-15 17:45:46 +0530177 self.validate_tax_account_company()
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530178
Neil Trini Lasrado3fbbb712015-07-17 12:10:12 +0530179 self.validate_party()
Nabin Hait895029d2015-08-20 14:55:39 +0530180 self.validate_currency()
Deepesh Garg80c85dd2021-08-12 15:39:07 +0530181 self.validate_party_account_currency()
Rushabh Mehta2cb7a9f2016-06-15 16:45:03 +0530182
Ankush Menat494bd9e2022-03-28 18:52:46 +0530183 if self.doctype in ["Purchase Invoice", "Sales Invoice"]:
184 pos_check_field = "is_pos" if self.doctype == "Sales Invoice" else "is_paid"
Nabin Hait4a994d42019-04-25 17:47:26 +0530185 if cint(self.allocate_advances_automatically) and not cint(self.get(pos_check_field)):
Nabin Hait041a5c22018-08-01 18:07:39 +0530186 self.set_advances()
187
Saqiba20999c2021-07-12 14:33:23 +0530188 self.set_advance_gain_or_loss()
189
Nabin Hait041a5c22018-08-01 18:07:39 +0530190 if self.is_return:
191 self.validate_qty()
Nabin Haitacdd5082019-12-04 15:30:01 +0530192 else:
193 self.validate_deferred_start_and_end_date()
rohitwaghchaure70489252018-06-11 12:02:14 +0530194
Deepesh Garg9bf5f762022-04-06 17:33:46 +0530195 self.validate_deferred_income_expense_account()
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530196 self.set_inter_company_account()
197
Ankush Menat494bd9e2022-03-28 18:52:46 +0530198 if self.doctype == "Purchase Invoice":
Deepesh Garg7f06c8c2021-11-26 10:27:57 +0530199 self.calculate_paid_amount()
200 # apply tax withholding only if checked and applicable
201 self.set_tax_withholding()
202
Gauravf1e28e02019-02-13 16:46:24 +0530203 validate_regional(self)
Deepesh Garg7c300852020-12-26 20:14:51 +0530204
Saqib Ansaric5782b02022-01-27 20:09:56 +0530205 validate_einvoice_fields(self)
206
Deepesh Gargb741ae12022-12-02 17:14:06 +0530207 if self.doctype != "Material Request" and not self.ignore_pricing_rule:
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530208 apply_pricing_rule_on_transaction(self)
Gauravf1e28e02019-02-13 16:46:24 +0530209
Saqib Ansaric5782b02022-01-27 20:09:56 +0530210 def before_cancel(self):
211 validate_einvoice_fields(self)
212
Saqib8e556772021-01-28 12:26:45 +0530213 def on_trash(self):
ruthra kumarc722f282023-02-19 12:09:10 +0530214 # delete references in 'Repost Payment Ledger'
215 rpi = frappe.qb.DocType("Repost Payment Ledger Items")
216 frappe.qb.from_(rpi).delete().where(
217 (rpi.voucher_type == self.doctype) & (rpi.voucher_no == self.name)
218 ).run()
219
Saqib8e556772021-01-28 12:26:45 +0530220 # delete sl and gl entries on deletion of transaction
Ankush Menat494bd9e2022-03-28 18:52:46 +0530221 if frappe.db.get_single_value("Accounts Settings", "delete_linked_ledger_entries"):
ruthra kumar70313df2022-09-08 18:53:30 +0530222 ple = frappe.qb.DocType("Payment Ledger Entry")
223 frappe.qb.from_(ple).delete().where(
224 (ple.voucher_type == self.doctype) & (ple.voucher_no == self.name)
225 ).run()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530226 frappe.db.sql(
227 "delete from `tabGL Entry` where voucher_type=%s and voucher_no=%s", (self.doctype, self.name)
228 )
229 frappe.db.sql(
230 "delete from `tabStock Ledger Entry` where voucher_type=%s and voucher_no=%s",
231 (self.doctype, self.name),
232 )
Nabin Hait0551f7b2017-11-21 19:58:16 +0530233
Deepesh Garg9bf5f762022-04-06 17:33:46 +0530234 def validate_deferred_income_expense_account(self):
235 field_map = {
236 "Sales Invoice": "deferred_revenue_account",
237 "Purchase Invoice": "deferred_expense_account",
238 }
239
240 for item in self.get("items"):
241 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
242 if not item.get(field_map.get(self.doctype)):
Daizy Modi4efc9472022-11-07 09:21:03 +0530243 default_deferred_account = frappe.get_cached_value(
Deepesh Garg9bf5f762022-04-06 17:33:46 +0530244 "Company", self.company, "default_" + field_map.get(self.doctype)
245 )
246 if not default_deferred_account:
247 frappe.throw(
248 _(
249 "Row #{0}: Please update deferred revenue/expense account in item row or default account in company master"
250 ).format(item.idx)
251 )
252 else:
253 item.set(field_map.get(self.doctype), default_deferred_account)
254
Deepesh Gargfa152212022-11-28 19:22:35 +0530255 def validate_auto_repeat_subscription_dates(self):
Deepesh Garg6a47fb62022-11-28 22:47:44 +0530256 if (
257 self.get("from_date")
258 and self.get("to_date")
259 and getdate(self.from_date) > getdate(self.to_date)
260 ):
Deepesh Gargfa152212022-11-28 19:22:35 +0530261 frappe.throw(_("To Date cannot be before From Date"), title=_("Invalid Auto Repeat Date"))
262
Nabin Haitacdd5082019-12-04 15:30:01 +0530263 def validate_deferred_start_and_end_date(self):
264 for d in self.items:
265 if d.get("enable_deferred_revenue") or d.get("enable_deferred_expense"):
266 if not (d.service_start_date and d.service_end_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530267 frappe.throw(
268 _("Row #{0}: Service Start and End Date is required for deferred accounting").format(d.idx)
269 )
Nabin Haitacdd5082019-12-04 15:30:01 +0530270 elif getdate(d.service_start_date) > getdate(d.service_end_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530271 frappe.throw(
272 _("Row #{0}: Service Start Date cannot be greater than Service End Date").format(d.idx)
273 )
Nabin Haitacdd5082019-12-04 15:30:01 +0530274 elif getdate(self.posting_date) > getdate(d.service_end_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530275 frappe.throw(
276 _("Row #{0}: Service End Date cannot be before Invoice Posting Date").format(d.idx)
277 )
Nabin Haitacdd5082019-12-04 15:30:01 +0530278
tunde62af5c52017-09-22 15:16:38 +0100279 def validate_invoice_documents_schedule(self):
Nabin Hait0551f7b2017-11-21 19:58:16 +0530280 self.validate_payment_schedule_dates()
281 self.set_due_date()
Nabin Hait0551f7b2017-11-21 19:58:16 +0530282 self.set_payment_schedule()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530283 if not self.get("ignore_default_payment_terms_template"):
Deepesh Garg5c758942023-04-16 17:11:24 +0530284 self.validate_payment_schedule_amount()
Deepesh Gargbd709f82021-08-23 19:05:52 +0530285 self.validate_due_date()
tunde62af5c52017-09-22 15:16:38 +0100286 self.validate_advance_entries()
287
288 def validate_non_invoice_documents_schedule(self):
Nabin Hait0551f7b2017-11-21 19:58:16 +0530289 self.set_payment_schedule()
Nabin Hait2f9f4f92017-12-20 12:24:59 +0530290 self.validate_payment_schedule_dates()
Nabin Hait0551f7b2017-11-21 19:58:16 +0530291 self.validate_payment_schedule_amount()
tunde62af5c52017-09-22 15:16:38 +0100292
293 def validate_all_documents_schedule(self):
294 if self.doctype in ("Sales Invoice", "Purchase Invoice") and not self.is_return:
295 self.validate_invoice_documents_schedule()
296 elif self.doctype in ("Quotation", "Purchase Order", "Sales Order"):
297 self.validate_non_invoice_documents_schedule()
298
prssanna71e5b602020-10-29 14:19:34 +0530299 def before_print(self, settings=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530300 if self.doctype in [
301 "Purchase Order",
302 "Sales Order",
303 "Sales Invoice",
304 "Purchase Invoice",
305 "Supplier Quotation",
306 "Purchase Receipt",
307 "Delivery Note",
308 "Quotation",
309 ]:
KanchanChauhan49a50fe2016-11-18 13:57:53 +0530310 if self.get("group_same_items"):
311 self.group_similar_items()
312
Zarrar5be6d192018-11-08 12:16:26 +0530313 df = self.meta.get_field("discount_amount")
314 if self.get("discount_amount") and hasattr(self, "taxes") and not len(self.taxes):
315 df.set("print_hide", 0)
316 self.discount_amount = -self.discount_amount
317 else:
318 df.set("print_hide", 1)
319
prssanna71e5b602020-10-29 14:19:34 +0530320 set_print_templates_for_item_table(self, settings)
321 set_print_templates_for_taxes(self, settings)
322
Mangesh-Khairnar7bcb24e2019-09-11 10:49:33 +0530323 def calculate_paid_amount(self):
Saurabh43520f92016-03-21 18:32:48 +0530324 if hasattr(self, "is_pos") or hasattr(self, "is_paid"):
325 is_paid = self.get("is_pos") or self.get("is_paid")
Mangesh-Khairnar7bcb24e2019-09-11 10:49:33 +0530326
327 if is_paid:
328 if not self.cash_bank_account:
329 # show message that the amount is not paid
Ankush Menat494bd9e2022-03-28 18:52:46 +0530330 frappe.throw(
331 _("Note: Payment Entry will not be created since 'Cash or Bank Account' was not specified")
332 )
Marica23d7b092019-09-25 17:17:36 +0530333
Mangesh-Khairnar7bcb24e2019-09-11 10:49:33 +0530334 if cint(self.is_return) and self.grand_total > self.paid_amount:
335 self.paid_amount = flt(flt(self.grand_total), self.precision("paid_amount"))
336
337 elif not flt(self.paid_amount) and flt(self.outstanding_amount) > 0:
338 self.paid_amount = flt(flt(self.outstanding_amount), self.precision("paid_amount"))
339
Ankush Menat494bd9e2022-03-28 18:52:46 +0530340 self.base_paid_amount = flt(
341 self.paid_amount * self.conversion_rate, self.precision("base_paid_amount")
342 )
Saurabh43520f92016-03-21 18:32:48 +0530343
Anand Doshiabc10032013-06-14 17:44:03 +0530344 def set_missing_values(self, for_validate=False):
Rohit Waghchaure5d97d892016-05-12 12:58:29 +0530345 if frappe.flags.in_test:
tunde62af5c52017-09-22 15:16:38 +0100346 for fieldname in ["posting_date", "transaction_date"]:
Rohit Waghchaure5d97d892016-05-12 12:58:29 +0530347 if self.meta.get_field(fieldname) and not self.get(fieldname):
348 self.set(fieldname, today())
349 break
Anand Doshid2946502014-04-08 20:10:03 +0530350
Nabin Hait3237c752015-02-17 11:11:11 +0530351 def calculate_taxes_and_totals(self):
Nabin Haitfe81da22015-02-18 12:23:18 +0530352 from erpnext.controllers.taxes_and_totals import calculate_taxes_and_totals
Ankush Menat494bd9e2022-03-28 18:52:46 +0530353
Nabin Haitfe81da22015-02-18 12:23:18 +0530354 calculate_taxes_and_totals(self)
Nabin Hait3237c752015-02-17 11:11:11 +0530355
Raffael Meyere10ab162021-11-30 13:24:18 +0100356 if self.doctype in (
Ankush Menat494bd9e2022-03-28 18:52:46 +0530357 "Sales Order",
358 "Delivery Note",
359 "Sales Invoice",
360 "POS Invoice",
Raffael Meyere10ab162021-11-30 13:24:18 +0100361 ):
Nabin Hait3237c752015-02-17 11:11:11 +0530362 self.calculate_commission()
363 self.calculate_contribution()
364
Nabin Haitcfecd2b2013-07-11 17:49:18 +0530365 def validate_date_with_fiscal_year(self):
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800366 if self.meta.get_field("fiscal_year"):
Rohan Bansal1e3a3b22021-05-26 15:18:10 +0530367 date_field = None
Nabin Haitcfecd2b2013-07-11 17:49:18 +0530368 if self.meta.get_field("posting_date"):
369 date_field = "posting_date"
370 elif self.meta.get_field("transaction_date"):
371 date_field = "transaction_date"
Anand Doshid2946502014-04-08 20:10:03 +0530372
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530373 if date_field and self.get(date_field):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530374 validate_fiscal_year(
375 self.get(date_field), self.fiscal_year, self.company, self.meta.get_label(date_field), self
376 )
Anand Doshid2946502014-04-08 20:10:03 +0530377
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530378 def validate_party_accounts(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530379 if self.doctype not in ("Sales Invoice", "Purchase Invoice"):
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530380 return
381
Ankush Menat494bd9e2022-03-28 18:52:46 +0530382 if self.doctype == "Sales Invoice":
383 party_account_field = "debit_to"
384 item_field = "income_account"
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530385 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530386 party_account_field = "credit_to"
387 item_field = "expense_account"
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530388
Ankush Menat494bd9e2022-03-28 18:52:46 +0530389 for item in self.get("items"):
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530390 if item.get(item_field) == self.get(party_account_field):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530391 frappe.throw(
392 _("Row {0}: {1} {2} cannot be same as {3} (Party Account) {4}").format(
393 item.idx,
394 frappe.bold(frappe.unscrub(item_field)),
395 item.get(item_field),
396 frappe.bold(frappe.unscrub(party_account_field)),
397 self.get(party_account_field),
398 )
399 )
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530400
Deepesh Gargb4be2922021-01-28 13:09:56 +0530401 def validate_inter_company_reference(self):
Rohit Waghchaure38aaba52023-05-13 13:00:05 +0530402 if self.get("is_return"):
403 return
404
Rohit Waghchaureb4a102d2022-09-06 16:22:00 +0530405 if self.doctype not in ("Purchase Invoice", "Purchase Receipt"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530406 return
407
408 if self.is_internal_transfer():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530409 if not (
410 self.get("inter_company_reference")
411 or self.get("inter_company_invoice_reference")
412 or self.get("inter_company_order_reference")
Deepesh Garg906ad102023-01-15 17:32:57 +0530413 ) and not self.get("is_return"):
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530414 msg = _("Internal Sale or Delivery Reference missing.")
Deepesh Gargb4be2922021-01-28 13:09:56 +0530415 msg += _("Please create purchase from internal sale or delivery document itself")
416 frappe.throw(msg, title=_("Internal Sales Reference Missing"))
417
Rohit Waghchaure19911b42023-04-21 16:49:48 +0530418 label = "Delivery Note Item" if self.doctype == "Purchase Receipt" else "Sales Invoice Item"
419
420 field = frappe.scrub(label)
421
422 for row in self.get("items"):
423 if not row.get(field):
424 msg = f"At Row {row.idx}: The field {bold(label)} is mandatory for internal transfer"
425 frappe.throw(_(msg), title=_("Internal Transfer Reference Missing"))
426
Ankush Menat3714e362022-05-16 18:09:14 +0530427 def disable_pricing_rule_on_internal_transfer(self):
428 if not self.get("ignore_pricing_rule") and self.is_internal_transfer():
429 self.ignore_pricing_rule = 1
430 frappe.msgprint(
431 _("Disabled pricing rules since this {} is an internal transfer").format(self.doctype),
432 alert=1,
433 )
434
Deepesh Garg8d30ebb2022-11-05 20:51:15 +0530435 def disable_tax_included_prices_for_internal_transfer(self):
436 if self.is_internal_transfer():
437 tax_updated = False
438 for tax in self.get("taxes"):
439 if tax.get("included_in_print_rate"):
440 tax.included_in_print_rate = 0
441 tax_updated = True
442
443 if tax_updated:
444 frappe.msgprint(
445 _("Disabled tax included prices since this {} is an internal transfer").format(self.doctype),
446 alert=1,
447 )
448
Nabin Haite9daefe2014-08-27 16:46:33 +0530449 def validate_due_date(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530450 if self.get("is_pos"):
451 return
rohitwaghchaureea943c62018-07-06 12:28:58 +0530452
Nabin Haite9daefe2014-08-27 16:46:33 +0530453 from erpnext.accounts.party import validate_due_date
Ankush Menat494bd9e2022-03-28 18:52:46 +0530454
Nabin Haite9daefe2014-08-27 16:46:33 +0530455 if self.doctype == "Sales Invoice":
Nabin Hait04d244a2015-07-22 17:47:49 +0530456 if not self.due_date:
457 frappe.throw(_("Due Date is mandatory"))
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530458
Ankush Menat494bd9e2022-03-28 18:52:46 +0530459 validate_due_date(
460 self.posting_date,
461 self.due_date,
462 "Customer",
463 self.customer,
464 self.company,
465 self.payment_terms_template,
466 )
Nabin Haite9daefe2014-08-27 16:46:33 +0530467 elif self.doctype == "Purchase Invoice":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530468 validate_due_date(
469 self.bill_date or self.posting_date,
470 self.due_date,
471 "Supplier",
472 self.supplier,
473 self.company,
474 self.bill_date,
475 self.payment_terms_template,
476 )
Nabin Haite9daefe2014-08-27 16:46:33 +0530477
Nabin Hait096d3632013-10-17 17:01:14 +0530478 def set_price_list_currency(self, buying_or_selling):
Nabin Hait1cc55fb2016-12-08 14:09:23 +0530479 if self.meta.get_field("posting_date"):
Nabin Hait288a18e2016-12-08 15:36:23 +0530480 transaction_date = self.posting_date
Nabin Hait1cc55fb2016-12-08 14:09:23 +0530481 else:
Nabin Hait288a18e2016-12-08 15:36:23 +0530482 transaction_date = self.transaction_date
Rushabh Mehta66958302017-01-16 16:57:53 +0530483
Rushabh Mehta4a404e92013-08-09 18:11:35 +0530484 if self.meta.get_field("currency"):
Nabin Hait7a75e102013-09-17 10:21:20 +0530485 # price list part
Shreya3f778522018-05-15 16:59:20 +0530486 if buying_or_selling.lower() == "selling":
487 fieldname = "selling_price_list"
488 args = "for_selling"
489 else:
490 fieldname = "buying_price_list"
491 args = "for_buying"
492
Anand Doshif78d1ae2014-03-28 13:55:00 +0530493 if self.meta.get_field(fieldname) and self.get(fieldname):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530494 self.price_list_currency = frappe.db.get_value("Price List", self.get(fieldname), "currency")
Anand Doshid2946502014-04-08 20:10:03 +0530495
Nabin Hait6e439a52015-08-28 19:24:22 +0530496 if self.price_list_currency == self.company_currency:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530497 self.plc_conversion_rate = 1.0
Nabin Hait11f41952013-09-24 14:36:55 +0530498
Anand Doshif78d1ae2014-03-28 13:55:00 +0530499 elif not self.plc_conversion_rate:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530500 self.plc_conversion_rate = get_exchange_rate(
501 self.price_list_currency, self.company_currency, transaction_date, args
502 )
Anand Doshid2946502014-04-08 20:10:03 +0530503
Nabin Hait7a75e102013-09-17 10:21:20 +0530504 # currency
Anand Doshif78d1ae2014-03-28 13:55:00 +0530505 if not self.currency:
506 self.currency = self.price_list_currency
507 self.conversion_rate = self.plc_conversion_rate
Nabin Hait6e439a52015-08-28 19:24:22 +0530508 elif self.currency == self.company_currency:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530509 self.conversion_rate = 1.0
510 elif not self.conversion_rate:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530511 self.conversion_rate = get_exchange_rate(
512 self.currency, self.company_currency, transaction_date, args
513 )
Nabin Hait7a75e102013-09-17 10:21:20 +0530514
Nabin Haitcccc45e2016-10-05 17:15:43 +0530515 def set_missing_item_details(self, for_validate=False):
Anand Doshi3543f302013-05-24 19:25:01 +0530516 """set missing item values"""
Nabin Haitf37d43d2017-07-18 12:14:42 +0530517 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530518
Nabin Haitdd38a262014-12-26 13:15:21 +0530519 if hasattr(self, "items"):
Nabin Hait444f9562014-06-20 15:59:49 +0530520 parent_dict = {}
Pratik Vyasf7daab72014-04-10 17:53:30 +0530521 for fieldname in self.meta.get_valid_columns():
522 parent_dict[fieldname] = self.get(fieldname)
523
mbauskara52472c2016-03-05 15:10:25 +0530524 if self.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
525 document_type = "{} Item".format(self.doctype)
mbauskarc97becb2016-01-18 16:28:21 +0530526 parent_dict.update({"document_type": document_type})
527
Nabin Hait34c551d2019-07-03 10:34:31 +0530528 # party_name field used for customer in quotation
Ankush Menat494bd9e2022-03-28 18:52:46 +0530529 if (
530 self.doctype == "Quotation"
531 and self.quotation_to == "Customer"
532 and parent_dict.get("party_name")
533 ):
Nabin Hait34c551d2019-07-03 10:34:31 +0530534 parent_dict.update({"customer": parent_dict.get("party_name")})
535
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530536 self.pricing_rules = []
Deepesh Garg4c61ee32023-04-02 09:35:27 +0530537
Nabin Haitdd38a262014-12-26 13:15:21 +0530538 for item in self.get("items"):
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530539 if item.get("item_code"):
Nabin Hait444f9562014-06-20 15:59:49 +0530540 args = parent_dict.copy()
541 args.update(item.as_dict())
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530542
Nabin Hait34d28222016-01-19 15:45:49 +0530543 args["doctype"] = self.doctype
544 args["name"] = self.name
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530545 args["child_docname"] = item.name
Ankush Menat494bd9e2022-03-28 18:52:46 +0530546 args["ignore_pricing_rule"] = (
547 self.ignore_pricing_rule if hasattr(self, "ignore_pricing_rule") else 0
548 )
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530549
Nabin Haite2f054c2015-03-09 14:54:37 +0530550 if not args.get("transaction_date"):
551 args["transaction_date"] = args.get("posting_date")
Anand Doshi2b2b6392015-03-20 14:18:09 +0530552
553 if self.get("is_subcontracted"):
554 args["is_subcontracted"] = self.is_subcontracted
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530555
Deepesh Garga7051cb2023-04-14 09:59:42 +0530556 ret = get_item_details(args, self, for_validate=True, overwrite_warehouse=False)
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530557
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530558 for fieldname, value in ret.items():
Anand Doshi602e8252015-11-16 19:05:46 +0530559 if item.meta.get_field(fieldname) and value is not None:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530560 if item.get(fieldname) is None or fieldname in force_item_fields:
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530561 item.set(fieldname, value)
Anand Doshid2946502014-04-08 20:10:03 +0530562
Ankush Menat494bd9e2022-03-28 18:52:46 +0530563 elif fieldname in ["cost_center", "conversion_factor"] and not item.get(fieldname):
Anand Doshi602e8252015-11-16 19:05:46 +0530564 item.set(fieldname, value)
565
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530566 elif fieldname == "serial_no":
Alchez9155e402018-07-09 16:57:42 +0530567 # Ensure that serial numbers are matched against Stock UOM
568 item_conversion_factor = item.get("conversion_factor") or 1.0
569 item_qty = abs(item.get("qty")) * item_conversion_factor
Alchez8f2a0f32018-07-06 14:36:52 +0530570
Ankush Menat494bd9e2022-03-28 18:52:46 +0530571 if item_qty != len(get_serial_nos(item.get("serial_no"))):
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530572 item.set(fieldname, value)
Nabin Haita74468b2014-12-30 18:33:52 +0530573
Saqib Ansariab36b272022-02-09 10:10:17 +0530574 elif (
575 ret.get("pricing_rule_removed")
576 and value is not None
577 and fieldname
578 in [
579 "discount_percentage",
580 "discount_amount",
581 "rate",
582 "margin_rate_or_amount",
583 "margin_type",
584 "remove_free_item",
585 ]
586 ):
Saqib Ansarib8c41e32022-01-20 13:06:08 +0530587 # reset pricing rule fields if pricing_rule_removed
588 item.set(fieldname, value)
589
Ankush Menat494bd9e2022-03-28 18:52:46 +0530590 if self.doctype in ["Purchase Invoice", "Sales Invoice"] and item.meta.get_field(
591 "is_fixed_asset"
592 ):
593 item.set("is_fixed_asset", ret.get("is_fixed_asset", 0))
Rohit Waghchauref6f503a2018-12-19 15:06:44 +0530594
Deepesh Garga60c3082021-05-11 16:38:33 +0530595 # Double check for cost center
596 # Items add via promotional scheme may not have cost center set
Ankush Menat494bd9e2022-03-28 18:52:46 +0530597 if hasattr(item, "cost_center") and not item.get("cost_center"):
598 item.set(
599 "cost_center", self.get("cost_center") or erpnext.get_default_cost_center(self.company)
600 )
Deepesh Garga60c3082021-05-11 16:38:33 +0530601
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530602 if ret.get("pricing_rules"):
603 self.apply_pricing_rule_on_items(item, ret)
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530604 self.set_pricing_rule_details(item, ret)
Ankush Menat10583eb2022-06-17 12:13:27 +0530605 else:
606 # Transactions line item without item code
607
608 uom = item.get("uom")
609 stock_uom = item.get("stock_uom")
610 if bool(uom) != bool(stock_uom): # xor
611 item.stock_uom = item.uom = uom or stock_uom
612
Deepesh Garg61751832022-12-29 10:41:36 +0530613 # UOM cannot be zero so substitute as 1
614 item.conversion_factor = (
615 get_uom_conv_factor(item.get("uom"), item.get("stock_uom"))
616 or item.get("conversion_factor")
617 or 1
618 )
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530619
Nabin Hait14aa9c52016-04-18 15:54:01 +0530620 if self.doctype == "Purchase Invoice":
Nabin Haitcccc45e2016-10-05 17:15:43 +0530621 self.set_expense_account(for_validate)
Nabin Haita3dd72a2014-05-28 12:49:20 +0530622
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530623 def apply_pricing_rule_on_items(self, item, pricing_rule_args):
624 if not pricing_rule_args.get("validate_applied_rule", 0):
625 # if user changed the discount percentage then set user's discount percentage ?
Ankush Menat494bd9e2022-03-28 18:52:46 +0530626 if pricing_rule_args.get("price_or_product_discount") == "Price":
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530627 item.set("pricing_rules", pricing_rule_args.get("pricing_rules"))
Rohit Waghchauref5bd3fa2022-09-16 15:23:10 +0530628 if pricing_rule_args.get("apply_rule_on_other_items"):
629 other_items = json.loads(pricing_rule_args.get("apply_rule_on_other_items"))
630 if other_items and item.item_code not in other_items:
631 return
632
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530633 item.set("discount_percentage", pricing_rule_args.get("discount_percentage"))
634 item.set("discount_amount", pricing_rule_args.get("discount_amount"))
635 if pricing_rule_args.get("pricing_rule_for") == "Rate":
636 item.set("price_list_rate", pricing_rule_args.get("price_list_rate"))
637
638 if item.get("price_list_rate"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530639 item.rate = flt(
640 item.price_list_rate * (1.0 - (flt(item.discount_percentage) / 100.0)),
641 item.precision("rate"),
642 )
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530643
Ankush Menat494bd9e2022-03-28 18:52:46 +0530644 if item.get("discount_amount"):
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530645 item.rate = item.price_list_rate - item.discount_amount
646
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530647 if item.get("apply_discount_on_discounted_rate") and pricing_rule_args.get("rate"):
648 item.rate = pricing_rule_args.get("rate")
649
Ankush Menat494bd9e2022-03-28 18:52:46 +0530650 elif pricing_rule_args.get("free_item_data"):
651 apply_pricing_rule_for_free_items(self, pricing_rule_args.get("free_item_data"))
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530652
653 elif pricing_rule_args.get("validate_applied_rule"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530654 for pricing_rule in get_applied_pricing_rules(item.get("pricing_rules")):
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530655 pricing_rule_doc = frappe.get_cached_doc("Pricing Rule", pricing_rule)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530656 for field in ["discount_percentage", "discount_amount", "rate"]:
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530657 if item.get(field) < pricing_rule_doc.get(field):
658 title = get_link_to_form("Pricing Rule", pricing_rule)
659
Ankush Menat494bd9e2022-03-28 18:52:46 +0530660 frappe.msgprint(
661 _("Row {0}: user has not applied the rule {1} on the item {2}").format(
662 item.idx, frappe.bold(title), frappe.bold(item.item_code)
663 )
664 )
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530665
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530666 def set_pricing_rule_details(self, item_row, args):
667 pricing_rules = get_applied_pricing_rules(args.get("pricing_rules"))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530668 if not pricing_rules:
669 return
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530670
671 for pricing_rule in pricing_rules:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530672 self.append(
673 "pricing_rules",
674 {
675 "pricing_rule": pricing_rule,
676 "item_code": item_row.item_code,
677 "child_docname": item_row.name,
678 "rule_applied": True,
679 },
680 )
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530681
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530682 def set_taxes(self):
683 if not self.meta.get_field("taxes"):
Anand Doshi3543f302013-05-24 19:25:01 +0530684 return
Anand Doshid2946502014-04-08 20:10:03 +0530685
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530686 tax_master_doctype = self.meta.get_field("taxes_and_charges").options
Anand Doshid2946502014-04-08 20:10:03 +0530687
rohitwaghchaure57914f12018-04-24 19:19:47 +0530688 if (self.is_new() or self.is_pos_profile_changed()) and not self.get("taxes"):
rohitwaghchaure505661b2017-12-11 14:52:28 +0530689 if self.company and not self.get("taxes_and_charges"):
Anand Doshi3543f302013-05-24 19:25:01 +0530690 # get the default tax master
Ankush Menat494bd9e2022-03-28 18:52:46 +0530691 self.taxes_and_charges = frappe.db.get_value(
692 tax_master_doctype, {"is_default": 1, "company": self.company}
693 )
Anand Doshid2946502014-04-08 20:10:03 +0530694
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530695 self.append_taxes_from_master(tax_master_doctype)
Anand Doshid2946502014-04-08 20:10:03 +0530696
rohitwaghchaure57914f12018-04-24 19:19:47 +0530697 def is_pos_profile_changed(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530698 if (
699 self.doctype == "Sales Invoice"
700 and self.is_pos
701 and self.pos_profile != frappe.db.get_value("Sales Invoice", self.name, "pos_profile")
702 ):
rohitwaghchaure57914f12018-04-24 19:19:47 +0530703 return True
704
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530705 def append_taxes_from_master(self, tax_master_doctype=None):
706 if self.get("taxes_and_charges"):
Anand Doshi99100a42013-07-04 17:13:53 +0530707 if not tax_master_doctype:
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530708 tax_master_doctype = self.meta.get_field("taxes_and_charges").options
Anand Doshid2946502014-04-08 20:10:03 +0530709
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530710 self.extend("taxes", get_taxes_and_charges(tax_master_doctype, self.get("taxes_and_charges")))
Akhilesh Darjee4cdb7992014-01-30 13:56:57 +0530711
Anand Doshiac32bad2014-04-18 01:30:14 +0530712 def set_other_charges(self):
Nabin Haite7d15362014-12-25 16:01:55 +0530713 self.set("taxes", [])
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530714 self.set_taxes()
Anand Doshid2946502014-04-08 20:10:03 +0530715
ankitjavalkarwork6c29d872014-10-06 13:20:53 +0530716 def validate_enabled_taxes_and_charges(self):
717 taxes_and_charges_doctype = self.meta.get_options("taxes_and_charges")
Daizy Modi4efc9472022-11-07 09:21:03 +0530718 if frappe.get_cached_value(taxes_and_charges_doctype, self.taxes_and_charges, "disabled"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530719 frappe.throw(
720 _("{0} '{1}' is disabled").format(taxes_and_charges_doctype, self.taxes_and_charges)
721 )
ankitjavalkarwork6c29d872014-10-06 13:20:53 +0530722
Nabin Haita2426fc2018-01-15 17:45:46 +0530723 def validate_tax_account_company(self):
724 for d in self.get("taxes"):
725 if d.account_head:
Daizy Modi4efc9472022-11-07 09:21:03 +0530726 tax_account_company = frappe.get_cached_value("Account", d.account_head, "company")
Nabin Haita2426fc2018-01-15 17:45:46 +0530727 if tax_account_company != self.company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530728 frappe.throw(
729 _("Row #{0}: Account {1} does not belong to company {2}").format(
730 d.idx, d.account_head, self.company
731 )
732 )
Nabin Haita2426fc2018-01-15 17:45:46 +0530733
deepeshgarg0073d11ac02019-05-19 00:02:01 +0530734 def get_gl_dict(self, args, account_currency=None, item=None):
Nabin Hait2df4d542013-01-29 11:34:39 +0530735 """this method populates the common properties of a gl entry record"""
Rushabh Mehta2cb7a9f2016-06-15 16:45:03 +0530736
Ankush Menat494bd9e2022-03-28 18:52:46 +0530737 posting_date = args.get("posting_date") or self.get("posting_date")
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530738 fiscal_years = get_fiscal_years(posting_date, company=self.company)
Nabin Hait2ed0b592016-03-29 13:14:17 +0530739 if len(fiscal_years) > 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530740 frappe.throw(
741 _("Multiple fiscal years exist for the date {0}. Please set company in Fiscal Year").format(
742 formatdate(posting_date)
743 )
744 )
Nabin Hait2ed0b592016-03-29 13:14:17 +0530745 else:
746 fiscal_year = fiscal_years[0][0]
Rushabh Mehta2cb7a9f2016-06-15 16:45:03 +0530747
Ankush Menat494bd9e2022-03-28 18:52:46 +0530748 gl_dict = frappe._dict(
749 {
750 "company": self.company,
751 "posting_date": posting_date,
752 "fiscal_year": fiscal_year,
753 "voucher_type": self.doctype,
754 "voucher_no": self.name,
755 "remarks": self.get("remarks") or self.get("remark"),
756 "debit": 0,
757 "credit": 0,
758 "debit_in_account_currency": 0,
759 "credit_in_account_currency": 0,
760 "is_opening": self.get("is_opening") or "No",
761 "party_type": None,
762 "party": None,
763 "project": self.get("project"),
764 "post_net_value": args.get("post_net_value"),
Deepesh Gargda6bc1a2023-06-23 20:57:51 +0530765 "voucher_detail_no": args.get("voucher_detail_no"),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530766 }
767 )
deepeshgarg007d83cf652019-05-12 18:34:23 +0530768
Sagar Vora4205f562023-07-24 18:37:36 +0530769 with temporary_flag("company", self.company):
770 update_gl_dict_with_regional_fields(self, gl_dict)
771
deepeshgarg007d83cf652019-05-12 18:34:23 +0530772 accounting_dimensions = get_accounting_dimensions()
773 dimension_dict = frappe._dict()
774
775 for dimension in accounting_dimensions:
776 dimension_dict[dimension] = self.get(dimension)
deepeshgarg0073d11ac02019-05-19 00:02:01 +0530777 if item and item.get(dimension):
778 dimension_dict[dimension] = item.get(dimension)
deepeshgarg007d83cf652019-05-12 18:34:23 +0530779
780 gl_dict.update(dimension_dict)
Nabin Hait2df4d542013-01-29 11:34:39 +0530781 gl_dict.update(args)
Anand Doshi979326b2015-09-11 16:22:37 +0530782
Nabin Hait895029d2015-08-20 14:55:39 +0530783 if not account_currency:
Anand Doshicd0989e2015-09-28 13:31:17 +0530784 account_currency = get_account_currency(gl_dict.account)
Anand Doshi979326b2015-09-11 16:22:37 +0530785
Ankush Menat494bd9e2022-03-28 18:52:46 +0530786 if gl_dict.account and self.doctype not in [
787 "Journal Entry",
788 "Period Closing Voucher",
789 "Payment Entry",
790 "Purchase Receipt",
791 "Purchase Invoice",
792 "Stock Entry",
793 ]:
Anand Doshibe6cfdd2015-09-17 21:07:04 +0530794 self.validate_account_currency(gl_dict.account, account_currency)
Deepesh Garg7c300852020-12-26 20:14:51 +0530795
Ankush Menat494bd9e2022-03-28 18:52:46 +0530796 if gl_dict.account and self.doctype not in [
797 "Journal Entry",
798 "Period Closing Voucher",
799 "Payment Entry",
800 ]:
801 set_balance_in_account_currency(
802 gl_dict, account_currency, self.get("conversion_rate"), self.company_currency
803 )
Anand Doshi979326b2015-09-11 16:22:37 +0530804
Nabin Haitc561a492015-08-19 19:22:34 +0530805 return gl_dict
Anand Doshi979326b2015-09-11 16:22:37 +0530806
Anurag Mishrae657fe82018-11-26 15:19:17 +0530807 def validate_qty_is_not_zero(self):
Maricac68a9402019-12-03 12:59:22 +0530808 if self.doctype != "Purchase Receipt":
809 for item in self.items:
810 if not item.qty:
811 frappe.throw(_("Item quantity can not be zero"))
Anurag Mishrae657fe82018-11-26 15:19:17 +0530812
Nabin Hait895029d2015-08-20 14:55:39 +0530813 def validate_account_currency(self, account, account_currency=None):
Nabin Hait6e439a52015-08-28 19:24:22 +0530814 valid_currency = [self.company_currency]
815 if self.get("currency") and self.currency != self.company_currency:
816 valid_currency.append(self.currency)
817
Nabin Hait895029d2015-08-20 14:55:39 +0530818 if account_currency not in valid_currency:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530819 frappe.throw(
820 _("Account {0} is invalid. Account Currency must be {1}").format(
821 account, (" " + _("or") + " ").join(valid_currency)
822 )
823 )
Anand Doshi979326b2015-09-11 16:22:37 +0530824
Anand Doshi613cb6a2013-02-06 17:33:46 +0530825 def clear_unallocated_advances(self, childtype, parentfield):
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530826 self.set(parentfield, self.get(parentfield, {"allocated_amount": ["not in", [0, None, ""]]}))
827
Ankush Menat494bd9e2022-03-28 18:52:46 +0530828 frappe.db.sql(
829 """delete from `tab%s` where parentfield=%s and parent = %s
830 and allocated_amount = 0"""
831 % (childtype, "%s", "%s"),
832 (parentfield, self.name),
833 )
Anand Doshid2946502014-04-08 20:10:03 +0530834
Walstan Baptistad6360752021-03-31 12:30:32 +0530835 @frappe.whitelist()
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530836 def apply_shipping_rule(self):
837 if self.shipping_rule:
838 shipping_rule = frappe.get_doc("Shipping Rule", self.shipping_rule)
839 shipping_rule.apply(self)
840 self.calculate_taxes_and_totals()
841
842 def get_shipping_address(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530843 """Returns Address object from shipping address fields if present"""
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530844
845 # shipping address fields can be `shipping_address_name` or `shipping_address`
846 # try getting value from both
847
Ankush Menat494bd9e2022-03-28 18:52:46 +0530848 for fieldname in ("shipping_address_name", "shipping_address"):
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530849 shipping_field = self.meta.get_field(fieldname)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530850 if shipping_field and shipping_field.fieldtype == "Link":
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530851 if self.get(fieldname):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530852 return frappe.get_doc("Address", self.get(fieldname))
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530853
854 return {}
855
Walstan Baptistad6360752021-03-31 12:30:32 +0530856 @frappe.whitelist()
Nabin Hait041a5c22018-08-01 18:07:39 +0530857 def set_advances(self):
858 """Returns list of advances against Account, Party, Reference"""
859
Deepesh Gargfd3fb642023-04-05 12:02:44 +0530860 res = self.get_advance_entries(
861 include_unallocated=not cint(self.get("only_include_allocated_payments"))
862 )
Nabin Hait041a5c22018-08-01 18:07:39 +0530863
864 self.set("advances", [])
865 advance_allocated = 0
866 for d in res:
Deepesh Garg181df2f2022-11-04 15:49:37 +0530867 if self.get("party_account_currency") == self.company_currency:
868 amount = self.get("base_rounded_total") or self.base_grand_total
Nabin Hait041a5c22018-08-01 18:07:39 +0530869 else:
Deepesh Garg181df2f2022-11-04 15:49:37 +0530870 amount = self.get("rounded_total") or self.grand_total
Deepesh Garg181df2f2022-11-04 15:49:37 +0530871 allocated_amount = min(amount - advance_allocated, d.amount)
Nabin Hait041a5c22018-08-01 18:07:39 +0530872 advance_allocated += flt(allocated_amount)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530873
Saqiba20999c2021-07-12 14:33:23 +0530874 advance_row = {
Nabin Hait041a5c22018-08-01 18:07:39 +0530875 "doctype": self.doctype + " Advance",
876 "reference_type": d.reference_type,
877 "reference_name": d.reference_name,
878 "reference_row": d.reference_row,
879 "remarks": d.remarks,
880 "advance_amount": flt(d.amount),
Saqiba20999c2021-07-12 14:33:23 +0530881 "allocated_amount": allocated_amount,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530882 "ref_exchange_rate": flt(d.exchange_rate), # exchange_rate of advance entry
Saqiba20999c2021-07-12 14:33:23 +0530883 }
Gursheen Anand74619262023-06-02 17:13:51 +0530884 if d.get("paid_from"):
885 advance_row["account"] = d.paid_from
886 if d.get("paid_to"):
887 advance_row["account"] = d.paid_to
Saqiba20999c2021-07-12 14:33:23 +0530888
889 self.append("advances", advance_row)
Nabin Hait041a5c22018-08-01 18:07:39 +0530890
Nabin Hait28a05282016-06-27 17:41:39 +0530891 def get_advance_entries(self, include_unallocated=True):
892 if self.doctype == "Sales Invoice":
Nabin Hait28a05282016-06-27 17:41:39 +0530893 party_type = "Customer"
894 party = self.customer
895 amount_field = "credit_in_account_currency"
896 order_field = "sales_order"
897 order_doctype = "Sales Order"
898 else:
Nabin Hait28a05282016-06-27 17:41:39 +0530899 party_type = "Supplier"
900 party = self.supplier
901 amount_field = "debit_in_account_currency"
902 order_field = "purchase_order"
903 order_doctype = "Purchase Order"
Deepesh Garg92f845c2023-06-21 12:21:19 +0530904
905 party_account = get_party_account(
906 party_type, party=party, company=self.company, include_advance=True
907 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530908
Ankush Menat494bd9e2022-03-28 18:52:46 +0530909 order_list = list(set(d.get(order_field) for d in self.get("items") if d.get(order_field)))
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530910
Ankush Menat494bd9e2022-03-28 18:52:46 +0530911 journal_entries = get_advance_journal_entries(
912 party_type, party, party_account, amount_field, order_doctype, order_list, include_unallocated
913 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530914
Ankush Menat494bd9e2022-03-28 18:52:46 +0530915 payment_entries = get_advance_payment_entries(
916 party_type, party, party_account, order_doctype, order_list, include_unallocated
917 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530918
Nabin Hait28a05282016-06-27 17:41:39 +0530919 res = journal_entries + payment_entries
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530920
Nabin Hait28a05282016-06-27 17:41:39 +0530921 return res
Nabin Hait48f5fa62014-09-18 15:03:54 +0530922
rohitwaghchaurebf4c1142018-01-08 15:20:15 +0530923 def is_inclusive_tax(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530924 is_inclusive = cint(
925 frappe.db.get_single_value("Accounts Settings", "show_inclusive_tax_in_print")
926 )
rohitwaghchaurebf4c1142018-01-08 15:20:15 +0530927
928 if is_inclusive:
929 is_inclusive = 0
930 if self.get("taxes", filters={"included_in_print_rate": 1}):
931 is_inclusive = 1
932
933 return is_inclusive
934
Anand Baburajan491a50a2023-06-13 19:42:56 +0530935 def should_show_taxes_as_table_in_print(self):
936 return cint(frappe.db.get_single_value("Accounts Settings", "show_taxes_as_table_in_print"))
937
Nabin Hait28a05282016-06-27 17:41:39 +0530938 def validate_advance_entries(self):
Nabin Hait05aefbb2016-06-28 19:42:19 +0530939 order_field = "sales_order" if self.doctype == "Sales Invoice" else "purchase_order"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530940 order_list = list(set(d.get(order_field) for d in self.get("items") if d.get(order_field)))
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530941
Ankush Menat494bd9e2022-03-28 18:52:46 +0530942 if not order_list:
943 return
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530944
Nabin Hait28a05282016-06-27 17:41:39 +0530945 advance_entries = self.get_advance_entries(include_unallocated=False)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530946
Nabin Hait28a05282016-06-27 17:41:39 +0530947 if advance_entries:
948 advance_entries_against_si = [d.reference_name for d in self.get("advances")]
949 for d in advance_entries:
950 if not advance_entries_against_si or d.reference_name not in advance_entries_against_si:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530951 frappe.msgprint(
952 _(
953 "Payment Entry {0} is linked against Order {1}, check if it should be pulled as advance in this invoice."
954 ).format(d.reference_name, d.against_order)
955 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530956
Saqiba20999c2021-07-12 14:33:23 +0530957 def set_advance_gain_or_loss(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530958 if self.get("conversion_rate") == 1 or not self.get("advances"):
Saqib Ansari64efe8b2021-09-26 15:46:13 +0530959 return
960
Ankush Menat494bd9e2022-03-28 18:52:46 +0530961 is_purchase_invoice = self.doctype == "Purchase Invoice"
Saqib Ansari64efe8b2021-09-26 15:46:13 +0530962 party_account = self.credit_to if is_purchase_invoice else self.debit_to
963 if get_account_currency(party_account) != self.currency:
Saqiba20999c2021-07-12 14:33:23 +0530964 return
965
966 for d in self.get("advances"):
967 advance_exchange_rate = d.ref_exchange_rate
Ankush Menat494bd9e2022-03-28 18:52:46 +0530968 if d.allocated_amount and self.conversion_rate != advance_exchange_rate:
Saqiba20999c2021-07-12 14:33:23 +0530969
970 base_allocated_amount_in_ref_rate = advance_exchange_rate * d.allocated_amount
971 base_allocated_amount_in_inv_rate = self.conversion_rate * d.allocated_amount
972 difference = base_allocated_amount_in_ref_rate - base_allocated_amount_in_inv_rate
973
974 d.exchange_gain_loss = difference
975
ruthra kumar66286322023-07-25 10:30:08 +0530976 def make_exchange_gain_loss_journal(self, args: dict = None) -> None:
ruthra kumar81cd7872023-04-27 09:46:54 +0530977 """
978 Make Exchange Gain/Loss journal for Invoices and Payments
979 """
ruthra kumarcd42b262023-07-10 15:28:10 +0530980 # Cancelling existing exchange gain/loss journals is handled during the `on_cancel` event.
981 # see accounts/utils.py:cancel_exchange_gain_loss_journal()
ruthra kumar81cd7872023-04-27 09:46:54 +0530982 if self.docstatus == 1:
ruthra kumar7b516f82023-06-26 17:34:28 +0530983 if self.get("doctype") == "Journal Entry":
ruthra kumarcd42b262023-07-10 15:28:10 +0530984 # 'args' is populated with exchange gain/loss account and the amount to be booked.
985 # These are generated by Sales/Purchase Invoice during reconciliation and advance allocation.
ruthra kumarc0b3b062023-07-25 10:51:58 +0530986 # and below logic is only for such scenarios
ruthra kumar7b516f82023-06-26 17:34:28 +0530987 if args:
988 for arg in args:
ruthra kumarf4a65cc2023-07-14 16:51:42 +0530989 # Advance section uses `exchange_gain_loss` and reconciliation uses `difference_amount`
990 if (
991 arg.get("difference_amount", 0) != 0 or arg.get("exchange_gain_loss", 0) != 0
992 ) and arg.get("difference_account"):
ruthra kumar7b516f82023-06-26 17:34:28 +0530993
ruthra kumaree3ce822023-06-26 21:43:20 +0530994 party_account = arg.get("account")
ruthra kumarc0b3b062023-07-25 10:51:58 +0530995 gain_loss_account = arg.get("difference_account")
ruthra kumarf4a65cc2023-07-14 16:51:42 +0530996 difference_amount = arg.get("difference_amount") or arg.get("exchange_gain_loss")
997 if difference_amount > 0:
ruthra kumar05672432023-07-12 06:14:17 +0530998 dr_or_cr = "debit" if arg.get("party_type") == "Customer" else "credit"
999 else:
1000 dr_or_cr = "credit" if arg.get("party_type") == "Customer" else "debit"
ruthra kumar7b516f82023-06-26 17:34:28 +05301001
1002 reverse_dr_or_cr = "debit" if dr_or_cr == "credit" else "credit"
1003
ruthra kumaracc73222023-07-27 07:52:01 +05301004 je = create_gain_loss_journal(
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05301005 self.company,
ruthra kumarc0b3b062023-07-25 10:51:58 +05301006 arg.get("party_type"),
1007 arg.get("party"),
1008 party_account,
1009 gain_loss_account,
1010 difference_amount,
1011 dr_or_cr,
1012 reverse_dr_or_cr,
1013 arg.get("against_voucher_type"),
1014 arg.get("against_voucher"),
1015 arg.get("idx"),
1016 self.doctype,
1017 self.name,
1018 arg.get("idx"),
ruthra kumar7b516f82023-06-26 17:34:28 +05301019 )
ruthra kumaracc73222023-07-27 07:52:01 +05301020 frappe.msgprint(
1021 _("Exchange Gain/Loss amount has been booked through {0}").format(
1022 get_link_to_form("Journal Entry", je)
1023 )
1024 )
ruthra kumar7b516f82023-06-26 17:34:28 +05301025
ruthra kumar81cd7872023-04-27 09:46:54 +05301026 if self.get("doctype") == "Payment Entry":
ruthra kumarcd42b262023-07-10 15:28:10 +05301027 # For Payment Entry, exchange_gain_loss field in the `references` table is the trigger for journal creation
ruthra kumar81cd7872023-04-27 09:46:54 +05301028 gain_loss_to_book = [x for x in self.references if x.exchange_gain_loss != 0]
1029 booked = []
1030 if gain_loss_to_book:
1031 vtypes = [x.reference_doctype for x in gain_loss_to_book]
1032 vnames = [x.reference_name for x in gain_loss_to_book]
1033 je = qb.DocType("Journal Entry")
1034 jea = qb.DocType("Journal Entry Account")
1035 parents = (
1036 qb.from_(jea)
1037 .select(jea.parent)
1038 .where(
1039 (jea.reference_type == "Payment Entry")
1040 & (jea.reference_name == self.name)
1041 & (jea.docstatus == 1)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301042 )
ruthra kumar81cd7872023-04-27 09:46:54 +05301043 .run()
Saqiba20999c2021-07-12 14:33:23 +05301044 )
1045
ruthra kumar81cd7872023-04-27 09:46:54 +05301046 booked = []
1047 if parents:
1048 booked = (
1049 qb.from_(je)
1050 .inner_join(jea)
1051 .on(je.name == jea.parent)
1052 .select(jea.reference_type, jea.reference_name, jea.reference_detail_no)
1053 .where(
1054 (je.docstatus == 1)
1055 & (je.name.isin(parents))
1056 & (je.voucher_type == "Exchange Gain or Loss")
1057 )
1058 .run()
1059 )
Saqiba20999c2021-07-12 14:33:23 +05301060
ruthra kumar81cd7872023-04-27 09:46:54 +05301061 for d in gain_loss_to_book:
ruthra kumarc0b3b062023-07-25 10:51:58 +05301062 # Filter out References for which Gain/Loss is already booked
ruthra kumar81cd7872023-04-27 09:46:54 +05301063 if d.exchange_gain_loss and (
1064 (d.reference_doctype, d.reference_name, str(d.idx)) not in booked
1065 ):
ruthra kumar81cd7872023-04-27 09:46:54 +05301066 if self.payment_type == "Receive":
1067 party_account = self.paid_from
1068 elif self.payment_type == "Pay":
1069 party_account = self.paid_to
1070
ruthra kumar81cd7872023-04-27 09:46:54 +05301071 dr_or_cr = "debit" if d.exchange_gain_loss > 0 else "credit"
ruthra kumar34b5e842023-06-16 14:07:44 +05301072
1073 if d.reference_doctype == "Purchase Invoice":
1074 dr_or_cr = "debit" if dr_or_cr == "credit" else "credit"
1075
ruthra kumar81cd7872023-04-27 09:46:54 +05301076 reverse_dr_or_cr = "debit" if dr_or_cr == "credit" else "credit"
1077
1078 gain_loss_account = frappe.get_cached_value(
1079 "Company", self.company, "exchange_gain_loss_account"
1080 )
ruthra kumar81cd7872023-04-27 09:46:54 +05301081
ruthra kumaracc73222023-07-27 07:52:01 +05301082 je = create_gain_loss_journal(
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05301083 self.company,
ruthra kumarc0b3b062023-07-25 10:51:58 +05301084 self.party_type,
1085 self.party,
1086 party_account,
1087 gain_loss_account,
1088 d.exchange_gain_loss,
1089 dr_or_cr,
1090 reverse_dr_or_cr,
1091 d.reference_doctype,
1092 d.reference_name,
1093 d.idx,
1094 self.doctype,
1095 self.name,
1096 d.idx,
Ankush Menat494bd9e2022-03-28 18:52:46 +05301097 )
ruthra kumaracc73222023-07-27 07:52:01 +05301098 frappe.msgprint(
1099 _("Exchange Gain/Loss amount has been booked through {0}").format(
1100 get_link_to_form("Journal Entry", je)
1101 )
1102 )
Saqiba20999c2021-07-12 14:33:23 +05301103
Deepesh Garg016ed952023-06-20 13:22:32 +05301104 def update_against_document_in_jv(self):
Nabin Hait28a05282016-06-27 17:41:39 +05301105 """
Ankush Menat494bd9e2022-03-28 18:52:46 +05301106 Links invoice and advance voucher:
1107 1. cancel advance voucher
1108 2. split into multiple rows if partially adjusted, assign against voucher
1109 3. submit advance voucher
Nabin Hait28a05282016-06-27 17:41:39 +05301110 """
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301111
Nabin Hait28a05282016-06-27 17:41:39 +05301112 if self.doctype == "Sales Invoice":
Nabin Haitff2f3ef2016-07-04 11:41:14 +05301113 party_type = "Customer"
Nabin Hait28a05282016-06-27 17:41:39 +05301114 party = self.customer
1115 party_account = self.debit_to
1116 dr_or_cr = "credit_in_account_currency"
1117 else:
Nabin Haitff2f3ef2016-07-04 11:41:14 +05301118 party_type = "Supplier"
Nabin Hait28a05282016-06-27 17:41:39 +05301119 party = self.supplier
1120 party_account = self.credit_to
1121 dr_or_cr = "debit_in_account_currency"
Nabin Hait48f5fa62014-09-18 15:03:54 +05301122
Nabin Hait28a05282016-06-27 17:41:39 +05301123 lst = []
Ankush Menat494bd9e2022-03-28 18:52:46 +05301124 for d in self.get("advances"):
Nabin Hait28a05282016-06-27 17:41:39 +05301125 if flt(d.allocated_amount) > 0:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301126 args = frappe._dict(
1127 {
1128 "voucher_type": d.reference_type,
1129 "voucher_no": d.reference_name,
1130 "voucher_detail_no": d.reference_row,
1131 "against_voucher_type": self.doctype,
1132 "against_voucher": self.name,
1133 "account": party_account,
1134 "party_type": party_type,
1135 "party": party,
1136 "is_advance": "Yes",
1137 "dr_or_cr": dr_or_cr,
1138 "unadjusted_amount": flt(d.advance_amount),
1139 "allocated_amount": flt(d.allocated_amount),
1140 "precision": d.precision("advance_amount"),
1141 "exchange_rate": (
1142 self.conversion_rate if self.party_account_currency != self.company_currency else 1
1143 ),
1144 "grand_total": (
1145 self.base_grand_total
1146 if self.party_account_currency == self.company_currency
1147 else self.grand_total
1148 ),
1149 "outstanding_amount": self.outstanding_amount,
Daizy Modi4efc9472022-11-07 09:21:03 +05301150 "difference_account": frappe.get_cached_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301151 "Company", self.company, "exchange_gain_loss_account"
1152 ),
1153 "exchange_gain_loss": flt(d.get("exchange_gain_loss")),
1154 }
1155 )
Nabin Hait28a05282016-06-27 17:41:39 +05301156 lst.append(args)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301157
Nabin Hait28a05282016-06-27 17:41:39 +05301158 if lst:
1159 from erpnext.accounts.utils import reconcile_against_document
Ankush Menat494bd9e2022-03-28 18:52:46 +05301160
Deepesh Garg016ed952023-06-20 13:22:32 +05301161 reconcile_against_document(lst)
Anand Doshid2946502014-04-08 20:10:03 +05301162
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +05301163 def on_cancel(self):
ruthra kumar81cd7872023-04-27 09:46:54 +05301164 from erpnext.accounts.utils import (
1165 cancel_exchange_gain_loss_journal,
1166 unlink_ref_doc_from_payment_entries,
1167 )
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +05301168
ruthra kumar6e18bb62023-07-11 12:21:10 +05301169 if self.doctype in ["Sales Invoice", "Purchase Invoice", "Payment Entry", "Journal Entry"]:
ruthra kumar81cd7872023-04-27 09:46:54 +05301170 # Cancel Exchange Gain/Loss Journal before unlinking
1171 cancel_exchange_gain_loss_journal(self)
1172
Ankush Menat494bd9e2022-03-28 18:52:46 +05301173 if frappe.db.get_single_value("Accounts Settings", "unlink_payment_on_cancellation_of_invoice"):
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +05301174 unlink_ref_doc_from_payment_entries(self)
1175
1176 elif self.doctype in ["Sales Order", "Purchase Order"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301177 if frappe.db.get_single_value(
1178 "Accounts Settings", "unlink_advance_payment_on_cancelation_of_order"
1179 ):
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +05301180 unlink_ref_doc_from_payment_entries(self)
1181
GangaManoj8396f242021-09-20 19:01:46 +05301182 if self.doctype == "Sales Order":
1183 self.unlink_ref_doc_from_po()
1184
1185 def unlink_ref_doc_from_po(self):
GangaManoj8396f242021-09-20 19:01:46 +05301186 so_items = []
1187 for item in self.items:
1188 so_items.append(item.name)
1189
Ankush Menat494bd9e2022-03-28 18:52:46 +05301190 linked_po = list(
1191 set(
1192 frappe.get_all(
1193 "Purchase Order Item",
1194 filters={
1195 "sales_order": self.name,
1196 "sales_order_item": ["in", so_items],
1197 "docstatus": ["<", 2],
1198 },
1199 pluck="parent",
1200 )
1201 )
1202 )
GangaManoj8396f242021-09-20 19:01:46 +05301203
GangaManoj8396f242021-09-20 19:01:46 +05301204 if linked_po:
GangaManoje77534f2021-09-20 19:01:46 +05301205 frappe.db.set_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301206 "Purchase Order Item",
1207 {"sales_order": self.name, "sales_order_item": ["in", so_items], "docstatus": ["<", 2]},
1208 {"sales_order": None, "sales_order_item": None},
GangaManoje77534f2021-09-20 19:01:46 +05301209 )
GangaManoj8396f242021-09-20 19:01:46 +05301210
1211 frappe.msgprint(_("Purchase Orders {0} are un-linked").format("\n".join(linked_po)))
1212
Deepesh Gargd18dde72020-11-29 21:40:04 +05301213 def get_tax_map(self):
1214 tax_map = {}
Ankush Menat494bd9e2022-03-28 18:52:46 +05301215 for tax in self.get("taxes"):
Deepesh Gargd18dde72020-11-29 21:40:04 +05301216 tax_map.setdefault(tax.account_head, 0.0)
1217 tax_map[tax.account_head] += tax.tax_amount
1218
1219 return tax_map
1220
Deepesh Garg92f7a5a2021-07-21 15:25:40 +05301221 def get_amount_and_base_amount(self, item, enable_discount_accounting):
1222 amount = item.net_amount
1223 base_amount = item.base_net_amount
1224
Ankush Menat494bd9e2022-03-28 18:52:46 +05301225 if (
1226 enable_discount_accounting
1227 and self.get("discount_amount")
1228 and self.get("additional_discount_account")
1229 ):
Deepesh Garg92f7a5a2021-07-21 15:25:40 +05301230 amount = item.amount
1231 base_amount = item.base_amount
1232
1233 return amount, base_amount
1234
1235 def get_tax_amounts(self, tax, enable_discount_accounting):
1236 amount = tax.tax_amount_after_discount_amount
1237 base_amount = tax.base_tax_amount_after_discount_amount
1238
Ankush Menat494bd9e2022-03-28 18:52:46 +05301239 if (
1240 enable_discount_accounting
1241 and self.get("discount_amount")
1242 and self.get("additional_discount_account")
1243 and self.get("apply_discount_on") == "Grand Total"
1244 ):
Deepesh Garg92f7a5a2021-07-21 15:25:40 +05301245 amount = tax.tax_amount
1246 base_amount = tax.base_tax_amount
1247
1248 return amount, base_amount
1249
GangaManoj8f7b0a12021-07-13 03:01:02 +05301250 def make_discount_gl_entries(self, gl_entries):
rahib-hassanf3fa6ac2022-04-20 16:01:12 +05301251 if self.doctype == "Purchase Invoice":
1252 enable_discount_accounting = cint(
1253 frappe.db.get_single_value("Buying Settings", "enable_discount_accounting")
1254 )
1255 elif self.doctype == "Sales Invoice":
1256 enable_discount_accounting = cint(
1257 frappe.db.get_single_value("Selling Settings", "enable_discount_accounting")
1258 )
GangaManoj8f7b0a12021-07-13 03:01:02 +05301259
Deepesh Garg3b159662022-08-21 17:51:05 +05301260 if self.doctype == "Purchase Invoice":
1261 dr_or_cr = "credit"
1262 rev_dr_cr = "debit"
1263 supplier_or_customer = self.supplier
1264
1265 else:
1266 dr_or_cr = "debit"
1267 rev_dr_cr = "credit"
1268 supplier_or_customer = self.customer
1269
GangaManoj8f7b0a12021-07-13 03:01:02 +05301270 if enable_discount_accounting:
1271 for item in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301272 if item.get("discount_amount") and item.get("discount_account"):
Deepesh Gargad7bb312021-07-28 11:38:44 +05301273 discount_amount = item.discount_amount * item.qty
GangaManoj8f7b0a12021-07-13 03:01:02 +05301274 if self.doctype == "Purchase Invoice":
Ankush Menat494bd9e2022-03-28 18:52:46 +05301275 income_or_expense_account = (
1276 item.expense_account
Ankush Menat4551d7d2021-08-19 13:41:10 +05301277 if (not item.enable_deferred_expense or self.is_return)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301278 else item.deferred_expense_account
1279 )
GangaManoj8f7b0a12021-07-13 03:01:02 +05301280 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301281 income_or_expense_account = (
1282 item.income_account
Ankush Menat4551d7d2021-08-19 13:41:10 +05301283 if (not item.enable_deferred_revenue or self.is_return)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301284 else item.deferred_revenue_account
1285 )
GangaManoj8f7b0a12021-07-13 03:01:02 +05301286
1287 account_currency = get_account_currency(item.discount_account)
1288 gl_entries.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301289 self.get_gl_dict(
1290 {
1291 "account": item.discount_account,
1292 "against": supplier_or_customer,
Saqib Ansarif915a9c2022-05-17 11:22:01 +05301293 dr_or_cr: flt(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301294 discount_amount * self.get("conversion_rate"), item.precision("discount_amount")
1295 ),
Saqib Ansarif915a9c2022-05-17 11:22:01 +05301296 dr_or_cr + "_in_account_currency": flt(discount_amount, item.precision("discount_amount")),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301297 "cost_center": item.cost_center,
1298 "project": item.project,
1299 },
1300 account_currency,
1301 item=item,
1302 )
GangaManoj8f7b0a12021-07-13 03:01:02 +05301303 )
1304
1305 account_currency = get_account_currency(income_or_expense_account)
1306 gl_entries.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301307 self.get_gl_dict(
1308 {
1309 "account": income_or_expense_account,
1310 "against": supplier_or_customer,
Saqib Ansarif915a9c2022-05-17 11:22:01 +05301311 rev_dr_cr: flt(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301312 discount_amount * self.get("conversion_rate"), item.precision("discount_amount")
1313 ),
Saqib Ansarif915a9c2022-05-17 11:22:01 +05301314 rev_dr_cr
1315 + "_in_account_currency": flt(discount_amount, item.precision("discount_amount")),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301316 "cost_center": item.cost_center,
1317 "project": item.project or self.project,
1318 },
1319 account_currency,
1320 item=item,
1321 )
GangaManoj8f7b0a12021-07-13 03:01:02 +05301322 )
GangaManoj857501c2021-07-15 22:03:46 +05301323
Deepesh Garg3b159662022-08-21 17:51:05 +05301324 if (
Deepesh Gargae3dce02022-08-22 08:57:58 +05301325 (enable_discount_accounting or self.get("is_cash_or_non_trade_discount"))
Deepesh Garg3b159662022-08-21 17:51:05 +05301326 and self.get("additional_discount_account")
1327 and self.get("discount_amount")
1328 ):
1329 gl_entries.append(
1330 self.get_gl_dict(
1331 {
1332 "account": self.additional_discount_account,
1333 "against": supplier_or_customer,
1334 dr_or_cr: self.discount_amount,
1335 "cost_center": self.cost_center,
1336 },
1337 item=self,
Ankush Menat4551d7d2021-08-19 13:41:10 +05301338 )
Deepesh Garg3b159662022-08-21 17:51:05 +05301339 )
Ankush Menat4551d7d2021-08-19 13:41:10 +05301340
Deepesh Garg4c61ee32023-04-02 09:35:27 +05301341 def validate_multiple_billing(self, ref_dt, item_ref_dn, based_on):
Nabin Hait868766d2019-07-15 18:02:58 +05301342 from erpnext.controllers.status_updater import get_allowance_for
Saqib9c913c92021-11-26 12:00:13 +05301343
Nabin Hait868766d2019-07-15 18:02:58 +05301344 item_allowance = {}
1345 global_qty_allowance, global_amount_allowance = None, None
Anand Doshid2946502014-04-08 20:10:03 +05301346
Ankush Menat494bd9e2022-03-28 18:52:46 +05301347 role_allowed_to_over_bill = frappe.db.get_single_value(
1348 "Accounts Settings", "role_allowed_to_over_bill"
1349 )
Ankush Menat648b2d72021-09-20 15:27:12 +05301350 user_roles = frappe.get_roles()
1351
Ankush Menat43bf82b2021-09-20 16:31:20 +05301352 total_overbilled_amt = 0.0
1353
Deepesh Garg4c61ee32023-04-02 09:35:27 +05301354 reference_names = [d.get(item_ref_dn) for d in self.get("items") if d.get(item_ref_dn)]
1355 reference_details = self.get_billing_reference_details(
1356 reference_names, ref_dt + " Item", based_on
1357 )
1358
Nabin Hait4b8185d2014-12-25 18:19:39 +05301359 for item in self.get("items"):
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301360 if not item.get(item_ref_dn):
1361 continue
Anand Doshid2946502014-04-08 20:10:03 +05301362
Deepesh Garg4c61ee32023-04-02 09:35:27 +05301363 ref_amt = flt(reference_details.get(item.get(item_ref_dn)), self.precision(based_on, item))
1364
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301365 if not ref_amt:
1366 frappe.msgprint(
Deepesh Garg4c61ee32023-04-02 09:35:27 +05301367 _("System will not check over billing since amount for Item {0} in {1} is zero").format(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301368 item.item_code, ref_dt
1369 ),
1370 title=_("Warning"),
1371 indicator="orange",
1372 )
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301373 continue
Anand Doshid2946502014-04-08 20:10:03 +05301374
Saqib9c913c92021-11-26 12:00:13 +05301375 already_billed = self.get_billed_amount_for_item(item, item_ref_dn, based_on)
Anand Doshid2946502014-04-08 20:10:03 +05301376
Ankush Menat494bd9e2022-03-28 18:52:46 +05301377 total_billed_amt = flt(
1378 flt(already_billed) + flt(item.get(based_on)), self.precision(based_on, item)
1379 )
Anand Doshid2946502014-04-08 20:10:03 +05301380
Ankush Menat494bd9e2022-03-28 18:52:46 +05301381 allowance, item_allowance, global_qty_allowance, global_amount_allowance = get_allowance_for(
1382 item.item_code, item_allowance, global_qty_allowance, global_amount_allowance, "amount"
1383 )
rohitwaghchaure285344e2019-10-11 11:02:11 +05301384
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301385 max_allowed_amt = flt(ref_amt * (100 + allowance) / 100)
Deepesh Gargcb718fc2021-04-19 13:25:15 +05301386
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301387 if total_billed_amt < 0 and max_allowed_amt < 0:
1388 # while making debit note against purchase return entry(purchase receipt) getting overbill error
1389 total_billed_amt = abs(total_billed_amt)
1390 max_allowed_amt = abs(max_allowed_amt)
Afshan53fefd72021-06-24 10:09:02 +05301391
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301392 overbill_amt = total_billed_amt - max_allowed_amt
1393 total_overbilled_amt += overbill_amt
1394
1395 if overbill_amt > 0.01 and role_allowed_to_over_bill not in user_roles:
1396 if self.doctype != "Purchase Invoice":
1397 self.throw_overbill_exception(item, max_allowed_amt)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301398 elif not cint(
1399 frappe.db.get_single_value(
1400 "Buying Settings", "bill_for_rejected_quantity_in_purchase_invoice"
1401 )
1402 ):
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301403 self.throw_overbill_exception(item, max_allowed_amt)
1404
1405 if role_allowed_to_over_bill in user_roles and total_overbilled_amt > 0.1:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301406 frappe.msgprint(
1407 _("Overbilling of {} ignored because you have {} role.").format(
1408 total_overbilled_amt, role_allowed_to_over_bill
1409 ),
1410 indicator="orange",
1411 alert=True,
1412 )
Afshan53fefd72021-06-24 10:09:02 +05301413
Deepesh Garg4c61ee32023-04-02 09:35:27 +05301414 def get_billing_reference_details(self, reference_names, reference_doctype, based_on):
1415 return frappe._dict(
1416 frappe.get_all(
1417 reference_doctype,
1418 filters={"name": ("in", reference_names)},
1419 fields=["name", based_on],
1420 as_list=1,
1421 )
1422 )
1423
Saqib9c913c92021-11-26 12:00:13 +05301424 def get_billed_amount_for_item(self, item, item_ref_dn, based_on):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301425 """
1426 Returns Sum of Amount of
1427 Sales/Purchase Invoice Items
1428 that are linked to `item_ref_dn` (`dn_detail` / `pr_detail`)
1429 that are submitted OR not submitted but are under current invoice
1430 """
Saqib9c913c92021-11-26 12:00:13 +05301431
1432 from frappe.query_builder import Criterion
1433 from frappe.query_builder.functions import Sum
1434
1435 item_doctype = frappe.qb.DocType(item.doctype)
1436 based_on_field = frappe.qb.Field(based_on)
1437 join_field = frappe.qb.Field(item_ref_dn)
1438
1439 result = (
1440 frappe.qb.from_(item_doctype)
1441 .select(Sum(based_on_field))
Ankush Menat494bd9e2022-03-28 18:52:46 +05301442 .where(join_field == item.get(item_ref_dn))
Saqib9c913c92021-11-26 12:00:13 +05301443 .where(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301444 Criterion.any(
1445 [ # select all items from other invoices OR current invoices
1446 Criterion.all(
1447 [ # for selecting items from other invoices
1448 item_doctype.docstatus == 1,
1449 item_doctype.parent != self.name,
1450 ]
1451 ),
1452 Criterion.all(
1453 [ # for selecting items from current invoice, that are linked to same reference
1454 item_doctype.docstatus == 0,
1455 item_doctype.parent == self.name,
1456 item_doctype.name != item.name,
1457 ]
1458 ),
1459 ]
1460 )
Saqib9c913c92021-11-26 12:00:13 +05301461 )
1462 ).run()
1463
1464 return result[0][0] if result else 0
1465
Afshan53fefd72021-06-24 10:09:02 +05301466 def throw_overbill_exception(self, item, max_allowed_amt):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301467 frappe.throw(
1468 _(
1469 "Cannot overbill for Item {0} in row {1} more than {2}. To allow over-billing, please set allowance in Accounts Settings"
1470 ).format(item.item_code, item.idx, max_allowed_amt)
1471 )
Anand Doshid2946502014-04-08 20:10:03 +05301472
Rohit Waghchaure2a14f252021-07-30 12:36:35 +05301473 def get_company_default(self, fieldname, ignore_validation=False):
Rushabh Mehta1f847992013-12-12 19:12:19 +05301474 from erpnext.accounts.utils import get_company_default
Ankush Menat494bd9e2022-03-28 18:52:46 +05301475
Rohit Waghchaure2a14f252021-07-30 12:36:35 +05301476 return get_company_default(self.company, fieldname, ignore_validation=ignore_validation)
Anand Doshid2946502014-04-08 20:10:03 +05301477
Nabin Haita36adbd2013-08-02 14:50:12 +05301478 def get_stock_items(self):
1479 stock_items = []
Nabin Haitdd38a262014-12-26 13:15:21 +05301480 item_codes = list(set(item.item_code for item in self.get("items")))
Nabin Haita36adbd2013-08-02 14:50:12 +05301481 if item_codes:
Saqib Ansari199a6da2022-03-31 11:41:52 +05301482 stock_items = frappe.db.get_values(
1483 "Item", {"name": ["in", item_codes], "is_stock_item": 1}, pluck="name", cache=True
1484 )
Anand Doshid2946502014-04-08 20:10:03 +05301485
Nabin Haita36adbd2013-08-02 14:50:12 +05301486 return stock_items
Anand Doshid2946502014-04-08 20:10:03 +05301487
Ankit Javalkar8e7ca412014-09-12 15:18:53 +05301488 def set_total_advance_paid(self):
ruthra kumar44870652022-11-01 10:11:38 +05301489 ple = frappe.qb.DocType("Payment Ledger Entry")
1490 party = self.customer if self.doctype == "Sales Order" else self.supplier
1491 advance = (
1492 frappe.qb.from_(ple)
ruthra kumarbf76b852022-11-22 12:16:11 +05301493 .select(ple.account_currency, Abs(Sum(ple.amount_in_account_currency)).as_("amount"))
ruthra kumar44870652022-11-01 10:11:38 +05301494 .where(
1495 (ple.against_voucher_type == self.doctype)
1496 & (ple.against_voucher_no == self.name)
1497 & (ple.party == party)
ruthra kumarbf76b852022-11-22 12:16:11 +05301498 & (ple.docstatus == 1)
ruthra kumar44870652022-11-01 10:11:38 +05301499 & (ple.company == self.company)
1500 )
1501 .run(as_dict=True)
1502 )
Ankit Javalkar8e7ca412014-09-12 15:18:53 +05301503
Nabin Haitb2206d12016-01-27 15:43:12 +05301504 if advance:
Anand Doshi7c0a58a2016-01-29 12:16:24 +05301505 advance = advance[0]
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301506
Anand Doshi7c0a58a2016-01-29 12:16:24 +05301507 advance_paid = flt(advance.amount, self.precision("advance_paid"))
Ankush Menat494bd9e2022-03-28 18:52:46 +05301508 formatted_advance_paid = fmt_money(
1509 advance_paid, precision=self.precision("advance_paid"), currency=advance.account_currency
1510 )
Anand Doshi7c0a58a2016-01-29 12:16:24 +05301511
Ankush Menat494bd9e2022-03-28 18:52:46 +05301512 frappe.db.set_value(self.doctype, self.name, "party_account_currency", advance.account_currency)
Anand Doshi7c0a58a2016-01-29 12:16:24 +05301513
1514 if advance.account_currency == self.currency:
finbyz5efc7972019-01-05 11:12:11 +05301515 order_total = self.get("rounded_total") or self.grand_total
1516 precision = "rounded_total" if self.get("rounded_total") else "grand_total"
Nabin Haitb2206d12016-01-27 15:43:12 +05301517 else:
finbyz5efc7972019-01-05 11:12:11 +05301518 order_total = self.get("base_rounded_total") or self.base_grand_total
1519 precision = "base_rounded_total" if self.get("base_rounded_total") else "base_grand_total"
Sagar Voraf733a392019-01-07 14:24:01 +05301520
Ankush Menat494bd9e2022-03-28 18:52:46 +05301521 formatted_order_total = fmt_money(
1522 order_total, precision=self.precision(precision), currency=advance.account_currency
1523 )
Anand Doshi7c0a58a2016-01-29 12:16:24 +05301524
Nabin Hait9db1b222016-06-30 12:37:53 +05301525 if self.currency == self.company_currency and advance_paid > order_total:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301526 frappe.throw(
1527 _(
1528 "Total advance ({0}) against Order {1} cannot be greater than the Grand Total ({2})"
1529 ).format(formatted_advance_paid, self.name, formatted_order_total)
1530 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301531
Nabin Hait13093b42016-06-29 18:04:37 +05301532 frappe.db.set_value(self.doctype, self.name, "advance_paid", advance_paid)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +05301533
ankitjavalkarworke60822b2014-08-26 14:29:06 +05301534 @property
1535 def company_abbr(self):
Nabin Hait6a5695f2018-08-09 11:30:21 +05301536 if not hasattr(self, "_abbr"):
Daizy Modi4efc9472022-11-07 09:21:03 +05301537 self._abbr = frappe.get_cached_value("Company", self.company, "abbr")
ankitjavalkarworke60822b2014-08-26 14:29:06 +05301538
1539 return self._abbr
1540
marination4be5b5c2020-10-08 19:08:27 +05301541 def raise_missing_debit_credit_account_error(self, party_type, party):
marination53b1a9a2020-11-03 15:45:25 +05301542 """Raise an error if debit to/credit to account does not exist."""
Ankush Menat494bd9e2022-03-28 18:52:46 +05301543 db_or_cr = (
1544 frappe.bold("Debit To") if self.doctype == "Sales Invoice" else frappe.bold("Credit To")
1545 )
marination4be5b5c2020-10-08 19:08:27 +05301546 rec_or_pay = "Receivable" if self.doctype == "Sales Invoice" else "Payable"
1547
1548 link_to_party = frappe.utils.get_link_to_form(party_type, party)
1549 link_to_company = frappe.utils.get_link_to_form("Company", self.company)
1550
Ankush Menat494bd9e2022-03-28 18:52:46 +05301551 message = _("{0} Account not found against Customer {1}.").format(
1552 db_or_cr, frappe.bold(party) or ""
1553 )
marination4be5b5c2020-10-08 19:08:27 +05301554 message += "<br>" + _("Please set one of the following:") + "<br>"
Ankush Menat494bd9e2022-03-28 18:52:46 +05301555 message += (
1556 "<br><ul><li>"
1557 + _("'Account' in the Accounting section of Customer {0}").format(link_to_party)
1558 + "</li>"
1559 )
1560 message += (
1561 "<li>"
1562 + _("'Default {0} Account' in Company {1}").format(rec_or_pay, link_to_company)
1563 + "</li></ul>"
1564 )
marination4be5b5c2020-10-08 19:08:27 +05301565
marination53b1a9a2020-11-03 15:45:25 +05301566 frappe.throw(message, title=_("Account Missing"), exc=AccountMissingError)
marination4be5b5c2020-10-08 19:08:27 +05301567
Neil Trini Lasrado3fbbb712015-07-17 12:10:12 +05301568 def validate_party(self):
Nabin Hait4ffd7f32015-08-27 12:28:36 +05301569 party_type, party = self.get_party()
shreyaseba9ca42016-01-26 14:56:52 +05301570 validate_party_frozen_disabled(party_type, party)
Anand Doshi979326b2015-09-11 16:22:37 +05301571
Nabin Hait4ffd7f32015-08-27 12:28:36 +05301572 def get_party(self):
Neil Trini Lasrado79bf2332015-07-20 13:03:48 +05301573 party_type = None
shreyas29b565f2016-01-25 17:30:49 +05301574 if self.doctype in ("Opportunity", "Quotation", "Sales Order", "Delivery Note", "Sales Invoice"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301575 party_type = "Customer"
shreyas29b565f2016-01-25 17:30:49 +05301576
Ankush Menat494bd9e2022-03-28 18:52:46 +05301577 elif self.doctype in (
1578 "Supplier Quotation",
1579 "Purchase Order",
1580 "Purchase Receipt",
1581 "Purchase Invoice",
1582 ):
1583 party_type = "Supplier"
shreyas29b565f2016-01-25 17:30:49 +05301584
1585 elif self.meta.get_field("customer"):
1586 party_type = "Customer"
Neil Trini Lasrado3fbbb712015-07-17 12:10:12 +05301587
Neil Trini Lasrado79bf2332015-07-20 13:03:48 +05301588 elif self.meta.get_field("supplier"):
shreyas29b565f2016-01-25 17:30:49 +05301589 party_type = "Supplier"
Anand Doshi979326b2015-09-11 16:22:37 +05301590
Nabin Hait4ffd7f32015-08-27 12:28:36 +05301591 party = self.get(party_type.lower()) if party_type else None
Anand Doshi979326b2015-09-11 16:22:37 +05301592
Nabin Hait4ffd7f32015-08-27 12:28:36 +05301593 return party_type, party
Anand Doshi979326b2015-09-11 16:22:37 +05301594
Nabin Hait4ffd7f32015-08-27 12:28:36 +05301595 def validate_currency(self):
Nabin Hait6e439a52015-08-28 19:24:22 +05301596 if self.get("currency"):
Nabin Hait4ffd7f32015-08-27 12:28:36 +05301597 party_type, party = self.get_party()
Nabin Hait6e439a52015-08-28 19:24:22 +05301598 if party_type and party:
Anand Doshib20baf82015-09-25 16:17:50 +05301599 party_account_currency = get_party_account_currency(party_type, party, self.company)
Anand Doshi979326b2015-09-11 16:22:37 +05301600
Ankush Menat494bd9e2022-03-28 18:52:46 +05301601 if (
1602 party_account_currency
1603 and party_account_currency != self.company_currency
1604 and self.currency != party_account_currency
1605 ):
1606 frappe.throw(
1607 _("Accounting Entry for {0}: {1} can only be made in currency: {2}").format(
1608 party_type, party, party_account_currency
1609 ),
1610 InvalidCurrency,
1611 )
Anand Doshi979326b2015-09-11 16:22:37 +05301612
shreyas29b565f2016-01-25 17:30:49 +05301613 # Note: not validating with gle account because we don't have the account
1614 # at quotation / sales order level and we shouldn't stop someone
1615 # from creating a sales invoice if sales order is already created
Rushabh Mehta2cb7a9f2016-06-15 16:45:03 +05301616
Deepesh Garg80c85dd2021-08-12 15:39:07 +05301617 def validate_party_account_currency(self):
Deepesh Garg33d97672022-05-12 16:40:29 +05301618 if self.doctype not in ("Sales Invoice", "Purchase Invoice"):
Deepesh Garg80c85dd2021-08-12 15:39:07 +05301619 return
1620
Deepesh Garg33d97672022-05-12 16:40:29 +05301621 if self.is_opening == "Yes":
Deepesh Garg60915e82021-08-21 23:05:48 +05301622 return
1623
Deepesh Garg80c85dd2021-08-12 15:39:07 +05301624 party_type, party = self.get_party()
1625 party_gle_currency = get_party_gle_currency(party_type, party, self.company)
Deepesh Garg33d97672022-05-12 16:40:29 +05301626 party_account = (
1627 self.get("debit_to") if self.doctype == "Sales Invoice" else self.get("credit_to")
1628 )
Deepesh Garg80c85dd2021-08-12 15:39:07 +05301629 party_account_currency = get_account_currency(party_account)
Deepesh Garge04e67c2022-07-11 19:25:18 +05301630 allow_multi_currency_invoices_against_single_party_account = frappe.db.get_singles_value(
Deepesh Garg3cf609f2022-07-11 13:46:59 +05301631 "Accounts Settings", "allow_multi_currency_invoices_against_single_party_account"
1632 )
Deepesh Garg80c85dd2021-08-12 15:39:07 +05301633
Deepesh Garg3cf609f2022-07-11 13:46:59 +05301634 if (
1635 not party_gle_currency
1636 and (party_account_currency != self.currency)
1637 and not allow_multi_currency_invoices_against_single_party_account
1638 ):
Deepesh Garg33d97672022-05-12 16:40:29 +05301639 frappe.throw(
Devin Slauenwhite3a1c9232022-06-02 14:15:50 -04001640 _("Party Account {0} currency ({1}) and document currency ({2}) should be same").format(
Devin Slauenwhiteb061ea42022-06-02 14:23:54 -04001641 frappe.bold(party_account), party_account_currency, self.currency
Deepesh Garg33d97672022-05-12 16:40:29 +05301642 )
1643 )
Deepesh Garg80c85dd2021-08-12 15:39:07 +05301644
Nabin Hait297d74a2016-11-23 15:58:51 +05301645 def delink_advance_entries(self, linked_doc_name):
1646 total_allocated_amount = 0
1647 for adv in self.advances:
1648 consider_for_total_advance = True
1649 if adv.reference_name == linked_doc_name:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301650 frappe.db.sql(
1651 """delete from `tab{0} Advance`
1652 where name = %s""".format(
1653 self.doctype
1654 ),
1655 adv.name,
1656 )
Nabin Hait297d74a2016-11-23 15:58:51 +05301657 consider_for_total_advance = False
1658
1659 if consider_for_total_advance:
1660 total_allocated_amount += flt(adv.allocated_amount, adv.precision("allocated_amount"))
1661
Ankush Menat494bd9e2022-03-28 18:52:46 +05301662 frappe.db.set_value(
1663 self.doctype, self.name, "total_advance", total_allocated_amount, update_modified=False
1664 )
Rohit Waghchaure6087fe12016-04-09 14:31:09 +05301665
KanchanChauhan49a50fe2016-11-18 13:57:53 +05301666 def group_similar_items(self):
1667 group_item_qty = {}
1668 group_item_amount = {}
Shreya Shah785f1aa2018-10-11 10:14:25 +05301669 # to update serial number in print
1670 count = 0
KanchanChauhan49a50fe2016-11-18 13:57:53 +05301671
1672 for item in self.items:
1673 group_item_qty[item.item_code] = group_item_qty.get(item.item_code, 0) + item.qty
1674 group_item_amount[item.item_code] = group_item_amount.get(item.item_code, 0) + item.amount
1675
1676 duplicate_list = []
KanchanChauhan49a50fe2016-11-18 13:57:53 +05301677 for item in self.items:
1678 if item.item_code in group_item_qty:
Shreya Shah785f1aa2018-10-11 10:14:25 +05301679 count += 1
KanchanChauhan49a50fe2016-11-18 13:57:53 +05301680 item.qty = group_item_qty[item.item_code]
1681 item.amount = group_item_amount[item.item_code]
deepeshgarg007e8d21cd2019-06-24 17:46:44 +05301682
1683 if item.qty:
1684 item.rate = flt(flt(item.amount) / flt(item.qty), item.precision("rate"))
1685 else:
1686 item.rate = 0
1687
Shreya Shah785f1aa2018-10-11 10:14:25 +05301688 item.idx = count
KanchanChauhan49a50fe2016-11-18 13:57:53 +05301689 del group_item_qty[item.item_code]
1690 else:
1691 duplicate_list.append(item)
KanchanChauhan49a50fe2016-11-18 13:57:53 +05301692 for item in duplicate_list:
1693 self.remove(item)
1694
tunde32aa7c12017-09-07 06:52:15 +01001695 def set_payment_schedule(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301696 if self.doctype == "Sales Invoice" and self.is_pos:
1697 self.payment_terms_template = ""
Manas Solankia7f55892018-04-02 10:32:00 +05301698 return
rohitwaghchauredb9fa782018-03-01 10:32:29 +05301699
Ankush Menat494bd9e2022-03-28 18:52:46 +05301700 party_account_currency = self.get("party_account_currency")
Deepesh Garg26210162020-08-11 16:06:13 +05301701 if not party_account_currency:
1702 party_type, party = self.get_party()
1703
1704 if party_type and party:
1705 party_account_currency = get_party_account_currency(party_type, party, self.company)
1706
rohitwaghchaureda941af2018-01-17 16:23:04 +05301707 posting_date = self.get("bill_date") or self.get("posting_date") or self.get("transaction_date")
tundedf3a1752017-09-11 11:02:57 +01001708 date = self.get("due_date")
1709 due_date = date or posting_date
Deepesh Garg26210162020-08-11 16:06:13 +05301710
Saqib Ansarid552fe62021-04-23 14:46:52 +05301711 base_grand_total = self.get("base_rounded_total") or self.base_grand_total
1712 grand_total = self.get("rounded_total") or self.grand_total
Deepesh Garg5c758942023-04-16 17:11:24 +05301713 automatically_fetch_payment_terms = 0
Deepesh Garg26210162020-08-11 16:06:13 +05301714
Nabin Hait2f9f4f92017-12-20 12:24:59 +05301715 if self.doctype in ("Sales Invoice", "Purchase Invoice"):
Saqib Ansarid552fe62021-04-23 14:46:52 +05301716 base_grand_total = base_grand_total - flt(self.base_write_off_amount)
Nabin Hait2f9f4f92017-12-20 12:24:59 +05301717 grand_total = grand_total - flt(self.write_off_amount)
Deepesh Gargbcf56e62021-08-06 23:53:16 +05301718 po_or_so, doctype, fieldname = self.get_order_details()
Ankush Menat494bd9e2022-03-28 18:52:46 +05301719 automatically_fetch_payment_terms = cint(
1720 frappe.db.get_single_value("Accounts Settings", "automatically_fetch_payment_terms")
1721 )
tunde96b8f222017-09-08 15:35:59 +01001722
Rohit Waghchaure4a267b92019-05-09 19:50:00 +05301723 if self.get("total_advance"):
Saqib Ansarid552fe62021-04-23 14:46:52 +05301724 if party_account_currency == self.company_currency:
1725 base_grand_total -= self.get("total_advance")
Ankush Menat494bd9e2022-03-28 18:52:46 +05301726 grand_total = flt(
1727 base_grand_total / self.get("conversion_rate"), self.precision("grand_total")
1728 )
Saqib Ansarid552fe62021-04-23 14:46:52 +05301729 else:
1730 grand_total -= self.get("total_advance")
Ankush Menat494bd9e2022-03-28 18:52:46 +05301731 base_grand_total = flt(
1732 grand_total * self.get("conversion_rate"), self.precision("base_grand_total")
1733 )
Rohit Waghchaure4a267b92019-05-09 19:50:00 +05301734
Nabin Hait0551f7b2017-11-21 19:58:16 +05301735 if not self.get("payment_schedule"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301736 if (
1737 self.doctype in ["Sales Invoice", "Purchase Invoice"]
1738 and automatically_fetch_payment_terms
1739 and self.linked_order_has_payment_terms(po_or_so, fieldname, doctype)
1740 ):
Deepesh Gargbcf56e62021-08-06 23:53:16 +05301741 self.fetch_payment_terms_from_order(po_or_so, doctype)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301742 if self.get("payment_terms_template"):
Deepesh Gargbcf56e62021-08-06 23:53:16 +05301743 self.ignore_default_payment_terms_template = 1
1744 elif self.get("payment_terms_template"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301745 data = get_payment_terms(
1746 self.payment_terms_template, posting_date, grand_total, base_grand_total
1747 )
Nabin Hait0551f7b2017-11-21 19:58:16 +05301748 for item in data:
1749 self.append("payment_schedule", item)
GangaManoj4323f4b2021-07-22 05:57:42 +05301750 elif self.doctype not in ["Purchase Receipt"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301751 data = dict(
1752 due_date=due_date,
1753 invoice_portion=100,
1754 payment_amount=grand_total,
1755 base_payment_amount=base_grand_total,
1756 )
Nabin Hait0551f7b2017-11-21 19:58:16 +05301757 self.append("payment_schedule", data)
Deepesh Gargbcf56e62021-08-06 23:53:16 +05301758
Deepesh Gargf7b50f22023-04-25 19:18:45 +05301759 if not (
1760 automatically_fetch_payment_terms
1761 and self.linked_order_has_payment_terms(po_or_so, fieldname, doctype)
1762 ):
Deepesh Garg5c758942023-04-16 17:11:24 +05301763 for d in self.get("payment_schedule"):
1764 if d.invoice_portion:
1765 d.payment_amount = flt(
1766 grand_total * flt(d.invoice_portion / 100), d.precision("payment_amount")
1767 )
1768 d.base_payment_amount = flt(
1769 base_grand_total * flt(d.invoice_portion / 100), d.precision("base_payment_amount")
1770 )
1771 d.outstanding = d.payment_amount
1772 elif not d.invoice_portion:
1773 d.base_payment_amount = flt(
1774 d.payment_amount * self.get("conversion_rate"), d.precision("base_payment_amount")
1775 )
ruthra kumar0da6c162023-05-16 18:57:42 +05301776 else:
1777 self.fetch_payment_terms_from_order(po_or_so, doctype)
1778 self.ignore_default_payment_terms_template = 1
tunde43870aa2017-08-18 11:59:30 +01001779
GangaManoj4323f4b2021-07-22 05:57:42 +05301780 def get_order_details(self):
1781 if self.doctype == "Sales Invoice":
Ankush Menat494bd9e2022-03-28 18:52:46 +05301782 po_or_so = self.get("items")[0].get("sales_order")
GangaManoj4323f4b2021-07-22 05:57:42 +05301783 po_or_so_doctype = "Sales Order"
1784 po_or_so_doctype_name = "sales_order"
1785
tunde43870aa2017-08-18 11:59:30 +01001786 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301787 po_or_so = self.get("items")[0].get("purchase_order")
GangaManoj4323f4b2021-07-22 05:57:42 +05301788 po_or_so_doctype = "Purchase Order"
1789 po_or_so_doctype_name = "purchase_order"
Ankush Menat4551d7d2021-08-19 13:41:10 +05301790
GangaManoj4323f4b2021-07-22 05:57:42 +05301791 return po_or_so, po_or_so_doctype, po_or_so_doctype_name
1792
GangaManojc7c90242021-07-29 19:18:35 +05301793 def linked_order_has_payment_terms(self, po_or_so, fieldname, doctype):
GangaManoj4323f4b2021-07-22 05:57:42 +05301794 if po_or_so and self.all_items_have_same_po_or_so(po_or_so, fieldname):
GangaManojc7c90242021-07-29 19:18:35 +05301795 if self.linked_order_has_payment_terms_template(po_or_so, doctype):
GangaManoj4323f4b2021-07-22 05:57:42 +05301796 return True
1797 elif self.linked_order_has_payment_schedule(po_or_so):
1798 return True
Ankush Menat4551d7d2021-08-19 13:41:10 +05301799
GangaManoj4323f4b2021-07-22 05:57:42 +05301800 return False
1801
1802 def all_items_have_same_po_or_so(self, po_or_so, fieldname):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301803 for item in self.get("items"):
GangaManoj4323f4b2021-07-22 05:57:42 +05301804 if item.get(fieldname) != po_or_so:
1805 return False
Ankush Menat4551d7d2021-08-19 13:41:10 +05301806
GangaManoj4323f4b2021-07-22 05:57:42 +05301807 return True
1808
GangaManojc7c90242021-07-29 19:18:35 +05301809 def linked_order_has_payment_terms_template(self, po_or_so, doctype):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301810 return frappe.get_value(doctype, po_or_so, "payment_terms_template")
GangaManoj4323f4b2021-07-22 05:57:42 +05301811
1812 def linked_order_has_payment_schedule(self, po_or_so):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301813 return frappe.get_all("Payment Schedule", filters={"parent": po_or_so})
GangaManoj4323f4b2021-07-22 05:57:42 +05301814
1815 def fetch_payment_terms_from_order(self, po_or_so, po_or_so_doctype):
1816 """
Ankush Menat494bd9e2022-03-28 18:52:46 +05301817 Fetch Payment Terms from Purchase/Sales Order on creating a new Purchase/Sales Invoice.
GangaManoj4323f4b2021-07-22 05:57:42 +05301818 """
1819 po_or_so = frappe.get_cached_doc(po_or_so_doctype, po_or_so)
1820
1821 self.payment_schedule = []
1822 self.payment_terms_template = po_or_so.payment_terms_template
1823
1824 for schedule in po_or_so.payment_schedule:
1825 payment_schedule = {
Ankush Menat494bd9e2022-03-28 18:52:46 +05301826 "payment_term": schedule.payment_term,
1827 "due_date": schedule.due_date,
1828 "invoice_portion": schedule.invoice_portion,
1829 "mode_of_payment": schedule.mode_of_payment,
1830 "description": schedule.description,
Deepesh Garg5c758942023-04-16 17:11:24 +05301831 "payment_amount": schedule.payment_amount,
1832 "base_payment_amount": schedule.base_payment_amount,
1833 "outstanding": schedule.outstanding,
1834 "paid_amount": schedule.paid_amount,
GangaManoj4323f4b2021-07-22 05:57:42 +05301835 }
GangaManoj5b33e752021-08-05 21:50:09 +05301836
Ankush Menat494bd9e2022-03-28 18:52:46 +05301837 if schedule.discount_type == "Percentage":
1838 payment_schedule["discount_type"] = schedule.discount_type
1839 payment_schedule["discount"] = schedule.discount
GangaManoj5b33e752021-08-05 21:50:09 +05301840
ruthra kumar9bd56b02022-02-01 14:14:04 +05301841 if not schedule.invoice_portion:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301842 payment_schedule["payment_amount"] = schedule.payment_amount
ruthra kumar9bd56b02022-02-01 14:14:04 +05301843
GangaManoj4323f4b2021-07-22 05:57:42 +05301844 self.append("payment_schedule", payment_schedule)
tunde43870aa2017-08-18 11:59:30 +01001845
tundebe1b8712017-08-19 08:21:44 +01001846 def set_due_date(self):
Nabin Hait0551f7b2017-11-21 19:58:16 +05301847 due_dates = [d.due_date for d in self.get("payment_schedule") if d.due_date]
1848 if due_dates:
1849 self.due_date = max(due_dates)
tunde62af5c52017-09-22 15:16:38 +01001850
1851 def validate_payment_schedule_dates(self):
tunde77ecacc2017-09-22 23:12:55 +01001852 dates = []
tunde9bed2de2017-09-25 10:19:35 +01001853 li = []
tunde43870aa2017-08-18 11:59:30 +01001854
Ankush Menat494bd9e2022-03-28 18:52:46 +05301855 if self.doctype == "Sales Invoice" and self.is_pos:
1856 return
rohitwaghchauredb9fa782018-03-01 10:32:29 +05301857
tunde43870aa2017-08-18 11:59:30 +01001858 for d in self.get("payment_schedule"):
Nabin Hait2f9f4f92017-12-20 12:24:59 +05301859 if self.doctype == "Sales Order" and getdate(d.due_date) < getdate(self.transaction_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301860 frappe.throw(
1861 _("Row {0}: Due Date in the Payment Terms table cannot be before Posting Date").format(d.idx)
1862 )
tunde77ecacc2017-09-22 23:12:55 +01001863 elif d.due_date in dates:
mnatalia5f0e8d62018-05-22 06:38:50 +03001864 li.append(_("{0} in row {1}").format(d.due_date, d.idx))
tunde9bed2de2017-09-25 10:19:35 +01001865 dates.append(d.due_date)
1866
1867 if li:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301868 duplicates = "<br>" + "<br>".join(li)
1869 frappe.throw(
1870 _("Rows with duplicate due dates in other rows were found: {0}").format(duplicates)
1871 )
tunde43870aa2017-08-18 11:59:30 +01001872
tunde62af5c52017-09-22 15:16:38 +01001873 def validate_payment_schedule_amount(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301874 if self.doctype == "Sales Invoice" and self.is_pos:
1875 return
rohitwaghchauredb9fa782018-03-01 10:32:29 +05301876
Ankush Menat494bd9e2022-03-28 18:52:46 +05301877 party_account_currency = self.get("party_account_currency")
Deepesh Garg26210162020-08-11 16:06:13 +05301878 if not party_account_currency:
1879 party_type, party = self.get_party()
1880
1881 if party_type and party:
1882 party_account_currency = get_party_account_currency(party_type, party, self.company)
1883
Nabin Hait0551f7b2017-11-21 19:58:16 +05301884 if self.get("payment_schedule"):
1885 total = 0
Saqib Ansarid552fe62021-04-23 14:46:52 +05301886 base_total = 0
Nabin Hait0551f7b2017-11-21 19:58:16 +05301887 for d in self.get("payment_schedule"):
Deepesh Garg9c170522021-10-25 20:06:24 +05301888 total += flt(d.payment_amount, d.precision("payment_amount"))
1889 base_total += flt(d.base_payment_amount, d.precision("base_payment_amount"))
tunde43870aa2017-08-18 11:59:30 +01001890
Saqib Ansarid552fe62021-04-23 14:46:52 +05301891 base_grand_total = self.get("base_rounded_total") or self.base_grand_total
1892 grand_total = self.get("rounded_total") or self.grand_total
Rohit Waghchaure4a267b92019-05-09 19:50:00 +05301893
Nabin Haite591c852017-12-21 11:46:30 +05301894 if self.doctype in ("Sales Invoice", "Purchase Invoice"):
Saqib Ansarid552fe62021-04-23 14:46:52 +05301895 base_grand_total = base_grand_total - flt(self.base_write_off_amount)
Nabin Haite591c852017-12-21 11:46:30 +05301896 grand_total = grand_total - flt(self.write_off_amount)
Saqib Ansarid552fe62021-04-23 14:46:52 +05301897
1898 if self.get("total_advance"):
1899 if party_account_currency == self.company_currency:
1900 base_grand_total -= self.get("total_advance")
Ankush Menat494bd9e2022-03-28 18:52:46 +05301901 grand_total = flt(
1902 base_grand_total / self.get("conversion_rate"), self.precision("grand_total")
1903 )
Saqib Ansarid552fe62021-04-23 14:46:52 +05301904 else:
1905 grand_total -= self.get("total_advance")
Ankush Menat494bd9e2022-03-28 18:52:46 +05301906 base_grand_total = flt(
1907 grand_total * self.get("conversion_rate"), self.precision("base_grand_total")
1908 )
Deepesh Garg9c170522021-10-25 20:06:24 +05301909
Ankush Menat494bd9e2022-03-28 18:52:46 +05301910 if (
1911 flt(total, self.precision("grand_total")) - flt(grand_total, self.precision("grand_total"))
1912 > 0.1
1913 or flt(base_total, self.precision("base_grand_total"))
1914 - flt(base_grand_total, self.precision("base_grand_total"))
1915 > 0.1
1916 ):
1917 frappe.throw(
1918 _("Total Payment Amount in Payment Schedule must be equal to Grand / Rounded Total")
1919 )
tunde43870aa2017-08-18 11:59:30 +01001920
Nabin Hait877e1bb2017-11-17 12:27:43 +05301921 def is_rounded_total_disabled(self):
1922 if self.meta.get_field("disable_rounded_total"):
1923 return self.disable_rounded_total
1924 else:
1925 return frappe.db.get_single_value("Global Defaults", "disable_rounded_total")
1926
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05301927 def set_inter_company_account(self):
1928 """
Ankush Menat494bd9e2022-03-28 18:52:46 +05301929 Set intercompany account for inter warehouse transactions
1930 This account will be used in case billing company and internal customer's
1931 representation company is same
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05301932 """
1933
1934 if self.is_internal_transfer() and not self.unrealized_profit_loss_account:
Daizy Modi4efc9472022-11-07 09:21:03 +05301935 unrealized_profit_loss_account = frappe.get_cached_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301936 "Company", self.company, "unrealized_profit_loss_account"
1937 )
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05301938
1939 if not unrealized_profit_loss_account:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301940 msg = _(
1941 "Please select Unrealized Profit / Loss account or add default Unrealized Profit / Loss account account for company {0}"
1942 ).format(frappe.bold(self.company))
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05301943 frappe.throw(msg)
1944
1945 self.unrealized_profit_loss_account = unrealized_profit_loss_account
1946
1947 def is_internal_transfer(self):
1948 """
Ankush Menat494bd9e2022-03-28 18:52:46 +05301949 It will an internal transfer if its an internal customer and representation
1950 company is same as billing company
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05301951 """
Ankush Menat494bd9e2022-03-28 18:52:46 +05301952 if self.doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
1953 internal_party_field = "is_internal_customer"
1954 elif self.doctype in ("Purchase Invoice", "Purchase Receipt", "Purchase Order"):
1955 internal_party_field = "is_internal_supplier"
Ankush Menat3714e362022-05-16 18:09:14 +05301956 else:
1957 return False
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05301958
1959 if self.get(internal_party_field) and (self.represents_company == self.company):
1960 return True
1961
1962 return False
1963
Saqib Ansari977b09b2021-08-19 17:57:30 +05301964 def process_common_party_accounting(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301965 is_invoice = self.doctype in ["Sales Invoice", "Purchase Invoice"]
Saqib Ansari977b09b2021-08-19 17:57:30 +05301966 if not is_invoice:
1967 return
1968
Ankush Menat494bd9e2022-03-28 18:52:46 +05301969 if frappe.db.get_single_value("Accounts Settings", "enable_common_party_accounting"):
Saqib Ansari977b09b2021-08-19 17:57:30 +05301970 party_link = self.get_common_party_link()
1971 if party_link and self.outstanding_amount:
1972 self.create_advance_and_reconcile(party_link)
1973
1974 def get_common_party_link(self):
1975 party_type, party = self.get_party()
Saqib Ansari72543682021-08-25 20:15:23 +05301976 return frappe.db.get_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301977 doctype="Party Link",
1978 filters={"secondary_role": party_type, "secondary_party": party},
1979 fieldname=["primary_role", "primary_party"],
1980 as_dict=True,
Saqib Ansari72543682021-08-25 20:15:23 +05301981 )
Saqib Ansari977b09b2021-08-19 17:57:30 +05301982
1983 def create_advance_and_reconcile(self, party_link):
1984 secondary_party_type, secondary_party = self.get_party()
1985 primary_party_type, primary_party = party_link.primary_role, party_link.primary_party
1986
1987 primary_account = get_party_account(primary_party_type, primary_party, self.company)
1988 secondary_account = get_party_account(secondary_party_type, secondary_party, self.company)
1989
Ankush Menat494bd9e2022-03-28 18:52:46 +05301990 jv = frappe.new_doc("Journal Entry")
1991 jv.voucher_type = "Journal Entry"
Saqib Ansari977b09b2021-08-19 17:57:30 +05301992 jv.posting_date = self.posting_date
1993 jv.company = self.company
Ankush Menat494bd9e2022-03-28 18:52:46 +05301994 jv.remark = "Adjustment for {} {}".format(self.doctype, self.name)
Saqib Ansari977b09b2021-08-19 17:57:30 +05301995
1996 reconcilation_entry = frappe._dict()
1997 advance_entry = frappe._dict()
Saqib Ansari977b09b2021-08-19 17:57:30 +05301998
1999 reconcilation_entry.account = secondary_account
2000 reconcilation_entry.party_type = secondary_party_type
2001 reconcilation_entry.party = secondary_party
2002 reconcilation_entry.reference_type = self.doctype
2003 reconcilation_entry.reference_name = self.name
Deepesh Gargf88431a2023-04-25 20:54:22 +05302004 reconcilation_entry.cost_center = self.cost_center or erpnext.get_default_cost_center(
2005 self.company
2006 )
Saqib Ansari977b09b2021-08-19 17:57:30 +05302007
2008 advance_entry.account = primary_account
2009 advance_entry.party_type = primary_party_type
2010 advance_entry.party = primary_party
Deepesh Gargf88431a2023-04-25 20:54:22 +05302011 advance_entry.cost_center = self.cost_center or erpnext.get_default_cost_center(self.company)
Ankush Menat494bd9e2022-03-28 18:52:46 +05302012 advance_entry.is_advance = "Yes"
Saqib Ansari977b09b2021-08-19 17:57:30 +05302013
Ankush Menat494bd9e2022-03-28 18:52:46 +05302014 if self.doctype == "Sales Invoice":
Saqib Ansari977b09b2021-08-19 17:57:30 +05302015 reconcilation_entry.credit_in_account_currency = self.outstanding_amount
2016 advance_entry.debit_in_account_currency = self.outstanding_amount
2017 else:
2018 advance_entry.credit_in_account_currency = self.outstanding_amount
2019 reconcilation_entry.debit_in_account_currency = self.outstanding_amount
2020
Ankush Menat494bd9e2022-03-28 18:52:46 +05302021 jv.append("accounts", reconcilation_entry)
2022 jv.append("accounts", advance_entry)
Saqib Ansari977b09b2021-08-19 17:57:30 +05302023
2024 jv.save()
2025 jv.submit()
2026
Deepesh Gargd05d1532022-06-14 12:50:49 +05302027 def check_conversion_rate(self):
2028 default_currency = erpnext.get_company_currency(self.company)
2029 if not default_currency:
2030 throw(_("Please enter default currency in Company Master"))
2031 if (
2032 (self.currency == default_currency and flt(self.conversion_rate) != 1.00)
2033 or not self.conversion_rate
2034 or (self.currency != default_currency and flt(self.conversion_rate) == 1.00)
2035 ):
2036 throw(_("Conversion rate cannot be 0 or 1"))
2037
Saif Ur Rehman7a5d75b2021-09-13 23:01:52 +05002038 def check_finance_books(self, item, asset):
Nabin Haitfefe9502022-09-09 14:40:36 +05302039 if (
2040 len(asset.finance_books) > 1
2041 and not item.get("finance_book")
2042 and not self.get("finance_book")
2043 and asset.finance_books[0].finance_book
2044 ):
2045 frappe.throw(
2046 _("Select finance book for the item {0} at row {1}").format(item.item_code, item.idx)
2047 )
Saif Ur Rehman7a5d75b2021-09-13 23:01:52 +05002048
Ankush Menat494bd9e2022-03-28 18:52:46 +05302049
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05302050@frappe.whitelist()
Rushabh Mehtaf56d73c2013-10-10 16:35:09 +05302051def get_tax_rate(account_head):
Daizy Modi4efc9472022-11-07 09:21:03 +05302052 return frappe.get_cached_value(
2053 "Account", account_head, ["tax_rate", "account_name"], as_dict=True
2054 )
Rushabh Mehtaa33d4682015-06-01 17:15:42 +05302055
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002056
Nabin Haitffc7f3f2015-05-12 15:07:02 +05302057@frappe.whitelist()
Nabin Haita2426fc2018-01-15 17:45:46 +05302058def get_default_taxes_and_charges(master_doctype, tax_template=None, company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302059 if not company:
2060 return {}
rohitwaghchaure505661b2017-12-11 14:52:28 +05302061
Nabin Haita2426fc2018-01-15 17:45:46 +05302062 if tax_template and company:
Daizy Modi4efc9472022-11-07 09:21:03 +05302063 tax_template_company = frappe.get_cached_value(master_doctype, tax_template, "company")
Nabin Haita2426fc2018-01-15 17:45:46 +05302064 if tax_template_company == company:
2065 return
2066
2067 default_tax = frappe.db.get_value(master_doctype, {"is_default": 1, "company": company})
rohitwaghchaure505661b2017-12-11 14:52:28 +05302068
Rushabh Mehta98aa5812017-11-14 09:32:32 +05302069 return {
Ankush Menat494bd9e2022-03-28 18:52:46 +05302070 "taxes_and_charges": default_tax,
2071 "taxes": get_taxes_and_charges(master_doctype, default_tax),
Rushabh Mehta98aa5812017-11-14 09:32:32 +05302072 }
Nabin Hait6b039142014-05-02 15:45:10 +05302073
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002074
Nabin Hait6b039142014-05-02 15:45:10 +05302075@frappe.whitelist()
Nabin Haitffc7f3f2015-05-12 15:07:02 +05302076def get_taxes_and_charges(master_doctype, master_name):
Nabin Hait1fe50122015-05-16 12:14:39 +05302077 if not master_name:
2078 return
Ankush Menat77dcdff2022-06-01 22:01:07 +05302079 from frappe.model import child_table_fields, default_fields
Ankush Menat494bd9e2022-03-28 18:52:46 +05302080
Nabin Hait6b039142014-05-02 15:45:10 +05302081 tax_master = frappe.get_doc(master_doctype, master_name)
2082
2083 taxes_and_charges = []
Nabin Haitffc7f3f2015-05-12 15:07:02 +05302084 for i, tax in enumerate(tax_master.get("taxes")):
Nabin Hait6b039142014-05-02 15:45:10 +05302085 tax = tax.as_dict()
2086
Ankush Menat77dcdff2022-06-01 22:01:07 +05302087 for fieldname in default_fields + child_table_fields:
Nabin Hait6b039142014-05-02 15:45:10 +05302088 if fieldname in tax:
2089 del tax[fieldname]
2090
2091 taxes_and_charges.append(tax)
2092
2093 return taxes_and_charges
Rushabh Mehta66e08e32014-09-29 12:17:03 +05302094
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002095
Rushabh Mehta66e08e32014-09-29 12:17:03 +05302096def validate_conversion_rate(currency, conversion_rate, conversion_rate_label, company):
2097 """common validation for currency and price list currency"""
2098
Ankush Menat494bd9e2022-03-28 18:52:46 +05302099 company_currency = frappe.get_cached_value("Company", company, "default_currency")
Rushabh Mehta66e08e32014-09-29 12:17:03 +05302100
2101 if not conversion_rate:
Saqib60212ff2020-10-26 11:17:04 +05302102 throw(
Ankush Menat494bd9e2022-03-28 18:52:46 +05302103 _("{0} is mandatory. Maybe Currency Exchange record is not created for {1} to {2}.").format(
2104 conversion_rate_label, currency, company_currency
2105 )
Saqib60212ff2020-10-26 11:17:04 +05302106 )
Nabin Hait613d0812015-02-23 11:58:15 +05302107
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002108
Nabin Hait613d0812015-02-23 11:58:15 +05302109def validate_taxes_and_charges(tax):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302110 if tax.charge_type in ["Actual", "On Net Total", "On Paid Amount"] and tax.row_id:
2111 frappe.throw(
2112 _("Can refer row only if the charge type is 'On Previous Row Amount' or 'Previous Row Total'")
2113 )
2114 elif tax.charge_type in ["On Previous Row Amount", "On Previous Row Total"]:
Nabin Hait613d0812015-02-23 11:58:15 +05302115 if cint(tax.idx) == 1:
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002116 frappe.throw(
Ankush Menat494bd9e2022-03-28 18:52:46 +05302117 _(
2118 "Cannot select charge type as 'On Previous Row Amount' or 'On Previous Row Total' for first row"
2119 )
2120 )
Nabin Hait613d0812015-02-23 11:58:15 +05302121 elif not tax.row_id:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302122 frappe.throw(
2123 _("Please specify a valid Row ID for row {0} in table {1}").format(tax.idx, _(tax.doctype))
2124 )
Nabin Hait613d0812015-02-23 11:58:15 +05302125 elif tax.row_id and cint(tax.row_id) >= cint(tax.idx):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302126 frappe.throw(
2127 _("Cannot refer row number greater than or equal to current row number for this Charge type")
2128 )
Nabin Hait613d0812015-02-23 11:58:15 +05302129
Rushabh Mehta2a21bc92015-02-25 15:08:42 +05302130 if tax.charge_type == "Actual":
Nabin Haitbc6c3602015-02-27 23:40:56 +05302131 tax.rate = None
Rushabh Mehta2a21bc92015-02-25 15:08:42 +05302132
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002133
Ankush Menat494bd9e2022-03-28 18:52:46 +05302134def validate_account_head(idx, account, company, context=""):
2135 account_company = frappe.get_cached_value("Account", account, "company")
Anuja Pawar0e337be2021-08-10 17:26:35 +05302136
Deepesh Garg5a2b5712022-02-18 20:05:49 +05302137 if account_company != company:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302138 frappe.throw(
2139 _("Row {0}: {3} Account {1} does not belong to Company {2}").format(
2140 idx, frappe.bold(account), frappe.bold(company), context
2141 ),
2142 title=_("Invalid Account"),
2143 )
Anuja Pawar0e337be2021-08-10 17:26:35 +05302144
2145
2146def validate_cost_center(tax, doc):
2147 if not tax.cost_center:
2148 return
2149
Ankush Menat494bd9e2022-03-28 18:52:46 +05302150 company = frappe.get_cached_value("Cost Center", tax.cost_center, "company")
Anuja Pawar0e337be2021-08-10 17:26:35 +05302151
2152 if company != doc.company:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302153 frappe.throw(
2154 _("Row {0}: Cost Center {1} does not belong to Company {2}").format(
2155 tax.idx, frappe.bold(tax.cost_center), frappe.bold(doc.company)
2156 ),
2157 title=_("Invalid Cost Center"),
2158 )
Anuja Pawar0e337be2021-08-10 17:26:35 +05302159
2160
Nabin Hait613d0812015-02-23 11:58:15 +05302161def validate_inclusive_tax(tax, doc):
2162 def _on_previous_row_error(row_range):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302163 throw(
2164 _("To include tax in row {0} in Item rate, taxes in rows {1} must also be included").format(
2165 tax.idx, row_range
2166 )
2167 )
Nabin Hait613d0812015-02-23 11:58:15 +05302168
2169 if cint(getattr(tax, "included_in_print_rate", None)):
2170 if tax.charge_type == "Actual":
2171 # inclusive tax cannot be of type Actual
Ankush Menat494bd9e2022-03-28 18:52:46 +05302172 throw(
2173 _("Charge of type 'Actual' in row {0} cannot be included in Item Rate or Paid Amount").format(
2174 tax.idx
2175 )
2176 )
2177 elif tax.charge_type == "On Previous Row Amount" and not cint(
2178 doc.get("taxes")[cint(tax.row_id) - 1].included_in_print_rate
2179 ):
Nabin Hait613d0812015-02-23 11:58:15 +05302180 # referred row should also be inclusive
2181 _on_previous_row_error(tax.row_id)
Ankush Menat494bd9e2022-03-28 18:52:46 +05302182 elif tax.charge_type == "On Previous Row Total" and not all(
2183 [cint(t.included_in_print_rate) for t in doc.get("taxes")[: cint(tax.row_id) - 1]]
2184 ):
Deepesh Garg5ef9a622021-06-14 14:34:44 +05302185 # all rows about the referred tax should be inclusive
Nabin Hait613d0812015-02-23 11:58:15 +05302186 _on_previous_row_error("1 - %d" % (tax.row_id,))
Nabin Hait93b3a372015-02-24 17:08:34 +05302187 elif tax.get("category") == "Valuation":
Nabin Hait19ea7212020-08-11 20:34:57 +05302188 frappe.throw(_("Valuation type charges can not be marked as Inclusive"))
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05302189
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05302190
Ankush Menat494bd9e2022-03-28 18:52:46 +05302191def set_balance_in_account_currency(
2192 gl_dict, account_currency=None, conversion_rate=None, company_currency=None
2193):
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002194 if (not conversion_rate) and (account_currency != company_currency):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302195 frappe.throw(
2196 _("Account: {0} with currency: {1} can not be selected").format(
2197 gl_dict.account, account_currency
2198 )
2199 )
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002200
Ankush Menat494bd9e2022-03-28 18:52:46 +05302201 gl_dict["account_currency"] = (
2202 company_currency if account_currency == company_currency else account_currency
2203 )
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05302204
2205 # set debit/credit in account currency if not provided
2206 if flt(gl_dict.debit) and not flt(gl_dict.debit_in_account_currency):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302207 gl_dict.debit_in_account_currency = (
2208 gl_dict.debit
2209 if account_currency == company_currency
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05302210 else flt(gl_dict.debit / conversion_rate, 2)
Ankush Menat494bd9e2022-03-28 18:52:46 +05302211 )
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05302212
2213 if flt(gl_dict.credit) and not flt(gl_dict.credit_in_account_currency):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302214 gl_dict.credit_in_account_currency = (
2215 gl_dict.credit
2216 if account_currency == company_currency
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05302217 else flt(gl_dict.credit / conversion_rate, 2)
Ankush Menat494bd9e2022-03-28 18:52:46 +05302218 )
Nabin Hait1991c7b2016-06-27 20:09:05 +05302219
2220
Ankush Menat494bd9e2022-03-28 18:52:46 +05302221def get_advance_journal_entries(
2222 party_type,
2223 party,
2224 party_account,
2225 amount_field,
2226 order_doctype,
2227 order_list,
2228 include_unallocated=True,
2229):
Gursheen Anand4ee16372023-06-08 13:15:23 +05302230 journal_entry = frappe.qb.DocType("Journal Entry")
2231 journal_acc = frappe.qb.DocType("Journal Entry Account")
2232 q = (
2233 frappe.qb.from_(journal_entry)
Gursheen Anand74619262023-06-02 17:13:51 +05302234 .inner_join(journal_acc)
2235 .on(journal_entry.name == journal_acc.parent)
2236 .select(
Gursheen Anand4ee16372023-06-08 13:15:23 +05302237 ConstantColumn("Journal Entry").as_("reference_type"),
2238 (journal_entry.name).as_("reference_name"),
2239 (journal_entry.remark).as_("remarks"),
Deepesh Garg3aead052023-06-22 11:41:43 +05302240 (journal_acc[amount_field]).as_("amount"),
Gursheen Anand4ee16372023-06-08 13:15:23 +05302241 (journal_acc.name).as_("reference_row"),
2242 (journal_acc.reference_name).as_("against_order"),
2243 (journal_acc.exchange_rate),
Gursheen Anand74619262023-06-02 17:13:51 +05302244 )
Gursheen Anand4ee16372023-06-08 13:15:23 +05302245 .where(
2246 journal_acc.account.isin(party_account)
2247 & (journal_acc.party_type == party_type)
2248 & (journal_acc.party == party)
2249 & (journal_acc.is_advance == "Yes")
2250 & (journal_entry.docstatus == 1)
2251 )
2252 )
Gursheen Anand74619262023-06-02 17:13:51 +05302253 if party_type == "Customer":
2254 q = q.where(journal_acc.credit_in_account_currency > 0)
Nabin Hait1991c7b2016-06-27 20:09:05 +05302255
Gursheen Anand4ee16372023-06-08 13:15:23 +05302256 else:
2257 q = q.where(journal_acc.debit_in_account_currency > 0)
2258
Deepesh Garg3aead052023-06-22 11:41:43 +05302259 if include_unallocated:
2260 q = q.where((journal_acc.reference_name.isnull()) | (journal_acc.reference_name == ""))
2261
Nabin Hait1991c7b2016-06-27 20:09:05 +05302262 if order_list:
Deepesh Garg3aead052023-06-22 11:41:43 +05302263 q = q.where(
Deepesh Garg6d121ae2023-06-22 13:03:09 +05302264 (journal_acc.reference_type == order_doctype) & ((journal_acc.reference_type).isin(order_list))
Deepesh Garg3aead052023-06-22 11:41:43 +05302265 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05302266
Gursheen Anand74619262023-06-02 17:13:51 +05302267 q = q.orderby(journal_entry.posting_date)
Rushabh Mehta66958302017-01-16 16:57:53 +05302268
Gursheen Anand74619262023-06-02 17:13:51 +05302269 journal_entries = q.run(as_dict=True)
Nabin Hait1991c7b2016-06-27 20:09:05 +05302270 return list(journal_entries)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05302271
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002272
Ankush Menat494bd9e2022-03-28 18:52:46 +05302273def get_advance_payment_entries(
2274 party_type,
2275 party,
2276 party_account,
2277 order_doctype,
2278 order_list=None,
2279 include_unallocated=True,
2280 against_all_orders=False,
2281 limit=None,
2282 condition=None,
2283):
Gursheen Anand74619262023-06-02 17:13:51 +05302284
Deepesh Garg92f845c2023-06-21 12:21:19 +05302285 payment_entries = []
2286 payment_entry = frappe.qb.DocType("Payment Entry")
Gursheen Anand74619262023-06-02 17:13:51 +05302287
Deepesh Garg92f845c2023-06-21 12:21:19 +05302288 if order_list or against_all_orders:
2289 q = get_common_query(
2290 party_type,
2291 party,
2292 party_account,
2293 limit,
2294 condition,
2295 )
2296 payment_ref = frappe.qb.DocType("Payment Entry Reference")
Gursheen Anand74619262023-06-02 17:13:51 +05302297
Deepesh Garg92f845c2023-06-21 12:21:19 +05302298 q = q.inner_join(payment_ref).on(payment_entry.name == payment_ref.parent)
2299 q = q.select(
2300 (payment_ref.allocated_amount).as_("amount"),
2301 (payment_ref.name).as_("reference_row"),
2302 (payment_ref.reference_name).as_("against_order"),
Deepesh Garg92f845c2023-06-21 12:21:19 +05302303 )
2304
Deepesh Garg3aead052023-06-22 11:41:43 +05302305 q = q.where(payment_ref.reference_doctype == order_doctype)
Deepesh Garg92f845c2023-06-21 12:21:19 +05302306 if order_list:
2307 q = q.where(payment_ref.reference_name.isin(order_list))
2308
2309 allocated = list(q.run(as_dict=True))
2310 payment_entries += allocated
Deepesh Garg92f845c2023-06-21 12:21:19 +05302311 if include_unallocated:
2312 q = get_common_query(
2313 party_type,
2314 party,
2315 party_account,
2316 limit,
2317 condition,
2318 )
2319 q = q.select((payment_entry.unallocated_amount).as_("amount"))
2320 q = q.where(payment_entry.unallocated_amount > 0)
2321
2322 unallocated = list(q.run(as_dict=True))
2323 payment_entries += unallocated
Deepesh Garg92f845c2023-06-21 12:21:19 +05302324 return payment_entries
Gursheen Anand74619262023-06-02 17:13:51 +05302325
Saqiba20999c2021-07-12 14:33:23 +05302326
Deepesh Garg92f845c2023-06-21 12:21:19 +05302327def get_common_query(
Gursheen Anand4ee16372023-06-08 13:15:23 +05302328 party_type,
2329 party,
2330 party_account,
Gursheen Anand4ee16372023-06-08 13:15:23 +05302331 limit,
2332 condition,
2333):
2334 payment_type = "Receive" if party_type == "Customer" else "Pay"
2335 payment_entry = frappe.qb.DocType("Payment Entry")
Gursheen Anand4ee16372023-06-08 13:15:23 +05302336
2337 q = (
2338 frappe.qb.from_(payment_entry)
Gursheen Anand74619262023-06-02 17:13:51 +05302339 .select(
Gursheen Anand4ee16372023-06-08 13:15:23 +05302340 ConstantColumn("Payment Entry").as_("reference_type"),
2341 (payment_entry.name).as_("reference_name"),
Gursheen Anand74619262023-06-02 17:13:51 +05302342 payment_entry.posting_date,
Gursheen Anand4ee16372023-06-08 13:15:23 +05302343 (payment_entry.remarks).as_("remarks"),
Ankush Menat494bd9e2022-03-28 18:52:46 +05302344 )
Gursheen Anand74619262023-06-02 17:13:51 +05302345 .where(payment_entry.payment_type == payment_type)
2346 .where(payment_entry.party_type == party_type)
2347 .where(payment_entry.party == party)
2348 .where(payment_entry.docstatus == 1)
2349 )
Gursheen Anand4ee16372023-06-08 13:15:23 +05302350
Gursheen Anand74619262023-06-02 17:13:51 +05302351 if party_type == "Customer":
Deepesh Gargb64ebc62023-06-21 17:49:45 +05302352 q = q.select((payment_entry.paid_from_account_currency).as_("currency"))
Gursheen Anand4ee16372023-06-08 13:15:23 +05302353 q = q.select(payment_entry.paid_from)
2354 q = q.where(payment_entry.paid_from.isin(party_account))
Gursheen Anand74619262023-06-02 17:13:51 +05302355 else:
Deepesh Gargb64ebc62023-06-21 17:49:45 +05302356 q = q.select((payment_entry.paid_to_account_currency).as_("currency"))
Gursheen Anand74619262023-06-02 17:13:51 +05302357 q = q.select(payment_entry.paid_to)
Gursheen Anand4ee16372023-06-08 13:15:23 +05302358 q = q.where(payment_entry.paid_to.isin(party_account))
Gursheen Anand74619262023-06-02 17:13:51 +05302359
2360 if payment_type == "Receive":
Deepesh Garg92f845c2023-06-21 12:21:19 +05302361 q = q.select((payment_entry.source_exchange_rate).as_("exchange_rate"))
Gursheen Anand4ee16372023-06-08 13:15:23 +05302362 else:
Deepesh Garg92f845c2023-06-21 12:21:19 +05302363 q = q.select((payment_entry.target_exchange_rate).as_("exchange_rate"))
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05302364
Deepesh Garg92f845c2023-06-21 12:21:19 +05302365 if condition:
2366 q = q.where(payment_entry.company == condition["company"])
2367 q = (
2368 q.where(payment_entry.posting_date >= condition["from_payment_date"])
2369 if condition.get("from_payment_date")
2370 else q
Gursheen Anand74619262023-06-02 17:13:51 +05302371 )
Deepesh Garg92f845c2023-06-21 12:21:19 +05302372 q = (
2373 q.where(payment_entry.posting_date <= condition["to_payment_date"])
2374 if condition.get("to_payment_date")
2375 else q
2376 )
2377 if condition.get("get_payments") == True:
2378 q = (
2379 q.where(payment_entry.cost_center == condition["cost_center"])
2380 if condition.get("cost_center")
2381 else q
2382 )
2383 q = (
2384 q.where(payment_entry.unallocated_amount >= condition["minimum_payment_amount"])
2385 if condition.get("minimum_payment_amount")
2386 else q
2387 )
2388 q = (
2389 q.where(payment_entry.unallocated_amount <= condition["maximum_payment_amount"])
2390 if condition.get("maximum_payment_amount")
2391 else q
2392 )
2393 else:
2394 q = (
2395 q.where(payment_entry.total_debit >= condition["minimum_payment_amount"])
2396 if condition.get("minimum_payment_amount")
2397 else q
2398 )
2399 q = (
2400 q.where(payment_entry.total_debit <= condition["maximum_payment_amount"])
2401 if condition.get("maximum_payment_amount")
2402 else q
2403 )
Gursheen Anand74619262023-06-02 17:13:51 +05302404
2405 q = q.orderby(payment_entry.posting_date)
2406 q = q.limit(limit) if limit else q
Deepesh Garg92f845c2023-06-21 12:21:19 +05302407
Gursheen Anand74619262023-06-02 17:13:51 +05302408 return q
Rohit Waghchaure2f1db572016-11-08 12:39:33 +05302409
Ankush Menat494bd9e2022-03-28 18:52:46 +05302410
Rohit Waghchaure2f1db572016-11-08 12:39:33 +05302411def update_invoice_status():
Sagar Vorac8b9a552021-09-22 12:11:35 +05302412 """Updates status as Overdue for applicable invoices. Runs daily."""
Sagar Vora8d9d0982021-10-20 19:15:35 +05302413 today = getdate()
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302414 payment_schedule = frappe.qb.DocType("Payment Schedule")
Sagar Vorac8b9a552021-09-22 12:11:35 +05302415 for doctype in ("Sales Invoice", "Purchase Invoice"):
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302416 invoice = frappe.qb.DocType(doctype)
2417
2418 consider_base_amount = invoice.party_account_currency != invoice.currency
2419 payment_amount = (
2420 frappe.qb.terms.Case()
2421 .when(consider_base_amount, payment_schedule.base_payment_amount)
2422 .else_(payment_schedule.payment_amount)
Sagar Vora8d9d0982021-10-20 19:15:35 +05302423 )
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002424
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302425 payable_amount = (
2426 frappe.qb.from_(payment_schedule)
2427 .select(Sum(payment_amount))
Ankush Menat494bd9e2022-03-28 18:52:46 +05302428 .where((payment_schedule.parent == invoice.name) & (payment_schedule.due_date < today))
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302429 )
2430
2431 total = (
2432 frappe.qb.terms.Case()
2433 .when(invoice.disable_rounded_total, invoice.grand_total)
2434 .else_(invoice.rounded_total)
2435 )
2436
2437 base_total = (
2438 frappe.qb.terms.Case()
2439 .when(invoice.disable_rounded_total, invoice.base_grand_total)
2440 .else_(invoice.base_rounded_total)
2441 )
2442
Ankush Menat494bd9e2022-03-28 18:52:46 +05302443 total_amount = frappe.qb.terms.Case().when(consider_base_amount, base_total).else_(total)
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302444
2445 is_overdue = total_amount - invoice.outstanding_amount < payable_amount
2446
2447 conditions = (
2448 (invoice.docstatus == 1)
2449 & (invoice.outstanding_amount > 0)
Ankush Menat494bd9e2022-03-28 18:52:46 +05302450 & (invoice.status.like("Unpaid%") | invoice.status.like("Partly Paid%"))
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302451 & (
Pruthvi Patel16a90d32021-12-20 13:24:19 +05302452 ((invoice.is_pos & invoice.due_date < today) | is_overdue)
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302453 if doctype == "Sales Invoice"
2454 else is_overdue
2455 )
2456 )
2457
Pruthvi Patel0799f372021-11-12 12:56:29 +05302458 status = (
2459 frappe.qb.terms.Case()
2460 .when(invoice.status.like("%Discounted"), "Overdue and Discounted")
2461 .else_("Overdue")
2462 )
2463
2464 frappe.qb.update(invoice).set("status", status).where(conditions).run()
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302465
2466
Nabin Hait92759692017-08-15 08:23:51 +05302467@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +05302468def get_payment_terms(
2469 terms_template, posting_date=None, grand_total=None, base_grand_total=None, bill_date=None
2470):
Nabin Hait92759692017-08-15 08:23:51 +05302471 if not terms_template:
2472 return
2473
2474 terms_doc = frappe.get_doc("Payment Terms Template", terms_template)
2475
2476 schedule = []
tundefb144302017-08-19 15:01:40 +01002477 for d in terms_doc.get("terms"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302478 term_details = get_payment_term_details(
2479 d, posting_date, grand_total, base_grand_total, bill_date
2480 )
Nabin Hait92759692017-08-15 08:23:51 +05302481 schedule.append(term_details)
2482
2483 return schedule
2484
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002485
Nabin Hait92759692017-08-15 08:23:51 +05302486@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +05302487def get_payment_term_details(
2488 term, posting_date=None, grand_total=None, base_grand_total=None, bill_date=None
2489):
Nabin Hait92759692017-08-15 08:23:51 +05302490 term_details = frappe._dict()
Ankush Menat8fe5feb2021-11-04 19:48:32 +05302491 if isinstance(term, str):
Nabin Hait92759692017-08-15 08:23:51 +05302492 term = frappe.get_doc("Payment Term", term)
2493 else:
2494 term_details.payment_term = term.payment_term
2495 term_details.description = term.description
2496 term_details.invoice_portion = term.invoice_portion
Rohit Waghchaure52bf56d2017-11-27 11:43:52 +05302497 term_details.payment_amount = flt(term.invoice_portion) * flt(grand_total) / 100
Saqib Ansarid552fe62021-04-23 14:46:52 +05302498 term_details.base_payment_amount = flt(term.invoice_portion) * flt(base_grand_total) / 100
Saqib0586b7d2021-03-31 15:03:53 +05302499 term_details.discount_type = term.discount_type
2500 term_details.discount = term.discount
Saqib0586b7d2021-03-31 15:03:53 +05302501 term_details.outstanding = term_details.payment_amount
2502 term_details.mode_of_payment = term.mode_of_payment
2503
Shreya Shah3a9eec22018-02-16 13:05:21 +05302504 if bill_date:
2505 term_details.due_date = get_due_date(term, bill_date)
Saqib0586b7d2021-03-31 15:03:53 +05302506 term_details.discount_date = get_discount_date(term, bill_date)
Shreya Shah3a9eec22018-02-16 13:05:21 +05302507 elif posting_date:
2508 term_details.due_date = get_due_date(term, posting_date)
Saqib0586b7d2021-03-31 15:03:53 +05302509 term_details.discount_date = get_discount_date(term, posting_date)
Shreya Shah3a9eec22018-02-16 13:05:21 +05302510
2511 if getdate(term_details.due_date) < getdate(posting_date):
2512 term_details.due_date = posting_date
2513
Nabin Hait92759692017-08-15 08:23:51 +05302514 return term_details
2515
Ankush Menat494bd9e2022-03-28 18:52:46 +05302516
Shreya Shah3a9eec22018-02-16 13:05:21 +05302517def get_due_date(term, posting_date=None, bill_date=None):
Nabin Hait92759692017-08-15 08:23:51 +05302518 due_date = None
Shreya Shah3a9eec22018-02-16 13:05:21 +05302519 date = bill_date or posting_date
Nabin Hait92759692017-08-15 08:23:51 +05302520 if term.due_date_based_on == "Day(s) after invoice date":
Shreya Shah3a9eec22018-02-16 13:05:21 +05302521 due_date = add_days(date, term.credit_days)
Nabin Hait92759692017-08-15 08:23:51 +05302522 elif term.due_date_based_on == "Day(s) after the end of the invoice month":
Shreya Shah3a9eec22018-02-16 13:05:21 +05302523 due_date = add_days(get_last_day(date), term.credit_days)
Nabin Hait92759692017-08-15 08:23:51 +05302524 elif term.due_date_based_on == "Month(s) after the end of the invoice month":
Deepesh Gargbfb81ef2022-11-30 20:53:41 +05302525 due_date = get_last_day(add_months(date, term.credit_months))
tunde96b8f222017-09-08 15:35:59 +01002526 return due_date
tundebabzyad08d4c2018-05-16 07:01:41 +01002527
Ankush Menat494bd9e2022-03-28 18:52:46 +05302528
Saqib0586b7d2021-03-31 15:03:53 +05302529def get_discount_date(term, posting_date=None, bill_date=None):
2530 discount_validity = None
2531 date = bill_date or posting_date
2532 if term.discount_validity_based_on == "Day(s) after invoice date":
2533 discount_validity = add_days(date, term.discount_validity)
2534 elif term.discount_validity_based_on == "Day(s) after the end of the invoice month":
2535 discount_validity = add_days(get_last_day(date), term.discount_validity)
2536 elif term.discount_validity_based_on == "Month(s) after the end of the invoice month":
Deepesh Gargbfb81ef2022-11-30 20:53:41 +05302537 discount_validity = get_last_day(add_months(date, term.discount_validity))
Saqib0586b7d2021-03-31 15:03:53 +05302538 return discount_validity
tundebabzyad08d4c2018-05-16 07:01:41 +01002539
Ankush Menat494bd9e2022-03-28 18:52:46 +05302540
tundebabzyad08d4c2018-05-16 07:01:41 +01002541def get_supplier_block_status(party_name):
2542 """
2543 Returns a dict containing the values of `on_hold`, `release_date` and `hold_type` of
2544 a `Supplier`
2545 """
Ankush Menat494bd9e2022-03-28 18:52:46 +05302546 supplier = frappe.get_doc("Supplier", party_name)
tundebabzyad08d4c2018-05-16 07:01:41 +01002547 info = {
Ankush Menat494bd9e2022-03-28 18:52:46 +05302548 "on_hold": supplier.on_hold,
2549 "release_date": supplier.release_date,
2550 "hold_type": supplier.hold_type,
tundebabzyad08d4c2018-05-16 07:01:41 +01002551 }
2552 return info
2553
Ankush Menat494bd9e2022-03-28 18:52:46 +05302554
marination698d9832020-08-19 14:59:46 +05302555def set_child_tax_template_and_map(item, child_item, parent_doc):
2556 args = {
Ankush Menat494bd9e2022-03-28 18:52:46 +05302557 "item_code": item.item_code,
2558 "posting_date": parent_doc.transaction_date,
2559 "tax_category": parent_doc.get("tax_category"),
2560 "company": parent_doc.get("company"),
2561 }
marination698d9832020-08-19 14:59:46 +05302562
2563 child_item.item_tax_template = _get_item_tax_template(args, item.taxes)
2564 if child_item.get("item_tax_template"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302565 child_item.item_tax_rate = get_item_tax_map(
2566 parent_doc.get("company"), child_item.item_tax_template, as_json=True
2567 )
2568
marination698d9832020-08-19 14:59:46 +05302569
Afshanb3bbebd2021-08-09 14:39:32 +05302570def add_taxes_from_tax_template(child_item, parent_doc, db_insert=True):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302571 add_taxes_from_item_tax_template = frappe.db.get_single_value(
2572 "Accounts Settings", "add_taxes_from_item_tax_template"
2573 )
Marica3b1be2b2020-10-22 17:04:31 +05302574
2575 if child_item.get("item_tax_rate") and add_taxes_from_item_tax_template:
2576 tax_map = json.loads(child_item.get("item_tax_rate"))
2577 for tax_type in tax_map:
2578 tax_rate = flt(tax_map[tax_type])
Ankush Menat494bd9e2022-03-28 18:52:46 +05302579 taxes = parent_doc.get("taxes") or []
Marica3b1be2b2020-10-22 17:04:31 +05302580 # add new row for tax head only if missing
2581 found = any(tax.account_head == tax_type for tax in taxes)
2582 if not found:
2583 tax_row = parent_doc.append("taxes", {})
Ankush Menat494bd9e2022-03-28 18:52:46 +05302584 tax_row.update(
2585 {
2586 "description": str(tax_type).split(" - ")[0],
2587 "charge_type": "On Net Total",
2588 "account_head": tax_type,
2589 "rate": tax_rate,
2590 }
2591 )
Marica3b1be2b2020-10-22 17:04:31 +05302592 if parent_doc.doctype == "Purchase Order":
Ankush Menat494bd9e2022-03-28 18:52:46 +05302593 tax_row.update({"category": "Total", "add_deduct_tax": "Add"})
Afshanb3bbebd2021-08-09 14:39:32 +05302594 if db_insert:
2595 tax_row.db_insert()
Marica3b1be2b2020-10-22 17:04:31 +05302596
Ankush Menat494bd9e2022-03-28 18:52:46 +05302597
2598def set_order_defaults(
2599 parent_doctype, parent_doctype_name, child_doctype, child_docname, trans_item
2600):
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002601 """
pateljannat637ddff2021-02-09 16:17:30 +05302602 Returns a Sales/Purchase Order Item child item containing the default values
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002603 """
Saqib438e0432020-04-03 10:02:56 +05302604 p_doc = frappe.get_doc(parent_doctype, parent_doctype_name)
Ankush Menat686685b2023-05-31 12:50:14 +05302605 child_item = frappe.new_doc(child_doctype, parent_doc=p_doc, parentfield=child_docname)
Ankush Menat494bd9e2022-03-28 18:52:46 +05302606 item = frappe.get_doc("Item", trans_item.get("item_code"))
marination0673f552021-03-31 01:38:22 +05302607
pateljannat637ddff2021-02-09 16:17:30 +05302608 for field in ("item_code", "item_name", "description", "item_group"):
marination0673f552021-03-31 01:38:22 +05302609 child_item.update({field: item.get(field)})
2610
pateljannat637ddff2021-02-09 16:17:30 +05302611 date_fieldname = "delivery_date" if child_doctype == "Sales Order Item" else "schedule_date"
Jannat Patelbb0d8f82021-02-11 20:59:28 +05302612 child_item.update({date_fieldname: trans_item.get(date_fieldname) or p_doc.get(date_fieldname)})
marination0673f552021-03-31 01:38:22 +05302613 child_item.stock_uom = item.stock_uom
Saqib61314242020-09-15 11:14:31 +05302614 child_item.uom = trans_item.get("uom") or item.stock_uom
Andy Zhu1062d7e2020-10-06 10:51:42 +13002615 child_item.warehouse = get_item_warehouse(item, p_doc, overwrite_warehouse=True)
Ankush Menat494bd9e2022-03-28 18:52:46 +05302616 conversion_factor = flt(
2617 get_conversion_factor(item.item_code, child_item.uom).get("conversion_factor")
2618 )
2619 child_item.conversion_factor = flt(trans_item.get("conversion_factor")) or conversion_factor
marination0673f552021-03-31 01:38:22 +05302620
pateljannat637ddff2021-02-09 16:17:30 +05302621 if child_doctype == "Purchase Order Item":
marination0673f552021-03-31 01:38:22 +05302622 # Initialized value will update in parent validation
2623 child_item.base_rate = 1
2624 child_item.base_amount = 1
pateljannat637ddff2021-02-09 16:17:30 +05302625 if child_doctype == "Sales Order Item":
2626 child_item.warehouse = get_item_warehouse(item, p_doc, overwrite_warehouse=True)
2627 if not child_item.warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302628 frappe.throw(
2629 _("Cannot find {} for item {}. Please set the same in Item Master or Stock Settings.").format(
2630 frappe.bold("default warehouse"), frappe.bold(item.item_code)
2631 )
2632 )
marination0673f552021-03-31 01:38:22 +05302633
marination698d9832020-08-19 14:59:46 +05302634 set_child_tax_template_and_map(item, child_item, p_doc)
Marica3b1be2b2020-10-22 17:04:31 +05302635 add_taxes_from_tax_template(child_item, p_doc)
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002636 return child_item
2637
Ankush Menat494bd9e2022-03-28 18:52:46 +05302638
marination0673f552021-03-31 01:38:22 +05302639def validate_child_on_delete(row, parent):
2640 """Check if partially transacted item (row) is being deleted."""
2641 if parent.doctype == "Sales Order":
2642 if flt(row.delivered_qty):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302643 frappe.throw(
2644 _("Row #{0}: Cannot delete item {1} which has already been delivered").format(
2645 row.idx, row.item_code
2646 )
2647 )
marination0673f552021-03-31 01:38:22 +05302648 if flt(row.work_order_qty):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302649 frappe.throw(
2650 _("Row #{0}: Cannot delete item {1} which has work order assigned to it.").format(
2651 row.idx, row.item_code
2652 )
2653 )
marination0673f552021-03-31 01:38:22 +05302654 if flt(row.ordered_qty):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302655 frappe.throw(
2656 _("Row #{0}: Cannot delete item {1} which is assigned to customer's purchase order.").format(
2657 row.idx, row.item_code
2658 )
2659 )
marination0673f552021-03-31 01:38:22 +05302660
2661 if parent.doctype == "Purchase Order" and flt(row.received_qty):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302662 frappe.throw(
2663 _("Row #{0}: Cannot delete item {1} which has already been received").format(
2664 row.idx, row.item_code
2665 )
2666 )
marination0673f552021-03-31 01:38:22 +05302667
2668 if flt(row.billed_amt):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302669 frappe.throw(
2670 _("Row #{0}: Cannot delete item {1} which has already been billed.").format(
2671 row.idx, row.item_code
2672 )
2673 )
2674
marination0673f552021-03-31 01:38:22 +05302675
2676def update_bin_on_delete(row, doctype):
2677 """Update bin for deleted item (row)."""
Chillar Anand915b3432021-09-02 16:44:59 +05302678 from erpnext.stock.stock_balance import (
2679 get_indented_qty,
2680 get_ordered_qty,
2681 get_reserved_qty,
2682 update_bin_qty,
2683 )
Ankush Menat494bd9e2022-03-28 18:52:46 +05302684
marination0673f552021-03-31 01:38:22 +05302685 qty_dict = {}
2686
2687 if doctype == "Sales Order":
2688 qty_dict["reserved_qty"] = get_reserved_qty(row.item_code, row.warehouse)
2689 else:
2690 if row.material_request_item:
2691 qty_dict["indented_qty"] = get_indented_qty(row.item_code, row.warehouse)
2692
2693 qty_dict["ordered_qty"] = get_ordered_qty(row.item_code, row.warehouse)
2694
Deepesh Garga61790c2022-02-22 20:58:10 +05302695 if row.warehouse:
2696 update_bin_qty(row.item_code, row.warehouse, qty_dict)
marination0673f552021-03-31 01:38:22 +05302697
Ankush Menat494bd9e2022-03-28 18:52:46 +05302698
Ankush Menatdd11f262022-06-27 15:55:08 +05302699def validate_and_delete_children(parent, data) -> bool:
Saqib0ad74492019-12-24 16:42:30 +05302700 deleted_children = []
2701 updated_item_names = [d.get("docname") for d in data]
2702 for item in parent.items:
2703 if item.name not in updated_item_names:
2704 deleted_children.append(item)
2705
2706 for d in deleted_children:
marination0673f552021-03-31 01:38:22 +05302707 validate_child_on_delete(d, parent)
Saqib0ad74492019-12-24 16:42:30 +05302708 d.cancel()
2709 d.delete()
marination0673f552021-03-31 01:38:22 +05302710
2711 # need to update ordered qty in Material Request first
2712 # bin uses Material Request Items to recalculate & update
2713 parent.update_prevdoc_status()
2714
2715 for d in deleted_children:
2716 update_bin_on_delete(d, parent.doctype)
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002717
Ankush Menatdd11f262022-06-27 15:55:08 +05302718 return bool(deleted_children)
2719
Rohan Bansala93b5142021-04-06 17:10:52 +05302720
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002721@frappe.whitelist()
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002722def update_child_qty_rate(parent_doctype, trans_items, parent_doctype_name, child_docname="items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302723 def check_doc_permissions(doc, perm_type="create"):
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302724 try:
2725 doc.check_permission(perm_type)
Saqib6db92fb2020-09-14 19:54:17 +05302726 except frappe.PermissionError:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302727 actions = {"create": "add", "write": "update"}
Saqib6db92fb2020-09-14 19:54:17 +05302728
Ankush Menat494bd9e2022-03-28 18:52:46 +05302729 frappe.throw(
2730 _("You do not have permissions to {} items in a {}.").format(
2731 actions[perm_type], parent_doctype
2732 ),
2733 title=_("Insufficient Permissions"),
2734 )
marination665c27a2020-09-15 12:04:38 +05302735
Saqib6db92fb2020-09-14 19:54:17 +05302736 def validate_workflow_conditions(doc):
2737 workflow = get_workflow_name(doc.doctype)
2738 if not workflow:
2739 return
2740
2741 workflow_doc = frappe.get_doc("Workflow", workflow)
2742 current_state = doc.get(workflow_doc.workflow_state_field)
2743 roles = frappe.get_roles()
2744
2745 transitions = []
2746 for transition in workflow_doc.transitions:
2747 if transition.next_state == current_state and transition.allowed in roles:
2748 if not is_transition_condition_satisfied(transition, doc):
2749 continue
2750 transitions.append(transition.as_dict())
2751
2752 if not transitions:
Saqib18318932020-09-23 13:01:49 +05302753 frappe.throw(
Ankush Menat494bd9e2022-03-28 18:52:46 +05302754 _("You are not allowed to update as per the conditions set in {} Workflow.").format(
2755 get_link_to_form("Workflow", workflow)
2756 ),
2757 title=_("Insufficient Permissions"),
Saqib18318932020-09-23 13:01:49 +05302758 )
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302759
Rohit Waghchaure8d5380a2020-06-18 14:06:31 +05302760 def get_new_child_item(item_row):
Rohit Waghchaureff70e612021-03-06 22:08:08 +05302761 child_doctype = "Sales Order Item" if parent_doctype == "Sales Order" else "Purchase Order Item"
Ankush Menat494bd9e2022-03-28 18:52:46 +05302762 return set_order_defaults(
2763 parent_doctype, parent_doctype_name, child_doctype, child_docname, item_row
2764 )
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302765
marination0c915432022-05-10 18:04:02 +05302766 def validate_quantity(child_item, new_data):
2767 if not flt(new_data.get("qty")):
2768 frappe.throw(
2769 _("Row # {0}: Quantity for Item {1} cannot be zero").format(
2770 new_data.get("idx"), frappe.bold(new_data.get("item_code"))
2771 ),
2772 title=_("Invalid Qty"),
2773 )
2774
2775 if parent_doctype == "Sales Order" and flt(new_data.get("qty")) < flt(child_item.delivered_qty):
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302776 frappe.throw(_("Cannot set quantity less than delivered quantity"))
2777
marination0c915432022-05-10 18:04:02 +05302778 if parent_doctype == "Purchase Order" and flt(new_data.get("qty")) < flt(
2779 child_item.received_qty
2780 ):
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302781 frappe.throw(_("Cannot set quantity less than received quantity"))
2782
Ankush Menatdd11f262022-06-27 15:55:08 +05302783 def should_update_supplied_items(doc) -> bool:
2784 """Subcontracted PO can allow following changes *after submit*:
2785
2786 1. Change rate of subcontracting - regardless of other changes.
2787 2. Change qty and/or add new items and/or remove items
2788 Exception: Transfer/Consumption is already made, qty change not allowed.
2789 """
2790
2791 supplied_items_processed = any(
2792 item.supplied_qty or item.consumed_qty or item.returned_qty for item in doc.supplied_items
2793 )
2794
2795 update_supplied_items = (
2796 any_qty_changed or items_added_or_removed or any_conversion_factor_changed
2797 )
2798 if update_supplied_items and supplied_items_processed:
2799 frappe.throw(_("Item qty can not be updated as raw materials are already processed."))
2800
2801 return update_supplied_items
2802
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002803 data = json.loads(trans_items)
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002804
Ankush Menatdd11f262022-06-27 15:55:08 +05302805 any_qty_changed = False # updated to true if any item's qty changes
2806 items_added_or_removed = False # updated to true if any new item is added or removed
2807 any_conversion_factor_changed = False
2808
Ankush Menat494bd9e2022-03-28 18:52:46 +05302809 sales_doctypes = ["Sales Order", "Sales Invoice", "Delivery Note", "Quotation"]
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302810 parent = frappe.get_doc(parent_doctype, parent_doctype_name)
marination665c27a2020-09-15 12:04:38 +05302811
Ankush Menat494bd9e2022-03-28 18:52:46 +05302812 check_doc_permissions(parent, "write")
Ankush Menatdd11f262022-06-27 15:55:08 +05302813 _removed_items = validate_and_delete_children(parent, data)
2814 items_added_or_removed |= _removed_items
Saqib0ad74492019-12-24 16:42:30 +05302815
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002816 for d in data:
2817 new_child_flag = False
Ankush Menat6de7b8e2021-08-24 12:18:40 +05302818
2819 if not d.get("item_code"):
2820 # ignore empty rows
2821 continue
2822
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002823 if not d.get("docname"):
2824 new_child_flag = True
Ankush Menatdd11f262022-06-27 15:55:08 +05302825 items_added_or_removed = True
Ankush Menat494bd9e2022-03-28 18:52:46 +05302826 check_doc_permissions(parent, "create")
Rohit Waghchaure8d5380a2020-06-18 14:06:31 +05302827 child_item = get_new_child_item(d)
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002828 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302829 check_doc_permissions(parent, "write")
2830 child_item = frappe.get_doc(parent_doctype + " Item", d.get("docname"))
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302831
Saqib Ansaric579b082020-05-29 22:21:50 +05302832 prev_rate, new_rate = flt(child_item.get("rate")), flt(d.get("rate"))
2833 prev_qty, new_qty = flt(child_item.get("qty")), flt(d.get("qty"))
Ankush Menat494bd9e2022-03-28 18:52:46 +05302834 prev_con_fac, new_con_fac = flt(child_item.get("conversion_factor")), flt(
2835 d.get("conversion_factor")
2836 )
Saqib61314242020-09-15 11:14:31 +05302837 prev_uom, new_uom = child_item.get("uom"), d.get("uom")
Saqib Ansaric579b082020-05-29 22:21:50 +05302838
Ankush Menat494bd9e2022-03-28 18:52:46 +05302839 if parent_doctype == "Sales Order":
Saqib Ansaric579b082020-05-29 22:21:50 +05302840 prev_date, new_date = child_item.get("delivery_date"), d.get("delivery_date")
Ankush Menat494bd9e2022-03-28 18:52:46 +05302841 elif parent_doctype == "Purchase Order":
marinationb7e94cc2020-06-15 11:32:42 +05302842 prev_date, new_date = child_item.get("schedule_date"), d.get("schedule_date")
Saqib Ansaric579b082020-05-29 22:21:50 +05302843
2844 rate_unchanged = prev_rate == new_rate
marinationf9c4b202020-06-12 15:49:53 +05302845 qty_unchanged = prev_qty == new_qty
Saqib61314242020-09-15 11:14:31 +05302846 uom_unchanged = prev_uom == new_uom
Saqib Ansaric579b082020-05-29 22:21:50 +05302847 conversion_factor_unchanged = prev_con_fac == new_con_fac
Ankush Menatdd11f262022-06-27 15:55:08 +05302848 any_conversion_factor_changed |= not conversion_factor_unchanged
Ankush Menat494bd9e2022-03-28 18:52:46 +05302849 date_unchanged = (
2850 prev_date == getdate(new_date) if prev_date and new_date else False
2851 ) # in case of delivery note etc
2852 if (
2853 rate_unchanged
2854 and qty_unchanged
2855 and conversion_factor_unchanged
2856 and uom_unchanged
2857 and date_unchanged
2858 ):
Saqibdd374ff2020-02-27 12:51:31 +05302859 continue
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002860
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302861 validate_quantity(child_item, d)
Ankush Menatdd11f262022-06-27 15:55:08 +05302862 if flt(child_item.get("qty")) != flt(d.get("qty")):
2863 any_qty_changed = True
deepeshgarg00777cde832018-12-27 15:56:51 +05302864
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002865 child_item.qty = flt(d.get("qty"))
Saqib56fea7d2020-10-09 21:19:25 +05302866 rate_precision = child_item.precision("rate") or 2
2867 conv_fac_precision = child_item.precision("conversion_factor") or 2
2868 qty_precision = child_item.precision("qty") or 2
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002869
Ankush Menat494bd9e2022-03-28 18:52:46 +05302870 if flt(child_item.billed_amt, rate_precision) > flt(
2871 flt(d.get("rate"), rate_precision) * flt(d.get("qty"), qty_precision), rate_precision
2872 ):
2873 frappe.throw(
2874 _("Row #{0}: Cannot set Rate if amount is greater than billed amount for Item {1}.").format(
2875 child_item.idx, child_item.item_code
2876 )
2877 )
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002878 else:
Saqib56fea7d2020-10-09 21:19:25 +05302879 child_item.rate = flt(d.get("rate"), rate_precision)
marinationf9c4b202020-06-12 15:49:53 +05302880
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302881 if d.get("conversion_factor"):
marinationf9c4b202020-06-12 15:49:53 +05302882 if child_item.stock_uom == child_item.uom:
2883 child_item.conversion_factor = 1
2884 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302885 child_item.conversion_factor = flt(d.get("conversion_factor"), conv_fac_precision)
marination665c27a2020-09-15 12:04:38 +05302886
Saqib61314242020-09-15 11:14:31 +05302887 if d.get("uom"):
2888 child_item.uom = d.get("uom")
Ankush Menat494bd9e2022-03-28 18:52:46 +05302889 conversion_factor = flt(
2890 get_conversion_factor(child_item.item_code, child_item.uom).get("conversion_factor")
2891 )
2892 child_item.conversion_factor = (
2893 flt(d.get("conversion_factor"), conv_fac_precision) or conversion_factor
2894 )
Mangesh-Khairnara3d52002019-08-05 10:16:40 +05302895
Ankush Menat494bd9e2022-03-28 18:52:46 +05302896 if d.get("delivery_date") and parent_doctype == "Sales Order":
2897 child_item.delivery_date = d.get("delivery_date")
marinationf9c4b202020-06-12 15:49:53 +05302898
Ankush Menat494bd9e2022-03-28 18:52:46 +05302899 if d.get("schedule_date") and parent_doctype == "Purchase Order":
2900 child_item.schedule_date = d.get("schedule_date")
Saqib Ansaric579b082020-05-29 22:21:50 +05302901
Mangesh-Khairnara3d52002019-08-05 10:16:40 +05302902 if flt(child_item.price_list_rate):
Maricaf0674472019-10-11 10:47:09 +05302903 if flt(child_item.rate) > flt(child_item.price_list_rate):
2904 # if rate is greater than price_list_rate, set margin
2905 # or set discount
2906 child_item.discount_percentage = 0
rohitwaghchaure81c21752019-10-31 15:56:10 +05302907
2908 if parent_doctype in sales_doctypes:
2909 child_item.margin_type = "Amount"
Ankush Menat494bd9e2022-03-28 18:52:46 +05302910 child_item.margin_rate_or_amount = flt(
2911 child_item.rate - child_item.price_list_rate, child_item.precision("margin_rate_or_amount")
2912 )
rohitwaghchaure81c21752019-10-31 15:56:10 +05302913 child_item.rate_with_margin = child_item.rate
Maricaf0674472019-10-11 10:47:09 +05302914 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302915 child_item.discount_percentage = flt(
2916 (1 - flt(child_item.rate) / flt(child_item.price_list_rate)) * 100.0,
2917 child_item.precision("discount_percentage"),
2918 )
2919 child_item.discount_amount = flt(child_item.price_list_rate) - flt(child_item.rate)
rohitwaghchaure81c21752019-10-31 15:56:10 +05302920
2921 if parent_doctype in sales_doctypes:
2922 child_item.margin_type = ""
2923 child_item.margin_rate_or_amount = 0
2924 child_item.rate_with_margin = 0
Mangesh-Khairnara3d52002019-08-05 10:16:40 +05302925
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002926 child_item.flags.ignore_validate_update_after_submit = True
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002927 if new_child_flag:
Saqib Ansarif53299e2020-04-15 22:08:12 +05302928 parent.load_from_db()
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302929 child_item.idx = len(parent.items) + 1
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002930 child_item.insert()
2931 else:
2932 child_item.save()
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002933
Rushabh Mehtafafbb022018-12-24 22:09:15 +05302934 parent.reload()
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302935 parent.flags.ignore_validate_update_after_submit = True
2936 parent.set_qty_as_per_stock_uom()
2937 parent.calculate_taxes_and_totals()
Ankush Menatdf6e2082021-02-11 11:04:39 +05302938 parent.set_total_in_words()
Nabin Hait49a46f02019-10-21 13:35:43 +05302939 if parent_doctype == "Sales Order":
Marica3dee5272020-06-23 10:33:47 +05302940 make_packing_list(parent)
Nabin Hait49a46f02019-10-21 13:35:43 +05302941 parent.set_gross_profit()
Ankush Menat494bd9e2022-03-28 18:52:46 +05302942 frappe.get_doc("Authorization Control").validate_approving_authority(
2943 parent.doctype, parent.company, parent.base_grand_total
2944 )
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002945
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302946 parent.set_payment_schedule()
Ankush Menat494bd9e2022-03-28 18:52:46 +05302947 if parent_doctype == "Purchase Order":
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302948 parent.validate_minimum_order_qty()
2949 parent.validate_budget()
2950 if parent.is_against_so():
2951 parent.update_status_updater()
Nabin Haitb2da0822018-07-13 17:01:40 +05302952 else:
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302953 parent.check_credit_limit()
Ankush Menat733c9de2022-01-04 18:39:30 +05302954
2955 # reset index of child table
2956 for idx, row in enumerate(parent.get(child_docname), start=1):
2957 row.idx = idx
2958
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302959 parent.save()
Nabin Haitb2da0822018-07-13 17:01:40 +05302960
Ankush Menat494bd9e2022-03-28 18:52:46 +05302961 if parent_doctype == "Purchase Order":
2962 update_last_purchase_rate(parent, is_submit=1)
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302963 parent.update_prevdoc_status()
2964 parent.update_requested_qty()
2965 parent.update_ordered_qty()
2966 parent.update_ordered_and_reserved_qty()
2967 parent.update_receiving_percentage()
s-aga-r6d89b2f2022-06-18 15:46:59 +05302968 if parent.is_old_subcontracting_flow:
Ankush Menatdd11f262022-06-27 15:55:08 +05302969 if should_update_supplied_items(parent):
2970 parent.update_reserved_qty_for_subcontract()
Sagar Sharma78ff1782022-06-28 22:20:32 +05302971 parent.create_raw_materials_supplied()
s-aga-r6d89b2f2022-06-18 15:46:59 +05302972 parent.save()
Ankush Menatc84e11a2022-06-01 12:55:10 +05302973 else: # Sales Order
2974 parent.validate_warehouse()
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302975 parent.update_reserved_qty()
2976 parent.update_project()
Ankush Menat494bd9e2022-03-28 18:52:46 +05302977 parent.update_prevdoc_status("submit")
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302978 parent.update_delivery_status()
Nabin Haitb2da0822018-07-13 17:01:40 +05302979
Saqib6db92fb2020-09-14 19:54:17 +05302980 parent.reload()
2981 validate_workflow_conditions(parent)
2982
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302983 parent.update_blanket_order()
2984 parent.update_billing_percentage()
2985 parent.set_status()
Gauravf1e28e02019-02-13 16:46:24 +05302986
s-aga-rac24d772023-04-05 19:48:15 +05302987 # Cancel and Recreate Stock Reservation Entries.
s-aga-r38e93672023-04-02 21:24:59 +05302988 if parent_doctype == "Sales Order":
2989 from erpnext.stock.doctype.stock_reservation_entry.stock_reservation_entry import (
2990 cancel_stock_reservation_entries,
2991 has_reserved_stock,
s-aga-r38e93672023-04-02 21:24:59 +05302992 )
2993
2994 if has_reserved_stock(parent.doctype, parent.name):
2995 cancel_stock_reservation_entries(parent.doctype, parent.name)
s-aga-rac24d772023-04-05 19:48:15 +05302996 parent.create_stock_reservation_entries()
s-aga-r38e93672023-04-02 21:24:59 +05302997
Ankush Menat494bd9e2022-03-28 18:52:46 +05302998
Gursheen Ananda06017c2023-06-12 15:24:53 +05302999@erpnext.allow_regional
3000def validate_regional(doc):
3001 pass
3002
3003
3004@erpnext.allow_regional
3005def validate_einvoice_fields(doc):
3006 pass
3007
3008
3009@erpnext.allow_regional
3010def update_gl_dict_with_regional_fields(doc, gl_dict):
3011 pass