blob: e83e0c2702d57e4c505dfb8d2b1e19f63e08ca1c [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
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05308from frappe import _, throw
Chillar Anand915b3432021-09-02 16:44:59 +05309from frappe.model.workflow import get_workflow_name, is_transition_condition_satisfied
Pruthvi Patel6c96ed42021-10-30 16:44:15 +053010from frappe.query_builder.functions import Sum
Chillar Anand915b3432021-09-02 16:44:59 +053011from frappe.utils import (
12 add_days,
13 add_months,
14 cint,
15 flt,
16 fmt_money,
17 formatdate,
18 get_last_day,
19 get_link_to_form,
20 getdate,
21 nowdate,
GangaManojd24cfff2021-10-28 20:06:48 +053022 today,
Chillar Anand915b3432021-09-02 16:44:59 +053023)
Chillar Anand915b3432021-09-02 16:44:59 +053024
25import erpnext
26from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import (
27 get_accounting_dimensions,
28)
29from erpnext.accounts.doctype.pricing_rule.utils import (
30 apply_pricing_rule_for_free_items,
31 apply_pricing_rule_on_transaction,
32 get_applied_pricing_rules,
33)
34from erpnext.accounts.party import (
35 get_party_account,
36 get_party_account_currency,
Deepesh Garga7f15a02021-12-12 21:09:11 +053037 get_party_gle_currency,
Chillar Anand915b3432021-09-02 16:44:59 +053038 validate_party_frozen_disabled,
39)
40from erpnext.accounts.utils import get_account_currency, get_fiscal_years, validate_fiscal_year
41from erpnext.buying.utils import update_last_purchase_rate
42from erpnext.controllers.print_settings import (
43 set_print_templates_for_item_table,
44 set_print_templates_for_taxes,
45)
46from erpnext.controllers.sales_and_purchase_return import validate_return
47from erpnext.exceptions import InvalidCurrency
48from erpnext.setup.utils import get_exchange_rate
Marica3dee5272020-06-23 10:33:47 +053049from erpnext.stock.doctype.packed_item.packed_item import make_packing_list
Chillar Anand915b3432021-09-02 16:44:59 +053050from erpnext.stock.get_item_details import (
51 _get_item_tax_template,
52 get_conversion_factor,
53 get_item_details,
54 get_item_tax_map,
55 get_item_warehouse,
56)
57from erpnext.utilities.transaction_base import TransactionBase
58
Nabin Hait1d218422015-07-17 15:19:02 +053059
Ankush Menat494bd9e2022-03-28 18:52:46 +053060class AccountMissingError(frappe.ValidationError):
61 pass
marination53b1a9a2020-11-03 15:45:25 +053062
Ankush Menat494bd9e2022-03-28 18:52:46 +053063
64force_item_fields = (
65 "item_group",
66 "brand",
67 "stock_uom",
68 "is_fixed_asset",
69 "item_tax_rate",
70 "pricing_rules",
71 "weight_per_unit",
72 "weight_uom",
73 "total_weight",
74)
75
Doridel Cahanap6f06cc22018-05-17 16:28:58 +080076
Nabin Haitbf495c92013-01-30 12:49:08 +053077class AccountsController(TransactionBase):
Nabin Hait7eba1a32017-10-02 15:59:27 +053078 def __init__(self, *args, **kwargs):
79 super(AccountsController, self).__init__(*args, **kwargs)
Anand Doshi979326b2015-09-11 16:22:37 +053080
prssanna71e5b602020-10-29 14:19:34 +053081 def get_print_settings(self):
82 print_setting_fields = []
Ankush Menat494bd9e2022-03-28 18:52:46 +053083 items_field = self.meta.get_field("items")
prssanna71e5b602020-10-29 14:19:34 +053084
Ankush Menat494bd9e2022-03-28 18:52:46 +053085 if items_field and items_field.fieldtype == "Table":
86 print_setting_fields += ["compact_item_print", "print_uom_after_quantity"]
prssanna71e5b602020-10-29 14:19:34 +053087
Ankush Menat494bd9e2022-03-28 18:52:46 +053088 taxes_field = self.meta.get_field("taxes")
89 if taxes_field and taxes_field.fieldtype == "Table":
90 print_setting_fields += ["print_taxes_with_zero_amount"]
prssanna71e5b602020-10-29 14:19:34 +053091
92 return print_setting_fields
93
Nabin Hait4ffd7f32015-08-27 12:28:36 +053094 @property
95 def company_currency(self):
96 if not hasattr(self, "__company_currency"):
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +053097 self.__company_currency = erpnext.get_company_currency(self.company)
Anand Doshi979326b2015-09-11 16:22:37 +053098
Nabin Hait4ffd7f32015-08-27 12:28:36 +053099 return self.__company_currency
Anand Doshi979326b2015-09-11 16:22:37 +0530100
Rohit Waghchaure7d529892016-10-06 14:35:04 +0530101 def onload(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530102 self.set_onload(
103 "make_payment_via_journal_entry",
104 frappe.db.get_single_value("Accounts Settings", "make_payment_via_journal_entry"),
105 )
Nabin Hait0551f7b2017-11-21 19:58:16 +0530106
tundee52bb822017-09-25 09:02:23 +0100107 if self.is_new():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530108 relevant_docs = (
109 "Quotation",
110 "Purchase Order",
111 "Sales Order",
112 "Purchase Invoice",
113 "Sales Invoice",
114 )
tundee52bb822017-09-25 09:02:23 +0100115 if self.doctype in relevant_docs:
116 self.set_payment_schedule()
Rohit Waghchaure7d529892016-10-06 14:35:04 +0530117
tundebabzyad08d4c2018-05-16 07:01:41 +0100118 def ensure_supplier_is_not_blocked(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530119 is_supplier_payment = self.doctype == "Payment Entry" and self.party_type == "Supplier"
120 is_buying_invoice = self.doctype in ["Purchase Invoice", "Purchase Order"]
tundebabzyad08d4c2018-05-16 07:01:41 +0100121 supplier = None
122 supplier_name = None
123
124 if is_buying_invoice or is_supplier_payment:
125 supplier_name = self.supplier if is_buying_invoice else self.party
Ankush Menat494bd9e2022-03-28 18:52:46 +0530126 supplier = frappe.get_doc("Supplier", supplier_name)
tundebabzyad08d4c2018-05-16 07:01:41 +0100127
128 if supplier and supplier_name and supplier.on_hold:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530129 if (is_buying_invoice and supplier.hold_type in ["All", "Invoices"]) or (
130 is_supplier_payment and supplier.hold_type in ["All", "Payments"]
131 ):
tundebabzyad08d4c2018-05-16 07:01:41 +0100132 if not supplier.release_date or getdate(nowdate()) <= supplier.release_date:
133 frappe.msgprint(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530134 _("{0} is blocked so this transaction cannot proceed").format(supplier_name),
135 raise_exception=1,
136 )
tundebabzyad08d4c2018-05-16 07:01:41 +0100137
Saurabh6f753182013-03-20 12:55:28 +0530138 def validate(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530139 if not self.get("is_return") and not self.get("is_debit_note"):
Deepesh Gargd301d262019-07-31 15:58:19 +0530140 self.validate_qty_is_not_zero()
141
nabinhait23cce732014-07-03 12:25:06 +0530142 if self.get("_action") and self._action != "update_after_submit":
Nabin Hait704a4532014-06-05 16:55:31 +0530143 self.set_missing_values(for_validate=True)
tunde62af5c52017-09-22 15:16:38 +0100144
tundebabzyad08d4c2018-05-16 07:01:41 +0100145 self.ensure_supplier_is_not_blocked()
146
Nabin Haitcfecd2b2013-07-11 17:49:18 +0530147 self.validate_date_with_fiscal_year()
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530148 self.validate_party_accounts()
149
Deepesh Gargb4be2922021-01-28 13:09:56 +0530150 self.validate_inter_company_reference()
151
Ankush Menat3714e362022-05-16 18:09:14 +0530152 self.disable_pricing_rule_on_internal_transfer()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530153 self.set_incoming_rate()
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530154
Anand Doshi3543f302013-05-24 19:25:01 +0530155 if self.meta.get_field("currency"):
Anand Doshi923d41d2013-05-28 17:23:36 +0530156 self.calculate_taxes_and_totals()
Rohit Waghchaure6087fe12016-04-09 14:31:09 +0530157
Nabin Hait1d218422015-07-17 15:19:02 +0530158 if not self.meta.get_field("is_return") or not self.is_return:
159 self.validate_value("base_grand_total", ">=", 0)
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530160
Nabin Hait3cf67a42015-07-24 13:26:36 +0530161 validate_return(self)
Anand Doshi3543f302013-05-24 19:25:01 +0530162 self.set_total_in_words()
Anand Doshid2946502014-04-08 20:10:03 +0530163
tunde62af5c52017-09-22 15:16:38 +0100164 self.validate_all_documents_schedule()
Anand Doshid2946502014-04-08 20:10:03 +0530165
ankitjavalkarwork6c29d872014-10-06 13:20:53 +0530166 if self.meta.get_field("taxes_and_charges"):
167 self.validate_enabled_taxes_and_charges()
Nabin Haita2426fc2018-01-15 17:45:46 +0530168 self.validate_tax_account_company()
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530169
Neil Trini Lasrado3fbbb712015-07-17 12:10:12 +0530170 self.validate_party()
Nabin Hait895029d2015-08-20 14:55:39 +0530171 self.validate_currency()
Deepesh Garg80c85dd2021-08-12 15:39:07 +0530172 self.validate_party_account_currency()
Rushabh Mehta2cb7a9f2016-06-15 16:45:03 +0530173
Ankush Menat494bd9e2022-03-28 18:52:46 +0530174 if self.doctype in ["Purchase Invoice", "Sales Invoice"]:
175 pos_check_field = "is_pos" if self.doctype == "Sales Invoice" else "is_paid"
Nabin Hait4a994d42019-04-25 17:47:26 +0530176 if cint(self.allocate_advances_automatically) and not cint(self.get(pos_check_field)):
Nabin Hait041a5c22018-08-01 18:07:39 +0530177 self.set_advances()
178
Saqiba20999c2021-07-12 14:33:23 +0530179 self.set_advance_gain_or_loss()
180
Nabin Hait041a5c22018-08-01 18:07:39 +0530181 if self.is_return:
182 self.validate_qty()
Nabin Haitacdd5082019-12-04 15:30:01 +0530183 else:
184 self.validate_deferred_start_and_end_date()
rohitwaghchaure70489252018-06-11 12:02:14 +0530185
Deepesh Garg9bf5f762022-04-06 17:33:46 +0530186 self.validate_deferred_income_expense_account()
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530187 self.set_inter_company_account()
188
Ankush Menat494bd9e2022-03-28 18:52:46 +0530189 if self.doctype == "Purchase Invoice":
Deepesh Garg7f06c8c2021-11-26 10:27:57 +0530190 self.calculate_paid_amount()
191 # apply tax withholding only if checked and applicable
192 self.set_tax_withholding()
193
Gauravf1e28e02019-02-13 16:46:24 +0530194 validate_regional(self)
Deepesh Garg7c300852020-12-26 20:14:51 +0530195
Saqib Ansaric5782b02022-01-27 20:09:56 +0530196 validate_einvoice_fields(self)
197
Ankush Menat494bd9e2022-03-28 18:52:46 +0530198 if self.doctype != "Material Request":
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530199 apply_pricing_rule_on_transaction(self)
Gauravf1e28e02019-02-13 16:46:24 +0530200
Saqib Ansaric5782b02022-01-27 20:09:56 +0530201 def before_cancel(self):
202 validate_einvoice_fields(self)
203
Saqib8e556772021-01-28 12:26:45 +0530204 def on_trash(self):
205 # delete sl and gl entries on deletion of transaction
Ankush Menat494bd9e2022-03-28 18:52:46 +0530206 if frappe.db.get_single_value("Accounts Settings", "delete_linked_ledger_entries"):
207 frappe.db.sql(
208 "delete from `tabGL Entry` where voucher_type=%s and voucher_no=%s", (self.doctype, self.name)
209 )
210 frappe.db.sql(
211 "delete from `tabStock Ledger Entry` where voucher_type=%s and voucher_no=%s",
212 (self.doctype, self.name),
213 )
Nabin Hait0551f7b2017-11-21 19:58:16 +0530214
Deepesh Garg9bf5f762022-04-06 17:33:46 +0530215 def validate_deferred_income_expense_account(self):
216 field_map = {
217 "Sales Invoice": "deferred_revenue_account",
218 "Purchase Invoice": "deferred_expense_account",
219 }
220
221 for item in self.get("items"):
222 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
223 if not item.get(field_map.get(self.doctype)):
224 default_deferred_account = frappe.db.get_value(
225 "Company", self.company, "default_" + field_map.get(self.doctype)
226 )
227 if not default_deferred_account:
228 frappe.throw(
229 _(
230 "Row #{0}: Please update deferred revenue/expense account in item row or default account in company master"
231 ).format(item.idx)
232 )
233 else:
234 item.set(field_map.get(self.doctype), default_deferred_account)
235
Nabin Haitacdd5082019-12-04 15:30:01 +0530236 def validate_deferred_start_and_end_date(self):
237 for d in self.items:
238 if d.get("enable_deferred_revenue") or d.get("enable_deferred_expense"):
239 if not (d.service_start_date and d.service_end_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530240 frappe.throw(
241 _("Row #{0}: Service Start and End Date is required for deferred accounting").format(d.idx)
242 )
Nabin Haitacdd5082019-12-04 15:30:01 +0530243 elif getdate(d.service_start_date) > getdate(d.service_end_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530244 frappe.throw(
245 _("Row #{0}: Service Start Date cannot be greater than Service End Date").format(d.idx)
246 )
Nabin Haitacdd5082019-12-04 15:30:01 +0530247 elif getdate(self.posting_date) > getdate(d.service_end_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530248 frappe.throw(
249 _("Row #{0}: Service End Date cannot be before Invoice Posting Date").format(d.idx)
250 )
Nabin Haitacdd5082019-12-04 15:30:01 +0530251
tunde62af5c52017-09-22 15:16:38 +0100252 def validate_invoice_documents_schedule(self):
Nabin Hait0551f7b2017-11-21 19:58:16 +0530253 self.validate_payment_schedule_dates()
254 self.set_due_date()
Nabin Hait0551f7b2017-11-21 19:58:16 +0530255 self.set_payment_schedule()
256 self.validate_payment_schedule_amount()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530257 if not self.get("ignore_default_payment_terms_template"):
Deepesh Gargbd709f82021-08-23 19:05:52 +0530258 self.validate_due_date()
tunde62af5c52017-09-22 15:16:38 +0100259 self.validate_advance_entries()
260
261 def validate_non_invoice_documents_schedule(self):
Nabin Hait0551f7b2017-11-21 19:58:16 +0530262 self.set_payment_schedule()
Nabin Hait2f9f4f92017-12-20 12:24:59 +0530263 self.validate_payment_schedule_dates()
Nabin Hait0551f7b2017-11-21 19:58:16 +0530264 self.validate_payment_schedule_amount()
tunde62af5c52017-09-22 15:16:38 +0100265
266 def validate_all_documents_schedule(self):
267 if self.doctype in ("Sales Invoice", "Purchase Invoice") and not self.is_return:
268 self.validate_invoice_documents_schedule()
269 elif self.doctype in ("Quotation", "Purchase Order", "Sales Order"):
270 self.validate_non_invoice_documents_schedule()
271
prssanna71e5b602020-10-29 14:19:34 +0530272 def before_print(self, settings=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530273 if self.doctype in [
274 "Purchase Order",
275 "Sales Order",
276 "Sales Invoice",
277 "Purchase Invoice",
278 "Supplier Quotation",
279 "Purchase Receipt",
280 "Delivery Note",
281 "Quotation",
282 ]:
KanchanChauhan49a50fe2016-11-18 13:57:53 +0530283 if self.get("group_same_items"):
284 self.group_similar_items()
285
Zarrar5be6d192018-11-08 12:16:26 +0530286 df = self.meta.get_field("discount_amount")
287 if self.get("discount_amount") and hasattr(self, "taxes") and not len(self.taxes):
288 df.set("print_hide", 0)
289 self.discount_amount = -self.discount_amount
290 else:
291 df.set("print_hide", 1)
292
prssanna71e5b602020-10-29 14:19:34 +0530293 set_print_templates_for_item_table(self, settings)
294 set_print_templates_for_taxes(self, settings)
295
Mangesh-Khairnar7bcb24e2019-09-11 10:49:33 +0530296 def calculate_paid_amount(self):
Saurabh43520f92016-03-21 18:32:48 +0530297 if hasattr(self, "is_pos") or hasattr(self, "is_paid"):
298 is_paid = self.get("is_pos") or self.get("is_paid")
Mangesh-Khairnar7bcb24e2019-09-11 10:49:33 +0530299
300 if is_paid:
301 if not self.cash_bank_account:
302 # show message that the amount is not paid
Ankush Menat494bd9e2022-03-28 18:52:46 +0530303 frappe.throw(
304 _("Note: Payment Entry will not be created since 'Cash or Bank Account' was not specified")
305 )
Marica23d7b092019-09-25 17:17:36 +0530306
Mangesh-Khairnar7bcb24e2019-09-11 10:49:33 +0530307 if cint(self.is_return) and self.grand_total > self.paid_amount:
308 self.paid_amount = flt(flt(self.grand_total), self.precision("paid_amount"))
309
310 elif not flt(self.paid_amount) and flt(self.outstanding_amount) > 0:
311 self.paid_amount = flt(flt(self.outstanding_amount), self.precision("paid_amount"))
312
Ankush Menat494bd9e2022-03-28 18:52:46 +0530313 self.base_paid_amount = flt(
314 self.paid_amount * self.conversion_rate, self.precision("base_paid_amount")
315 )
Saurabh43520f92016-03-21 18:32:48 +0530316
Anand Doshiabc10032013-06-14 17:44:03 +0530317 def set_missing_values(self, for_validate=False):
Rohit Waghchaure5d97d892016-05-12 12:58:29 +0530318 if frappe.flags.in_test:
tunde62af5c52017-09-22 15:16:38 +0100319 for fieldname in ["posting_date", "transaction_date"]:
Rohit Waghchaure5d97d892016-05-12 12:58:29 +0530320 if self.meta.get_field(fieldname) and not self.get(fieldname):
321 self.set(fieldname, today())
322 break
Anand Doshid2946502014-04-08 20:10:03 +0530323
Nabin Hait3237c752015-02-17 11:11:11 +0530324 def calculate_taxes_and_totals(self):
Nabin Haitfe81da22015-02-18 12:23:18 +0530325 from erpnext.controllers.taxes_and_totals import calculate_taxes_and_totals
Ankush Menat494bd9e2022-03-28 18:52:46 +0530326
Nabin Haitfe81da22015-02-18 12:23:18 +0530327 calculate_taxes_and_totals(self)
Nabin Hait3237c752015-02-17 11:11:11 +0530328
Raffael Meyere10ab162021-11-30 13:24:18 +0100329 if self.doctype in (
Ankush Menat494bd9e2022-03-28 18:52:46 +0530330 "Sales Order",
331 "Delivery Note",
332 "Sales Invoice",
333 "POS Invoice",
Raffael Meyere10ab162021-11-30 13:24:18 +0100334 ):
Nabin Hait3237c752015-02-17 11:11:11 +0530335 self.calculate_commission()
336 self.calculate_contribution()
337
Nabin Haitcfecd2b2013-07-11 17:49:18 +0530338 def validate_date_with_fiscal_year(self):
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800339 if self.meta.get_field("fiscal_year"):
Rohan Bansal1e3a3b22021-05-26 15:18:10 +0530340 date_field = None
Nabin Haitcfecd2b2013-07-11 17:49:18 +0530341 if self.meta.get_field("posting_date"):
342 date_field = "posting_date"
343 elif self.meta.get_field("transaction_date"):
344 date_field = "transaction_date"
Anand Doshid2946502014-04-08 20:10:03 +0530345
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530346 if date_field and self.get(date_field):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530347 validate_fiscal_year(
348 self.get(date_field), self.fiscal_year, self.company, self.meta.get_label(date_field), self
349 )
Anand Doshid2946502014-04-08 20:10:03 +0530350
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530351 def validate_party_accounts(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530352 if self.doctype not in ("Sales Invoice", "Purchase Invoice"):
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530353 return
354
Ankush Menat494bd9e2022-03-28 18:52:46 +0530355 if self.doctype == "Sales Invoice":
356 party_account_field = "debit_to"
357 item_field = "income_account"
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530358 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530359 party_account_field = "credit_to"
360 item_field = "expense_account"
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530361
Ankush Menat494bd9e2022-03-28 18:52:46 +0530362 for item in self.get("items"):
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530363 if item.get(item_field) == self.get(party_account_field):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530364 frappe.throw(
365 _("Row {0}: {1} {2} cannot be same as {3} (Party Account) {4}").format(
366 item.idx,
367 frappe.bold(frappe.unscrub(item_field)),
368 item.get(item_field),
369 frappe.bold(frappe.unscrub(party_account_field)),
370 self.get(party_account_field),
371 )
372 )
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530373
Deepesh Gargb4be2922021-01-28 13:09:56 +0530374 def validate_inter_company_reference(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530375 if self.doctype not in ("Purchase Invoice", "Purchase Receipt", "Purchase Order"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530376 return
377
378 if self.is_internal_transfer():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530379 if not (
380 self.get("inter_company_reference")
381 or self.get("inter_company_invoice_reference")
382 or self.get("inter_company_order_reference")
383 ):
Deepesh Garg4c8d15b2021-04-26 15:24:34 +0530384 msg = _("Internal Sale or Delivery Reference missing.")
Deepesh Gargb4be2922021-01-28 13:09:56 +0530385 msg += _("Please create purchase from internal sale or delivery document itself")
386 frappe.throw(msg, title=_("Internal Sales Reference Missing"))
387
Ankush Menat3714e362022-05-16 18:09:14 +0530388 def disable_pricing_rule_on_internal_transfer(self):
389 if not self.get("ignore_pricing_rule") and self.is_internal_transfer():
390 self.ignore_pricing_rule = 1
391 frappe.msgprint(
392 _("Disabled pricing rules since this {} is an internal transfer").format(self.doctype),
393 alert=1,
394 )
395
Nabin Haite9daefe2014-08-27 16:46:33 +0530396 def validate_due_date(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530397 if self.get("is_pos"):
398 return
rohitwaghchaureea943c62018-07-06 12:28:58 +0530399
Nabin Haite9daefe2014-08-27 16:46:33 +0530400 from erpnext.accounts.party import validate_due_date
Ankush Menat494bd9e2022-03-28 18:52:46 +0530401
Nabin Haite9daefe2014-08-27 16:46:33 +0530402 if self.doctype == "Sales Invoice":
Nabin Hait04d244a2015-07-22 17:47:49 +0530403 if not self.due_date:
404 frappe.throw(_("Due Date is mandatory"))
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530405
Ankush Menat494bd9e2022-03-28 18:52:46 +0530406 validate_due_date(
407 self.posting_date,
408 self.due_date,
409 "Customer",
410 self.customer,
411 self.company,
412 self.payment_terms_template,
413 )
Nabin Haite9daefe2014-08-27 16:46:33 +0530414 elif self.doctype == "Purchase Invoice":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530415 validate_due_date(
416 self.bill_date or self.posting_date,
417 self.due_date,
418 "Supplier",
419 self.supplier,
420 self.company,
421 self.bill_date,
422 self.payment_terms_template,
423 )
Nabin Haite9daefe2014-08-27 16:46:33 +0530424
Nabin Hait096d3632013-10-17 17:01:14 +0530425 def set_price_list_currency(self, buying_or_selling):
Nabin Hait1cc55fb2016-12-08 14:09:23 +0530426 if self.meta.get_field("posting_date"):
Nabin Hait288a18e2016-12-08 15:36:23 +0530427 transaction_date = self.posting_date
Nabin Hait1cc55fb2016-12-08 14:09:23 +0530428 else:
Nabin Hait288a18e2016-12-08 15:36:23 +0530429 transaction_date = self.transaction_date
Rushabh Mehta66958302017-01-16 16:57:53 +0530430
Rushabh Mehta4a404e92013-08-09 18:11:35 +0530431 if self.meta.get_field("currency"):
Nabin Hait7a75e102013-09-17 10:21:20 +0530432 # price list part
Shreya3f778522018-05-15 16:59:20 +0530433 if buying_or_selling.lower() == "selling":
434 fieldname = "selling_price_list"
435 args = "for_selling"
436 else:
437 fieldname = "buying_price_list"
438 args = "for_buying"
439
Anand Doshif78d1ae2014-03-28 13:55:00 +0530440 if self.meta.get_field(fieldname) and self.get(fieldname):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530441 self.price_list_currency = frappe.db.get_value("Price List", self.get(fieldname), "currency")
Anand Doshid2946502014-04-08 20:10:03 +0530442
Nabin Hait6e439a52015-08-28 19:24:22 +0530443 if self.price_list_currency == self.company_currency:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530444 self.plc_conversion_rate = 1.0
Nabin Hait11f41952013-09-24 14:36:55 +0530445
Anand Doshif78d1ae2014-03-28 13:55:00 +0530446 elif not self.plc_conversion_rate:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530447 self.plc_conversion_rate = get_exchange_rate(
448 self.price_list_currency, self.company_currency, transaction_date, args
449 )
Anand Doshid2946502014-04-08 20:10:03 +0530450
Nabin Hait7a75e102013-09-17 10:21:20 +0530451 # currency
Anand Doshif78d1ae2014-03-28 13:55:00 +0530452 if not self.currency:
453 self.currency = self.price_list_currency
454 self.conversion_rate = self.plc_conversion_rate
Nabin Hait6e439a52015-08-28 19:24:22 +0530455 elif self.currency == self.company_currency:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530456 self.conversion_rate = 1.0
457 elif not self.conversion_rate:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530458 self.conversion_rate = get_exchange_rate(
459 self.currency, self.company_currency, transaction_date, args
460 )
Nabin Hait7a75e102013-09-17 10:21:20 +0530461
Nabin Haitcccc45e2016-10-05 17:15:43 +0530462 def set_missing_item_details(self, for_validate=False):
Anand Doshi3543f302013-05-24 19:25:01 +0530463 """set missing item values"""
Nabin Haitf37d43d2017-07-18 12:14:42 +0530464 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530465
Nabin Haitdd38a262014-12-26 13:15:21 +0530466 if hasattr(self, "items"):
Nabin Hait444f9562014-06-20 15:59:49 +0530467 parent_dict = {}
Pratik Vyasf7daab72014-04-10 17:53:30 +0530468 for fieldname in self.meta.get_valid_columns():
469 parent_dict[fieldname] = self.get(fieldname)
470
mbauskara52472c2016-03-05 15:10:25 +0530471 if self.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
472 document_type = "{} Item".format(self.doctype)
mbauskarc97becb2016-01-18 16:28:21 +0530473 parent_dict.update({"document_type": document_type})
474
Nabin Hait34c551d2019-07-03 10:34:31 +0530475 # party_name field used for customer in quotation
Ankush Menat494bd9e2022-03-28 18:52:46 +0530476 if (
477 self.doctype == "Quotation"
478 and self.quotation_to == "Customer"
479 and parent_dict.get("party_name")
480 ):
Nabin Hait34c551d2019-07-03 10:34:31 +0530481 parent_dict.update({"customer": parent_dict.get("party_name")})
482
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530483 self.pricing_rules = []
Nabin Haitdd38a262014-12-26 13:15:21 +0530484 for item in self.get("items"):
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530485 if item.get("item_code"):
Nabin Hait444f9562014-06-20 15:59:49 +0530486 args = parent_dict.copy()
487 args.update(item.as_dict())
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530488
Nabin Hait34d28222016-01-19 15:45:49 +0530489 args["doctype"] = self.doctype
490 args["name"] = self.name
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530491 args["child_docname"] = item.name
Ankush Menat494bd9e2022-03-28 18:52:46 +0530492 args["ignore_pricing_rule"] = (
493 self.ignore_pricing_rule if hasattr(self, "ignore_pricing_rule") else 0
494 )
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530495
Nabin Haite2f054c2015-03-09 14:54:37 +0530496 if not args.get("transaction_date"):
497 args["transaction_date"] = args.get("posting_date")
Anand Doshi2b2b6392015-03-20 14:18:09 +0530498
499 if self.get("is_subcontracted"):
500 args["is_subcontracted"] = self.is_subcontracted
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530501
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530502 ret = get_item_details(args, self, for_validate=True, overwrite_warehouse=False)
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530503
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530504 for fieldname, value in ret.items():
Anand Doshi602e8252015-11-16 19:05:46 +0530505 if item.meta.get_field(fieldname) and value is not None:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530506 if item.get(fieldname) is None or fieldname in force_item_fields:
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530507 item.set(fieldname, value)
Anand Doshid2946502014-04-08 20:10:03 +0530508
Ankush Menat494bd9e2022-03-28 18:52:46 +0530509 elif fieldname in ["cost_center", "conversion_factor"] and not item.get(fieldname):
Anand Doshi602e8252015-11-16 19:05:46 +0530510 item.set(fieldname, value)
511
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530512 elif fieldname == "serial_no":
Alchez9155e402018-07-09 16:57:42 +0530513 # Ensure that serial numbers are matched against Stock UOM
514 item_conversion_factor = item.get("conversion_factor") or 1.0
515 item_qty = abs(item.get("qty")) * item_conversion_factor
Alchez8f2a0f32018-07-06 14:36:52 +0530516
Ankush Menat494bd9e2022-03-28 18:52:46 +0530517 if item_qty != len(get_serial_nos(item.get("serial_no"))):
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530518 item.set(fieldname, value)
Nabin Haita74468b2014-12-30 18:33:52 +0530519
Saqib Ansariab36b272022-02-09 10:10:17 +0530520 elif (
521 ret.get("pricing_rule_removed")
522 and value is not None
523 and fieldname
524 in [
525 "discount_percentage",
526 "discount_amount",
527 "rate",
528 "margin_rate_or_amount",
529 "margin_type",
530 "remove_free_item",
531 ]
532 ):
Saqib Ansarib8c41e32022-01-20 13:06:08 +0530533 # reset pricing rule fields if pricing_rule_removed
534 item.set(fieldname, value)
535
Ankush Menat494bd9e2022-03-28 18:52:46 +0530536 if self.doctype in ["Purchase Invoice", "Sales Invoice"] and item.meta.get_field(
537 "is_fixed_asset"
538 ):
539 item.set("is_fixed_asset", ret.get("is_fixed_asset", 0))
Rohit Waghchauref6f503a2018-12-19 15:06:44 +0530540
Deepesh Garga60c3082021-05-11 16:38:33 +0530541 # Double check for cost center
542 # Items add via promotional scheme may not have cost center set
Ankush Menat494bd9e2022-03-28 18:52:46 +0530543 if hasattr(item, "cost_center") and not item.get("cost_center"):
544 item.set(
545 "cost_center", self.get("cost_center") or erpnext.get_default_cost_center(self.company)
546 )
Deepesh Garga60c3082021-05-11 16:38:33 +0530547
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530548 if ret.get("pricing_rules"):
549 self.apply_pricing_rule_on_items(item, ret)
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530550 self.set_pricing_rule_details(item, ret)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530551
Nabin Hait14aa9c52016-04-18 15:54:01 +0530552 if self.doctype == "Purchase Invoice":
Nabin Haitcccc45e2016-10-05 17:15:43 +0530553 self.set_expense_account(for_validate)
Nabin Haita3dd72a2014-05-28 12:49:20 +0530554
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530555 def apply_pricing_rule_on_items(self, item, pricing_rule_args):
556 if not pricing_rule_args.get("validate_applied_rule", 0):
557 # if user changed the discount percentage then set user's discount percentage ?
Ankush Menat494bd9e2022-03-28 18:52:46 +0530558 if pricing_rule_args.get("price_or_product_discount") == "Price":
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530559 item.set("pricing_rules", pricing_rule_args.get("pricing_rules"))
560 item.set("discount_percentage", pricing_rule_args.get("discount_percentage"))
561 item.set("discount_amount", pricing_rule_args.get("discount_amount"))
562 if pricing_rule_args.get("pricing_rule_for") == "Rate":
563 item.set("price_list_rate", pricing_rule_args.get("price_list_rate"))
564
565 if item.get("price_list_rate"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530566 item.rate = flt(
567 item.price_list_rate * (1.0 - (flt(item.discount_percentage) / 100.0)),
568 item.precision("rate"),
569 )
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530570
Ankush Menat494bd9e2022-03-28 18:52:46 +0530571 if item.get("discount_amount"):
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530572 item.rate = item.price_list_rate - item.discount_amount
573
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530574 if item.get("apply_discount_on_discounted_rate") and pricing_rule_args.get("rate"):
575 item.rate = pricing_rule_args.get("rate")
576
Ankush Menat494bd9e2022-03-28 18:52:46 +0530577 elif pricing_rule_args.get("free_item_data"):
578 apply_pricing_rule_for_free_items(self, pricing_rule_args.get("free_item_data"))
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530579
580 elif pricing_rule_args.get("validate_applied_rule"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530581 for pricing_rule in get_applied_pricing_rules(item.get("pricing_rules")):
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530582 pricing_rule_doc = frappe.get_cached_doc("Pricing Rule", pricing_rule)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530583 for field in ["discount_percentage", "discount_amount", "rate"]:
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530584 if item.get(field) < pricing_rule_doc.get(field):
585 title = get_link_to_form("Pricing Rule", pricing_rule)
586
Ankush Menat494bd9e2022-03-28 18:52:46 +0530587 frappe.msgprint(
588 _("Row {0}: user has not applied the rule {1} on the item {2}").format(
589 item.idx, frappe.bold(title), frappe.bold(item.item_code)
590 )
591 )
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530592
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530593 def set_pricing_rule_details(self, item_row, args):
594 pricing_rules = get_applied_pricing_rules(args.get("pricing_rules"))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530595 if not pricing_rules:
596 return
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530597
598 for pricing_rule in pricing_rules:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530599 self.append(
600 "pricing_rules",
601 {
602 "pricing_rule": pricing_rule,
603 "item_code": item_row.item_code,
604 "child_docname": item_row.name,
605 "rule_applied": True,
606 },
607 )
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530608
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530609 def set_taxes(self):
610 if not self.meta.get_field("taxes"):
Anand Doshi3543f302013-05-24 19:25:01 +0530611 return
Anand Doshid2946502014-04-08 20:10:03 +0530612
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530613 tax_master_doctype = self.meta.get_field("taxes_and_charges").options
Anand Doshid2946502014-04-08 20:10:03 +0530614
rohitwaghchaure57914f12018-04-24 19:19:47 +0530615 if (self.is_new() or self.is_pos_profile_changed()) and not self.get("taxes"):
rohitwaghchaure505661b2017-12-11 14:52:28 +0530616 if self.company and not self.get("taxes_and_charges"):
Anand Doshi3543f302013-05-24 19:25:01 +0530617 # get the default tax master
Ankush Menat494bd9e2022-03-28 18:52:46 +0530618 self.taxes_and_charges = frappe.db.get_value(
619 tax_master_doctype, {"is_default": 1, "company": self.company}
620 )
Anand Doshid2946502014-04-08 20:10:03 +0530621
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530622 self.append_taxes_from_master(tax_master_doctype)
Anand Doshid2946502014-04-08 20:10:03 +0530623
rohitwaghchaure57914f12018-04-24 19:19:47 +0530624 def is_pos_profile_changed(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530625 if (
626 self.doctype == "Sales Invoice"
627 and self.is_pos
628 and self.pos_profile != frappe.db.get_value("Sales Invoice", self.name, "pos_profile")
629 ):
rohitwaghchaure57914f12018-04-24 19:19:47 +0530630 return True
631
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530632 def append_taxes_from_master(self, tax_master_doctype=None):
633 if self.get("taxes_and_charges"):
Anand Doshi99100a42013-07-04 17:13:53 +0530634 if not tax_master_doctype:
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530635 tax_master_doctype = self.meta.get_field("taxes_and_charges").options
Anand Doshid2946502014-04-08 20:10:03 +0530636
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530637 self.extend("taxes", get_taxes_and_charges(tax_master_doctype, self.get("taxes_and_charges")))
Akhilesh Darjee4cdb7992014-01-30 13:56:57 +0530638
Anand Doshiac32bad2014-04-18 01:30:14 +0530639 def set_other_charges(self):
Nabin Haite7d15362014-12-25 16:01:55 +0530640 self.set("taxes", [])
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530641 self.set_taxes()
Anand Doshid2946502014-04-08 20:10:03 +0530642
ankitjavalkarwork6c29d872014-10-06 13:20:53 +0530643 def validate_enabled_taxes_and_charges(self):
644 taxes_and_charges_doctype = self.meta.get_options("taxes_and_charges")
645 if frappe.db.get_value(taxes_and_charges_doctype, self.taxes_and_charges, "disabled"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530646 frappe.throw(
647 _("{0} '{1}' is disabled").format(taxes_and_charges_doctype, self.taxes_and_charges)
648 )
ankitjavalkarwork6c29d872014-10-06 13:20:53 +0530649
Nabin Haita2426fc2018-01-15 17:45:46 +0530650 def validate_tax_account_company(self):
651 for d in self.get("taxes"):
652 if d.account_head:
653 tax_account_company = frappe.db.get_value("Account", d.account_head, "company")
654 if tax_account_company != self.company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530655 frappe.throw(
656 _("Row #{0}: Account {1} does not belong to company {2}").format(
657 d.idx, d.account_head, self.company
658 )
659 )
Nabin Haita2426fc2018-01-15 17:45:46 +0530660
deepeshgarg0073d11ac02019-05-19 00:02:01 +0530661 def get_gl_dict(self, args, account_currency=None, item=None):
Nabin Hait2df4d542013-01-29 11:34:39 +0530662 """this method populates the common properties of a gl entry record"""
Rushabh Mehta2cb7a9f2016-06-15 16:45:03 +0530663
Ankush Menat494bd9e2022-03-28 18:52:46 +0530664 posting_date = args.get("posting_date") or self.get("posting_date")
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530665 fiscal_years = get_fiscal_years(posting_date, company=self.company)
Nabin Hait2ed0b592016-03-29 13:14:17 +0530666 if len(fiscal_years) > 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530667 frappe.throw(
668 _("Multiple fiscal years exist for the date {0}. Please set company in Fiscal Year").format(
669 formatdate(posting_date)
670 )
671 )
Nabin Hait2ed0b592016-03-29 13:14:17 +0530672 else:
673 fiscal_year = fiscal_years[0][0]
Rushabh Mehta2cb7a9f2016-06-15 16:45:03 +0530674
Ankush Menat494bd9e2022-03-28 18:52:46 +0530675 gl_dict = frappe._dict(
676 {
677 "company": self.company,
678 "posting_date": posting_date,
679 "fiscal_year": fiscal_year,
680 "voucher_type": self.doctype,
681 "voucher_no": self.name,
682 "remarks": self.get("remarks") or self.get("remark"),
683 "debit": 0,
684 "credit": 0,
685 "debit_in_account_currency": 0,
686 "credit_in_account_currency": 0,
687 "is_opening": self.get("is_opening") or "No",
688 "party_type": None,
689 "party": None,
690 "project": self.get("project"),
691 "post_net_value": args.get("post_net_value"),
692 }
693 )
deepeshgarg007d83cf652019-05-12 18:34:23 +0530694
695 accounting_dimensions = get_accounting_dimensions()
696 dimension_dict = frappe._dict()
697
698 for dimension in accounting_dimensions:
699 dimension_dict[dimension] = self.get(dimension)
deepeshgarg0073d11ac02019-05-19 00:02:01 +0530700 if item and item.get(dimension):
701 dimension_dict[dimension] = item.get(dimension)
deepeshgarg007d83cf652019-05-12 18:34:23 +0530702
703 gl_dict.update(dimension_dict)
Nabin Hait2df4d542013-01-29 11:34:39 +0530704 gl_dict.update(args)
Anand Doshi979326b2015-09-11 16:22:37 +0530705
Nabin Hait895029d2015-08-20 14:55:39 +0530706 if not account_currency:
Anand Doshicd0989e2015-09-28 13:31:17 +0530707 account_currency = get_account_currency(gl_dict.account)
Anand Doshi979326b2015-09-11 16:22:37 +0530708
Ankush Menat494bd9e2022-03-28 18:52:46 +0530709 if gl_dict.account and self.doctype not in [
710 "Journal Entry",
711 "Period Closing Voucher",
712 "Payment Entry",
713 "Purchase Receipt",
714 "Purchase Invoice",
715 "Stock Entry",
716 ]:
Anand Doshibe6cfdd2015-09-17 21:07:04 +0530717 self.validate_account_currency(gl_dict.account, account_currency)
Deepesh Garg7c300852020-12-26 20:14:51 +0530718
Ankush Menat494bd9e2022-03-28 18:52:46 +0530719 if gl_dict.account and self.doctype not in [
720 "Journal Entry",
721 "Period Closing Voucher",
722 "Payment Entry",
723 ]:
724 set_balance_in_account_currency(
725 gl_dict, account_currency, self.get("conversion_rate"), self.company_currency
726 )
Anand Doshi979326b2015-09-11 16:22:37 +0530727
Nabin Haitc561a492015-08-19 19:22:34 +0530728 return gl_dict
Anand Doshi979326b2015-09-11 16:22:37 +0530729
Anurag Mishrae657fe82018-11-26 15:19:17 +0530730 def validate_qty_is_not_zero(self):
Maricac68a9402019-12-03 12:59:22 +0530731 if self.doctype != "Purchase Receipt":
732 for item in self.items:
733 if not item.qty:
734 frappe.throw(_("Item quantity can not be zero"))
Anurag Mishrae657fe82018-11-26 15:19:17 +0530735
Nabin Hait895029d2015-08-20 14:55:39 +0530736 def validate_account_currency(self, account, account_currency=None):
Nabin Hait6e439a52015-08-28 19:24:22 +0530737 valid_currency = [self.company_currency]
738 if self.get("currency") and self.currency != self.company_currency:
739 valid_currency.append(self.currency)
740
Nabin Hait895029d2015-08-20 14:55:39 +0530741 if account_currency not in valid_currency:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530742 frappe.throw(
743 _("Account {0} is invalid. Account Currency must be {1}").format(
744 account, (" " + _("or") + " ").join(valid_currency)
745 )
746 )
Anand Doshi979326b2015-09-11 16:22:37 +0530747
Anand Doshi613cb6a2013-02-06 17:33:46 +0530748 def clear_unallocated_advances(self, childtype, parentfield):
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530749 self.set(parentfield, self.get(parentfield, {"allocated_amount": ["not in", [0, None, ""]]}))
750
Ankush Menat494bd9e2022-03-28 18:52:46 +0530751 frappe.db.sql(
752 """delete from `tab%s` where parentfield=%s and parent = %s
753 and allocated_amount = 0"""
754 % (childtype, "%s", "%s"),
755 (parentfield, self.name),
756 )
Anand Doshid2946502014-04-08 20:10:03 +0530757
Walstan Baptistad6360752021-03-31 12:30:32 +0530758 @frappe.whitelist()
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530759 def apply_shipping_rule(self):
760 if self.shipping_rule:
761 shipping_rule = frappe.get_doc("Shipping Rule", self.shipping_rule)
762 shipping_rule.apply(self)
763 self.calculate_taxes_and_totals()
764
765 def get_shipping_address(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530766 """Returns Address object from shipping address fields if present"""
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530767
768 # shipping address fields can be `shipping_address_name` or `shipping_address`
769 # try getting value from both
770
Ankush Menat494bd9e2022-03-28 18:52:46 +0530771 for fieldname in ("shipping_address_name", "shipping_address"):
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530772 shipping_field = self.meta.get_field(fieldname)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530773 if shipping_field and shipping_field.fieldtype == "Link":
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530774 if self.get(fieldname):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530775 return frappe.get_doc("Address", self.get(fieldname))
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530776
777 return {}
778
Walstan Baptistad6360752021-03-31 12:30:32 +0530779 @frappe.whitelist()
Nabin Hait041a5c22018-08-01 18:07:39 +0530780 def set_advances(self):
781 """Returns list of advances against Account, Party, Reference"""
782
783 res = self.get_advance_entries()
784
785 self.set("advances", [])
786 advance_allocated = 0
787 for d in res:
788 if d.against_order:
789 allocated_amount = flt(d.amount)
790 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530791 if self.get("party_account_currency") == self.company_currency:
792 amount = self.get("base_rounded_total") or self.base_grand_total
Deepesh Garg26210162020-08-11 16:06:13 +0530793 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530794 amount = self.get("rounded_total") or self.grand_total
Deepesh Garg26210162020-08-11 16:06:13 +0530795
Rohit Waghchaure6cc2f522018-11-27 12:07:03 +0530796 allocated_amount = min(amount - advance_allocated, d.amount)
Nabin Hait041a5c22018-08-01 18:07:39 +0530797 advance_allocated += flt(allocated_amount)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530798
Saqiba20999c2021-07-12 14:33:23 +0530799 advance_row = {
Nabin Hait041a5c22018-08-01 18:07:39 +0530800 "doctype": self.doctype + " Advance",
801 "reference_type": d.reference_type,
802 "reference_name": d.reference_name,
803 "reference_row": d.reference_row,
804 "remarks": d.remarks,
805 "advance_amount": flt(d.amount),
Saqiba20999c2021-07-12 14:33:23 +0530806 "allocated_amount": allocated_amount,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530807 "ref_exchange_rate": flt(d.exchange_rate), # exchange_rate of advance entry
Saqiba20999c2021-07-12 14:33:23 +0530808 }
809
810 self.append("advances", advance_row)
Nabin Hait041a5c22018-08-01 18:07:39 +0530811
Nabin Hait28a05282016-06-27 17:41:39 +0530812 def get_advance_entries(self, include_unallocated=True):
813 if self.doctype == "Sales Invoice":
814 party_account = self.debit_to
815 party_type = "Customer"
816 party = self.customer
817 amount_field = "credit_in_account_currency"
818 order_field = "sales_order"
819 order_doctype = "Sales Order"
820 else:
821 party_account = self.credit_to
822 party_type = "Supplier"
823 party = self.supplier
824 amount_field = "debit_in_account_currency"
825 order_field = "purchase_order"
826 order_doctype = "Purchase Order"
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530827
Ankush Menat494bd9e2022-03-28 18:52:46 +0530828 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 +0530829
Ankush Menat494bd9e2022-03-28 18:52:46 +0530830 journal_entries = get_advance_journal_entries(
831 party_type, party, party_account, amount_field, order_doctype, order_list, include_unallocated
832 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530833
Ankush Menat494bd9e2022-03-28 18:52:46 +0530834 payment_entries = get_advance_payment_entries(
835 party_type, party, party_account, order_doctype, order_list, include_unallocated
836 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530837
Nabin Hait28a05282016-06-27 17:41:39 +0530838 res = journal_entries + payment_entries
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530839
Nabin Hait28a05282016-06-27 17:41:39 +0530840 return res
Nabin Hait48f5fa62014-09-18 15:03:54 +0530841
rohitwaghchaurebf4c1142018-01-08 15:20:15 +0530842 def is_inclusive_tax(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530843 is_inclusive = cint(
844 frappe.db.get_single_value("Accounts Settings", "show_inclusive_tax_in_print")
845 )
rohitwaghchaurebf4c1142018-01-08 15:20:15 +0530846
847 if is_inclusive:
848 is_inclusive = 0
849 if self.get("taxes", filters={"included_in_print_rate": 1}):
850 is_inclusive = 1
851
852 return is_inclusive
853
Nabin Hait28a05282016-06-27 17:41:39 +0530854 def validate_advance_entries(self):
Nabin Hait05aefbb2016-06-28 19:42:19 +0530855 order_field = "sales_order" if self.doctype == "Sales Invoice" else "purchase_order"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530856 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 +0530857
Ankush Menat494bd9e2022-03-28 18:52:46 +0530858 if not order_list:
859 return
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530860
Nabin Hait28a05282016-06-27 17:41:39 +0530861 advance_entries = self.get_advance_entries(include_unallocated=False)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530862
Nabin Hait28a05282016-06-27 17:41:39 +0530863 if advance_entries:
864 advance_entries_against_si = [d.reference_name for d in self.get("advances")]
865 for d in advance_entries:
866 if not advance_entries_against_si or d.reference_name not in advance_entries_against_si:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530867 frappe.msgprint(
868 _(
869 "Payment Entry {0} is linked against Order {1}, check if it should be pulled as advance in this invoice."
870 ).format(d.reference_name, d.against_order)
871 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530872
Saqiba20999c2021-07-12 14:33:23 +0530873 def set_advance_gain_or_loss(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530874 if self.get("conversion_rate") == 1 or not self.get("advances"):
Saqib Ansari64efe8b2021-09-26 15:46:13 +0530875 return
876
Ankush Menat494bd9e2022-03-28 18:52:46 +0530877 is_purchase_invoice = self.doctype == "Purchase Invoice"
Saqib Ansari64efe8b2021-09-26 15:46:13 +0530878 party_account = self.credit_to if is_purchase_invoice else self.debit_to
879 if get_account_currency(party_account) != self.currency:
Saqiba20999c2021-07-12 14:33:23 +0530880 return
881
882 for d in self.get("advances"):
883 advance_exchange_rate = d.ref_exchange_rate
Ankush Menat494bd9e2022-03-28 18:52:46 +0530884 if d.allocated_amount and self.conversion_rate != advance_exchange_rate:
Saqiba20999c2021-07-12 14:33:23 +0530885
886 base_allocated_amount_in_ref_rate = advance_exchange_rate * d.allocated_amount
887 base_allocated_amount_in_inv_rate = self.conversion_rate * d.allocated_amount
888 difference = base_allocated_amount_in_ref_rate - base_allocated_amount_in_inv_rate
889
890 d.exchange_gain_loss = difference
891
892 def make_exchange_gain_loss_gl_entries(self, gl_entries):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530893 if self.get("doctype") in ["Purchase Invoice", "Sales Invoice"]:
Saqiba20999c2021-07-12 14:33:23 +0530894 for d in self.get("advances"):
895 if d.exchange_gain_loss:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530896 is_purchase_invoice = self.get("doctype") == "Purchase Invoice"
Saqibd4ae1fe2021-07-30 11:21:49 +0530897 party = self.supplier if is_purchase_invoice else self.customer
898 party_account = self.credit_to if is_purchase_invoice else self.debit_to
899 party_type = "Supplier" if is_purchase_invoice else "Customer"
Saqiba20999c2021-07-12 14:33:23 +0530900
Ankush Menat494bd9e2022-03-28 18:52:46 +0530901 gain_loss_account = frappe.db.get_value("Company", self.company, "exchange_gain_loss_account")
Saqibd4ae1fe2021-07-30 11:21:49 +0530902 if not gain_loss_account:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530903 frappe.throw(
904 _("Please set default Exchange Gain/Loss Account in Company {}").format(self.get("company"))
905 )
Saqiba20999c2021-07-12 14:33:23 +0530906 account_currency = get_account_currency(gain_loss_account)
907 if account_currency != self.company_currency:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530908 frappe.throw(
909 _("Currency for {0} must be {1}").format(gain_loss_account, self.company_currency)
910 )
Saqiba20999c2021-07-12 14:33:23 +0530911
912 # for purchase
Ankush Menat494bd9e2022-03-28 18:52:46 +0530913 dr_or_cr = "debit" if d.exchange_gain_loss > 0 else "credit"
Saqibd4ae1fe2021-07-30 11:21:49 +0530914 if not is_purchase_invoice:
915 # just reverse for sales?
Ankush Menat494bd9e2022-03-28 18:52:46 +0530916 dr_or_cr = "debit" if dr_or_cr == "credit" else "credit"
Saqiba20999c2021-07-12 14:33:23 +0530917
918 gl_entries.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530919 self.get_gl_dict(
920 {
921 "account": gain_loss_account,
922 "account_currency": account_currency,
923 "against": party,
924 dr_or_cr + "_in_account_currency": abs(d.exchange_gain_loss),
925 dr_or_cr: abs(d.exchange_gain_loss),
926 "cost_center": self.cost_center or erpnext.get_default_cost_center(self.company),
927 "project": self.project,
928 },
929 item=d,
930 )
Saqiba20999c2021-07-12 14:33:23 +0530931 )
932
Ankush Menat494bd9e2022-03-28 18:52:46 +0530933 dr_or_cr = "debit" if dr_or_cr == "credit" else "credit"
Saqiba20999c2021-07-12 14:33:23 +0530934
935 gl_entries.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530936 self.get_gl_dict(
937 {
938 "account": party_account,
939 "party_type": party_type,
940 "party": party,
941 "against": gain_loss_account,
942 dr_or_cr + "_in_account_currency": flt(abs(d.exchange_gain_loss) / self.conversion_rate),
943 dr_or_cr: abs(d.exchange_gain_loss),
944 "cost_center": self.cost_center,
945 "project": self.project,
946 },
947 self.party_account_currency,
948 item=self,
949 )
Saqiba20999c2021-07-12 14:33:23 +0530950 )
951
Nabin Hait28a05282016-06-27 17:41:39 +0530952 def update_against_document_in_jv(self):
953 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530954 Links invoice and advance voucher:
955 1. cancel advance voucher
956 2. split into multiple rows if partially adjusted, assign against voucher
957 3. submit advance voucher
Nabin Hait28a05282016-06-27 17:41:39 +0530958 """
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530959
Nabin Hait28a05282016-06-27 17:41:39 +0530960 if self.doctype == "Sales Invoice":
Nabin Haitff2f3ef2016-07-04 11:41:14 +0530961 party_type = "Customer"
Nabin Hait28a05282016-06-27 17:41:39 +0530962 party = self.customer
963 party_account = self.debit_to
964 dr_or_cr = "credit_in_account_currency"
965 else:
Nabin Haitff2f3ef2016-07-04 11:41:14 +0530966 party_type = "Supplier"
Nabin Hait28a05282016-06-27 17:41:39 +0530967 party = self.supplier
968 party_account = self.credit_to
969 dr_or_cr = "debit_in_account_currency"
Nabin Hait48f5fa62014-09-18 15:03:54 +0530970
Nabin Hait28a05282016-06-27 17:41:39 +0530971 lst = []
Ankush Menat494bd9e2022-03-28 18:52:46 +0530972 for d in self.get("advances"):
Nabin Hait28a05282016-06-27 17:41:39 +0530973 if flt(d.allocated_amount) > 0:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530974 args = frappe._dict(
975 {
976 "voucher_type": d.reference_type,
977 "voucher_no": d.reference_name,
978 "voucher_detail_no": d.reference_row,
979 "against_voucher_type": self.doctype,
980 "against_voucher": self.name,
981 "account": party_account,
982 "party_type": party_type,
983 "party": party,
984 "is_advance": "Yes",
985 "dr_or_cr": dr_or_cr,
986 "unadjusted_amount": flt(d.advance_amount),
987 "allocated_amount": flt(d.allocated_amount),
988 "precision": d.precision("advance_amount"),
989 "exchange_rate": (
990 self.conversion_rate if self.party_account_currency != self.company_currency else 1
991 ),
992 "grand_total": (
993 self.base_grand_total
994 if self.party_account_currency == self.company_currency
995 else self.grand_total
996 ),
997 "outstanding_amount": self.outstanding_amount,
998 "difference_account": frappe.db.get_value(
999 "Company", self.company, "exchange_gain_loss_account"
1000 ),
1001 "exchange_gain_loss": flt(d.get("exchange_gain_loss")),
1002 }
1003 )
Nabin Hait28a05282016-06-27 17:41:39 +05301004 lst.append(args)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301005
Nabin Hait28a05282016-06-27 17:41:39 +05301006 if lst:
1007 from erpnext.accounts.utils import reconcile_against_document
Ankush Menat494bd9e2022-03-28 18:52:46 +05301008
Nabin Hait28a05282016-06-27 17:41:39 +05301009 reconcile_against_document(lst)
Anand Doshid2946502014-04-08 20:10:03 +05301010
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +05301011 def on_cancel(self):
1012 from erpnext.accounts.utils import unlink_ref_doc_from_payment_entries
1013
1014 if self.doctype in ["Sales Invoice", "Purchase Invoice"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301015 if frappe.db.get_single_value("Accounts Settings", "unlink_payment_on_cancellation_of_invoice"):
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +05301016 unlink_ref_doc_from_payment_entries(self)
1017
1018 elif self.doctype in ["Sales Order", "Purchase Order"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301019 if frappe.db.get_single_value(
1020 "Accounts Settings", "unlink_advance_payment_on_cancelation_of_order"
1021 ):
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +05301022 unlink_ref_doc_from_payment_entries(self)
1023
GangaManoj8396f242021-09-20 19:01:46 +05301024 if self.doctype == "Sales Order":
1025 self.unlink_ref_doc_from_po()
1026
1027 def unlink_ref_doc_from_po(self):
GangaManoj8396f242021-09-20 19:01:46 +05301028 so_items = []
1029 for item in self.items:
1030 so_items.append(item.name)
1031
Ankush Menat494bd9e2022-03-28 18:52:46 +05301032 linked_po = list(
1033 set(
1034 frappe.get_all(
1035 "Purchase Order Item",
1036 filters={
1037 "sales_order": self.name,
1038 "sales_order_item": ["in", so_items],
1039 "docstatus": ["<", 2],
1040 },
1041 pluck="parent",
1042 )
1043 )
1044 )
GangaManoj8396f242021-09-20 19:01:46 +05301045
GangaManoj8396f242021-09-20 19:01:46 +05301046 if linked_po:
GangaManoje77534f2021-09-20 19:01:46 +05301047 frappe.db.set_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301048 "Purchase Order Item",
1049 {"sales_order": self.name, "sales_order_item": ["in", so_items], "docstatus": ["<", 2]},
1050 {"sales_order": None, "sales_order_item": None},
GangaManoje77534f2021-09-20 19:01:46 +05301051 )
GangaManoj8396f242021-09-20 19:01:46 +05301052
1053 frappe.msgprint(_("Purchase Orders {0} are un-linked").format("\n".join(linked_po)))
1054
Deepesh Gargd18dde72020-11-29 21:40:04 +05301055 def get_tax_map(self):
1056 tax_map = {}
Ankush Menat494bd9e2022-03-28 18:52:46 +05301057 for tax in self.get("taxes"):
Deepesh Gargd18dde72020-11-29 21:40:04 +05301058 tax_map.setdefault(tax.account_head, 0.0)
1059 tax_map[tax.account_head] += tax.tax_amount
1060
1061 return tax_map
1062
Deepesh Garg92f7a5a2021-07-21 15:25:40 +05301063 def get_amount_and_base_amount(self, item, enable_discount_accounting):
1064 amount = item.net_amount
1065 base_amount = item.base_net_amount
1066
Ankush Menat494bd9e2022-03-28 18:52:46 +05301067 if (
1068 enable_discount_accounting
1069 and self.get("discount_amount")
1070 and self.get("additional_discount_account")
1071 ):
Deepesh Garg92f7a5a2021-07-21 15:25:40 +05301072 amount = item.amount
1073 base_amount = item.base_amount
1074
1075 return amount, base_amount
1076
1077 def get_tax_amounts(self, tax, enable_discount_accounting):
1078 amount = tax.tax_amount_after_discount_amount
1079 base_amount = tax.base_tax_amount_after_discount_amount
1080
Ankush Menat494bd9e2022-03-28 18:52:46 +05301081 if (
1082 enable_discount_accounting
1083 and self.get("discount_amount")
1084 and self.get("additional_discount_account")
1085 and self.get("apply_discount_on") == "Grand Total"
1086 ):
Deepesh Garg92f7a5a2021-07-21 15:25:40 +05301087 amount = tax.tax_amount
1088 base_amount = tax.base_tax_amount
1089
1090 return amount, base_amount
1091
GangaManoj8f7b0a12021-07-13 03:01:02 +05301092 def make_discount_gl_entries(self, gl_entries):
rahib-hassanf3fa6ac2022-04-20 16:01:12 +05301093 if self.doctype == "Purchase Invoice":
1094 enable_discount_accounting = cint(
1095 frappe.db.get_single_value("Buying Settings", "enable_discount_accounting")
1096 )
1097 elif self.doctype == "Sales Invoice":
1098 enable_discount_accounting = cint(
1099 frappe.db.get_single_value("Selling Settings", "enable_discount_accounting")
1100 )
GangaManoj8f7b0a12021-07-13 03:01:02 +05301101
1102 if enable_discount_accounting:
GangaManoj4105e272021-07-20 03:46:02 +05301103 if self.doctype == "Purchase Invoice":
1104 dr_or_cr = "credit"
1105 rev_dr_cr = "debit"
1106 supplier_or_customer = self.supplier
Ankush Menat4551d7d2021-08-19 13:41:10 +05301107
GangaManoj4105e272021-07-20 03:46:02 +05301108 else:
1109 dr_or_cr = "debit"
1110 rev_dr_cr = "credit"
1111 supplier_or_customer = self.customer
1112
GangaManoj8f7b0a12021-07-13 03:01:02 +05301113 for item in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301114 if item.get("discount_amount") and item.get("discount_account"):
Deepesh Gargad7bb312021-07-28 11:38:44 +05301115 discount_amount = item.discount_amount * item.qty
GangaManoj8f7b0a12021-07-13 03:01:02 +05301116 if self.doctype == "Purchase Invoice":
Ankush Menat494bd9e2022-03-28 18:52:46 +05301117 income_or_expense_account = (
1118 item.expense_account
Ankush Menat4551d7d2021-08-19 13:41:10 +05301119 if (not item.enable_deferred_expense or self.is_return)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301120 else item.deferred_expense_account
1121 )
GangaManoj8f7b0a12021-07-13 03:01:02 +05301122 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301123 income_or_expense_account = (
1124 item.income_account
Ankush Menat4551d7d2021-08-19 13:41:10 +05301125 if (not item.enable_deferred_revenue or self.is_return)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301126 else item.deferred_revenue_account
1127 )
GangaManoj8f7b0a12021-07-13 03:01:02 +05301128
1129 account_currency = get_account_currency(item.discount_account)
1130 gl_entries.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301131 self.get_gl_dict(
1132 {
1133 "account": item.discount_account,
1134 "against": supplier_or_customer,
Saqib Ansarif915a9c2022-05-17 11:22:01 +05301135 dr_or_cr: flt(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301136 discount_amount * self.get("conversion_rate"), item.precision("discount_amount")
1137 ),
Saqib Ansarif915a9c2022-05-17 11:22:01 +05301138 dr_or_cr + "_in_account_currency": flt(discount_amount, item.precision("discount_amount")),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301139 "cost_center": item.cost_center,
1140 "project": item.project,
1141 },
1142 account_currency,
1143 item=item,
1144 )
GangaManoj8f7b0a12021-07-13 03:01:02 +05301145 )
1146
1147 account_currency = get_account_currency(income_or_expense_account)
1148 gl_entries.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301149 self.get_gl_dict(
1150 {
1151 "account": income_or_expense_account,
1152 "against": supplier_or_customer,
Saqib Ansarif915a9c2022-05-17 11:22:01 +05301153 rev_dr_cr: flt(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301154 discount_amount * self.get("conversion_rate"), item.precision("discount_amount")
1155 ),
Saqib Ansarif915a9c2022-05-17 11:22:01 +05301156 rev_dr_cr
1157 + "_in_account_currency": flt(discount_amount, item.precision("discount_amount")),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301158 "cost_center": item.cost_center,
1159 "project": item.project or self.project,
1160 },
1161 account_currency,
1162 item=item,
1163 )
GangaManoj8f7b0a12021-07-13 03:01:02 +05301164 )
GangaManoj857501c2021-07-15 22:03:46 +05301165
Ankush Menat494bd9e2022-03-28 18:52:46 +05301166 if self.get("discount_amount") and self.get("additional_discount_account"):
GangaManoj857501c2021-07-15 22:03:46 +05301167 gl_entries.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301168 self.get_gl_dict(
1169 {
1170 "account": self.additional_discount_account,
1171 "against": supplier_or_customer,
1172 dr_or_cr: self.discount_amount,
1173 "cost_center": self.cost_center,
1174 },
1175 item=self,
1176 )
Ankush Menat4551d7d2021-08-19 13:41:10 +05301177 )
1178
Nabin Hait19d945a2013-07-29 18:35:39 +05301179 def validate_multiple_billing(self, ref_dt, item_ref_dn, based_on, parentfield):
Nabin Hait868766d2019-07-15 18:02:58 +05301180 from erpnext.controllers.status_updater import get_allowance_for
Saqib9c913c92021-11-26 12:00:13 +05301181
Nabin Hait868766d2019-07-15 18:02:58 +05301182 item_allowance = {}
1183 global_qty_allowance, global_amount_allowance = None, None
Anand Doshid2946502014-04-08 20:10:03 +05301184
Ankush Menat494bd9e2022-03-28 18:52:46 +05301185 role_allowed_to_over_bill = frappe.db.get_single_value(
1186 "Accounts Settings", "role_allowed_to_over_bill"
1187 )
Ankush Menat648b2d72021-09-20 15:27:12 +05301188 user_roles = frappe.get_roles()
1189
Ankush Menat43bf82b2021-09-20 16:31:20 +05301190 total_overbilled_amt = 0.0
1191
Nabin Hait4b8185d2014-12-25 18:19:39 +05301192 for item in self.get("items"):
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301193 if not item.get(item_ref_dn):
1194 continue
Anand Doshid2946502014-04-08 20:10:03 +05301195
Ankush Menat494bd9e2022-03-28 18:52:46 +05301196 ref_amt = flt(
1197 frappe.db.get_value(ref_dt + " Item", item.get(item_ref_dn), based_on),
1198 self.precision(based_on, item),
1199 )
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301200 if not ref_amt:
1201 frappe.msgprint(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301202 _("System will not check overbilling since amount for Item {0} in {1} is zero").format(
1203 item.item_code, ref_dt
1204 ),
1205 title=_("Warning"),
1206 indicator="orange",
1207 )
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301208 continue
Anand Doshid2946502014-04-08 20:10:03 +05301209
Saqib9c913c92021-11-26 12:00:13 +05301210 already_billed = self.get_billed_amount_for_item(item, item_ref_dn, based_on)
Anand Doshid2946502014-04-08 20:10:03 +05301211
Ankush Menat494bd9e2022-03-28 18:52:46 +05301212 total_billed_amt = flt(
1213 flt(already_billed) + flt(item.get(based_on)), self.precision(based_on, item)
1214 )
Anand Doshid2946502014-04-08 20:10:03 +05301215
Ankush Menat494bd9e2022-03-28 18:52:46 +05301216 allowance, item_allowance, global_qty_allowance, global_amount_allowance = get_allowance_for(
1217 item.item_code, item_allowance, global_qty_allowance, global_amount_allowance, "amount"
1218 )
rohitwaghchaure285344e2019-10-11 11:02:11 +05301219
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301220 max_allowed_amt = flt(ref_amt * (100 + allowance) / 100)
Deepesh Gargcb718fc2021-04-19 13:25:15 +05301221
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301222 if total_billed_amt < 0 and max_allowed_amt < 0:
1223 # while making debit note against purchase return entry(purchase receipt) getting overbill error
1224 total_billed_amt = abs(total_billed_amt)
1225 max_allowed_amt = abs(max_allowed_amt)
Afshan53fefd72021-06-24 10:09:02 +05301226
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301227 overbill_amt = total_billed_amt - max_allowed_amt
1228 total_overbilled_amt += overbill_amt
1229
1230 if overbill_amt > 0.01 and role_allowed_to_over_bill not in user_roles:
1231 if self.doctype != "Purchase Invoice":
1232 self.throw_overbill_exception(item, max_allowed_amt)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301233 elif not cint(
1234 frappe.db.get_single_value(
1235 "Buying Settings", "bill_for_rejected_quantity_in_purchase_invoice"
1236 )
1237 ):
Ankush Menat5e4fbba2021-09-20 16:36:27 +05301238 self.throw_overbill_exception(item, max_allowed_amt)
1239
1240 if role_allowed_to_over_bill in user_roles and total_overbilled_amt > 0.1:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301241 frappe.msgprint(
1242 _("Overbilling of {} ignored because you have {} role.").format(
1243 total_overbilled_amt, role_allowed_to_over_bill
1244 ),
1245 indicator="orange",
1246 alert=True,
1247 )
Afshan53fefd72021-06-24 10:09:02 +05301248
Saqib9c913c92021-11-26 12:00:13 +05301249 def get_billed_amount_for_item(self, item, item_ref_dn, based_on):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301250 """
1251 Returns Sum of Amount of
1252 Sales/Purchase Invoice Items
1253 that are linked to `item_ref_dn` (`dn_detail` / `pr_detail`)
1254 that are submitted OR not submitted but are under current invoice
1255 """
Saqib9c913c92021-11-26 12:00:13 +05301256
1257 from frappe.query_builder import Criterion
1258 from frappe.query_builder.functions import Sum
1259
1260 item_doctype = frappe.qb.DocType(item.doctype)
1261 based_on_field = frappe.qb.Field(based_on)
1262 join_field = frappe.qb.Field(item_ref_dn)
1263
1264 result = (
1265 frappe.qb.from_(item_doctype)
1266 .select(Sum(based_on_field))
Ankush Menat494bd9e2022-03-28 18:52:46 +05301267 .where(join_field == item.get(item_ref_dn))
Saqib9c913c92021-11-26 12:00:13 +05301268 .where(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301269 Criterion.any(
1270 [ # select all items from other invoices OR current invoices
1271 Criterion.all(
1272 [ # for selecting items from other invoices
1273 item_doctype.docstatus == 1,
1274 item_doctype.parent != self.name,
1275 ]
1276 ),
1277 Criterion.all(
1278 [ # for selecting items from current invoice, that are linked to same reference
1279 item_doctype.docstatus == 0,
1280 item_doctype.parent == self.name,
1281 item_doctype.name != item.name,
1282 ]
1283 ),
1284 ]
1285 )
Saqib9c913c92021-11-26 12:00:13 +05301286 )
1287 ).run()
1288
1289 return result[0][0] if result else 0
1290
Afshan53fefd72021-06-24 10:09:02 +05301291 def throw_overbill_exception(self, item, max_allowed_amt):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301292 frappe.throw(
1293 _(
1294 "Cannot overbill for Item {0} in row {1} more than {2}. To allow over-billing, please set allowance in Accounts Settings"
1295 ).format(item.item_code, item.idx, max_allowed_amt)
1296 )
Anand Doshid2946502014-04-08 20:10:03 +05301297
Rohit Waghchaure2a14f252021-07-30 12:36:35 +05301298 def get_company_default(self, fieldname, ignore_validation=False):
Rushabh Mehta1f847992013-12-12 19:12:19 +05301299 from erpnext.accounts.utils import get_company_default
Ankush Menat494bd9e2022-03-28 18:52:46 +05301300
Rohit Waghchaure2a14f252021-07-30 12:36:35 +05301301 return get_company_default(self.company, fieldname, ignore_validation=ignore_validation)
Anand Doshid2946502014-04-08 20:10:03 +05301302
Nabin Haita36adbd2013-08-02 14:50:12 +05301303 def get_stock_items(self):
1304 stock_items = []
Nabin Haitdd38a262014-12-26 13:15:21 +05301305 item_codes = list(set(item.item_code for item in self.get("items")))
Nabin Haita36adbd2013-08-02 14:50:12 +05301306 if item_codes:
Saqib Ansari199a6da2022-03-31 11:41:52 +05301307 stock_items = frappe.db.get_values(
1308 "Item", {"name": ["in", item_codes], "is_stock_item": 1}, pluck="name", cache=True
1309 )
Anand Doshid2946502014-04-08 20:10:03 +05301310
Nabin Haita36adbd2013-08-02 14:50:12 +05301311 return stock_items
Anand Doshid2946502014-04-08 20:10:03 +05301312
Ankit Javalkar8e7ca412014-09-12 15:18:53 +05301313 def set_total_advance_paid(self):
1314 if self.doctype == "Sales Order":
Nabin Hait6e439a52015-08-28 19:24:22 +05301315 dr_or_cr = "credit_in_account_currency"
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301316 rev_dr_or_cr = "debit_in_account_currency"
Nabin Haitb2206d12016-01-27 15:43:12 +05301317 party = self.customer
Ankit Javalkar8e7ca412014-09-12 15:18:53 +05301318 else:
Nabin Hait6e439a52015-08-28 19:24:22 +05301319 dr_or_cr = "debit_in_account_currency"
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301320 rev_dr_or_cr = "credit_in_account_currency"
Nabin Haitb2206d12016-01-27 15:43:12 +05301321 party = self.supplier
Ankit Javalkar8e7ca412014-09-12 15:18:53 +05301322
Ankush Menat494bd9e2022-03-28 18:52:46 +05301323 advance = frappe.db.sql(
1324 """
Ankit Javalkar8e7ca412014-09-12 15:18:53 +05301325 select
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301326 account_currency, sum({dr_or_cr}) - sum({rev_dr_cr}) as amount
Ankit Javalkar8e7ca412014-09-12 15:18:53 +05301327 from
Nabin Hait12e2a512016-06-26 01:37:21 +05301328 `tabGL Entry`
Ankit Javalkar8e7ca412014-09-12 15:18:53 +05301329 where
Nabin Hait12e2a512016-06-26 01:37:21 +05301330 against_voucher_type = %s and against_voucher = %s and party=%s
1331 and docstatus = 1
Ankush Menat494bd9e2022-03-28 18:52:46 +05301332 """.format(
1333 dr_or_cr=dr_or_cr, rev_dr_cr=rev_dr_or_cr
1334 ),
1335 (self.doctype, self.name, party),
1336 as_dict=1,
1337 ) # nosec
Ankit Javalkar8e7ca412014-09-12 15:18:53 +05301338
Nabin Haitb2206d12016-01-27 15:43:12 +05301339 if advance:
Anand Doshi7c0a58a2016-01-29 12:16:24 +05301340 advance = advance[0]
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301341
Anand Doshi7c0a58a2016-01-29 12:16:24 +05301342 advance_paid = flt(advance.amount, self.precision("advance_paid"))
Ankush Menat494bd9e2022-03-28 18:52:46 +05301343 formatted_advance_paid = fmt_money(
1344 advance_paid, precision=self.precision("advance_paid"), currency=advance.account_currency
1345 )
Anand Doshi7c0a58a2016-01-29 12:16:24 +05301346
Ankush Menat494bd9e2022-03-28 18:52:46 +05301347 frappe.db.set_value(self.doctype, self.name, "party_account_currency", advance.account_currency)
Anand Doshi7c0a58a2016-01-29 12:16:24 +05301348
1349 if advance.account_currency == self.currency:
finbyz5efc7972019-01-05 11:12:11 +05301350 order_total = self.get("rounded_total") or self.grand_total
1351 precision = "rounded_total" if self.get("rounded_total") else "grand_total"
Nabin Haitb2206d12016-01-27 15:43:12 +05301352 else:
finbyz5efc7972019-01-05 11:12:11 +05301353 order_total = self.get("base_rounded_total") or self.base_grand_total
1354 precision = "base_rounded_total" if self.get("base_rounded_total") else "base_grand_total"
Sagar Voraf733a392019-01-07 14:24:01 +05301355
Ankush Menat494bd9e2022-03-28 18:52:46 +05301356 formatted_order_total = fmt_money(
1357 order_total, precision=self.precision(precision), currency=advance.account_currency
1358 )
Anand Doshi7c0a58a2016-01-29 12:16:24 +05301359
Nabin Hait9db1b222016-06-30 12:37:53 +05301360 if self.currency == self.company_currency and advance_paid > order_total:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301361 frappe.throw(
1362 _(
1363 "Total advance ({0}) against Order {1} cannot be greater than the Grand Total ({2})"
1364 ).format(formatted_advance_paid, self.name, formatted_order_total)
1365 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301366
Nabin Hait13093b42016-06-29 18:04:37 +05301367 frappe.db.set_value(self.doctype, self.name, "advance_paid", advance_paid)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +05301368
ankitjavalkarworke60822b2014-08-26 14:29:06 +05301369 @property
1370 def company_abbr(self):
Nabin Hait6a5695f2018-08-09 11:30:21 +05301371 if not hasattr(self, "_abbr"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301372 self._abbr = frappe.db.get_value("Company", self.company, "abbr")
ankitjavalkarworke60822b2014-08-26 14:29:06 +05301373
1374 return self._abbr
1375
marination4be5b5c2020-10-08 19:08:27 +05301376 def raise_missing_debit_credit_account_error(self, party_type, party):
marination53b1a9a2020-11-03 15:45:25 +05301377 """Raise an error if debit to/credit to account does not exist."""
Ankush Menat494bd9e2022-03-28 18:52:46 +05301378 db_or_cr = (
1379 frappe.bold("Debit To") if self.doctype == "Sales Invoice" else frappe.bold("Credit To")
1380 )
marination4be5b5c2020-10-08 19:08:27 +05301381 rec_or_pay = "Receivable" if self.doctype == "Sales Invoice" else "Payable"
1382
1383 link_to_party = frappe.utils.get_link_to_form(party_type, party)
1384 link_to_company = frappe.utils.get_link_to_form("Company", self.company)
1385
Ankush Menat494bd9e2022-03-28 18:52:46 +05301386 message = _("{0} Account not found against Customer {1}.").format(
1387 db_or_cr, frappe.bold(party) or ""
1388 )
marination4be5b5c2020-10-08 19:08:27 +05301389 message += "<br>" + _("Please set one of the following:") + "<br>"
Ankush Menat494bd9e2022-03-28 18:52:46 +05301390 message += (
1391 "<br><ul><li>"
1392 + _("'Account' in the Accounting section of Customer {0}").format(link_to_party)
1393 + "</li>"
1394 )
1395 message += (
1396 "<li>"
1397 + _("'Default {0} Account' in Company {1}").format(rec_or_pay, link_to_company)
1398 + "</li></ul>"
1399 )
marination4be5b5c2020-10-08 19:08:27 +05301400
marination53b1a9a2020-11-03 15:45:25 +05301401 frappe.throw(message, title=_("Account Missing"), exc=AccountMissingError)
marination4be5b5c2020-10-08 19:08:27 +05301402
Neil Trini Lasrado3fbbb712015-07-17 12:10:12 +05301403 def validate_party(self):
Nabin Hait4ffd7f32015-08-27 12:28:36 +05301404 party_type, party = self.get_party()
shreyaseba9ca42016-01-26 14:56:52 +05301405 validate_party_frozen_disabled(party_type, party)
Anand Doshi979326b2015-09-11 16:22:37 +05301406
Nabin Hait4ffd7f32015-08-27 12:28:36 +05301407 def get_party(self):
Neil Trini Lasrado79bf2332015-07-20 13:03:48 +05301408 party_type = None
shreyas29b565f2016-01-25 17:30:49 +05301409 if self.doctype in ("Opportunity", "Quotation", "Sales Order", "Delivery Note", "Sales Invoice"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301410 party_type = "Customer"
shreyas29b565f2016-01-25 17:30:49 +05301411
Ankush Menat494bd9e2022-03-28 18:52:46 +05301412 elif self.doctype in (
1413 "Supplier Quotation",
1414 "Purchase Order",
1415 "Purchase Receipt",
1416 "Purchase Invoice",
1417 ):
1418 party_type = "Supplier"
shreyas29b565f2016-01-25 17:30:49 +05301419
1420 elif self.meta.get_field("customer"):
1421 party_type = "Customer"
Neil Trini Lasrado3fbbb712015-07-17 12:10:12 +05301422
Neil Trini Lasrado79bf2332015-07-20 13:03:48 +05301423 elif self.meta.get_field("supplier"):
shreyas29b565f2016-01-25 17:30:49 +05301424 party_type = "Supplier"
Anand Doshi979326b2015-09-11 16:22:37 +05301425
Nabin Hait4ffd7f32015-08-27 12:28:36 +05301426 party = self.get(party_type.lower()) if party_type else None
Anand Doshi979326b2015-09-11 16:22:37 +05301427
Nabin Hait4ffd7f32015-08-27 12:28:36 +05301428 return party_type, party
Anand Doshi979326b2015-09-11 16:22:37 +05301429
Nabin Hait4ffd7f32015-08-27 12:28:36 +05301430 def validate_currency(self):
Nabin Hait6e439a52015-08-28 19:24:22 +05301431 if self.get("currency"):
Nabin Hait4ffd7f32015-08-27 12:28:36 +05301432 party_type, party = self.get_party()
Nabin Hait6e439a52015-08-28 19:24:22 +05301433 if party_type and party:
Anand Doshib20baf82015-09-25 16:17:50 +05301434 party_account_currency = get_party_account_currency(party_type, party, self.company)
Anand Doshi979326b2015-09-11 16:22:37 +05301435
Ankush Menat494bd9e2022-03-28 18:52:46 +05301436 if (
1437 party_account_currency
1438 and party_account_currency != self.company_currency
1439 and self.currency != party_account_currency
1440 ):
1441 frappe.throw(
1442 _("Accounting Entry for {0}: {1} can only be made in currency: {2}").format(
1443 party_type, party, party_account_currency
1444 ),
1445 InvalidCurrency,
1446 )
Anand Doshi979326b2015-09-11 16:22:37 +05301447
shreyas29b565f2016-01-25 17:30:49 +05301448 # Note: not validating with gle account because we don't have the account
1449 # at quotation / sales order level and we shouldn't stop someone
1450 # from creating a sales invoice if sales order is already created
Rushabh Mehta2cb7a9f2016-06-15 16:45:03 +05301451
Deepesh Garg80c85dd2021-08-12 15:39:07 +05301452 def validate_party_account_currency(self):
Deepesh Garg33d97672022-05-12 16:40:29 +05301453 if self.doctype not in ("Sales Invoice", "Purchase Invoice"):
Deepesh Garg80c85dd2021-08-12 15:39:07 +05301454 return
1455
Deepesh Garg33d97672022-05-12 16:40:29 +05301456 if self.is_opening == "Yes":
Deepesh Garg60915e82021-08-21 23:05:48 +05301457 return
1458
Deepesh Garg80c85dd2021-08-12 15:39:07 +05301459 party_type, party = self.get_party()
1460 party_gle_currency = get_party_gle_currency(party_type, party, self.company)
Deepesh Garg33d97672022-05-12 16:40:29 +05301461 party_account = (
1462 self.get("debit_to") if self.doctype == "Sales Invoice" else self.get("credit_to")
1463 )
Deepesh Garg80c85dd2021-08-12 15:39:07 +05301464 party_account_currency = get_account_currency(party_account)
1465
1466 if not party_gle_currency and (party_account_currency != self.currency):
Deepesh Garg33d97672022-05-12 16:40:29 +05301467 frappe.throw(
Devin Slauenwhite3a1c9232022-06-02 14:15:50 -04001468 _("Party Account {0} currency ({1}) and document currency ({2}) should be same").format(
Devin Slauenwhiteb061ea42022-06-02 14:23:54 -04001469 frappe.bold(party_account), party_account_currency, self.currency
Deepesh Garg33d97672022-05-12 16:40:29 +05301470 )
1471 )
Deepesh Garg80c85dd2021-08-12 15:39:07 +05301472
Nabin Hait297d74a2016-11-23 15:58:51 +05301473 def delink_advance_entries(self, linked_doc_name):
1474 total_allocated_amount = 0
1475 for adv in self.advances:
1476 consider_for_total_advance = True
1477 if adv.reference_name == linked_doc_name:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301478 frappe.db.sql(
1479 """delete from `tab{0} Advance`
1480 where name = %s""".format(
1481 self.doctype
1482 ),
1483 adv.name,
1484 )
Nabin Hait297d74a2016-11-23 15:58:51 +05301485 consider_for_total_advance = False
1486
1487 if consider_for_total_advance:
1488 total_allocated_amount += flt(adv.allocated_amount, adv.precision("allocated_amount"))
1489
Ankush Menat494bd9e2022-03-28 18:52:46 +05301490 frappe.db.set_value(
1491 self.doctype, self.name, "total_advance", total_allocated_amount, update_modified=False
1492 )
Rohit Waghchaure6087fe12016-04-09 14:31:09 +05301493
KanchanChauhan49a50fe2016-11-18 13:57:53 +05301494 def group_similar_items(self):
1495 group_item_qty = {}
1496 group_item_amount = {}
Shreya Shah785f1aa2018-10-11 10:14:25 +05301497 # to update serial number in print
1498 count = 0
KanchanChauhan49a50fe2016-11-18 13:57:53 +05301499
1500 for item in self.items:
1501 group_item_qty[item.item_code] = group_item_qty.get(item.item_code, 0) + item.qty
1502 group_item_amount[item.item_code] = group_item_amount.get(item.item_code, 0) + item.amount
1503
1504 duplicate_list = []
KanchanChauhan49a50fe2016-11-18 13:57:53 +05301505 for item in self.items:
1506 if item.item_code in group_item_qty:
Shreya Shah785f1aa2018-10-11 10:14:25 +05301507 count += 1
KanchanChauhan49a50fe2016-11-18 13:57:53 +05301508 item.qty = group_item_qty[item.item_code]
1509 item.amount = group_item_amount[item.item_code]
deepeshgarg007e8d21cd2019-06-24 17:46:44 +05301510
1511 if item.qty:
1512 item.rate = flt(flt(item.amount) / flt(item.qty), item.precision("rate"))
1513 else:
1514 item.rate = 0
1515
Shreya Shah785f1aa2018-10-11 10:14:25 +05301516 item.idx = count
KanchanChauhan49a50fe2016-11-18 13:57:53 +05301517 del group_item_qty[item.item_code]
1518 else:
1519 duplicate_list.append(item)
KanchanChauhan49a50fe2016-11-18 13:57:53 +05301520 for item in duplicate_list:
1521 self.remove(item)
1522
tunde32aa7c12017-09-07 06:52:15 +01001523 def set_payment_schedule(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301524 if self.doctype == "Sales Invoice" and self.is_pos:
1525 self.payment_terms_template = ""
Manas Solankia7f55892018-04-02 10:32:00 +05301526 return
rohitwaghchauredb9fa782018-03-01 10:32:29 +05301527
Ankush Menat494bd9e2022-03-28 18:52:46 +05301528 party_account_currency = self.get("party_account_currency")
Deepesh Garg26210162020-08-11 16:06:13 +05301529 if not party_account_currency:
1530 party_type, party = self.get_party()
1531
1532 if party_type and party:
1533 party_account_currency = get_party_account_currency(party_type, party, self.company)
1534
rohitwaghchaureda941af2018-01-17 16:23:04 +05301535 posting_date = self.get("bill_date") or self.get("posting_date") or self.get("transaction_date")
tundedf3a1752017-09-11 11:02:57 +01001536 date = self.get("due_date")
1537 due_date = date or posting_date
Deepesh Garg26210162020-08-11 16:06:13 +05301538
Saqib Ansarid552fe62021-04-23 14:46:52 +05301539 base_grand_total = self.get("base_rounded_total") or self.base_grand_total
1540 grand_total = self.get("rounded_total") or self.grand_total
Deepesh Garg26210162020-08-11 16:06:13 +05301541
Nabin Hait2f9f4f92017-12-20 12:24:59 +05301542 if self.doctype in ("Sales Invoice", "Purchase Invoice"):
Saqib Ansarid552fe62021-04-23 14:46:52 +05301543 base_grand_total = base_grand_total - flt(self.base_write_off_amount)
Nabin Hait2f9f4f92017-12-20 12:24:59 +05301544 grand_total = grand_total - flt(self.write_off_amount)
Deepesh Gargbcf56e62021-08-06 23:53:16 +05301545 po_or_so, doctype, fieldname = self.get_order_details()
Ankush Menat494bd9e2022-03-28 18:52:46 +05301546 automatically_fetch_payment_terms = cint(
1547 frappe.db.get_single_value("Accounts Settings", "automatically_fetch_payment_terms")
1548 )
tunde96b8f222017-09-08 15:35:59 +01001549
Rohit Waghchaure4a267b92019-05-09 19:50:00 +05301550 if self.get("total_advance"):
Saqib Ansarid552fe62021-04-23 14:46:52 +05301551 if party_account_currency == self.company_currency:
1552 base_grand_total -= self.get("total_advance")
Ankush Menat494bd9e2022-03-28 18:52:46 +05301553 grand_total = flt(
1554 base_grand_total / self.get("conversion_rate"), self.precision("grand_total")
1555 )
Saqib Ansarid552fe62021-04-23 14:46:52 +05301556 else:
1557 grand_total -= self.get("total_advance")
Ankush Menat494bd9e2022-03-28 18:52:46 +05301558 base_grand_total = flt(
1559 grand_total * self.get("conversion_rate"), self.precision("base_grand_total")
1560 )
Rohit Waghchaure4a267b92019-05-09 19:50:00 +05301561
Nabin Hait0551f7b2017-11-21 19:58:16 +05301562 if not self.get("payment_schedule"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301563 if (
1564 self.doctype in ["Sales Invoice", "Purchase Invoice"]
1565 and automatically_fetch_payment_terms
1566 and self.linked_order_has_payment_terms(po_or_so, fieldname, doctype)
1567 ):
Deepesh Gargbcf56e62021-08-06 23:53:16 +05301568 self.fetch_payment_terms_from_order(po_or_so, doctype)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301569 if self.get("payment_terms_template"):
Deepesh Gargbcf56e62021-08-06 23:53:16 +05301570 self.ignore_default_payment_terms_template = 1
1571 elif self.get("payment_terms_template"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301572 data = get_payment_terms(
1573 self.payment_terms_template, posting_date, grand_total, base_grand_total
1574 )
Nabin Hait0551f7b2017-11-21 19:58:16 +05301575 for item in data:
1576 self.append("payment_schedule", item)
GangaManoj4323f4b2021-07-22 05:57:42 +05301577 elif self.doctype not in ["Purchase Receipt"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301578 data = dict(
1579 due_date=due_date,
1580 invoice_portion=100,
1581 payment_amount=grand_total,
1582 base_payment_amount=base_grand_total,
1583 )
Nabin Hait0551f7b2017-11-21 19:58:16 +05301584 self.append("payment_schedule", data)
Deepesh Gargbcf56e62021-08-06 23:53:16 +05301585
1586 for d in self.get("payment_schedule"):
1587 if d.invoice_portion:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301588 d.payment_amount = flt(
1589 grand_total * flt(d.invoice_portion / 100), d.precision("payment_amount")
1590 )
1591 d.base_payment_amount = flt(
1592 base_grand_total * flt(d.invoice_portion / 100), d.precision("base_payment_amount")
1593 )
Deepesh Gargbcf56e62021-08-06 23:53:16 +05301594 d.outstanding = d.payment_amount
1595 elif not d.invoice_portion:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301596 d.base_payment_amount = flt(
1597 d.payment_amount * self.get("conversion_rate"), d.precision("base_payment_amount")
1598 )
tunde43870aa2017-08-18 11:59:30 +01001599
GangaManoj4323f4b2021-07-22 05:57:42 +05301600 def get_order_details(self):
1601 if self.doctype == "Sales Invoice":
Ankush Menat494bd9e2022-03-28 18:52:46 +05301602 po_or_so = self.get("items")[0].get("sales_order")
GangaManoj4323f4b2021-07-22 05:57:42 +05301603 po_or_so_doctype = "Sales Order"
1604 po_or_so_doctype_name = "sales_order"
1605
tunde43870aa2017-08-18 11:59:30 +01001606 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301607 po_or_so = self.get("items")[0].get("purchase_order")
GangaManoj4323f4b2021-07-22 05:57:42 +05301608 po_or_so_doctype = "Purchase Order"
1609 po_or_so_doctype_name = "purchase_order"
Ankush Menat4551d7d2021-08-19 13:41:10 +05301610
GangaManoj4323f4b2021-07-22 05:57:42 +05301611 return po_or_so, po_or_so_doctype, po_or_so_doctype_name
1612
GangaManojc7c90242021-07-29 19:18:35 +05301613 def linked_order_has_payment_terms(self, po_or_so, fieldname, doctype):
GangaManoj4323f4b2021-07-22 05:57:42 +05301614 if po_or_so and self.all_items_have_same_po_or_so(po_or_so, fieldname):
GangaManojc7c90242021-07-29 19:18:35 +05301615 if self.linked_order_has_payment_terms_template(po_or_so, doctype):
GangaManoj4323f4b2021-07-22 05:57:42 +05301616 return True
1617 elif self.linked_order_has_payment_schedule(po_or_so):
1618 return True
Ankush Menat4551d7d2021-08-19 13:41:10 +05301619
GangaManoj4323f4b2021-07-22 05:57:42 +05301620 return False
1621
1622 def all_items_have_same_po_or_so(self, po_or_so, fieldname):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301623 for item in self.get("items"):
GangaManoj4323f4b2021-07-22 05:57:42 +05301624 if item.get(fieldname) != po_or_so:
1625 return False
Ankush Menat4551d7d2021-08-19 13:41:10 +05301626
GangaManoj4323f4b2021-07-22 05:57:42 +05301627 return True
1628
GangaManojc7c90242021-07-29 19:18:35 +05301629 def linked_order_has_payment_terms_template(self, po_or_so, doctype):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301630 return frappe.get_value(doctype, po_or_so, "payment_terms_template")
GangaManoj4323f4b2021-07-22 05:57:42 +05301631
1632 def linked_order_has_payment_schedule(self, po_or_so):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301633 return frappe.get_all("Payment Schedule", filters={"parent": po_or_so})
GangaManoj4323f4b2021-07-22 05:57:42 +05301634
1635 def fetch_payment_terms_from_order(self, po_or_so, po_or_so_doctype):
1636 """
Ankush Menat494bd9e2022-03-28 18:52:46 +05301637 Fetch Payment Terms from Purchase/Sales Order on creating a new Purchase/Sales Invoice.
GangaManoj4323f4b2021-07-22 05:57:42 +05301638 """
1639 po_or_so = frappe.get_cached_doc(po_or_so_doctype, po_or_so)
1640
1641 self.payment_schedule = []
1642 self.payment_terms_template = po_or_so.payment_terms_template
1643
1644 for schedule in po_or_so.payment_schedule:
1645 payment_schedule = {
Ankush Menat494bd9e2022-03-28 18:52:46 +05301646 "payment_term": schedule.payment_term,
1647 "due_date": schedule.due_date,
1648 "invoice_portion": schedule.invoice_portion,
1649 "mode_of_payment": schedule.mode_of_payment,
1650 "description": schedule.description,
GangaManoj4323f4b2021-07-22 05:57:42 +05301651 }
GangaManoj5b33e752021-08-05 21:50:09 +05301652
Ankush Menat494bd9e2022-03-28 18:52:46 +05301653 if schedule.discount_type == "Percentage":
1654 payment_schedule["discount_type"] = schedule.discount_type
1655 payment_schedule["discount"] = schedule.discount
GangaManoj5b33e752021-08-05 21:50:09 +05301656
ruthra kumar9bd56b02022-02-01 14:14:04 +05301657 if not schedule.invoice_portion:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301658 payment_schedule["payment_amount"] = schedule.payment_amount
ruthra kumar9bd56b02022-02-01 14:14:04 +05301659
GangaManoj4323f4b2021-07-22 05:57:42 +05301660 self.append("payment_schedule", payment_schedule)
tunde43870aa2017-08-18 11:59:30 +01001661
tundebe1b8712017-08-19 08:21:44 +01001662 def set_due_date(self):
Nabin Hait0551f7b2017-11-21 19:58:16 +05301663 due_dates = [d.due_date for d in self.get("payment_schedule") if d.due_date]
1664 if due_dates:
1665 self.due_date = max(due_dates)
tunde62af5c52017-09-22 15:16:38 +01001666
1667 def validate_payment_schedule_dates(self):
tunde77ecacc2017-09-22 23:12:55 +01001668 dates = []
tunde9bed2de2017-09-25 10:19:35 +01001669 li = []
tunde43870aa2017-08-18 11:59:30 +01001670
Ankush Menat494bd9e2022-03-28 18:52:46 +05301671 if self.doctype == "Sales Invoice" and self.is_pos:
1672 return
rohitwaghchauredb9fa782018-03-01 10:32:29 +05301673
tunde43870aa2017-08-18 11:59:30 +01001674 for d in self.get("payment_schedule"):
Nabin Hait2f9f4f92017-12-20 12:24:59 +05301675 if self.doctype == "Sales Order" and getdate(d.due_date) < getdate(self.transaction_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301676 frappe.throw(
1677 _("Row {0}: Due Date in the Payment Terms table cannot be before Posting Date").format(d.idx)
1678 )
tunde77ecacc2017-09-22 23:12:55 +01001679 elif d.due_date in dates:
mnatalia5f0e8d62018-05-22 06:38:50 +03001680 li.append(_("{0} in row {1}").format(d.due_date, d.idx))
tunde9bed2de2017-09-25 10:19:35 +01001681 dates.append(d.due_date)
1682
1683 if li:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301684 duplicates = "<br>" + "<br>".join(li)
1685 frappe.throw(
1686 _("Rows with duplicate due dates in other rows were found: {0}").format(duplicates)
1687 )
tunde43870aa2017-08-18 11:59:30 +01001688
tunde62af5c52017-09-22 15:16:38 +01001689 def validate_payment_schedule_amount(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301690 if self.doctype == "Sales Invoice" and self.is_pos:
1691 return
rohitwaghchauredb9fa782018-03-01 10:32:29 +05301692
Ankush Menat494bd9e2022-03-28 18:52:46 +05301693 party_account_currency = self.get("party_account_currency")
Deepesh Garg26210162020-08-11 16:06:13 +05301694 if not party_account_currency:
1695 party_type, party = self.get_party()
1696
1697 if party_type and party:
1698 party_account_currency = get_party_account_currency(party_type, party, self.company)
1699
Nabin Hait0551f7b2017-11-21 19:58:16 +05301700 if self.get("payment_schedule"):
1701 total = 0
Saqib Ansarid552fe62021-04-23 14:46:52 +05301702 base_total = 0
Nabin Hait0551f7b2017-11-21 19:58:16 +05301703 for d in self.get("payment_schedule"):
Deepesh Garg9c170522021-10-25 20:06:24 +05301704 total += flt(d.payment_amount, d.precision("payment_amount"))
1705 base_total += flt(d.base_payment_amount, d.precision("base_payment_amount"))
tunde43870aa2017-08-18 11:59:30 +01001706
Saqib Ansarid552fe62021-04-23 14:46:52 +05301707 base_grand_total = self.get("base_rounded_total") or self.base_grand_total
1708 grand_total = self.get("rounded_total") or self.grand_total
Rohit Waghchaure4a267b92019-05-09 19:50:00 +05301709
Nabin Haite591c852017-12-21 11:46:30 +05301710 if self.doctype in ("Sales Invoice", "Purchase Invoice"):
Saqib Ansarid552fe62021-04-23 14:46:52 +05301711 base_grand_total = base_grand_total - flt(self.base_write_off_amount)
Nabin Haite591c852017-12-21 11:46:30 +05301712 grand_total = grand_total - flt(self.write_off_amount)
Saqib Ansarid552fe62021-04-23 14:46:52 +05301713
1714 if self.get("total_advance"):
1715 if party_account_currency == self.company_currency:
1716 base_grand_total -= self.get("total_advance")
Ankush Menat494bd9e2022-03-28 18:52:46 +05301717 grand_total = flt(
1718 base_grand_total / self.get("conversion_rate"), self.precision("grand_total")
1719 )
Saqib Ansarid552fe62021-04-23 14:46:52 +05301720 else:
1721 grand_total -= self.get("total_advance")
Ankush Menat494bd9e2022-03-28 18:52:46 +05301722 base_grand_total = flt(
1723 grand_total * self.get("conversion_rate"), self.precision("base_grand_total")
1724 )
Deepesh Garg9c170522021-10-25 20:06:24 +05301725
Ankush Menat494bd9e2022-03-28 18:52:46 +05301726 if (
1727 flt(total, self.precision("grand_total")) - flt(grand_total, self.precision("grand_total"))
1728 > 0.1
1729 or flt(base_total, self.precision("base_grand_total"))
1730 - flt(base_grand_total, self.precision("base_grand_total"))
1731 > 0.1
1732 ):
1733 frappe.throw(
1734 _("Total Payment Amount in Payment Schedule must be equal to Grand / Rounded Total")
1735 )
tunde43870aa2017-08-18 11:59:30 +01001736
Nabin Hait877e1bb2017-11-17 12:27:43 +05301737 def is_rounded_total_disabled(self):
1738 if self.meta.get_field("disable_rounded_total"):
1739 return self.disable_rounded_total
1740 else:
1741 return frappe.db.get_single_value("Global Defaults", "disable_rounded_total")
1742
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05301743 def set_inter_company_account(self):
1744 """
Ankush Menat494bd9e2022-03-28 18:52:46 +05301745 Set intercompany account for inter warehouse transactions
1746 This account will be used in case billing company and internal customer's
1747 representation company is same
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05301748 """
1749
1750 if self.is_internal_transfer() and not self.unrealized_profit_loss_account:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301751 unrealized_profit_loss_account = frappe.db.get_value(
1752 "Company", self.company, "unrealized_profit_loss_account"
1753 )
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05301754
1755 if not unrealized_profit_loss_account:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301756 msg = _(
1757 "Please select Unrealized Profit / Loss account or add default Unrealized Profit / Loss account account for company {0}"
1758 ).format(frappe.bold(self.company))
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05301759 frappe.throw(msg)
1760
1761 self.unrealized_profit_loss_account = unrealized_profit_loss_account
1762
1763 def is_internal_transfer(self):
1764 """
Ankush Menat494bd9e2022-03-28 18:52:46 +05301765 It will an internal transfer if its an internal customer and representation
1766 company is same as billing company
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05301767 """
Ankush Menat494bd9e2022-03-28 18:52:46 +05301768 if self.doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
1769 internal_party_field = "is_internal_customer"
1770 elif self.doctype in ("Purchase Invoice", "Purchase Receipt", "Purchase Order"):
1771 internal_party_field = "is_internal_supplier"
Ankush Menat3714e362022-05-16 18:09:14 +05301772 else:
1773 return False
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05301774
1775 if self.get(internal_party_field) and (self.represents_company == self.company):
1776 return True
1777
1778 return False
1779
Saqib Ansari977b09b2021-08-19 17:57:30 +05301780 def process_common_party_accounting(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301781 is_invoice = self.doctype in ["Sales Invoice", "Purchase Invoice"]
Saqib Ansari977b09b2021-08-19 17:57:30 +05301782 if not is_invoice:
1783 return
1784
Ankush Menat494bd9e2022-03-28 18:52:46 +05301785 if frappe.db.get_single_value("Accounts Settings", "enable_common_party_accounting"):
Saqib Ansari977b09b2021-08-19 17:57:30 +05301786 party_link = self.get_common_party_link()
1787 if party_link and self.outstanding_amount:
1788 self.create_advance_and_reconcile(party_link)
1789
1790 def get_common_party_link(self):
1791 party_type, party = self.get_party()
Saqib Ansari72543682021-08-25 20:15:23 +05301792 return frappe.db.get_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301793 doctype="Party Link",
1794 filters={"secondary_role": party_type, "secondary_party": party},
1795 fieldname=["primary_role", "primary_party"],
1796 as_dict=True,
Saqib Ansari72543682021-08-25 20:15:23 +05301797 )
Saqib Ansari977b09b2021-08-19 17:57:30 +05301798
1799 def create_advance_and_reconcile(self, party_link):
1800 secondary_party_type, secondary_party = self.get_party()
1801 primary_party_type, primary_party = party_link.primary_role, party_link.primary_party
1802
1803 primary_account = get_party_account(primary_party_type, primary_party, self.company)
1804 secondary_account = get_party_account(secondary_party_type, secondary_party, self.company)
1805
Ankush Menat494bd9e2022-03-28 18:52:46 +05301806 jv = frappe.new_doc("Journal Entry")
1807 jv.voucher_type = "Journal Entry"
Saqib Ansari977b09b2021-08-19 17:57:30 +05301808 jv.posting_date = self.posting_date
1809 jv.company = self.company
Ankush Menat494bd9e2022-03-28 18:52:46 +05301810 jv.remark = "Adjustment for {} {}".format(self.doctype, self.name)
Saqib Ansari977b09b2021-08-19 17:57:30 +05301811
1812 reconcilation_entry = frappe._dict()
1813 advance_entry = frappe._dict()
Saqib Ansari977b09b2021-08-19 17:57:30 +05301814
1815 reconcilation_entry.account = secondary_account
1816 reconcilation_entry.party_type = secondary_party_type
1817 reconcilation_entry.party = secondary_party
1818 reconcilation_entry.reference_type = self.doctype
1819 reconcilation_entry.reference_name = self.name
Saqib Ansaric6c7a8b2021-08-25 20:17:04 +05301820 reconcilation_entry.cost_center = self.cost_center
Saqib Ansari977b09b2021-08-19 17:57:30 +05301821
1822 advance_entry.account = primary_account
1823 advance_entry.party_type = primary_party_type
1824 advance_entry.party = primary_party
Saqib Ansaric6c7a8b2021-08-25 20:17:04 +05301825 advance_entry.cost_center = self.cost_center
Ankush Menat494bd9e2022-03-28 18:52:46 +05301826 advance_entry.is_advance = "Yes"
Saqib Ansari977b09b2021-08-19 17:57:30 +05301827
Ankush Menat494bd9e2022-03-28 18:52:46 +05301828 if self.doctype == "Sales Invoice":
Saqib Ansari977b09b2021-08-19 17:57:30 +05301829 reconcilation_entry.credit_in_account_currency = self.outstanding_amount
1830 advance_entry.debit_in_account_currency = self.outstanding_amount
1831 else:
1832 advance_entry.credit_in_account_currency = self.outstanding_amount
1833 reconcilation_entry.debit_in_account_currency = self.outstanding_amount
1834
Ankush Menat494bd9e2022-03-28 18:52:46 +05301835 jv.append("accounts", reconcilation_entry)
1836 jv.append("accounts", advance_entry)
Saqib Ansari977b09b2021-08-19 17:57:30 +05301837
1838 jv.save()
1839 jv.submit()
1840
Ankush Menat494bd9e2022-03-28 18:52:46 +05301841
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301842@frappe.whitelist()
Rushabh Mehtaf56d73c2013-10-10 16:35:09 +05301843def get_tax_rate(account_head):
Rushabh Mehta2cb7a9f2016-06-15 16:45:03 +05301844 return frappe.db.get_value("Account", account_head, ["tax_rate", "account_name"], as_dict=True)
Rushabh Mehtaa33d4682015-06-01 17:15:42 +05301845
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001846
Nabin Haitffc7f3f2015-05-12 15:07:02 +05301847@frappe.whitelist()
Nabin Haita2426fc2018-01-15 17:45:46 +05301848def get_default_taxes_and_charges(master_doctype, tax_template=None, company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301849 if not company:
1850 return {}
rohitwaghchaure505661b2017-12-11 14:52:28 +05301851
Nabin Haita2426fc2018-01-15 17:45:46 +05301852 if tax_template and company:
1853 tax_template_company = frappe.db.get_value(master_doctype, tax_template, "company")
1854 if tax_template_company == company:
1855 return
1856
1857 default_tax = frappe.db.get_value(master_doctype, {"is_default": 1, "company": company})
rohitwaghchaure505661b2017-12-11 14:52:28 +05301858
Rushabh Mehta98aa5812017-11-14 09:32:32 +05301859 return {
Ankush Menat494bd9e2022-03-28 18:52:46 +05301860 "taxes_and_charges": default_tax,
1861 "taxes": get_taxes_and_charges(master_doctype, default_tax),
Rushabh Mehta98aa5812017-11-14 09:32:32 +05301862 }
Nabin Hait6b039142014-05-02 15:45:10 +05301863
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001864
Nabin Hait6b039142014-05-02 15:45:10 +05301865@frappe.whitelist()
Nabin Haitffc7f3f2015-05-12 15:07:02 +05301866def get_taxes_and_charges(master_doctype, master_name):
Nabin Hait1fe50122015-05-16 12:14:39 +05301867 if not master_name:
1868 return
Ankush Menat77dcdff2022-06-01 22:01:07 +05301869 from frappe.model import child_table_fields, default_fields
Ankush Menat494bd9e2022-03-28 18:52:46 +05301870
Nabin Hait6b039142014-05-02 15:45:10 +05301871 tax_master = frappe.get_doc(master_doctype, master_name)
1872
1873 taxes_and_charges = []
Nabin Haitffc7f3f2015-05-12 15:07:02 +05301874 for i, tax in enumerate(tax_master.get("taxes")):
Nabin Hait6b039142014-05-02 15:45:10 +05301875 tax = tax.as_dict()
1876
Ankush Menat77dcdff2022-06-01 22:01:07 +05301877 for fieldname in default_fields + child_table_fields:
Nabin Hait6b039142014-05-02 15:45:10 +05301878 if fieldname in tax:
1879 del tax[fieldname]
1880
1881 taxes_and_charges.append(tax)
1882
1883 return taxes_and_charges
Rushabh Mehta66e08e32014-09-29 12:17:03 +05301884
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001885
Rushabh Mehta66e08e32014-09-29 12:17:03 +05301886def validate_conversion_rate(currency, conversion_rate, conversion_rate_label, company):
1887 """common validation for currency and price list currency"""
1888
Ankush Menat494bd9e2022-03-28 18:52:46 +05301889 company_currency = frappe.get_cached_value("Company", company, "default_currency")
Rushabh Mehta66e08e32014-09-29 12:17:03 +05301890
1891 if not conversion_rate:
Saqib60212ff2020-10-26 11:17:04 +05301892 throw(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301893 _("{0} is mandatory. Maybe Currency Exchange record is not created for {1} to {2}.").format(
1894 conversion_rate_label, currency, company_currency
1895 )
Saqib60212ff2020-10-26 11:17:04 +05301896 )
Nabin Hait613d0812015-02-23 11:58:15 +05301897
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001898
Nabin Hait613d0812015-02-23 11:58:15 +05301899def validate_taxes_and_charges(tax):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301900 if tax.charge_type in ["Actual", "On Net Total", "On Paid Amount"] and tax.row_id:
1901 frappe.throw(
1902 _("Can refer row only if the charge type is 'On Previous Row Amount' or 'Previous Row Total'")
1903 )
1904 elif tax.charge_type in ["On Previous Row Amount", "On Previous Row Total"]:
Nabin Hait613d0812015-02-23 11:58:15 +05301905 if cint(tax.idx) == 1:
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001906 frappe.throw(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301907 _(
1908 "Cannot select charge type as 'On Previous Row Amount' or 'On Previous Row Total' for first row"
1909 )
1910 )
Nabin Hait613d0812015-02-23 11:58:15 +05301911 elif not tax.row_id:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301912 frappe.throw(
1913 _("Please specify a valid Row ID for row {0} in table {1}").format(tax.idx, _(tax.doctype))
1914 )
Nabin Hait613d0812015-02-23 11:58:15 +05301915 elif tax.row_id and cint(tax.row_id) >= cint(tax.idx):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301916 frappe.throw(
1917 _("Cannot refer row number greater than or equal to current row number for this Charge type")
1918 )
Nabin Hait613d0812015-02-23 11:58:15 +05301919
Rushabh Mehta2a21bc92015-02-25 15:08:42 +05301920 if tax.charge_type == "Actual":
Nabin Haitbc6c3602015-02-27 23:40:56 +05301921 tax.rate = None
Rushabh Mehta2a21bc92015-02-25 15:08:42 +05301922
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001923
Ankush Menat494bd9e2022-03-28 18:52:46 +05301924def validate_account_head(idx, account, company, context=""):
1925 account_company = frappe.get_cached_value("Account", account, "company")
Anuja Pawar0e337be2021-08-10 17:26:35 +05301926
Deepesh Garg5a2b5712022-02-18 20:05:49 +05301927 if account_company != company:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301928 frappe.throw(
1929 _("Row {0}: {3} Account {1} does not belong to Company {2}").format(
1930 idx, frappe.bold(account), frappe.bold(company), context
1931 ),
1932 title=_("Invalid Account"),
1933 )
Anuja Pawar0e337be2021-08-10 17:26:35 +05301934
1935
1936def validate_cost_center(tax, doc):
1937 if not tax.cost_center:
1938 return
1939
Ankush Menat494bd9e2022-03-28 18:52:46 +05301940 company = frappe.get_cached_value("Cost Center", tax.cost_center, "company")
Anuja Pawar0e337be2021-08-10 17:26:35 +05301941
1942 if company != doc.company:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301943 frappe.throw(
1944 _("Row {0}: Cost Center {1} does not belong to Company {2}").format(
1945 tax.idx, frappe.bold(tax.cost_center), frappe.bold(doc.company)
1946 ),
1947 title=_("Invalid Cost Center"),
1948 )
Anuja Pawar0e337be2021-08-10 17:26:35 +05301949
1950
Nabin Hait613d0812015-02-23 11:58:15 +05301951def validate_inclusive_tax(tax, doc):
1952 def _on_previous_row_error(row_range):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301953 throw(
1954 _("To include tax in row {0} in Item rate, taxes in rows {1} must also be included").format(
1955 tax.idx, row_range
1956 )
1957 )
Nabin Hait613d0812015-02-23 11:58:15 +05301958
1959 if cint(getattr(tax, "included_in_print_rate", None)):
1960 if tax.charge_type == "Actual":
1961 # inclusive tax cannot be of type Actual
Ankush Menat494bd9e2022-03-28 18:52:46 +05301962 throw(
1963 _("Charge of type 'Actual' in row {0} cannot be included in Item Rate or Paid Amount").format(
1964 tax.idx
1965 )
1966 )
1967 elif tax.charge_type == "On Previous Row Amount" and not cint(
1968 doc.get("taxes")[cint(tax.row_id) - 1].included_in_print_rate
1969 ):
Nabin Hait613d0812015-02-23 11:58:15 +05301970 # referred row should also be inclusive
1971 _on_previous_row_error(tax.row_id)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301972 elif tax.charge_type == "On Previous Row Total" and not all(
1973 [cint(t.included_in_print_rate) for t in doc.get("taxes")[: cint(tax.row_id) - 1]]
1974 ):
Deepesh Garg5ef9a622021-06-14 14:34:44 +05301975 # all rows about the referred tax should be inclusive
Nabin Hait613d0812015-02-23 11:58:15 +05301976 _on_previous_row_error("1 - %d" % (tax.row_id,))
Nabin Hait93b3a372015-02-24 17:08:34 +05301977 elif tax.get("category") == "Valuation":
Nabin Hait19ea7212020-08-11 20:34:57 +05301978 frappe.throw(_("Valuation type charges can not be marked as Inclusive"))
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05301979
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05301980
Ankush Menat494bd9e2022-03-28 18:52:46 +05301981def set_balance_in_account_currency(
1982 gl_dict, account_currency=None, conversion_rate=None, company_currency=None
1983):
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001984 if (not conversion_rate) and (account_currency != company_currency):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301985 frappe.throw(
1986 _("Account: {0} with currency: {1} can not be selected").format(
1987 gl_dict.account, account_currency
1988 )
1989 )
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001990
Ankush Menat494bd9e2022-03-28 18:52:46 +05301991 gl_dict["account_currency"] = (
1992 company_currency if account_currency == company_currency else account_currency
1993 )
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05301994
1995 # set debit/credit in account currency if not provided
1996 if flt(gl_dict.debit) and not flt(gl_dict.debit_in_account_currency):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301997 gl_dict.debit_in_account_currency = (
1998 gl_dict.debit
1999 if account_currency == company_currency
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05302000 else flt(gl_dict.debit / conversion_rate, 2)
Ankush Menat494bd9e2022-03-28 18:52:46 +05302001 )
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05302002
2003 if flt(gl_dict.credit) and not flt(gl_dict.credit_in_account_currency):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302004 gl_dict.credit_in_account_currency = (
2005 gl_dict.credit
2006 if account_currency == company_currency
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05302007 else flt(gl_dict.credit / conversion_rate, 2)
Ankush Menat494bd9e2022-03-28 18:52:46 +05302008 )
Nabin Hait1991c7b2016-06-27 20:09:05 +05302009
2010
Ankush Menat494bd9e2022-03-28 18:52:46 +05302011def get_advance_journal_entries(
2012 party_type,
2013 party,
2014 party_account,
2015 amount_field,
2016 order_doctype,
2017 order_list,
2018 include_unallocated=True,
2019):
2020 dr_or_cr = (
2021 "credit_in_account_currency" if party_type == "Customer" else "debit_in_account_currency"
2022 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05302023
Nabin Hait1991c7b2016-06-27 20:09:05 +05302024 conditions = []
2025 if include_unallocated:
2026 conditions.append("ifnull(t2.reference_name, '')=''")
2027
2028 if order_list:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302029 order_condition = ", ".join(["%s"] * len(order_list))
2030 conditions.append(
2031 " (t2.reference_type = '{0}' and ifnull(t2.reference_name, '') in ({1}))".format(
2032 order_doctype, order_condition
2033 )
2034 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05302035
Nabin Hait1991c7b2016-06-27 20:09:05 +05302036 reference_condition = " and (" + " or ".join(conditions) + ")" if conditions else ""
Rushabh Mehta66958302017-01-16 16:57:53 +05302037
Deepesh Gargc38be532022-04-14 13:26:47 +05302038 # nosemgrep
Ankush Menat494bd9e2022-03-28 18:52:46 +05302039 journal_entries = frappe.db.sql(
2040 """
Nabin Hait1991c7b2016-06-27 20:09:05 +05302041 select
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05302042 "Journal Entry" as reference_type, t1.name as reference_name,
Nabin Hait1991c7b2016-06-27 20:09:05 +05302043 t1.remark as remarks, t2.{0} as amount, t2.name as reference_row,
Deepesh Garg31883b62022-04-13 20:52:25 +05302044 t2.reference_name as against_order, t2.exchange_rate
Nabin Hait1991c7b2016-06-27 20:09:05 +05302045 from
2046 `tabJournal Entry` t1, `tabJournal Entry Account` t2
2047 where
2048 t1.name = t2.parent and t2.account = %s
2049 and t2.party_type = %s and t2.party = %s
2050 and t2.is_advance = 'Yes' and t1.docstatus = 1
Nabin Haitca627fb2016-09-05 16:16:53 +05302051 and {1} > 0 {2}
Ankush Menat494bd9e2022-03-28 18:52:46 +05302052 order by t1.posting_date""".format(
2053 amount_field, dr_or_cr, reference_condition
2054 ),
2055 [party_account, party_type, party] + order_list,
2056 as_dict=1,
2057 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05302058
Nabin Hait1991c7b2016-06-27 20:09:05 +05302059 return list(journal_entries)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05302060
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002061
Ankush Menat494bd9e2022-03-28 18:52:46 +05302062def get_advance_payment_entries(
2063 party_type,
2064 party,
2065 party_account,
2066 order_doctype,
2067 order_list=None,
2068 include_unallocated=True,
2069 against_all_orders=False,
2070 limit=None,
2071 condition=None,
2072):
Nabin Hait1991c7b2016-06-27 20:09:05 +05302073 party_account_field = "paid_from" if party_type == "Customer" else "paid_to"
Ankush Menat494bd9e2022-03-28 18:52:46 +05302074 currency_field = (
2075 "paid_from_account_currency" if party_type == "Customer" else "paid_to_account_currency"
2076 )
Nabin Hait1991c7b2016-06-27 20:09:05 +05302077 payment_type = "Receive" if party_type == "Customer" else "Pay"
Ankush Menat494bd9e2022-03-28 18:52:46 +05302078 exchange_rate_field = (
2079 "source_exchange_rate" if payment_type == "Receive" else "target_exchange_rate"
2080 )
Saqiba20999c2021-07-12 14:33:23 +05302081
Nabin Hait1991c7b2016-06-27 20:09:05 +05302082 payment_entries_against_order, unallocated_payment_entries = [], []
Nabin Hait34c551d2019-07-03 10:34:31 +05302083 limit_cond = "limit %s" % limit if limit else ""
Nabin Haitff2f3ef2016-07-04 11:41:14 +05302084
Nabin Hait1991c7b2016-06-27 20:09:05 +05302085 if order_list or against_all_orders:
2086 if order_list:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302087 reference_condition = " and t2.reference_name in ({0})".format(
2088 ", ".join(["%s"] * len(order_list))
2089 )
Nabin Hait1991c7b2016-06-27 20:09:05 +05302090 else:
2091 reference_condition = ""
2092 order_list = []
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05302093
Ankush Menat494bd9e2022-03-28 18:52:46 +05302094 payment_entries_against_order = frappe.db.sql(
2095 """
Nabin Hait1991c7b2016-06-27 20:09:05 +05302096 select
2097 "Payment Entry" as reference_type, t1.name as reference_name,
2098 t1.remarks, t2.allocated_amount as amount, t2.name as reference_row,
Deepesh Gargc7eadfc2020-07-22 17:59:37 +05302099 t2.reference_name as against_order, t1.posting_date,
Saqiba20999c2021-07-12 14:33:23 +05302100 t1.{0} as currency, t1.{4} as exchange_rate
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05302101 from `tabPayment Entry` t1, `tabPayment Entry Reference` t2
Nabin Hait1991c7b2016-06-27 20:09:05 +05302102 where
Deepesh Gargc7eadfc2020-07-22 17:59:37 +05302103 t1.name = t2.parent and t1.{1} = %s and t1.payment_type = %s
Nabin Hait1991c7b2016-06-27 20:09:05 +05302104 and t1.party_type = %s and t1.party = %s and t1.docstatus = 1
Deepesh Gargc7eadfc2020-07-22 17:59:37 +05302105 and t2.reference_doctype = %s {2}
2106 order by t1.posting_date {3}
Ankush Menat494bd9e2022-03-28 18:52:46 +05302107 """.format(
2108 currency_field, party_account_field, reference_condition, limit_cond, exchange_rate_field
2109 ),
2110 [party_account, payment_type, party_type, party, order_doctype] + order_list,
2111 as_dict=1,
2112 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05302113
Nabin Hait1991c7b2016-06-27 20:09:05 +05302114 if include_unallocated:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302115 unallocated_payment_entries = frappe.db.sql(
2116 """
Anuja Pawar3e404f12021-08-31 18:59:29 +05302117 select "Payment Entry" as reference_type, name as reference_name, posting_date,
2118 remarks, unallocated_amount as amount, {2} as exchange_rate, {3} as currency
Nabin Hait1991c7b2016-06-27 20:09:05 +05302119 from `tabPayment Entry`
2120 where
2121 {0} = %s and party_type = %s and party = %s and payment_type = %s
Anuja Pawar3e404f12021-08-31 18:59:29 +05302122 and docstatus = 1 and unallocated_amount > 0 {condition}
Rohit Waghchauref7258162019-01-15 18:12:04 +05302123 order by posting_date {1}
Ankush Menat494bd9e2022-03-28 18:52:46 +05302124 """.format(
2125 party_account_field, limit_cond, exchange_rate_field, currency_field, condition=condition or ""
2126 ),
2127 (party_account, party_type, party, payment_type),
2128 as_dict=1,
2129 )
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05302130
Rohit Waghchaure2f1db572016-11-08 12:39:33 +05302131 return list(payment_entries_against_order) + list(unallocated_payment_entries)
2132
Ankush Menat494bd9e2022-03-28 18:52:46 +05302133
Rohit Waghchaure2f1db572016-11-08 12:39:33 +05302134def update_invoice_status():
Sagar Vorac8b9a552021-09-22 12:11:35 +05302135 """Updates status as Overdue for applicable invoices. Runs daily."""
Sagar Vora8d9d0982021-10-20 19:15:35 +05302136 today = getdate()
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302137 payment_schedule = frappe.qb.DocType("Payment Schedule")
Sagar Vorac8b9a552021-09-22 12:11:35 +05302138 for doctype in ("Sales Invoice", "Purchase Invoice"):
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302139 invoice = frappe.qb.DocType(doctype)
2140
2141 consider_base_amount = invoice.party_account_currency != invoice.currency
2142 payment_amount = (
2143 frappe.qb.terms.Case()
2144 .when(consider_base_amount, payment_schedule.base_payment_amount)
2145 .else_(payment_schedule.payment_amount)
Sagar Vora8d9d0982021-10-20 19:15:35 +05302146 )
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002147
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302148 payable_amount = (
2149 frappe.qb.from_(payment_schedule)
2150 .select(Sum(payment_amount))
Ankush Menat494bd9e2022-03-28 18:52:46 +05302151 .where((payment_schedule.parent == invoice.name) & (payment_schedule.due_date < today))
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302152 )
2153
2154 total = (
2155 frappe.qb.terms.Case()
2156 .when(invoice.disable_rounded_total, invoice.grand_total)
2157 .else_(invoice.rounded_total)
2158 )
2159
2160 base_total = (
2161 frappe.qb.terms.Case()
2162 .when(invoice.disable_rounded_total, invoice.base_grand_total)
2163 .else_(invoice.base_rounded_total)
2164 )
2165
Ankush Menat494bd9e2022-03-28 18:52:46 +05302166 total_amount = frappe.qb.terms.Case().when(consider_base_amount, base_total).else_(total)
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302167
2168 is_overdue = total_amount - invoice.outstanding_amount < payable_amount
2169
2170 conditions = (
2171 (invoice.docstatus == 1)
2172 & (invoice.outstanding_amount > 0)
Ankush Menat494bd9e2022-03-28 18:52:46 +05302173 & (invoice.status.like("Unpaid%") | invoice.status.like("Partly Paid%"))
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302174 & (
Pruthvi Patel16a90d32021-12-20 13:24:19 +05302175 ((invoice.is_pos & invoice.due_date < today) | is_overdue)
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302176 if doctype == "Sales Invoice"
2177 else is_overdue
2178 )
2179 )
2180
Pruthvi Patel0799f372021-11-12 12:56:29 +05302181 status = (
2182 frappe.qb.terms.Case()
2183 .when(invoice.status.like("%Discounted"), "Overdue and Discounted")
2184 .else_("Overdue")
2185 )
2186
2187 frappe.qb.update(invoice).set("status", status).where(conditions).run()
Pruthvi Patel6c96ed42021-10-30 16:44:15 +05302188
2189
Nabin Hait92759692017-08-15 08:23:51 +05302190@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +05302191def get_payment_terms(
2192 terms_template, posting_date=None, grand_total=None, base_grand_total=None, bill_date=None
2193):
Nabin Hait92759692017-08-15 08:23:51 +05302194 if not terms_template:
2195 return
2196
2197 terms_doc = frappe.get_doc("Payment Terms Template", terms_template)
2198
2199 schedule = []
tundefb144302017-08-19 15:01:40 +01002200 for d in terms_doc.get("terms"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302201 term_details = get_payment_term_details(
2202 d, posting_date, grand_total, base_grand_total, bill_date
2203 )
Nabin Hait92759692017-08-15 08:23:51 +05302204 schedule.append(term_details)
2205
2206 return schedule
2207
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002208
Nabin Hait92759692017-08-15 08:23:51 +05302209@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +05302210def get_payment_term_details(
2211 term, posting_date=None, grand_total=None, base_grand_total=None, bill_date=None
2212):
Nabin Hait92759692017-08-15 08:23:51 +05302213 term_details = frappe._dict()
Ankush Menat8fe5feb2021-11-04 19:48:32 +05302214 if isinstance(term, str):
Nabin Hait92759692017-08-15 08:23:51 +05302215 term = frappe.get_doc("Payment Term", term)
2216 else:
2217 term_details.payment_term = term.payment_term
2218 term_details.description = term.description
2219 term_details.invoice_portion = term.invoice_portion
Rohit Waghchaure52bf56d2017-11-27 11:43:52 +05302220 term_details.payment_amount = flt(term.invoice_portion) * flt(grand_total) / 100
Saqib Ansarid552fe62021-04-23 14:46:52 +05302221 term_details.base_payment_amount = flt(term.invoice_portion) * flt(base_grand_total) / 100
Saqib0586b7d2021-03-31 15:03:53 +05302222 term_details.discount_type = term.discount_type
2223 term_details.discount = term.discount
Saqib0586b7d2021-03-31 15:03:53 +05302224 term_details.outstanding = term_details.payment_amount
2225 term_details.mode_of_payment = term.mode_of_payment
2226
Shreya Shah3a9eec22018-02-16 13:05:21 +05302227 if bill_date:
2228 term_details.due_date = get_due_date(term, bill_date)
Saqib0586b7d2021-03-31 15:03:53 +05302229 term_details.discount_date = get_discount_date(term, bill_date)
Shreya Shah3a9eec22018-02-16 13:05:21 +05302230 elif posting_date:
2231 term_details.due_date = get_due_date(term, posting_date)
Saqib0586b7d2021-03-31 15:03:53 +05302232 term_details.discount_date = get_discount_date(term, posting_date)
Shreya Shah3a9eec22018-02-16 13:05:21 +05302233
2234 if getdate(term_details.due_date) < getdate(posting_date):
2235 term_details.due_date = posting_date
2236
Nabin Hait92759692017-08-15 08:23:51 +05302237 return term_details
2238
Ankush Menat494bd9e2022-03-28 18:52:46 +05302239
Shreya Shah3a9eec22018-02-16 13:05:21 +05302240def get_due_date(term, posting_date=None, bill_date=None):
Nabin Hait92759692017-08-15 08:23:51 +05302241 due_date = None
Shreya Shah3a9eec22018-02-16 13:05:21 +05302242 date = bill_date or posting_date
Nabin Hait92759692017-08-15 08:23:51 +05302243 if term.due_date_based_on == "Day(s) after invoice date":
Shreya Shah3a9eec22018-02-16 13:05:21 +05302244 due_date = add_days(date, term.credit_days)
Nabin Hait92759692017-08-15 08:23:51 +05302245 elif term.due_date_based_on == "Day(s) after the end of the invoice month":
Shreya Shah3a9eec22018-02-16 13:05:21 +05302246 due_date = add_days(get_last_day(date), term.credit_days)
Nabin Hait92759692017-08-15 08:23:51 +05302247 elif term.due_date_based_on == "Month(s) after the end of the invoice month":
Shreya Shah3a9eec22018-02-16 13:05:21 +05302248 due_date = add_months(get_last_day(date), term.credit_months)
tunde96b8f222017-09-08 15:35:59 +01002249 return due_date
tundebabzyad08d4c2018-05-16 07:01:41 +01002250
Ankush Menat494bd9e2022-03-28 18:52:46 +05302251
Saqib0586b7d2021-03-31 15:03:53 +05302252def get_discount_date(term, posting_date=None, bill_date=None):
2253 discount_validity = None
2254 date = bill_date or posting_date
2255 if term.discount_validity_based_on == "Day(s) after invoice date":
2256 discount_validity = add_days(date, term.discount_validity)
2257 elif term.discount_validity_based_on == "Day(s) after the end of the invoice month":
2258 discount_validity = add_days(get_last_day(date), term.discount_validity)
2259 elif term.discount_validity_based_on == "Month(s) after the end of the invoice month":
2260 discount_validity = add_months(get_last_day(date), term.discount_validity)
2261 return discount_validity
tundebabzyad08d4c2018-05-16 07:01:41 +01002262
Ankush Menat494bd9e2022-03-28 18:52:46 +05302263
tundebabzyad08d4c2018-05-16 07:01:41 +01002264def get_supplier_block_status(party_name):
2265 """
2266 Returns a dict containing the values of `on_hold`, `release_date` and `hold_type` of
2267 a `Supplier`
2268 """
Ankush Menat494bd9e2022-03-28 18:52:46 +05302269 supplier = frappe.get_doc("Supplier", party_name)
tundebabzyad08d4c2018-05-16 07:01:41 +01002270 info = {
Ankush Menat494bd9e2022-03-28 18:52:46 +05302271 "on_hold": supplier.on_hold,
2272 "release_date": supplier.release_date,
2273 "hold_type": supplier.hold_type,
tundebabzyad08d4c2018-05-16 07:01:41 +01002274 }
2275 return info
2276
Ankush Menat494bd9e2022-03-28 18:52:46 +05302277
marination698d9832020-08-19 14:59:46 +05302278def set_child_tax_template_and_map(item, child_item, parent_doc):
2279 args = {
Ankush Menat494bd9e2022-03-28 18:52:46 +05302280 "item_code": item.item_code,
2281 "posting_date": parent_doc.transaction_date,
2282 "tax_category": parent_doc.get("tax_category"),
2283 "company": parent_doc.get("company"),
2284 }
marination698d9832020-08-19 14:59:46 +05302285
2286 child_item.item_tax_template = _get_item_tax_template(args, item.taxes)
2287 if child_item.get("item_tax_template"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302288 child_item.item_tax_rate = get_item_tax_map(
2289 parent_doc.get("company"), child_item.item_tax_template, as_json=True
2290 )
2291
marination698d9832020-08-19 14:59:46 +05302292
Afshanb3bbebd2021-08-09 14:39:32 +05302293def add_taxes_from_tax_template(child_item, parent_doc, db_insert=True):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302294 add_taxes_from_item_tax_template = frappe.db.get_single_value(
2295 "Accounts Settings", "add_taxes_from_item_tax_template"
2296 )
Marica3b1be2b2020-10-22 17:04:31 +05302297
2298 if child_item.get("item_tax_rate") and add_taxes_from_item_tax_template:
2299 tax_map = json.loads(child_item.get("item_tax_rate"))
2300 for tax_type in tax_map:
2301 tax_rate = flt(tax_map[tax_type])
Ankush Menat494bd9e2022-03-28 18:52:46 +05302302 taxes = parent_doc.get("taxes") or []
Marica3b1be2b2020-10-22 17:04:31 +05302303 # add new row for tax head only if missing
2304 found = any(tax.account_head == tax_type for tax in taxes)
2305 if not found:
2306 tax_row = parent_doc.append("taxes", {})
Ankush Menat494bd9e2022-03-28 18:52:46 +05302307 tax_row.update(
2308 {
2309 "description": str(tax_type).split(" - ")[0],
2310 "charge_type": "On Net Total",
2311 "account_head": tax_type,
2312 "rate": tax_rate,
2313 }
2314 )
Marica3b1be2b2020-10-22 17:04:31 +05302315 if parent_doc.doctype == "Purchase Order":
Ankush Menat494bd9e2022-03-28 18:52:46 +05302316 tax_row.update({"category": "Total", "add_deduct_tax": "Add"})
Afshanb3bbebd2021-08-09 14:39:32 +05302317 if db_insert:
2318 tax_row.db_insert()
Marica3b1be2b2020-10-22 17:04:31 +05302319
Ankush Menat494bd9e2022-03-28 18:52:46 +05302320
2321def set_order_defaults(
2322 parent_doctype, parent_doctype_name, child_doctype, child_docname, trans_item
2323):
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002324 """
pateljannat637ddff2021-02-09 16:17:30 +05302325 Returns a Sales/Purchase Order Item child item containing the default values
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002326 """
Saqib438e0432020-04-03 10:02:56 +05302327 p_doc = frappe.get_doc(parent_doctype, parent_doctype_name)
pateljannat637ddff2021-02-09 16:17:30 +05302328 child_item = frappe.new_doc(child_doctype, p_doc, child_docname)
Ankush Menat494bd9e2022-03-28 18:52:46 +05302329 item = frappe.get_doc("Item", trans_item.get("item_code"))
marination0673f552021-03-31 01:38:22 +05302330
pateljannat637ddff2021-02-09 16:17:30 +05302331 for field in ("item_code", "item_name", "description", "item_group"):
marination0673f552021-03-31 01:38:22 +05302332 child_item.update({field: item.get(field)})
2333
pateljannat637ddff2021-02-09 16:17:30 +05302334 date_fieldname = "delivery_date" if child_doctype == "Sales Order Item" else "schedule_date"
Jannat Patelbb0d8f82021-02-11 20:59:28 +05302335 child_item.update({date_fieldname: trans_item.get(date_fieldname) or p_doc.get(date_fieldname)})
marination0673f552021-03-31 01:38:22 +05302336 child_item.stock_uom = item.stock_uom
Saqib61314242020-09-15 11:14:31 +05302337 child_item.uom = trans_item.get("uom") or item.stock_uom
Andy Zhu1062d7e2020-10-06 10:51:42 +13002338 child_item.warehouse = get_item_warehouse(item, p_doc, overwrite_warehouse=True)
Ankush Menat494bd9e2022-03-28 18:52:46 +05302339 conversion_factor = flt(
2340 get_conversion_factor(item.item_code, child_item.uom).get("conversion_factor")
2341 )
2342 child_item.conversion_factor = flt(trans_item.get("conversion_factor")) or conversion_factor
marination0673f552021-03-31 01:38:22 +05302343
pateljannat637ddff2021-02-09 16:17:30 +05302344 if child_doctype == "Purchase Order Item":
marination0673f552021-03-31 01:38:22 +05302345 # Initialized value will update in parent validation
2346 child_item.base_rate = 1
2347 child_item.base_amount = 1
pateljannat637ddff2021-02-09 16:17:30 +05302348 if child_doctype == "Sales Order Item":
2349 child_item.warehouse = get_item_warehouse(item, p_doc, overwrite_warehouse=True)
2350 if not child_item.warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302351 frappe.throw(
2352 _("Cannot find {} for item {}. Please set the same in Item Master or Stock Settings.").format(
2353 frappe.bold("default warehouse"), frappe.bold(item.item_code)
2354 )
2355 )
marination0673f552021-03-31 01:38:22 +05302356
marination698d9832020-08-19 14:59:46 +05302357 set_child_tax_template_and_map(item, child_item, p_doc)
Marica3b1be2b2020-10-22 17:04:31 +05302358 add_taxes_from_tax_template(child_item, p_doc)
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002359 return child_item
2360
Ankush Menat494bd9e2022-03-28 18:52:46 +05302361
marination0673f552021-03-31 01:38:22 +05302362def validate_child_on_delete(row, parent):
2363 """Check if partially transacted item (row) is being deleted."""
2364 if parent.doctype == "Sales Order":
2365 if flt(row.delivered_qty):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302366 frappe.throw(
2367 _("Row #{0}: Cannot delete item {1} which has already been delivered").format(
2368 row.idx, row.item_code
2369 )
2370 )
marination0673f552021-03-31 01:38:22 +05302371 if flt(row.work_order_qty):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302372 frappe.throw(
2373 _("Row #{0}: Cannot delete item {1} which has work order assigned to it.").format(
2374 row.idx, row.item_code
2375 )
2376 )
marination0673f552021-03-31 01:38:22 +05302377 if flt(row.ordered_qty):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302378 frappe.throw(
2379 _("Row #{0}: Cannot delete item {1} which is assigned to customer's purchase order.").format(
2380 row.idx, row.item_code
2381 )
2382 )
marination0673f552021-03-31 01:38:22 +05302383
2384 if parent.doctype == "Purchase Order" and flt(row.received_qty):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302385 frappe.throw(
2386 _("Row #{0}: Cannot delete item {1} which has already been received").format(
2387 row.idx, row.item_code
2388 )
2389 )
marination0673f552021-03-31 01:38:22 +05302390
2391 if flt(row.billed_amt):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302392 frappe.throw(
2393 _("Row #{0}: Cannot delete item {1} which has already been billed.").format(
2394 row.idx, row.item_code
2395 )
2396 )
2397
marination0673f552021-03-31 01:38:22 +05302398
2399def update_bin_on_delete(row, doctype):
2400 """Update bin for deleted item (row)."""
Chillar Anand915b3432021-09-02 16:44:59 +05302401 from erpnext.stock.stock_balance import (
2402 get_indented_qty,
2403 get_ordered_qty,
2404 get_reserved_qty,
2405 update_bin_qty,
2406 )
Ankush Menat494bd9e2022-03-28 18:52:46 +05302407
marination0673f552021-03-31 01:38:22 +05302408 qty_dict = {}
2409
2410 if doctype == "Sales Order":
2411 qty_dict["reserved_qty"] = get_reserved_qty(row.item_code, row.warehouse)
2412 else:
2413 if row.material_request_item:
2414 qty_dict["indented_qty"] = get_indented_qty(row.item_code, row.warehouse)
2415
2416 qty_dict["ordered_qty"] = get_ordered_qty(row.item_code, row.warehouse)
2417
Deepesh Garga61790c2022-02-22 20:58:10 +05302418 if row.warehouse:
2419 update_bin_qty(row.item_code, row.warehouse, qty_dict)
marination0673f552021-03-31 01:38:22 +05302420
Ankush Menat494bd9e2022-03-28 18:52:46 +05302421
Saqib6db92fb2020-09-14 19:54:17 +05302422def validate_and_delete_children(parent, data):
Saqib0ad74492019-12-24 16:42:30 +05302423 deleted_children = []
2424 updated_item_names = [d.get("docname") for d in data]
2425 for item in parent.items:
2426 if item.name not in updated_item_names:
2427 deleted_children.append(item)
2428
2429 for d in deleted_children:
marination0673f552021-03-31 01:38:22 +05302430 validate_child_on_delete(d, parent)
Saqib0ad74492019-12-24 16:42:30 +05302431 d.cancel()
2432 d.delete()
marination0673f552021-03-31 01:38:22 +05302433
2434 # need to update ordered qty in Material Request first
2435 # bin uses Material Request Items to recalculate & update
2436 parent.update_prevdoc_status()
2437
2438 for d in deleted_children:
2439 update_bin_on_delete(d, parent.doctype)
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002440
Rohan Bansala93b5142021-04-06 17:10:52 +05302441
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002442@frappe.whitelist()
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002443def update_child_qty_rate(parent_doctype, trans_items, parent_doctype_name, child_docname="items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05302444 def check_doc_permissions(doc, perm_type="create"):
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302445 try:
2446 doc.check_permission(perm_type)
Saqib6db92fb2020-09-14 19:54:17 +05302447 except frappe.PermissionError:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302448 actions = {"create": "add", "write": "update"}
Saqib6db92fb2020-09-14 19:54:17 +05302449
Ankush Menat494bd9e2022-03-28 18:52:46 +05302450 frappe.throw(
2451 _("You do not have permissions to {} items in a {}.").format(
2452 actions[perm_type], parent_doctype
2453 ),
2454 title=_("Insufficient Permissions"),
2455 )
marination665c27a2020-09-15 12:04:38 +05302456
Saqib6db92fb2020-09-14 19:54:17 +05302457 def validate_workflow_conditions(doc):
2458 workflow = get_workflow_name(doc.doctype)
2459 if not workflow:
2460 return
2461
2462 workflow_doc = frappe.get_doc("Workflow", workflow)
2463 current_state = doc.get(workflow_doc.workflow_state_field)
2464 roles = frappe.get_roles()
2465
2466 transitions = []
2467 for transition in workflow_doc.transitions:
2468 if transition.next_state == current_state and transition.allowed in roles:
2469 if not is_transition_condition_satisfied(transition, doc):
2470 continue
2471 transitions.append(transition.as_dict())
2472
2473 if not transitions:
Saqib18318932020-09-23 13:01:49 +05302474 frappe.throw(
Ankush Menat494bd9e2022-03-28 18:52:46 +05302475 _("You are not allowed to update as per the conditions set in {} Workflow.").format(
2476 get_link_to_form("Workflow", workflow)
2477 ),
2478 title=_("Insufficient Permissions"),
Saqib18318932020-09-23 13:01:49 +05302479 )
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302480
Rohit Waghchaure8d5380a2020-06-18 14:06:31 +05302481 def get_new_child_item(item_row):
Rohit Waghchaureff70e612021-03-06 22:08:08 +05302482 child_doctype = "Sales Order Item" if parent_doctype == "Sales Order" else "Purchase Order Item"
Ankush Menat494bd9e2022-03-28 18:52:46 +05302483 return set_order_defaults(
2484 parent_doctype, parent_doctype_name, child_doctype, child_docname, item_row
2485 )
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302486
marination0c915432022-05-10 18:04:02 +05302487 def validate_quantity(child_item, new_data):
2488 if not flt(new_data.get("qty")):
2489 frappe.throw(
2490 _("Row # {0}: Quantity for Item {1} cannot be zero").format(
2491 new_data.get("idx"), frappe.bold(new_data.get("item_code"))
2492 ),
2493 title=_("Invalid Qty"),
2494 )
2495
2496 if parent_doctype == "Sales Order" and flt(new_data.get("qty")) < flt(child_item.delivered_qty):
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302497 frappe.throw(_("Cannot set quantity less than delivered quantity"))
2498
marination0c915432022-05-10 18:04:02 +05302499 if parent_doctype == "Purchase Order" and flt(new_data.get("qty")) < flt(
2500 child_item.received_qty
2501 ):
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302502 frappe.throw(_("Cannot set quantity less than received quantity"))
2503
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002504 data = json.loads(trans_items)
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002505
Ankush Menat494bd9e2022-03-28 18:52:46 +05302506 sales_doctypes = ["Sales Order", "Sales Invoice", "Delivery Note", "Quotation"]
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302507 parent = frappe.get_doc(parent_doctype, parent_doctype_name)
marination665c27a2020-09-15 12:04:38 +05302508
Ankush Menat494bd9e2022-03-28 18:52:46 +05302509 check_doc_permissions(parent, "write")
Saqib6db92fb2020-09-14 19:54:17 +05302510 validate_and_delete_children(parent, data)
Saqib0ad74492019-12-24 16:42:30 +05302511
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002512 for d in data:
2513 new_child_flag = False
Ankush Menat6de7b8e2021-08-24 12:18:40 +05302514
2515 if not d.get("item_code"):
2516 # ignore empty rows
2517 continue
2518
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002519 if not d.get("docname"):
2520 new_child_flag = True
Ankush Menat494bd9e2022-03-28 18:52:46 +05302521 check_doc_permissions(parent, "create")
Rohit Waghchaure8d5380a2020-06-18 14:06:31 +05302522 child_item = get_new_child_item(d)
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002523 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302524 check_doc_permissions(parent, "write")
2525 child_item = frappe.get_doc(parent_doctype + " Item", d.get("docname"))
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302526
Saqib Ansaric579b082020-05-29 22:21:50 +05302527 prev_rate, new_rate = flt(child_item.get("rate")), flt(d.get("rate"))
2528 prev_qty, new_qty = flt(child_item.get("qty")), flt(d.get("qty"))
Ankush Menat494bd9e2022-03-28 18:52:46 +05302529 prev_con_fac, new_con_fac = flt(child_item.get("conversion_factor")), flt(
2530 d.get("conversion_factor")
2531 )
Saqib61314242020-09-15 11:14:31 +05302532 prev_uom, new_uom = child_item.get("uom"), d.get("uom")
Saqib Ansaric579b082020-05-29 22:21:50 +05302533
Ankush Menat494bd9e2022-03-28 18:52:46 +05302534 if parent_doctype == "Sales Order":
Saqib Ansaric579b082020-05-29 22:21:50 +05302535 prev_date, new_date = child_item.get("delivery_date"), d.get("delivery_date")
Ankush Menat494bd9e2022-03-28 18:52:46 +05302536 elif parent_doctype == "Purchase Order":
marinationb7e94cc2020-06-15 11:32:42 +05302537 prev_date, new_date = child_item.get("schedule_date"), d.get("schedule_date")
Saqib Ansaric579b082020-05-29 22:21:50 +05302538
2539 rate_unchanged = prev_rate == new_rate
marinationf9c4b202020-06-12 15:49:53 +05302540 qty_unchanged = prev_qty == new_qty
Saqib61314242020-09-15 11:14:31 +05302541 uom_unchanged = prev_uom == new_uom
Saqib Ansaric579b082020-05-29 22:21:50 +05302542 conversion_factor_unchanged = prev_con_fac == new_con_fac
Ankush Menat494bd9e2022-03-28 18:52:46 +05302543 date_unchanged = (
2544 prev_date == getdate(new_date) if prev_date and new_date else False
2545 ) # in case of delivery note etc
2546 if (
2547 rate_unchanged
2548 and qty_unchanged
2549 and conversion_factor_unchanged
2550 and uom_unchanged
2551 and date_unchanged
2552 ):
Saqibdd374ff2020-02-27 12:51:31 +05302553 continue
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002554
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302555 validate_quantity(child_item, d)
deepeshgarg00777cde832018-12-27 15:56:51 +05302556
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002557 child_item.qty = flt(d.get("qty"))
Saqib56fea7d2020-10-09 21:19:25 +05302558 rate_precision = child_item.precision("rate") or 2
2559 conv_fac_precision = child_item.precision("conversion_factor") or 2
2560 qty_precision = child_item.precision("qty") or 2
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002561
Ankush Menat494bd9e2022-03-28 18:52:46 +05302562 if flt(child_item.billed_amt, rate_precision) > flt(
2563 flt(d.get("rate"), rate_precision) * flt(d.get("qty"), qty_precision), rate_precision
2564 ):
2565 frappe.throw(
2566 _("Row #{0}: Cannot set Rate if amount is greater than billed amount for Item {1}.").format(
2567 child_item.idx, child_item.item_code
2568 )
2569 )
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002570 else:
Saqib56fea7d2020-10-09 21:19:25 +05302571 child_item.rate = flt(d.get("rate"), rate_precision)
marinationf9c4b202020-06-12 15:49:53 +05302572
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05302573 if d.get("conversion_factor"):
marinationf9c4b202020-06-12 15:49:53 +05302574 if child_item.stock_uom == child_item.uom:
2575 child_item.conversion_factor = 1
2576 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302577 child_item.conversion_factor = flt(d.get("conversion_factor"), conv_fac_precision)
marination665c27a2020-09-15 12:04:38 +05302578
Saqib61314242020-09-15 11:14:31 +05302579 if d.get("uom"):
2580 child_item.uom = d.get("uom")
Ankush Menat494bd9e2022-03-28 18:52:46 +05302581 conversion_factor = flt(
2582 get_conversion_factor(child_item.item_code, child_item.uom).get("conversion_factor")
2583 )
2584 child_item.conversion_factor = (
2585 flt(d.get("conversion_factor"), conv_fac_precision) or conversion_factor
2586 )
Mangesh-Khairnara3d52002019-08-05 10:16:40 +05302587
Ankush Menat494bd9e2022-03-28 18:52:46 +05302588 if d.get("delivery_date") and parent_doctype == "Sales Order":
2589 child_item.delivery_date = d.get("delivery_date")
marinationf9c4b202020-06-12 15:49:53 +05302590
Ankush Menat494bd9e2022-03-28 18:52:46 +05302591 if d.get("schedule_date") and parent_doctype == "Purchase Order":
2592 child_item.schedule_date = d.get("schedule_date")
Saqib Ansaric579b082020-05-29 22:21:50 +05302593
Mangesh-Khairnara3d52002019-08-05 10:16:40 +05302594 if flt(child_item.price_list_rate):
Maricaf0674472019-10-11 10:47:09 +05302595 if flt(child_item.rate) > flt(child_item.price_list_rate):
2596 # if rate is greater than price_list_rate, set margin
2597 # or set discount
2598 child_item.discount_percentage = 0
rohitwaghchaure81c21752019-10-31 15:56:10 +05302599
2600 if parent_doctype in sales_doctypes:
2601 child_item.margin_type = "Amount"
Ankush Menat494bd9e2022-03-28 18:52:46 +05302602 child_item.margin_rate_or_amount = flt(
2603 child_item.rate - child_item.price_list_rate, child_item.precision("margin_rate_or_amount")
2604 )
rohitwaghchaure81c21752019-10-31 15:56:10 +05302605 child_item.rate_with_margin = child_item.rate
Maricaf0674472019-10-11 10:47:09 +05302606 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05302607 child_item.discount_percentage = flt(
2608 (1 - flt(child_item.rate) / flt(child_item.price_list_rate)) * 100.0,
2609 child_item.precision("discount_percentage"),
2610 )
2611 child_item.discount_amount = flt(child_item.price_list_rate) - flt(child_item.rate)
rohitwaghchaure81c21752019-10-31 15:56:10 +05302612
2613 if parent_doctype in sales_doctypes:
2614 child_item.margin_type = ""
2615 child_item.margin_rate_or_amount = 0
2616 child_item.rate_with_margin = 0
Mangesh-Khairnara3d52002019-08-05 10:16:40 +05302617
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002618 child_item.flags.ignore_validate_update_after_submit = True
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002619 if new_child_flag:
Saqib Ansarif53299e2020-04-15 22:08:12 +05302620 parent.load_from_db()
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302621 child_item.idx = len(parent.items) + 1
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01002622 child_item.insert()
2623 else:
2624 child_item.save()
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002625
Rushabh Mehtafafbb022018-12-24 22:09:15 +05302626 parent.reload()
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302627 parent.flags.ignore_validate_update_after_submit = True
2628 parent.set_qty_as_per_stock_uom()
2629 parent.calculate_taxes_and_totals()
Ankush Menatdf6e2082021-02-11 11:04:39 +05302630 parent.set_total_in_words()
Nabin Hait49a46f02019-10-21 13:35:43 +05302631 if parent_doctype == "Sales Order":
Marica3dee5272020-06-23 10:33:47 +05302632 make_packing_list(parent)
Nabin Hait49a46f02019-10-21 13:35:43 +05302633 parent.set_gross_profit()
Ankush Menat494bd9e2022-03-28 18:52:46 +05302634 frappe.get_doc("Authorization Control").validate_approving_authority(
2635 parent.doctype, parent.company, parent.base_grand_total
2636 )
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08002637
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302638 parent.set_payment_schedule()
Ankush Menat494bd9e2022-03-28 18:52:46 +05302639 if parent_doctype == "Purchase Order":
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302640 parent.validate_minimum_order_qty()
2641 parent.validate_budget()
2642 if parent.is_against_so():
2643 parent.update_status_updater()
Nabin Haitb2da0822018-07-13 17:01:40 +05302644 else:
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302645 parent.check_credit_limit()
Ankush Menat733c9de2022-01-04 18:39:30 +05302646
2647 # reset index of child table
2648 for idx, row in enumerate(parent.get(child_docname), start=1):
2649 row.idx = idx
2650
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302651 parent.save()
Nabin Haitb2da0822018-07-13 17:01:40 +05302652
Ankush Menat494bd9e2022-03-28 18:52:46 +05302653 if parent_doctype == "Purchase Order":
2654 update_last_purchase_rate(parent, is_submit=1)
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302655 parent.update_prevdoc_status()
2656 parent.update_requested_qty()
2657 parent.update_ordered_qty()
2658 parent.update_ordered_and_reserved_qty()
2659 parent.update_receiving_percentage()
s-aga-r6d89b2f2022-06-18 15:46:59 +05302660 if parent.is_old_subcontracting_flow:
2661 parent.update_reserved_qty_for_subcontract()
2662 parent.create_raw_materials_supplied()
2663 parent.save()
Ankush Menatc84e11a2022-06-01 12:55:10 +05302664 else: # Sales Order
2665 parent.validate_warehouse()
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302666 parent.update_reserved_qty()
2667 parent.update_project()
Ankush Menat494bd9e2022-03-28 18:52:46 +05302668 parent.update_prevdoc_status("submit")
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302669 parent.update_delivery_status()
Nabin Haitb2da0822018-07-13 17:01:40 +05302670
Saqib6db92fb2020-09-14 19:54:17 +05302671 parent.reload()
2672 validate_workflow_conditions(parent)
2673
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05302674 parent.update_blanket_order()
2675 parent.update_billing_percentage()
2676 parent.set_status()
Gauravf1e28e02019-02-13 16:46:24 +05302677
Ankush Menat494bd9e2022-03-28 18:52:46 +05302678
Gauravf1e28e02019-02-13 16:46:24 +05302679@erpnext.allow_regional
2680def validate_regional(doc):
2681 pass
Saqib Ansaric5782b02022-01-27 20:09:56 +05302682
Ankush Menat494bd9e2022-03-28 18:52:46 +05302683
Saqib Ansaric5782b02022-01-27 20:09:56 +05302684@erpnext.allow_regional
2685def validate_einvoice_fields(doc):
2686 pass