blob: 7e778e094254566624d91ca8ce61de840f1b3fe6 [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
4from __future__ import unicode_literals
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +05305import frappe, erpnext
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08006import json
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05307from frappe import _, throw
rohitwaghchaurea85ddf22019-11-19 18:47:48 +05308from frappe.utils import (today, flt, cint, fmt_money, formatdate,
9 getdate, add_days, add_months, get_last_day, nowdate, get_link_to_form)
Saqib6db92fb2020-09-14 19:54:17 +053010from frappe.model.workflow import get_workflow_name, is_transition_condition_satisfied, WorkflowPermissionError
rohitwaghchaurea85ddf22019-11-19 18:47:48 +053011from erpnext.stock.get_item_details import get_conversion_factor, get_item_details
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +053012from erpnext.setup.utils import get_exchange_rate
Nabin Hait2ed0b592016-03-29 13:14:17 +053013from erpnext.accounts.utils import get_fiscal_years, validate_fiscal_year, get_account_currency
Nabin Hait436f5262014-02-10 14:47:54 +053014from erpnext.utilities.transaction_base import TransactionBase
Doridel Cahanap6f06cc22018-05-17 16:28:58 +080015from erpnext.buying.utils import update_last_purchase_rate
Nabin Hait3cf67a42015-07-24 13:26:36 +053016from erpnext.controllers.sales_and_purchase_return import validate_return
shreyas29b565f2016-01-25 17:30:49 +053017from erpnext.accounts.party import get_party_account_currency, validate_party_frozen_disabled
rohitwaghchaurea85ddf22019-11-19 18:47:48 +053018from erpnext.accounts.doctype.pricing_rule.utils import (apply_pricing_rule_on_transaction,
19 apply_pricing_rule_for_free_items, get_applied_pricing_rules)
shreyasf76853a2016-01-25 21:25:11 +053020from erpnext.exceptions import InvalidCurrency
Achilles Rasquinha90509982018-03-08 12:55:41 +053021from six import text_type
deepeshgarg007d83cf652019-05-12 18:34:23 +053022from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import get_accounting_dimensions
marination698d9832020-08-19 14:59:46 +053023from erpnext.stock.get_item_details import get_item_warehouse, _get_item_tax_template, get_item_tax_map
Marica3dee5272020-06-23 10:33:47 +053024from erpnext.stock.doctype.packed_item.packed_item import make_packing_list
prssanna71e5b602020-10-29 14:19:34 +053025from erpnext.controllers.print_settings import set_print_templates_for_item_table, set_print_templates_for_taxes
Nabin Hait1d218422015-07-17 15:19:02 +053026
marination53b1a9a2020-11-03 15:45:25 +053027class AccountMissingError(frappe.ValidationError): pass
28
Rohit Waghchaurebde159a2021-03-22 23:36:48 +053029force_item_fields = ("item_group", "brand", "stock_uom", "is_fixed_asset", "item_tax_rate",
30 "pricing_rules", "weight_per_unit", "weight_uom", "total_weight")
Doridel Cahanap6f06cc22018-05-17 16:28:58 +080031
Nabin Haitbf495c92013-01-30 12:49:08 +053032class AccountsController(TransactionBase):
Nabin Hait7eba1a32017-10-02 15:59:27 +053033 def __init__(self, *args, **kwargs):
34 super(AccountsController, self).__init__(*args, **kwargs)
Anand Doshi979326b2015-09-11 16:22:37 +053035
prssanna71e5b602020-10-29 14:19:34 +053036 def get_print_settings(self):
37 print_setting_fields = []
38 items_field = self.meta.get_field('items')
39
40 if items_field and items_field.fieldtype == 'Table':
41 print_setting_fields += ['compact_item_print', 'print_uom_after_quantity']
42
43 taxes_field = self.meta.get_field('taxes')
44 if taxes_field and taxes_field.fieldtype == 'Table':
45 print_setting_fields += ['print_taxes_with_zero_amount']
46
47 return print_setting_fields
48
Nabin Hait4ffd7f32015-08-27 12:28:36 +053049 @property
50 def company_currency(self):
51 if not hasattr(self, "__company_currency"):
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +053052 self.__company_currency = erpnext.get_company_currency(self.company)
Anand Doshi979326b2015-09-11 16:22:37 +053053
Nabin Hait4ffd7f32015-08-27 12:28:36 +053054 return self.__company_currency
Anand Doshi979326b2015-09-11 16:22:37 +053055
Rohit Waghchaure7d529892016-10-06 14:35:04 +053056 def onload(self):
Nabin Hait34c551d2019-07-03 10:34:31 +053057 self.set_onload("make_payment_via_journal_entry",
58 frappe.db.get_single_value('Accounts Settings', 'make_payment_via_journal_entry'))
Nabin Hait0551f7b2017-11-21 19:58:16 +053059
tundee52bb822017-09-25 09:02:23 +010060 if self.is_new():
Nabin Hait0551f7b2017-11-21 19:58:16 +053061 relevant_docs = ("Quotation", "Purchase Order", "Sales Order",
Doridel Cahanap6f06cc22018-05-17 16:28:58 +080062 "Purchase Invoice", "Sales Invoice")
tundee52bb822017-09-25 09:02:23 +010063 if self.doctype in relevant_docs:
64 self.set_payment_schedule()
Rohit Waghchaure7d529892016-10-06 14:35:04 +053065
tundebabzyad08d4c2018-05-16 07:01:41 +010066 def ensure_supplier_is_not_blocked(self):
67 is_supplier_payment = self.doctype == 'Payment Entry' and self.party_type == 'Supplier'
68 is_buying_invoice = self.doctype in ['Purchase Invoice', 'Purchase Order']
69 supplier = None
70 supplier_name = None
71
72 if is_buying_invoice or is_supplier_payment:
73 supplier_name = self.supplier if is_buying_invoice else self.party
74 supplier = frappe.get_doc('Supplier', supplier_name)
75
76 if supplier and supplier_name and supplier.on_hold:
77 if (is_buying_invoice and supplier.hold_type in ['All', 'Invoices']) or \
78 (is_supplier_payment and supplier.hold_type in ['All', 'Payments']):
79 if not supplier.release_date or getdate(nowdate()) <= supplier.release_date:
80 frappe.msgprint(
Suraj Shetty48e9bc32020-01-29 15:06:18 +053081 _('{0} is blocked so this transaction cannot proceed').format(supplier_name), raise_exception=1)
tundebabzyad08d4c2018-05-16 07:01:41 +010082
Saurabh6f753182013-03-20 12:55:28 +053083 def validate(self):
Deepesh Gargd301d262019-07-31 15:58:19 +053084 if not self.get('is_return'):
85 self.validate_qty_is_not_zero()
86
nabinhait23cce732014-07-03 12:25:06 +053087 if self.get("_action") and self._action != "update_after_submit":
Nabin Hait704a4532014-06-05 16:55:31 +053088 self.set_missing_values(for_validate=True)
tunde62af5c52017-09-22 15:16:38 +010089
tundebabzyad08d4c2018-05-16 07:01:41 +010090 self.ensure_supplier_is_not_blocked()
91
Nabin Haitcfecd2b2013-07-11 17:49:18 +053092 self.validate_date_with_fiscal_year()
Deepesh Gargb4be2922021-01-28 13:09:56 +053093 self.validate_inter_company_reference()
94
95 self.set_incoming_rate()
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +053096
Anand Doshi3543f302013-05-24 19:25:01 +053097 if self.meta.get_field("currency"):
Anand Doshi923d41d2013-05-28 17:23:36 +053098 self.calculate_taxes_and_totals()
Rohit Waghchaure6087fe12016-04-09 14:31:09 +053099
Nabin Hait1d218422015-07-17 15:19:02 +0530100 if not self.meta.get_field("is_return") or not self.is_return:
101 self.validate_value("base_grand_total", ">=", 0)
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530102
Nabin Hait3cf67a42015-07-24 13:26:36 +0530103 validate_return(self)
Anand Doshi3543f302013-05-24 19:25:01 +0530104 self.set_total_in_words()
Anand Doshid2946502014-04-08 20:10:03 +0530105
tunde62af5c52017-09-22 15:16:38 +0100106 self.validate_all_documents_schedule()
Anand Doshid2946502014-04-08 20:10:03 +0530107
ankitjavalkarwork6c29d872014-10-06 13:20:53 +0530108 if self.meta.get_field("taxes_and_charges"):
109 self.validate_enabled_taxes_and_charges()
Nabin Haita2426fc2018-01-15 17:45:46 +0530110 self.validate_tax_account_company()
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530111
Neil Trini Lasrado3fbbb712015-07-17 12:10:12 +0530112 self.validate_party()
Nabin Hait895029d2015-08-20 14:55:39 +0530113 self.validate_currency()
Rushabh Mehta2cb7a9f2016-06-15 16:45:03 +0530114
Rohit Waghchaure6087fe12016-04-09 14:31:09 +0530115 if self.doctype == 'Purchase Invoice':
Mangesh-Khairnar7bcb24e2019-09-11 10:49:33 +0530116 self.calculate_paid_amount()
Rohit Waghchaure6087fe12016-04-09 14:31:09 +0530117
Nabin Hait041a5c22018-08-01 18:07:39 +0530118 if self.doctype in ['Purchase Invoice', 'Sales Invoice']:
Nabin Hait4a994d42019-04-25 17:47:26 +0530119 pos_check_field = "is_pos" if self.doctype=="Sales Invoice" else "is_paid"
120 if cint(self.allocate_advances_automatically) and not cint(self.get(pos_check_field)):
Nabin Hait041a5c22018-08-01 18:07:39 +0530121 self.set_advances()
122
123 if self.is_return:
124 self.validate_qty()
Nabin Haitacdd5082019-12-04 15:30:01 +0530125 else:
126 self.validate_deferred_start_and_end_date()
rohitwaghchaure70489252018-06-11 12:02:14 +0530127
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530128 self.set_inter_company_account()
129
Gauravf1e28e02019-02-13 16:46:24 +0530130 validate_regional(self)
Deepesh Garg7c300852020-12-26 20:14:51 +0530131
Saqib6d74f5b2020-12-25 10:26:43 +0530132 validate_einvoice_fields(self)
133
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530134 if self.doctype != 'Material Request':
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530135 apply_pricing_rule_on_transaction(self)
Deepesh Garg7c300852020-12-26 20:14:51 +0530136
Saqib6d74f5b2020-12-25 10:26:43 +0530137 def before_cancel(self):
138 validate_einvoice_fields(self)
rohitwaghchaurebf7317d2021-02-01 20:22:14 +0530139
Saqib8e556772021-01-28 12:26:45 +0530140 def on_trash(self):
141 # delete sl and gl entries on deletion of transaction
142 if frappe.db.get_single_value('Accounts Settings', 'delete_linked_ledger_entries'):
143 frappe.db.sql("delete from `tabGL Entry` where voucher_type=%s and voucher_no=%s", (self.doctype, self.name))
144 frappe.db.sql("delete from `tabStock Ledger Entry` where voucher_type=%s and voucher_no=%s", (self.doctype, self.name))
Gauravf1e28e02019-02-13 16:46:24 +0530145
Nabin Haitacdd5082019-12-04 15:30:01 +0530146 def validate_deferred_start_and_end_date(self):
147 for d in self.items:
148 if d.get("enable_deferred_revenue") or d.get("enable_deferred_expense"):
149 if not (d.service_start_date and d.service_end_date):
150 frappe.throw(_("Row #{0}: Service Start and End Date is required for deferred accounting").format(d.idx))
151 elif getdate(d.service_start_date) > getdate(d.service_end_date):
152 frappe.throw(_("Row #{0}: Service Start Date cannot be greater than Service End Date").format(d.idx))
153 elif getdate(self.posting_date) > getdate(d.service_end_date):
154 frappe.throw(_("Row #{0}: Service End Date cannot be before Invoice Posting Date").format(d.idx))
155
tunde62af5c52017-09-22 15:16:38 +0100156 def validate_invoice_documents_schedule(self):
Nabin Hait0551f7b2017-11-21 19:58:16 +0530157 self.validate_payment_schedule_dates()
158 self.set_due_date()
Nabin Hait0551f7b2017-11-21 19:58:16 +0530159 self.set_payment_schedule()
160 self.validate_payment_schedule_amount()
tunde62af5c52017-09-22 15:16:38 +0100161 self.validate_due_date()
162 self.validate_advance_entries()
163
164 def validate_non_invoice_documents_schedule(self):
Nabin Hait0551f7b2017-11-21 19:58:16 +0530165 self.set_payment_schedule()
Nabin Hait2f9f4f92017-12-20 12:24:59 +0530166 self.validate_payment_schedule_dates()
Nabin Hait0551f7b2017-11-21 19:58:16 +0530167 self.validate_payment_schedule_amount()
tunde62af5c52017-09-22 15:16:38 +0100168
169 def validate_all_documents_schedule(self):
170 if self.doctype in ("Sales Invoice", "Purchase Invoice") and not self.is_return:
171 self.validate_invoice_documents_schedule()
172 elif self.doctype in ("Quotation", "Purchase Order", "Sales Order"):
173 self.validate_non_invoice_documents_schedule()
174
prssanna71e5b602020-10-29 14:19:34 +0530175 def before_print(self, settings=None):
Zarrarb9f54ca2018-05-28 17:41:09 +0530176 if self.doctype in ['Purchase Order', 'Sales Order', 'Sales Invoice', 'Purchase Invoice',
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800177 'Supplier Quotation', 'Purchase Receipt', 'Delivery Note', 'Quotation']:
KanchanChauhan49a50fe2016-11-18 13:57:53 +0530178 if self.get("group_same_items"):
179 self.group_similar_items()
180
Zarrar5be6d192018-11-08 12:16:26 +0530181 df = self.meta.get_field("discount_amount")
182 if self.get("discount_amount") and hasattr(self, "taxes") and not len(self.taxes):
183 df.set("print_hide", 0)
184 self.discount_amount = -self.discount_amount
185 else:
186 df.set("print_hide", 1)
187
prssanna71e5b602020-10-29 14:19:34 +0530188 set_print_templates_for_item_table(self, settings)
189 set_print_templates_for_taxes(self, settings)
190
Mangesh-Khairnar7bcb24e2019-09-11 10:49:33 +0530191 def calculate_paid_amount(self):
Saurabh43520f92016-03-21 18:32:48 +0530192 if hasattr(self, "is_pos") or hasattr(self, "is_paid"):
193 is_paid = self.get("is_pos") or self.get("is_paid")
Mangesh-Khairnar7bcb24e2019-09-11 10:49:33 +0530194
195 if is_paid:
196 if not self.cash_bank_account:
197 # show message that the amount is not paid
198 frappe.throw(_("Note: Payment Entry will not be created since 'Cash or Bank Account' was not specified"))
Marica23d7b092019-09-25 17:17:36 +0530199
Mangesh-Khairnar7bcb24e2019-09-11 10:49:33 +0530200 if cint(self.is_return) and self.grand_total > self.paid_amount:
201 self.paid_amount = flt(flt(self.grand_total), self.precision("paid_amount"))
202
203 elif not flt(self.paid_amount) and flt(self.outstanding_amount) > 0:
204 self.paid_amount = flt(flt(self.outstanding_amount), self.precision("paid_amount"))
205
206 self.base_paid_amount = flt(self.paid_amount * self.conversion_rate,
207 self.precision("base_paid_amount"))
Saurabh43520f92016-03-21 18:32:48 +0530208
Anand Doshiabc10032013-06-14 17:44:03 +0530209 def set_missing_values(self, for_validate=False):
Rohit Waghchaure5d97d892016-05-12 12:58:29 +0530210 if frappe.flags.in_test:
tunde62af5c52017-09-22 15:16:38 +0100211 for fieldname in ["posting_date", "transaction_date"]:
Rohit Waghchaure5d97d892016-05-12 12:58:29 +0530212 if self.meta.get_field(fieldname) and not self.get(fieldname):
213 self.set(fieldname, today())
214 break
Anand Doshid2946502014-04-08 20:10:03 +0530215
Nabin Hait3237c752015-02-17 11:11:11 +0530216 def calculate_taxes_and_totals(self):
Nabin Haitfe81da22015-02-18 12:23:18 +0530217 from erpnext.controllers.taxes_and_totals import calculate_taxes_and_totals
218 calculate_taxes_and_totals(self)
Nabin Hait3237c752015-02-17 11:11:11 +0530219
220 if self.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
221 self.calculate_commission()
222 self.calculate_contribution()
223
Nabin Haitcfecd2b2013-07-11 17:49:18 +0530224 def validate_date_with_fiscal_year(self):
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800225 if self.meta.get_field("fiscal_year"):
Nabin Haitcfecd2b2013-07-11 17:49:18 +0530226 date_field = ""
227 if self.meta.get_field("posting_date"):
228 date_field = "posting_date"
229 elif self.meta.get_field("transaction_date"):
230 date_field = "transaction_date"
Anand Doshid2946502014-04-08 20:10:03 +0530231
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530232 if date_field and self.get(date_field):
Rushabh Mehta66958302017-01-16 16:57:53 +0530233 validate_fiscal_year(self.get(date_field), self.fiscal_year, self.company,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800234 self.meta.get_label(date_field), self)
Anand Doshid2946502014-04-08 20:10:03 +0530235
Deepesh Gargb4be2922021-01-28 13:09:56 +0530236 def validate_inter_company_reference(self):
237 if self.doctype not in ('Purchase Invoice', 'Purchase Receipt', 'Purchase Order'):
238 return
239
240 if self.is_internal_transfer():
241 if not (self.get('inter_company_reference') or self.get('inter_company_invoice_reference')
242 or self.get('inter_company_order_reference')):
243 msg = _("Internal Sale or Delivery Reference missing. ")
244 msg += _("Please create purchase from internal sale or delivery document itself")
245 frappe.throw(msg, title=_("Internal Sales Reference Missing"))
246
Nabin Haite9daefe2014-08-27 16:46:33 +0530247 def validate_due_date(self):
rohitwaghchaureea943c62018-07-06 12:28:58 +0530248 if self.get('is_pos'): return
249
Nabin Haite9daefe2014-08-27 16:46:33 +0530250 from erpnext.accounts.party import validate_due_date
251 if self.doctype == "Sales Invoice":
Nabin Hait04d244a2015-07-22 17:47:49 +0530252 if not self.due_date:
253 frappe.throw(_("Due Date is mandatory"))
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530254
rohitwaghchaure3ffe8962018-07-13 17:40:48 +0530255 validate_due_date(self.posting_date, self.due_date,
256 "Customer", self.customer, self.company, self.payment_terms_template)
Nabin Haite9daefe2014-08-27 16:46:33 +0530257 elif self.doctype == "Purchase Invoice":
Rohit Waghchaured1a85a32018-11-26 18:42:29 +0530258 validate_due_date(self.bill_date or self.posting_date, self.due_date,
Saurabhd7897f12018-07-18 17:08:16 +0530259 "Supplier", self.supplier, self.company, self.bill_date, self.payment_terms_template)
Nabin Haite9daefe2014-08-27 16:46:33 +0530260
Nabin Hait096d3632013-10-17 17:01:14 +0530261 def set_price_list_currency(self, buying_or_selling):
Nabin Hait1cc55fb2016-12-08 14:09:23 +0530262 if self.meta.get_field("posting_date"):
Nabin Hait288a18e2016-12-08 15:36:23 +0530263 transaction_date = self.posting_date
Nabin Hait1cc55fb2016-12-08 14:09:23 +0530264 else:
Nabin Hait288a18e2016-12-08 15:36:23 +0530265 transaction_date = self.transaction_date
Rushabh Mehta66958302017-01-16 16:57:53 +0530266
Rushabh Mehta4a404e92013-08-09 18:11:35 +0530267 if self.meta.get_field("currency"):
Nabin Hait7a75e102013-09-17 10:21:20 +0530268 # price list part
Shreya3f778522018-05-15 16:59:20 +0530269 if buying_or_selling.lower() == "selling":
270 fieldname = "selling_price_list"
271 args = "for_selling"
272 else:
273 fieldname = "buying_price_list"
274 args = "for_buying"
275
Anand Doshif78d1ae2014-03-28 13:55:00 +0530276 if self.meta.get_field(fieldname) and self.get(fieldname):
277 self.price_list_currency = frappe.db.get_value("Price List",
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800278 self.get(fieldname), "currency")
Anand Doshid2946502014-04-08 20:10:03 +0530279
Nabin Hait6e439a52015-08-28 19:24:22 +0530280 if self.price_list_currency == self.company_currency:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530281 self.plc_conversion_rate = 1.0
Nabin Hait11f41952013-09-24 14:36:55 +0530282
Anand Doshif78d1ae2014-03-28 13:55:00 +0530283 elif not self.plc_conversion_rate:
Rushabh Mehta66958302017-01-16 16:57:53 +0530284 self.plc_conversion_rate = get_exchange_rate(self.price_list_currency,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800285 self.company_currency, transaction_date, args)
Anand Doshid2946502014-04-08 20:10:03 +0530286
Nabin Hait7a75e102013-09-17 10:21:20 +0530287 # currency
Anand Doshif78d1ae2014-03-28 13:55:00 +0530288 if not self.currency:
289 self.currency = self.price_list_currency
290 self.conversion_rate = self.plc_conversion_rate
Nabin Hait6e439a52015-08-28 19:24:22 +0530291 elif self.currency == self.company_currency:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530292 self.conversion_rate = 1.0
293 elif not self.conversion_rate:
Anand Doshidffec8f2014-07-01 17:45:15 +0530294 self.conversion_rate = get_exchange_rate(self.currency,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800295 self.company_currency, transaction_date, args)
Nabin Hait7a75e102013-09-17 10:21:20 +0530296
Nabin Haitcccc45e2016-10-05 17:15:43 +0530297 def set_missing_item_details(self, for_validate=False):
Anand Doshi3543f302013-05-24 19:25:01 +0530298 """set missing item values"""
Nabin Haitf37d43d2017-07-18 12:14:42 +0530299 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530300
Nabin Haitdd38a262014-12-26 13:15:21 +0530301 if hasattr(self, "items"):
Nabin Hait444f9562014-06-20 15:59:49 +0530302 parent_dict = {}
Pratik Vyasf7daab72014-04-10 17:53:30 +0530303 for fieldname in self.meta.get_valid_columns():
304 parent_dict[fieldname] = self.get(fieldname)
305
mbauskara52472c2016-03-05 15:10:25 +0530306 if self.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
307 document_type = "{} Item".format(self.doctype)
mbauskarc97becb2016-01-18 16:28:21 +0530308 parent_dict.update({"document_type": document_type})
309
Nabin Hait34c551d2019-07-03 10:34:31 +0530310 # party_name field used for customer in quotation
311 if self.doctype == "Quotation" and self.quotation_to == "Customer" and parent_dict.get("party_name"):
312 parent_dict.update({"customer": parent_dict.get("party_name")})
313
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530314 self.pricing_rules = []
Nabin Haitdd38a262014-12-26 13:15:21 +0530315 for item in self.get("items"):
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530316 if item.get("item_code"):
Nabin Hait444f9562014-06-20 15:59:49 +0530317 args = parent_dict.copy()
318 args.update(item.as_dict())
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530319
Nabin Hait34d28222016-01-19 15:45:49 +0530320 args["doctype"] = self.doctype
321 args["name"] = self.name
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530322 args["child_docname"] = item.name
Saqibac9e6ff2021-01-28 17:58:55 +0530323 args["ignore_pricing_rule"] = self.ignore_pricing_rule if hasattr(self, 'ignore_pricing_rule') else 0
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530324
Nabin Haite2f054c2015-03-09 14:54:37 +0530325 if not args.get("transaction_date"):
326 args["transaction_date"] = args.get("posting_date")
Anand Doshi2b2b6392015-03-20 14:18:09 +0530327
328 if self.get("is_subcontracted"):
329 args["is_subcontracted"] = self.is_subcontracted
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530330
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530331 ret = get_item_details(args, self, for_validate=True, overwrite_warehouse=False)
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530332
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530333 for fieldname, value in ret.items():
Anand Doshi602e8252015-11-16 19:05:46 +0530334 if item.meta.get_field(fieldname) and value is not None:
335 if (item.get(fieldname) is None or fieldname in force_item_fields):
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530336 item.set(fieldname, value)
Anand Doshid2946502014-04-08 20:10:03 +0530337
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530338 elif fieldname in ['cost_center', 'conversion_factor'] and not item.get(fieldname):
Anand Doshi602e8252015-11-16 19:05:46 +0530339 item.set(fieldname, value)
340
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530341 elif fieldname == "serial_no":
Alchez9155e402018-07-09 16:57:42 +0530342 # Ensure that serial numbers are matched against Stock UOM
343 item_conversion_factor = item.get("conversion_factor") or 1.0
344 item_qty = abs(item.get("qty")) * item_conversion_factor
Alchez8f2a0f32018-07-06 14:36:52 +0530345
346 if item_qty != len(get_serial_nos(item.get('serial_no'))):
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530347 item.set(fieldname, value)
Nabin Haita74468b2014-12-30 18:33:52 +0530348
Rohit Waghchauref6f503a2018-12-19 15:06:44 +0530349 if self.doctype in ["Purchase Invoice", "Sales Invoice"] and item.meta.get_field('is_fixed_asset'):
350 item.set('is_fixed_asset', ret.get('is_fixed_asset', 0))
351
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530352 if ret.get("pricing_rules"):
353 self.apply_pricing_rule_on_items(item, ret)
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530354 self.set_pricing_rule_details(item, ret)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530355
Nabin Hait14aa9c52016-04-18 15:54:01 +0530356 if self.doctype == "Purchase Invoice":
Nabin Haitcccc45e2016-10-05 17:15:43 +0530357 self.set_expense_account(for_validate)
Nabin Haita3dd72a2014-05-28 12:49:20 +0530358
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530359 def apply_pricing_rule_on_items(self, item, pricing_rule_args):
360 if not pricing_rule_args.get("validate_applied_rule", 0):
361 # if user changed the discount percentage then set user's discount percentage ?
362 if pricing_rule_args.get("price_or_product_discount") == 'Price':
363 item.set("pricing_rules", pricing_rule_args.get("pricing_rules"))
364 item.set("discount_percentage", pricing_rule_args.get("discount_percentage"))
365 item.set("discount_amount", pricing_rule_args.get("discount_amount"))
366 if pricing_rule_args.get("pricing_rule_for") == "Rate":
367 item.set("price_list_rate", pricing_rule_args.get("price_list_rate"))
368
369 if item.get("price_list_rate"):
370 item.rate = flt(item.price_list_rate *
371 (1.0 - (flt(item.discount_percentage) / 100.0)), item.precision("rate"))
372
373 if item.get('discount_amount'):
374 item.rate = item.price_list_rate - item.discount_amount
375
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530376 if item.get("apply_discount_on_discounted_rate") and pricing_rule_args.get("rate"):
377 item.rate = pricing_rule_args.get("rate")
378
Rohit Waghchaure21fe97e2019-12-13 16:18:38 +0530379 elif pricing_rule_args.get('free_item_data'):
380 apply_pricing_rule_for_free_items(self, pricing_rule_args.get('free_item_data'))
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530381
382 elif pricing_rule_args.get("validate_applied_rule"):
Rushabh Mehtaff5d1962020-08-25 11:59:57 +0530383 for pricing_rule in get_applied_pricing_rules(item.get('pricing_rules')):
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530384 pricing_rule_doc = frappe.get_cached_doc("Pricing Rule", pricing_rule)
385 for field in ['discount_percentage', 'discount_amount', 'rate']:
386 if item.get(field) < pricing_rule_doc.get(field):
387 title = get_link_to_form("Pricing Rule", pricing_rule)
388
389 frappe.msgprint(_("Row {0}: user has not applied the rule {1} on the item {2}")
390 .format(item.idx, frappe.bold(title), frappe.bold(item.item_code)))
391
Rohit Waghchaurea248dfb2020-07-16 17:27:26 +0530392 def set_pricing_rule_details(self, item_row, args):
393 pricing_rules = get_applied_pricing_rules(args.get("pricing_rules"))
394 if not pricing_rules: return
395
396 for pricing_rule in pricing_rules:
397 self.append("pricing_rules", {
398 "pricing_rule": pricing_rule,
399 "item_code": item_row.item_code,
400 "child_docname": item_row.name,
401 "rule_applied": True
402 })
403
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530404 def set_taxes(self):
405 if not self.meta.get_field("taxes"):
Anand Doshi3543f302013-05-24 19:25:01 +0530406 return
Anand Doshid2946502014-04-08 20:10:03 +0530407
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530408 tax_master_doctype = self.meta.get_field("taxes_and_charges").options
Anand Doshid2946502014-04-08 20:10:03 +0530409
rohitwaghchaure57914f12018-04-24 19:19:47 +0530410 if (self.is_new() or self.is_pos_profile_changed()) and not self.get("taxes"):
rohitwaghchaure505661b2017-12-11 14:52:28 +0530411 if self.company and not self.get("taxes_and_charges"):
Anand Doshi3543f302013-05-24 19:25:01 +0530412 # get the default tax master
rohitwaghchaure505661b2017-12-11 14:52:28 +0530413 self.taxes_and_charges = frappe.db.get_value(tax_master_doctype,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800414 {"is_default": 1, 'company': self.company})
Anand Doshid2946502014-04-08 20:10:03 +0530415
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530416 self.append_taxes_from_master(tax_master_doctype)
Anand Doshid2946502014-04-08 20:10:03 +0530417
rohitwaghchaure57914f12018-04-24 19:19:47 +0530418 def is_pos_profile_changed(self):
419 if (self.doctype == 'Sales Invoice' and self.is_pos and
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800420 self.pos_profile != frappe.db.get_value('Sales Invoice', self.name, 'pos_profile')):
rohitwaghchaure57914f12018-04-24 19:19:47 +0530421 return True
422
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530423 def append_taxes_from_master(self, tax_master_doctype=None):
424 if self.get("taxes_and_charges"):
Anand Doshi99100a42013-07-04 17:13:53 +0530425 if not tax_master_doctype:
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530426 tax_master_doctype = self.meta.get_field("taxes_and_charges").options
Anand Doshid2946502014-04-08 20:10:03 +0530427
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530428 self.extend("taxes", get_taxes_and_charges(tax_master_doctype, self.get("taxes_and_charges")))
Akhilesh Darjee4cdb7992014-01-30 13:56:57 +0530429
Anand Doshiac32bad2014-04-18 01:30:14 +0530430 def set_other_charges(self):
Nabin Haite7d15362014-12-25 16:01:55 +0530431 self.set("taxes", [])
Nabin Haitffc7f3f2015-05-12 15:07:02 +0530432 self.set_taxes()
Anand Doshid2946502014-04-08 20:10:03 +0530433
ankitjavalkarwork6c29d872014-10-06 13:20:53 +0530434 def validate_enabled_taxes_and_charges(self):
435 taxes_and_charges_doctype = self.meta.get_options("taxes_and_charges")
436 if frappe.db.get_value(taxes_and_charges_doctype, self.taxes_and_charges, "disabled"):
437 frappe.throw(_("{0} '{1}' is disabled").format(taxes_and_charges_doctype, self.taxes_and_charges))
438
Nabin Haita2426fc2018-01-15 17:45:46 +0530439 def validate_tax_account_company(self):
440 for d in self.get("taxes"):
441 if d.account_head:
442 tax_account_company = frappe.db.get_value("Account", d.account_head, "company")
443 if tax_account_company != self.company:
444 frappe.throw(_("Row #{0}: Account {1} does not belong to company {2}")
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800445 .format(d.idx, d.account_head, self.company))
Nabin Haita2426fc2018-01-15 17:45:46 +0530446
deepeshgarg0073d11ac02019-05-19 00:02:01 +0530447 def get_gl_dict(self, args, account_currency=None, item=None):
Nabin Hait2df4d542013-01-29 11:34:39 +0530448 """this method populates the common properties of a gl entry record"""
Rushabh Mehta2cb7a9f2016-06-15 16:45:03 +0530449
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530450 posting_date = args.get('posting_date') or self.get('posting_date')
451 fiscal_years = get_fiscal_years(posting_date, company=self.company)
Nabin Hait2ed0b592016-03-29 13:14:17 +0530452 if len(fiscal_years) > 1:
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800453 frappe.throw(_("Multiple fiscal years exist for the date {0}. Please set company in Fiscal Year").format(
454 formatdate(posting_date)))
Nabin Hait2ed0b592016-03-29 13:14:17 +0530455 else:
456 fiscal_year = fiscal_years[0][0]
Rushabh Mehta2cb7a9f2016-06-15 16:45:03 +0530457
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530458 gl_dict = frappe._dict({
Anand Doshid2946502014-04-08 20:10:03 +0530459 'company': self.company,
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530460 'posting_date': posting_date,
Nabin Hait2ed0b592016-03-29 13:14:17 +0530461 'fiscal_year': fiscal_year,
Anand Doshif78d1ae2014-03-28 13:55:00 +0530462 'voucher_type': self.doctype,
463 'voucher_no': self.name,
Nabin Hait5cd04a62019-05-27 11:44:06 +0530464 'remarks': self.get("remarks") or self.get("remark"),
Nabin Hait2df4d542013-01-29 11:34:39 +0530465 'debit': 0,
466 'credit': 0,
Nabin Hait46bcbaf2015-08-19 13:49:10 +0530467 'debit_in_account_currency': 0,
468 'credit_in_account_currency': 0,
Anand Doshif78d1ae2014-03-28 13:55:00 +0530469 'is_opening': self.get("is_opening") or "No",
Nabin Hait32251022014-08-29 11:18:32 +0530470 'party_type': None,
Nabin Hait591a5ab2016-05-26 17:41:39 +0530471 'party': None,
472 'project': self.get("project")
Nabin Hait2e296fa2013-08-28 18:53:11 +0530473 })
deepeshgarg007d83cf652019-05-12 18:34:23 +0530474
475 accounting_dimensions = get_accounting_dimensions()
476 dimension_dict = frappe._dict()
477
478 for dimension in accounting_dimensions:
479 dimension_dict[dimension] = self.get(dimension)
deepeshgarg0073d11ac02019-05-19 00:02:01 +0530480 if item and item.get(dimension):
481 dimension_dict[dimension] = item.get(dimension)
deepeshgarg007d83cf652019-05-12 18:34:23 +0530482
483 gl_dict.update(dimension_dict)
Nabin Hait2df4d542013-01-29 11:34:39 +0530484 gl_dict.update(args)
Anand Doshi979326b2015-09-11 16:22:37 +0530485
Nabin Hait895029d2015-08-20 14:55:39 +0530486 if not account_currency:
Anand Doshicd0989e2015-09-28 13:31:17 +0530487 account_currency = get_account_currency(gl_dict.account)
Anand Doshi979326b2015-09-11 16:22:37 +0530488
Rushabh Mehtabc4e2cd2017-10-17 12:30:34 +0530489 if gl_dict.account and self.doctype not in ["Journal Entry",
Deepesh Gargbfc17e42020-12-25 18:34:39 +0530490 "Period Closing Voucher", "Payment Entry", "Purchase Receipt", "Purchase Invoice", "Stock Entry"]:
Anand Doshibe6cfdd2015-09-17 21:07:04 +0530491 self.validate_account_currency(gl_dict.account, account_currency)
Deepesh Garg7c300852020-12-26 20:14:51 +0530492
493 if gl_dict.account and self.doctype not in ["Journal Entry", "Period Closing Voucher", "Payment Entry"]:
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800494 set_balance_in_account_currency(gl_dict, account_currency, self.get("conversion_rate"),
495 self.company_currency)
Anand Doshi979326b2015-09-11 16:22:37 +0530496
Nabin Haitc561a492015-08-19 19:22:34 +0530497 return gl_dict
Anand Doshi979326b2015-09-11 16:22:37 +0530498
Anurag Mishrae657fe82018-11-26 15:19:17 +0530499 def validate_qty_is_not_zero(self):
Maricac68a9402019-12-03 12:59:22 +0530500 if self.doctype != "Purchase Receipt":
501 for item in self.items:
502 if not item.qty:
503 frappe.throw(_("Item quantity can not be zero"))
Anurag Mishrae657fe82018-11-26 15:19:17 +0530504
Nabin Hait895029d2015-08-20 14:55:39 +0530505 def validate_account_currency(self, account, account_currency=None):
Nabin Hait6e439a52015-08-28 19:24:22 +0530506 valid_currency = [self.company_currency]
507 if self.get("currency") and self.currency != self.company_currency:
508 valid_currency.append(self.currency)
509
Nabin Hait895029d2015-08-20 14:55:39 +0530510 if account_currency not in valid_currency:
Nabin Hait4ffd7f32015-08-27 12:28:36 +0530511 frappe.throw(_("Account {0} is invalid. Account Currency must be {1}")
Suraj Shettyda6806e2020-04-08 09:32:41 +0530512 .format(account, (' ' + _("or") + ' ').join(valid_currency)))
Anand Doshi979326b2015-09-11 16:22:37 +0530513
Anand Doshi613cb6a2013-02-06 17:33:46 +0530514 def clear_unallocated_advances(self, childtype, parentfield):
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530515 self.set(parentfield, self.get(parentfield, {"allocated_amount": ["not in", [0, None, ""]]}))
516
Anand Doshid2946502014-04-08 20:10:03 +0530517 frappe.db.sql("""delete from `tab%s` where parentfield=%s and parent = %s
Anand Doshi602e8252015-11-16 19:05:46 +0530518 and allocated_amount = 0""" % (childtype, '%s', '%s'), (parentfield, self.name))
Anand Doshid2946502014-04-08 20:10:03 +0530519
Walstan Baptistad6360752021-03-31 12:30:32 +0530520 @frappe.whitelist()
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530521 def apply_shipping_rule(self):
522 if self.shipping_rule:
523 shipping_rule = frappe.get_doc("Shipping Rule", self.shipping_rule)
524 shipping_rule.apply(self)
525 self.calculate_taxes_and_totals()
526
527 def get_shipping_address(self):
528 '''Returns Address object from shipping address fields if present'''
529
530 # shipping address fields can be `shipping_address_name` or `shipping_address`
531 # try getting value from both
532
533 for fieldname in ('shipping_address_name', 'shipping_address'):
534 shipping_field = self.meta.get_field(fieldname)
535 if shipping_field and shipping_field.fieldtype == 'Link':
536 if self.get(fieldname):
537 return frappe.get_doc('Address', self.get(fieldname))
538
539 return {}
540
Walstan Baptistad6360752021-03-31 12:30:32 +0530541 @frappe.whitelist()
Nabin Hait041a5c22018-08-01 18:07:39 +0530542 def set_advances(self):
543 """Returns list of advances against Account, Party, Reference"""
544
545 res = self.get_advance_entries()
546
547 self.set("advances", [])
548 advance_allocated = 0
549 for d in res:
550 if d.against_order:
551 allocated_amount = flt(d.amount)
552 else:
Deepesh Garg26210162020-08-11 16:06:13 +0530553 if self.get('party_account_currency') == self.company_currency:
554 amount = self.get('base_rounded_total') or self.base_grand_total
555 else:
556 amount = self.get('rounded_total') or self.grand_total
557
Rohit Waghchaure6cc2f522018-11-27 12:07:03 +0530558 allocated_amount = min(amount - advance_allocated, d.amount)
Nabin Hait041a5c22018-08-01 18:07:39 +0530559 advance_allocated += flt(allocated_amount)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530560
Nabin Hait041a5c22018-08-01 18:07:39 +0530561 self.append("advances", {
562 "doctype": self.doctype + " Advance",
563 "reference_type": d.reference_type,
564 "reference_name": d.reference_name,
565 "reference_row": d.reference_row,
566 "remarks": d.remarks,
567 "advance_amount": flt(d.amount),
568 "allocated_amount": allocated_amount
569 })
570
Nabin Hait28a05282016-06-27 17:41:39 +0530571 def get_advance_entries(self, include_unallocated=True):
572 if self.doctype == "Sales Invoice":
573 party_account = self.debit_to
574 party_type = "Customer"
575 party = self.customer
576 amount_field = "credit_in_account_currency"
577 order_field = "sales_order"
578 order_doctype = "Sales Order"
579 else:
580 party_account = self.credit_to
581 party_type = "Supplier"
582 party = self.supplier
583 amount_field = "debit_in_account_currency"
584 order_field = "purchase_order"
585 order_doctype = "Purchase Order"
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530586
587 order_list = list(set([d.get(order_field)
Nabin Hait868766d2019-07-15 18:02:58 +0530588 for d in self.get("items") if d.get(order_field)]))
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530589
590 journal_entries = get_advance_journal_entries(party_type, party, party_account,
Nabin Hait868766d2019-07-15 18:02:58 +0530591 amount_field, order_doctype, order_list, include_unallocated)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530592
593 payment_entries = get_advance_payment_entries(party_type, party, party_account,
Nabin Hait868766d2019-07-15 18:02:58 +0530594 order_doctype, order_list, include_unallocated)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530595
Nabin Hait28a05282016-06-27 17:41:39 +0530596 res = journal_entries + payment_entries
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530597
Nabin Hait28a05282016-06-27 17:41:39 +0530598 return res
Nabin Hait48f5fa62014-09-18 15:03:54 +0530599
rohitwaghchaurebf4c1142018-01-08 15:20:15 +0530600 def is_inclusive_tax(self):
Nabin Hait868766d2019-07-15 18:02:58 +0530601 is_inclusive = cint(frappe.db.get_single_value("Accounts Settings", "show_inclusive_tax_in_print"))
rohitwaghchaurebf4c1142018-01-08 15:20:15 +0530602
603 if is_inclusive:
604 is_inclusive = 0
605 if self.get("taxes", filters={"included_in_print_rate": 1}):
606 is_inclusive = 1
607
608 return is_inclusive
609
Nabin Hait28a05282016-06-27 17:41:39 +0530610 def validate_advance_entries(self):
Nabin Hait05aefbb2016-06-28 19:42:19 +0530611 order_field = "sales_order" if self.doctype == "Sales Invoice" else "purchase_order"
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530612 order_list = list(set([d.get(order_field)
Nabin Hait868766d2019-07-15 18:02:58 +0530613 for d in self.get("items") if d.get(order_field)]))
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530614
Nabin Hait05aefbb2016-06-28 19:42:19 +0530615 if not order_list: return
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530616
Nabin Hait28a05282016-06-27 17:41:39 +0530617 advance_entries = self.get_advance_entries(include_unallocated=False)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530618
Nabin Hait28a05282016-06-27 17:41:39 +0530619 if advance_entries:
620 advance_entries_against_si = [d.reference_name for d in self.get("advances")]
621 for d in advance_entries:
622 if not advance_entries_against_si or d.reference_name not in advance_entries_against_si:
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800623 frappe.msgprint(_(
624 "Payment Entry {0} is linked against Order {1}, check if it should be pulled as advance in this invoice.")
Nabin Hait868766d2019-07-15 18:02:58 +0530625 .format(d.reference_name, d.against_order))
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530626
Nabin Hait28a05282016-06-27 17:41:39 +0530627 def update_against_document_in_jv(self):
628 """
629 Links invoice and advance voucher:
630 1. cancel advance voucher
631 2. split into multiple rows if partially adjusted, assign against voucher
632 3. submit advance voucher
633 """
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530634
Nabin Hait28a05282016-06-27 17:41:39 +0530635 if self.doctype == "Sales Invoice":
Nabin Haitff2f3ef2016-07-04 11:41:14 +0530636 party_type = "Customer"
Nabin Hait28a05282016-06-27 17:41:39 +0530637 party = self.customer
638 party_account = self.debit_to
639 dr_or_cr = "credit_in_account_currency"
640 else:
Nabin Haitff2f3ef2016-07-04 11:41:14 +0530641 party_type = "Supplier"
Nabin Hait28a05282016-06-27 17:41:39 +0530642 party = self.supplier
643 party_account = self.credit_to
644 dr_or_cr = "debit_in_account_currency"
Nabin Hait48f5fa62014-09-18 15:03:54 +0530645
Nabin Hait28a05282016-06-27 17:41:39 +0530646 lst = []
647 for d in self.get('advances'):
648 if flt(d.allocated_amount) > 0:
649 args = frappe._dict({
650 'voucher_type': d.reference_type,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800651 'voucher_no': d.reference_name,
652 'voucher_detail_no': d.reference_row,
653 'against_voucher_type': self.doctype,
654 'against_voucher': self.name,
655 'account': party_account,
Nabin Haitff2f3ef2016-07-04 11:41:14 +0530656 'party_type': party_type,
Nabin Hait28a05282016-06-27 17:41:39 +0530657 'party': party,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800658 'is_advance': 'Yes',
659 'dr_or_cr': dr_or_cr,
660 'unadjusted_amount': flt(d.advance_amount),
661 'allocated_amount': flt(d.allocated_amount),
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530662 'exchange_rate': (self.conversion_rate
Nabin Hait868766d2019-07-15 18:02:58 +0530663 if self.party_account_currency != self.company_currency else 1),
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530664 'grand_total': (self.base_grand_total
Nabin Hait868766d2019-07-15 18:02:58 +0530665 if self.party_account_currency == self.company_currency else self.grand_total),
Nabin Hait28a05282016-06-27 17:41:39 +0530666 'outstanding_amount': self.outstanding_amount
667 })
668 lst.append(args)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530669
Nabin Hait28a05282016-06-27 17:41:39 +0530670 if lst:
671 from erpnext.accounts.utils import reconcile_against_document
672 reconcile_against_document(lst)
Anand Doshid2946502014-04-08 20:10:03 +0530673
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +0530674 def on_cancel(self):
675 from erpnext.accounts.utils import unlink_ref_doc_from_payment_entries
676
677 if self.doctype in ["Sales Invoice", "Purchase Invoice"]:
678 if frappe.db.get_single_value('Accounts Settings', 'unlink_payment_on_cancellation_of_invoice'):
679 unlink_ref_doc_from_payment_entries(self)
680
681 elif self.doctype in ["Sales Order", "Purchase Order"]:
Rohit Waghchaure9835c892019-04-01 01:02:06 +0530682 if frappe.db.get_single_value('Accounts Settings', 'unlink_advance_payment_on_cancelation_of_order'):
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +0530683 unlink_ref_doc_from_payment_entries(self)
684
Nabin Hait19d945a2013-07-29 18:35:39 +0530685 def validate_multiple_billing(self, ref_dt, item_ref_dn, based_on, parentfield):
Nabin Hait868766d2019-07-15 18:02:58 +0530686 from erpnext.controllers.status_updater import get_allowance_for
687 item_allowance = {}
688 global_qty_allowance, global_amount_allowance = None, None
Anand Doshid2946502014-04-08 20:10:03 +0530689
Nabin Hait4b8185d2014-12-25 18:19:39 +0530690 for item in self.get("items"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530691 if item.get(item_ref_dn):
Anand Doshid2946502014-04-08 20:10:03 +0530692 ref_amt = flt(frappe.db.get_value(ref_dt + " Item",
Nabin Hait868766d2019-07-15 18:02:58 +0530693 item.get(item_ref_dn), based_on), self.precision(based_on, item))
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530694 if not ref_amt:
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800695 frappe.msgprint(
Nabin Hait868766d2019-07-15 18:02:58 +0530696 _("Warning: System will not check overbilling since amount for Item {0} in {1} is zero")
697 .format(item.item_code, ref_dt))
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530698 else:
Nabin Hait868766d2019-07-15 18:02:58 +0530699 already_billed = frappe.db.sql("""
700 select sum(%s)
701 from `tab%s`
702 where %s=%s and docstatus=1 and parent != %s
703 """ % (based_on, self.doctype + " Item", item_ref_dn, '%s', '%s'),
704 (item.get(item_ref_dn), self.name))[0][0]
Anand Doshid2946502014-04-08 20:10:03 +0530705
706 total_billed_amt = flt(flt(already_billed) + flt(item.get(based_on)),
Nabin Hait868766d2019-07-15 18:02:58 +0530707 self.precision(based_on, item))
Anand Doshid2946502014-04-08 20:10:03 +0530708
Nabin Hait868766d2019-07-15 18:02:58 +0530709 allowance, item_allowance, global_qty_allowance, global_amount_allowance = \
710 get_allowance_for(item.item_code, item_allowance, global_qty_allowance, global_amount_allowance, "amount")
Anand Doshid2946502014-04-08 20:10:03 +0530711
Nabin Hait868766d2019-07-15 18:02:58 +0530712 max_allowed_amt = flt(ref_amt * (100 + allowance) / 100)
Anand Doshid2946502014-04-08 20:10:03 +0530713
rohitwaghchaure285344e2019-10-11 11:02:11 +0530714 if total_billed_amt < 0 and max_allowed_amt < 0:
715 # while making debit note against purchase return entry(purchase receipt) getting overbill error
716 total_billed_amt = abs(total_billed_amt)
717 max_allowed_amt = abs(max_allowed_amt)
718
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530719 if total_billed_amt - max_allowed_amt > 0.01:
rohitwaghchaure285344e2019-10-11 11:02:11 +0530720 frappe.throw(_("Cannot overbill for Item {0} in row {1} more than {2}. To allow over-billing, please set allowance in Accounts Settings")
Nabin Hait868766d2019-07-15 18:02:58 +0530721 .format(item.item_code, item.idx, max_allowed_amt))
Anand Doshid2946502014-04-08 20:10:03 +0530722
Nabin Hait0fc24542013-03-25 11:06:00 +0530723 def get_company_default(self, fieldname):
Rushabh Mehta1f847992013-12-12 19:12:19 +0530724 from erpnext.accounts.utils import get_company_default
Anand Doshif78d1ae2014-03-28 13:55:00 +0530725 return get_company_default(self.company, fieldname)
Anand Doshid2946502014-04-08 20:10:03 +0530726
Nabin Haita36adbd2013-08-02 14:50:12 +0530727 def get_stock_items(self):
728 stock_items = []
Nabin Haitdd38a262014-12-26 13:15:21 +0530729 item_codes = list(set(item.item_code for item in self.get("items")))
Nabin Haita36adbd2013-08-02 14:50:12 +0530730 if item_codes:
Nabin Hait868766d2019-07-15 18:02:58 +0530731 stock_items = [r[0] for r in frappe.db.sql("""
732 select name from `tabItem`
733 where name in (%s) and is_stock_item=1
734 """ % (", ".join((["%s"] * len(item_codes))),), item_codes)]
Anand Doshid2946502014-04-08 20:10:03 +0530735
Nabin Haita36adbd2013-08-02 14:50:12 +0530736 return stock_items
Anand Doshid2946502014-04-08 20:10:03 +0530737
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530738 def set_total_advance_paid(self):
739 if self.doctype == "Sales Order":
Nabin Hait6e439a52015-08-28 19:24:22 +0530740 dr_or_cr = "credit_in_account_currency"
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530741 rev_dr_or_cr = "debit_in_account_currency"
Nabin Haitb2206d12016-01-27 15:43:12 +0530742 party = self.customer
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530743 else:
Nabin Hait6e439a52015-08-28 19:24:22 +0530744 dr_or_cr = "debit_in_account_currency"
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530745 rev_dr_or_cr = "credit_in_account_currency"
Nabin Haitb2206d12016-01-27 15:43:12 +0530746 party = self.supplier
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530747
Nabin Haitb2206d12016-01-27 15:43:12 +0530748 advance = frappe.db.sql("""
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530749 select
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530750 account_currency, sum({dr_or_cr}) - sum({rev_dr_cr}) as amount
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530751 from
Nabin Hait12e2a512016-06-26 01:37:21 +0530752 `tabGL Entry`
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530753 where
Nabin Hait12e2a512016-06-26 01:37:21 +0530754 against_voucher_type = %s and against_voucher = %s and party=%s
755 and docstatus = 1
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530756 """.format(dr_or_cr=dr_or_cr, rev_dr_cr=rev_dr_or_cr), (self.doctype, self.name, party), as_dict=1) #nosec
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530757
Nabin Haitb2206d12016-01-27 15:43:12 +0530758 if advance:
Anand Doshi7c0a58a2016-01-29 12:16:24 +0530759 advance = advance[0]
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530760
Anand Doshi7c0a58a2016-01-29 12:16:24 +0530761 advance_paid = flt(advance.amount, self.precision("advance_paid"))
762 formatted_advance_paid = fmt_money(advance_paid, precision=self.precision("advance_paid"),
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800763 currency=advance.account_currency)
Anand Doshi7c0a58a2016-01-29 12:16:24 +0530764
765 frappe.db.set_value(self.doctype, self.name, "party_account_currency",
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800766 advance.account_currency)
Anand Doshi7c0a58a2016-01-29 12:16:24 +0530767
768 if advance.account_currency == self.currency:
finbyz5efc7972019-01-05 11:12:11 +0530769 order_total = self.get("rounded_total") or self.grand_total
770 precision = "rounded_total" if self.get("rounded_total") else "grand_total"
Nabin Haitb2206d12016-01-27 15:43:12 +0530771 else:
finbyz5efc7972019-01-05 11:12:11 +0530772 order_total = self.get("base_rounded_total") or self.base_grand_total
773 precision = "base_rounded_total" if self.get("base_rounded_total") else "base_grand_total"
Sagar Voraf733a392019-01-07 14:24:01 +0530774
finbyz5efc7972019-01-05 11:12:11 +0530775 formatted_order_total = fmt_money(order_total, precision=self.precision(precision),
776 currency=advance.account_currency)
Anand Doshi7c0a58a2016-01-29 12:16:24 +0530777
Nabin Hait9db1b222016-06-30 12:37:53 +0530778 if self.currency == self.company_currency and advance_paid > order_total:
Nabin Haitb2206d12016-01-27 15:43:12 +0530779 frappe.throw(_("Total advance ({0}) against Order {1} cannot be greater than the Grand Total ({2})")
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800780 .format(formatted_advance_paid, self.name, formatted_order_total))
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530781
Nabin Hait13093b42016-06-29 18:04:37 +0530782 frappe.db.set_value(self.doctype, self.name, "advance_paid", advance_paid)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530783
ankitjavalkarworke60822b2014-08-26 14:29:06 +0530784 @property
785 def company_abbr(self):
Nabin Hait6a5695f2018-08-09 11:30:21 +0530786 if not hasattr(self, "_abbr"):
787 self._abbr = frappe.db.get_value('Company', self.company, "abbr")
ankitjavalkarworke60822b2014-08-26 14:29:06 +0530788
789 return self._abbr
790
marination4be5b5c2020-10-08 19:08:27 +0530791 def raise_missing_debit_credit_account_error(self, party_type, party):
marination53b1a9a2020-11-03 15:45:25 +0530792 """Raise an error if debit to/credit to account does not exist."""
marination4be5b5c2020-10-08 19:08:27 +0530793 db_or_cr = frappe.bold("Debit To") if self.doctype == "Sales Invoice" else frappe.bold("Credit To")
794 rec_or_pay = "Receivable" if self.doctype == "Sales Invoice" else "Payable"
795
796 link_to_party = frappe.utils.get_link_to_form(party_type, party)
797 link_to_company = frappe.utils.get_link_to_form("Company", self.company)
798
799 message = _("{0} Account not found against Customer {1}.").format(db_or_cr, frappe.bold(party) or '')
800 message += "<br>" + _("Please set one of the following:") + "<br>"
801 message += "<br><ul><li>" + _("'Account' in the Accounting section of Customer {0}").format(link_to_party) + "</li>"
802 message += "<li>" + _("'Default {0} Account' in Company {1}").format(rec_or_pay, link_to_company) + "</li></ul>"
803
marination53b1a9a2020-11-03 15:45:25 +0530804 frappe.throw(message, title=_("Account Missing"), exc=AccountMissingError)
marination4be5b5c2020-10-08 19:08:27 +0530805
Neil Trini Lasrado3fbbb712015-07-17 12:10:12 +0530806 def validate_party(self):
Nabin Hait4ffd7f32015-08-27 12:28:36 +0530807 party_type, party = self.get_party()
shreyaseba9ca42016-01-26 14:56:52 +0530808 validate_party_frozen_disabled(party_type, party)
Anand Doshi979326b2015-09-11 16:22:37 +0530809
Nabin Hait4ffd7f32015-08-27 12:28:36 +0530810 def get_party(self):
Neil Trini Lasrado79bf2332015-07-20 13:03:48 +0530811 party_type = None
shreyas29b565f2016-01-25 17:30:49 +0530812 if self.doctype in ("Opportunity", "Quotation", "Sales Order", "Delivery Note", "Sales Invoice"):
shreyaseba9ca42016-01-26 14:56:52 +0530813 party_type = 'Customer'
shreyas29b565f2016-01-25 17:30:49 +0530814
815 elif self.doctype in ("Supplier Quotation", "Purchase Order", "Purchase Receipt", "Purchase Invoice"):
shreyaseba9ca42016-01-26 14:56:52 +0530816 party_type = 'Supplier'
shreyas29b565f2016-01-25 17:30:49 +0530817
818 elif self.meta.get_field("customer"):
819 party_type = "Customer"
Neil Trini Lasrado3fbbb712015-07-17 12:10:12 +0530820
Neil Trini Lasrado79bf2332015-07-20 13:03:48 +0530821 elif self.meta.get_field("supplier"):
shreyas29b565f2016-01-25 17:30:49 +0530822 party_type = "Supplier"
Anand Doshi979326b2015-09-11 16:22:37 +0530823
Nabin Hait4ffd7f32015-08-27 12:28:36 +0530824 party = self.get(party_type.lower()) if party_type else None
Anand Doshi979326b2015-09-11 16:22:37 +0530825
Nabin Hait4ffd7f32015-08-27 12:28:36 +0530826 return party_type, party
Anand Doshi979326b2015-09-11 16:22:37 +0530827
Nabin Hait4ffd7f32015-08-27 12:28:36 +0530828 def validate_currency(self):
Nabin Hait6e439a52015-08-28 19:24:22 +0530829 if self.get("currency"):
Nabin Hait4ffd7f32015-08-27 12:28:36 +0530830 party_type, party = self.get_party()
Nabin Hait6e439a52015-08-28 19:24:22 +0530831 if party_type and party:
Anand Doshib20baf82015-09-25 16:17:50 +0530832 party_account_currency = get_party_account_currency(party_type, party, self.company)
Anand Doshi979326b2015-09-11 16:22:37 +0530833
Anand Doshi7afaeb02015-10-01 18:55:25 +0530834 if (party_account_currency
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800835 and party_account_currency != self.company_currency
836 and self.currency != party_account_currency):
Nabin Hait98096772015-09-03 10:28:08 +0530837 frappe.throw(_("Accounting Entry for {0}: {1} can only be made in currency: {2}")
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800838 .format(party_type, party, party_account_currency), InvalidCurrency)
Anand Doshi979326b2015-09-11 16:22:37 +0530839
shreyas29b565f2016-01-25 17:30:49 +0530840 # Note: not validating with gle account because we don't have the account
841 # at quotation / sales order level and we shouldn't stop someone
842 # from creating a sales invoice if sales order is already created
Rushabh Mehta2cb7a9f2016-06-15 16:45:03 +0530843
Nabin Hait297d74a2016-11-23 15:58:51 +0530844 def delink_advance_entries(self, linked_doc_name):
845 total_allocated_amount = 0
846 for adv in self.advances:
847 consider_for_total_advance = True
848 if adv.reference_name == linked_doc_name:
849 frappe.db.sql("""delete from `tab{0} Advance`
850 where name = %s""".format(self.doctype), adv.name)
851 consider_for_total_advance = False
852
853 if consider_for_total_advance:
854 total_allocated_amount += flt(adv.allocated_amount, adv.precision("allocated_amount"))
855
Rushabh Mehta66958302017-01-16 16:57:53 +0530856 frappe.db.set_value(self.doctype, self.name, "total_advance",
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800857 total_allocated_amount, update_modified=False)
Rohit Waghchaure6087fe12016-04-09 14:31:09 +0530858
KanchanChauhan49a50fe2016-11-18 13:57:53 +0530859 def group_similar_items(self):
860 group_item_qty = {}
861 group_item_amount = {}
Shreya Shah785f1aa2018-10-11 10:14:25 +0530862 # to update serial number in print
863 count = 0
KanchanChauhan49a50fe2016-11-18 13:57:53 +0530864
865 for item in self.items:
866 group_item_qty[item.item_code] = group_item_qty.get(item.item_code, 0) + item.qty
867 group_item_amount[item.item_code] = group_item_amount.get(item.item_code, 0) + item.amount
868
869 duplicate_list = []
KanchanChauhan49a50fe2016-11-18 13:57:53 +0530870 for item in self.items:
871 if item.item_code in group_item_qty:
Shreya Shah785f1aa2018-10-11 10:14:25 +0530872 count += 1
KanchanChauhan49a50fe2016-11-18 13:57:53 +0530873 item.qty = group_item_qty[item.item_code]
874 item.amount = group_item_amount[item.item_code]
deepeshgarg007e8d21cd2019-06-24 17:46:44 +0530875
876 if item.qty:
877 item.rate = flt(flt(item.amount) / flt(item.qty), item.precision("rate"))
878 else:
879 item.rate = 0
880
Shreya Shah785f1aa2018-10-11 10:14:25 +0530881 item.idx = count
KanchanChauhan49a50fe2016-11-18 13:57:53 +0530882 del group_item_qty[item.item_code]
883 else:
884 duplicate_list.append(item)
KanchanChauhan49a50fe2016-11-18 13:57:53 +0530885 for item in duplicate_list:
886 self.remove(item)
887
tunde32aa7c12017-09-07 06:52:15 +0100888 def set_payment_schedule(self):
Manas Solankia7f55892018-04-02 10:32:00 +0530889 if self.doctype == 'Sales Invoice' and self.is_pos:
890 self.payment_terms_template = ''
891 return
rohitwaghchauredb9fa782018-03-01 10:32:29 +0530892
Deepesh Garg26210162020-08-11 16:06:13 +0530893 party_account_currency = self.get('party_account_currency')
894 if not party_account_currency:
895 party_type, party = self.get_party()
896
897 if party_type and party:
898 party_account_currency = get_party_account_currency(party_type, party, self.company)
899
rohitwaghchaureda941af2018-01-17 16:23:04 +0530900 posting_date = self.get("bill_date") or self.get("posting_date") or self.get("transaction_date")
tundedf3a1752017-09-11 11:02:57 +0100901 date = self.get("due_date")
902 due_date = date or posting_date
Deepesh Garg26210162020-08-11 16:06:13 +0530903
904 if party_account_currency == self.company_currency:
905 grand_total = self.get("base_rounded_total") or self.base_grand_total
906 else:
907 grand_total = self.get("rounded_total") or self.grand_total
908
Nabin Hait2f9f4f92017-12-20 12:24:59 +0530909 if self.doctype in ("Sales Invoice", "Purchase Invoice"):
910 grand_total = grand_total - flt(self.write_off_amount)
tunde96b8f222017-09-08 15:35:59 +0100911
Rohit Waghchaure4a267b92019-05-09 19:50:00 +0530912 if self.get("total_advance"):
913 grand_total -= self.get("total_advance")
914
Nabin Hait0551f7b2017-11-21 19:58:16 +0530915 if not self.get("payment_schedule"):
916 if self.get("payment_terms_template"):
917 data = get_payment_terms(self.payment_terms_template, posting_date, grand_total)
918 for item in data:
919 self.append("payment_schedule", item)
920 else:
921 data = dict(due_date=due_date, invoice_portion=100, payment_amount=grand_total)
922 self.append("payment_schedule", data)
923 else:
924 for d in self.get("payment_schedule"):
Nabin Hait2f9f4f92017-12-20 12:24:59 +0530925 if d.invoice_portion:
Saqib0586b7d2021-03-31 15:03:53 +0530926 d.payment_amount = flt(grand_total * flt(d.invoice_portion / 100), d.precision('payment_amount'))
927 d.outstanding = d.payment_amount
tunde43870aa2017-08-18 11:59:30 +0100928
tundebe1b8712017-08-19 08:21:44 +0100929 def set_due_date(self):
Nabin Hait0551f7b2017-11-21 19:58:16 +0530930 due_dates = [d.due_date for d in self.get("payment_schedule") if d.due_date]
931 if due_dates:
932 self.due_date = max(due_dates)
tunde62af5c52017-09-22 15:16:38 +0100933
934 def validate_payment_schedule_dates(self):
tunde77ecacc2017-09-22 23:12:55 +0100935 dates = []
tunde9bed2de2017-09-25 10:19:35 +0100936 li = []
tunde43870aa2017-08-18 11:59:30 +0100937
rohitwaghchauredb9fa782018-03-01 10:32:29 +0530938 if self.doctype == 'Sales Invoice' and self.is_pos: return
939
tunde43870aa2017-08-18 11:59:30 +0100940 for d in self.get("payment_schedule"):
Nabin Hait2f9f4f92017-12-20 12:24:59 +0530941 if self.doctype == "Sales Order" and getdate(d.due_date) < getdate(self.transaction_date):
Michelle Alva7f2477b2020-04-09 17:23:23 +0530942 frappe.throw(_("Row {0}: Due Date in the Payment Terms table cannot be before Posting Date").format(d.idx))
tunde77ecacc2017-09-22 23:12:55 +0100943 elif d.due_date in dates:
mnatalia5f0e8d62018-05-22 06:38:50 +0300944 li.append(_("{0} in row {1}").format(d.due_date, d.idx))
tunde9bed2de2017-09-25 10:19:35 +0100945 dates.append(d.due_date)
946
947 if li:
948 duplicates = '<br>' + '<br>'.join(li)
Faris Ansari2ab6e0e2018-09-19 13:13:59 +0530949 frappe.throw(_("Rows with duplicate due dates in other rows were found: {0}").format(duplicates))
tunde43870aa2017-08-18 11:59:30 +0100950
tunde62af5c52017-09-22 15:16:38 +0100951 def validate_payment_schedule_amount(self):
rohitwaghchauredb9fa782018-03-01 10:32:29 +0530952 if self.doctype == 'Sales Invoice' and self.is_pos: return
953
Deepesh Garg26210162020-08-11 16:06:13 +0530954 party_account_currency = self.get('party_account_currency')
955 if not party_account_currency:
956 party_type, party = self.get_party()
957
958 if party_type and party:
959 party_account_currency = get_party_account_currency(party_type, party, self.company)
960
Nabin Hait0551f7b2017-11-21 19:58:16 +0530961 if self.get("payment_schedule"):
962 total = 0
963 for d in self.get("payment_schedule"):
Nabin Haitf592f2c2017-12-19 11:31:34 +0530964 total += flt(d.payment_amount)
tunde43870aa2017-08-18 11:59:30 +0100965
Deepesh Garg26210162020-08-11 16:06:13 +0530966 if party_account_currency == self.company_currency:
967 total = flt(total, self.precision("base_grand_total"))
968 grand_total = flt(self.get("base_rounded_total") or self.base_grand_total, self.precision('base_grand_total'))
969 else:
970 total = flt(total, self.precision("grand_total"))
971 grand_total = flt(self.get("rounded_total") or self.grand_total, self.precision('grand_total'))
972
Rohit Waghchaure4a267b92019-05-09 19:50:00 +0530973 if self.get("total_advance"):
974 grand_total -= self.get("total_advance")
975
Nabin Haite591c852017-12-21 11:46:30 +0530976 if self.doctype in ("Sales Invoice", "Purchase Invoice"):
977 grand_total = grand_total - flt(self.write_off_amount)
Mangesh-Khairnar88620d62019-07-22 11:29:26 +0530978 if total != flt(grand_total, self.precision("grand_total")):
Nabin Hait0551f7b2017-11-21 19:58:16 +0530979 frappe.throw(_("Total Payment Amount in Payment Schedule must be equal to Grand / Rounded Total"))
tunde43870aa2017-08-18 11:59:30 +0100980
Nabin Hait877e1bb2017-11-17 12:27:43 +0530981 def is_rounded_total_disabled(self):
982 if self.meta.get_field("disable_rounded_total"):
983 return self.disable_rounded_total
984 else:
985 return frappe.db.get_single_value("Global Defaults", "disable_rounded_total")
986
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530987 def set_inter_company_account(self):
988 """
989 Set intercompany account for inter warehouse transactions
990 This account will be used in case billing company and internal customer's
991 representation company is same
992 """
993
994 if self.is_internal_transfer() and not self.unrealized_profit_loss_account:
995 unrealized_profit_loss_account = frappe.db.get_value('Company', self.company, 'unrealized_profit_loss_account')
996
997 if not unrealized_profit_loss_account:
998 msg = _("Please select Unrealized Profit / Loss account or add default Unrealized Profit / Loss account account for company {0}").format(
999 frappe.bold(self.company))
1000 frappe.throw(msg)
1001
1002 self.unrealized_profit_loss_account = unrealized_profit_loss_account
1003
1004 def is_internal_transfer(self):
1005 """
1006 It will an internal transfer if its an internal customer and representation
1007 company is same as billing company
1008 """
Deepesh Gargb4be2922021-01-28 13:09:56 +05301009 if self.doctype in ('Sales Invoice', 'Delivery Note', 'Sales Order'):
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05301010 internal_party_field = 'is_internal_customer'
Deepesh Gargb4be2922021-01-28 13:09:56 +05301011 elif self.doctype in ('Purchase Invoice', 'Purchase Receipt', 'Purchase Order'):
Deepesh Gargf17ea2c2020-12-11 21:30:39 +05301012 internal_party_field = 'is_internal_supplier'
1013
1014 if self.get(internal_party_field) and (self.represents_company == self.company):
1015 return True
1016
1017 return False
1018
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301019@frappe.whitelist()
Rushabh Mehtaf56d73c2013-10-10 16:35:09 +05301020def get_tax_rate(account_head):
Rushabh Mehta2cb7a9f2016-06-15 16:45:03 +05301021 return frappe.db.get_value("Account", account_head, ["tax_rate", "account_name"], as_dict=True)
Rushabh Mehtaa33d4682015-06-01 17:15:42 +05301022
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001023
Nabin Haitffc7f3f2015-05-12 15:07:02 +05301024@frappe.whitelist()
Nabin Haita2426fc2018-01-15 17:45:46 +05301025def get_default_taxes_and_charges(master_doctype, tax_template=None, company=None):
rohitwaghchaure505661b2017-12-11 14:52:28 +05301026 if not company: return {}
1027
Nabin Haita2426fc2018-01-15 17:45:46 +05301028 if tax_template and company:
1029 tax_template_company = frappe.db.get_value(master_doctype, tax_template, "company")
1030 if tax_template_company == company:
1031 return
1032
1033 default_tax = frappe.db.get_value(master_doctype, {"is_default": 1, "company": company})
rohitwaghchaure505661b2017-12-11 14:52:28 +05301034
Rushabh Mehta98aa5812017-11-14 09:32:32 +05301035 return {
1036 'taxes_and_charges': default_tax,
1037 'taxes': get_taxes_and_charges(master_doctype, default_tax)
1038 }
Nabin Hait6b039142014-05-02 15:45:10 +05301039
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001040
Nabin Hait6b039142014-05-02 15:45:10 +05301041@frappe.whitelist()
Nabin Haitffc7f3f2015-05-12 15:07:02 +05301042def get_taxes_and_charges(master_doctype, master_name):
Nabin Hait1fe50122015-05-16 12:14:39 +05301043 if not master_name:
1044 return
Nabin Hait6b039142014-05-02 15:45:10 +05301045 from frappe.model import default_fields
1046 tax_master = frappe.get_doc(master_doctype, master_name)
1047
1048 taxes_and_charges = []
Nabin Haitffc7f3f2015-05-12 15:07:02 +05301049 for i, tax in enumerate(tax_master.get("taxes")):
Nabin Hait6b039142014-05-02 15:45:10 +05301050 tax = tax.as_dict()
1051
1052 for fieldname in default_fields:
1053 if fieldname in tax:
1054 del tax[fieldname]
1055
1056 taxes_and_charges.append(tax)
1057
1058 return taxes_and_charges
Rushabh Mehta66e08e32014-09-29 12:17:03 +05301059
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001060
Rushabh Mehta66e08e32014-09-29 12:17:03 +05301061def validate_conversion_rate(currency, conversion_rate, conversion_rate_label, company):
1062 """common validation for currency and price list currency"""
1063
Rushabh Mehta708e47a2018-08-08 16:37:31 +05301064 company_currency = frappe.get_cached_value('Company', company, "default_currency")
Rushabh Mehta66e08e32014-09-29 12:17:03 +05301065
1066 if not conversion_rate:
Saqib60212ff2020-10-26 11:17:04 +05301067 throw(
1068 _("{0} is mandatory. Maybe Currency Exchange record is not created for {1} to {2}.")
1069 .format(conversion_rate_label, currency, company_currency)
1070 )
Nabin Hait613d0812015-02-23 11:58:15 +05301071
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001072
Nabin Hait613d0812015-02-23 11:58:15 +05301073def validate_taxes_and_charges(tax):
Nabin Hait37b047d2015-02-23 16:01:33 +05301074 if tax.charge_type in ['Actual', 'On Net Total'] and tax.row_id:
Nabin Hait613d0812015-02-23 11:58:15 +05301075 frappe.throw(_("Can refer row only if the charge type is 'On Previous Row Amount' or 'Previous Row Total'"))
Nabin Hait37b047d2015-02-23 16:01:33 +05301076 elif tax.charge_type in ['On Previous Row Amount', 'On Previous Row Total']:
Nabin Hait613d0812015-02-23 11:58:15 +05301077 if cint(tax.idx) == 1:
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001078 frappe.throw(
1079 _("Cannot select charge type as 'On Previous Row Amount' or 'On Previous Row Total' for first row"))
Nabin Hait613d0812015-02-23 11:58:15 +05301080 elif not tax.row_id:
Suraj Shetty48e9bc32020-01-29 15:06:18 +05301081 frappe.throw(_("Please specify a valid Row ID for row {0} in table {1}").format(tax.idx, _(tax.doctype)))
Nabin Hait613d0812015-02-23 11:58:15 +05301082 elif tax.row_id and cint(tax.row_id) >= cint(tax.idx):
1083 frappe.throw(_("Cannot refer row number greater than or equal to current row number for this Charge type"))
1084
Rushabh Mehta2a21bc92015-02-25 15:08:42 +05301085 if tax.charge_type == "Actual":
Nabin Haitbc6c3602015-02-27 23:40:56 +05301086 tax.rate = None
Rushabh Mehta2a21bc92015-02-25 15:08:42 +05301087
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001088
Nabin Hait613d0812015-02-23 11:58:15 +05301089def validate_inclusive_tax(tax, doc):
1090 def _on_previous_row_error(row_range):
1091 throw(_("To include tax in row {0} in Item rate, taxes in rows {1} must also be included").format(tax.idx,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001092 row_range))
Nabin Hait613d0812015-02-23 11:58:15 +05301093
1094 if cint(getattr(tax, "included_in_print_rate", None)):
1095 if tax.charge_type == "Actual":
1096 # inclusive tax cannot be of type Actual
1097 throw(_("Charge of type 'Actual' in row {0} cannot be included in Item Rate").format(tax.idx))
1098 elif tax.charge_type == "On Previous Row Amount" and \
1099 not cint(doc.get("taxes")[cint(tax.row_id) - 1].included_in_print_rate):
1100 # referred row should also be inclusive
1101 _on_previous_row_error(tax.row_id)
1102 elif tax.charge_type == "On Previous Row Total" and \
1103 not all([cint(t.included_in_print_rate) for t in doc.get("taxes")[:cint(tax.row_id) - 1]]):
1104 # all rows about the reffered tax should be inclusive
1105 _on_previous_row_error("1 - %d" % (tax.row_id,))
Nabin Hait93b3a372015-02-24 17:08:34 +05301106 elif tax.get("category") == "Valuation":
Nabin Hait19ea7212020-08-11 20:34:57 +05301107 frappe.throw(_("Valuation type charges can not be marked as Inclusive"))
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05301108
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05301109
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001110def set_balance_in_account_currency(gl_dict, account_currency=None, conversion_rate=None, company_currency=None):
1111 if (not conversion_rate) and (account_currency != company_currency):
1112 frappe.throw(_("Account: {0} with currency: {1} can not be selected")
1113 .format(gl_dict.account, account_currency))
1114
1115 gl_dict["account_currency"] = company_currency if account_currency == company_currency \
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05301116 else account_currency
1117
1118 # set debit/credit in account currency if not provided
1119 if flt(gl_dict.debit) and not flt(gl_dict.debit_in_account_currency):
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001120 gl_dict.debit_in_account_currency = gl_dict.debit if account_currency == company_currency \
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05301121 else flt(gl_dict.debit / conversion_rate, 2)
1122
1123 if flt(gl_dict.credit) and not flt(gl_dict.credit_in_account_currency):
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001124 gl_dict.credit_in_account_currency = gl_dict.credit if account_currency == company_currency \
Revant Nandgaonkar5da941b2016-02-18 16:02:05 +05301125 else flt(gl_dict.credit / conversion_rate, 2)
Nabin Hait1991c7b2016-06-27 20:09:05 +05301126
1127
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301128def get_advance_journal_entries(party_type, party, party_account, amount_field,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001129 order_doctype, order_list, include_unallocated=True):
1130 dr_or_cr = "credit_in_account_currency" if party_type == "Customer" else "debit_in_account_currency"
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301131
Nabin Hait1991c7b2016-06-27 20:09:05 +05301132 conditions = []
1133 if include_unallocated:
1134 conditions.append("ifnull(t2.reference_name, '')=''")
1135
1136 if order_list:
1137 order_condition = ', '.join(['%s'] * len(order_list))
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001138 conditions.append(" (t2.reference_type = '{0}' and ifnull(t2.reference_name, '') in ({1}))" \
1139 .format(order_doctype, order_condition))
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301140
Nabin Hait1991c7b2016-06-27 20:09:05 +05301141 reference_condition = " and (" + " or ".join(conditions) + ")" if conditions else ""
Rushabh Mehta66958302017-01-16 16:57:53 +05301142
Nabin Hait1991c7b2016-06-27 20:09:05 +05301143 journal_entries = frappe.db.sql("""
1144 select
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301145 "Journal Entry" as reference_type, t1.name as reference_name,
Nabin Hait1991c7b2016-06-27 20:09:05 +05301146 t1.remark as remarks, t2.{0} as amount, t2.name as reference_row,
1147 t2.reference_name as against_order
1148 from
1149 `tabJournal Entry` t1, `tabJournal Entry Account` t2
1150 where
1151 t1.name = t2.parent and t2.account = %s
1152 and t2.party_type = %s and t2.party = %s
1153 and t2.is_advance = 'Yes' and t1.docstatus = 1
Nabin Haitca627fb2016-09-05 16:16:53 +05301154 and {1} > 0 {2}
Nabin Hait1991c7b2016-06-27 20:09:05 +05301155 order by t1.posting_date""".format(amount_field, dr_or_cr, reference_condition),
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001156 [party_account, party_type, party] + order_list, as_dict=1)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301157
Nabin Hait1991c7b2016-06-27 20:09:05 +05301158 return list(journal_entries)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301159
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001160
Rohit Waghchauref7258162019-01-15 18:12:04 +05301161def get_advance_payment_entries(party_type, party, party_account, order_doctype,
Nabin Hait34c551d2019-07-03 10:34:31 +05301162 order_list=None, include_unallocated=True, against_all_orders=False, limit=None):
Nabin Hait1991c7b2016-06-27 20:09:05 +05301163 party_account_field = "paid_from" if party_type == "Customer" else "paid_to"
Deepesh Gargc7eadfc2020-07-22 17:59:37 +05301164 currency_field = "paid_from_account_currency" if party_type == "Customer" else "paid_to_account_currency"
Nabin Hait1991c7b2016-06-27 20:09:05 +05301165 payment_type = "Receive" if party_type == "Customer" else "Pay"
1166 payment_entries_against_order, unallocated_payment_entries = [], []
Nabin Hait34c551d2019-07-03 10:34:31 +05301167 limit_cond = "limit %s" % limit if limit else ""
Nabin Haitff2f3ef2016-07-04 11:41:14 +05301168
Nabin Hait1991c7b2016-06-27 20:09:05 +05301169 if order_list or against_all_orders:
1170 if order_list:
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001171 reference_condition = " and t2.reference_name in ({0})" \
Nabin Hait1991c7b2016-06-27 20:09:05 +05301172 .format(', '.join(['%s'] * len(order_list)))
1173 else:
1174 reference_condition = ""
1175 order_list = []
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301176
Nabin Hait1991c7b2016-06-27 20:09:05 +05301177 payment_entries_against_order = frappe.db.sql("""
1178 select
1179 "Payment Entry" as reference_type, t1.name as reference_name,
1180 t1.remarks, t2.allocated_amount as amount, t2.name as reference_row,
Deepesh Gargc7eadfc2020-07-22 17:59:37 +05301181 t2.reference_name as against_order, t1.posting_date,
1182 t1.{0} as currency
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301183 from `tabPayment Entry` t1, `tabPayment Entry Reference` t2
Nabin Hait1991c7b2016-06-27 20:09:05 +05301184 where
Deepesh Gargc7eadfc2020-07-22 17:59:37 +05301185 t1.name = t2.parent and t1.{1} = %s and t1.payment_type = %s
Nabin Hait1991c7b2016-06-27 20:09:05 +05301186 and t1.party_type = %s and t1.party = %s and t1.docstatus = 1
Deepesh Gargc7eadfc2020-07-22 17:59:37 +05301187 and t2.reference_doctype = %s {2}
1188 order by t1.posting_date {3}
1189 """.format(currency_field, party_account_field, reference_condition, limit_cond),
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001190 [party_account, payment_type, party_type, party,
1191 order_doctype] + order_list, as_dict=1)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301192
Nabin Hait1991c7b2016-06-27 20:09:05 +05301193 if include_unallocated:
1194 unallocated_payment_entries = frappe.db.sql("""
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301195 select "Payment Entry" as reference_type, name as reference_name,
Nabin Hait1991c7b2016-06-27 20:09:05 +05301196 remarks, unallocated_amount as amount
1197 from `tabPayment Entry`
1198 where
1199 {0} = %s and party_type = %s and party = %s and payment_type = %s
1200 and docstatus = 1 and unallocated_amount > 0
Rohit Waghchauref7258162019-01-15 18:12:04 +05301201 order by posting_date {1}
1202 """.format(party_account_field, limit_cond), (party_account, party_type, party, payment_type), as_dict=1)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05301203
Rohit Waghchaure2f1db572016-11-08 12:39:33 +05301204 return list(payment_entries_against_order) + list(unallocated_payment_entries)
1205
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001206
Rohit Waghchaure2f1db572016-11-08 12:39:33 +05301207def update_invoice_status():
1208 # Daily update the status of the invoices
1209
Rushabh Mehta66958302017-01-16 16:57:53 +05301210 frappe.db.sql(""" update `tabSales Invoice` set status = 'Overdue'
Rohit Waghchaure2f1db572016-11-08 12:39:33 +05301211 where due_date < CURDATE() and docstatus = 1 and outstanding_amount > 0""")
1212
Rushabh Mehta66958302017-01-16 16:57:53 +05301213 frappe.db.sql(""" update `tabPurchase Invoice` set status = 'Overdue'
Nabin Hait92759692017-08-15 08:23:51 +05301214 where due_date < CURDATE() and docstatus = 1 and outstanding_amount > 0""")
1215
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001216
Nabin Hait92759692017-08-15 08:23:51 +05301217@frappe.whitelist()
Shreya Shah3a9eec22018-02-16 13:05:21 +05301218def get_payment_terms(terms_template, posting_date=None, grand_total=None, bill_date=None):
Nabin Hait92759692017-08-15 08:23:51 +05301219 if not terms_template:
1220 return
1221
1222 terms_doc = frappe.get_doc("Payment Terms Template", terms_template)
1223
1224 schedule = []
tundefb144302017-08-19 15:01:40 +01001225 for d in terms_doc.get("terms"):
Shreya Shah3a9eec22018-02-16 13:05:21 +05301226 term_details = get_payment_term_details(d, posting_date, grand_total, bill_date)
Nabin Hait92759692017-08-15 08:23:51 +05301227 schedule.append(term_details)
1228
1229 return schedule
1230
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001231
Nabin Hait92759692017-08-15 08:23:51 +05301232@frappe.whitelist()
Shreya Shah3a9eec22018-02-16 13:05:21 +05301233def get_payment_term_details(term, posting_date=None, grand_total=None, bill_date=None):
Nabin Hait92759692017-08-15 08:23:51 +05301234 term_details = frappe._dict()
Achilles Rasquinha90509982018-03-08 12:55:41 +05301235 if isinstance(term, text_type):
Nabin Hait92759692017-08-15 08:23:51 +05301236 term = frappe.get_doc("Payment Term", term)
1237 else:
1238 term_details.payment_term = term.payment_term
1239 term_details.description = term.description
1240 term_details.invoice_portion = term.invoice_portion
Rohit Waghchaure52bf56d2017-11-27 11:43:52 +05301241 term_details.payment_amount = flt(term.invoice_portion) * flt(grand_total) / 100
Saqib0586b7d2021-03-31 15:03:53 +05301242 term_details.discount_type = term.discount_type
1243 term_details.discount = term.discount
1244 # term_details.discounted_amount = flt(grand_total) * (term.discount / 100) if term.discount_type == 'Percentage' else discount
1245 term_details.outstanding = term_details.payment_amount
1246 term_details.mode_of_payment = term.mode_of_payment
1247
Shreya Shah3a9eec22018-02-16 13:05:21 +05301248 if bill_date:
1249 term_details.due_date = get_due_date(term, bill_date)
Saqib0586b7d2021-03-31 15:03:53 +05301250 term_details.discount_date = get_discount_date(term, bill_date)
Shreya Shah3a9eec22018-02-16 13:05:21 +05301251 elif posting_date:
1252 term_details.due_date = get_due_date(term, posting_date)
Saqib0586b7d2021-03-31 15:03:53 +05301253 term_details.discount_date = get_discount_date(term, posting_date)
Shreya Shah3a9eec22018-02-16 13:05:21 +05301254
1255 if getdate(term_details.due_date) < getdate(posting_date):
1256 term_details.due_date = posting_date
1257
Nabin Hait92759692017-08-15 08:23:51 +05301258 return term_details
1259
Shreya Shah3a9eec22018-02-16 13:05:21 +05301260def get_due_date(term, posting_date=None, bill_date=None):
Nabin Hait92759692017-08-15 08:23:51 +05301261 due_date = None
Shreya Shah3a9eec22018-02-16 13:05:21 +05301262 date = bill_date or posting_date
Nabin Hait92759692017-08-15 08:23:51 +05301263 if term.due_date_based_on == "Day(s) after invoice date":
Shreya Shah3a9eec22018-02-16 13:05:21 +05301264 due_date = add_days(date, term.credit_days)
Nabin Hait92759692017-08-15 08:23:51 +05301265 elif term.due_date_based_on == "Day(s) after the end of the invoice month":
Shreya Shah3a9eec22018-02-16 13:05:21 +05301266 due_date = add_days(get_last_day(date), term.credit_days)
Nabin Hait92759692017-08-15 08:23:51 +05301267 elif term.due_date_based_on == "Month(s) after the end of the invoice month":
Shreya Shah3a9eec22018-02-16 13:05:21 +05301268 due_date = add_months(get_last_day(date), term.credit_months)
tunde96b8f222017-09-08 15:35:59 +01001269 return due_date
tundebabzyad08d4c2018-05-16 07:01:41 +01001270
Saqib0586b7d2021-03-31 15:03:53 +05301271def get_discount_date(term, posting_date=None, bill_date=None):
1272 discount_validity = None
1273 date = bill_date or posting_date
1274 if term.discount_validity_based_on == "Day(s) after invoice date":
1275 discount_validity = add_days(date, term.discount_validity)
1276 elif term.discount_validity_based_on == "Day(s) after the end of the invoice month":
1277 discount_validity = add_days(get_last_day(date), term.discount_validity)
1278 elif term.discount_validity_based_on == "Month(s) after the end of the invoice month":
1279 discount_validity = add_months(get_last_day(date), term.discount_validity)
1280 return discount_validity
tundebabzyad08d4c2018-05-16 07:01:41 +01001281
1282def get_supplier_block_status(party_name):
1283 """
1284 Returns a dict containing the values of `on_hold`, `release_date` and `hold_type` of
1285 a `Supplier`
1286 """
1287 supplier = frappe.get_doc('Supplier', party_name)
1288 info = {
1289 'on_hold': supplier.on_hold,
1290 'release_date': supplier.release_date,
1291 'hold_type': supplier.hold_type
1292 }
1293 return info
1294
marination698d9832020-08-19 14:59:46 +05301295def set_child_tax_template_and_map(item, child_item, parent_doc):
1296 args = {
1297 'item_code': item.item_code,
1298 'posting_date': parent_doc.transaction_date,
1299 'tax_category': parent_doc.get('tax_category'),
1300 'company': parent_doc.get('company')
1301 }
1302
1303 child_item.item_tax_template = _get_item_tax_template(args, item.taxes)
1304 if child_item.get("item_tax_template"):
1305 child_item.item_tax_rate = get_item_tax_map(parent_doc.get('company'), child_item.item_tax_template, as_json=True)
1306
Marica3b1be2b2020-10-22 17:04:31 +05301307def add_taxes_from_tax_template(child_item, parent_doc):
1308 add_taxes_from_item_tax_template = frappe.db.get_single_value("Accounts Settings", "add_taxes_from_item_tax_template")
1309
1310 if child_item.get("item_tax_rate") and add_taxes_from_item_tax_template:
1311 tax_map = json.loads(child_item.get("item_tax_rate"))
1312 for tax_type in tax_map:
1313 tax_rate = flt(tax_map[tax_type])
1314 taxes = parent_doc.get('taxes') or []
1315 # add new row for tax head only if missing
1316 found = any(tax.account_head == tax_type for tax in taxes)
1317 if not found:
1318 tax_row = parent_doc.append("taxes", {})
1319 tax_row.update({
1320 "description" : str(tax_type).split(' - ')[0],
1321 "charge_type" : "On Net Total",
1322 "account_head" : tax_type,
1323 "rate" : tax_rate
1324 })
1325 if parent_doc.doctype == "Purchase Order":
1326 tax_row.update({
1327 "category" : "Total",
1328 "add_deduct_tax" : "Add"
1329 })
1330 tax_row.db_insert()
1331
pateljannat637ddff2021-02-09 16:17:30 +05301332def set_order_defaults(parent_doctype, parent_doctype_name, child_doctype, child_docname, trans_item):
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01001333 """
pateljannat637ddff2021-02-09 16:17:30 +05301334 Returns a Sales/Purchase Order Item child item containing the default values
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01001335 """
Saqib438e0432020-04-03 10:02:56 +05301336 p_doc = frappe.get_doc(parent_doctype, parent_doctype_name)
pateljannat637ddff2021-02-09 16:17:30 +05301337 child_item = frappe.new_doc(child_doctype, p_doc, child_docname)
Saqib Ansarif53299e2020-04-15 22:08:12 +05301338 item = frappe.get_doc("Item", trans_item.get('item_code'))
pateljannat637ddff2021-02-09 16:17:30 +05301339 for field in ("item_code", "item_name", "description", "item_group"):
1340 child_item.update({field: item.get(field)})
1341 date_fieldname = "delivery_date" if child_doctype == "Sales Order Item" else "schedule_date"
Jannat Patelbb0d8f82021-02-11 20:59:28 +05301342 child_item.update({date_fieldname: trans_item.get(date_fieldname) or p_doc.get(date_fieldname)})
Saqib61314242020-09-15 11:14:31 +05301343 child_item.uom = trans_item.get("uom") or item.stock_uom
1344 conversion_factor = flt(get_conversion_factor(item.item_code, child_item.uom).get("conversion_factor"))
1345 child_item.conversion_factor = flt(trans_item.get('conversion_factor')) or conversion_factor
pateljannat637ddff2021-02-09 16:17:30 +05301346 if child_doctype == "Purchase Order Item":
1347 child_item.base_rate = 1 # Initiallize value will update in parent validation
1348 child_item.base_amount = 1 # Initiallize value will update in parent validation
1349 if child_doctype == "Sales Order Item":
1350 child_item.warehouse = get_item_warehouse(item, p_doc, overwrite_warehouse=True)
1351 if not child_item.warehouse:
1352 frappe.throw(_("Cannot find {} for item {}. Please set the same in Item Master or Stock Settings.")
1353 .format(frappe.bold("default warehouse"), frappe.bold(item.item_code)))
marination698d9832020-08-19 14:59:46 +05301354 set_child_tax_template_and_map(item, child_item, p_doc)
Marica3b1be2b2020-10-22 17:04:31 +05301355 add_taxes_from_tax_template(child_item, p_doc)
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01001356 return child_item
1357
Saqib6db92fb2020-09-14 19:54:17 +05301358def validate_and_delete_children(parent, data):
Saqib0ad74492019-12-24 16:42:30 +05301359 deleted_children = []
1360 updated_item_names = [d.get("docname") for d in data]
1361 for item in parent.items:
1362 if item.name not in updated_item_names:
1363 deleted_children.append(item)
1364
1365 for d in deleted_children:
thefalconx332073eeb2019-12-27 16:26:03 +05301366 if parent.doctype == "Sales Order":
1367 if flt(d.delivered_qty):
1368 frappe.throw(_("Row #{0}: Cannot delete item {1} which has already been delivered").format(d.idx, d.item_code))
1369 if flt(d.work_order_qty):
1370 frappe.throw(_("Row #{0}: Cannot delete item {1} which has work order assigned to it.").format(d.idx, d.item_code))
1371 if flt(d.ordered_qty):
1372 frappe.throw(_("Row #{0}: Cannot delete item {1} which is assigned to customer's purchase order.").format(d.idx, d.item_code))
Saqib0ad74492019-12-24 16:42:30 +05301373
1374 if parent.doctype == "Purchase Order" and flt(d.received_qty):
1375 frappe.throw(_("Row #{0}: Cannot delete item {1} which has already been received").format(d.idx, d.item_code))
Suraj Shetty48e9bc32020-01-29 15:06:18 +05301376
Saqib0ad74492019-12-24 16:42:30 +05301377 if flt(d.billed_amt):
1378 frappe.throw(_("Row #{0}: Cannot delete item {1} which has already been billed.").format(d.idx, d.item_code))
1379
1380 d.cancel()
1381 d.delete()
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001382
1383@frappe.whitelist()
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01001384def update_child_qty_rate(parent_doctype, trans_items, parent_doctype_name, child_docname="items"):
Saqib6db92fb2020-09-14 19:54:17 +05301385 def check_doc_permissions(doc, perm_type='create'):
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05301386 try:
1387 doc.check_permission(perm_type)
Saqib6db92fb2020-09-14 19:54:17 +05301388 except frappe.PermissionError:
marination661bf642020-09-29 18:16:45 +05301389 actions = { 'create': 'add', 'write': 'update'}
Saqib6db92fb2020-09-14 19:54:17 +05301390
1391 frappe.throw(_("You do not have permissions to {} items in a {}.")
1392 .format(actions[perm_type], parent_doctype), title=_("Insufficient Permissions"))
marination665c27a2020-09-15 12:04:38 +05301393
Saqib6db92fb2020-09-14 19:54:17 +05301394 def validate_workflow_conditions(doc):
1395 workflow = get_workflow_name(doc.doctype)
1396 if not workflow:
1397 return
1398
1399 workflow_doc = frappe.get_doc("Workflow", workflow)
1400 current_state = doc.get(workflow_doc.workflow_state_field)
1401 roles = frappe.get_roles()
1402
1403 transitions = []
1404 for transition in workflow_doc.transitions:
1405 if transition.next_state == current_state and transition.allowed in roles:
1406 if not is_transition_condition_satisfied(transition, doc):
1407 continue
1408 transitions.append(transition.as_dict())
1409
1410 if not transitions:
Saqib18318932020-09-23 13:01:49 +05301411 frappe.throw(
1412 _("You are not allowed to update as per the conditions set in {} Workflow.").format(get_link_to_form("Workflow", workflow)),
1413 title=_("Insufficient Permissions")
1414 )
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05301415
Rohit Waghchaure8d5380a2020-06-18 14:06:31 +05301416 def get_new_child_item(item_row):
Rohit Waghchaureff70e612021-03-06 22:08:08 +05301417 child_doctype = "Sales Order Item" if parent_doctype == "Sales Order" else "Purchase Order Item"
pateljannat637ddff2021-02-09 16:17:30 +05301418 return set_order_defaults(parent_doctype, parent_doctype_name, child_doctype, child_docname, item_row)
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05301419
1420 def validate_quantity(child_item, d):
1421 if parent_doctype == "Sales Order" and flt(d.get("qty")) < flt(child_item.delivered_qty):
1422 frappe.throw(_("Cannot set quantity less than delivered quantity"))
1423
1424 if parent_doctype == "Purchase Order" and flt(d.get("qty")) < flt(child_item.received_qty):
1425 frappe.throw(_("Cannot set quantity less than received quantity"))
1426
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001427 data = json.loads(trans_items)
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001428
rohitwaghchaure81c21752019-10-31 15:56:10 +05301429 sales_doctypes = ['Sales Order', 'Sales Invoice', 'Delivery Note', 'Quotation']
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05301430 parent = frappe.get_doc(parent_doctype, parent_doctype_name)
marination665c27a2020-09-15 12:04:38 +05301431
marination661bf642020-09-29 18:16:45 +05301432 check_doc_permissions(parent, 'write')
Saqib6db92fb2020-09-14 19:54:17 +05301433 validate_and_delete_children(parent, data)
Saqib0ad74492019-12-24 16:42:30 +05301434
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01001435 for d in data:
1436 new_child_flag = False
1437 if not d.get("docname"):
1438 new_child_flag = True
Saqib6db92fb2020-09-14 19:54:17 +05301439 check_doc_permissions(parent, 'create')
Rohit Waghchaure8d5380a2020-06-18 14:06:31 +05301440 child_item = get_new_child_item(d)
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01001441 else:
Saqib6db92fb2020-09-14 19:54:17 +05301442 check_doc_permissions(parent, 'write')
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01001443 child_item = frappe.get_doc(parent_doctype + ' Item', d.get("docname"))
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05301444
Saqib Ansaric579b082020-05-29 22:21:50 +05301445 prev_rate, new_rate = flt(child_item.get("rate")), flt(d.get("rate"))
1446 prev_qty, new_qty = flt(child_item.get("qty")), flt(d.get("qty"))
1447 prev_con_fac, new_con_fac = flt(child_item.get("conversion_factor")), flt(d.get("conversion_factor"))
Saqib61314242020-09-15 11:14:31 +05301448 prev_uom, new_uom = child_item.get("uom"), d.get("uom")
Saqib Ansaric579b082020-05-29 22:21:50 +05301449
1450 if parent_doctype == 'Sales Order':
1451 prev_date, new_date = child_item.get("delivery_date"), d.get("delivery_date")
1452 elif parent_doctype == 'Purchase Order':
marinationb7e94cc2020-06-15 11:32:42 +05301453 prev_date, new_date = child_item.get("schedule_date"), d.get("schedule_date")
Saqib Ansaric579b082020-05-29 22:21:50 +05301454
1455 rate_unchanged = prev_rate == new_rate
marinationf9c4b202020-06-12 15:49:53 +05301456 qty_unchanged = prev_qty == new_qty
Saqib61314242020-09-15 11:14:31 +05301457 uom_unchanged = prev_uom == new_uom
Saqib Ansaric579b082020-05-29 22:21:50 +05301458 conversion_factor_unchanged = prev_con_fac == new_con_fac
1459 date_unchanged = prev_date == new_date if prev_date and new_date else False # in case of delivery note etc
Saqib61314242020-09-15 11:14:31 +05301460 if rate_unchanged and qty_unchanged and conversion_factor_unchanged and uom_unchanged and date_unchanged:
Saqibdd374ff2020-02-27 12:51:31 +05301461 continue
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01001462
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05301463 validate_quantity(child_item, d)
deepeshgarg00777cde832018-12-27 15:56:51 +05301464
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01001465 child_item.qty = flt(d.get("qty"))
Saqib56fea7d2020-10-09 21:19:25 +05301466 rate_precision = child_item.precision("rate") or 2
1467 conv_fac_precision = child_item.precision("conversion_factor") or 2
1468 qty_precision = child_item.precision("qty") or 2
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001469
Saqib56fea7d2020-10-09 21:19:25 +05301470 if flt(child_item.billed_amt, rate_precision) > flt(flt(d.get("rate"), rate_precision) * flt(d.get("qty"), qty_precision), rate_precision):
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001471 frappe.throw(_("Row #{0}: Cannot set Rate if amount is greater than billed amount for Item {1}.")
1472 .format(child_item.idx, child_item.item_code))
1473 else:
Saqib56fea7d2020-10-09 21:19:25 +05301474 child_item.rate = flt(d.get("rate"), rate_precision)
marinationf9c4b202020-06-12 15:49:53 +05301475
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +05301476 if d.get("conversion_factor"):
marinationf9c4b202020-06-12 15:49:53 +05301477 if child_item.stock_uom == child_item.uom:
1478 child_item.conversion_factor = 1
1479 else:
Saqib56fea7d2020-10-09 21:19:25 +05301480 child_item.conversion_factor = flt(d.get('conversion_factor'), conv_fac_precision)
marination665c27a2020-09-15 12:04:38 +05301481
Saqib61314242020-09-15 11:14:31 +05301482 if d.get("uom"):
1483 child_item.uom = d.get("uom")
1484 conversion_factor = flt(get_conversion_factor(child_item.item_code, child_item.uom).get("conversion_factor"))
Saqib56fea7d2020-10-09 21:19:25 +05301485 child_item.conversion_factor = flt(d.get('conversion_factor'), conv_fac_precision) or conversion_factor
Mangesh-Khairnara3d52002019-08-05 10:16:40 +05301486
Saqib Ansaric579b082020-05-29 22:21:50 +05301487 if d.get("delivery_date") and parent_doctype == 'Sales Order':
1488 child_item.delivery_date = d.get('delivery_date')
marinationf9c4b202020-06-12 15:49:53 +05301489
Saqib Ansaric579b082020-05-29 22:21:50 +05301490 if d.get("schedule_date") and parent_doctype == 'Purchase Order':
1491 child_item.schedule_date = d.get('schedule_date')
1492
Mangesh-Khairnara3d52002019-08-05 10:16:40 +05301493 if flt(child_item.price_list_rate):
Maricaf0674472019-10-11 10:47:09 +05301494 if flt(child_item.rate) > flt(child_item.price_list_rate):
1495 # if rate is greater than price_list_rate, set margin
1496 # or set discount
1497 child_item.discount_percentage = 0
rohitwaghchaure81c21752019-10-31 15:56:10 +05301498
1499 if parent_doctype in sales_doctypes:
1500 child_item.margin_type = "Amount"
1501 child_item.margin_rate_or_amount = flt(child_item.rate - child_item.price_list_rate,
1502 child_item.precision("margin_rate_or_amount"))
1503 child_item.rate_with_margin = child_item.rate
Maricaf0674472019-10-11 10:47:09 +05301504 else:
1505 child_item.discount_percentage = flt((1 - flt(child_item.rate) / flt(child_item.price_list_rate)) * 100.0,
1506 child_item.precision("discount_percentage"))
1507 child_item.discount_amount = flt(
1508 child_item.price_list_rate) - flt(child_item.rate)
rohitwaghchaure81c21752019-10-31 15:56:10 +05301509
1510 if parent_doctype in sales_doctypes:
1511 child_item.margin_type = ""
1512 child_item.margin_rate_or_amount = 0
1513 child_item.rate_with_margin = 0
Mangesh-Khairnara3d52002019-08-05 10:16:40 +05301514
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001515 child_item.flags.ignore_validate_update_after_submit = True
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01001516 if new_child_flag:
Saqib Ansarif53299e2020-04-15 22:08:12 +05301517 parent.load_from_db()
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05301518 child_item.idx = len(parent.items) + 1
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +01001519 child_item.insert()
1520 else:
1521 child_item.save()
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001522
Rushabh Mehtafafbb022018-12-24 22:09:15 +05301523 parent.reload()
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05301524 parent.flags.ignore_validate_update_after_submit = True
1525 parent.set_qty_as_per_stock_uom()
1526 parent.calculate_taxes_and_totals()
Ankush Menatdf6e2082021-02-11 11:04:39 +05301527 parent.set_total_in_words()
Nabin Hait49a46f02019-10-21 13:35:43 +05301528 if parent_doctype == "Sales Order":
Marica3dee5272020-06-23 10:33:47 +05301529 make_packing_list(parent)
Nabin Hait49a46f02019-10-21 13:35:43 +05301530 parent.set_gross_profit()
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05301531 frappe.get_doc('Authorization Control').validate_approving_authority(parent.doctype,
1532 parent.company, parent.base_grand_total)
Doridel Cahanap6f06cc22018-05-17 16:28:58 +08001533
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05301534 parent.set_payment_schedule()
Nabin Haitb2da0822018-07-13 17:01:40 +05301535 if parent_doctype == 'Purchase Order':
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05301536 parent.validate_minimum_order_qty()
1537 parent.validate_budget()
1538 if parent.is_against_so():
1539 parent.update_status_updater()
Nabin Haitb2da0822018-07-13 17:01:40 +05301540 else:
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05301541 parent.check_credit_limit()
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05301542 parent.save()
Nabin Haitb2da0822018-07-13 17:01:40 +05301543
1544 if parent_doctype == 'Purchase Order':
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05301545 update_last_purchase_rate(parent, is_submit = 1)
1546 parent.update_prevdoc_status()
1547 parent.update_requested_qty()
1548 parent.update_ordered_qty()
1549 parent.update_ordered_and_reserved_qty()
1550 parent.update_receiving_percentage()
1551 if parent.is_subcontracted == "Yes":
1552 parent.update_reserved_qty_for_subcontract()
Saqib61314242020-09-15 11:14:31 +05301553 parent.create_raw_materials_supplied("supplied_items")
1554 parent.save()
Nabin Haitb2da0822018-07-13 17:01:40 +05301555 else:
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05301556 parent.update_reserved_qty()
1557 parent.update_project()
1558 parent.update_prevdoc_status('submit')
1559 parent.update_delivery_status()
Nabin Haitb2da0822018-07-13 17:01:40 +05301560
Saqib6db92fb2020-09-14 19:54:17 +05301561 parent.reload()
1562 validate_workflow_conditions(parent)
1563
Rushabh Mehtac9b1a352018-12-24 20:55:35 +05301564 parent.update_blanket_order()
1565 parent.update_billing_percentage()
1566 parent.set_status()
Gauravf1e28e02019-02-13 16:46:24 +05301567
1568@erpnext.allow_regional
1569def validate_regional(doc):
1570 pass
Saqib6d74f5b2020-12-25 10:26:43 +05301571
1572@erpnext.allow_regional
1573def validate_einvoice_fields(doc):
1574 pass