blob: 6812940ee26687f777f005112faeb74c249f4a27 [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)
Deepesh Garg492ea3b2023-08-08 11:39:44 +053035from erpnext.accounts.general_ledger import get_round_off_account_and_cost_center
Chillar Anand915b3432021-09-02 16:44:59 +053036from erpnext.accounts.party import (
37 get_party_account,
38 get_party_account_currency,
Deepesh Garga7f15a02021-12-12 21:09:11 +053039 get_party_gle_currency,
Chillar Anand915b3432021-09-02 16:44:59 +053040 validate_party_frozen_disabled,
41)
ruthra kumar1ea1bfe2023-07-26 16:19:38 +053042from erpnext.accounts.utils import (
43 create_gain_loss_journal,
44 get_account_currency,
45 get_fiscal_years,
46 validate_fiscal_year,
47)
Chillar Anand915b3432021-09-02 16:44:59 +053048from erpnext.buying.utils import update_last_purchase_rate
49from erpnext.controllers.print_settings import (
50 set_print_templates_for_item_table,
51 set_print_templates_for_taxes,
52)
53from erpnext.controllers.sales_and_purchase_return import validate_return
54from erpnext.exceptions import InvalidCurrency
55from erpnext.setup.utils import get_exchange_rate
Ankush Menat10583eb2022-06-17 12:13:27 +053056from erpnext.stock.doctype.item.item import get_uom_conv_factor
Marica3dee5272020-06-23 10:33:47 +053057from erpnext.stock.doctype.packed_item.packed_item import make_packing_list
Chillar Anand915b3432021-09-02 16:44:59 +053058from erpnext.stock.get_item_details import (
59 _get_item_tax_template,
60 get_conversion_factor,
61 get_item_details,
62 get_item_tax_map,
63 get_item_warehouse,
64)
Sagar Vora4205f562023-07-24 18:37:36 +053065from erpnext.utilities.regional import temporary_flag
Chillar Anand915b3432021-09-02 16:44:59 +053066from erpnext.utilities.transaction_base import TransactionBase
67
Nabin Hait1d218422015-07-17 15:19:02 +053068
Ankush Menat494bd9e2022-03-28 18:52:46 +053069class AccountMissingError(frappe.ValidationError):
70 pass
marination53b1a9a2020-11-03 15:45:25 +053071
Ankush Menat494bd9e2022-03-28 18:52:46 +053072
73force_item_fields = (
74 "item_group",
75 "brand",
76 "stock_uom",
77 "is_fixed_asset",
78 "item_tax_rate",
79 "pricing_rules",
80 "weight_per_unit",
81 "weight_uom",
82 "total_weight",
83)
84
Doridel Cahanap6f06cc22018-05-17 16:28:58 +080085
Nabin Haitbf495c92013-01-30 12:49:08 +053086class AccountsController(TransactionBase):
Nabin Hait7eba1a32017-10-02 15:59:27 +053087 def __init__(self, *args, **kwargs):
88 super(AccountsController, self).__init__(*args, **kwargs)
Anand Doshi979326b2015-09-11 16:22:37 +053089
prssanna71e5b602020-10-29 14:19:34 +053090 def get_print_settings(self):
91 print_setting_fields = []
Ankush Menat494bd9e2022-03-28 18:52:46 +053092 items_field = self.meta.get_field("items")
prssanna71e5b602020-10-29 14:19:34 +053093
Ankush Menat494bd9e2022-03-28 18:52:46 +053094 if items_field and items_field.fieldtype == "Table":
95 print_setting_fields += ["compact_item_print", "print_uom_after_quantity"]
prssanna71e5b602020-10-29 14:19:34 +053096
Ankush Menat494bd9e2022-03-28 18:52:46 +053097 taxes_field = self.meta.get_field("taxes")
98 if taxes_field and taxes_field.fieldtype == "Table":
99 print_setting_fields += ["print_taxes_with_zero_amount"]
prssanna71e5b602020-10-29 14:19:34 +0530100
101 return print_setting_fields
102
Nabin Hait4ffd7f32015-08-27 12:28:36 +0530103 @property
104 def company_currency(self):
105 if not hasattr(self, "__company_currency"):
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530106 self.__company_currency = erpnext.get_company_currency(self.company)
Anand Doshi979326b2015-09-11 16:22:37 +0530107
Nabin Hait4ffd7f32015-08-27 12:28:36 +0530108 return self.__company_currency
Anand Doshi979326b2015-09-11 16:22:37 +0530109
Rohit Waghchaure7d529892016-10-06 14:35:04 +0530110 def onload(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530111 self.set_onload(
112 "make_payment_via_journal_entry",
113 frappe.db.get_single_value("Accounts Settings", "make_payment_via_journal_entry"),
114 )
Nabin Hait0551f7b2017-11-21 19:58:16 +0530115
tundee52bb822017-09-25 09:02:23 +0100116 if self.is_new():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530117 relevant_docs = (
118 "Quotation",
119 "Purchase Order",
120 "Sales Order",
121 "Purchase Invoice",
122 "Sales Invoice",
123 )
tundee52bb822017-09-25 09:02:23 +0100124 if self.doctype in relevant_docs:
125 self.set_payment_schedule()
Rohit Waghchaure7d529892016-10-06 14:35:04 +0530126
tundebabzyad08d4c2018-05-16 07:01:41 +0100127 def ensure_supplier_is_not_blocked(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530128 is_supplier_payment = self.doctype == "Payment Entry" and self.party_type == "Supplier"
129 is_buying_invoice = self.doctype in ["Purchase Invoice", "Purchase Order"]
tundebabzyad08d4c2018-05-16 07:01:41 +0100130 supplier = None
131 supplier_name = None
132
133 if is_buying_invoice or is_supplier_payment:
134 supplier_name = self.supplier if is_buying_invoice else self.party
Ankush Menat494bd9e2022-03-28 18:52:46 +0530135 supplier = frappe.get_doc("Supplier", supplier_name)
tundebabzyad08d4c2018-05-16 07:01:41 +0100136
137 if supplier and supplier_name and supplier.on_hold:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530138 if (is_buying_invoice and supplier.hold_type in ["All", "Invoices"]) or (
139 is_supplier_payment and supplier.hold_type in ["All", "Payments"]
140 ):
tundebabzyad08d4c2018-05-16 07:01:41 +0100141 if not supplier.release_date or getdate(nowdate()) <= supplier.release_date:
142 frappe.msgprint(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530143 _("{0} is blocked so this transaction cannot proceed").format(supplier_name),
144 raise_exception=1,
145 )
tundebabzyad08d4c2018-05-16 07:01:41 +0100146
Saurabh6f753182013-03-20 12:55:28 +0530147 def validate(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530148 if not self.get("is_return") and not self.get("is_debit_note"):
Deepesh Gargd301d262019-07-31 15:58:19 +0530149 self.validate_qty_is_not_zero()
150
nabinhait23cce732014-07-03 12:25:06 +0530151 if self.get("_action") and self._action != "update_after_submit":
Nabin Hait704a4532014-06-05 16:55:31 +0530152 self.set_missing_values(for_validate=True)
tunde62af5c52017-09-22 15:16:38 +0100153
tundebabzyad08d4c2018-05-16 07:01:41 +0100154 self.ensure_supplier_is_not_blocked()
155
Nabin Haitcfecd2b2013-07-11 17:49:18 +0530156 self.validate_date_with_fiscal_year()
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530157 self.validate_party_accounts()
158
Deepesh Gargb4be2922021-01-28 13:09:56 +0530159 self.validate_inter_company_reference()
160
Ankush Menat3714e362022-05-16 18:09:14 +0530161 self.disable_pricing_rule_on_internal_transfer()
Deepesh Garg8d30ebb2022-11-05 20:51:15 +0530162 self.disable_tax_included_prices_for_internal_transfer()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530163 self.set_incoming_rate()
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530164
Anand Doshi3543f302013-05-24 19:25:01 +0530165 if self.meta.get_field("currency"):
Anand Doshi923d41d2013-05-28 17:23:36 +0530166 self.calculate_taxes_and_totals()
Rohit Waghchaure6087fe12016-04-09 14:31:09 +0530167
Nabin Hait1d218422015-07-17 15:19:02 +0530168 if not self.meta.get_field("is_return") or not self.is_return:
169 self.validate_value("base_grand_total", ">=", 0)
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530170
Nabin Hait3cf67a42015-07-24 13:26:36 +0530171 validate_return(self)
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
Dany Robert9bc59522023-08-26 18:14:40 +0530203 with temporary_flag("company", self.company):
204 validate_regional(self)
205 validate_einvoice_fields(self)
Saqib Ansaric5782b02022-01-27 20:09:56 +0530206
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
RitvikSardana03f0abf2023-09-19 13:08:17 +0530210 self.set_total_in_words()
211
Saqib Ansaric5782b02022-01-27 20:09:56 +0530212 def before_cancel(self):
213 validate_einvoice_fields(self)
214
ruthra kumar42df0d32023-08-28 17:36:12 +0530215 def _remove_references_in_unreconcile(self):
ruthra kumar9a1588f2023-08-30 20:50:16 +0530216 upe = frappe.qb.DocType("Unreconcile Payment Entries")
ruthra kumar42df0d32023-08-28 17:36:12 +0530217 rows = (
218 frappe.qb.from_(upe)
219 .select(upe.name, upe.parent)
220 .where((upe.reference_doctype == self.doctype) & (upe.reference_name == self.name))
221 .run(as_dict=True)
222 )
223
ruthra kumar6bbe47c2023-08-28 17:49:09 +0530224 if rows:
225 references_map = frappe._dict()
226 for x in rows:
227 references_map.setdefault(x.parent, []).append(x.name)
ruthra kumar42df0d32023-08-28 17:36:12 +0530228
ruthra kumar6bbe47c2023-08-28 17:49:09 +0530229 for doc, rows in references_map.items():
230 unreconcile_doc = frappe.get_doc("Unreconcile Payments", doc)
231 for row in rows:
232 unreconcile_doc.remove(unreconcile_doc.get("allocations", {"name": row})[0])
ruthra kumar42df0d32023-08-28 17:36:12 +0530233
ruthra kumar6bbe47c2023-08-28 17:49:09 +0530234 unreconcile_doc.flags.ignore_validate_update_after_submit = True
235 unreconcile_doc.flags.ignore_links = True
236 unreconcile_doc.save(ignore_permissions=True)
237
238 # delete docs upon parent doc deletion
239 unreconcile_docs = frappe.db.get_all("Unreconcile Payments", filters={"voucher_no": self.name})
240 for x in unreconcile_docs:
241 _doc = frappe.get_doc("Unreconcile Payments", x.name)
242 if _doc.docstatus == 1:
243 _doc.cancel()
244 _doc.delete()
ruthra kumar42df0d32023-08-28 17:36:12 +0530245
ruthra kumared7f67b2023-09-26 14:23:21 +0530246 def _remove_references_in_repost_doctypes(self):
247 repost_doctypes = ["Repost Payment Ledger Items", "Repost Accounting Ledger Items"]
ruthra kumarc722f282023-02-19 12:09:10 +0530248
ruthra kumared7f67b2023-09-26 14:23:21 +0530249 for _doctype in repost_doctypes:
250 dt = frappe.qb.DocType(_doctype)
251 rows = (
252 frappe.qb.from_(dt)
253 .select(dt.name, dt.parent, dt.parenttype)
254 .where((dt.voucher_type == self.doctype) & (dt.voucher_no == self.name))
255 .run(as_dict=True)
256 )
257
258 if rows:
259 references_map = frappe._dict()
260 for x in rows:
261 references_map.setdefault((x.parenttype, x.parent), []).append(x.name)
262
263 for doc, rows in references_map.items():
264 repost_doc = frappe.get_doc(doc[0], doc[1])
265
266 for row in rows:
267 if _doctype == "Repost Payment Ledger Items":
268 repost_doc.remove(repost_doc.get("repost_vouchers", {"name": row})[0])
269 else:
270 repost_doc.remove(repost_doc.get("vouchers", {"name": row})[0])
271
272 repost_doc.flags.ignore_validate_update_after_submit = True
273 repost_doc.flags.ignore_links = True
274 repost_doc.save(ignore_permissions=True)
275
276 def on_trash(self):
277 self._remove_references_in_repost_doctypes()
ruthra kumar42df0d32023-08-28 17:36:12 +0530278 self._remove_references_in_unreconcile()
ruthra kumarfbdfb812023-08-28 16:27:29 +0530279
Saqib8e556772021-01-28 12:26:45 +0530280 # delete sl and gl entries on deletion of transaction
Ankush Menat494bd9e2022-03-28 18:52:46 +0530281 if frappe.db.get_single_value("Accounts Settings", "delete_linked_ledger_entries"):
ruthra kumar70313df2022-09-08 18:53:30 +0530282 ple = frappe.qb.DocType("Payment Ledger Entry")
283 frappe.qb.from_(ple).delete().where(
284 (ple.voucher_type == self.doctype) & (ple.voucher_no == self.name)
285 ).run()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530286 frappe.db.sql(
287 "delete from `tabGL Entry` where voucher_type=%s and voucher_no=%s", (self.doctype, self.name)
288 )
289 frappe.db.sql(
290 "delete from `tabStock Ledger Entry` where voucher_type=%s and voucher_no=%s",
291 (self.doctype, self.name),
292 )
Nabin Hait0551f7b2017-11-21 19:58:16 +0530293
Deepesh Garg9bf5f762022-04-06 17:33:46 +0530294 def validate_deferred_income_expense_account(self):
295 field_map = {
296 "Sales Invoice": "deferred_revenue_account",
297 "Purchase Invoice": "deferred_expense_account",
298 }
299
300 for item in self.get("items"):
301 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
302 if not item.get(field_map.get(self.doctype)):
Daizy Modi4efc9472022-11-07 09:21:03 +0530303 default_deferred_account = frappe.get_cached_value(
Deepesh Garg9bf5f762022-04-06 17:33:46 +0530304 "Company", self.company, "default_" + field_map.get(self.doctype)
305 )
306 if not default_deferred_account:
307 frappe.throw(
308 _(
309 "Row #{0}: Please update deferred revenue/expense account in item row or default account in company master"
310 ).format(item.idx)
311 )
312 else:
313 item.set(field_map.get(self.doctype), default_deferred_account)
314
Deepesh Gargfa152212022-11-28 19:22:35 +0530315 def validate_auto_repeat_subscription_dates(self):
Deepesh Garg6a47fb62022-11-28 22:47:44 +0530316 if (
317 self.get("from_date")
318 and self.get("to_date")
319 and getdate(self.from_date) > getdate(self.to_date)
320 ):
Deepesh Gargfa152212022-11-28 19:22:35 +0530321 frappe.throw(_("To Date cannot be before From Date"), title=_("Invalid Auto Repeat Date"))
322
Nabin Haitacdd5082019-12-04 15:30:01 +0530323 def validate_deferred_start_and_end_date(self):
324 for d in self.items:
325 if d.get("enable_deferred_revenue") or d.get("enable_deferred_expense"):
326 if not (d.service_start_date and d.service_end_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530327 frappe.throw(
328 _("Row #{0}: Service Start and End Date is required for deferred accounting").format(d.idx)
329 )
Nabin Haitacdd5082019-12-04 15:30:01 +0530330 elif getdate(d.service_start_date) > getdate(d.service_end_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530331 frappe.throw(
332 _("Row #{0}: Service Start Date cannot be greater than Service End Date").format(d.idx)
333 )
Nabin Haitacdd5082019-12-04 15:30:01 +0530334 elif getdate(self.posting_date) > getdate(d.service_end_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530335 frappe.throw(
336 _("Row #{0}: Service End Date cannot be before Invoice Posting Date").format(d.idx)
337 )
Nabin Haitacdd5082019-12-04 15:30:01 +0530338
tunde62af5c52017-09-22 15:16:38 +0100339 def validate_invoice_documents_schedule(self):
Nabin Hait0551f7b2017-11-21 19:58:16 +0530340 self.validate_payment_schedule_dates()
341 self.set_due_date()
Nabin Hait0551f7b2017-11-21 19:58:16 +0530342 self.set_payment_schedule()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530343 if not self.get("ignore_default_payment_terms_template"):
Deepesh Garg5c758942023-04-16 17:11:24 +0530344 self.validate_payment_schedule_amount()
Deepesh Gargbd709f82021-08-23 19:05:52 +0530345 self.validate_due_date()
tunde62af5c52017-09-22 15:16:38 +0100346 self.validate_advance_entries()
347
348 def validate_non_invoice_documents_schedule(self):
Nabin Hait0551f7b2017-11-21 19:58:16 +0530349 self.set_payment_schedule()
Nabin Hait2f9f4f92017-12-20 12:24:59 +0530350 self.validate_payment_schedule_dates()
Nabin Hait0551f7b2017-11-21 19:58:16 +0530351 self.validate_payment_schedule_amount()
tunde62af5c52017-09-22 15:16:38 +0100352
353 def validate_all_documents_schedule(self):
354 if self.doctype in ("Sales Invoice", "Purchase Invoice") and not self.is_return:
355 self.validate_invoice_documents_schedule()
356 elif self.doctype in ("Quotation", "Purchase Order", "Sales Order"):
357 self.validate_non_invoice_documents_schedule()
358
prssanna71e5b602020-10-29 14:19:34 +0530359 def before_print(self, settings=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530360 if self.doctype in [
361 "Purchase Order",
362 "Sales Order",
363 "Sales Invoice",
364 "Purchase Invoice",
365 "Supplier Quotation",
366 "Purchase Receipt",
367 "Delivery Note",
368 "Quotation",
369 ]:
KanchanChauhan49a50fe2016-11-18 13:57:53 +0530370 if self.get("group_same_items"):
371 self.group_similar_items()
372
Zarrar5be6d192018-11-08 12:16:26 +0530373 df = self.meta.get_field("discount_amount")
374 if self.get("discount_amount") and hasattr(self, "taxes") and not len(self.taxes):
375 df.set("print_hide", 0)
376 self.discount_amount = -self.discount_amount
377 else:
378 df.set("print_hide", 1)
379
prssanna71e5b602020-10-29 14:19:34 +0530380 set_print_templates_for_item_table(self, settings)
381 set_print_templates_for_taxes(self, settings)
382
Mangesh-Khairnar7bcb24e2019-09-11 10:49:33 +0530383 def calculate_paid_amount(self):
Saurabh43520f92016-03-21 18:32:48 +0530384 if hasattr(self, "is_pos") or hasattr(self, "is_paid"):
385 is_paid = self.get("is_pos") or self.get("is_paid")
Mangesh-Khairnar7bcb24e2019-09-11 10:49:33 +0530386
387 if is_paid:
388 if not self.cash_bank_account:
389 # show message that the amount is not paid
Ankush Menat494bd9e2022-03-28 18:52:46 +0530390 frappe.throw(
391 _("Note: Payment Entry will not be created since 'Cash or Bank Account' was not specified")
392 )
Marica23d7b092019-09-25 17:17:36 +0530393
Mangesh-Khairnar7bcb24e2019-09-11 10:49:33 +0530394 if cint(self.is_return) and self.grand_total > self.paid_amount:
395 self.paid_amount = flt(flt(self.grand_total), self.precision("paid_amount"))
396
397 elif not flt(self.paid_amount) and flt(self.outstanding_amount) > 0:
398 self.paid_amount = flt(flt(self.outstanding_amount), self.precision("paid_amount"))
399
Ankush Menat494bd9e2022-03-28 18:52:46 +0530400 self.base_paid_amount = flt(
401 self.paid_amount * self.conversion_rate, self.precision("base_paid_amount")
402 )
Saurabh43520f92016-03-21 18:32:48 +0530403
Anand Doshiabc10032013-06-14 17:44:03 +0530404 def set_missing_values(self, for_validate=False):
Rohit Waghchaure5d97d892016-05-12 12:58:29 +0530405 if frappe.flags.in_test:
tunde62af5c52017-09-22 15:16:38 +0100406 for fieldname in ["posting_date", "transaction_date"]:
Rohit Waghchaure5d97d892016-05-12 12:58:29 +0530407 if self.meta.get_field(fieldname) and not self.get(fieldname):
408 self.set(fieldname, today())
409 break
Anand Doshid2946502014-04-08 20:10:03 +0530410
Nabin Hait3237c752015-02-17 11:11:11 +0530411 def calculate_taxes_and_totals(self):
Nabin Haitfe81da22015-02-18 12:23:18 +0530412 from erpnext.controllers.taxes_and_totals import calculate_taxes_and_totals
Ankush Menat494bd9e2022-03-28 18:52:46 +0530413
Nabin Haitfe81da22015-02-18 12:23:18 +0530414 calculate_taxes_and_totals(self)
Nabin Hait3237c752015-02-17 11:11:11 +0530415
Raffael Meyere10ab162021-11-30 13:24:18 +0100416 if self.doctype in (
Ankush Menat494bd9e2022-03-28 18:52:46 +0530417 "Sales Order",
418 "Delivery Note",
419 "Sales Invoice",
420 "POS Invoice",
Raffael Meyere10ab162021-11-30 13:24:18 +0100421 ):
Nabin Hait3237c752015-02-17 11:11:11 +0530422 self.calculate_commission()
423 self.calculate_contribution()
424
Nabin Haitcfecd2b2013-07-11 17:49:18 +0530425 def validate_date_with_fiscal_year(self):
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800426 if self.meta.get_field("fiscal_year"):
Rohan Bansal1e3a3b22021-05-26 15:18:10 +0530427 date_field = None
Nabin Haitcfecd2b2013-07-11 17:49:18 +0530428 if self.meta.get_field("posting_date"):
429 date_field = "posting_date"
430 elif self.meta.get_field("transaction_date"):
431 date_field = "transaction_date"
Anand Doshid2946502014-04-08 20:10:03 +0530432
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530433 if date_field and self.get(date_field):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530434 validate_fiscal_year(
435 self.get(date_field), self.fiscal_year, self.company, self.meta.get_label(date_field), self
436 )
Anand Doshid2946502014-04-08 20:10:03 +0530437
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530438 def validate_party_accounts(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530439 if self.doctype not in ("Sales Invoice", "Purchase Invoice"):
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530440 return
441
Ankush Menat494bd9e2022-03-28 18:52:46 +0530442 if self.doctype == "Sales Invoice":
443 party_account_field = "debit_to"
444 item_field = "income_account"
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530445 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530446 party_account_field = "credit_to"
447 item_field = "expense_account"
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530448
Ankush Menat494bd9e2022-03-28 18:52:46 +0530449 for item in self.get("items"):
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530450 if item.get(item_field) == self.get(party_account_field):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530451 frappe.throw(
452 _("Row {0}: {1} {2} cannot be same as {3} (Party Account) {4}").format(
453 item.idx,
454 frappe.bold(frappe.unscrub(item_field)),
455 item.get(item_field),
456 frappe.bold(frappe.unscrub(party_account_field)),
457 self.get(party_account_field),
458 )
459 )
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530460
Deepesh Gargb4be2922021-01-28 13:09:56 +0530461 def validate_inter_company_reference(self):
Rohit Waghchaure38aaba52023-05-13 13:00:05 +0530462 if self.get("is_return"):
463 return
464
Rohit Waghchaureb4a102d2022-09-06 16:22:00 +0530465 if self.doctype not in ("Purchase Invoice", "Purchase Receipt"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530466 return
467
468 if self.is_internal_transfer():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530469 if not (
470 self.get("inter_company_reference")
471 or self.get("inter_company_invoice_reference")
472 or self.get("inter_company_order_reference")
Deepesh Garg906ad102023-01-15 17:32:57 +0530473 ) and not self.get("is_return"):
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530474 msg = _("Internal Sale or Delivery Reference missing.")
Deepesh Gargb4be2922021-01-28 13:09:56 +0530475 msg += _("Please create purchase from internal sale or delivery document itself")
476 frappe.throw(msg, title=_("Internal Sales Reference Missing"))
477
Rohit Waghchaure19911b42023-04-21 16:49:48 +0530478 label = "Delivery Note Item" if self.doctype == "Purchase Receipt" else "Sales Invoice Item"
479
480 field = frappe.scrub(label)
481
482 for row in self.get("items"):
483 if not row.get(field):
484 msg = f"At Row {row.idx}: The field {bold(label)} is mandatory for internal transfer"
485 frappe.throw(_(msg), title=_("Internal Transfer Reference Missing"))
486
Ankush Menat3714e362022-05-16 18:09:14 +0530487 def disable_pricing_rule_on_internal_transfer(self):
488 if not self.get("ignore_pricing_rule") and self.is_internal_transfer():
489 self.ignore_pricing_rule = 1
490 frappe.msgprint(
491 _("Disabled pricing rules since this {} is an internal transfer").format(self.doctype),
492 alert=1,
493 )
494
Deepesh Garg8d30ebb2022-11-05 20:51:15 +0530495 def disable_tax_included_prices_for_internal_transfer(self):
496 if self.is_internal_transfer():
497 tax_updated = False
498 for tax in self.get("taxes"):
499 if tax.get("included_in_print_rate"):
500 tax.included_in_print_rate = 0
501 tax_updated = True
502
503 if tax_updated:
504 frappe.msgprint(
505 _("Disabled tax included prices since this {} is an internal transfer").format(self.doctype),
506 alert=1,
507 )
508
Nabin Haite9daefe2014-08-27 16:46:33 +0530509 def validate_due_date(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530510 if self.get("is_pos"):
511 return
rohitwaghchaureea943c62018-07-06 12:28:58 +0530512
Nabin Haite9daefe2014-08-27 16:46:33 +0530513 from erpnext.accounts.party import validate_due_date
Ankush Menat494bd9e2022-03-28 18:52:46 +0530514
Nabin Haite9daefe2014-08-27 16:46:33 +0530515 if self.doctype == "Sales Invoice":
Nabin Hait04d244a2015-07-22 17:47:49 +0530516 if not self.due_date:
517 frappe.throw(_("Due Date is mandatory"))
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530518
Ankush Menat494bd9e2022-03-28 18:52:46 +0530519 validate_due_date(
520 self.posting_date,
521 self.due_date,
522 "Customer",
523 self.customer,
524 self.company,
525 self.payment_terms_template,
526 )
Nabin Haite9daefe2014-08-27 16:46:33 +0530527 elif self.doctype == "Purchase Invoice":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530528 validate_due_date(
529 self.bill_date or self.posting_date,
530 self.due_date,
531 "Supplier",
532 self.supplier,
533 self.company,
534 self.bill_date,
535 self.payment_terms_template,
536 )
Nabin Haite9daefe2014-08-27 16:46:33 +0530537
Nabin Hait096d3632013-10-17 17:01:14 +0530538 def set_price_list_currency(self, buying_or_selling):
Nabin Hait1cc55fb2016-12-08 14:09:23 +0530539 if self.meta.get_field("posting_date"):
Nabin Hait288a18e2016-12-08 15:36:23 +0530540 transaction_date = self.posting_date
Nabin Hait1cc55fb2016-12-08 14:09:23 +0530541 else:
Nabin Hait288a18e2016-12-08 15:36:23 +0530542 transaction_date = self.transaction_date
Rushabh Mehta66958302017-01-16 16:57:53 +0530543
Rushabh Mehta4a404e92013-08-09 18:11:35 +0530544 if self.meta.get_field("currency"):
Nabin Hait7a75e102013-09-17 10:21:20 +0530545 # price list part
Shreya3f778522018-05-15 16:59:20 +0530546 if buying_or_selling.lower() == "selling":
547 fieldname = "selling_price_list"
548 args = "for_selling"
549 else:
550 fieldname = "buying_price_list"
551 args = "for_buying"
552
Anand Doshif78d1ae2014-03-28 13:55:00 +0530553 if self.meta.get_field(fieldname) and self.get(fieldname):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530554 self.price_list_currency = frappe.db.get_value("Price List", self.get(fieldname), "currency")
Anand Doshid2946502014-04-08 20:10:03 +0530555
Nabin Hait6e439a52015-08-28 19:24:22 +0530556 if self.price_list_currency == self.company_currency:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530557 self.plc_conversion_rate = 1.0
Nabin Hait11f41952013-09-24 14:36:55 +0530558
Anand Doshif78d1ae2014-03-28 13:55:00 +0530559 elif not self.plc_conversion_rate:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530560 self.plc_conversion_rate = get_exchange_rate(
561 self.price_list_currency, self.company_currency, transaction_date, args
562 )
Anand Doshid2946502014-04-08 20:10:03 +0530563
Nabin Hait7a75e102013-09-17 10:21:20 +0530564 # currency
Anand Doshif78d1ae2014-03-28 13:55:00 +0530565 if not self.currency:
566 self.currency = self.price_list_currency
567 self.conversion_rate = self.plc_conversion_rate
Nabin Hait6e439a52015-08-28 19:24:22 +0530568 elif self.currency == self.company_currency:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530569 self.conversion_rate = 1.0
570 elif not self.conversion_rate:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530571 self.conversion_rate = get_exchange_rate(
572 self.currency, self.company_currency, transaction_date, args
573 )
Nabin Hait7a75e102013-09-17 10:21:20 +0530574
Nabin Haitcccc45e2016-10-05 17:15:43 +0530575 def set_missing_item_details(self, for_validate=False):
Anand Doshi3543f302013-05-24 19:25:01 +0530576 """set missing item values"""
Nabin Haitf37d43d2017-07-18 12:14:42 +0530577 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530578
Nabin Haitdd38a262014-12-26 13:15:21 +0530579 if hasattr(self, "items"):
Nabin Hait444f9562014-06-20 15:59:49 +0530580 parent_dict = {}
Pratik Vyasf7daab72014-04-10 17:53:30 +0530581 for fieldname in self.meta.get_valid_columns():
582 parent_dict[fieldname] = self.get(fieldname)
583
mbauskara52472c2016-03-05 15:10:25 +0530584 if self.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
585 document_type = "{} Item".format(self.doctype)
mbauskarc97becb2016-01-18 16:28:21 +0530586 parent_dict.update({"document_type": document_type})
587
Nabin Hait34c551d2019-07-03 10:34:31 +0530588 # party_name field used for customer in quotation
Ankush Menat494bd9e2022-03-28 18:52:46 +0530589 if (
590 self.doctype == "Quotation"
591 and self.quotation_to == "Customer"
592 and parent_dict.get("party_name")
593 ):
Nabin Hait34c551d2019-07-03 10:34:31 +0530594 parent_dict.update({"customer": parent_dict.get("party_name")})
595
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530596 self.pricing_rules = []
Deepesh Garg4c61ee32023-04-02 09:35:27 +0530597
Nabin Haitdd38a262014-12-26 13:15:21 +0530598 for item in self.get("items"):
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530599 if item.get("item_code"):
Nabin Hait444f9562014-06-20 15:59:49 +0530600 args = parent_dict.copy()
601 args.update(item.as_dict())
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530602
Nabin Hait34d28222016-01-19 15:45:49 +0530603 args["doctype"] = self.doctype
604 args["name"] = self.name
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530605 args["child_docname"] = item.name
Ankush Menat494bd9e2022-03-28 18:52:46 +0530606 args["ignore_pricing_rule"] = (
607 self.ignore_pricing_rule if hasattr(self, "ignore_pricing_rule") else 0
608 )
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530609
Nabin Haite2f054c2015-03-09 14:54:37 +0530610 if not args.get("transaction_date"):
611 args["transaction_date"] = args.get("posting_date")
Anand Doshi2b2b6392015-03-20 14:18:09 +0530612
613 if self.get("is_subcontracted"):
614 args["is_subcontracted"] = self.is_subcontracted
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530615
Deepesh Garga7051cb2023-04-14 09:59:42 +0530616 ret = get_item_details(args, self, for_validate=True, overwrite_warehouse=False)
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530617
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530618 for fieldname, value in ret.items():
Anand Doshi602e8252015-11-16 19:05:46 +0530619 if item.meta.get_field(fieldname) and value is not None:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530620 if item.get(fieldname) is None or fieldname in force_item_fields:
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530621 item.set(fieldname, value)
Anand Doshid2946502014-04-08 20:10:03 +0530622
Ankush Menat494bd9e2022-03-28 18:52:46 +0530623 elif fieldname in ["cost_center", "conversion_factor"] and not item.get(fieldname):
Anand Doshi602e8252015-11-16 19:05:46 +0530624 item.set(fieldname, value)
625
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530626 elif fieldname == "serial_no":
Alchez9155e402018-07-09 16:57:42 +0530627 # Ensure that serial numbers are matched against Stock UOM
628 item_conversion_factor = item.get("conversion_factor") or 1.0
629 item_qty = abs(item.get("qty")) * item_conversion_factor
Alchez8f2a0f32018-07-06 14:36:52 +0530630
Ankush Menat494bd9e2022-03-28 18:52:46 +0530631 if item_qty != len(get_serial_nos(item.get("serial_no"))):
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530632 item.set(fieldname, value)
Nabin Haita74468b2014-12-30 18:33:52 +0530633
Saqib Ansariab36b272022-02-09 10:10:17 +0530634 elif (
635 ret.get("pricing_rule_removed")
636 and value is not None
637 and fieldname
638 in [
639 "discount_percentage",
640 "discount_amount",
641 "rate",
642 "margin_rate_or_amount",
643 "margin_type",
644 "remove_free_item",
645 ]
646 ):
Saqib Ansarib8c41e32022-01-20 13:06:08 +0530647 # reset pricing rule fields if pricing_rule_removed
648 item.set(fieldname, value)
649
Ankush Menat494bd9e2022-03-28 18:52:46 +0530650 if self.doctype in ["Purchase Invoice", "Sales Invoice"] and item.meta.get_field(
651 "is_fixed_asset"
652 ):
653 item.set("is_fixed_asset", ret.get("is_fixed_asset", 0))
Rohit Waghchauref6f503a2018-12-19 15:06:44 +0530654
Deepesh Garga60c3082021-05-11 16:38:33 +0530655 # Double check for cost center
656 # Items add via promotional scheme may not have cost center set
Ankush Menat494bd9e2022-03-28 18:52:46 +0530657 if hasattr(item, "cost_center") and not item.get("cost_center"):
658 item.set(
659 "cost_center", self.get("cost_center") or erpnext.get_default_cost_center(self.company)
660 )
Deepesh Garga60c3082021-05-11 16:38:33 +0530661
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530662 if ret.get("pricing_rules"):
663 self.apply_pricing_rule_on_items(item, ret)
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530664 self.set_pricing_rule_details(item, ret)
Ankush Menat10583eb2022-06-17 12:13:27 +0530665 else:
666 # Transactions line item without item code
667
668 uom = item.get("uom")
669 stock_uom = item.get("stock_uom")
670 if bool(uom) != bool(stock_uom): # xor
671 item.stock_uom = item.uom = uom or stock_uom
672
Deepesh Garg61751832022-12-29 10:41:36 +0530673 # UOM cannot be zero so substitute as 1
674 item.conversion_factor = (
675 get_uom_conv_factor(item.get("uom"), item.get("stock_uom"))
676 or item.get("conversion_factor")
677 or 1
678 )
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530679
Nabin Hait14aa9c52016-04-18 15:54:01 +0530680 if self.doctype == "Purchase Invoice":
Nabin Haitcccc45e2016-10-05 17:15:43 +0530681 self.set_expense_account(for_validate)
Nabin Haita3dd72a2014-05-28 12:49:20 +0530682
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530683 def apply_pricing_rule_on_items(self, item, pricing_rule_args):
684 if not pricing_rule_args.get("validate_applied_rule", 0):
685 # if user changed the discount percentage then set user's discount percentage ?
Ankush Menat494bd9e2022-03-28 18:52:46 +0530686 if pricing_rule_args.get("price_or_product_discount") == "Price":
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530687 item.set("pricing_rules", pricing_rule_args.get("pricing_rules"))
Rohit Waghchauref5bd3fa2022-09-16 15:23:10 +0530688 if pricing_rule_args.get("apply_rule_on_other_items"):
689 other_items = json.loads(pricing_rule_args.get("apply_rule_on_other_items"))
690 if other_items and item.item_code not in other_items:
691 return
692
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530693 item.set("discount_percentage", pricing_rule_args.get("discount_percentage"))
694 item.set("discount_amount", pricing_rule_args.get("discount_amount"))
695 if pricing_rule_args.get("pricing_rule_for") == "Rate":
696 item.set("price_list_rate", pricing_rule_args.get("price_list_rate"))
697
698 if item.get("price_list_rate"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530699 item.rate = flt(
700 item.price_list_rate * (1.0 - (flt(item.discount_percentage) / 100.0)),
701 item.precision("rate"),
702 )
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530703
Ankush Menat494bd9e2022-03-28 18:52:46 +0530704 if item.get("discount_amount"):
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530705 item.rate = item.price_list_rate - item.discount_amount
706
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530707 if item.get("apply_discount_on_discounted_rate") and pricing_rule_args.get("rate"):
708 item.rate = pricing_rule_args.get("rate")
709
Ankush Menat494bd9e2022-03-28 18:52:46 +0530710 elif pricing_rule_args.get("free_item_data"):
711 apply_pricing_rule_for_free_items(self, pricing_rule_args.get("free_item_data"))
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530712
713 elif pricing_rule_args.get("validate_applied_rule"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530714 for pricing_rule in get_applied_pricing_rules(item.get("pricing_rules")):
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530715 pricing_rule_doc = frappe.get_cached_doc("Pricing Rule", pricing_rule)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530716 for field in ["discount_percentage", "discount_amount", "rate"]:
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530717 if item.get(field) < pricing_rule_doc.get(field):
718 title = get_link_to_form("Pricing Rule", pricing_rule)
719
Ankush Menat494bd9e2022-03-28 18:52:46 +0530720 frappe.msgprint(
721 _("Row {0}: user has not applied the rule {1} on the item {2}").format(
722 item.idx, frappe.bold(title), frappe.bold(item.item_code)
723 )
724 )
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530725
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530726 def set_pricing_rule_details(self, item_row, args):
727 pricing_rules = get_applied_pricing_rules(args.get("pricing_rules"))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530728 if not pricing_rules:
729 return
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530730
731 for pricing_rule in pricing_rules:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530732 self.append(
733 "pricing_rules",
734 {
735 "pricing_rule": pricing_rule,
736 "item_code": item_row.item_code,
737 "child_docname": item_row.name,
738 "rule_applied": True,
739 },
740 )
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530741
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530742 def set_taxes(self):
743 if not self.meta.get_field("taxes"):
Anand Doshi3543f302013-05-24 19:25:01 +0530744 return
Anand Doshid2946502014-04-08 20:10:03 +0530745
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530746 tax_master_doctype = self.meta.get_field("taxes_and_charges").options
Anand Doshid2946502014-04-08 20:10:03 +0530747
rohitwaghchaure57914f12018-04-24 19:19:47 +0530748 if (self.is_new() or self.is_pos_profile_changed()) and not self.get("taxes"):
rohitwaghchaure505661b2017-12-11 14:52:28 +0530749 if self.company and not self.get("taxes_and_charges"):
Anand Doshi3543f302013-05-24 19:25:01 +0530750 # get the default tax master
Ankush Menat494bd9e2022-03-28 18:52:46 +0530751 self.taxes_and_charges = frappe.db.get_value(
752 tax_master_doctype, {"is_default": 1, "company": self.company}
753 )
Anand Doshid2946502014-04-08 20:10:03 +0530754
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530755 self.append_taxes_from_master(tax_master_doctype)
Anand Doshid2946502014-04-08 20:10:03 +0530756
rohitwaghchaure57914f12018-04-24 19:19:47 +0530757 def is_pos_profile_changed(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530758 if (
759 self.doctype == "Sales Invoice"
760 and self.is_pos
761 and self.pos_profile != frappe.db.get_value("Sales Invoice", self.name, "pos_profile")
762 ):
rohitwaghchaure57914f12018-04-24 19:19:47 +0530763 return True
764
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530765 def append_taxes_from_master(self, tax_master_doctype=None):
766 if self.get("taxes_and_charges"):
Anand Doshi99100a42013-07-04 17:13:53 +0530767 if not tax_master_doctype:
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530768 tax_master_doctype = self.meta.get_field("taxes_and_charges").options
Anand Doshid2946502014-04-08 20:10:03 +0530769
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530770 self.extend("taxes", get_taxes_and_charges(tax_master_doctype, self.get("taxes_and_charges")))
Akhilesh Darjee4cdb7992014-01-30 13:56:57 +0530771
Anand Doshiac32bad2014-04-18 01:30:14 +0530772 def set_other_charges(self):
Nabin Haite7d15362014-12-25 16:01:55 +0530773 self.set("taxes", [])
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530774 self.set_taxes()
Anand Doshid2946502014-04-08 20:10:03 +0530775
ankitjavalkarwork6c29d872014-10-06 13:20:53 +0530776 def validate_enabled_taxes_and_charges(self):
777 taxes_and_charges_doctype = self.meta.get_options("taxes_and_charges")
Shariq Ansari21c11412023-08-17 12:14:13 +0530778 if self.taxes_and_charges and frappe.get_cached_value(
779 taxes_and_charges_doctype, self.taxes_and_charges, "disabled"
780 ):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530781 frappe.throw(
782 _("{0} '{1}' is disabled").format(taxes_and_charges_doctype, self.taxes_and_charges)
783 )
ankitjavalkarwork6c29d872014-10-06 13:20:53 +0530784
Nabin Haita2426fc2018-01-15 17:45:46 +0530785 def validate_tax_account_company(self):
786 for d in self.get("taxes"):
787 if d.account_head:
Daizy Modi4efc9472022-11-07 09:21:03 +0530788 tax_account_company = frappe.get_cached_value("Account", d.account_head, "company")
Nabin Haita2426fc2018-01-15 17:45:46 +0530789 if tax_account_company != self.company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530790 frappe.throw(
791 _("Row #{0}: Account {1} does not belong to company {2}").format(
792 d.idx, d.account_head, self.company
793 )
794 )
Nabin Haita2426fc2018-01-15 17:45:46 +0530795
deepeshgarg0073d11ac02019-05-19 00:02:01 +0530796 def get_gl_dict(self, args, account_currency=None, item=None):
Nabin Hait2df4d542013-01-29 11:34:39 +0530797 """this method populates the common properties of a gl entry record"""
Rushabh Mehta2cb7a9f2016-06-15 16:45:03 +0530798
Ankush Menat494bd9e2022-03-28 18:52:46 +0530799 posting_date = args.get("posting_date") or self.get("posting_date")
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530800 fiscal_years = get_fiscal_years(posting_date, company=self.company)
Nabin Hait2ed0b592016-03-29 13:14:17 +0530801 if len(fiscal_years) > 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530802 frappe.throw(
803 _("Multiple fiscal years exist for the date {0}. Please set company in Fiscal Year").format(
804 formatdate(posting_date)
805 )
806 )
Nabin Hait2ed0b592016-03-29 13:14:17 +0530807 else:
808 fiscal_year = fiscal_years[0][0]
Rushabh Mehta2cb7a9f2016-06-15 16:45:03 +0530809
Ankush Menat494bd9e2022-03-28 18:52:46 +0530810 gl_dict = frappe._dict(
811 {
812 "company": self.company,
813 "posting_date": posting_date,
814 "fiscal_year": fiscal_year,
815 "voucher_type": self.doctype,
816 "voucher_no": self.name,
817 "remarks": self.get("remarks") or self.get("remark"),
818 "debit": 0,
819 "credit": 0,
820 "debit_in_account_currency": 0,
821 "credit_in_account_currency": 0,
822 "is_opening": self.get("is_opening") or "No",
823 "party_type": None,
824 "party": None,
825 "project": self.get("project"),
826 "post_net_value": args.get("post_net_value"),
Deepesh Gargda6bc1a2023-06-23 20:57:51 +0530827 "voucher_detail_no": args.get("voucher_detail_no"),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530828 }
829 )
deepeshgarg007d83cf652019-05-12 18:34:23 +0530830
Sagar Vora4205f562023-07-24 18:37:36 +0530831 with temporary_flag("company", self.company):
832 update_gl_dict_with_regional_fields(self, gl_dict)
833
deepeshgarg007d83cf652019-05-12 18:34:23 +0530834 accounting_dimensions = get_accounting_dimensions()
835 dimension_dict = frappe._dict()
836
837 for dimension in accounting_dimensions:
838 dimension_dict[dimension] = self.get(dimension)
deepeshgarg0073d11ac02019-05-19 00:02:01 +0530839 if item and item.get(dimension):
840 dimension_dict[dimension] = item.get(dimension)
deepeshgarg007d83cf652019-05-12 18:34:23 +0530841
842 gl_dict.update(dimension_dict)
Nabin Hait2df4d542013-01-29 11:34:39 +0530843 gl_dict.update(args)
Anand Doshi979326b2015-09-11 16:22:37 +0530844
Nabin Hait895029d2015-08-20 14:55:39 +0530845 if not account_currency:
Anand Doshicd0989e2015-09-28 13:31:17 +0530846 account_currency = get_account_currency(gl_dict.account)
Anand Doshi979326b2015-09-11 16:22:37 +0530847
Ankush Menat494bd9e2022-03-28 18:52:46 +0530848 if gl_dict.account and self.doctype not in [
849 "Journal Entry",
850 "Period Closing Voucher",
851 "Payment Entry",
852 "Purchase Receipt",
853 "Purchase Invoice",
854 "Stock Entry",
855 ]:
Anand Doshibe6cfdd2015-09-17 21:07:04 +0530856 self.validate_account_currency(gl_dict.account, account_currency)
Deepesh Garg7c300852020-12-26 20:14:51 +0530857
Ankush Menat494bd9e2022-03-28 18:52:46 +0530858 if gl_dict.account and self.doctype not in [
859 "Journal Entry",
860 "Period Closing Voucher",
861 "Payment Entry",
862 ]:
863 set_balance_in_account_currency(
864 gl_dict, account_currency, self.get("conversion_rate"), self.company_currency
865 )
Anand Doshi979326b2015-09-11 16:22:37 +0530866
Deepesh Garg35be3ac2023-08-17 11:31:40 +0530867 # Update details in transaction currency
868 gl_dict.update(
869 {
870 "transaction_currency": self.get("currency") or self.company_currency,
871 "transaction_exchange_rate": self.get("conversion_rate", 1),
872 "debit_in_transaction_currency": self.get_value_in_transaction_currency(
873 account_currency, args, "debit"
874 ),
875 "credit_in_transaction_currency": self.get_value_in_transaction_currency(
876 account_currency, args, "credit"
877 ),
878 }
879 )
880
Nabin Haitc561a492015-08-19 19:22:34 +0530881 return gl_dict
Anand Doshi979326b2015-09-11 16:22:37 +0530882
Deepesh Garg35be3ac2023-08-17 11:31:40 +0530883 def get_value_in_transaction_currency(self, account_currency, args, field):
884 if account_currency == self.get("currency"):
885 return args.get(field + "_in_account_currency")
886 else:
887 return flt(args.get(field, 0) / self.get("conversion_rate", 1))
888
Anurag Mishrae657fe82018-11-26 15:19:17 +0530889 def validate_qty_is_not_zero(self):
Maricac68a9402019-12-03 12:59:22 +0530890 if self.doctype != "Purchase Receipt":
891 for item in self.items:
892 if not item.qty:
893 frappe.throw(_("Item quantity can not be zero"))
Anurag Mishrae657fe82018-11-26 15:19:17 +0530894
Nabin Hait895029d2015-08-20 14:55:39 +0530895 def validate_account_currency(self, account, account_currency=None):
Nabin Hait6e439a52015-08-28 19:24:22 +0530896 valid_currency = [self.company_currency]
897 if self.get("currency") and self.currency != self.company_currency:
898 valid_currency.append(self.currency)
899
Nabin Hait895029d2015-08-20 14:55:39 +0530900 if account_currency not in valid_currency:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530901 frappe.throw(
902 _("Account {0} is invalid. Account Currency must be {1}").format(
903 account, (" " + _("or") + " ").join(valid_currency)
904 )
905 )
Anand Doshi979326b2015-09-11 16:22:37 +0530906
Anand Doshi613cb6a2013-02-06 17:33:46 +0530907 def clear_unallocated_advances(self, childtype, parentfield):
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530908 self.set(parentfield, self.get(parentfield, {"allocated_amount": ["not in", [0, None, ""]]}))
909
Ankush Menat494bd9e2022-03-28 18:52:46 +0530910 frappe.db.sql(
911 """delete from `tab%s` where parentfield=%s and parent = %s
912 and allocated_amount = 0"""
913 % (childtype, "%s", "%s"),
914 (parentfield, self.name),
915 )
Anand Doshid2946502014-04-08 20:10:03 +0530916
Walstan Baptistad6360752021-03-31 12:30:32 +0530917 @frappe.whitelist()
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530918 def apply_shipping_rule(self):
919 if self.shipping_rule:
920 shipping_rule = frappe.get_doc("Shipping Rule", self.shipping_rule)
921 shipping_rule.apply(self)
922 self.calculate_taxes_and_totals()
923
924 def get_shipping_address(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530925 """Returns Address object from shipping address fields if present"""
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530926
927 # shipping address fields can be `shipping_address_name` or `shipping_address`
928 # try getting value from both
929
Ankush Menat494bd9e2022-03-28 18:52:46 +0530930 for fieldname in ("shipping_address_name", "shipping_address"):
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530931 shipping_field = self.meta.get_field(fieldname)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530932 if shipping_field and shipping_field.fieldtype == "Link":
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530933 if self.get(fieldname):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530934 return frappe.get_doc("Address", self.get(fieldname))
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530935
936 return {}
937
Walstan Baptistad6360752021-03-31 12:30:32 +0530938 @frappe.whitelist()
Nabin Hait041a5c22018-08-01 18:07:39 +0530939 def set_advances(self):
940 """Returns list of advances against Account, Party, Reference"""
941
Deepesh Gargfd3fb642023-04-05 12:02:44 +0530942 res = self.get_advance_entries(
943 include_unallocated=not cint(self.get("only_include_allocated_payments"))
944 )
Nabin Hait041a5c22018-08-01 18:07:39 +0530945
946 self.set("advances", [])
947 advance_allocated = 0
948 for d in res:
Deepesh Garg181df2f2022-11-04 15:49:37 +0530949 if self.get("party_account_currency") == self.company_currency:
950 amount = self.get("base_rounded_total") or self.base_grand_total
Nabin Hait041a5c22018-08-01 18:07:39 +0530951 else:
Deepesh Garg181df2f2022-11-04 15:49:37 +0530952 amount = self.get("rounded_total") or self.grand_total
Deepesh Garg181df2f2022-11-04 15:49:37 +0530953 allocated_amount = min(amount - advance_allocated, d.amount)
Nabin Hait041a5c22018-08-01 18:07:39 +0530954 advance_allocated += flt(allocated_amount)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530955
Saqiba20999c2021-07-12 14:33:23 +0530956 advance_row = {
Nabin Hait041a5c22018-08-01 18:07:39 +0530957 "doctype": self.doctype + " Advance",
958 "reference_type": d.reference_type,
959 "reference_name": d.reference_name,
960 "reference_row": d.reference_row,
961 "remarks": d.remarks,
962 "advance_amount": flt(d.amount),
Saqiba20999c2021-07-12 14:33:23 +0530963 "allocated_amount": allocated_amount,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530964 "ref_exchange_rate": flt(d.exchange_rate), # exchange_rate of advance entry
Saqiba20999c2021-07-12 14:33:23 +0530965 }
Gursheen Anand74619262023-06-02 17:13:51 +0530966 if d.get("paid_from"):
967 advance_row["account"] = d.paid_from
968 if d.get("paid_to"):
969 advance_row["account"] = d.paid_to
Saqiba20999c2021-07-12 14:33:23 +0530970
971 self.append("advances", advance_row)
Nabin Hait041a5c22018-08-01 18:07:39 +0530972
Nabin Hait28a05282016-06-27 17:41:39 +0530973 def get_advance_entries(self, include_unallocated=True):
974 if self.doctype == "Sales Invoice":
Nabin Hait28a05282016-06-27 17:41:39 +0530975 party_type = "Customer"
976 party = self.customer
977 amount_field = "credit_in_account_currency"
978 order_field = "sales_order"
979 order_doctype = "Sales Order"
980 else:
Nabin Hait28a05282016-06-27 17:41:39 +0530981 party_type = "Supplier"
982 party = self.supplier
983 amount_field = "debit_in_account_currency"
984 order_field = "purchase_order"
985 order_doctype = "Purchase Order"
Deepesh Garg92f845c2023-06-21 12:21:19 +0530986
987 party_account = get_party_account(
988 party_type, party=party, company=self.company, include_advance=True
989 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530990
Ankush Menat494bd9e2022-03-28 18:52:46 +0530991 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 +0530992
Ankush Menat494bd9e2022-03-28 18:52:46 +0530993 journal_entries = get_advance_journal_entries(
994 party_type, party, party_account, amount_field, order_doctype, order_list, include_unallocated
995 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530996
Smit Vora3e282bf2023-09-19 20:47:21 +0530997 payment_entries = get_advance_payment_entries_for_regional(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530998 party_type, party, party_account, order_doctype, order_list, include_unallocated
999 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301000
Nabin Hait28a05282016-06-27 17:41:39 +05301001 res = journal_entries + payment_entries
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301002
Nabin Hait28a05282016-06-27 17:41:39 +05301003 return res
Nabin Hait48f5fa62014-09-18 15:03:54 +05301004
rohitwaghchaurebf4c1142018-01-08 15:20:15 +05301005 def is_inclusive_tax(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301006 is_inclusive = cint(
1007 frappe.db.get_single_value("Accounts Settings", "show_inclusive_tax_in_print")
1008 )
rohitwaghchaurebf4c1142018-01-08 15:20:15 +05301009
1010 if is_inclusive:
1011 is_inclusive = 0
1012 if self.get("taxes", filters={"included_in_print_rate": 1}):
1013 is_inclusive = 1
1014
1015 return is_inclusive
1016
Anand Baburajan491a50a2023-06-13 19:42:56 +05301017 def should_show_taxes_as_table_in_print(self):
1018 return cint(frappe.db.get_single_value("Accounts Settings", "show_taxes_as_table_in_print"))
1019
Nabin Hait28a05282016-06-27 17:41:39 +05301020 def validate_advance_entries(self):
Nabin Hait05aefbb2016-06-28 19:42:19 +05301021 order_field = "sales_order" if self.doctype == "Sales Invoice" else "purchase_order"
Ankush Menat494bd9e2022-03-28 18:52:46 +05301022 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 +05301023
Ankush Menat494bd9e2022-03-28 18:52:46 +05301024 if not order_list:
1025 return
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301026
Nabin Hait28a05282016-06-27 17:41:39 +05301027 advance_entries = self.get_advance_entries(include_unallocated=False)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301028
Nabin Hait28a05282016-06-27 17:41:39 +05301029 if advance_entries:
1030 advance_entries_against_si = [d.reference_name for d in self.get("advances")]
1031 for d in advance_entries:
1032 if not advance_entries_against_si or d.reference_name not in advance_entries_against_si:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301033 frappe.msgprint(
1034 _(
1035 "Payment Entry {0} is linked against Order {1}, check if it should be pulled as advance in this invoice."
1036 ).format(d.reference_name, d.against_order)
1037 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301038
Saqiba20999c2021-07-12 14:33:23 +05301039 def set_advance_gain_or_loss(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301040 if self.get("conversion_rate") == 1 or not self.get("advances"):
Saqib Ansari64efe8b2021-09-26 15:46:13 +05301041 return
1042
Ankush Menat494bd9e2022-03-28 18:52:46 +05301043 is_purchase_invoice = self.doctype == "Purchase Invoice"
Saqib Ansari64efe8b2021-09-26 15:46:13 +05301044 party_account = self.credit_to if is_purchase_invoice else self.debit_to
1045 if get_account_currency(party_account) != self.currency:
Saqiba20999c2021-07-12 14:33:23 +05301046 return
1047
1048 for d in self.get("advances"):
1049 advance_exchange_rate = d.ref_exchange_rate
Ankush Menat494bd9e2022-03-28 18:52:46 +05301050 if d.allocated_amount and self.conversion_rate != advance_exchange_rate:
Saqiba20999c2021-07-12 14:33:23 +05301051
1052 base_allocated_amount_in_ref_rate = advance_exchange_rate * d.allocated_amount
1053 base_allocated_amount_in_inv_rate = self.conversion_rate * d.allocated_amount
1054 difference = base_allocated_amount_in_ref_rate - base_allocated_amount_in_inv_rate
1055
1056 d.exchange_gain_loss = difference
1057
Deepesh Garg492ea3b2023-08-08 11:39:44 +05301058 def make_precision_loss_gl_entry(self, gl_entries):
1059 round_off_account, round_off_cost_center = get_round_off_account_and_cost_center(
1060 self.company, "Purchase Invoice", self.name, self.use_company_roundoff_cost_center
1061 )
1062
1063 precision_loss = self.get("base_net_total") - flt(
1064 self.get("net_total") * self.conversion_rate, self.precision("net_total")
1065 )
1066
1067 credit_or_debit = "credit" if self.doctype == "Purchase Invoice" else "debit"
1068 against = self.supplier if self.doctype == "Purchase Invoice" else self.customer
1069
1070 if precision_loss:
1071 gl_entries.append(
1072 self.get_gl_dict(
1073 {
1074 "account": round_off_account,
1075 "against": against,
1076 credit_or_debit: precision_loss,
1077 "cost_center": round_off_cost_center
1078 if self.use_company_roundoff_cost_center
1079 else self.cost_center or round_off_cost_center,
1080 "remarks": _("Net total calculation precision loss"),
1081 }
1082 )
1083 )
1084
ruthra kumar79c6f012023-09-01 14:57:12 +05301085 def gain_loss_journal_already_booked(
1086 self,
1087 gain_loss_account,
1088 exc_gain_loss,
1089 ref2_dt,
1090 ref2_dn,
1091 ref2_detail_no,
1092 ) -> bool:
1093 """
1094 Check if gain/loss is booked
1095 """
1096 if res := frappe.db.get_all(
1097 "Journal Entry Account",
1098 filters={
1099 "docstatus": 1,
1100 "account": gain_loss_account,
1101 "reference_type": ref2_dt, # this will be Journal Entry
1102 "reference_name": ref2_dn,
1103 "reference_detail_no": ref2_detail_no,
1104 },
1105 pluck="parent",
1106 ):
1107 # deduplicate
1108 res = list({x for x in res})
1109 if exc_vouchers := frappe.db.get_all(
1110 "Journal Entry",
1111 filters={"name": ["in", res], "voucher_type": "Exchange Gain Or Loss"},
1112 fields=["voucher_type", "total_debit", "total_credit"],
1113 ):
1114 booked_voucher = exc_vouchers[0]
1115 if (
1116 booked_voucher.total_debit == exc_gain_loss
1117 and booked_voucher.total_credit == exc_gain_loss
1118 and booked_voucher.voucher_type == "Exchange Gain Or Loss"
1119 ):
1120 return True
1121 return False
1122
ruthra kumar66286322023-07-25 10:30:08 +05301123 def make_exchange_gain_loss_journal(self, args: dict = None) -> None:
ruthra kumar81cd7872023-04-27 09:46:54 +05301124 """
1125 Make Exchange Gain/Loss journal for Invoices and Payments
1126 """
ruthra kumarcd42b262023-07-10 15:28:10 +05301127 # Cancelling existing exchange gain/loss journals is handled during the `on_cancel` event.
1128 # see accounts/utils.py:cancel_exchange_gain_loss_journal()
ruthra kumar81cd7872023-04-27 09:46:54 +05301129 if self.docstatus == 1:
ruthra kumar7b516f82023-06-26 17:34:28 +05301130 if self.get("doctype") == "Journal Entry":
ruthra kumarcd42b262023-07-10 15:28:10 +05301131 # 'args' is populated with exchange gain/loss account and the amount to be booked.
1132 # These are generated by Sales/Purchase Invoice during reconciliation and advance allocation.
ruthra kumarc0b3b062023-07-25 10:51:58 +05301133 # and below logic is only for such scenarios
ruthra kumar7b516f82023-06-26 17:34:28 +05301134 if args:
1135 for arg in args:
ruthra kumarf4a65cc2023-07-14 16:51:42 +05301136 # Advance section uses `exchange_gain_loss` and reconciliation uses `difference_amount`
1137 if (
1138 arg.get("difference_amount", 0) != 0 or arg.get("exchange_gain_loss", 0) != 0
1139 ) and arg.get("difference_account"):
ruthra kumar7b516f82023-06-26 17:34:28 +05301140
ruthra kumaree3ce822023-06-26 21:43:20 +05301141 party_account = arg.get("account")
ruthra kumarc0b3b062023-07-25 10:51:58 +05301142 gain_loss_account = arg.get("difference_account")
ruthra kumarf4a65cc2023-07-14 16:51:42 +05301143 difference_amount = arg.get("difference_amount") or arg.get("exchange_gain_loss")
1144 if difference_amount > 0:
ruthra kumar05672432023-07-12 06:14:17 +05301145 dr_or_cr = "debit" if arg.get("party_type") == "Customer" else "credit"
1146 else:
1147 dr_or_cr = "credit" if arg.get("party_type") == "Customer" else "debit"
ruthra kumar7b516f82023-06-26 17:34:28 +05301148
1149 reverse_dr_or_cr = "debit" if dr_or_cr == "credit" else "credit"
1150
ruthra kumar79c6f012023-09-01 14:57:12 +05301151 if not self.gain_loss_journal_already_booked(
ruthra kumarc0b3b062023-07-25 10:51:58 +05301152 gain_loss_account,
1153 difference_amount,
ruthra kumarc0b3b062023-07-25 10:51:58 +05301154 self.doctype,
1155 self.name,
ruthra kumar79c6f012023-09-01 14:57:12 +05301156 arg.get("referenced_row"),
1157 ):
ruthra kumarf7865da2023-09-04 20:38:10 +05301158 posting_date = frappe.db.get_value(arg.voucher_type, arg.voucher_no, "posting_date")
ruthra kumar79c6f012023-09-01 14:57:12 +05301159 je = create_gain_loss_journal(
1160 self.company,
ruthra kumarf7865da2023-09-04 20:38:10 +05301161 posting_date,
ruthra kumar79c6f012023-09-01 14:57:12 +05301162 arg.get("party_type"),
1163 arg.get("party"),
1164 party_account,
1165 gain_loss_account,
1166 difference_amount,
1167 dr_or_cr,
1168 reverse_dr_or_cr,
1169 arg.get("against_voucher_type"),
1170 arg.get("against_voucher"),
1171 arg.get("idx"),
1172 self.doctype,
1173 self.name,
1174 arg.get("referenced_row"),
ruthra kumard6a3b9a2023-09-03 07:21:09 +05301175 arg.get("cost_center"),
ruthra kumaracc73222023-07-27 07:52:01 +05301176 )
ruthra kumar79c6f012023-09-01 14:57:12 +05301177 frappe.msgprint(
1178 _("Exchange Gain/Loss amount has been booked through {0}").format(
1179 get_link_to_form("Journal Entry", je)
1180 )
1181 )
ruthra kumar7b516f82023-06-26 17:34:28 +05301182
ruthra kumar81cd7872023-04-27 09:46:54 +05301183 if self.get("doctype") == "Payment Entry":
ruthra kumarcd42b262023-07-10 15:28:10 +05301184 # For Payment Entry, exchange_gain_loss field in the `references` table is the trigger for journal creation
ruthra kumar81cd7872023-04-27 09:46:54 +05301185 gain_loss_to_book = [x for x in self.references if x.exchange_gain_loss != 0]
1186 booked = []
1187 if gain_loss_to_book:
1188 vtypes = [x.reference_doctype for x in gain_loss_to_book]
1189 vnames = [x.reference_name for x in gain_loss_to_book]
1190 je = qb.DocType("Journal Entry")
1191 jea = qb.DocType("Journal Entry Account")
1192 parents = (
1193 qb.from_(jea)
1194 .select(jea.parent)
1195 .where(
1196 (jea.reference_type == "Payment Entry")
1197 & (jea.reference_name == self.name)
1198 & (jea.docstatus == 1)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301199 )
ruthra kumar81cd7872023-04-27 09:46:54 +05301200 .run()
Saqiba20999c2021-07-12 14:33:23 +05301201 )
1202
ruthra kumar81cd7872023-04-27 09:46:54 +05301203 booked = []
1204 if parents:
1205 booked = (
1206 qb.from_(je)
1207 .inner_join(jea)
1208 .on(je.name == jea.parent)
1209 .select(jea.reference_type, jea.reference_name, jea.reference_detail_no)
1210 .where(
1211 (je.docstatus == 1)
1212 & (je.name.isin(parents))
1213 & (je.voucher_type == "Exchange Gain or Loss")
1214 )
1215 .run()
1216 )
Saqiba20999c2021-07-12 14:33:23 +05301217
ruthra kumar81cd7872023-04-27 09:46:54 +05301218 for d in gain_loss_to_book:
ruthra kumarc0b3b062023-07-25 10:51:58 +05301219 # Filter out References for which Gain/Loss is already booked
ruthra kumar81cd7872023-04-27 09:46:54 +05301220 if d.exchange_gain_loss and (
1221 (d.reference_doctype, d.reference_name, str(d.idx)) not in booked
1222 ):
ruthra kumar81cd7872023-04-27 09:46:54 +05301223 if self.payment_type == "Receive":
1224 party_account = self.paid_from
1225 elif self.payment_type == "Pay":
1226 party_account = self.paid_to
1227
ruthra kumar81cd7872023-04-27 09:46:54 +05301228 dr_or_cr = "debit" if d.exchange_gain_loss > 0 else "credit"
ruthra kumar34b5e842023-06-16 14:07:44 +05301229
1230 if d.reference_doctype == "Purchase Invoice":
1231 dr_or_cr = "debit" if dr_or_cr == "credit" else "credit"
1232
ruthra kumar81cd7872023-04-27 09:46:54 +05301233 reverse_dr_or_cr = "debit" if dr_or_cr == "credit" else "credit"
1234
1235 gain_loss_account = frappe.get_cached_value(
1236 "Company", self.company, "exchange_gain_loss_account"
1237 )
ruthra kumar81cd7872023-04-27 09:46:54 +05301238
ruthra kumaracc73222023-07-27 07:52:01 +05301239 je = create_gain_loss_journal(
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05301240 self.company,
ruthra kumarf7865da2023-09-04 20:38:10 +05301241 self.posting_date,
ruthra kumarc0b3b062023-07-25 10:51:58 +05301242 self.party_type,
1243 self.party,
1244 party_account,
1245 gain_loss_account,
1246 d.exchange_gain_loss,
1247 dr_or_cr,
1248 reverse_dr_or_cr,
1249 d.reference_doctype,
1250 d.reference_name,
1251 d.idx,
1252 self.doctype,
1253 self.name,
1254 d.idx,
ruthra kumard6a3b9a2023-09-03 07:21:09 +05301255 self.cost_center,
Ankush Menat494bd9e2022-03-28 18:52:46 +05301256 )
ruthra kumaracc73222023-07-27 07:52:01 +05301257 frappe.msgprint(
1258 _("Exchange Gain/Loss amount has been booked through {0}").format(
1259 get_link_to_form("Journal Entry", je)
1260 )
1261 )
Saqiba20999c2021-07-12 14:33:23 +05301262
Deepesh Garg016ed952023-06-20 13:22:32 +05301263 def update_against_document_in_jv(self):
Nabin Hait28a05282016-06-27 17:41:39 +05301264 """
Ankush Menat494bd9e2022-03-28 18:52:46 +05301265 Links invoice and advance voucher:
1266 1. cancel advance voucher
1267 2. split into multiple rows if partially adjusted, assign against voucher
1268 3. submit advance voucher
Nabin Hait28a05282016-06-27 17:41:39 +05301269 """
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301270
Nabin Hait28a05282016-06-27 17:41:39 +05301271 if self.doctype == "Sales Invoice":
Nabin Haitff2f3ef2016-07-04 11:41:14 +05301272 party_type = "Customer"
Nabin Hait28a05282016-06-27 17:41:39 +05301273 party = self.customer
1274 party_account = self.debit_to
1275 dr_or_cr = "credit_in_account_currency"
1276 else:
Nabin Haitff2f3ef2016-07-04 11:41:14 +05301277 party_type = "Supplier"
Nabin Hait28a05282016-06-27 17:41:39 +05301278 party = self.supplier
1279 party_account = self.credit_to
1280 dr_or_cr = "debit_in_account_currency"
Nabin Hait48f5fa62014-09-18 15:03:54 +05301281
Nabin Hait28a05282016-06-27 17:41:39 +05301282 lst = []
Ankush Menat494bd9e2022-03-28 18:52:46 +05301283 for d in self.get("advances"):
Nabin Hait28a05282016-06-27 17:41:39 +05301284 if flt(d.allocated_amount) > 0:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301285 args = frappe._dict(
1286 {
1287 "voucher_type": d.reference_type,
1288 "voucher_no": d.reference_name,
1289 "voucher_detail_no": d.reference_row,
1290 "against_voucher_type": self.doctype,
1291 "against_voucher": self.name,
1292 "account": party_account,
1293 "party_type": party_type,
1294 "party": party,
1295 "is_advance": "Yes",
1296 "dr_or_cr": dr_or_cr,
1297 "unadjusted_amount": flt(d.advance_amount),
1298 "allocated_amount": flt(d.allocated_amount),
1299 "precision": d.precision("advance_amount"),
1300 "exchange_rate": (
1301 self.conversion_rate if self.party_account_currency != self.company_currency else 1
1302 ),
1303 "grand_total": (
1304 self.base_grand_total
1305 if self.party_account_currency == self.company_currency
1306 else self.grand_total
1307 ),
1308 "outstanding_amount": self.outstanding_amount,
Daizy Modi4efc9472022-11-07 09:21:03 +05301309 "difference_account": frappe.get_cached_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301310 "Company", self.company, "exchange_gain_loss_account"
1311 ),
1312 "exchange_gain_loss": flt(d.get("exchange_gain_loss")),
1313 }
1314 )
Nabin Hait28a05282016-06-27 17:41:39 +05301315 lst.append(args)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301316
Nabin Hait28a05282016-06-27 17:41:39 +05301317 if lst:
1318 from erpnext.accounts.utils import reconcile_against_document
Ankush Menat494bd9e2022-03-28 18:52:46 +05301319
Deepesh Garg016ed952023-06-20 13:22:32 +05301320 reconcile_against_document(lst)
Anand Doshid2946502014-04-08 20:10:03 +05301321
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +05301322 def on_cancel(self):
ruthra kumar81cd7872023-04-27 09:46:54 +05301323 from erpnext.accounts.utils import (
1324 cancel_exchange_gain_loss_journal,
1325 unlink_ref_doc_from_payment_entries,
1326 )
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +05301327
ruthra kumar6e18bb62023-07-11 12:21:10 +05301328 if self.doctype in ["Sales Invoice", "Purchase Invoice", "Payment Entry", "Journal Entry"]:
ruthra kumar81cd7872023-04-27 09:46:54 +05301329 # Cancel Exchange Gain/Loss Journal before unlinking
1330 cancel_exchange_gain_loss_journal(self)
1331
Ankush Menat494bd9e2022-03-28 18:52:46 +05301332 if frappe.db.get_single_value("Accounts Settings", "unlink_payment_on_cancellation_of_invoice"):
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +05301333 unlink_ref_doc_from_payment_entries(self)
1334
1335 elif self.doctype in ["Sales Order", "Purchase Order"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301336 if frappe.db.get_single_value(
1337 "Accounts Settings", "unlink_advance_payment_on_cancelation_of_order"
1338 ):
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +05301339 unlink_ref_doc_from_payment_entries(self)
1340
GangaManoj8396f242021-09-20 19:01:46 +05301341 if self.doctype == "Sales Order":
1342 self.unlink_ref_doc_from_po()
1343
1344 def unlink_ref_doc_from_po(self):
GangaManoj8396f242021-09-20 19:01:46 +05301345 so_items = []
1346 for item in self.items:
1347 so_items.append(item.name)
1348
Ankush Menat494bd9e2022-03-28 18:52:46 +05301349 linked_po = list(
1350 set(
1351 frappe.get_all(
1352 "Purchase Order Item",
1353 filters={
1354 "sales_order": self.name,
1355 "sales_order_item": ["in", so_items],
1356 "docstatus": ["<", 2],
1357 },
1358 pluck="parent",
1359 )
1360 )
1361 )
GangaManoj8396f242021-09-20 19:01:46 +05301362
GangaManoj8396f242021-09-20 19:01:46 +05301363 if linked_po:
GangaManoje77534f2021-09-20 19:01:46 +05301364 frappe.db.set_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301365 "Purchase Order Item",
1366 {"sales_order": self.name, "sales_order_item": ["in", so_items], "docstatus": ["<", 2]},
1367 {"sales_order": None, "sales_order_item": None},
GangaManoje77534f2021-09-20 19:01:46 +05301368 )
GangaManoj8396f242021-09-20 19:01:46 +05301369
1370 frappe.msgprint(_("Purchase Orders {0} are un-linked").format("\n".join(linked_po)))
1371
Deepesh Gargd18dde72020-11-29 21:40:04 +05301372 def get_tax_map(self):
1373 tax_map = {}
Ankush Menat494bd9e2022-03-28 18:52:46 +05301374 for tax in self.get("taxes"):
Deepesh Gargd18dde72020-11-29 21:40:04 +05301375 tax_map.setdefault(tax.account_head, 0.0)
1376 tax_map[tax.account_head] += tax.tax_amount
1377
1378 return tax_map
1379
Deepesh Garg92f7a5a2021-07-21 15:25:40 +05301380 def get_amount_and_base_amount(self, item, enable_discount_accounting):
1381 amount = item.net_amount
1382 base_amount = item.base_net_amount
1383
Ankush Menat494bd9e2022-03-28 18:52:46 +05301384 if (
1385 enable_discount_accounting
1386 and self.get("discount_amount")
1387 and self.get("additional_discount_account")
1388 ):
Deepesh Garg92f7a5a2021-07-21 15:25:40 +05301389 amount = item.amount
1390 base_amount = item.base_amount
1391
1392 return amount, base_amount
1393
1394 def get_tax_amounts(self, tax, enable_discount_accounting):
1395 amount = tax.tax_amount_after_discount_amount
1396 base_amount = tax.base_tax_amount_after_discount_amount
1397
Ankush Menat494bd9e2022-03-28 18:52:46 +05301398 if (
1399 enable_discount_accounting
1400 and self.get("discount_amount")
1401 and self.get("additional_discount_account")
1402 and self.get("apply_discount_on") == "Grand Total"
1403 ):
Deepesh Garg92f7a5a2021-07-21 15:25:40 +05301404 amount = tax.tax_amount
1405 base_amount = tax.base_tax_amount
1406
1407 return amount, base_amount
1408
GangaManoj8f7b0a12021-07-13 03:01:02 +05301409 def make_discount_gl_entries(self, gl_entries):
rahib-hassanf3fa6ac2022-04-20 16:01:12 +05301410 if self.doctype == "Purchase Invoice":
1411 enable_discount_accounting = cint(
1412 frappe.db.get_single_value("Buying Settings", "enable_discount_accounting")
1413 )
1414 elif self.doctype == "Sales Invoice":
1415 enable_discount_accounting = cint(
1416 frappe.db.get_single_value("Selling Settings", "enable_discount_accounting")
1417 )
GangaManoj8f7b0a12021-07-13 03:01:02 +05301418
Deepesh Garg3b159662022-08-21 17:51:05 +05301419 if self.doctype == "Purchase Invoice":
1420 dr_or_cr = "credit"
1421 rev_dr_cr = "debit"
1422 supplier_or_customer = self.supplier
1423
1424 else:
1425 dr_or_cr = "debit"
1426 rev_dr_cr = "credit"
1427 supplier_or_customer = self.customer
1428
GangaManoj8f7b0a12021-07-13 03:01:02 +05301429 if enable_discount_accounting:
1430 for item in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301431 if item.get("discount_amount") and item.get("discount_account"):
Deepesh Gargad7bb312021-07-28 11:38:44 +05301432 discount_amount = item.discount_amount * item.qty
GangaManoj8f7b0a12021-07-13 03:01:02 +05301433 if self.doctype == "Purchase Invoice":
Ankush Menat494bd9e2022-03-28 18:52:46 +05301434 income_or_expense_account = (
1435 item.expense_account
Ankush Menat4551d7d2021-08-19 13:41:10 +05301436 if (not item.enable_deferred_expense or self.is_return)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301437 else item.deferred_expense_account
1438 )
GangaManoj8f7b0a12021-07-13 03:01:02 +05301439 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301440 income_or_expense_account = (
1441 item.income_account
Ankush Menat4551d7d2021-08-19 13:41:10 +05301442 if (not item.enable_deferred_revenue or self.is_return)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301443 else item.deferred_revenue_account
1444 )
GangaManoj8f7b0a12021-07-13 03:01:02 +05301445
1446 account_currency = get_account_currency(item.discount_account)
1447 gl_entries.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301448 self.get_gl_dict(
1449 {
1450 "account": item.discount_account,
1451 "against": supplier_or_customer,
Saqib Ansarif915a9c2022-05-17 11:22:01 +05301452 dr_or_cr: flt(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301453 discount_amount * self.get("conversion_rate"), item.precision("discount_amount")
1454 ),
Saqib Ansarif915a9c2022-05-17 11:22:01 +05301455 dr_or_cr + "_in_account_currency": flt(discount_amount, item.precision("discount_amount")),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301456 "cost_center": item.cost_center,
1457 "project": item.project,
1458 },
1459 account_currency,
1460 item=item,
1461 )
GangaManoj8f7b0a12021-07-13 03:01:02 +05301462 )
1463
1464 account_currency = get_account_currency(income_or_expense_account)
1465 gl_entries.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301466 self.get_gl_dict(
1467 {
1468 "account": income_or_expense_account,
1469 "against": supplier_or_customer,
Saqib Ansarif915a9c2022-05-17 11:22:01 +05301470 rev_dr_cr: flt(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301471 discount_amount * self.get("conversion_rate"), item.precision("discount_amount")
1472 ),
Saqib Ansarif915a9c2022-05-17 11:22:01 +05301473 rev_dr_cr
1474 + "_in_account_currency": flt(discount_amount, item.precision("discount_amount")),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301475 "cost_center": item.cost_center,
1476 "project": item.project or self.project,
1477 },
1478 account_currency,
1479 item=item,
1480 )
GangaManoj8f7b0a12021-07-13 03:01:02 +05301481 )
GangaManoj857501c2021-07-15 22:03:46 +05301482
Deepesh Garg3b159662022-08-21 17:51:05 +05301483 if (
Deepesh Gargae3dce02022-08-22 08:57:58 +05301484 (enable_discount_accounting or self.get("is_cash_or_non_trade_discount"))
Deepesh Garg3b159662022-08-21 17:51:05 +05301485 and self.get("additional_discount_account")
1486 and self.get("discount_amount")
1487 ):
1488 gl_entries.append(
1489 self.get_gl_dict(
1490 {
1491 "account": self.additional_discount_account,
1492 "against": supplier_or_customer,
Gursheen Anand112cfe62023-08-31 17:08:51 +05301493 dr_or_cr: self.base_discount_amount,
vr-greycube4ada5a42023-09-27 10:38:32 +05301494 "cost_center": self.cost_center or erpnext.get_default_cost_center(self.company),
Deepesh Garg3b159662022-08-21 17:51:05 +05301495 },
1496 item=self,
Ankush Menat4551d7d2021-08-19 13:41:10 +05301497 )
Deepesh Garg3b159662022-08-21 17:51:05 +05301498 )
Ankush Menat4551d7d2021-08-19 13:41:10 +05301499
Deepesh Garg4c61ee32023-04-02 09:35:27 +05301500 def validate_multiple_billing(self, ref_dt, item_ref_dn, based_on):
Nabin Hait868766d2019-07-15 18:02:58 +05301501 from erpnext.controllers.status_updater import get_allowance_for
Saqib9c913c92021-11-26 12:00:13 +05301502
Nabin Hait868766d2019-07-15 18:02:58 +05301503 item_allowance = {}
1504 global_qty_allowance, global_amount_allowance = None, None
Anand Doshid2946502014-04-08 20:10:03 +05301505
Ankush Menat494bd9e2022-03-28 18:52:46 +05301506 role_allowed_to_over_bill = frappe.db.get_single_value(
1507 "Accounts Settings", "role_allowed_to_over_bill"
1508 )
Ankush Menat648b2d72021-09-20 15:27:12 +05301509 user_roles = frappe.get_roles()
1510
Ankush Menat43bf82b2021-09-20 16:31:20 +05301511 total_overbilled_amt = 0.0
1512
Deepesh Garg4c61ee32023-04-02 09:35:27 +05301513 reference_names = [d.get(item_ref_dn) for d in self.get("items") if d.get(item_ref_dn)]
1514 reference_details = self.get_billing_reference_details(
1515 reference_names, ref_dt + " Item", based_on
1516 )
1517
Nabin Hait4b8185d2014-12-25 18:19:39 +05301518 for item in self.get("items"):
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301519 if not item.get(item_ref_dn):
1520 continue
Anand Doshid2946502014-04-08 20:10:03 +05301521
Deepesh Garg4c61ee32023-04-02 09:35:27 +05301522 ref_amt = flt(reference_details.get(item.get(item_ref_dn)), self.precision(based_on, item))
1523
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301524 if not ref_amt:
1525 frappe.msgprint(
Deepesh Garg4c61ee32023-04-02 09:35:27 +05301526 _("System will not check over billing since amount for Item {0} in {1} is zero").format(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301527 item.item_code, ref_dt
1528 ),
1529 title=_("Warning"),
1530 indicator="orange",
1531 )
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301532 continue
Anand Doshid2946502014-04-08 20:10:03 +05301533
Saqib9c913c92021-11-26 12:00:13 +05301534 already_billed = self.get_billed_amount_for_item(item, item_ref_dn, based_on)
Anand Doshid2946502014-04-08 20:10:03 +05301535
Ankush Menat494bd9e2022-03-28 18:52:46 +05301536 total_billed_amt = flt(
1537 flt(already_billed) + flt(item.get(based_on)), self.precision(based_on, item)
1538 )
Anand Doshid2946502014-04-08 20:10:03 +05301539
Ankush Menat494bd9e2022-03-28 18:52:46 +05301540 allowance, item_allowance, global_qty_allowance, global_amount_allowance = get_allowance_for(
1541 item.item_code, item_allowance, global_qty_allowance, global_amount_allowance, "amount"
1542 )
rohitwaghchaure285344e2019-10-11 11:02:11 +05301543
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301544 max_allowed_amt = flt(ref_amt * (100 + allowance) / 100)
Deepesh Gargcb718fc2021-04-19 13:25:15 +05301545
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301546 if total_billed_amt < 0 and max_allowed_amt < 0:
1547 # while making debit note against purchase return entry(purchase receipt) getting overbill error
1548 total_billed_amt = abs(total_billed_amt)
1549 max_allowed_amt = abs(max_allowed_amt)
Afshan53fefd72021-06-24 10:09:02 +05301550
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301551 overbill_amt = total_billed_amt - max_allowed_amt
1552 total_overbilled_amt += overbill_amt
1553
1554 if overbill_amt > 0.01 and role_allowed_to_over_bill not in user_roles:
1555 if self.doctype != "Purchase Invoice":
1556 self.throw_overbill_exception(item, max_allowed_amt)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301557 elif not cint(
1558 frappe.db.get_single_value(
1559 "Buying Settings", "bill_for_rejected_quantity_in_purchase_invoice"
1560 )
1561 ):
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301562 self.throw_overbill_exception(item, max_allowed_amt)
1563
1564 if role_allowed_to_over_bill in user_roles and total_overbilled_amt > 0.1:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301565 frappe.msgprint(
1566 _("Overbilling of {} ignored because you have {} role.").format(
1567 total_overbilled_amt, role_allowed_to_over_bill
1568 ),
1569 indicator="orange",
1570 alert=True,
1571 )
Afshan53fefd72021-06-24 10:09:02 +05301572
Deepesh Garg4c61ee32023-04-02 09:35:27 +05301573 def get_billing_reference_details(self, reference_names, reference_doctype, based_on):
1574 return frappe._dict(
1575 frappe.get_all(
1576 reference_doctype,
1577 filters={"name": ("in", reference_names)},
1578 fields=["name", based_on],
1579 as_list=1,
1580 )
1581 )
1582
Saqib9c913c92021-11-26 12:00:13 +05301583 def get_billed_amount_for_item(self, item, item_ref_dn, based_on):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301584 """
1585 Returns Sum of Amount of
1586 Sales/Purchase Invoice Items
1587 that are linked to `item_ref_dn` (`dn_detail` / `pr_detail`)
1588 that are submitted OR not submitted but are under current invoice
1589 """
Saqib9c913c92021-11-26 12:00:13 +05301590
1591 from frappe.query_builder import Criterion
1592 from frappe.query_builder.functions import Sum
1593
1594 item_doctype = frappe.qb.DocType(item.doctype)
1595 based_on_field = frappe.qb.Field(based_on)
1596 join_field = frappe.qb.Field(item_ref_dn)
1597
1598 result = (
1599 frappe.qb.from_(item_doctype)
1600 .select(Sum(based_on_field))
Ankush Menat494bd9e2022-03-28 18:52:46 +05301601 .where(join_field == item.get(item_ref_dn))
Saqib9c913c92021-11-26 12:00:13 +05301602 .where(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301603 Criterion.any(
1604 [ # select all items from other invoices OR current invoices
1605 Criterion.all(
1606 [ # for selecting items from other invoices
1607 item_doctype.docstatus == 1,
1608 item_doctype.parent != self.name,
1609 ]
1610 ),
1611 Criterion.all(
1612 [ # for selecting items from current invoice, that are linked to same reference
1613 item_doctype.docstatus == 0,
1614 item_doctype.parent == self.name,
1615 item_doctype.name != item.name,
1616 ]
1617 ),
1618 ]
1619 )
Saqib9c913c92021-11-26 12:00:13 +05301620 )
1621 ).run()
1622
1623 return result[0][0] if result else 0
1624
Afshan53fefd72021-06-24 10:09:02 +05301625 def throw_overbill_exception(self, item, max_allowed_amt):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301626 frappe.throw(
1627 _(
1628 "Cannot overbill for Item {0} in row {1} more than {2}. To allow over-billing, please set allowance in Accounts Settings"
1629 ).format(item.item_code, item.idx, max_allowed_amt)
1630 )
Anand Doshid2946502014-04-08 20:10:03 +05301631
Rohit Waghchaure2a14f252021-07-30 12:36:35 +05301632 def get_company_default(self, fieldname, ignore_validation=False):
Rushabh Mehta1f847992013-12-12 19:12:19 +05301633 from erpnext.accounts.utils import get_company_default
Ankush Menat494bd9e2022-03-28 18:52:46 +05301634
Rohit Waghchaure2a14f252021-07-30 12:36:35 +05301635 return get_company_default(self.company, fieldname, ignore_validation=ignore_validation)
Anand Doshid2946502014-04-08 20:10:03 +05301636
Nabin Haita36adbd2013-08-02 14:50:12 +05301637 def get_stock_items(self):
1638 stock_items = []
Nabin Haitdd38a262014-12-26 13:15:21 +05301639 item_codes = list(set(item.item_code for item in self.get("items")))
Nabin Haita36adbd2013-08-02 14:50:12 +05301640 if item_codes:
Saqib Ansari199a6da2022-03-31 11:41:52 +05301641 stock_items = frappe.db.get_values(
1642 "Item", {"name": ["in", item_codes], "is_stock_item": 1}, pluck="name", cache=True
1643 )
Anand Doshid2946502014-04-08 20:10:03 +05301644
Nabin Haita36adbd2013-08-02 14:50:12 +05301645 return stock_items
Anand Doshid2946502014-04-08 20:10:03 +05301646
Ankit Javalkar8e7ca412014-09-12 15:18:53 +05301647 def set_total_advance_paid(self):
ruthra kumar44870652022-11-01 10:11:38 +05301648 ple = frappe.qb.DocType("Payment Ledger Entry")
1649 party = self.customer if self.doctype == "Sales Order" else self.supplier
1650 advance = (
1651 frappe.qb.from_(ple)
ruthra kumarbf76b852022-11-22 12:16:11 +05301652 .select(ple.account_currency, Abs(Sum(ple.amount_in_account_currency)).as_("amount"))
ruthra kumar44870652022-11-01 10:11:38 +05301653 .where(
1654 (ple.against_voucher_type == self.doctype)
1655 & (ple.against_voucher_no == self.name)
1656 & (ple.party == party)
ruthra kumarbf76b852022-11-22 12:16:11 +05301657 & (ple.docstatus == 1)
ruthra kumar44870652022-11-01 10:11:38 +05301658 & (ple.company == self.company)
1659 )
1660 .run(as_dict=True)
1661 )
Ankit Javalkar8e7ca412014-09-12 15:18:53 +05301662
Nabin Haitb2206d12016-01-27 15:43:12 +05301663 if advance:
Anand Doshi7c0a58a2016-01-29 12:16:24 +05301664 advance = advance[0]
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301665
Anand Doshi7c0a58a2016-01-29 12:16:24 +05301666 advance_paid = flt(advance.amount, self.precision("advance_paid"))
Ankush Menat494bd9e2022-03-28 18:52:46 +05301667 formatted_advance_paid = fmt_money(
1668 advance_paid, precision=self.precision("advance_paid"), currency=advance.account_currency
1669 )
Anand Doshi7c0a58a2016-01-29 12:16:24 +05301670
Ankush Menat494bd9e2022-03-28 18:52:46 +05301671 frappe.db.set_value(self.doctype, self.name, "party_account_currency", advance.account_currency)
Anand Doshi7c0a58a2016-01-29 12:16:24 +05301672
1673 if advance.account_currency == self.currency:
finbyz5efc7972019-01-05 11:12:11 +05301674 order_total = self.get("rounded_total") or self.grand_total
1675 precision = "rounded_total" if self.get("rounded_total") else "grand_total"
Nabin Haitb2206d12016-01-27 15:43:12 +05301676 else:
finbyz5efc7972019-01-05 11:12:11 +05301677 order_total = self.get("base_rounded_total") or self.base_grand_total
1678 precision = "base_rounded_total" if self.get("base_rounded_total") else "base_grand_total"
Sagar Voraf733a392019-01-07 14:24:01 +05301679
Ankush Menat494bd9e2022-03-28 18:52:46 +05301680 formatted_order_total = fmt_money(
1681 order_total, precision=self.precision(precision), currency=advance.account_currency
1682 )
Anand Doshi7c0a58a2016-01-29 12:16:24 +05301683
Nabin Hait9db1b222016-06-30 12:37:53 +05301684 if self.currency == self.company_currency and advance_paid > order_total:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301685 frappe.throw(
1686 _(
1687 "Total advance ({0}) against Order {1} cannot be greater than the Grand Total ({2})"
1688 ).format(formatted_advance_paid, self.name, formatted_order_total)
1689 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301690
Nabin Hait13093b42016-06-29 18:04:37 +05301691 frappe.db.set_value(self.doctype, self.name, "advance_paid", advance_paid)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +05301692
ankitjavalkarworke60822b2014-08-26 14:29:06 +05301693 @property
1694 def company_abbr(self):
Nabin Hait6a5695f2018-08-09 11:30:21 +05301695 if not hasattr(self, "_abbr"):
Daizy Modi4efc9472022-11-07 09:21:03 +05301696 self._abbr = frappe.get_cached_value("Company", self.company, "abbr")
ankitjavalkarworke60822b2014-08-26 14:29:06 +05301697
1698 return self._abbr
1699
marination4be5b5c2020-10-08 19:08:27 +05301700 def raise_missing_debit_credit_account_error(self, party_type, party):
marination53b1a9a2020-11-03 15:45:25 +05301701 """Raise an error if debit to/credit to account does not exist."""
Ankush Menat494bd9e2022-03-28 18:52:46 +05301702 db_or_cr = (
1703 frappe.bold("Debit To") if self.doctype == "Sales Invoice" else frappe.bold("Credit To")
1704 )
marination4be5b5c2020-10-08 19:08:27 +05301705 rec_or_pay = "Receivable" if self.doctype == "Sales Invoice" else "Payable"
1706
1707 link_to_party = frappe.utils.get_link_to_form(party_type, party)
1708 link_to_company = frappe.utils.get_link_to_form("Company", self.company)
1709
Ankush Menat494bd9e2022-03-28 18:52:46 +05301710 message = _("{0} Account not found against Customer {1}.").format(
1711 db_or_cr, frappe.bold(party) or ""
1712 )
marination4be5b5c2020-10-08 19:08:27 +05301713 message += "<br>" + _("Please set one of the following:") + "<br>"
Ankush Menat494bd9e2022-03-28 18:52:46 +05301714 message += (
1715 "<br><ul><li>"
1716 + _("'Account' in the Accounting section of Customer {0}").format(link_to_party)
1717 + "</li>"
1718 )
1719 message += (
1720 "<li>"
1721 + _("'Default {0} Account' in Company {1}").format(rec_or_pay, link_to_company)
1722 + "</li></ul>"
1723 )
marination4be5b5c2020-10-08 19:08:27 +05301724
marination53b1a9a2020-11-03 15:45:25 +05301725 frappe.throw(message, title=_("Account Missing"), exc=AccountMissingError)
marination4be5b5c2020-10-08 19:08:27 +05301726
Neil Trini Lasrado3fbbb712015-07-17 12:10:12 +05301727 def validate_party(self):
Nabin Hait4ffd7f32015-08-27 12:28:36 +05301728 party_type, party = self.get_party()
shreyaseba9ca42016-01-26 14:56:52 +05301729 validate_party_frozen_disabled(party_type, party)
Anand Doshi979326b2015-09-11 16:22:37 +05301730
Nabin Hait4ffd7f32015-08-27 12:28:36 +05301731 def get_party(self):
Neil Trini Lasrado79bf2332015-07-20 13:03:48 +05301732 party_type = None
shreyas29b565f2016-01-25 17:30:49 +05301733 if self.doctype in ("Opportunity", "Quotation", "Sales Order", "Delivery Note", "Sales Invoice"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301734 party_type = "Customer"
shreyas29b565f2016-01-25 17:30:49 +05301735
Ankush Menat494bd9e2022-03-28 18:52:46 +05301736 elif self.doctype in (
1737 "Supplier Quotation",
1738 "Purchase Order",
1739 "Purchase Receipt",
1740 "Purchase Invoice",
1741 ):
1742 party_type = "Supplier"
shreyas29b565f2016-01-25 17:30:49 +05301743
1744 elif self.meta.get_field("customer"):
1745 party_type = "Customer"
Neil Trini Lasrado3fbbb712015-07-17 12:10:12 +05301746
Neil Trini Lasrado79bf2332015-07-20 13:03:48 +05301747 elif self.meta.get_field("supplier"):
shreyas29b565f2016-01-25 17:30:49 +05301748 party_type = "Supplier"
Anand Doshi979326b2015-09-11 16:22:37 +05301749
Nabin Hait4ffd7f32015-08-27 12:28:36 +05301750 party = self.get(party_type.lower()) if party_type else None
Anand Doshi979326b2015-09-11 16:22:37 +05301751
Nabin Hait4ffd7f32015-08-27 12:28:36 +05301752 return party_type, party
Anand Doshi979326b2015-09-11 16:22:37 +05301753
Nabin Hait4ffd7f32015-08-27 12:28:36 +05301754 def validate_currency(self):
Nabin Hait6e439a52015-08-28 19:24:22 +05301755 if self.get("currency"):
Nabin Hait4ffd7f32015-08-27 12:28:36 +05301756 party_type, party = self.get_party()
Nabin Hait6e439a52015-08-28 19:24:22 +05301757 if party_type and party:
Anand Doshib20baf82015-09-25 16:17:50 +05301758 party_account_currency = get_party_account_currency(party_type, party, self.company)
Anand Doshi979326b2015-09-11 16:22:37 +05301759
Ankush Menat494bd9e2022-03-28 18:52:46 +05301760 if (
1761 party_account_currency
1762 and party_account_currency != self.company_currency
1763 and self.currency != party_account_currency
1764 ):
Gursheen Anand112cfe62023-08-31 17:08:51 +05301765
Ankush Menat494bd9e2022-03-28 18:52:46 +05301766 frappe.throw(
1767 _("Accounting Entry for {0}: {1} can only be made in currency: {2}").format(
1768 party_type, party, party_account_currency
1769 ),
1770 InvalidCurrency,
1771 )
Anand Doshi979326b2015-09-11 16:22:37 +05301772
shreyas29b565f2016-01-25 17:30:49 +05301773 # Note: not validating with gle account because we don't have the account
1774 # at quotation / sales order level and we shouldn't stop someone
1775 # from creating a sales invoice if sales order is already created
Rushabh Mehta2cb7a9f2016-06-15 16:45:03 +05301776
Deepesh Garg80c85dd2021-08-12 15:39:07 +05301777 def validate_party_account_currency(self):
Deepesh Garg33d97672022-05-12 16:40:29 +05301778 if self.doctype not in ("Sales Invoice", "Purchase Invoice"):
Deepesh Garg80c85dd2021-08-12 15:39:07 +05301779 return
1780
Deepesh Garg33d97672022-05-12 16:40:29 +05301781 if self.is_opening == "Yes":
Deepesh Garg60915e82021-08-21 23:05:48 +05301782 return
1783
Deepesh Garg80c85dd2021-08-12 15:39:07 +05301784 party_type, party = self.get_party()
1785 party_gle_currency = get_party_gle_currency(party_type, party, self.company)
Deepesh Garg33d97672022-05-12 16:40:29 +05301786 party_account = (
1787 self.get("debit_to") if self.doctype == "Sales Invoice" else self.get("credit_to")
1788 )
Deepesh Garg80c85dd2021-08-12 15:39:07 +05301789 party_account_currency = get_account_currency(party_account)
Deepesh Garge04e67c2022-07-11 19:25:18 +05301790 allow_multi_currency_invoices_against_single_party_account = frappe.db.get_singles_value(
Deepesh Garg3cf609f2022-07-11 13:46:59 +05301791 "Accounts Settings", "allow_multi_currency_invoices_against_single_party_account"
1792 )
Deepesh Garg80c85dd2021-08-12 15:39:07 +05301793
Deepesh Garg3cf609f2022-07-11 13:46:59 +05301794 if (
1795 not party_gle_currency
1796 and (party_account_currency != self.currency)
1797 and not allow_multi_currency_invoices_against_single_party_account
1798 ):
Deepesh Garg33d97672022-05-12 16:40:29 +05301799 frappe.throw(
Devin Slauenwhite3a1c9232022-06-02 14:15:50 -04001800 _("Party Account {0} currency ({1}) and document currency ({2}) should be same").format(
Devin Slauenwhiteb061ea42022-06-02 14:23:54 -04001801 frappe.bold(party_account), party_account_currency, self.currency
Deepesh Garg33d97672022-05-12 16:40:29 +05301802 )
1803 )
Deepesh Garg80c85dd2021-08-12 15:39:07 +05301804
Nabin Hait297d74a2016-11-23 15:58:51 +05301805 def delink_advance_entries(self, linked_doc_name):
1806 total_allocated_amount = 0
1807 for adv in self.advances:
1808 consider_for_total_advance = True
1809 if adv.reference_name == linked_doc_name:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301810 frappe.db.sql(
1811 """delete from `tab{0} Advance`
1812 where name = %s""".format(
1813 self.doctype
1814 ),
1815 adv.name,
1816 )
Nabin Hait297d74a2016-11-23 15:58:51 +05301817 consider_for_total_advance = False
1818
1819 if consider_for_total_advance:
1820 total_allocated_amount += flt(adv.allocated_amount, adv.precision("allocated_amount"))
1821
Ankush Menat494bd9e2022-03-28 18:52:46 +05301822 frappe.db.set_value(
1823 self.doctype, self.name, "total_advance", total_allocated_amount, update_modified=False
1824 )
Rohit Waghchaure6087fe12016-04-09 14:31:09 +05301825
KanchanChauhan49a50fe2016-11-18 13:57:53 +05301826 def group_similar_items(self):
1827 group_item_qty = {}
1828 group_item_amount = {}
Shreya Shah785f1aa2018-10-11 10:14:25 +05301829 # to update serial number in print
1830 count = 0
KanchanChauhan49a50fe2016-11-18 13:57:53 +05301831
1832 for item in self.items:
1833 group_item_qty[item.item_code] = group_item_qty.get(item.item_code, 0) + item.qty
1834 group_item_amount[item.item_code] = group_item_amount.get(item.item_code, 0) + item.amount
1835
1836 duplicate_list = []
KanchanChauhan49a50fe2016-11-18 13:57:53 +05301837 for item in self.items:
1838 if item.item_code in group_item_qty:
Shreya Shah785f1aa2018-10-11 10:14:25 +05301839 count += 1
KanchanChauhan49a50fe2016-11-18 13:57:53 +05301840 item.qty = group_item_qty[item.item_code]
1841 item.amount = group_item_amount[item.item_code]
deepeshgarg007e8d21cd2019-06-24 17:46:44 +05301842
1843 if item.qty:
1844 item.rate = flt(flt(item.amount) / flt(item.qty), item.precision("rate"))
1845 else:
1846 item.rate = 0
1847
Shreya Shah785f1aa2018-10-11 10:14:25 +05301848 item.idx = count
KanchanChauhan49a50fe2016-11-18 13:57:53 +05301849 del group_item_qty[item.item_code]
1850 else:
1851 duplicate_list.append(item)
KanchanChauhan49a50fe2016-11-18 13:57:53 +05301852 for item in duplicate_list:
1853 self.remove(item)
1854
tunde32aa7c12017-09-07 06:52:15 +01001855 def set_payment_schedule(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301856 if self.doctype == "Sales Invoice" and self.is_pos:
1857 self.payment_terms_template = ""
Manas Solankia7f55892018-04-02 10:32:00 +05301858 return
rohitwaghchauredb9fa782018-03-01 10:32:29 +05301859
Ankush Menat494bd9e2022-03-28 18:52:46 +05301860 party_account_currency = self.get("party_account_currency")
Deepesh Garg26210162020-08-11 16:06:13 +05301861 if not party_account_currency:
1862 party_type, party = self.get_party()
1863
1864 if party_type and party:
1865 party_account_currency = get_party_account_currency(party_type, party, self.company)
1866
rohitwaghchaureda941af2018-01-17 16:23:04 +05301867 posting_date = self.get("bill_date") or self.get("posting_date") or self.get("transaction_date")
tundedf3a1752017-09-11 11:02:57 +01001868 date = self.get("due_date")
1869 due_date = date or posting_date
Deepesh Garg26210162020-08-11 16:06:13 +05301870
Saqib Ansarid552fe62021-04-23 14:46:52 +05301871 base_grand_total = self.get("base_rounded_total") or self.base_grand_total
1872 grand_total = self.get("rounded_total") or self.grand_total
Deepesh Garg5c758942023-04-16 17:11:24 +05301873 automatically_fetch_payment_terms = 0
Deepesh Garg26210162020-08-11 16:06:13 +05301874
Nabin Hait2f9f4f92017-12-20 12:24:59 +05301875 if self.doctype in ("Sales Invoice", "Purchase Invoice"):
Saqib Ansarid552fe62021-04-23 14:46:52 +05301876 base_grand_total = base_grand_total - flt(self.base_write_off_amount)
Nabin Hait2f9f4f92017-12-20 12:24:59 +05301877 grand_total = grand_total - flt(self.write_off_amount)
Deepesh Gargbcf56e62021-08-06 23:53:16 +05301878 po_or_so, doctype, fieldname = self.get_order_details()
Ankush Menat494bd9e2022-03-28 18:52:46 +05301879 automatically_fetch_payment_terms = cint(
1880 frappe.db.get_single_value("Accounts Settings", "automatically_fetch_payment_terms")
1881 )
tunde96b8f222017-09-08 15:35:59 +01001882
Rohit Waghchaure4a267b92019-05-09 19:50:00 +05301883 if self.get("total_advance"):
Saqib Ansarid552fe62021-04-23 14:46:52 +05301884 if party_account_currency == self.company_currency:
1885 base_grand_total -= self.get("total_advance")
Ankush Menat494bd9e2022-03-28 18:52:46 +05301886 grand_total = flt(
1887 base_grand_total / self.get("conversion_rate"), self.precision("grand_total")
1888 )
Saqib Ansarid552fe62021-04-23 14:46:52 +05301889 else:
1890 grand_total -= self.get("total_advance")
Ankush Menat494bd9e2022-03-28 18:52:46 +05301891 base_grand_total = flt(
1892 grand_total * self.get("conversion_rate"), self.precision("base_grand_total")
1893 )
Rohit Waghchaure4a267b92019-05-09 19:50:00 +05301894
Nabin Hait0551f7b2017-11-21 19:58:16 +05301895 if not self.get("payment_schedule"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301896 if (
1897 self.doctype in ["Sales Invoice", "Purchase Invoice"]
1898 and automatically_fetch_payment_terms
1899 and self.linked_order_has_payment_terms(po_or_so, fieldname, doctype)
1900 ):
Deepesh Gargbcf56e62021-08-06 23:53:16 +05301901 self.fetch_payment_terms_from_order(po_or_so, doctype)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301902 if self.get("payment_terms_template"):
Deepesh Gargbcf56e62021-08-06 23:53:16 +05301903 self.ignore_default_payment_terms_template = 1
1904 elif self.get("payment_terms_template"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301905 data = get_payment_terms(
1906 self.payment_terms_template, posting_date, grand_total, base_grand_total
1907 )
Nabin Hait0551f7b2017-11-21 19:58:16 +05301908 for item in data:
1909 self.append("payment_schedule", item)
GangaManoj4323f4b2021-07-22 05:57:42 +05301910 elif self.doctype not in ["Purchase Receipt"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301911 data = dict(
1912 due_date=due_date,
1913 invoice_portion=100,
1914 payment_amount=grand_total,
1915 base_payment_amount=base_grand_total,
1916 )
Nabin Hait0551f7b2017-11-21 19:58:16 +05301917 self.append("payment_schedule", data)
Deepesh Gargbcf56e62021-08-06 23:53:16 +05301918
Gursheen Kaur Anandedbefee2023-08-04 17:49:17 +05301919 allocate_payment_based_on_payment_terms = frappe.db.get_value(
1920 "Payment Terms Template", self.payment_terms_template, "allocate_payment_based_on_payment_terms"
1921 )
1922
Deepesh Gargf7b50f22023-04-25 19:18:45 +05301923 if not (
1924 automatically_fetch_payment_terms
Gursheen Kaur Anandedbefee2023-08-04 17:49:17 +05301925 and allocate_payment_based_on_payment_terms
Deepesh Gargf7b50f22023-04-25 19:18:45 +05301926 and self.linked_order_has_payment_terms(po_or_so, fieldname, doctype)
1927 ):
Deepesh Garg5c758942023-04-16 17:11:24 +05301928 for d in self.get("payment_schedule"):
1929 if d.invoice_portion:
1930 d.payment_amount = flt(
1931 grand_total * flt(d.invoice_portion / 100), d.precision("payment_amount")
1932 )
1933 d.base_payment_amount = flt(
1934 base_grand_total * flt(d.invoice_portion / 100), d.precision("base_payment_amount")
1935 )
1936 d.outstanding = d.payment_amount
1937 elif not d.invoice_portion:
1938 d.base_payment_amount = flt(
1939 d.payment_amount * self.get("conversion_rate"), d.precision("base_payment_amount")
1940 )
ruthra kumar0da6c162023-05-16 18:57:42 +05301941 else:
1942 self.fetch_payment_terms_from_order(po_or_so, doctype)
1943 self.ignore_default_payment_terms_template = 1
tunde43870aa2017-08-18 11:59:30 +01001944
GangaManoj4323f4b2021-07-22 05:57:42 +05301945 def get_order_details(self):
1946 if self.doctype == "Sales Invoice":
Ankush Menat494bd9e2022-03-28 18:52:46 +05301947 po_or_so = self.get("items")[0].get("sales_order")
GangaManoj4323f4b2021-07-22 05:57:42 +05301948 po_or_so_doctype = "Sales Order"
1949 po_or_so_doctype_name = "sales_order"
1950
tunde43870aa2017-08-18 11:59:30 +01001951 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301952 po_or_so = self.get("items")[0].get("purchase_order")
GangaManoj4323f4b2021-07-22 05:57:42 +05301953 po_or_so_doctype = "Purchase Order"
1954 po_or_so_doctype_name = "purchase_order"
Ankush Menat4551d7d2021-08-19 13:41:10 +05301955
GangaManoj4323f4b2021-07-22 05:57:42 +05301956 return po_or_so, po_or_so_doctype, po_or_so_doctype_name
1957
GangaManojc7c90242021-07-29 19:18:35 +05301958 def linked_order_has_payment_terms(self, po_or_so, fieldname, doctype):
GangaManoj4323f4b2021-07-22 05:57:42 +05301959 if po_or_so and self.all_items_have_same_po_or_so(po_or_so, fieldname):
GangaManojc7c90242021-07-29 19:18:35 +05301960 if self.linked_order_has_payment_terms_template(po_or_so, doctype):
GangaManoj4323f4b2021-07-22 05:57:42 +05301961 return True
1962 elif self.linked_order_has_payment_schedule(po_or_so):
1963 return True
Ankush Menat4551d7d2021-08-19 13:41:10 +05301964
GangaManoj4323f4b2021-07-22 05:57:42 +05301965 return False
1966
1967 def all_items_have_same_po_or_so(self, po_or_so, fieldname):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301968 for item in self.get("items"):
GangaManoj4323f4b2021-07-22 05:57:42 +05301969 if item.get(fieldname) != po_or_so:
1970 return False
Ankush Menat4551d7d2021-08-19 13:41:10 +05301971
GangaManoj4323f4b2021-07-22 05:57:42 +05301972 return True
1973
GangaManojc7c90242021-07-29 19:18:35 +05301974 def linked_order_has_payment_terms_template(self, po_or_so, doctype):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301975 return frappe.get_value(doctype, po_or_so, "payment_terms_template")
GangaManoj4323f4b2021-07-22 05:57:42 +05301976
1977 def linked_order_has_payment_schedule(self, po_or_so):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301978 return frappe.get_all("Payment Schedule", filters={"parent": po_or_so})
GangaManoj4323f4b2021-07-22 05:57:42 +05301979
1980 def fetch_payment_terms_from_order(self, po_or_so, po_or_so_doctype):
1981 """
Ankush Menat494bd9e2022-03-28 18:52:46 +05301982 Fetch Payment Terms from Purchase/Sales Order on creating a new Purchase/Sales Invoice.
GangaManoj4323f4b2021-07-22 05:57:42 +05301983 """
1984 po_or_so = frappe.get_cached_doc(po_or_so_doctype, po_or_so)
1985
1986 self.payment_schedule = []
1987 self.payment_terms_template = po_or_so.payment_terms_template
1988
1989 for schedule in po_or_so.payment_schedule:
1990 payment_schedule = {
Ankush Menat494bd9e2022-03-28 18:52:46 +05301991 "payment_term": schedule.payment_term,
1992 "due_date": schedule.due_date,
1993 "invoice_portion": schedule.invoice_portion,
1994 "mode_of_payment": schedule.mode_of_payment,
1995 "description": schedule.description,
Deepesh Garg5c758942023-04-16 17:11:24 +05301996 "payment_amount": schedule.payment_amount,
1997 "base_payment_amount": schedule.base_payment_amount,
1998 "outstanding": schedule.outstanding,
1999 "paid_amount": schedule.paid_amount,
GangaManoj4323f4b2021-07-22 05:57:42 +05302000 }
GangaManoj5b33e752021-08-05 21:50:09 +05302001
Ankush Menat494bd9e2022-03-28 18:52:46 +05302002 if schedule.discount_type == "Percentage":
2003 payment_schedule["discount_type"] = schedule.discount_type
2004 payment_schedule["discount"] = schedule.discount
GangaManoj5b33e752021-08-05 21:50:09 +05302005
ruthra kumar9bd56b02022-02-01 14:14:04 +05302006 if not schedule.invoice_portion:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302007 payment_schedule["payment_amount"] = schedule.payment_amount
ruthra kumar9bd56b02022-02-01 14:14:04 +05302008
GangaManoj4323f4b2021-07-22 05:57:42 +05302009 self.append("payment_schedule", payment_schedule)
tunde43870aa2017-08-18 11:59:30 +01002010
tundebe1b8712017-08-19 08:21:44 +01002011 def set_due_date(self):
Nabin Hait0551f7b2017-11-21 19:58:16 +05302012 due_dates = [d.due_date for d in self.get("payment_schedule") if d.due_date]
2013 if due_dates:
2014 self.due_date = max(due_dates)
tunde62af5c52017-09-22 15:16:38 +01002015
2016 def validate_payment_schedule_dates(self):
tunde77ecacc2017-09-22 23:12:55 +01002017 dates = []
tunde9bed2de2017-09-25 10:19:35 +01002018 li = []
tunde43870aa2017-08-18 11:59:30 +01002019
Ankush Menat494bd9e2022-03-28 18:52:46 +05302020 if self.doctype == "Sales Invoice" and self.is_pos:
2021 return
rohitwaghchauredb9fa782018-03-01 10:32:29 +05302022
tunde43870aa2017-08-18 11:59:30 +01002023 for d in self.get("payment_schedule"):
Nabin Hait2f9f4f92017-12-20 12:24:59 +05302024 if self.doctype == "Sales Order" and getdate(d.due_date) < getdate(self.transaction_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302025 frappe.throw(
2026 _("Row {0}: Due Date in the Payment Terms table cannot be before Posting Date").format(d.idx)
2027 )
tunde77ecacc2017-09-22 23:12:55 +01002028 elif d.due_date in dates:
mnatalia5f0e8d62018-05-22 06:38:50 +03002029 li.append(_("{0} in row {1}").format(d.due_date, d.idx))
tunde9bed2de2017-09-25 10:19:35 +01002030 dates.append(d.due_date)
2031
2032 if li:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302033 duplicates = "<br>" + "<br>".join(li)
2034 frappe.throw(
2035 _("Rows with duplicate due dates in other rows were found: {0}").format(duplicates)
2036 )
tunde43870aa2017-08-18 11:59:30 +01002037
tunde62af5c52017-09-22 15:16:38 +01002038 def validate_payment_schedule_amount(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302039 if self.doctype == "Sales Invoice" and self.is_pos:
2040 return
rohitwaghchauredb9fa782018-03-01 10:32:29 +05302041
Ankush Menat494bd9e2022-03-28 18:52:46 +05302042 party_account_currency = self.get("party_account_currency")
Deepesh Garg26210162020-08-11 16:06:13 +05302043 if not party_account_currency:
2044 party_type, party = self.get_party()
2045
2046 if party_type and party:
2047 party_account_currency = get_party_account_currency(party_type, party, self.company)
2048
Nabin Hait0551f7b2017-11-21 19:58:16 +05302049 if self.get("payment_schedule"):
2050 total = 0
Saqib Ansarid552fe62021-04-23 14:46:52 +05302051 base_total = 0
Nabin Hait0551f7b2017-11-21 19:58:16 +05302052 for d in self.get("payment_schedule"):
Deepesh Garg9c170522021-10-25 20:06:24 +05302053 total += flt(d.payment_amount, d.precision("payment_amount"))
2054 base_total += flt(d.base_payment_amount, d.precision("base_payment_amount"))
tunde43870aa2017-08-18 11:59:30 +01002055
Saqib Ansarid552fe62021-04-23 14:46:52 +05302056 base_grand_total = self.get("base_rounded_total") or self.base_grand_total
2057 grand_total = self.get("rounded_total") or self.grand_total
Rohit Waghchaure4a267b92019-05-09 19:50:00 +05302058
Nabin Haite591c852017-12-21 11:46:30 +05302059 if self.doctype in ("Sales Invoice", "Purchase Invoice"):
Saqib Ansarid552fe62021-04-23 14:46:52 +05302060 base_grand_total = base_grand_total - flt(self.base_write_off_amount)
Nabin Haite591c852017-12-21 11:46:30 +05302061 grand_total = grand_total - flt(self.write_off_amount)
Saqib Ansarid552fe62021-04-23 14:46:52 +05302062
2063 if self.get("total_advance"):
2064 if party_account_currency == self.company_currency:
2065 base_grand_total -= self.get("total_advance")
Ankush Menat494bd9e2022-03-28 18:52:46 +05302066 grand_total = flt(
2067 base_grand_total / self.get("conversion_rate"), self.precision("grand_total")
2068 )
Saqib Ansarid552fe62021-04-23 14:46:52 +05302069 else:
2070 grand_total -= self.get("total_advance")
Ankush Menat494bd9e2022-03-28 18:52:46 +05302071 base_grand_total = flt(
2072 grand_total * self.get("conversion_rate"), self.precision("base_grand_total")
2073 )
Deepesh Garg9c170522021-10-25 20:06:24 +05302074
Ankush Menat494bd9e2022-03-28 18:52:46 +05302075 if (
2076 flt(total, self.precision("grand_total")) - flt(grand_total, self.precision("grand_total"))
2077 > 0.1
2078 or flt(base_total, self.precision("base_grand_total"))
2079 - flt(base_grand_total, self.precision("base_grand_total"))
2080 > 0.1
2081 ):
2082 frappe.throw(
2083 _("Total Payment Amount in Payment Schedule must be equal to Grand / Rounded Total")
2084 )
tunde43870aa2017-08-18 11:59:30 +01002085
Nabin Hait877e1bb2017-11-17 12:27:43 +05302086 def is_rounded_total_disabled(self):
2087 if self.meta.get_field("disable_rounded_total"):
2088 return self.disable_rounded_total
2089 else:
2090 return frappe.db.get_single_value("Global Defaults", "disable_rounded_total")
2091
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05302092 def set_inter_company_account(self):
2093 """
Ankush Menat494bd9e2022-03-28 18:52:46 +05302094 Set intercompany account for inter warehouse transactions
2095 This account will be used in case billing company and internal customer's
2096 representation company is same
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05302097 """
2098
2099 if self.is_internal_transfer() and not self.unrealized_profit_loss_account:
Daizy Modi4efc9472022-11-07 09:21:03 +05302100 unrealized_profit_loss_account = frappe.get_cached_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +05302101 "Company", self.company, "unrealized_profit_loss_account"
2102 )
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05302103
2104 if not unrealized_profit_loss_account:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302105 msg = _(
2106 "Please select Unrealized Profit / Loss account or add default Unrealized Profit / Loss account account for company {0}"
2107 ).format(frappe.bold(self.company))
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05302108 frappe.throw(msg)
2109
2110 self.unrealized_profit_loss_account = unrealized_profit_loss_account
2111
2112 def is_internal_transfer(self):
2113 """
Ankush Menat494bd9e2022-03-28 18:52:46 +05302114 It will an internal transfer if its an internal customer and representation
2115 company is same as billing company
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05302116 """
Ankush Menat494bd9e2022-03-28 18:52:46 +05302117 if self.doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
2118 internal_party_field = "is_internal_customer"
2119 elif self.doctype in ("Purchase Invoice", "Purchase Receipt", "Purchase Order"):
2120 internal_party_field = "is_internal_supplier"
Ankush Menat3714e362022-05-16 18:09:14 +05302121 else:
2122 return False
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05302123
2124 if self.get(internal_party_field) and (self.represents_company == self.company):
2125 return True
2126
2127 return False
2128
Saqib Ansari977b09b2021-08-19 17:57:30 +05302129 def process_common_party_accounting(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302130 is_invoice = self.doctype in ["Sales Invoice", "Purchase Invoice"]
Saqib Ansari977b09b2021-08-19 17:57:30 +05302131 if not is_invoice:
2132 return
2133
Ankush Menat494bd9e2022-03-28 18:52:46 +05302134 if frappe.db.get_single_value("Accounts Settings", "enable_common_party_accounting"):
Saqib Ansari977b09b2021-08-19 17:57:30 +05302135 party_link = self.get_common_party_link()
2136 if party_link and self.outstanding_amount:
2137 self.create_advance_and_reconcile(party_link)
2138
2139 def get_common_party_link(self):
2140 party_type, party = self.get_party()
Saqib Ansari72543682021-08-25 20:15:23 +05302141 return frappe.db.get_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +05302142 doctype="Party Link",
2143 filters={"secondary_role": party_type, "secondary_party": party},
2144 fieldname=["primary_role", "primary_party"],
2145 as_dict=True,
Saqib Ansari72543682021-08-25 20:15:23 +05302146 )
Saqib Ansari977b09b2021-08-19 17:57:30 +05302147
2148 def create_advance_and_reconcile(self, party_link):
2149 secondary_party_type, secondary_party = self.get_party()
2150 primary_party_type, primary_party = party_link.primary_role, party_link.primary_party
2151
2152 primary_account = get_party_account(primary_party_type, primary_party, self.company)
2153 secondary_account = get_party_account(secondary_party_type, secondary_party, self.company)
2154
Ankush Menat494bd9e2022-03-28 18:52:46 +05302155 jv = frappe.new_doc("Journal Entry")
2156 jv.voucher_type = "Journal Entry"
Saqib Ansari977b09b2021-08-19 17:57:30 +05302157 jv.posting_date = self.posting_date
2158 jv.company = self.company
Ankush Menat494bd9e2022-03-28 18:52:46 +05302159 jv.remark = "Adjustment for {} {}".format(self.doctype, self.name)
Saqib Ansari977b09b2021-08-19 17:57:30 +05302160
2161 reconcilation_entry = frappe._dict()
2162 advance_entry = frappe._dict()
Saqib Ansari977b09b2021-08-19 17:57:30 +05302163
2164 reconcilation_entry.account = secondary_account
2165 reconcilation_entry.party_type = secondary_party_type
2166 reconcilation_entry.party = secondary_party
2167 reconcilation_entry.reference_type = self.doctype
2168 reconcilation_entry.reference_name = self.name
Deepesh Gargf88431a2023-04-25 20:54:22 +05302169 reconcilation_entry.cost_center = self.cost_center or erpnext.get_default_cost_center(
2170 self.company
2171 )
Saqib Ansari977b09b2021-08-19 17:57:30 +05302172
2173 advance_entry.account = primary_account
2174 advance_entry.party_type = primary_party_type
2175 advance_entry.party = primary_party
Deepesh Gargf88431a2023-04-25 20:54:22 +05302176 advance_entry.cost_center = self.cost_center or erpnext.get_default_cost_center(self.company)
Ankush Menat494bd9e2022-03-28 18:52:46 +05302177 advance_entry.is_advance = "Yes"
Saqib Ansari977b09b2021-08-19 17:57:30 +05302178
Ankush Menat494bd9e2022-03-28 18:52:46 +05302179 if self.doctype == "Sales Invoice":
Saqib Ansari977b09b2021-08-19 17:57:30 +05302180 reconcilation_entry.credit_in_account_currency = self.outstanding_amount
2181 advance_entry.debit_in_account_currency = self.outstanding_amount
2182 else:
2183 advance_entry.credit_in_account_currency = self.outstanding_amount
2184 reconcilation_entry.debit_in_account_currency = self.outstanding_amount
2185
Ankush Menat494bd9e2022-03-28 18:52:46 +05302186 jv.append("accounts", reconcilation_entry)
2187 jv.append("accounts", advance_entry)
Saqib Ansari977b09b2021-08-19 17:57:30 +05302188
2189 jv.save()
2190 jv.submit()
2191
Deepesh Gargd05d1532022-06-14 12:50:49 +05302192 def check_conversion_rate(self):
2193 default_currency = erpnext.get_company_currency(self.company)
2194 if not default_currency:
2195 throw(_("Please enter default currency in Company Master"))
2196 if (
2197 (self.currency == default_currency and flt(self.conversion_rate) != 1.00)
2198 or not self.conversion_rate
2199 or (self.currency != default_currency and flt(self.conversion_rate) == 1.00)
2200 ):
2201 throw(_("Conversion rate cannot be 0 or 1"))
2202
Saif Ur Rehman7a5d75b2021-09-13 23:01:52 +05002203 def check_finance_books(self, item, asset):
Nabin Haitfefe9502022-09-09 14:40:36 +05302204 if (
2205 len(asset.finance_books) > 1
2206 and not item.get("finance_book")
2207 and not self.get("finance_book")
2208 and asset.finance_books[0].finance_book
2209 ):
2210 frappe.throw(
2211 _("Select finance book for the item {0} at row {1}").format(item.item_code, item.idx)
2212 )
Saif Ur Rehman7a5d75b2021-09-13 23:01:52 +05002213
Gursheen Anand68effd92023-09-21 17:28:07 +05302214 def check_if_fields_updated(self, fields_to_check, child_tables):
2215 # Check if any field affecting accounting entry is altered
2216 doc_before_update = self.get_doc_before_save()
2217 accounting_dimensions = get_accounting_dimensions() + ["cost_center", "project"]
2218
2219 # Check if opening entry check updated
2220 needs_repost = doc_before_update.get("is_opening") != self.is_opening
2221
2222 if not needs_repost:
2223 # Parent Level Accounts excluding party account
2224 fields_to_check += accounting_dimensions
2225 for field in fields_to_check:
2226 if doc_before_update.get(field) != self.get(field):
2227 needs_repost = 1
2228 break
2229
2230 if not needs_repost:
2231 # Check for child tables
2232 for table in child_tables:
2233 needs_repost = check_if_child_table_updated(
2234 doc_before_update.get(table), self.get(table), child_tables[table]
2235 )
2236 if needs_repost:
2237 break
2238
2239 return needs_repost
2240
2241 @frappe.whitelist()
2242 def repost_accounting_entries(self):
2243 if self.repost_required:
Gursheen Anand7ebf0832023-09-23 19:13:33 +05302244 repost_ledger = frappe.new_doc("Repost Accounting Ledger")
2245 repost_ledger.company = self.company
2246 repost_ledger.append("vouchers", {"voucher_type": self.doctype, "voucher_no": self.name})
2247 repost_ledger.insert()
2248 repost_ledger.submit()
Gursheen Anand68effd92023-09-21 17:28:07 +05302249 self.db_set("repost_required", 0)
2250 else:
2251 frappe.throw(_("No updates pending for reposting"))
2252
Ankush Menat494bd9e2022-03-28 18:52:46 +05302253
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05302254@frappe.whitelist()
Rushabh Mehtaf56d73c2013-10-10 16:35:09 +05302255def get_tax_rate(account_head):
Daizy Modi4efc9472022-11-07 09:21:03 +05302256 return frappe.get_cached_value(
2257 "Account", account_head, ["tax_rate", "account_name"], as_dict=True
2258 )
Rushabh Mehtaa33d4682015-06-01 17:15:42 +05302259
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002260
Nabin Haitffc7f3f2015-05-12 15:07:02 +05302261@frappe.whitelist()
Nabin Haita2426fc2018-01-15 17:45:46 +05302262def get_default_taxes_and_charges(master_doctype, tax_template=None, company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302263 if not company:
2264 return {}
rohitwaghchaure505661b2017-12-11 14:52:28 +05302265
Nabin Haita2426fc2018-01-15 17:45:46 +05302266 if tax_template and company:
Daizy Modi4efc9472022-11-07 09:21:03 +05302267 tax_template_company = frappe.get_cached_value(master_doctype, tax_template, "company")
Nabin Haita2426fc2018-01-15 17:45:46 +05302268 if tax_template_company == company:
2269 return
2270
2271 default_tax = frappe.db.get_value(master_doctype, {"is_default": 1, "company": company})
rohitwaghchaure505661b2017-12-11 14:52:28 +05302272
Rushabh Mehta98aa5812017-11-14 09:32:32 +05302273 return {
Ankush Menat494bd9e2022-03-28 18:52:46 +05302274 "taxes_and_charges": default_tax,
2275 "taxes": get_taxes_and_charges(master_doctype, default_tax),
Rushabh Mehta98aa5812017-11-14 09:32:32 +05302276 }
Nabin Hait6b039142014-05-02 15:45:10 +05302277
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002278
Nabin Hait6b039142014-05-02 15:45:10 +05302279@frappe.whitelist()
Nabin Haitffc7f3f2015-05-12 15:07:02 +05302280def get_taxes_and_charges(master_doctype, master_name):
Nabin Hait1fe50122015-05-16 12:14:39 +05302281 if not master_name:
2282 return
Ankush Menat77dcdff2022-06-01 22:01:07 +05302283 from frappe.model import child_table_fields, default_fields
Ankush Menat494bd9e2022-03-28 18:52:46 +05302284
Nabin Hait6b039142014-05-02 15:45:10 +05302285 tax_master = frappe.get_doc(master_doctype, master_name)
2286
2287 taxes_and_charges = []
Nabin Haitffc7f3f2015-05-12 15:07:02 +05302288 for i, tax in enumerate(tax_master.get("taxes")):
Nabin Hait6b039142014-05-02 15:45:10 +05302289 tax = tax.as_dict()
2290
Ankush Menat77dcdff2022-06-01 22:01:07 +05302291 for fieldname in default_fields + child_table_fields:
Nabin Hait6b039142014-05-02 15:45:10 +05302292 if fieldname in tax:
2293 del tax[fieldname]
2294
2295 taxes_and_charges.append(tax)
2296
2297 return taxes_and_charges
Rushabh Mehta66e08e32014-09-29 12:17:03 +05302298
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002299
Rushabh Mehta66e08e32014-09-29 12:17:03 +05302300def validate_conversion_rate(currency, conversion_rate, conversion_rate_label, company):
2301 """common validation for currency and price list currency"""
2302
Ankush Menat494bd9e2022-03-28 18:52:46 +05302303 company_currency = frappe.get_cached_value("Company", company, "default_currency")
Rushabh Mehta66e08e32014-09-29 12:17:03 +05302304
2305 if not conversion_rate:
Saqib60212ff2020-10-26 11:17:04 +05302306 throw(
Ankush Menat494bd9e2022-03-28 18:52:46 +05302307 _("{0} is mandatory. Maybe Currency Exchange record is not created for {1} to {2}.").format(
2308 conversion_rate_label, currency, company_currency
2309 )
Saqib60212ff2020-10-26 11:17:04 +05302310 )
Nabin Hait613d0812015-02-23 11:58:15 +05302311
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002312
Nabin Hait613d0812015-02-23 11:58:15 +05302313def validate_taxes_and_charges(tax):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302314 if tax.charge_type in ["Actual", "On Net Total", "On Paid Amount"] and tax.row_id:
2315 frappe.throw(
2316 _("Can refer row only if the charge type is 'On Previous Row Amount' or 'Previous Row Total'")
2317 )
2318 elif tax.charge_type in ["On Previous Row Amount", "On Previous Row Total"]:
Nabin Hait613d0812015-02-23 11:58:15 +05302319 if cint(tax.idx) == 1:
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002320 frappe.throw(
Ankush Menat494bd9e2022-03-28 18:52:46 +05302321 _(
2322 "Cannot select charge type as 'On Previous Row Amount' or 'On Previous Row Total' for first row"
2323 )
2324 )
Nabin Hait613d0812015-02-23 11:58:15 +05302325 elif not tax.row_id:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302326 frappe.throw(
2327 _("Please specify a valid Row ID for row {0} in table {1}").format(tax.idx, _(tax.doctype))
2328 )
Nabin Hait613d0812015-02-23 11:58:15 +05302329 elif tax.row_id and cint(tax.row_id) >= cint(tax.idx):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302330 frappe.throw(
2331 _("Cannot refer row number greater than or equal to current row number for this Charge type")
2332 )
Nabin Hait613d0812015-02-23 11:58:15 +05302333
Rushabh Mehta2a21bc92015-02-25 15:08:42 +05302334 if tax.charge_type == "Actual":
Nabin Haitbc6c3602015-02-27 23:40:56 +05302335 tax.rate = None
Rushabh Mehta2a21bc92015-02-25 15:08:42 +05302336
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002337
Ankush Menat494bd9e2022-03-28 18:52:46 +05302338def validate_account_head(idx, account, company, context=""):
2339 account_company = frappe.get_cached_value("Account", account, "company")
Anuja Pawar0e337be2021-08-10 17:26:35 +05302340
Deepesh Garg5a2b5712022-02-18 20:05:49 +05302341 if account_company != company:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302342 frappe.throw(
2343 _("Row {0}: {3} Account {1} does not belong to Company {2}").format(
2344 idx, frappe.bold(account), frappe.bold(company), context
2345 ),
2346 title=_("Invalid Account"),
2347 )
Anuja Pawar0e337be2021-08-10 17:26:35 +05302348
2349
2350def validate_cost_center(tax, doc):
2351 if not tax.cost_center:
2352 return
2353
Ankush Menat494bd9e2022-03-28 18:52:46 +05302354 company = frappe.get_cached_value("Cost Center", tax.cost_center, "company")
Anuja Pawar0e337be2021-08-10 17:26:35 +05302355
2356 if company != doc.company:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302357 frappe.throw(
2358 _("Row {0}: Cost Center {1} does not belong to Company {2}").format(
2359 tax.idx, frappe.bold(tax.cost_center), frappe.bold(doc.company)
2360 ),
2361 title=_("Invalid Cost Center"),
2362 )
Anuja Pawar0e337be2021-08-10 17:26:35 +05302363
2364
Nabin Hait613d0812015-02-23 11:58:15 +05302365def validate_inclusive_tax(tax, doc):
2366 def _on_previous_row_error(row_range):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302367 throw(
2368 _("To include tax in row {0} in Item rate, taxes in rows {1} must also be included").format(
2369 tax.idx, row_range
2370 )
2371 )
Nabin Hait613d0812015-02-23 11:58:15 +05302372
2373 if cint(getattr(tax, "included_in_print_rate", None)):
2374 if tax.charge_type == "Actual":
2375 # inclusive tax cannot be of type Actual
Ankush Menat494bd9e2022-03-28 18:52:46 +05302376 throw(
2377 _("Charge of type 'Actual' in row {0} cannot be included in Item Rate or Paid Amount").format(
2378 tax.idx
2379 )
2380 )
2381 elif tax.charge_type == "On Previous Row Amount" and not cint(
2382 doc.get("taxes")[cint(tax.row_id) - 1].included_in_print_rate
2383 ):
Nabin Hait613d0812015-02-23 11:58:15 +05302384 # referred row should also be inclusive
2385 _on_previous_row_error(tax.row_id)
Ankush Menat494bd9e2022-03-28 18:52:46 +05302386 elif tax.charge_type == "On Previous Row Total" and not all(
2387 [cint(t.included_in_print_rate) for t in doc.get("taxes")[: cint(tax.row_id) - 1]]
2388 ):
Deepesh Garg5ef9a622021-06-14 14:34:44 +05302389 # all rows about the referred tax should be inclusive
Nabin Hait613d0812015-02-23 11:58:15 +05302390 _on_previous_row_error("1 - %d" % (tax.row_id,))
Nabin Hait93b3a372015-02-24 17:08:34 +05302391 elif tax.get("category") == "Valuation":
Nabin Hait19ea7212020-08-11 20:34:57 +05302392 frappe.throw(_("Valuation type charges can not be marked as Inclusive"))
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05302393
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05302394
Ankush Menat494bd9e2022-03-28 18:52:46 +05302395def set_balance_in_account_currency(
2396 gl_dict, account_currency=None, conversion_rate=None, company_currency=None
2397):
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002398 if (not conversion_rate) and (account_currency != company_currency):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302399 frappe.throw(
2400 _("Account: {0} with currency: {1} can not be selected").format(
2401 gl_dict.account, account_currency
2402 )
2403 )
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002404
Ankush Menat494bd9e2022-03-28 18:52:46 +05302405 gl_dict["account_currency"] = (
2406 company_currency if account_currency == company_currency else account_currency
2407 )
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05302408
2409 # set debit/credit in account currency if not provided
2410 if flt(gl_dict.debit) and not flt(gl_dict.debit_in_account_currency):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302411 gl_dict.debit_in_account_currency = (
2412 gl_dict.debit
2413 if account_currency == company_currency
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05302414 else flt(gl_dict.debit / conversion_rate, 2)
Ankush Menat494bd9e2022-03-28 18:52:46 +05302415 )
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05302416
2417 if flt(gl_dict.credit) and not flt(gl_dict.credit_in_account_currency):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302418 gl_dict.credit_in_account_currency = (
2419 gl_dict.credit
2420 if account_currency == company_currency
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05302421 else flt(gl_dict.credit / conversion_rate, 2)
Ankush Menat494bd9e2022-03-28 18:52:46 +05302422 )
Nabin Hait1991c7b2016-06-27 20:09:05 +05302423
2424
Ankush Menat494bd9e2022-03-28 18:52:46 +05302425def get_advance_journal_entries(
2426 party_type,
2427 party,
2428 party_account,
2429 amount_field,
2430 order_doctype,
2431 order_list,
2432 include_unallocated=True,
2433):
Gursheen Anand4ee16372023-06-08 13:15:23 +05302434 journal_entry = frappe.qb.DocType("Journal Entry")
2435 journal_acc = frappe.qb.DocType("Journal Entry Account")
2436 q = (
2437 frappe.qb.from_(journal_entry)
Gursheen Anand74619262023-06-02 17:13:51 +05302438 .inner_join(journal_acc)
2439 .on(journal_entry.name == journal_acc.parent)
2440 .select(
Gursheen Anand4ee16372023-06-08 13:15:23 +05302441 ConstantColumn("Journal Entry").as_("reference_type"),
2442 (journal_entry.name).as_("reference_name"),
2443 (journal_entry.remark).as_("remarks"),
Deepesh Garg3aead052023-06-22 11:41:43 +05302444 (journal_acc[amount_field]).as_("amount"),
Gursheen Anand4ee16372023-06-08 13:15:23 +05302445 (journal_acc.name).as_("reference_row"),
2446 (journal_acc.reference_name).as_("against_order"),
2447 (journal_acc.exchange_rate),
Gursheen Anand74619262023-06-02 17:13:51 +05302448 )
Gursheen Anand4ee16372023-06-08 13:15:23 +05302449 .where(
2450 journal_acc.account.isin(party_account)
2451 & (journal_acc.party_type == party_type)
2452 & (journal_acc.party == party)
2453 & (journal_acc.is_advance == "Yes")
2454 & (journal_entry.docstatus == 1)
2455 )
2456 )
Gursheen Anand74619262023-06-02 17:13:51 +05302457 if party_type == "Customer":
2458 q = q.where(journal_acc.credit_in_account_currency > 0)
Nabin Hait1991c7b2016-06-27 20:09:05 +05302459
Gursheen Anand4ee16372023-06-08 13:15:23 +05302460 else:
2461 q = q.where(journal_acc.debit_in_account_currency > 0)
2462
Deepesh Garg3aead052023-06-22 11:41:43 +05302463 if include_unallocated:
2464 q = q.where((journal_acc.reference_name.isnull()) | (journal_acc.reference_name == ""))
2465
Nabin Hait1991c7b2016-06-27 20:09:05 +05302466 if order_list:
Deepesh Garg3aead052023-06-22 11:41:43 +05302467 q = q.where(
Deepesh Garg6d121ae2023-06-22 13:03:09 +05302468 (journal_acc.reference_type == order_doctype) & ((journal_acc.reference_type).isin(order_list))
Deepesh Garg3aead052023-06-22 11:41:43 +05302469 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05302470
Gursheen Anand74619262023-06-02 17:13:51 +05302471 q = q.orderby(journal_entry.posting_date)
Rushabh Mehta66958302017-01-16 16:57:53 +05302472
Gursheen Anand74619262023-06-02 17:13:51 +05302473 journal_entries = q.run(as_dict=True)
Nabin Hait1991c7b2016-06-27 20:09:05 +05302474 return list(journal_entries)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05302475
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002476
Smit Vora3e282bf2023-09-19 20:47:21 +05302477@erpnext.allow_regional
2478def get_advance_payment_entries_for_regional(*args, **kwargs):
2479 return get_advance_payment_entries(*args, **kwargs)
2480
2481
Ankush Menat494bd9e2022-03-28 18:52:46 +05302482def get_advance_payment_entries(
2483 party_type,
2484 party,
2485 party_account,
2486 order_doctype,
2487 order_list=None,
2488 include_unallocated=True,
2489 against_all_orders=False,
2490 limit=None,
2491 condition=None,
2492):
Gursheen Anand74619262023-06-02 17:13:51 +05302493
Deepesh Garg92f845c2023-06-21 12:21:19 +05302494 payment_entries = []
2495 payment_entry = frappe.qb.DocType("Payment Entry")
Gursheen Anand74619262023-06-02 17:13:51 +05302496
Deepesh Garg92f845c2023-06-21 12:21:19 +05302497 if order_list or against_all_orders:
2498 q = get_common_query(
2499 party_type,
2500 party,
2501 party_account,
2502 limit,
2503 condition,
2504 )
2505 payment_ref = frappe.qb.DocType("Payment Entry Reference")
Gursheen Anand74619262023-06-02 17:13:51 +05302506
Deepesh Garg92f845c2023-06-21 12:21:19 +05302507 q = q.inner_join(payment_ref).on(payment_entry.name == payment_ref.parent)
2508 q = q.select(
2509 (payment_ref.allocated_amount).as_("amount"),
2510 (payment_ref.name).as_("reference_row"),
2511 (payment_ref.reference_name).as_("against_order"),
Deepesh Garg92f845c2023-06-21 12:21:19 +05302512 )
2513
Deepesh Garg3aead052023-06-22 11:41:43 +05302514 q = q.where(payment_ref.reference_doctype == order_doctype)
Deepesh Garg92f845c2023-06-21 12:21:19 +05302515 if order_list:
2516 q = q.where(payment_ref.reference_name.isin(order_list))
2517
2518 allocated = list(q.run(as_dict=True))
2519 payment_entries += allocated
Deepesh Garg92f845c2023-06-21 12:21:19 +05302520 if include_unallocated:
2521 q = get_common_query(
2522 party_type,
2523 party,
2524 party_account,
2525 limit,
2526 condition,
2527 )
2528 q = q.select((payment_entry.unallocated_amount).as_("amount"))
2529 q = q.where(payment_entry.unallocated_amount > 0)
2530
2531 unallocated = list(q.run(as_dict=True))
2532 payment_entries += unallocated
Deepesh Garg92f845c2023-06-21 12:21:19 +05302533 return payment_entries
Gursheen Anand74619262023-06-02 17:13:51 +05302534
Saqiba20999c2021-07-12 14:33:23 +05302535
Deepesh Garg92f845c2023-06-21 12:21:19 +05302536def get_common_query(
Gursheen Anand4ee16372023-06-08 13:15:23 +05302537 party_type,
2538 party,
2539 party_account,
Gursheen Anand4ee16372023-06-08 13:15:23 +05302540 limit,
2541 condition,
2542):
RitvikSardanad2f03c82023-09-05 12:00:54 +05302543 account_type = frappe.db.get_value("Party Type", party_type, "account_type")
2544 payment_type = "Receive" if account_type == "Receivable" else "Pay"
Gursheen Anand4ee16372023-06-08 13:15:23 +05302545 payment_entry = frappe.qb.DocType("Payment Entry")
Gursheen Anand4ee16372023-06-08 13:15:23 +05302546
2547 q = (
2548 frappe.qb.from_(payment_entry)
Gursheen Anand74619262023-06-02 17:13:51 +05302549 .select(
Gursheen Anand4ee16372023-06-08 13:15:23 +05302550 ConstantColumn("Payment Entry").as_("reference_type"),
2551 (payment_entry.name).as_("reference_name"),
Gursheen Anand74619262023-06-02 17:13:51 +05302552 payment_entry.posting_date,
Gursheen Anand4ee16372023-06-08 13:15:23 +05302553 (payment_entry.remarks).as_("remarks"),
Ankush Menat494bd9e2022-03-28 18:52:46 +05302554 )
Gursheen Anand74619262023-06-02 17:13:51 +05302555 .where(payment_entry.payment_type == payment_type)
2556 .where(payment_entry.party_type == party_type)
2557 .where(payment_entry.party == party)
2558 .where(payment_entry.docstatus == 1)
2559 )
Gursheen Anand4ee16372023-06-08 13:15:23 +05302560
RitvikSardanad2f03c82023-09-05 12:00:54 +05302561 if payment_type == "Receive":
Deepesh Gargb64ebc62023-06-21 17:49:45 +05302562 q = q.select((payment_entry.paid_from_account_currency).as_("currency"))
Gursheen Anand4ee16372023-06-08 13:15:23 +05302563 q = q.select(payment_entry.paid_from)
2564 q = q.where(payment_entry.paid_from.isin(party_account))
Gursheen Anand74619262023-06-02 17:13:51 +05302565 else:
Deepesh Gargb64ebc62023-06-21 17:49:45 +05302566 q = q.select((payment_entry.paid_to_account_currency).as_("currency"))
Gursheen Anand74619262023-06-02 17:13:51 +05302567 q = q.select(payment_entry.paid_to)
Gursheen Anand4ee16372023-06-08 13:15:23 +05302568 q = q.where(payment_entry.paid_to.isin(party_account))
Gursheen Anand74619262023-06-02 17:13:51 +05302569
2570 if payment_type == "Receive":
Deepesh Garg92f845c2023-06-21 12:21:19 +05302571 q = q.select((payment_entry.source_exchange_rate).as_("exchange_rate"))
Gursheen Anand4ee16372023-06-08 13:15:23 +05302572 else:
Deepesh Garg92f845c2023-06-21 12:21:19 +05302573 q = q.select((payment_entry.target_exchange_rate).as_("exchange_rate"))
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05302574
Deepesh Garg92f845c2023-06-21 12:21:19 +05302575 if condition:
ruthra kumar86bac2c2023-07-04 09:02:05 +05302576 if condition.get("name", None):
2577 q = q.where(payment_entry.name.like(f"%{condition.get('name')}%"))
2578
Deepesh Garg92f845c2023-06-21 12:21:19 +05302579 q = q.where(payment_entry.company == condition["company"])
2580 q = (
2581 q.where(payment_entry.posting_date >= condition["from_payment_date"])
2582 if condition.get("from_payment_date")
2583 else q
Gursheen Anand74619262023-06-02 17:13:51 +05302584 )
Deepesh Garg92f845c2023-06-21 12:21:19 +05302585 q = (
2586 q.where(payment_entry.posting_date <= condition["to_payment_date"])
2587 if condition.get("to_payment_date")
2588 else q
2589 )
2590 if condition.get("get_payments") == True:
2591 q = (
2592 q.where(payment_entry.cost_center == condition["cost_center"])
2593 if condition.get("cost_center")
2594 else q
2595 )
2596 q = (
2597 q.where(payment_entry.unallocated_amount >= condition["minimum_payment_amount"])
2598 if condition.get("minimum_payment_amount")
2599 else q
2600 )
2601 q = (
2602 q.where(payment_entry.unallocated_amount <= condition["maximum_payment_amount"])
2603 if condition.get("maximum_payment_amount")
2604 else q
2605 )
2606 else:
2607 q = (
2608 q.where(payment_entry.total_debit >= condition["minimum_payment_amount"])
2609 if condition.get("minimum_payment_amount")
2610 else q
2611 )
2612 q = (
2613 q.where(payment_entry.total_debit <= condition["maximum_payment_amount"])
2614 if condition.get("maximum_payment_amount")
2615 else q
2616 )
Gursheen Anand74619262023-06-02 17:13:51 +05302617
2618 q = q.orderby(payment_entry.posting_date)
2619 q = q.limit(limit) if limit else q
Deepesh Garg92f845c2023-06-21 12:21:19 +05302620
Gursheen Anand74619262023-06-02 17:13:51 +05302621 return q
Rohit Waghchaure2f1db572016-11-08 12:39:33 +05302622
Ankush Menat494bd9e2022-03-28 18:52:46 +05302623
Rohit Waghchaure2f1db572016-11-08 12:39:33 +05302624def update_invoice_status():
Sagar Vorac8b9a552021-09-22 12:11:35 +05302625 """Updates status as Overdue for applicable invoices. Runs daily."""
Sagar Vora8d9d0982021-10-20 19:15:35 +05302626 today = getdate()
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302627 payment_schedule = frappe.qb.DocType("Payment Schedule")
Sagar Vorac8b9a552021-09-22 12:11:35 +05302628 for doctype in ("Sales Invoice", "Purchase Invoice"):
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302629 invoice = frappe.qb.DocType(doctype)
2630
2631 consider_base_amount = invoice.party_account_currency != invoice.currency
2632 payment_amount = (
2633 frappe.qb.terms.Case()
2634 .when(consider_base_amount, payment_schedule.base_payment_amount)
2635 .else_(payment_schedule.payment_amount)
Sagar Vora8d9d0982021-10-20 19:15:35 +05302636 )
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002637
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302638 payable_amount = (
2639 frappe.qb.from_(payment_schedule)
2640 .select(Sum(payment_amount))
Ankush Menat494bd9e2022-03-28 18:52:46 +05302641 .where((payment_schedule.parent == invoice.name) & (payment_schedule.due_date < today))
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302642 )
2643
2644 total = (
2645 frappe.qb.terms.Case()
2646 .when(invoice.disable_rounded_total, invoice.grand_total)
2647 .else_(invoice.rounded_total)
2648 )
2649
2650 base_total = (
2651 frappe.qb.terms.Case()
2652 .when(invoice.disable_rounded_total, invoice.base_grand_total)
2653 .else_(invoice.base_rounded_total)
2654 )
2655
Ankush Menat494bd9e2022-03-28 18:52:46 +05302656 total_amount = frappe.qb.terms.Case().when(consider_base_amount, base_total).else_(total)
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302657
2658 is_overdue = total_amount - invoice.outstanding_amount < payable_amount
2659
2660 conditions = (
2661 (invoice.docstatus == 1)
2662 & (invoice.outstanding_amount > 0)
Ankush Menat494bd9e2022-03-28 18:52:46 +05302663 & (invoice.status.like("Unpaid%") | invoice.status.like("Partly Paid%"))
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302664 & (
Pruthvi Patel16a90d32021-12-20 13:24:19 +05302665 ((invoice.is_pos & invoice.due_date < today) | is_overdue)
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302666 if doctype == "Sales Invoice"
2667 else is_overdue
2668 )
2669 )
2670
Pruthvi Patel0799f372021-11-12 12:56:29 +05302671 status = (
2672 frappe.qb.terms.Case()
2673 .when(invoice.status.like("%Discounted"), "Overdue and Discounted")
2674 .else_("Overdue")
2675 )
2676
2677 frappe.qb.update(invoice).set("status", status).where(conditions).run()
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302678
2679
Nabin Hait92759692017-08-15 08:23:51 +05302680@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +05302681def get_payment_terms(
2682 terms_template, posting_date=None, grand_total=None, base_grand_total=None, bill_date=None
2683):
Nabin Hait92759692017-08-15 08:23:51 +05302684 if not terms_template:
2685 return
2686
2687 terms_doc = frappe.get_doc("Payment Terms Template", terms_template)
2688
2689 schedule = []
tundefb144302017-08-19 15:01:40 +01002690 for d in terms_doc.get("terms"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302691 term_details = get_payment_term_details(
2692 d, posting_date, grand_total, base_grand_total, bill_date
2693 )
Nabin Hait92759692017-08-15 08:23:51 +05302694 schedule.append(term_details)
2695
2696 return schedule
2697
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002698
Nabin Hait92759692017-08-15 08:23:51 +05302699@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +05302700def get_payment_term_details(
2701 term, posting_date=None, grand_total=None, base_grand_total=None, bill_date=None
2702):
Nabin Hait92759692017-08-15 08:23:51 +05302703 term_details = frappe._dict()
Ankush Menat8fe5feb2021-11-04 19:48:32 +05302704 if isinstance(term, str):
Nabin Hait92759692017-08-15 08:23:51 +05302705 term = frappe.get_doc("Payment Term", term)
2706 else:
2707 term_details.payment_term = term.payment_term
2708 term_details.description = term.description
2709 term_details.invoice_portion = term.invoice_portion
Rohit Waghchaure52bf56d2017-11-27 11:43:52 +05302710 term_details.payment_amount = flt(term.invoice_portion) * flt(grand_total) / 100
Saqib Ansarid552fe62021-04-23 14:46:52 +05302711 term_details.base_payment_amount = flt(term.invoice_portion) * flt(base_grand_total) / 100
Saqib0586b7d2021-03-31 15:03:53 +05302712 term_details.discount_type = term.discount_type
2713 term_details.discount = term.discount
Saqib0586b7d2021-03-31 15:03:53 +05302714 term_details.outstanding = term_details.payment_amount
2715 term_details.mode_of_payment = term.mode_of_payment
2716
Shreya Shah3a9eec22018-02-16 13:05:21 +05302717 if bill_date:
2718 term_details.due_date = get_due_date(term, bill_date)
Saqib0586b7d2021-03-31 15:03:53 +05302719 term_details.discount_date = get_discount_date(term, bill_date)
Shreya Shah3a9eec22018-02-16 13:05:21 +05302720 elif posting_date:
2721 term_details.due_date = get_due_date(term, posting_date)
Saqib0586b7d2021-03-31 15:03:53 +05302722 term_details.discount_date = get_discount_date(term, posting_date)
Shreya Shah3a9eec22018-02-16 13:05:21 +05302723
2724 if getdate(term_details.due_date) < getdate(posting_date):
2725 term_details.due_date = posting_date
2726
Nabin Hait92759692017-08-15 08:23:51 +05302727 return term_details
2728
Ankush Menat494bd9e2022-03-28 18:52:46 +05302729
Shreya Shah3a9eec22018-02-16 13:05:21 +05302730def get_due_date(term, posting_date=None, bill_date=None):
Nabin Hait92759692017-08-15 08:23:51 +05302731 due_date = None
Shreya Shah3a9eec22018-02-16 13:05:21 +05302732 date = bill_date or posting_date
Nabin Hait92759692017-08-15 08:23:51 +05302733 if term.due_date_based_on == "Day(s) after invoice date":
Shreya Shah3a9eec22018-02-16 13:05:21 +05302734 due_date = add_days(date, term.credit_days)
Nabin Hait92759692017-08-15 08:23:51 +05302735 elif term.due_date_based_on == "Day(s) after the end of the invoice month":
Shreya Shah3a9eec22018-02-16 13:05:21 +05302736 due_date = add_days(get_last_day(date), term.credit_days)
Nabin Hait92759692017-08-15 08:23:51 +05302737 elif term.due_date_based_on == "Month(s) after the end of the invoice month":
Deepesh Gargbfb81ef2022-11-30 20:53:41 +05302738 due_date = get_last_day(add_months(date, term.credit_months))
tunde96b8f222017-09-08 15:35:59 +01002739 return due_date
tundebabzyad08d4c2018-05-16 07:01:41 +01002740
Ankush Menat494bd9e2022-03-28 18:52:46 +05302741
Saqib0586b7d2021-03-31 15:03:53 +05302742def get_discount_date(term, posting_date=None, bill_date=None):
2743 discount_validity = None
2744 date = bill_date or posting_date
2745 if term.discount_validity_based_on == "Day(s) after invoice date":
2746 discount_validity = add_days(date, term.discount_validity)
2747 elif term.discount_validity_based_on == "Day(s) after the end of the invoice month":
2748 discount_validity = add_days(get_last_day(date), term.discount_validity)
2749 elif term.discount_validity_based_on == "Month(s) after the end of the invoice month":
Deepesh Gargbfb81ef2022-11-30 20:53:41 +05302750 discount_validity = get_last_day(add_months(date, term.discount_validity))
Saqib0586b7d2021-03-31 15:03:53 +05302751 return discount_validity
tundebabzyad08d4c2018-05-16 07:01:41 +01002752
Ankush Menat494bd9e2022-03-28 18:52:46 +05302753
tundebabzyad08d4c2018-05-16 07:01:41 +01002754def get_supplier_block_status(party_name):
2755 """
2756 Returns a dict containing the values of `on_hold`, `release_date` and `hold_type` of
2757 a `Supplier`
2758 """
Ankush Menat494bd9e2022-03-28 18:52:46 +05302759 supplier = frappe.get_doc("Supplier", party_name)
tundebabzyad08d4c2018-05-16 07:01:41 +01002760 info = {
Ankush Menat494bd9e2022-03-28 18:52:46 +05302761 "on_hold": supplier.on_hold,
2762 "release_date": supplier.release_date,
2763 "hold_type": supplier.hold_type,
tundebabzyad08d4c2018-05-16 07:01:41 +01002764 }
2765 return info
2766
Ankush Menat494bd9e2022-03-28 18:52:46 +05302767
marination698d9832020-08-19 14:59:46 +05302768def set_child_tax_template_and_map(item, child_item, parent_doc):
2769 args = {
Ankush Menat494bd9e2022-03-28 18:52:46 +05302770 "item_code": item.item_code,
2771 "posting_date": parent_doc.transaction_date,
2772 "tax_category": parent_doc.get("tax_category"),
2773 "company": parent_doc.get("company"),
2774 }
marination698d9832020-08-19 14:59:46 +05302775
2776 child_item.item_tax_template = _get_item_tax_template(args, item.taxes)
2777 if child_item.get("item_tax_template"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302778 child_item.item_tax_rate = get_item_tax_map(
2779 parent_doc.get("company"), child_item.item_tax_template, as_json=True
2780 )
2781
marination698d9832020-08-19 14:59:46 +05302782
Afshanb3bbebd2021-08-09 14:39:32 +05302783def add_taxes_from_tax_template(child_item, parent_doc, db_insert=True):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302784 add_taxes_from_item_tax_template = frappe.db.get_single_value(
2785 "Accounts Settings", "add_taxes_from_item_tax_template"
2786 )
Marica3b1be2b2020-10-22 17:04:31 +05302787
2788 if child_item.get("item_tax_rate") and add_taxes_from_item_tax_template:
2789 tax_map = json.loads(child_item.get("item_tax_rate"))
2790 for tax_type in tax_map:
2791 tax_rate = flt(tax_map[tax_type])
Ankush Menat494bd9e2022-03-28 18:52:46 +05302792 taxes = parent_doc.get("taxes") or []
Marica3b1be2b2020-10-22 17:04:31 +05302793 # add new row for tax head only if missing
2794 found = any(tax.account_head == tax_type for tax in taxes)
2795 if not found:
2796 tax_row = parent_doc.append("taxes", {})
Ankush Menat494bd9e2022-03-28 18:52:46 +05302797 tax_row.update(
2798 {
2799 "description": str(tax_type).split(" - ")[0],
2800 "charge_type": "On Net Total",
2801 "account_head": tax_type,
2802 "rate": tax_rate,
2803 }
2804 )
Marica3b1be2b2020-10-22 17:04:31 +05302805 if parent_doc.doctype == "Purchase Order":
Ankush Menat494bd9e2022-03-28 18:52:46 +05302806 tax_row.update({"category": "Total", "add_deduct_tax": "Add"})
Afshanb3bbebd2021-08-09 14:39:32 +05302807 if db_insert:
2808 tax_row.db_insert()
Marica3b1be2b2020-10-22 17:04:31 +05302809
Ankush Menat494bd9e2022-03-28 18:52:46 +05302810
2811def set_order_defaults(
2812 parent_doctype, parent_doctype_name, child_doctype, child_docname, trans_item
2813):
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002814 """
pateljannat637ddff2021-02-09 16:17:30 +05302815 Returns a Sales/Purchase Order Item child item containing the default values
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002816 """
Saqib438e0432020-04-03 10:02:56 +05302817 p_doc = frappe.get_doc(parent_doctype, parent_doctype_name)
Ankush Menat686685b2023-05-31 12:50:14 +05302818 child_item = frappe.new_doc(child_doctype, parent_doc=p_doc, parentfield=child_docname)
Ankush Menat494bd9e2022-03-28 18:52:46 +05302819 item = frappe.get_doc("Item", trans_item.get("item_code"))
marination0673f552021-03-31 01:38:22 +05302820
pateljannat637ddff2021-02-09 16:17:30 +05302821 for field in ("item_code", "item_name", "description", "item_group"):
marination0673f552021-03-31 01:38:22 +05302822 child_item.update({field: item.get(field)})
2823
pateljannat637ddff2021-02-09 16:17:30 +05302824 date_fieldname = "delivery_date" if child_doctype == "Sales Order Item" else "schedule_date"
Jannat Patelbb0d8f82021-02-11 20:59:28 +05302825 child_item.update({date_fieldname: trans_item.get(date_fieldname) or p_doc.get(date_fieldname)})
marination0673f552021-03-31 01:38:22 +05302826 child_item.stock_uom = item.stock_uom
Saqib61314242020-09-15 11:14:31 +05302827 child_item.uom = trans_item.get("uom") or item.stock_uom
Andy Zhu1062d7e2020-10-06 10:51:42 +13002828 child_item.warehouse = get_item_warehouse(item, p_doc, overwrite_warehouse=True)
Ankush Menat494bd9e2022-03-28 18:52:46 +05302829 conversion_factor = flt(
2830 get_conversion_factor(item.item_code, child_item.uom).get("conversion_factor")
2831 )
2832 child_item.conversion_factor = flt(trans_item.get("conversion_factor")) or conversion_factor
marination0673f552021-03-31 01:38:22 +05302833
pateljannat637ddff2021-02-09 16:17:30 +05302834 if child_doctype == "Purchase Order Item":
marination0673f552021-03-31 01:38:22 +05302835 # Initialized value will update in parent validation
2836 child_item.base_rate = 1
2837 child_item.base_amount = 1
pateljannat637ddff2021-02-09 16:17:30 +05302838 if child_doctype == "Sales Order Item":
2839 child_item.warehouse = get_item_warehouse(item, p_doc, overwrite_warehouse=True)
2840 if not child_item.warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302841 frappe.throw(
2842 _("Cannot find {} for item {}. Please set the same in Item Master or Stock Settings.").format(
2843 frappe.bold("default warehouse"), frappe.bold(item.item_code)
2844 )
2845 )
marination0673f552021-03-31 01:38:22 +05302846
marination698d9832020-08-19 14:59:46 +05302847 set_child_tax_template_and_map(item, child_item, p_doc)
Marica3b1be2b2020-10-22 17:04:31 +05302848 add_taxes_from_tax_template(child_item, p_doc)
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002849 return child_item
2850
Ankush Menat494bd9e2022-03-28 18:52:46 +05302851
marination0673f552021-03-31 01:38:22 +05302852def validate_child_on_delete(row, parent):
2853 """Check if partially transacted item (row) is being deleted."""
2854 if parent.doctype == "Sales Order":
2855 if flt(row.delivered_qty):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302856 frappe.throw(
2857 _("Row #{0}: Cannot delete item {1} which has already been delivered").format(
2858 row.idx, row.item_code
2859 )
2860 )
marination0673f552021-03-31 01:38:22 +05302861 if flt(row.work_order_qty):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302862 frappe.throw(
2863 _("Row #{0}: Cannot delete item {1} which has work order assigned to it.").format(
2864 row.idx, row.item_code
2865 )
2866 )
marination0673f552021-03-31 01:38:22 +05302867 if flt(row.ordered_qty):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302868 frappe.throw(
2869 _("Row #{0}: Cannot delete item {1} which is assigned to customer's purchase order.").format(
2870 row.idx, row.item_code
2871 )
2872 )
marination0673f552021-03-31 01:38:22 +05302873
2874 if parent.doctype == "Purchase Order" and flt(row.received_qty):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302875 frappe.throw(
2876 _("Row #{0}: Cannot delete item {1} which has already been received").format(
2877 row.idx, row.item_code
2878 )
2879 )
marination0673f552021-03-31 01:38:22 +05302880
2881 if flt(row.billed_amt):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302882 frappe.throw(
2883 _("Row #{0}: Cannot delete item {1} which has already been billed.").format(
2884 row.idx, row.item_code
2885 )
2886 )
2887
marination0673f552021-03-31 01:38:22 +05302888
2889def update_bin_on_delete(row, doctype):
2890 """Update bin for deleted item (row)."""
Chillar Anand915b3432021-09-02 16:44:59 +05302891 from erpnext.stock.stock_balance import (
2892 get_indented_qty,
2893 get_ordered_qty,
2894 get_reserved_qty,
2895 update_bin_qty,
2896 )
Ankush Menat494bd9e2022-03-28 18:52:46 +05302897
marination0673f552021-03-31 01:38:22 +05302898 qty_dict = {}
2899
2900 if doctype == "Sales Order":
2901 qty_dict["reserved_qty"] = get_reserved_qty(row.item_code, row.warehouse)
2902 else:
2903 if row.material_request_item:
2904 qty_dict["indented_qty"] = get_indented_qty(row.item_code, row.warehouse)
2905
2906 qty_dict["ordered_qty"] = get_ordered_qty(row.item_code, row.warehouse)
2907
Deepesh Garga61790c2022-02-22 20:58:10 +05302908 if row.warehouse:
2909 update_bin_qty(row.item_code, row.warehouse, qty_dict)
marination0673f552021-03-31 01:38:22 +05302910
Ankush Menat494bd9e2022-03-28 18:52:46 +05302911
Ankush Menatdd11f262022-06-27 15:55:08 +05302912def validate_and_delete_children(parent, data) -> bool:
Saqib0ad74492019-12-24 16:42:30 +05302913 deleted_children = []
2914 updated_item_names = [d.get("docname") for d in data]
2915 for item in parent.items:
2916 if item.name not in updated_item_names:
2917 deleted_children.append(item)
2918
2919 for d in deleted_children:
marination0673f552021-03-31 01:38:22 +05302920 validate_child_on_delete(d, parent)
Saqib0ad74492019-12-24 16:42:30 +05302921 d.cancel()
2922 d.delete()
marination0673f552021-03-31 01:38:22 +05302923
2924 # need to update ordered qty in Material Request first
2925 # bin uses Material Request Items to recalculate & update
2926 parent.update_prevdoc_status()
2927
2928 for d in deleted_children:
2929 update_bin_on_delete(d, parent.doctype)
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002930
Ankush Menatdd11f262022-06-27 15:55:08 +05302931 return bool(deleted_children)
2932
Rohan Bansala93b5142021-04-06 17:10:52 +05302933
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002934@frappe.whitelist()
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002935def update_child_qty_rate(parent_doctype, trans_items, parent_doctype_name, child_docname="items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302936 def check_doc_permissions(doc, perm_type="create"):
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302937 try:
2938 doc.check_permission(perm_type)
Saqib6db92fb2020-09-14 19:54:17 +05302939 except frappe.PermissionError:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302940 actions = {"create": "add", "write": "update"}
Saqib6db92fb2020-09-14 19:54:17 +05302941
Ankush Menat494bd9e2022-03-28 18:52:46 +05302942 frappe.throw(
2943 _("You do not have permissions to {} items in a {}.").format(
2944 actions[perm_type], parent_doctype
2945 ),
2946 title=_("Insufficient Permissions"),
2947 )
marination665c27a2020-09-15 12:04:38 +05302948
Saqib6db92fb2020-09-14 19:54:17 +05302949 def validate_workflow_conditions(doc):
2950 workflow = get_workflow_name(doc.doctype)
2951 if not workflow:
2952 return
2953
2954 workflow_doc = frappe.get_doc("Workflow", workflow)
2955 current_state = doc.get(workflow_doc.workflow_state_field)
2956 roles = frappe.get_roles()
2957
2958 transitions = []
2959 for transition in workflow_doc.transitions:
2960 if transition.next_state == current_state and transition.allowed in roles:
2961 if not is_transition_condition_satisfied(transition, doc):
2962 continue
2963 transitions.append(transition.as_dict())
2964
2965 if not transitions:
Saqib18318932020-09-23 13:01:49 +05302966 frappe.throw(
Ankush Menat494bd9e2022-03-28 18:52:46 +05302967 _("You are not allowed to update as per the conditions set in {} Workflow.").format(
2968 get_link_to_form("Workflow", workflow)
2969 ),
2970 title=_("Insufficient Permissions"),
Saqib18318932020-09-23 13:01:49 +05302971 )
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302972
Rohit Waghchaure8d5380a2020-06-18 14:06:31 +05302973 def get_new_child_item(item_row):
Rohit Waghchaureff70e612021-03-06 22:08:08 +05302974 child_doctype = "Sales Order Item" if parent_doctype == "Sales Order" else "Purchase Order Item"
Ankush Menat494bd9e2022-03-28 18:52:46 +05302975 return set_order_defaults(
2976 parent_doctype, parent_doctype_name, child_doctype, child_docname, item_row
2977 )
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302978
marination0c915432022-05-10 18:04:02 +05302979 def validate_quantity(child_item, new_data):
2980 if not flt(new_data.get("qty")):
2981 frappe.throw(
2982 _("Row # {0}: Quantity for Item {1} cannot be zero").format(
2983 new_data.get("idx"), frappe.bold(new_data.get("item_code"))
2984 ),
2985 title=_("Invalid Qty"),
2986 )
2987
2988 if parent_doctype == "Sales Order" and flt(new_data.get("qty")) < flt(child_item.delivered_qty):
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302989 frappe.throw(_("Cannot set quantity less than delivered quantity"))
2990
marination0c915432022-05-10 18:04:02 +05302991 if parent_doctype == "Purchase Order" and flt(new_data.get("qty")) < flt(
2992 child_item.received_qty
2993 ):
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302994 frappe.throw(_("Cannot set quantity less than received quantity"))
2995
Ankush Menatdd11f262022-06-27 15:55:08 +05302996 def should_update_supplied_items(doc) -> bool:
2997 """Subcontracted PO can allow following changes *after submit*:
2998
2999 1. Change rate of subcontracting - regardless of other changes.
3000 2. Change qty and/or add new items and/or remove items
3001 Exception: Transfer/Consumption is already made, qty change not allowed.
3002 """
3003
3004 supplied_items_processed = any(
3005 item.supplied_qty or item.consumed_qty or item.returned_qty for item in doc.supplied_items
3006 )
3007
3008 update_supplied_items = (
3009 any_qty_changed or items_added_or_removed or any_conversion_factor_changed
3010 )
3011 if update_supplied_items and supplied_items_processed:
3012 frappe.throw(_("Item qty can not be updated as raw materials are already processed."))
3013
3014 return update_supplied_items
3015
s-aga-r9588bb72023-08-21 22:23:57 +05303016 def validate_fg_item_for_subcontracting(new_data, is_new):
3017 if is_new:
3018 if not new_data.get("fg_item"):
3019 frappe.throw(
3020 _("Finished Good Item is not specified for service item {0}").format(new_data["item_code"])
3021 )
3022 else:
3023 is_sub_contracted_item, default_bom = frappe.db.get_value(
3024 "Item", new_data["fg_item"], ["is_sub_contracted_item", "default_bom"]
3025 )
3026
3027 if not is_sub_contracted_item:
3028 frappe.throw(
3029 _("Finished Good Item {0} must be a sub-contracted item").format(new_data["fg_item"])
3030 )
3031 elif not default_bom:
3032 frappe.throw(_("Default BOM not found for FG Item {0}").format(new_data["fg_item"]))
3033
3034 if not new_data.get("fg_item_qty"):
3035 frappe.throw(_("Finished Good Item {0} Qty can not be zero").format(new_data["fg_item"]))
3036
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08003037 data = json.loads(trans_items)
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08003038
Ankush Menatdd11f262022-06-27 15:55:08 +05303039 any_qty_changed = False # updated to true if any item's qty changes
3040 items_added_or_removed = False # updated to true if any new item is added or removed
3041 any_conversion_factor_changed = False
3042
Ankush Menat494bd9e2022-03-28 18:52:46 +05303043 sales_doctypes = ["Sales Order", "Sales Invoice", "Delivery Note", "Quotation"]
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05303044 parent = frappe.get_doc(parent_doctype, parent_doctype_name)
marination665c27a2020-09-15 12:04:38 +05303045
Ankush Menat494bd9e2022-03-28 18:52:46 +05303046 check_doc_permissions(parent, "write")
Ankush Menatdd11f262022-06-27 15:55:08 +05303047 _removed_items = validate_and_delete_children(parent, data)
3048 items_added_or_removed |= _removed_items
Saqib0ad74492019-12-24 16:42:30 +05303049
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01003050 for d in data:
3051 new_child_flag = False
Ankush Menat6de7b8e2021-08-24 12:18:40 +05303052
3053 if not d.get("item_code"):
3054 # ignore empty rows
3055 continue
3056
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01003057 if not d.get("docname"):
3058 new_child_flag = True
Ankush Menatdd11f262022-06-27 15:55:08 +05303059 items_added_or_removed = True
Ankush Menat494bd9e2022-03-28 18:52:46 +05303060 check_doc_permissions(parent, "create")
Rohit Waghchaure8d5380a2020-06-18 14:06:31 +05303061 child_item = get_new_child_item(d)
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01003062 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05303063 check_doc_permissions(parent, "write")
3064 child_item = frappe.get_doc(parent_doctype + " Item", d.get("docname"))
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05303065
Saqib Ansaric579b082020-05-29 22:21:50 +05303066 prev_rate, new_rate = flt(child_item.get("rate")), flt(d.get("rate"))
3067 prev_qty, new_qty = flt(child_item.get("qty")), flt(d.get("qty"))
s-aga-r9588bb72023-08-21 22:23:57 +05303068 prev_fg_qty, new_fg_qty = flt(child_item.get("fg_item_qty")), flt(d.get("fg_item_qty"))
Ankush Menat494bd9e2022-03-28 18:52:46 +05303069 prev_con_fac, new_con_fac = flt(child_item.get("conversion_factor")), flt(
3070 d.get("conversion_factor")
3071 )
Saqib61314242020-09-15 11:14:31 +05303072 prev_uom, new_uom = child_item.get("uom"), d.get("uom")
Saqib Ansaric579b082020-05-29 22:21:50 +05303073
Ankush Menat494bd9e2022-03-28 18:52:46 +05303074 if parent_doctype == "Sales Order":
Saqib Ansaric579b082020-05-29 22:21:50 +05303075 prev_date, new_date = child_item.get("delivery_date"), d.get("delivery_date")
Ankush Menat494bd9e2022-03-28 18:52:46 +05303076 elif parent_doctype == "Purchase Order":
marinationb7e94cc2020-06-15 11:32:42 +05303077 prev_date, new_date = child_item.get("schedule_date"), d.get("schedule_date")
Saqib Ansaric579b082020-05-29 22:21:50 +05303078
3079 rate_unchanged = prev_rate == new_rate
marinationf9c4b202020-06-12 15:49:53 +05303080 qty_unchanged = prev_qty == new_qty
s-aga-r9588bb72023-08-21 22:23:57 +05303081 fg_qty_unchanged = prev_fg_qty == new_fg_qty
Saqib61314242020-09-15 11:14:31 +05303082 uom_unchanged = prev_uom == new_uom
Saqib Ansaric579b082020-05-29 22:21:50 +05303083 conversion_factor_unchanged = prev_con_fac == new_con_fac
Ankush Menatdd11f262022-06-27 15:55:08 +05303084 any_conversion_factor_changed |= not conversion_factor_unchanged
Ankush Menat494bd9e2022-03-28 18:52:46 +05303085 date_unchanged = (
3086 prev_date == getdate(new_date) if prev_date and new_date else False
3087 ) # in case of delivery note etc
3088 if (
3089 rate_unchanged
3090 and qty_unchanged
s-aga-r9588bb72023-08-21 22:23:57 +05303091 and fg_qty_unchanged
Ankush Menat494bd9e2022-03-28 18:52:46 +05303092 and conversion_factor_unchanged
3093 and uom_unchanged
3094 and date_unchanged
3095 ):
Saqibdd374ff2020-02-27 12:51:31 +05303096 continue
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01003097
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05303098 validate_quantity(child_item, d)
Ankush Menatdd11f262022-06-27 15:55:08 +05303099 if flt(child_item.get("qty")) != flt(d.get("qty")):
3100 any_qty_changed = True
deepeshgarg00777cde832018-12-27 15:56:51 +05303101
s-aga-r9588bb72023-08-21 22:23:57 +05303102 if (
3103 parent.doctype == "Purchase Order"
3104 and parent.is_subcontracted
3105 and not parent.is_old_subcontracting_flow
3106 ):
3107 validate_fg_item_for_subcontracting(d, new_child_flag)
3108 child_item.fg_item_qty = flt(d["fg_item_qty"])
3109
3110 if new_child_flag:
3111 child_item.fg_item = d["fg_item"]
3112
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01003113 child_item.qty = flt(d.get("qty"))
Saqib56fea7d2020-10-09 21:19:25 +05303114 rate_precision = child_item.precision("rate") or 2
3115 conv_fac_precision = child_item.precision("conversion_factor") or 2
3116 qty_precision = child_item.precision("qty") or 2
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08003117
Ankush Menat494bd9e2022-03-28 18:52:46 +05303118 if flt(child_item.billed_amt, rate_precision) > flt(
3119 flt(d.get("rate"), rate_precision) * flt(d.get("qty"), qty_precision), rate_precision
3120 ):
3121 frappe.throw(
3122 _("Row #{0}: Cannot set Rate if amount is greater than billed amount for Item {1}.").format(
3123 child_item.idx, child_item.item_code
3124 )
3125 )
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08003126 else:
Saqib56fea7d2020-10-09 21:19:25 +05303127 child_item.rate = flt(d.get("rate"), rate_precision)
marinationf9c4b202020-06-12 15:49:53 +05303128
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05303129 if d.get("conversion_factor"):
marinationf9c4b202020-06-12 15:49:53 +05303130 if child_item.stock_uom == child_item.uom:
3131 child_item.conversion_factor = 1
3132 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05303133 child_item.conversion_factor = flt(d.get("conversion_factor"), conv_fac_precision)
marination665c27a2020-09-15 12:04:38 +05303134
Saqib61314242020-09-15 11:14:31 +05303135 if d.get("uom"):
3136 child_item.uom = d.get("uom")
Ankush Menat494bd9e2022-03-28 18:52:46 +05303137 conversion_factor = flt(
3138 get_conversion_factor(child_item.item_code, child_item.uom).get("conversion_factor")
3139 )
3140 child_item.conversion_factor = (
3141 flt(d.get("conversion_factor"), conv_fac_precision) or conversion_factor
3142 )
Mangesh-Khairnara3d52002019-08-05 10:16:40 +05303143
Ankush Menat494bd9e2022-03-28 18:52:46 +05303144 if d.get("delivery_date") and parent_doctype == "Sales Order":
3145 child_item.delivery_date = d.get("delivery_date")
marinationf9c4b202020-06-12 15:49:53 +05303146
Ankush Menat494bd9e2022-03-28 18:52:46 +05303147 if d.get("schedule_date") and parent_doctype == "Purchase Order":
3148 child_item.schedule_date = d.get("schedule_date")
Saqib Ansaric579b082020-05-29 22:21:50 +05303149
Mangesh-Khairnara3d52002019-08-05 10:16:40 +05303150 if flt(child_item.price_list_rate):
Maricaf0674472019-10-11 10:47:09 +05303151 if flt(child_item.rate) > flt(child_item.price_list_rate):
3152 # if rate is greater than price_list_rate, set margin
3153 # or set discount
3154 child_item.discount_percentage = 0
rohitwaghchaure81c21752019-10-31 15:56:10 +05303155
3156 if parent_doctype in sales_doctypes:
3157 child_item.margin_type = "Amount"
Ankush Menat494bd9e2022-03-28 18:52:46 +05303158 child_item.margin_rate_or_amount = flt(
3159 child_item.rate - child_item.price_list_rate, child_item.precision("margin_rate_or_amount")
3160 )
rohitwaghchaure81c21752019-10-31 15:56:10 +05303161 child_item.rate_with_margin = child_item.rate
Maricaf0674472019-10-11 10:47:09 +05303162 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05303163 child_item.discount_percentage = flt(
3164 (1 - flt(child_item.rate) / flt(child_item.price_list_rate)) * 100.0,
3165 child_item.precision("discount_percentage"),
3166 )
3167 child_item.discount_amount = flt(child_item.price_list_rate) - flt(child_item.rate)
rohitwaghchaure81c21752019-10-31 15:56:10 +05303168
3169 if parent_doctype in sales_doctypes:
3170 child_item.margin_type = ""
3171 child_item.margin_rate_or_amount = 0
3172 child_item.rate_with_margin = 0
Mangesh-Khairnara3d52002019-08-05 10:16:40 +05303173
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08003174 child_item.flags.ignore_validate_update_after_submit = True
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01003175 if new_child_flag:
Saqib Ansarif53299e2020-04-15 22:08:12 +05303176 parent.load_from_db()
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05303177 child_item.idx = len(parent.items) + 1
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01003178 child_item.insert()
3179 else:
3180 child_item.save()
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08003181
Rushabh Mehtafafbb022018-12-24 22:09:15 +05303182 parent.reload()
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05303183 parent.flags.ignore_validate_update_after_submit = True
3184 parent.set_qty_as_per_stock_uom()
3185 parent.calculate_taxes_and_totals()
Ankush Menatdf6e2082021-02-11 11:04:39 +05303186 parent.set_total_in_words()
Nabin Hait49a46f02019-10-21 13:35:43 +05303187 if parent_doctype == "Sales Order":
Marica3dee5272020-06-23 10:33:47 +05303188 make_packing_list(parent)
Nabin Hait49a46f02019-10-21 13:35:43 +05303189 parent.set_gross_profit()
Ankush Menat494bd9e2022-03-28 18:52:46 +05303190 frappe.get_doc("Authorization Control").validate_approving_authority(
3191 parent.doctype, parent.company, parent.base_grand_total
3192 )
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08003193
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05303194 parent.set_payment_schedule()
Ankush Menat494bd9e2022-03-28 18:52:46 +05303195 if parent_doctype == "Purchase Order":
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05303196 parent.validate_minimum_order_qty()
3197 parent.validate_budget()
3198 if parent.is_against_so():
3199 parent.update_status_updater()
Nabin Haitb2da0822018-07-13 17:01:40 +05303200 else:
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05303201 parent.check_credit_limit()
Ankush Menat733c9de2022-01-04 18:39:30 +05303202
3203 # reset index of child table
3204 for idx, row in enumerate(parent.get(child_docname), start=1):
3205 row.idx = idx
3206
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05303207 parent.save()
Nabin Haitb2da0822018-07-13 17:01:40 +05303208
Ankush Menat494bd9e2022-03-28 18:52:46 +05303209 if parent_doctype == "Purchase Order":
3210 update_last_purchase_rate(parent, is_submit=1)
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05303211 parent.update_prevdoc_status()
3212 parent.update_requested_qty()
3213 parent.update_ordered_qty()
3214 parent.update_ordered_and_reserved_qty()
3215 parent.update_receiving_percentage()
s-aga-rb9b17172023-08-22 16:53:54 +05303216
3217 if parent.is_subcontracted:
3218 if parent.is_old_subcontracting_flow:
3219 if should_update_supplied_items(parent):
3220 parent.update_reserved_qty_for_subcontract()
3221 parent.create_raw_materials_supplied()
3222 parent.save()
3223 else:
3224 if not parent.can_update_items():
3225 frappe.throw(
3226 _(
3227 "Items cannot be updated as Subcontracting Order is created against the Purchase Order {0}."
3228 ).format(frappe.bold(parent.name))
3229 )
Ankush Menatc84e11a2022-06-01 12:55:10 +05303230 else: # Sales Order
3231 parent.validate_warehouse()
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05303232 parent.update_reserved_qty()
3233 parent.update_project()
Ankush Menat494bd9e2022-03-28 18:52:46 +05303234 parent.update_prevdoc_status("submit")
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05303235 parent.update_delivery_status()
Nabin Haitb2da0822018-07-13 17:01:40 +05303236
Saqib6db92fb2020-09-14 19:54:17 +05303237 parent.reload()
3238 validate_workflow_conditions(parent)
3239
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05303240 parent.update_blanket_order()
3241 parent.update_billing_percentage()
3242 parent.set_status()
Gauravf1e28e02019-02-13 16:46:24 +05303243
s-aga-rac24d772023-04-05 19:48:15 +05303244 # Cancel and Recreate Stock Reservation Entries.
s-aga-r38e93672023-04-02 21:24:59 +05303245 if parent_doctype == "Sales Order":
3246 from erpnext.stock.doctype.stock_reservation_entry.stock_reservation_entry import (
3247 cancel_stock_reservation_entries,
3248 has_reserved_stock,
s-aga-r38e93672023-04-02 21:24:59 +05303249 )
3250
3251 if has_reserved_stock(parent.doctype, parent.name):
3252 cancel_stock_reservation_entries(parent.doctype, parent.name)
s-aga-r2d8363a2023-09-02 11:02:24 +05303253
3254 if parent.per_picked == 0:
3255 parent.create_stock_reservation_entries()
s-aga-r38e93672023-04-02 21:24:59 +05303256
Ankush Menat494bd9e2022-03-28 18:52:46 +05303257
Gursheen Anand68effd92023-09-21 17:28:07 +05303258def check_if_child_table_updated(
3259 child_table_before_update, child_table_after_update, fields_to_check
3260):
3261 accounting_dimensions = get_accounting_dimensions() + ["cost_center", "project"]
3262 # Check if any field affecting accounting entry is altered
3263 for index, item in enumerate(child_table_after_update):
3264 for field in fields_to_check:
3265 if child_table_before_update[index].get(field) != item.get(field):
3266 return True
3267
3268 for dimension in accounting_dimensions:
3269 if child_table_before_update[index].get(dimension) != item.get(dimension):
3270 return True
3271
3272 return False
3273
3274
Gursheen Ananda06017c2023-06-12 15:24:53 +05303275@erpnext.allow_regional
3276def validate_regional(doc):
3277 pass
3278
3279
3280@erpnext.allow_regional
3281def validate_einvoice_fields(doc):
3282 pass
3283
3284
3285@erpnext.allow_regional
3286def update_gl_dict_with_regional_fields(doc, gl_dict):
3287 pass