You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

2832 lines
90 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # License: GNU General Public License v3. See license.txt
  3. import json
  4. import frappe
  5. from frappe import _, bold, throw
  6. from frappe.model.workflow import get_workflow_name, is_transition_condition_satisfied
  7. from frappe.query_builder.functions import Abs, Sum
  8. from frappe.utils import (
  9. add_days,
  10. add_months,
  11. cint,
  12. flt,
  13. fmt_money,
  14. formatdate,
  15. get_last_day,
  16. get_link_to_form,
  17. getdate,
  18. nowdate,
  19. today,
  20. )
  21. import erpnext
  22. from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import (
  23. get_accounting_dimensions,
  24. )
  25. from erpnext.accounts.doctype.pricing_rule.utils import (
  26. apply_pricing_rule_for_free_items,
  27. apply_pricing_rule_on_transaction,
  28. get_applied_pricing_rules,
  29. )
  30. from erpnext.accounts.party import (
  31. get_party_account,
  32. get_party_account_currency,
  33. get_party_gle_currency,
  34. validate_party_frozen_disabled,
  35. )
  36. from erpnext.accounts.utils import get_account_currency, get_fiscal_years, validate_fiscal_year
  37. from erpnext.buying.utils import update_last_purchase_rate
  38. from erpnext.controllers.print_settings import (
  39. set_print_templates_for_item_table,
  40. set_print_templates_for_taxes,
  41. )
  42. from erpnext.controllers.sales_and_purchase_return import validate_return
  43. from erpnext.exceptions import InvalidCurrency
  44. from erpnext.setup.utils import get_exchange_rate
  45. from erpnext.stock.doctype.item.item import get_uom_conv_factor
  46. from erpnext.stock.doctype.packed_item.packed_item import make_packing_list
  47. from erpnext.stock.get_item_details import (
  48. _get_item_tax_template,
  49. get_conversion_factor,
  50. get_item_details,
  51. get_item_tax_map,
  52. get_item_warehouse,
  53. )
  54. from erpnext.utilities.transaction_base import TransactionBase
  55. class AccountMissingError(frappe.ValidationError):
  56. pass
  57. force_item_fields = (
  58. "item_group",
  59. "brand",
  60. "stock_uom",
  61. "is_fixed_asset",
  62. "item_tax_rate",
  63. "pricing_rules",
  64. "weight_per_unit",
  65. "weight_uom",
  66. "total_weight",
  67. )
  68. class AccountsController(TransactionBase):
  69. def __init__(self, *args, **kwargs):
  70. super(AccountsController, self).__init__(*args, **kwargs)
  71. def get_print_settings(self):
  72. print_setting_fields = []
  73. items_field = self.meta.get_field("items")
  74. if items_field and items_field.fieldtype == "Table":
  75. print_setting_fields += ["compact_item_print", "print_uom_after_quantity"]
  76. taxes_field = self.meta.get_field("taxes")
  77. if taxes_field and taxes_field.fieldtype == "Table":
  78. print_setting_fields += ["print_taxes_with_zero_amount"]
  79. return print_setting_fields
  80. @property
  81. def company_currency(self):
  82. if not hasattr(self, "__company_currency"):
  83. self.__company_currency = erpnext.get_company_currency(self.company)
  84. return self.__company_currency
  85. def onload(self):
  86. self.set_onload(
  87. "make_payment_via_journal_entry",
  88. frappe.db.get_single_value("Accounts Settings", "make_payment_via_journal_entry"),
  89. )
  90. if self.is_new():
  91. relevant_docs = (
  92. "Quotation",
  93. "Purchase Order",
  94. "Sales Order",
  95. "Purchase Invoice",
  96. "Sales Invoice",
  97. )
  98. if self.doctype in relevant_docs:
  99. self.set_payment_schedule()
  100. def ensure_supplier_is_not_blocked(self):
  101. is_supplier_payment = self.doctype == "Payment Entry" and self.party_type == "Supplier"
  102. is_buying_invoice = self.doctype in ["Purchase Invoice", "Purchase Order"]
  103. supplier = None
  104. supplier_name = None
  105. if is_buying_invoice or is_supplier_payment:
  106. supplier_name = self.supplier if is_buying_invoice else self.party
  107. supplier = frappe.get_doc("Supplier", supplier_name)
  108. if supplier and supplier_name and supplier.on_hold:
  109. if (is_buying_invoice and supplier.hold_type in ["All", "Invoices"]) or (
  110. is_supplier_payment and supplier.hold_type in ["All", "Payments"]
  111. ):
  112. if not supplier.release_date or getdate(nowdate()) <= supplier.release_date:
  113. frappe.msgprint(
  114. _("{0} is blocked so this transaction cannot proceed").format(supplier_name),
  115. raise_exception=1,
  116. )
  117. def validate(self):
  118. if not self.get("is_return") and not self.get("is_debit_note"):
  119. self.validate_qty_is_not_zero()
  120. if self.get("_action") and self._action != "update_after_submit":
  121. self.set_missing_values(for_validate=True)
  122. self.ensure_supplier_is_not_blocked()
  123. self.validate_date_with_fiscal_year()
  124. self.validate_party_accounts()
  125. self.validate_inter_company_reference()
  126. self.disable_pricing_rule_on_internal_transfer()
  127. self.disable_tax_included_prices_for_internal_transfer()
  128. self.set_incoming_rate()
  129. if self.meta.get_field("currency"):
  130. self.calculate_taxes_and_totals()
  131. if not self.meta.get_field("is_return") or not self.is_return:
  132. self.validate_value("base_grand_total", ">=", 0)
  133. validate_return(self)
  134. self.set_total_in_words()
  135. self.validate_all_documents_schedule()
  136. if self.meta.get_field("taxes_and_charges"):
  137. self.validate_enabled_taxes_and_charges()
  138. self.validate_tax_account_company()
  139. self.validate_party()
  140. self.validate_currency()
  141. self.validate_party_account_currency()
  142. if self.doctype in ["Purchase Invoice", "Sales Invoice"]:
  143. pos_check_field = "is_pos" if self.doctype == "Sales Invoice" else "is_paid"
  144. if cint(self.allocate_advances_automatically) and not cint(self.get(pos_check_field)):
  145. self.set_advances()
  146. self.set_advance_gain_or_loss()
  147. if self.is_return:
  148. self.validate_qty()
  149. else:
  150. self.validate_deferred_start_and_end_date()
  151. self.validate_deferred_income_expense_account()
  152. self.set_inter_company_account()
  153. if self.doctype == "Purchase Invoice":
  154. self.calculate_paid_amount()
  155. # apply tax withholding only if checked and applicable
  156. self.set_tax_withholding()
  157. validate_regional(self)
  158. validate_einvoice_fields(self)
  159. if self.doctype != "Material Request" and not self.ignore_pricing_rule:
  160. apply_pricing_rule_on_transaction(self)
  161. def before_cancel(self):
  162. validate_einvoice_fields(self)
  163. def on_trash(self):
  164. # delete references in 'Repost Payment Ledger'
  165. rpi = frappe.qb.DocType("Repost Payment Ledger Items")
  166. frappe.qb.from_(rpi).delete().where(
  167. (rpi.voucher_type == self.doctype) & (rpi.voucher_no == self.name)
  168. ).run()
  169. # delete sl and gl entries on deletion of transaction
  170. if frappe.db.get_single_value("Accounts Settings", "delete_linked_ledger_entries"):
  171. ple = frappe.qb.DocType("Payment Ledger Entry")
  172. frappe.qb.from_(ple).delete().where(
  173. (ple.voucher_type == self.doctype) & (ple.voucher_no == self.name)
  174. ).run()
  175. frappe.db.sql(
  176. "delete from `tabGL Entry` where voucher_type=%s and voucher_no=%s", (self.doctype, self.name)
  177. )
  178. frappe.db.sql(
  179. "delete from `tabStock Ledger Entry` where voucher_type=%s and voucher_no=%s",
  180. (self.doctype, self.name),
  181. )
  182. def validate_deferred_income_expense_account(self):
  183. field_map = {
  184. "Sales Invoice": "deferred_revenue_account",
  185. "Purchase Invoice": "deferred_expense_account",
  186. }
  187. for item in self.get("items"):
  188. if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
  189. if not item.get(field_map.get(self.doctype)):
  190. default_deferred_account = frappe.get_cached_value(
  191. "Company", self.company, "default_" + field_map.get(self.doctype)
  192. )
  193. if not default_deferred_account:
  194. frappe.throw(
  195. _(
  196. "Row #{0}: Please update deferred revenue/expense account in item row or default account in company master"
  197. ).format(item.idx)
  198. )
  199. else:
  200. item.set(field_map.get(self.doctype), default_deferred_account)
  201. def validate_auto_repeat_subscription_dates(self):
  202. if (
  203. self.get("from_date")
  204. and self.get("to_date")
  205. and getdate(self.from_date) > getdate(self.to_date)
  206. ):
  207. frappe.throw(_("To Date cannot be before From Date"), title=_("Invalid Auto Repeat Date"))
  208. def validate_deferred_start_and_end_date(self):
  209. for d in self.items:
  210. if d.get("enable_deferred_revenue") or d.get("enable_deferred_expense"):
  211. if not (d.service_start_date and d.service_end_date):
  212. frappe.throw(
  213. _("Row #{0}: Service Start and End Date is required for deferred accounting").format(d.idx)
  214. )
  215. elif getdate(d.service_start_date) > getdate(d.service_end_date):
  216. frappe.throw(
  217. _("Row #{0}: Service Start Date cannot be greater than Service End Date").format(d.idx)
  218. )
  219. elif getdate(self.posting_date) > getdate(d.service_end_date):
  220. frappe.throw(
  221. _("Row #{0}: Service End Date cannot be before Invoice Posting Date").format(d.idx)
  222. )
  223. def validate_invoice_documents_schedule(self):
  224. self.validate_payment_schedule_dates()
  225. self.set_due_date()
  226. self.set_payment_schedule()
  227. if not self.get("ignore_default_payment_terms_template"):
  228. self.validate_payment_schedule_amount()
  229. self.validate_due_date()
  230. self.validate_advance_entries()
  231. def validate_non_invoice_documents_schedule(self):
  232. self.set_payment_schedule()
  233. self.validate_payment_schedule_dates()
  234. self.validate_payment_schedule_amount()
  235. def validate_all_documents_schedule(self):
  236. if self.doctype in ("Sales Invoice", "Purchase Invoice") and not self.is_return:
  237. self.validate_invoice_documents_schedule()
  238. elif self.doctype in ("Quotation", "Purchase Order", "Sales Order"):
  239. self.validate_non_invoice_documents_schedule()
  240. def before_print(self, settings=None):
  241. if self.doctype in [
  242. "Purchase Order",
  243. "Sales Order",
  244. "Sales Invoice",
  245. "Purchase Invoice",
  246. "Supplier Quotation",
  247. "Purchase Receipt",
  248. "Delivery Note",
  249. "Quotation",
  250. ]:
  251. if self.get("group_same_items"):
  252. self.group_similar_items()
  253. df = self.meta.get_field("discount_amount")
  254. if self.get("discount_amount") and hasattr(self, "taxes") and not len(self.taxes):
  255. df.set("print_hide", 0)
  256. self.discount_amount = -self.discount_amount
  257. else:
  258. df.set("print_hide", 1)
  259. set_print_templates_for_item_table(self, settings)
  260. set_print_templates_for_taxes(self, settings)
  261. def calculate_paid_amount(self):
  262. if hasattr(self, "is_pos") or hasattr(self, "is_paid"):
  263. is_paid = self.get("is_pos") or self.get("is_paid")
  264. if is_paid:
  265. if not self.cash_bank_account:
  266. # show message that the amount is not paid
  267. frappe.throw(
  268. _("Note: Payment Entry will not be created since 'Cash or Bank Account' was not specified")
  269. )
  270. if cint(self.is_return) and self.grand_total > self.paid_amount:
  271. self.paid_amount = flt(flt(self.grand_total), self.precision("paid_amount"))
  272. elif not flt(self.paid_amount) and flt(self.outstanding_amount) > 0:
  273. self.paid_amount = flt(flt(self.outstanding_amount), self.precision("paid_amount"))
  274. self.base_paid_amount = flt(
  275. self.paid_amount * self.conversion_rate, self.precision("base_paid_amount")
  276. )
  277. def set_missing_values(self, for_validate=False):
  278. if frappe.flags.in_test:
  279. for fieldname in ["posting_date", "transaction_date"]:
  280. if self.meta.get_field(fieldname) and not self.get(fieldname):
  281. self.set(fieldname, today())
  282. break
  283. def calculate_taxes_and_totals(self):
  284. from erpnext.controllers.taxes_and_totals import calculate_taxes_and_totals
  285. calculate_taxes_and_totals(self)
  286. if self.doctype in (
  287. "Sales Order",
  288. "Delivery Note",
  289. "Sales Invoice",
  290. "POS Invoice",
  291. ):
  292. self.calculate_commission()
  293. self.calculate_contribution()
  294. def validate_date_with_fiscal_year(self):
  295. if self.meta.get_field("fiscal_year"):
  296. date_field = None
  297. if self.meta.get_field("posting_date"):
  298. date_field = "posting_date"
  299. elif self.meta.get_field("transaction_date"):
  300. date_field = "transaction_date"
  301. if date_field and self.get(date_field):
  302. validate_fiscal_year(
  303. self.get(date_field), self.fiscal_year, self.company, self.meta.get_label(date_field), self
  304. )
  305. def validate_party_accounts(self):
  306. if self.doctype not in ("Sales Invoice", "Purchase Invoice"):
  307. return
  308. if self.doctype == "Sales Invoice":
  309. party_account_field = "debit_to"
  310. item_field = "income_account"
  311. else:
  312. party_account_field = "credit_to"
  313. item_field = "expense_account"
  314. for item in self.get("items"):
  315. if item.get(item_field) == self.get(party_account_field):
  316. frappe.throw(
  317. _("Row {0}: {1} {2} cannot be same as {3} (Party Account) {4}").format(
  318. item.idx,
  319. frappe.bold(frappe.unscrub(item_field)),
  320. item.get(item_field),
  321. frappe.bold(frappe.unscrub(party_account_field)),
  322. self.get(party_account_field),
  323. )
  324. )
  325. def validate_inter_company_reference(self):
  326. if self.doctype not in ("Purchase Invoice", "Purchase Receipt"):
  327. return
  328. if self.is_internal_transfer():
  329. if not (
  330. self.get("inter_company_reference")
  331. or self.get("inter_company_invoice_reference")
  332. or self.get("inter_company_order_reference")
  333. ) and not self.get("is_return"):
  334. msg = _("Internal Sale or Delivery Reference missing.")
  335. msg += _("Please create purchase from internal sale or delivery document itself")
  336. frappe.throw(msg, title=_("Internal Sales Reference Missing"))
  337. label = "Delivery Note Item" if self.doctype == "Purchase Receipt" else "Sales Invoice Item"
  338. field = frappe.scrub(label)
  339. for row in self.get("items"):
  340. if not row.get(field):
  341. msg = f"At Row {row.idx}: The field {bold(label)} is mandatory for internal transfer"
  342. frappe.throw(_(msg), title=_("Internal Transfer Reference Missing"))
  343. def disable_pricing_rule_on_internal_transfer(self):
  344. if not self.get("ignore_pricing_rule") and self.is_internal_transfer():
  345. self.ignore_pricing_rule = 1
  346. frappe.msgprint(
  347. _("Disabled pricing rules since this {} is an internal transfer").format(self.doctype),
  348. alert=1,
  349. )
  350. def disable_tax_included_prices_for_internal_transfer(self):
  351. if self.is_internal_transfer():
  352. tax_updated = False
  353. for tax in self.get("taxes"):
  354. if tax.get("included_in_print_rate"):
  355. tax.included_in_print_rate = 0
  356. tax_updated = True
  357. if tax_updated:
  358. frappe.msgprint(
  359. _("Disabled tax included prices since this {} is an internal transfer").format(self.doctype),
  360. alert=1,
  361. )
  362. def validate_due_date(self):
  363. if self.get("is_pos"):
  364. return
  365. from erpnext.accounts.party import validate_due_date
  366. if self.doctype == "Sales Invoice":
  367. if not self.due_date:
  368. frappe.throw(_("Due Date is mandatory"))
  369. validate_due_date(
  370. self.posting_date,
  371. self.due_date,
  372. "Customer",
  373. self.customer,
  374. self.company,
  375. self.payment_terms_template,
  376. )
  377. elif self.doctype == "Purchase Invoice":
  378. validate_due_date(
  379. self.bill_date or self.posting_date,
  380. self.due_date,
  381. "Supplier",
  382. self.supplier,
  383. self.company,
  384. self.bill_date,
  385. self.payment_terms_template,
  386. )
  387. def set_price_list_currency(self, buying_or_selling):
  388. if self.meta.get_field("posting_date"):
  389. transaction_date = self.posting_date
  390. else:
  391. transaction_date = self.transaction_date
  392. if self.meta.get_field("currency"):
  393. # price list part
  394. if buying_or_selling.lower() == "selling":
  395. fieldname = "selling_price_list"
  396. args = "for_selling"
  397. else:
  398. fieldname = "buying_price_list"
  399. args = "for_buying"
  400. if self.meta.get_field(fieldname) and self.get(fieldname):
  401. self.price_list_currency = frappe.db.get_value("Price List", self.get(fieldname), "currency")
  402. if self.price_list_currency == self.company_currency:
  403. self.plc_conversion_rate = 1.0
  404. elif not self.plc_conversion_rate:
  405. self.plc_conversion_rate = get_exchange_rate(
  406. self.price_list_currency, self.company_currency, transaction_date, args
  407. )
  408. # currency
  409. if not self.currency:
  410. self.currency = self.price_list_currency
  411. self.conversion_rate = self.plc_conversion_rate
  412. elif self.currency == self.company_currency:
  413. self.conversion_rate = 1.0
  414. elif not self.conversion_rate:
  415. self.conversion_rate = get_exchange_rate(
  416. self.currency, self.company_currency, transaction_date, args
  417. )
  418. def set_missing_item_details(self, for_validate=False):
  419. """set missing item values"""
  420. from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
  421. if hasattr(self, "items"):
  422. parent_dict = {}
  423. for fieldname in self.meta.get_valid_columns():
  424. parent_dict[fieldname] = self.get(fieldname)
  425. if self.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
  426. document_type = "{} Item".format(self.doctype)
  427. parent_dict.update({"document_type": document_type})
  428. # party_name field used for customer in quotation
  429. if (
  430. self.doctype == "Quotation"
  431. and self.quotation_to == "Customer"
  432. and parent_dict.get("party_name")
  433. ):
  434. parent_dict.update({"customer": parent_dict.get("party_name")})
  435. self.pricing_rules = []
  436. for item in self.get("items"):
  437. if item.get("item_code"):
  438. args = parent_dict.copy()
  439. args.update(item.as_dict())
  440. args["doctype"] = self.doctype
  441. args["name"] = self.name
  442. args["child_docname"] = item.name
  443. args["ignore_pricing_rule"] = (
  444. self.ignore_pricing_rule if hasattr(self, "ignore_pricing_rule") else 0
  445. )
  446. if not args.get("transaction_date"):
  447. args["transaction_date"] = args.get("posting_date")
  448. if self.get("is_subcontracted"):
  449. args["is_subcontracted"] = self.is_subcontracted
  450. ret = get_item_details(args, self, for_validate=True, overwrite_warehouse=False)
  451. for fieldname, value in ret.items():
  452. if item.meta.get_field(fieldname) and value is not None:
  453. if item.get(fieldname) is None or fieldname in force_item_fields:
  454. item.set(fieldname, value)
  455. elif fieldname in ["cost_center", "conversion_factor"] and not item.get(fieldname):
  456. item.set(fieldname, value)
  457. elif fieldname == "serial_no":
  458. # Ensure that serial numbers are matched against Stock UOM
  459. item_conversion_factor = item.get("conversion_factor") or 1.0
  460. item_qty = abs(item.get("qty")) * item_conversion_factor
  461. if item_qty != len(get_serial_nos(item.get("serial_no"))):
  462. item.set(fieldname, value)
  463. elif (
  464. ret.get("pricing_rule_removed")
  465. and value is not None
  466. and fieldname
  467. in [
  468. "discount_percentage",
  469. "discount_amount",
  470. "rate",
  471. "margin_rate_or_amount",
  472. "margin_type",
  473. "remove_free_item",
  474. ]
  475. ):
  476. # reset pricing rule fields if pricing_rule_removed
  477. item.set(fieldname, value)
  478. if self.doctype in ["Purchase Invoice", "Sales Invoice"] and item.meta.get_field(
  479. "is_fixed_asset"
  480. ):
  481. item.set("is_fixed_asset", ret.get("is_fixed_asset", 0))
  482. # Double check for cost center
  483. # Items add via promotional scheme may not have cost center set
  484. if hasattr(item, "cost_center") and not item.get("cost_center"):
  485. item.set(
  486. "cost_center", self.get("cost_center") or erpnext.get_default_cost_center(self.company)
  487. )
  488. if ret.get("pricing_rules"):
  489. self.apply_pricing_rule_on_items(item, ret)
  490. self.set_pricing_rule_details(item, ret)
  491. else:
  492. # Transactions line item without item code
  493. uom = item.get("uom")
  494. stock_uom = item.get("stock_uom")
  495. if bool(uom) != bool(stock_uom): # xor
  496. item.stock_uom = item.uom = uom or stock_uom
  497. # UOM cannot be zero so substitute as 1
  498. item.conversion_factor = (
  499. get_uom_conv_factor(item.get("uom"), item.get("stock_uom"))
  500. or item.get("conversion_factor")
  501. or 1
  502. )
  503. if self.doctype == "Purchase Invoice":
  504. self.set_expense_account(for_validate)
  505. def apply_pricing_rule_on_items(self, item, pricing_rule_args):
  506. if not pricing_rule_args.get("validate_applied_rule", 0):
  507. # if user changed the discount percentage then set user's discount percentage ?
  508. if pricing_rule_args.get("price_or_product_discount") == "Price":
  509. item.set("pricing_rules", pricing_rule_args.get("pricing_rules"))
  510. if pricing_rule_args.get("apply_rule_on_other_items"):
  511. other_items = json.loads(pricing_rule_args.get("apply_rule_on_other_items"))
  512. if other_items and item.item_code not in other_items:
  513. return
  514. item.set("discount_percentage", pricing_rule_args.get("discount_percentage"))
  515. item.set("discount_amount", pricing_rule_args.get("discount_amount"))
  516. if pricing_rule_args.get("pricing_rule_for") == "Rate":
  517. item.set("price_list_rate", pricing_rule_args.get("price_list_rate"))
  518. if item.get("price_list_rate"):
  519. item.rate = flt(
  520. item.price_list_rate * (1.0 - (flt(item.discount_percentage) / 100.0)),
  521. item.precision("rate"),
  522. )
  523. if item.get("discount_amount"):
  524. item.rate = item.price_list_rate - item.discount_amount
  525. if item.get("apply_discount_on_discounted_rate") and pricing_rule_args.get("rate"):
  526. item.rate = pricing_rule_args.get("rate")
  527. elif pricing_rule_args.get("free_item_data"):
  528. apply_pricing_rule_for_free_items(self, pricing_rule_args.get("free_item_data"))
  529. elif pricing_rule_args.get("validate_applied_rule"):
  530. for pricing_rule in get_applied_pricing_rules(item.get("pricing_rules")):
  531. pricing_rule_doc = frappe.get_cached_doc("Pricing Rule", pricing_rule)
  532. for field in ["discount_percentage", "discount_amount", "rate"]:
  533. if item.get(field) < pricing_rule_doc.get(field):
  534. title = get_link_to_form("Pricing Rule", pricing_rule)
  535. frappe.msgprint(
  536. _("Row {0}: user has not applied the rule {1} on the item {2}").format(
  537. item.idx, frappe.bold(title), frappe.bold(item.item_code)
  538. )
  539. )
  540. def set_pricing_rule_details(self, item_row, args):
  541. pricing_rules = get_applied_pricing_rules(args.get("pricing_rules"))
  542. if not pricing_rules:
  543. return
  544. for pricing_rule in pricing_rules:
  545. self.append(
  546. "pricing_rules",
  547. {
  548. "pricing_rule": pricing_rule,
  549. "item_code": item_row.item_code,
  550. "child_docname": item_row.name,
  551. "rule_applied": True,
  552. },
  553. )
  554. def set_taxes(self):
  555. if not self.meta.get_field("taxes"):
  556. return
  557. tax_master_doctype = self.meta.get_field("taxes_and_charges").options
  558. if (self.is_new() or self.is_pos_profile_changed()) and not self.get("taxes"):
  559. if self.company and not self.get("taxes_and_charges"):
  560. # get the default tax master
  561. self.taxes_and_charges = frappe.db.get_value(
  562. tax_master_doctype, {"is_default": 1, "company": self.company}
  563. )
  564. self.append_taxes_from_master(tax_master_doctype)
  565. def is_pos_profile_changed(self):
  566. if (
  567. self.doctype == "Sales Invoice"
  568. and self.is_pos
  569. and self.pos_profile != frappe.db.get_value("Sales Invoice", self.name, "pos_profile")
  570. ):
  571. return True
  572. def append_taxes_from_master(self, tax_master_doctype=None):
  573. if self.get("taxes_and_charges"):
  574. if not tax_master_doctype:
  575. tax_master_doctype = self.meta.get_field("taxes_and_charges").options
  576. self.extend("taxes", get_taxes_and_charges(tax_master_doctype, self.get("taxes_and_charges")))
  577. def set_other_charges(self):
  578. self.set("taxes", [])
  579. self.set_taxes()
  580. def validate_enabled_taxes_and_charges(self):
  581. taxes_and_charges_doctype = self.meta.get_options("taxes_and_charges")
  582. if frappe.get_cached_value(taxes_and_charges_doctype, self.taxes_and_charges, "disabled"):
  583. frappe.throw(
  584. _("{0} '{1}' is disabled").format(taxes_and_charges_doctype, self.taxes_and_charges)
  585. )
  586. def validate_tax_account_company(self):
  587. for d in self.get("taxes"):
  588. if d.account_head:
  589. tax_account_company = frappe.get_cached_value("Account", d.account_head, "company")
  590. if tax_account_company != self.company:
  591. frappe.throw(
  592. _("Row #{0}: Account {1} does not belong to company {2}").format(
  593. d.idx, d.account_head, self.company
  594. )
  595. )
  596. def get_gl_dict(self, args, account_currency=None, item=None):
  597. """this method populates the common properties of a gl entry record"""
  598. posting_date = args.get("posting_date") or self.get("posting_date")
  599. fiscal_years = get_fiscal_years(posting_date, company=self.company)
  600. if len(fiscal_years) > 1:
  601. frappe.throw(
  602. _("Multiple fiscal years exist for the date {0}. Please set company in Fiscal Year").format(
  603. formatdate(posting_date)
  604. )
  605. )
  606. else:
  607. fiscal_year = fiscal_years[0][0]
  608. gl_dict = frappe._dict(
  609. {
  610. "company": self.company,
  611. "posting_date": posting_date,
  612. "fiscal_year": fiscal_year,
  613. "voucher_type": self.doctype,
  614. "voucher_no": self.name,
  615. "remarks": self.get("remarks") or self.get("remark"),
  616. "debit": 0,
  617. "credit": 0,
  618. "debit_in_account_currency": 0,
  619. "credit_in_account_currency": 0,
  620. "is_opening": self.get("is_opening") or "No",
  621. "party_type": None,
  622. "party": None,
  623. "project": self.get("project"),
  624. "post_net_value": args.get("post_net_value"),
  625. }
  626. )
  627. accounting_dimensions = get_accounting_dimensions()
  628. dimension_dict = frappe._dict()
  629. for dimension in accounting_dimensions:
  630. dimension_dict[dimension] = self.get(dimension)
  631. if item and item.get(dimension):
  632. dimension_dict[dimension] = item.get(dimension)
  633. gl_dict.update(dimension_dict)
  634. gl_dict.update(args)
  635. if not account_currency:
  636. account_currency = get_account_currency(gl_dict.account)
  637. if gl_dict.account and self.doctype not in [
  638. "Journal Entry",
  639. "Period Closing Voucher",
  640. "Payment Entry",
  641. "Purchase Receipt",
  642. "Purchase Invoice",
  643. "Stock Entry",
  644. ]:
  645. self.validate_account_currency(gl_dict.account, account_currency)
  646. if gl_dict.account and self.doctype not in [
  647. "Journal Entry",
  648. "Period Closing Voucher",
  649. "Payment Entry",
  650. ]:
  651. set_balance_in_account_currency(
  652. gl_dict, account_currency, self.get("conversion_rate"), self.company_currency
  653. )
  654. return gl_dict
  655. def validate_qty_is_not_zero(self):
  656. if self.doctype != "Purchase Receipt":
  657. for item in self.items:
  658. if not item.qty:
  659. frappe.throw(_("Item quantity can not be zero"))
  660. def validate_account_currency(self, account, account_currency=None):
  661. valid_currency = [self.company_currency]
  662. if self.get("currency") and self.currency != self.company_currency:
  663. valid_currency.append(self.currency)
  664. if account_currency not in valid_currency:
  665. frappe.throw(
  666. _("Account {0} is invalid. Account Currency must be {1}").format(
  667. account, (" " + _("or") + " ").join(valid_currency)
  668. )
  669. )
  670. def clear_unallocated_advances(self, childtype, parentfield):
  671. self.set(parentfield, self.get(parentfield, {"allocated_amount": ["not in", [0, None, ""]]}))
  672. frappe.db.sql(
  673. """delete from `tab%s` where parentfield=%s and parent = %s
  674. and allocated_amount = 0"""
  675. % (childtype, "%s", "%s"),
  676. (parentfield, self.name),
  677. )
  678. @frappe.whitelist()
  679. def apply_shipping_rule(self):
  680. if self.shipping_rule:
  681. shipping_rule = frappe.get_doc("Shipping Rule", self.shipping_rule)
  682. shipping_rule.apply(self)
  683. self.calculate_taxes_and_totals()
  684. def get_shipping_address(self):
  685. """Returns Address object from shipping address fields if present"""
  686. # shipping address fields can be `shipping_address_name` or `shipping_address`
  687. # try getting value from both
  688. for fieldname in ("shipping_address_name", "shipping_address"):
  689. shipping_field = self.meta.get_field(fieldname)
  690. if shipping_field and shipping_field.fieldtype == "Link":
  691. if self.get(fieldname):
  692. return frappe.get_doc("Address", self.get(fieldname))
  693. return {}
  694. @frappe.whitelist()
  695. def set_advances(self):
  696. """Returns list of advances against Account, Party, Reference"""
  697. res = self.get_advance_entries(
  698. include_unallocated=not cint(self.get("only_include_allocated_payments"))
  699. )
  700. self.set("advances", [])
  701. advance_allocated = 0
  702. for d in res:
  703. if self.get("party_account_currency") == self.company_currency:
  704. amount = self.get("base_rounded_total") or self.base_grand_total
  705. else:
  706. amount = self.get("rounded_total") or self.grand_total
  707. allocated_amount = min(amount - advance_allocated, d.amount)
  708. advance_allocated += flt(allocated_amount)
  709. advance_row = {
  710. "doctype": self.doctype + " Advance",
  711. "reference_type": d.reference_type,
  712. "reference_name": d.reference_name,
  713. "reference_row": d.reference_row,
  714. "remarks": d.remarks,
  715. "advance_amount": flt(d.amount),
  716. "allocated_amount": allocated_amount,
  717. "ref_exchange_rate": flt(d.exchange_rate), # exchange_rate of advance entry
  718. }
  719. self.append("advances", advance_row)
  720. def get_advance_entries(self, include_unallocated=True):
  721. if self.doctype == "Sales Invoice":
  722. party_account = self.debit_to
  723. party_type = "Customer"
  724. party = self.customer
  725. amount_field = "credit_in_account_currency"
  726. order_field = "sales_order"
  727. order_doctype = "Sales Order"
  728. else:
  729. party_account = self.credit_to
  730. party_type = "Supplier"
  731. party = self.supplier
  732. amount_field = "debit_in_account_currency"
  733. order_field = "purchase_order"
  734. order_doctype = "Purchase Order"
  735. order_list = list(set(d.get(order_field) for d in self.get("items") if d.get(order_field)))
  736. journal_entries = get_advance_journal_entries(
  737. party_type, party, party_account, amount_field, order_doctype, order_list, include_unallocated
  738. )
  739. payment_entries = get_advance_payment_entries(
  740. party_type, party, party_account, order_doctype, order_list, include_unallocated
  741. )
  742. res = journal_entries + payment_entries
  743. return res
  744. def is_inclusive_tax(self):
  745. is_inclusive = cint(
  746. frappe.db.get_single_value("Accounts Settings", "show_inclusive_tax_in_print")
  747. )
  748. if is_inclusive:
  749. is_inclusive = 0
  750. if self.get("taxes", filters={"included_in_print_rate": 1}):
  751. is_inclusive = 1
  752. return is_inclusive
  753. def validate_advance_entries(self):
  754. order_field = "sales_order" if self.doctype == "Sales Invoice" else "purchase_order"
  755. order_list = list(set(d.get(order_field) for d in self.get("items") if d.get(order_field)))
  756. if not order_list:
  757. return
  758. advance_entries = self.get_advance_entries(include_unallocated=False)
  759. if advance_entries:
  760. advance_entries_against_si = [d.reference_name for d in self.get("advances")]
  761. for d in advance_entries:
  762. if not advance_entries_against_si or d.reference_name not in advance_entries_against_si:
  763. frappe.msgprint(
  764. _(
  765. "Payment Entry {0} is linked against Order {1}, check if it should be pulled as advance in this invoice."
  766. ).format(d.reference_name, d.against_order)
  767. )
  768. def set_advance_gain_or_loss(self):
  769. if self.get("conversion_rate") == 1 or not self.get("advances"):
  770. return
  771. is_purchase_invoice = self.doctype == "Purchase Invoice"
  772. party_account = self.credit_to if is_purchase_invoice else self.debit_to
  773. if get_account_currency(party_account) != self.currency:
  774. return
  775. for d in self.get("advances"):
  776. advance_exchange_rate = d.ref_exchange_rate
  777. if d.allocated_amount and self.conversion_rate != advance_exchange_rate:
  778. base_allocated_amount_in_ref_rate = advance_exchange_rate * d.allocated_amount
  779. base_allocated_amount_in_inv_rate = self.conversion_rate * d.allocated_amount
  780. difference = base_allocated_amount_in_ref_rate - base_allocated_amount_in_inv_rate
  781. d.exchange_gain_loss = difference
  782. def make_exchange_gain_loss_gl_entries(self, gl_entries):
  783. if self.get("doctype") in ["Purchase Invoice", "Sales Invoice"]:
  784. for d in self.get("advances"):
  785. if d.exchange_gain_loss:
  786. is_purchase_invoice = self.get("doctype") == "Purchase Invoice"
  787. party = self.supplier if is_purchase_invoice else self.customer
  788. party_account = self.credit_to if is_purchase_invoice else self.debit_to
  789. party_type = "Supplier" if is_purchase_invoice else "Customer"
  790. gain_loss_account = frappe.get_cached_value(
  791. "Company", self.company, "exchange_gain_loss_account"
  792. )
  793. if not gain_loss_account:
  794. frappe.throw(
  795. _("Please set default Exchange Gain/Loss Account in Company {}").format(self.get("company"))
  796. )
  797. account_currency = get_account_currency(gain_loss_account)
  798. if account_currency != self.company_currency:
  799. frappe.throw(
  800. _("Currency for {0} must be {1}").format(gain_loss_account, self.company_currency)
  801. )
  802. # for purchase
  803. dr_or_cr = "debit" if d.exchange_gain_loss > 0 else "credit"
  804. if not is_purchase_invoice:
  805. # just reverse for sales?
  806. dr_or_cr = "debit" if dr_or_cr == "credit" else "credit"
  807. gl_entries.append(
  808. self.get_gl_dict(
  809. {
  810. "account": gain_loss_account,
  811. "account_currency": account_currency,
  812. "against": party,
  813. dr_or_cr + "_in_account_currency": abs(d.exchange_gain_loss),
  814. dr_or_cr: abs(d.exchange_gain_loss),
  815. "cost_center": self.cost_center or erpnext.get_default_cost_center(self.company),
  816. "project": self.project,
  817. },
  818. item=d,
  819. )
  820. )
  821. dr_or_cr = "debit" if dr_or_cr == "credit" else "credit"
  822. gl_entries.append(
  823. self.get_gl_dict(
  824. {
  825. "account": party_account,
  826. "party_type": party_type,
  827. "party": party,
  828. "against": gain_loss_account,
  829. dr_or_cr + "_in_account_currency": flt(abs(d.exchange_gain_loss) / self.conversion_rate),
  830. dr_or_cr: abs(d.exchange_gain_loss),
  831. "cost_center": self.cost_center,
  832. "project": self.project,
  833. },
  834. self.party_account_currency,
  835. item=self,
  836. )
  837. )
  838. def update_against_document_in_jv(self):
  839. """
  840. Links invoice and advance voucher:
  841. 1. cancel advance voucher
  842. 2. split into multiple rows if partially adjusted, assign against voucher
  843. 3. submit advance voucher
  844. """
  845. if self.doctype == "Sales Invoice":
  846. party_type = "Customer"
  847. party = self.customer
  848. party_account = self.debit_to
  849. dr_or_cr = "credit_in_account_currency"
  850. else:
  851. party_type = "Supplier"
  852. party = self.supplier
  853. party_account = self.credit_to
  854. dr_or_cr = "debit_in_account_currency"
  855. lst = []
  856. for d in self.get("advances"):
  857. if flt(d.allocated_amount) > 0:
  858. args = frappe._dict(
  859. {
  860. "voucher_type": d.reference_type,
  861. "voucher_no": d.reference_name,
  862. "voucher_detail_no": d.reference_row,
  863. "against_voucher_type": self.doctype,
  864. "against_voucher": self.name,
  865. "account": party_account,
  866. "party_type": party_type,
  867. "party": party,
  868. "is_advance": "Yes",
  869. "dr_or_cr": dr_or_cr,
  870. "unadjusted_amount": flt(d.advance_amount),
  871. "allocated_amount": flt(d.allocated_amount),
  872. "precision": d.precision("advance_amount"),
  873. "exchange_rate": (
  874. self.conversion_rate if self.party_account_currency != self.company_currency else 1
  875. ),
  876. "grand_total": (
  877. self.base_grand_total
  878. if self.party_account_currency == self.company_currency
  879. else self.grand_total
  880. ),
  881. "outstanding_amount": self.outstanding_amount,
  882. "difference_account": frappe.get_cached_value(
  883. "Company", self.company, "exchange_gain_loss_account"
  884. ),
  885. "exchange_gain_loss": flt(d.get("exchange_gain_loss")),
  886. }
  887. )
  888. lst.append(args)
  889. if lst:
  890. from erpnext.accounts.utils import reconcile_against_document
  891. reconcile_against_document(lst)
  892. def on_cancel(self):
  893. from erpnext.accounts.utils import unlink_ref_doc_from_payment_entries
  894. if self.doctype in ["Sales Invoice", "Purchase Invoice"]:
  895. if frappe.db.get_single_value("Accounts Settings", "unlink_payment_on_cancellation_of_invoice"):
  896. unlink_ref_doc_from_payment_entries(self)
  897. elif self.doctype in ["Sales Order", "Purchase Order"]:
  898. if frappe.db.get_single_value(
  899. "Accounts Settings", "unlink_advance_payment_on_cancelation_of_order"
  900. ):
  901. unlink_ref_doc_from_payment_entries(self)
  902. if self.doctype == "Sales Order":
  903. self.unlink_ref_doc_from_po()
  904. def unlink_ref_doc_from_po(self):
  905. so_items = []
  906. for item in self.items:
  907. so_items.append(item.name)
  908. linked_po = list(
  909. set(
  910. frappe.get_all(
  911. "Purchase Order Item",
  912. filters={
  913. "sales_order": self.name,
  914. "sales_order_item": ["in", so_items],
  915. "docstatus": ["<", 2],
  916. },
  917. pluck="parent",
  918. )
  919. )
  920. )
  921. if linked_po:
  922. frappe.db.set_value(
  923. "Purchase Order Item",
  924. {"sales_order": self.name, "sales_order_item": ["in", so_items], "docstatus": ["<", 2]},
  925. {"sales_order": None, "sales_order_item": None},
  926. )
  927. frappe.msgprint(_("Purchase Orders {0} are un-linked").format("\n".join(linked_po)))
  928. def get_tax_map(self):
  929. tax_map = {}
  930. for tax in self.get("taxes"):
  931. tax_map.setdefault(tax.account_head, 0.0)
  932. tax_map[tax.account_head] += tax.tax_amount
  933. return tax_map
  934. def get_amount_and_base_amount(self, item, enable_discount_accounting):
  935. amount = item.net_amount
  936. base_amount = item.base_net_amount
  937. if (
  938. enable_discount_accounting
  939. and self.get("discount_amount")
  940. and self.get("additional_discount_account")
  941. ):
  942. amount = item.amount
  943. base_amount = item.base_amount
  944. return amount, base_amount
  945. def get_tax_amounts(self, tax, enable_discount_accounting):
  946. amount = tax.tax_amount_after_discount_amount
  947. base_amount = tax.base_tax_amount_after_discount_amount
  948. if (
  949. enable_discount_accounting
  950. and self.get("discount_amount")
  951. and self.get("additional_discount_account")
  952. and self.get("apply_discount_on") == "Grand Total"
  953. ):
  954. amount = tax.tax_amount
  955. base_amount = tax.base_tax_amount
  956. return amount, base_amount
  957. def make_discount_gl_entries(self, gl_entries):
  958. if self.doctype == "Purchase Invoice":
  959. enable_discount_accounting = cint(
  960. frappe.db.get_single_value("Buying Settings", "enable_discount_accounting")
  961. )
  962. elif self.doctype == "Sales Invoice":
  963. enable_discount_accounting = cint(
  964. frappe.db.get_single_value("Selling Settings", "enable_discount_accounting")
  965. )
  966. if self.doctype == "Purchase Invoice":
  967. dr_or_cr = "credit"
  968. rev_dr_cr = "debit"
  969. supplier_or_customer = self.supplier
  970. else:
  971. dr_or_cr = "debit"
  972. rev_dr_cr = "credit"
  973. supplier_or_customer = self.customer
  974. if enable_discount_accounting:
  975. for item in self.get("items"):
  976. if item.get("discount_amount") and item.get("discount_account"):
  977. discount_amount = item.discount_amount * item.qty
  978. if self.doctype == "Purchase Invoice":
  979. income_or_expense_account = (
  980. item.expense_account
  981. if (not item.enable_deferred_expense or self.is_return)
  982. else item.deferred_expense_account
  983. )
  984. else:
  985. income_or_expense_account = (
  986. item.income_account
  987. if (not item.enable_deferred_revenue or self.is_return)
  988. else item.deferred_revenue_account
  989. )
  990. account_currency = get_account_currency(item.discount_account)
  991. gl_entries.append(
  992. self.get_gl_dict(
  993. {
  994. "account": item.discount_account,
  995. "against": supplier_or_customer,
  996. dr_or_cr: flt(
  997. discount_amount * self.get("conversion_rate"), item.precision("discount_amount")
  998. ),
  999. dr_or_cr + "_in_account_currency": flt(discount_amount, item.precision("discount_amount")),
  1000. "cost_center": item.cost_center,
  1001. "project": item.project,
  1002. },
  1003. account_currency,
  1004. item=item,
  1005. )
  1006. )
  1007. account_currency = get_account_currency(income_or_expense_account)
  1008. gl_entries.append(
  1009. self.get_gl_dict(
  1010. {
  1011. "account": income_or_expense_account,
  1012. "against": supplier_or_customer,
  1013. rev_dr_cr: flt(
  1014. discount_amount * self.get("conversion_rate"), item.precision("discount_amount")
  1015. ),
  1016. rev_dr_cr
  1017. + "_in_account_currency": flt(discount_amount, item.precision("discount_amount")),
  1018. "cost_center": item.cost_center,
  1019. "project": item.project or self.project,
  1020. },
  1021. account_currency,
  1022. item=item,
  1023. )
  1024. )
  1025. if (
  1026. (enable_discount_accounting or self.get("is_cash_or_non_trade_discount"))
  1027. and self.get("additional_discount_account")
  1028. and self.get("discount_amount")
  1029. ):
  1030. gl_entries.append(
  1031. self.get_gl_dict(
  1032. {
  1033. "account": self.additional_discount_account,
  1034. "against": supplier_or_customer,
  1035. dr_or_cr: self.discount_amount,
  1036. "cost_center": self.cost_center,
  1037. },
  1038. item=self,
  1039. )
  1040. )
  1041. def validate_multiple_billing(self, ref_dt, item_ref_dn, based_on):
  1042. from erpnext.controllers.status_updater import get_allowance_for
  1043. item_allowance = {}
  1044. global_qty_allowance, global_amount_allowance = None, None
  1045. role_allowed_to_over_bill = frappe.db.get_single_value(
  1046. "Accounts Settings", "role_allowed_to_over_bill"
  1047. )
  1048. user_roles = frappe.get_roles()
  1049. total_overbilled_amt = 0.0
  1050. reference_names = [d.get(item_ref_dn) for d in self.get("items") if d.get(item_ref_dn)]
  1051. reference_details = self.get_billing_reference_details(
  1052. reference_names, ref_dt + " Item", based_on
  1053. )
  1054. for item in self.get("items"):
  1055. if not item.get(item_ref_dn):
  1056. continue
  1057. ref_amt = flt(reference_details.get(item.get(item_ref_dn)), self.precision(based_on, item))
  1058. if not ref_amt:
  1059. frappe.msgprint(
  1060. _("System will not check over billing since amount for Item {0} in {1} is zero").format(
  1061. item.item_code, ref_dt
  1062. ),
  1063. title=_("Warning"),
  1064. indicator="orange",
  1065. )
  1066. continue
  1067. already_billed = self.get_billed_amount_for_item(item, item_ref_dn, based_on)
  1068. total_billed_amt = flt(
  1069. flt(already_billed) + flt(item.get(based_on)), self.precision(based_on, item)
  1070. )
  1071. allowance, item_allowance, global_qty_allowance, global_amount_allowance = get_allowance_for(
  1072. item.item_code, item_allowance, global_qty_allowance, global_amount_allowance, "amount"
  1073. )
  1074. max_allowed_amt = flt(ref_amt * (100 + allowance) / 100)
  1075. if total_billed_amt < 0 and max_allowed_amt < 0:
  1076. # while making debit note against purchase return entry(purchase receipt) getting overbill error
  1077. total_billed_amt = abs(total_billed_amt)
  1078. max_allowed_amt = abs(max_allowed_amt)
  1079. overbill_amt = total_billed_amt - max_allowed_amt
  1080. total_overbilled_amt += overbill_amt
  1081. if overbill_amt > 0.01 and role_allowed_to_over_bill not in user_roles:
  1082. if self.doctype != "Purchase Invoice":
  1083. self.throw_overbill_exception(item, max_allowed_amt)
  1084. elif not cint(
  1085. frappe.db.get_single_value(
  1086. "Buying Settings", "bill_for_rejected_quantity_in_purchase_invoice"
  1087. )
  1088. ):
  1089. self.throw_overbill_exception(item, max_allowed_amt)
  1090. if role_allowed_to_over_bill in user_roles and total_overbilled_amt > 0.1:
  1091. frappe.msgprint(
  1092. _("Overbilling of {} ignored because you have {} role.").format(
  1093. total_overbilled_amt, role_allowed_to_over_bill
  1094. ),
  1095. indicator="orange",
  1096. alert=True,
  1097. )
  1098. def get_billing_reference_details(self, reference_names, reference_doctype, based_on):
  1099. return frappe._dict(
  1100. frappe.get_all(
  1101. reference_doctype,
  1102. filters={"name": ("in", reference_names)},
  1103. fields=["name", based_on],
  1104. as_list=1,
  1105. )
  1106. )
  1107. def get_billed_amount_for_item(self, item, item_ref_dn, based_on):
  1108. """
  1109. Returns Sum of Amount of
  1110. Sales/Purchase Invoice Items
  1111. that are linked to `item_ref_dn` (`dn_detail` / `pr_detail`)
  1112. that are submitted OR not submitted but are under current invoice
  1113. """
  1114. from frappe.query_builder import Criterion
  1115. from frappe.query_builder.functions import Sum
  1116. item_doctype = frappe.qb.DocType(item.doctype)
  1117. based_on_field = frappe.qb.Field(based_on)
  1118. join_field = frappe.qb.Field(item_ref_dn)
  1119. result = (
  1120. frappe.qb.from_(item_doctype)
  1121. .select(Sum(based_on_field))
  1122. .where(join_field == item.get(item_ref_dn))
  1123. .where(
  1124. Criterion.any(
  1125. [ # select all items from other invoices OR current invoices
  1126. Criterion.all(
  1127. [ # for selecting items from other invoices
  1128. item_doctype.docstatus == 1,
  1129. item_doctype.parent != self.name,
  1130. ]
  1131. ),
  1132. Criterion.all(
  1133. [ # for selecting items from current invoice, that are linked to same reference
  1134. item_doctype.docstatus == 0,
  1135. item_doctype.parent == self.name,
  1136. item_doctype.name != item.name,
  1137. ]
  1138. ),
  1139. ]
  1140. )
  1141. )
  1142. ).run()
  1143. return result[0][0] if result else 0
  1144. def throw_overbill_exception(self, item, max_allowed_amt):
  1145. frappe.throw(
  1146. _(
  1147. "Cannot overbill for Item {0} in row {1} more than {2}. To allow over-billing, please set allowance in Accounts Settings"
  1148. ).format(item.item_code, item.idx, max_allowed_amt)
  1149. )
  1150. def get_company_default(self, fieldname, ignore_validation=False):
  1151. from erpnext.accounts.utils import get_company_default
  1152. return get_company_default(self.company, fieldname, ignore_validation=ignore_validation)
  1153. def get_stock_items(self):
  1154. stock_items = []
  1155. item_codes = list(set(item.item_code for item in self.get("items")))
  1156. if item_codes:
  1157. stock_items = frappe.db.get_values(
  1158. "Item", {"name": ["in", item_codes], "is_stock_item": 1}, pluck="name", cache=True
  1159. )
  1160. return stock_items
  1161. def set_total_advance_paid(self):
  1162. ple = frappe.qb.DocType("Payment Ledger Entry")
  1163. party = self.customer if self.doctype == "Sales Order" else self.supplier
  1164. advance = (
  1165. frappe.qb.from_(ple)
  1166. .select(ple.account_currency, Abs(Sum(ple.amount_in_account_currency)).as_("amount"))
  1167. .where(
  1168. (ple.against_voucher_type == self.doctype)
  1169. & (ple.against_voucher_no == self.name)
  1170. & (ple.party == party)
  1171. & (ple.docstatus == 1)
  1172. & (ple.company == self.company)
  1173. )
  1174. .run(as_dict=True)
  1175. )
  1176. if advance:
  1177. advance = advance[0]
  1178. advance_paid = flt(advance.amount, self.precision("advance_paid"))
  1179. formatted_advance_paid = fmt_money(
  1180. advance_paid, precision=self.precision("advance_paid"), currency=advance.account_currency
  1181. )
  1182. frappe.db.set_value(self.doctype, self.name, "party_account_currency", advance.account_currency)
  1183. if advance.account_currency == self.currency:
  1184. order_total = self.get("rounded_total") or self.grand_total
  1185. precision = "rounded_total" if self.get("rounded_total") else "grand_total"
  1186. else:
  1187. order_total = self.get("base_rounded_total") or self.base_grand_total
  1188. precision = "base_rounded_total" if self.get("base_rounded_total") else "base_grand_total"
  1189. formatted_order_total = fmt_money(
  1190. order_total, precision=self.precision(precision), currency=advance.account_currency
  1191. )
  1192. if self.currency == self.company_currency and advance_paid > order_total:
  1193. frappe.throw(
  1194. _(
  1195. "Total advance ({0}) against Order {1} cannot be greater than the Grand Total ({2})"
  1196. ).format(formatted_advance_paid, self.name, formatted_order_total)
  1197. )
  1198. frappe.db.set_value(self.doctype, self.name, "advance_paid", advance_paid)
  1199. @property
  1200. def company_abbr(self):
  1201. if not hasattr(self, "_abbr"):
  1202. self._abbr = frappe.get_cached_value("Company", self.company, "abbr")
  1203. return self._abbr
  1204. def raise_missing_debit_credit_account_error(self, party_type, party):
  1205. """Raise an error if debit to/credit to account does not exist."""
  1206. db_or_cr = (
  1207. frappe.bold("Debit To") if self.doctype == "Sales Invoice" else frappe.bold("Credit To")
  1208. )
  1209. rec_or_pay = "Receivable" if self.doctype == "Sales Invoice" else "Payable"
  1210. link_to_party = frappe.utils.get_link_to_form(party_type, party)
  1211. link_to_company = frappe.utils.get_link_to_form("Company", self.company)
  1212. message = _("{0} Account not found against Customer {1}.").format(
  1213. db_or_cr, frappe.bold(party) or ""
  1214. )
  1215. message += "<br>" + _("Please set one of the following:") + "<br>"
  1216. message += (
  1217. "<br><ul><li>"
  1218. + _("'Account' in the Accounting section of Customer {0}").format(link_to_party)
  1219. + "</li>"
  1220. )
  1221. message += (
  1222. "<li>"
  1223. + _("'Default {0} Account' in Company {1}").format(rec_or_pay, link_to_company)
  1224. + "</li></ul>"
  1225. )
  1226. frappe.throw(message, title=_("Account Missing"), exc=AccountMissingError)
  1227. def validate_party(self):
  1228. party_type, party = self.get_party()
  1229. validate_party_frozen_disabled(party_type, party)
  1230. def get_party(self):
  1231. party_type = None
  1232. if self.doctype in ("Opportunity", "Quotation", "Sales Order", "Delivery Note", "Sales Invoice"):
  1233. party_type = "Customer"
  1234. elif self.doctype in (
  1235. "Supplier Quotation",
  1236. "Purchase Order",
  1237. "Purchase Receipt",
  1238. "Purchase Invoice",
  1239. ):
  1240. party_type = "Supplier"
  1241. elif self.meta.get_field("customer"):
  1242. party_type = "Customer"
  1243. elif self.meta.get_field("supplier"):
  1244. party_type = "Supplier"
  1245. party = self.get(party_type.lower()) if party_type else None
  1246. return party_type, party
  1247. def validate_currency(self):
  1248. if self.get("currency"):
  1249. party_type, party = self.get_party()
  1250. if party_type and party:
  1251. party_account_currency = get_party_account_currency(party_type, party, self.company)
  1252. if (
  1253. party_account_currency
  1254. and party_account_currency != self.company_currency
  1255. and self.currency != party_account_currency
  1256. ):
  1257. frappe.throw(
  1258. _("Accounting Entry for {0}: {1} can only be made in currency: {2}").format(
  1259. party_type, party, party_account_currency
  1260. ),
  1261. InvalidCurrency,
  1262. )
  1263. # Note: not validating with gle account because we don't have the account
  1264. # at quotation / sales order level and we shouldn't stop someone
  1265. # from creating a sales invoice if sales order is already created
  1266. def validate_party_account_currency(self):
  1267. if self.doctype not in ("Sales Invoice", "Purchase Invoice"):
  1268. return
  1269. if self.is_opening == "Yes":
  1270. return
  1271. party_type, party = self.get_party()
  1272. party_gle_currency = get_party_gle_currency(party_type, party, self.company)
  1273. party_account = (
  1274. self.get("debit_to") if self.doctype == "Sales Invoice" else self.get("credit_to")
  1275. )
  1276. party_account_currency = get_account_currency(party_account)
  1277. allow_multi_currency_invoices_against_single_party_account = frappe.db.get_singles_value(
  1278. "Accounts Settings", "allow_multi_currency_invoices_against_single_party_account"
  1279. )
  1280. if (
  1281. not party_gle_currency
  1282. and (party_account_currency != self.currency)
  1283. and not allow_multi_currency_invoices_against_single_party_account
  1284. ):
  1285. frappe.throw(
  1286. _("Party Account {0} currency ({1}) and document currency ({2}) should be same").format(
  1287. frappe.bold(party_account), party_account_currency, self.currency
  1288. )
  1289. )
  1290. def delink_advance_entries(self, linked_doc_name):
  1291. total_allocated_amount = 0
  1292. for adv in self.advances:
  1293. consider_for_total_advance = True
  1294. if adv.reference_name == linked_doc_name:
  1295. frappe.db.sql(
  1296. """delete from `tab{0} Advance`
  1297. where name = %s""".format(
  1298. self.doctype
  1299. ),
  1300. adv.name,
  1301. )
  1302. consider_for_total_advance = False
  1303. if consider_for_total_advance:
  1304. total_allocated_amount += flt(adv.allocated_amount, adv.precision("allocated_amount"))
  1305. frappe.db.set_value(
  1306. self.doctype, self.name, "total_advance", total_allocated_amount, update_modified=False
  1307. )
  1308. def group_similar_items(self):
  1309. group_item_qty = {}
  1310. group_item_amount = {}
  1311. # to update serial number in print
  1312. count = 0
  1313. for item in self.items:
  1314. group_item_qty[item.item_code] = group_item_qty.get(item.item_code, 0) + item.qty
  1315. group_item_amount[item.item_code] = group_item_amount.get(item.item_code, 0) + item.amount
  1316. duplicate_list = []
  1317. for item in self.items:
  1318. if item.item_code in group_item_qty:
  1319. count += 1
  1320. item.qty = group_item_qty[item.item_code]
  1321. item.amount = group_item_amount[item.item_code]
  1322. if item.qty:
  1323. item.rate = flt(flt(item.amount) / flt(item.qty), item.precision("rate"))
  1324. else:
  1325. item.rate = 0
  1326. item.idx = count
  1327. del group_item_qty[item.item_code]
  1328. else:
  1329. duplicate_list.append(item)
  1330. for item in duplicate_list:
  1331. self.remove(item)
  1332. def set_payment_schedule(self):
  1333. if self.doctype == "Sales Invoice" and self.is_pos:
  1334. self.payment_terms_template = ""
  1335. return
  1336. party_account_currency = self.get("party_account_currency")
  1337. if not party_account_currency:
  1338. party_type, party = self.get_party()
  1339. if party_type and party:
  1340. party_account_currency = get_party_account_currency(party_type, party, self.company)
  1341. posting_date = self.get("bill_date") or self.get("posting_date") or self.get("transaction_date")
  1342. date = self.get("due_date")
  1343. due_date = date or posting_date
  1344. base_grand_total = self.get("base_rounded_total") or self.base_grand_total
  1345. grand_total = self.get("rounded_total") or self.grand_total
  1346. automatically_fetch_payment_terms = 0
  1347. if self.doctype in ("Sales Invoice", "Purchase Invoice"):
  1348. base_grand_total = base_grand_total - flt(self.base_write_off_amount)
  1349. grand_total = grand_total - flt(self.write_off_amount)
  1350. po_or_so, doctype, fieldname = self.get_order_details()
  1351. automatically_fetch_payment_terms = cint(
  1352. frappe.db.get_single_value("Accounts Settings", "automatically_fetch_payment_terms")
  1353. )
  1354. if self.get("total_advance"):
  1355. if party_account_currency == self.company_currency:
  1356. base_grand_total -= self.get("total_advance")
  1357. grand_total = flt(
  1358. base_grand_total / self.get("conversion_rate"), self.precision("grand_total")
  1359. )
  1360. else:
  1361. grand_total -= self.get("total_advance")
  1362. base_grand_total = flt(
  1363. grand_total * self.get("conversion_rate"), self.precision("base_grand_total")
  1364. )
  1365. if not self.get("payment_schedule"):
  1366. if (
  1367. self.doctype in ["Sales Invoice", "Purchase Invoice"]
  1368. and automatically_fetch_payment_terms
  1369. and self.linked_order_has_payment_terms(po_or_so, fieldname, doctype)
  1370. ):
  1371. self.fetch_payment_terms_from_order(po_or_so, doctype)
  1372. if self.get("payment_terms_template"):
  1373. self.ignore_default_payment_terms_template = 1
  1374. elif self.get("payment_terms_template"):
  1375. data = get_payment_terms(
  1376. self.payment_terms_template, posting_date, grand_total, base_grand_total
  1377. )
  1378. for item in data:
  1379. self.append("payment_schedule", item)
  1380. elif self.doctype not in ["Purchase Receipt"]:
  1381. data = dict(
  1382. due_date=due_date,
  1383. invoice_portion=100,
  1384. payment_amount=grand_total,
  1385. base_payment_amount=base_grand_total,
  1386. )
  1387. self.append("payment_schedule", data)
  1388. if not (
  1389. automatically_fetch_payment_terms
  1390. and self.linked_order_has_payment_terms(po_or_so, fieldname, doctype)
  1391. ):
  1392. for d in self.get("payment_schedule"):
  1393. if d.invoice_portion:
  1394. d.payment_amount = flt(
  1395. grand_total * flt(d.invoice_portion / 100), d.precision("payment_amount")
  1396. )
  1397. d.base_payment_amount = flt(
  1398. base_grand_total * flt(d.invoice_portion / 100), d.precision("base_payment_amount")
  1399. )
  1400. d.outstanding = d.payment_amount
  1401. elif not d.invoice_portion:
  1402. d.base_payment_amount = flt(
  1403. d.payment_amount * self.get("conversion_rate"), d.precision("base_payment_amount")
  1404. )
  1405. def get_order_details(self):
  1406. if self.doctype == "Sales Invoice":
  1407. po_or_so = self.get("items")[0].get("sales_order")
  1408. po_or_so_doctype = "Sales Order"
  1409. po_or_so_doctype_name = "sales_order"
  1410. else:
  1411. po_or_so = self.get("items")[0].get("purchase_order")
  1412. po_or_so_doctype = "Purchase Order"
  1413. po_or_so_doctype_name = "purchase_order"
  1414. return po_or_so, po_or_so_doctype, po_or_so_doctype_name
  1415. def linked_order_has_payment_terms(self, po_or_so, fieldname, doctype):
  1416. if po_or_so and self.all_items_have_same_po_or_so(po_or_so, fieldname):
  1417. if self.linked_order_has_payment_terms_template(po_or_so, doctype):
  1418. return True
  1419. elif self.linked_order_has_payment_schedule(po_or_so):
  1420. return True
  1421. return False
  1422. def all_items_have_same_po_or_so(self, po_or_so, fieldname):
  1423. for item in self.get("items"):
  1424. if item.get(fieldname) != po_or_so:
  1425. return False
  1426. return True
  1427. def linked_order_has_payment_terms_template(self, po_or_so, doctype):
  1428. return frappe.get_value(doctype, po_or_so, "payment_terms_template")
  1429. def linked_order_has_payment_schedule(self, po_or_so):
  1430. return frappe.get_all("Payment Schedule", filters={"parent": po_or_so})
  1431. def fetch_payment_terms_from_order(self, po_or_so, po_or_so_doctype):
  1432. """
  1433. Fetch Payment Terms from Purchase/Sales Order on creating a new Purchase/Sales Invoice.
  1434. """
  1435. po_or_so = frappe.get_cached_doc(po_or_so_doctype, po_or_so)
  1436. self.payment_schedule = []
  1437. self.payment_terms_template = po_or_so.payment_terms_template
  1438. for schedule in po_or_so.payment_schedule:
  1439. payment_schedule = {
  1440. "payment_term": schedule.payment_term,
  1441. "due_date": schedule.due_date,
  1442. "invoice_portion": schedule.invoice_portion,
  1443. "mode_of_payment": schedule.mode_of_payment,
  1444. "description": schedule.description,
  1445. "payment_amount": schedule.payment_amount,
  1446. "base_payment_amount": schedule.base_payment_amount,
  1447. "outstanding": schedule.outstanding,
  1448. "paid_amount": schedule.paid_amount,
  1449. }
  1450. if schedule.discount_type == "Percentage":
  1451. payment_schedule["discount_type"] = schedule.discount_type
  1452. payment_schedule["discount"] = schedule.discount
  1453. if not schedule.invoice_portion:
  1454. payment_schedule["payment_amount"] = schedule.payment_amount
  1455. self.append("payment_schedule", payment_schedule)
  1456. def set_due_date(self):
  1457. due_dates = [d.due_date for d in self.get("payment_schedule") if d.due_date]
  1458. if due_dates:
  1459. self.due_date = max(due_dates)
  1460. def validate_payment_schedule_dates(self):
  1461. dates = []
  1462. li = []
  1463. if self.doctype == "Sales Invoice" and self.is_pos:
  1464. return
  1465. for d in self.get("payment_schedule"):
  1466. if self.doctype == "Sales Order" and getdate(d.due_date) < getdate(self.transaction_date):
  1467. frappe.throw(
  1468. _("Row {0}: Due Date in the Payment Terms table cannot be before Posting Date").format(d.idx)
  1469. )
  1470. elif d.due_date in dates:
  1471. li.append(_("{0} in row {1}").format(d.due_date, d.idx))
  1472. dates.append(d.due_date)
  1473. if li:
  1474. duplicates = "<br>" + "<br>".join(li)
  1475. frappe.throw(
  1476. _("Rows with duplicate due dates in other rows were found: {0}").format(duplicates)
  1477. )
  1478. def validate_payment_schedule_amount(self):
  1479. if self.doctype == "Sales Invoice" and self.is_pos:
  1480. return
  1481. party_account_currency = self.get("party_account_currency")
  1482. if not party_account_currency:
  1483. party_type, party = self.get_party()
  1484. if party_type and party:
  1485. party_account_currency = get_party_account_currency(party_type, party, self.company)
  1486. if self.get("payment_schedule"):
  1487. total = 0
  1488. base_total = 0
  1489. for d in self.get("payment_schedule"):
  1490. total += flt(d.payment_amount, d.precision("payment_amount"))
  1491. base_total += flt(d.base_payment_amount, d.precision("base_payment_amount"))
  1492. base_grand_total = self.get("base_rounded_total") or self.base_grand_total
  1493. grand_total = self.get("rounded_total") or self.grand_total
  1494. if self.doctype in ("Sales Invoice", "Purchase Invoice"):
  1495. base_grand_total = base_grand_total - flt(self.base_write_off_amount)
  1496. grand_total = grand_total - flt(self.write_off_amount)
  1497. if self.get("total_advance"):
  1498. if party_account_currency == self.company_currency:
  1499. base_grand_total -= self.get("total_advance")
  1500. grand_total = flt(
  1501. base_grand_total / self.get("conversion_rate"), self.precision("grand_total")
  1502. )
  1503. else:
  1504. grand_total -= self.get("total_advance")
  1505. base_grand_total = flt(
  1506. grand_total * self.get("conversion_rate"), self.precision("base_grand_total")
  1507. )
  1508. if (
  1509. flt(total, self.precision("grand_total")) - flt(grand_total, self.precision("grand_total"))
  1510. > 0.1
  1511. or flt(base_total, self.precision("base_grand_total"))
  1512. - flt(base_grand_total, self.precision("base_grand_total"))
  1513. > 0.1
  1514. ):
  1515. frappe.throw(
  1516. _("Total Payment Amount in Payment Schedule must be equal to Grand / Rounded Total")
  1517. )
  1518. def is_rounded_total_disabled(self):
  1519. if self.meta.get_field("disable_rounded_total"):
  1520. return self.disable_rounded_total
  1521. else:
  1522. return frappe.db.get_single_value("Global Defaults", "disable_rounded_total")
  1523. def set_inter_company_account(self):
  1524. """
  1525. Set intercompany account for inter warehouse transactions
  1526. This account will be used in case billing company and internal customer's
  1527. representation company is same
  1528. """
  1529. if self.is_internal_transfer() and not self.unrealized_profit_loss_account:
  1530. unrealized_profit_loss_account = frappe.get_cached_value(
  1531. "Company", self.company, "unrealized_profit_loss_account"
  1532. )
  1533. if not unrealized_profit_loss_account:
  1534. msg = _(
  1535. "Please select Unrealized Profit / Loss account or add default Unrealized Profit / Loss account account for company {0}"
  1536. ).format(frappe.bold(self.company))
  1537. frappe.throw(msg)
  1538. self.unrealized_profit_loss_account = unrealized_profit_loss_account
  1539. def is_internal_transfer(self):
  1540. """
  1541. It will an internal transfer if its an internal customer and representation
  1542. company is same as billing company
  1543. """
  1544. if self.doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
  1545. internal_party_field = "is_internal_customer"
  1546. elif self.doctype in ("Purchase Invoice", "Purchase Receipt", "Purchase Order"):
  1547. internal_party_field = "is_internal_supplier"
  1548. else:
  1549. return False
  1550. if self.get(internal_party_field) and (self.represents_company == self.company):
  1551. return True
  1552. return False
  1553. def process_common_party_accounting(self):
  1554. is_invoice = self.doctype in ["Sales Invoice", "Purchase Invoice"]
  1555. if not is_invoice:
  1556. return
  1557. if frappe.db.get_single_value("Accounts Settings", "enable_common_party_accounting"):
  1558. party_link = self.get_common_party_link()
  1559. if party_link and self.outstanding_amount:
  1560. self.create_advance_and_reconcile(party_link)
  1561. def get_common_party_link(self):
  1562. party_type, party = self.get_party()
  1563. return frappe.db.get_value(
  1564. doctype="Party Link",
  1565. filters={"secondary_role": party_type, "secondary_party": party},
  1566. fieldname=["primary_role", "primary_party"],
  1567. as_dict=True,
  1568. )
  1569. def create_advance_and_reconcile(self, party_link):
  1570. secondary_party_type, secondary_party = self.get_party()
  1571. primary_party_type, primary_party = party_link.primary_role, party_link.primary_party
  1572. primary_account = get_party_account(primary_party_type, primary_party, self.company)
  1573. secondary_account = get_party_account(secondary_party_type, secondary_party, self.company)
  1574. jv = frappe.new_doc("Journal Entry")
  1575. jv.voucher_type = "Journal Entry"
  1576. jv.posting_date = self.posting_date
  1577. jv.company = self.company
  1578. jv.remark = "Adjustment for {} {}".format(self.doctype, self.name)
  1579. reconcilation_entry = frappe._dict()
  1580. advance_entry = frappe._dict()
  1581. reconcilation_entry.account = secondary_account
  1582. reconcilation_entry.party_type = secondary_party_type
  1583. reconcilation_entry.party = secondary_party
  1584. reconcilation_entry.reference_type = self.doctype
  1585. reconcilation_entry.reference_name = self.name
  1586. reconcilation_entry.cost_center = self.cost_center or erpnext.get_default_cost_center(
  1587. self.company
  1588. )
  1589. advance_entry.account = primary_account
  1590. advance_entry.party_type = primary_party_type
  1591. advance_entry.party = primary_party
  1592. advance_entry.cost_center = self.cost_center or erpnext.get_default_cost_center(self.company)
  1593. advance_entry.is_advance = "Yes"
  1594. if self.doctype == "Sales Invoice":
  1595. reconcilation_entry.credit_in_account_currency = self.outstanding_amount
  1596. advance_entry.debit_in_account_currency = self.outstanding_amount
  1597. else:
  1598. advance_entry.credit_in_account_currency = self.outstanding_amount
  1599. reconcilation_entry.debit_in_account_currency = self.outstanding_amount
  1600. jv.append("accounts", reconcilation_entry)
  1601. jv.append("accounts", advance_entry)
  1602. jv.save()
  1603. jv.submit()
  1604. def check_conversion_rate(self):
  1605. default_currency = erpnext.get_company_currency(self.company)
  1606. if not default_currency:
  1607. throw(_("Please enter default currency in Company Master"))
  1608. if (
  1609. (self.currency == default_currency and flt(self.conversion_rate) != 1.00)
  1610. or not self.conversion_rate
  1611. or (self.currency != default_currency and flt(self.conversion_rate) == 1.00)
  1612. ):
  1613. throw(_("Conversion rate cannot be 0 or 1"))
  1614. def check_finance_books(self, item, asset):
  1615. if (
  1616. len(asset.finance_books) > 1
  1617. and not item.get("finance_book")
  1618. and not self.get("finance_book")
  1619. and asset.finance_books[0].finance_book
  1620. ):
  1621. frappe.throw(
  1622. _("Select finance book for the item {0} at row {1}").format(item.item_code, item.idx)
  1623. )
  1624. @frappe.whitelist()
  1625. def get_tax_rate(account_head):
  1626. return frappe.get_cached_value(
  1627. "Account", account_head, ["tax_rate", "account_name"], as_dict=True
  1628. )
  1629. @frappe.whitelist()
  1630. def get_default_taxes_and_charges(master_doctype, tax_template=None, company=None):
  1631. if not company:
  1632. return {}
  1633. if tax_template and company:
  1634. tax_template_company = frappe.get_cached_value(master_doctype, tax_template, "company")
  1635. if tax_template_company == company:
  1636. return
  1637. default_tax = frappe.db.get_value(master_doctype, {"is_default": 1, "company": company})
  1638. return {
  1639. "taxes_and_charges": default_tax,
  1640. "taxes": get_taxes_and_charges(master_doctype, default_tax),
  1641. }
  1642. @frappe.whitelist()
  1643. def get_taxes_and_charges(master_doctype, master_name):
  1644. if not master_name:
  1645. return
  1646. from frappe.model import child_table_fields, default_fields
  1647. tax_master = frappe.get_doc(master_doctype, master_name)
  1648. taxes_and_charges = []
  1649. for i, tax in enumerate(tax_master.get("taxes")):
  1650. tax = tax.as_dict()
  1651. for fieldname in default_fields + child_table_fields:
  1652. if fieldname in tax:
  1653. del tax[fieldname]
  1654. taxes_and_charges.append(tax)
  1655. return taxes_and_charges
  1656. def validate_conversion_rate(currency, conversion_rate, conversion_rate_label, company):
  1657. """common validation for currency and price list currency"""
  1658. company_currency = frappe.get_cached_value("Company", company, "default_currency")
  1659. if not conversion_rate:
  1660. throw(
  1661. _("{0} is mandatory. Maybe Currency Exchange record is not created for {1} to {2}.").format(
  1662. conversion_rate_label, currency, company_currency
  1663. )
  1664. )
  1665. def validate_taxes_and_charges(tax):
  1666. if tax.charge_type in ["Actual", "On Net Total", "On Paid Amount"] and tax.row_id:
  1667. frappe.throw(
  1668. _("Can refer row only if the charge type is 'On Previous Row Amount' or 'Previous Row Total'")
  1669. )
  1670. elif tax.charge_type in ["On Previous Row Amount", "On Previous Row Total"]:
  1671. if cint(tax.idx) == 1:
  1672. frappe.throw(
  1673. _(
  1674. "Cannot select charge type as 'On Previous Row Amount' or 'On Previous Row Total' for first row"
  1675. )
  1676. )
  1677. elif not tax.row_id:
  1678. frappe.throw(
  1679. _("Please specify a valid Row ID for row {0} in table {1}").format(tax.idx, _(tax.doctype))
  1680. )
  1681. elif tax.row_id and cint(tax.row_id) >= cint(tax.idx):
  1682. frappe.throw(
  1683. _("Cannot refer row number greater than or equal to current row number for this Charge type")
  1684. )
  1685. if tax.charge_type == "Actual":
  1686. tax.rate = None
  1687. def validate_account_head(idx, account, company, context=""):
  1688. account_company = frappe.get_cached_value("Account", account, "company")
  1689. if account_company != company:
  1690. frappe.throw(
  1691. _("Row {0}: {3} Account {1} does not belong to Company {2}").format(
  1692. idx, frappe.bold(account), frappe.bold(company), context
  1693. ),
  1694. title=_("Invalid Account"),
  1695. )
  1696. def validate_cost_center(tax, doc):
  1697. if not tax.cost_center:
  1698. return
  1699. company = frappe.get_cached_value("Cost Center", tax.cost_center, "company")
  1700. if company != doc.company:
  1701. frappe.throw(
  1702. _("Row {0}: Cost Center {1} does not belong to Company {2}").format(
  1703. tax.idx, frappe.bold(tax.cost_center), frappe.bold(doc.company)
  1704. ),
  1705. title=_("Invalid Cost Center"),
  1706. )
  1707. def validate_inclusive_tax(tax, doc):
  1708. def _on_previous_row_error(row_range):
  1709. throw(
  1710. _("To include tax in row {0} in Item rate, taxes in rows {1} must also be included").format(
  1711. tax.idx, row_range
  1712. )
  1713. )
  1714. if cint(getattr(tax, "included_in_print_rate", None)):
  1715. if tax.charge_type == "Actual":
  1716. # inclusive tax cannot be of type Actual
  1717. throw(
  1718. _("Charge of type 'Actual' in row {0} cannot be included in Item Rate or Paid Amount").format(
  1719. tax.idx
  1720. )
  1721. )
  1722. elif tax.charge_type == "On Previous Row Amount" and not cint(
  1723. doc.get("taxes")[cint(tax.row_id) - 1].included_in_print_rate
  1724. ):
  1725. # referred row should also be inclusive
  1726. _on_previous_row_error(tax.row_id)
  1727. elif tax.charge_type == "On Previous Row Total" and not all(
  1728. [cint(t.included_in_print_rate) for t in doc.get("taxes")[: cint(tax.row_id) - 1]]
  1729. ):
  1730. # all rows about the referred tax should be inclusive
  1731. _on_previous_row_error("1 - %d" % (tax.row_id,))
  1732. elif tax.get("category") == "Valuation":
  1733. frappe.throw(_("Valuation type charges can not be marked as Inclusive"))
  1734. def set_balance_in_account_currency(
  1735. gl_dict, account_currency=None, conversion_rate=None, company_currency=None
  1736. ):
  1737. if (not conversion_rate) and (account_currency != company_currency):
  1738. frappe.throw(
  1739. _("Account: {0} with currency: {1} can not be selected").format(
  1740. gl_dict.account, account_currency
  1741. )
  1742. )
  1743. gl_dict["account_currency"] = (
  1744. company_currency if account_currency == company_currency else account_currency
  1745. )
  1746. # set debit/credit in account currency if not provided
  1747. if flt(gl_dict.debit) and not flt(gl_dict.debit_in_account_currency):
  1748. gl_dict.debit_in_account_currency = (
  1749. gl_dict.debit
  1750. if account_currency == company_currency
  1751. else flt(gl_dict.debit / conversion_rate, 2)
  1752. )
  1753. if flt(gl_dict.credit) and not flt(gl_dict.credit_in_account_currency):
  1754. gl_dict.credit_in_account_currency = (
  1755. gl_dict.credit
  1756. if account_currency == company_currency
  1757. else flt(gl_dict.credit / conversion_rate, 2)
  1758. )
  1759. def get_advance_journal_entries(
  1760. party_type,
  1761. party,
  1762. party_account,
  1763. amount_field,
  1764. order_doctype,
  1765. order_list,
  1766. include_unallocated=True,
  1767. ):
  1768. dr_or_cr = (
  1769. "credit_in_account_currency" if party_type == "Customer" else "debit_in_account_currency"
  1770. )
  1771. conditions = []
  1772. if include_unallocated:
  1773. conditions.append("ifnull(t2.reference_name, '')=''")
  1774. if order_list:
  1775. order_condition = ", ".join(["%s"] * len(order_list))
  1776. conditions.append(
  1777. " (t2.reference_type = '{0}' and ifnull(t2.reference_name, '') in ({1}))".format(
  1778. order_doctype, order_condition
  1779. )
  1780. )
  1781. reference_condition = " and (" + " or ".join(conditions) + ")" if conditions else ""
  1782. # nosemgrep
  1783. journal_entries = frappe.db.sql(
  1784. """
  1785. select
  1786. 'Journal Entry' as reference_type, t1.name as reference_name,
  1787. t1.remark as remarks, t2.{0} as amount, t2.name as reference_row,
  1788. t2.reference_name as against_order, t2.exchange_rate
  1789. from
  1790. `tabJournal Entry` t1, `tabJournal Entry Account` t2
  1791. where
  1792. t1.name = t2.parent and t2.account = %s
  1793. and t2.party_type = %s and t2.party = %s
  1794. and t2.is_advance = 'Yes' and t1.docstatus = 1
  1795. and {1} > 0 {2}
  1796. order by t1.posting_date""".format(
  1797. amount_field, dr_or_cr, reference_condition
  1798. ),
  1799. [party_account, party_type, party] + order_list,
  1800. as_dict=1,
  1801. )
  1802. return list(journal_entries)
  1803. def get_advance_payment_entries(
  1804. party_type,
  1805. party,
  1806. party_account,
  1807. order_doctype,
  1808. order_list=None,
  1809. include_unallocated=True,
  1810. against_all_orders=False,
  1811. limit=None,
  1812. condition=None,
  1813. ):
  1814. party_account_field = "paid_from" if party_type == "Customer" else "paid_to"
  1815. currency_field = (
  1816. "paid_from_account_currency" if party_type == "Customer" else "paid_to_account_currency"
  1817. )
  1818. payment_type = "Receive" if party_type == "Customer" else "Pay"
  1819. exchange_rate_field = (
  1820. "source_exchange_rate" if payment_type == "Receive" else "target_exchange_rate"
  1821. )
  1822. payment_entries_against_order, unallocated_payment_entries = [], []
  1823. limit_cond = "limit %s" % limit if limit else ""
  1824. if order_list or against_all_orders:
  1825. if order_list:
  1826. reference_condition = " and t2.reference_name in ({0})".format(
  1827. ", ".join(["%s"] * len(order_list))
  1828. )
  1829. else:
  1830. reference_condition = ""
  1831. order_list = []
  1832. payment_entries_against_order = frappe.db.sql(
  1833. """
  1834. select
  1835. 'Payment Entry' as reference_type, t1.name as reference_name,
  1836. t1.remarks, t2.allocated_amount as amount, t2.name as reference_row,
  1837. t2.reference_name as against_order, t1.posting_date,
  1838. t1.{0} as currency, t1.{4} as exchange_rate
  1839. from `tabPayment Entry` t1, `tabPayment Entry Reference` t2
  1840. where
  1841. t1.name = t2.parent and t1.{1} = %s and t1.payment_type = %s
  1842. and t1.party_type = %s and t1.party = %s and t1.docstatus = 1
  1843. and t2.reference_doctype = %s {2}
  1844. order by t1.posting_date {3}
  1845. """.format(
  1846. currency_field, party_account_field, reference_condition, limit_cond, exchange_rate_field
  1847. ),
  1848. [party_account, payment_type, party_type, party, order_doctype] + order_list,
  1849. as_dict=1,
  1850. )
  1851. if include_unallocated:
  1852. unallocated_payment_entries = frappe.db.sql(
  1853. """
  1854. select 'Payment Entry' as reference_type, name as reference_name, posting_date,
  1855. remarks, unallocated_amount as amount, {2} as exchange_rate, {3} as currency
  1856. from `tabPayment Entry`
  1857. where
  1858. {0} = %s and party_type = %s and party = %s and payment_type = %s
  1859. and docstatus = 1 and unallocated_amount > 0 {condition}
  1860. order by posting_date {1}
  1861. """.format(
  1862. party_account_field, limit_cond, exchange_rate_field, currency_field, condition=condition or ""
  1863. ),
  1864. (party_account, party_type, party, payment_type),
  1865. as_dict=1,
  1866. )
  1867. return list(payment_entries_against_order) + list(unallocated_payment_entries)
  1868. def update_invoice_status():
  1869. """Updates status as Overdue for applicable invoices. Runs daily."""
  1870. today = getdate()
  1871. payment_schedule = frappe.qb.DocType("Payment Schedule")
  1872. for doctype in ("Sales Invoice", "Purchase Invoice"):
  1873. invoice = frappe.qb.DocType(doctype)
  1874. consider_base_amount = invoice.party_account_currency != invoice.currency
  1875. payment_amount = (
  1876. frappe.qb.terms.Case()
  1877. .when(consider_base_amount, payment_schedule.base_payment_amount)
  1878. .else_(payment_schedule.payment_amount)
  1879. )
  1880. payable_amount = (
  1881. frappe.qb.from_(payment_schedule)
  1882. .select(Sum(payment_amount))
  1883. .where((payment_schedule.parent == invoice.name) & (payment_schedule.due_date < today))
  1884. )
  1885. total = (
  1886. frappe.qb.terms.Case()
  1887. .when(invoice.disable_rounded_total, invoice.grand_total)
  1888. .else_(invoice.rounded_total)
  1889. )
  1890. base_total = (
  1891. frappe.qb.terms.Case()
  1892. .when(invoice.disable_rounded_total, invoice.base_grand_total)
  1893. .else_(invoice.base_rounded_total)
  1894. )
  1895. total_amount = frappe.qb.terms.Case().when(consider_base_amount, base_total).else_(total)
  1896. is_overdue = total_amount - invoice.outstanding_amount < payable_amount
  1897. conditions = (
  1898. (invoice.docstatus == 1)
  1899. & (invoice.outstanding_amount > 0)
  1900. & (invoice.status.like("Unpaid%") | invoice.status.like("Partly Paid%"))
  1901. & (
  1902. ((invoice.is_pos & invoice.due_date < today) | is_overdue)
  1903. if doctype == "Sales Invoice"
  1904. else is_overdue
  1905. )
  1906. )
  1907. status = (
  1908. frappe.qb.terms.Case()
  1909. .when(invoice.status.like("%Discounted"), "Overdue and Discounted")
  1910. .else_("Overdue")
  1911. )
  1912. frappe.qb.update(invoice).set("status", status).where(conditions).run()
  1913. @frappe.whitelist()
  1914. def get_payment_terms(
  1915. terms_template, posting_date=None, grand_total=None, base_grand_total=None, bill_date=None
  1916. ):
  1917. if not terms_template:
  1918. return
  1919. terms_doc = frappe.get_doc("Payment Terms Template", terms_template)
  1920. schedule = []
  1921. for d in terms_doc.get("terms"):
  1922. term_details = get_payment_term_details(
  1923. d, posting_date, grand_total, base_grand_total, bill_date
  1924. )
  1925. schedule.append(term_details)
  1926. return schedule
  1927. @frappe.whitelist()
  1928. def get_payment_term_details(
  1929. term, posting_date=None, grand_total=None, base_grand_total=None, bill_date=None
  1930. ):
  1931. term_details = frappe._dict()
  1932. if isinstance(term, str):
  1933. term = frappe.get_doc("Payment Term", term)
  1934. else:
  1935. term_details.payment_term = term.payment_term
  1936. term_details.description = term.description
  1937. term_details.invoice_portion = term.invoice_portion
  1938. term_details.payment_amount = flt(term.invoice_portion) * flt(grand_total) / 100
  1939. term_details.base_payment_amount = flt(term.invoice_portion) * flt(base_grand_total) / 100
  1940. term_details.discount_type = term.discount_type
  1941. term_details.discount = term.discount
  1942. term_details.outstanding = term_details.payment_amount
  1943. term_details.mode_of_payment = term.mode_of_payment
  1944. if bill_date:
  1945. term_details.due_date = get_due_date(term, bill_date)
  1946. term_details.discount_date = get_discount_date(term, bill_date)
  1947. elif posting_date:
  1948. term_details.due_date = get_due_date(term, posting_date)
  1949. term_details.discount_date = get_discount_date(term, posting_date)
  1950. if getdate(term_details.due_date) < getdate(posting_date):
  1951. term_details.due_date = posting_date
  1952. return term_details
  1953. def get_due_date(term, posting_date=None, bill_date=None):
  1954. due_date = None
  1955. date = bill_date or posting_date
  1956. if term.due_date_based_on == "Day(s) after invoice date":
  1957. due_date = add_days(date, term.credit_days)
  1958. elif term.due_date_based_on == "Day(s) after the end of the invoice month":
  1959. due_date = add_days(get_last_day(date), term.credit_days)
  1960. elif term.due_date_based_on == "Month(s) after the end of the invoice month":
  1961. due_date = get_last_day(add_months(date, term.credit_months))
  1962. return due_date
  1963. def get_discount_date(term, posting_date=None, bill_date=None):
  1964. discount_validity = None
  1965. date = bill_date or posting_date
  1966. if term.discount_validity_based_on == "Day(s) after invoice date":
  1967. discount_validity = add_days(date, term.discount_validity)
  1968. elif term.discount_validity_based_on == "Day(s) after the end of the invoice month":
  1969. discount_validity = add_days(get_last_day(date), term.discount_validity)
  1970. elif term.discount_validity_based_on == "Month(s) after the end of the invoice month":
  1971. discount_validity = get_last_day(add_months(date, term.discount_validity))
  1972. return discount_validity
  1973. def get_supplier_block_status(party_name):
  1974. """
  1975. Returns a dict containing the values of `on_hold`, `release_date` and `hold_type` of
  1976. a `Supplier`
  1977. """
  1978. supplier = frappe.get_doc("Supplier", party_name)
  1979. info = {
  1980. "on_hold": supplier.on_hold,
  1981. "release_date": supplier.release_date,
  1982. "hold_type": supplier.hold_type,
  1983. }
  1984. return info
  1985. def set_child_tax_template_and_map(item, child_item, parent_doc):
  1986. args = {
  1987. "item_code": item.item_code,
  1988. "posting_date": parent_doc.transaction_date,
  1989. "tax_category": parent_doc.get("tax_category"),
  1990. "company": parent_doc.get("company"),
  1991. }
  1992. child_item.item_tax_template = _get_item_tax_template(args, item.taxes)
  1993. if child_item.get("item_tax_template"):
  1994. child_item.item_tax_rate = get_item_tax_map(
  1995. parent_doc.get("company"), child_item.item_tax_template, as_json=True
  1996. )
  1997. def add_taxes_from_tax_template(child_item, parent_doc, db_insert=True):
  1998. add_taxes_from_item_tax_template = frappe.db.get_single_value(
  1999. "Accounts Settings", "add_taxes_from_item_tax_template"
  2000. )
  2001. if child_item.get("item_tax_rate") and add_taxes_from_item_tax_template:
  2002. tax_map = json.loads(child_item.get("item_tax_rate"))
  2003. for tax_type in tax_map:
  2004. tax_rate = flt(tax_map[tax_type])
  2005. taxes = parent_doc.get("taxes") or []
  2006. # add new row for tax head only if missing
  2007. found = any(tax.account_head == tax_type for tax in taxes)
  2008. if not found:
  2009. tax_row = parent_doc.append("taxes", {})
  2010. tax_row.update(
  2011. {
  2012. "description": str(tax_type).split(" - ")[0],
  2013. "charge_type": "On Net Total",
  2014. "account_head": tax_type,
  2015. "rate": tax_rate,
  2016. }
  2017. )
  2018. if parent_doc.doctype == "Purchase Order":
  2019. tax_row.update({"category": "Total", "add_deduct_tax": "Add"})
  2020. if db_insert:
  2021. tax_row.db_insert()
  2022. def set_order_defaults(
  2023. parent_doctype, parent_doctype_name, child_doctype, child_docname, trans_item
  2024. ):
  2025. """
  2026. Returns a Sales/Purchase Order Item child item containing the default values
  2027. """
  2028. p_doc = frappe.get_doc(parent_doctype, parent_doctype_name)
  2029. child_item = frappe.new_doc(child_doctype, p_doc, child_docname)
  2030. item = frappe.get_doc("Item", trans_item.get("item_code"))
  2031. for field in ("item_code", "item_name", "description", "item_group"):
  2032. child_item.update({field: item.get(field)})
  2033. date_fieldname = "delivery_date" if child_doctype == "Sales Order Item" else "schedule_date"
  2034. child_item.update({date_fieldname: trans_item.get(date_fieldname) or p_doc.get(date_fieldname)})
  2035. child_item.stock_uom = item.stock_uom
  2036. child_item.uom = trans_item.get("uom") or item.stock_uom
  2037. child_item.warehouse = get_item_warehouse(item, p_doc, overwrite_warehouse=True)
  2038. conversion_factor = flt(
  2039. get_conversion_factor(item.item_code, child_item.uom).get("conversion_factor")
  2040. )
  2041. child_item.conversion_factor = flt(trans_item.get("conversion_factor")) or conversion_factor
  2042. if child_doctype == "Purchase Order Item":
  2043. # Initialized value will update in parent validation
  2044. child_item.base_rate = 1
  2045. child_item.base_amount = 1
  2046. if child_doctype == "Sales Order Item":
  2047. child_item.warehouse = get_item_warehouse(item, p_doc, overwrite_warehouse=True)
  2048. if not child_item.warehouse:
  2049. frappe.throw(
  2050. _("Cannot find {} for item {}. Please set the same in Item Master or Stock Settings.").format(
  2051. frappe.bold("default warehouse"), frappe.bold(item.item_code)
  2052. )
  2053. )
  2054. set_child_tax_template_and_map(item, child_item, p_doc)
  2055. add_taxes_from_tax_template(child_item, p_doc)
  2056. return child_item
  2057. def validate_child_on_delete(row, parent):
  2058. """Check if partially transacted item (row) is being deleted."""
  2059. if parent.doctype == "Sales Order":
  2060. if flt(row.delivered_qty):
  2061. frappe.throw(
  2062. _("Row #{0}: Cannot delete item {1} which has already been delivered").format(
  2063. row.idx, row.item_code
  2064. )
  2065. )
  2066. if flt(row.work_order_qty):
  2067. frappe.throw(
  2068. _("Row #{0}: Cannot delete item {1} which has work order assigned to it.").format(
  2069. row.idx, row.item_code
  2070. )
  2071. )
  2072. if flt(row.ordered_qty):
  2073. frappe.throw(
  2074. _("Row #{0}: Cannot delete item {1} which is assigned to customer's purchase order.").format(
  2075. row.idx, row.item_code
  2076. )
  2077. )
  2078. if parent.doctype == "Purchase Order" and flt(row.received_qty):
  2079. frappe.throw(
  2080. _("Row #{0}: Cannot delete item {1} which has already been received").format(
  2081. row.idx, row.item_code
  2082. )
  2083. )
  2084. if flt(row.billed_amt):
  2085. frappe.throw(
  2086. _("Row #{0}: Cannot delete item {1} which has already been billed.").format(
  2087. row.idx, row.item_code
  2088. )
  2089. )
  2090. def update_bin_on_delete(row, doctype):
  2091. """Update bin for deleted item (row)."""
  2092. from erpnext.stock.stock_balance import (
  2093. get_indented_qty,
  2094. get_ordered_qty,
  2095. get_reserved_qty,
  2096. update_bin_qty,
  2097. )
  2098. qty_dict = {}
  2099. if doctype == "Sales Order":
  2100. qty_dict["reserved_qty"] = get_reserved_qty(row.item_code, row.warehouse)
  2101. else:
  2102. if row.material_request_item:
  2103. qty_dict["indented_qty"] = get_indented_qty(row.item_code, row.warehouse)
  2104. qty_dict["ordered_qty"] = get_ordered_qty(row.item_code, row.warehouse)
  2105. if row.warehouse:
  2106. update_bin_qty(row.item_code, row.warehouse, qty_dict)
  2107. def validate_and_delete_children(parent, data) -> bool:
  2108. deleted_children = []
  2109. updated_item_names = [d.get("docname") for d in data]
  2110. for item in parent.items:
  2111. if item.name not in updated_item_names:
  2112. deleted_children.append(item)
  2113. for d in deleted_children:
  2114. validate_child_on_delete(d, parent)
  2115. d.cancel()
  2116. d.delete()
  2117. # need to update ordered qty in Material Request first
  2118. # bin uses Material Request Items to recalculate & update
  2119. parent.update_prevdoc_status()
  2120. for d in deleted_children:
  2121. update_bin_on_delete(d, parent.doctype)
  2122. return bool(deleted_children)
  2123. @frappe.whitelist()
  2124. def update_child_qty_rate(parent_doctype, trans_items, parent_doctype_name, child_docname="items"):
  2125. def check_doc_permissions(doc, perm_type="create"):
  2126. try:
  2127. doc.check_permission(perm_type)
  2128. except frappe.PermissionError:
  2129. actions = {"create": "add", "write": "update"}
  2130. frappe.throw(
  2131. _("You do not have permissions to {} items in a {}.").format(
  2132. actions[perm_type], parent_doctype
  2133. ),
  2134. title=_("Insufficient Permissions"),
  2135. )
  2136. def validate_workflow_conditions(doc):
  2137. workflow = get_workflow_name(doc.doctype)
  2138. if not workflow:
  2139. return
  2140. workflow_doc = frappe.get_doc("Workflow", workflow)
  2141. current_state = doc.get(workflow_doc.workflow_state_field)
  2142. roles = frappe.get_roles()
  2143. transitions = []
  2144. for transition in workflow_doc.transitions:
  2145. if transition.next_state == current_state and transition.allowed in roles:
  2146. if not is_transition_condition_satisfied(transition, doc):
  2147. continue
  2148. transitions.append(transition.as_dict())
  2149. if not transitions:
  2150. frappe.throw(
  2151. _("You are not allowed to update as per the conditions set in {} Workflow.").format(
  2152. get_link_to_form("Workflow", workflow)
  2153. ),
  2154. title=_("Insufficient Permissions"),
  2155. )
  2156. def get_new_child_item(item_row):
  2157. child_doctype = "Sales Order Item" if parent_doctype == "Sales Order" else "Purchase Order Item"
  2158. return set_order_defaults(
  2159. parent_doctype, parent_doctype_name, child_doctype, child_docname, item_row
  2160. )
  2161. def validate_quantity(child_item, new_data):
  2162. if not flt(new_data.get("qty")):
  2163. frappe.throw(
  2164. _("Row # {0}: Quantity for Item {1} cannot be zero").format(
  2165. new_data.get("idx"), frappe.bold(new_data.get("item_code"))
  2166. ),
  2167. title=_("Invalid Qty"),
  2168. )
  2169. if parent_doctype == "Sales Order" and flt(new_data.get("qty")) < flt(child_item.delivered_qty):
  2170. frappe.throw(_("Cannot set quantity less than delivered quantity"))
  2171. if parent_doctype == "Purchase Order" and flt(new_data.get("qty")) < flt(
  2172. child_item.received_qty
  2173. ):
  2174. frappe.throw(_("Cannot set quantity less than received quantity"))
  2175. def should_update_supplied_items(doc) -> bool:
  2176. """Subcontracted PO can allow following changes *after submit*:
  2177. 1. Change rate of subcontracting - regardless of other changes.
  2178. 2. Change qty and/or add new items and/or remove items
  2179. Exception: Transfer/Consumption is already made, qty change not allowed.
  2180. """
  2181. supplied_items_processed = any(
  2182. item.supplied_qty or item.consumed_qty or item.returned_qty for item in doc.supplied_items
  2183. )
  2184. update_supplied_items = (
  2185. any_qty_changed or items_added_or_removed or any_conversion_factor_changed
  2186. )
  2187. if update_supplied_items and supplied_items_processed:
  2188. frappe.throw(_("Item qty can not be updated as raw materials are already processed."))
  2189. return update_supplied_items
  2190. data = json.loads(trans_items)
  2191. any_qty_changed = False # updated to true if any item's qty changes
  2192. items_added_or_removed = False # updated to true if any new item is added or removed
  2193. any_conversion_factor_changed = False
  2194. sales_doctypes = ["Sales Order", "Sales Invoice", "Delivery Note", "Quotation"]
  2195. parent = frappe.get_doc(parent_doctype, parent_doctype_name)
  2196. check_doc_permissions(parent, "write")
  2197. _removed_items = validate_and_delete_children(parent, data)
  2198. items_added_or_removed |= _removed_items
  2199. for d in data:
  2200. new_child_flag = False
  2201. if not d.get("item_code"):
  2202. # ignore empty rows
  2203. continue
  2204. if not d.get("docname"):
  2205. new_child_flag = True
  2206. items_added_or_removed = True
  2207. check_doc_permissions(parent, "create")
  2208. child_item = get_new_child_item(d)
  2209. else:
  2210. check_doc_permissions(parent, "write")
  2211. child_item = frappe.get_doc(parent_doctype + " Item", d.get("docname"))
  2212. prev_rate, new_rate = flt(child_item.get("rate")), flt(d.get("rate"))
  2213. prev_qty, new_qty = flt(child_item.get("qty")), flt(d.get("qty"))
  2214. prev_con_fac, new_con_fac = flt(child_item.get("conversion_factor")), flt(
  2215. d.get("conversion_factor")
  2216. )
  2217. prev_uom, new_uom = child_item.get("uom"), d.get("uom")
  2218. if parent_doctype == "Sales Order":
  2219. prev_date, new_date = child_item.get("delivery_date"), d.get("delivery_date")
  2220. elif parent_doctype == "Purchase Order":
  2221. prev_date, new_date = child_item.get("schedule_date"), d.get("schedule_date")
  2222. rate_unchanged = prev_rate == new_rate
  2223. qty_unchanged = prev_qty == new_qty
  2224. uom_unchanged = prev_uom == new_uom
  2225. conversion_factor_unchanged = prev_con_fac == new_con_fac
  2226. any_conversion_factor_changed |= not conversion_factor_unchanged
  2227. date_unchanged = (
  2228. prev_date == getdate(new_date) if prev_date and new_date else False
  2229. ) # in case of delivery note etc
  2230. if (
  2231. rate_unchanged
  2232. and qty_unchanged
  2233. and conversion_factor_unchanged
  2234. and uom_unchanged
  2235. and date_unchanged
  2236. ):
  2237. continue
  2238. validate_quantity(child_item, d)
  2239. if flt(child_item.get("qty")) != flt(d.get("qty")):
  2240. any_qty_changed = True
  2241. child_item.qty = flt(d.get("qty"))
  2242. rate_precision = child_item.precision("rate") or 2
  2243. conv_fac_precision = child_item.precision("conversion_factor") or 2
  2244. qty_precision = child_item.precision("qty") or 2
  2245. if flt(child_item.billed_amt, rate_precision) > flt(
  2246. flt(d.get("rate"), rate_precision) * flt(d.get("qty"), qty_precision), rate_precision
  2247. ):
  2248. frappe.throw(
  2249. _("Row #{0}: Cannot set Rate if amount is greater than billed amount for Item {1}.").format(
  2250. child_item.idx, child_item.item_code
  2251. )
  2252. )
  2253. else:
  2254. child_item.rate = flt(d.get("rate"), rate_precision)
  2255. if d.get("conversion_factor"):
  2256. if child_item.stock_uom == child_item.uom:
  2257. child_item.conversion_factor = 1
  2258. else:
  2259. child_item.conversion_factor = flt(d.get("conversion_factor"), conv_fac_precision)
  2260. if d.get("uom"):
  2261. child_item.uom = d.get("uom")
  2262. conversion_factor = flt(
  2263. get_conversion_factor(child_item.item_code, child_item.uom).get("conversion_factor")
  2264. )
  2265. child_item.conversion_factor = (
  2266. flt(d.get("conversion_factor"), conv_fac_precision) or conversion_factor
  2267. )
  2268. if d.get("delivery_date") and parent_doctype == "Sales Order":
  2269. child_item.delivery_date = d.get("delivery_date")
  2270. if d.get("schedule_date") and parent_doctype == "Purchase Order":
  2271. child_item.schedule_date = d.get("schedule_date")
  2272. if flt(child_item.price_list_rate):
  2273. if flt(child_item.rate) > flt(child_item.price_list_rate):
  2274. # if rate is greater than price_list_rate, set margin
  2275. # or set discount
  2276. child_item.discount_percentage = 0
  2277. if parent_doctype in sales_doctypes:
  2278. child_item.margin_type = "Amount"
  2279. child_item.margin_rate_or_amount = flt(
  2280. child_item.rate - child_item.price_list_rate, child_item.precision("margin_rate_or_amount")
  2281. )
  2282. child_item.rate_with_margin = child_item.rate
  2283. else:
  2284. child_item.discount_percentage = flt(
  2285. (1 - flt(child_item.rate) / flt(child_item.price_list_rate)) * 100.0,
  2286. child_item.precision("discount_percentage"),
  2287. )
  2288. child_item.discount_amount = flt(child_item.price_list_rate) - flt(child_item.rate)
  2289. if parent_doctype in sales_doctypes:
  2290. child_item.margin_type = ""
  2291. child_item.margin_rate_or_amount = 0
  2292. child_item.rate_with_margin = 0
  2293. child_item.flags.ignore_validate_update_after_submit = True
  2294. if new_child_flag:
  2295. parent.load_from_db()
  2296. child_item.idx = len(parent.items) + 1
  2297. child_item.insert()
  2298. else:
  2299. child_item.save()
  2300. parent.reload()
  2301. parent.flags.ignore_validate_update_after_submit = True
  2302. parent.set_qty_as_per_stock_uom()
  2303. parent.calculate_taxes_and_totals()
  2304. parent.set_total_in_words()
  2305. if parent_doctype == "Sales Order":
  2306. make_packing_list(parent)
  2307. parent.set_gross_profit()
  2308. frappe.get_doc("Authorization Control").validate_approving_authority(
  2309. parent.doctype, parent.company, parent.base_grand_total
  2310. )
  2311. parent.set_payment_schedule()
  2312. if parent_doctype == "Purchase Order":
  2313. parent.validate_minimum_order_qty()
  2314. parent.validate_budget()
  2315. if parent.is_against_so():
  2316. parent.update_status_updater()
  2317. else:
  2318. parent.check_credit_limit()
  2319. # reset index of child table
  2320. for idx, row in enumerate(parent.get(child_docname), start=1):
  2321. row.idx = idx
  2322. parent.save()
  2323. if parent_doctype == "Purchase Order":
  2324. update_last_purchase_rate(parent, is_submit=1)
  2325. parent.update_prevdoc_status()
  2326. parent.update_requested_qty()
  2327. parent.update_ordered_qty()
  2328. parent.update_ordered_and_reserved_qty()
  2329. parent.update_receiving_percentage()
  2330. if parent.is_old_subcontracting_flow:
  2331. if should_update_supplied_items(parent):
  2332. parent.update_reserved_qty_for_subcontract()
  2333. parent.create_raw_materials_supplied()
  2334. parent.save()
  2335. else: # Sales Order
  2336. parent.validate_warehouse()
  2337. parent.update_reserved_qty()
  2338. parent.update_project()
  2339. parent.update_prevdoc_status("submit")
  2340. parent.update_delivery_status()
  2341. parent.reload()
  2342. validate_workflow_conditions(parent)
  2343. parent.update_blanket_order()
  2344. parent.update_billing_percentage()
  2345. parent.set_status()
  2346. @erpnext.allow_regional
  2347. def validate_regional(doc):
  2348. pass
  2349. @erpnext.allow_regional
  2350. def validate_einvoice_fields(doc):
  2351. pass