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.
 
 
 
 

618 lines
19 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # License: GNU General Public License v3. See license.txt
  3. import frappe
  4. from frappe import _
  5. from frappe.model.document import Document
  6. from frappe.utils import comma_or, flt, getdate, now, nowdate
  7. class OverAllowanceError(frappe.ValidationError):
  8. pass
  9. def validate_status(status, options):
  10. if status not in options:
  11. frappe.throw(_("Status must be one of {0}").format(comma_or(options)))
  12. status_map = {
  13. "Lead": [
  14. ["Lost Quotation", "has_lost_quotation"],
  15. ["Opportunity", "has_opportunity"],
  16. ["Quotation", "has_quotation"],
  17. ["Converted", "has_customer"],
  18. ],
  19. "Opportunity": [
  20. ["Lost", "eval:self.status=='Lost'"],
  21. ["Lost", "has_lost_quotation"],
  22. ["Quotation", "has_active_quotation"],
  23. ["Converted", "has_ordered_quotation"],
  24. ["Closed", "eval:self.status=='Closed'"],
  25. ],
  26. "Quotation": [
  27. ["Draft", None],
  28. ["Open", "eval:self.docstatus==1"],
  29. ["Lost", "eval:self.status=='Lost'"],
  30. ["Partially Ordered", "is_partially_ordered"],
  31. ["Ordered", "is_fully_ordered"],
  32. ["Cancelled", "eval:self.docstatus==2"],
  33. ],
  34. "Sales Order": [
  35. ["Draft", None],
  36. [
  37. "To Deliver and Bill",
  38. "eval:self.per_delivered < 100 and self.per_billed < 100 and self.docstatus == 1",
  39. ],
  40. [
  41. "To Bill",
  42. "eval:(self.per_delivered == 100 or self.skip_delivery_note) and self.per_billed < 100 and self.docstatus == 1",
  43. ],
  44. [
  45. "To Deliver",
  46. "eval:self.per_delivered < 100 and self.per_billed == 100 and self.docstatus == 1 and not self.skip_delivery_note",
  47. ],
  48. [
  49. "Completed",
  50. "eval:(self.per_delivered == 100 or self.skip_delivery_note) and self.per_billed == 100 and self.docstatus == 1",
  51. ],
  52. ["Cancelled", "eval:self.docstatus==2"],
  53. ["Closed", "eval:self.status=='Closed' and self.docstatus != 2"],
  54. ["On Hold", "eval:self.status=='On Hold'"],
  55. ],
  56. "Purchase Order": [
  57. ["Draft", None],
  58. [
  59. "To Receive and Bill",
  60. "eval:self.per_received < 100 and self.per_billed < 100 and self.docstatus == 1",
  61. ],
  62. ["To Bill", "eval:self.per_received >= 100 and self.per_billed < 100 and self.docstatus == 1"],
  63. [
  64. "To Receive",
  65. "eval:self.per_received < 100 and self.per_billed == 100 and self.docstatus == 1",
  66. ],
  67. [
  68. "Completed",
  69. "eval:self.per_received >= 100 and self.per_billed == 100 and self.docstatus == 1",
  70. ],
  71. ["Delivered", "eval:self.status=='Delivered'"],
  72. ["Cancelled", "eval:self.docstatus==2"],
  73. ["On Hold", "eval:self.status=='On Hold'"],
  74. ["Closed", "eval:self.status=='Closed' and self.docstatus != 2"],
  75. ],
  76. "Delivery Note": [
  77. ["Draft", None],
  78. ["To Bill", "eval:self.per_billed < 100 and self.docstatus == 1"],
  79. ["Return Issued", "eval:self.per_returned == 100 and self.docstatus == 1"],
  80. ["Completed", "eval:self.per_billed == 100 and self.docstatus == 1"],
  81. ["Cancelled", "eval:self.docstatus==2"],
  82. ["Closed", "eval:self.status=='Closed' and self.docstatus != 2"],
  83. ],
  84. "Purchase Receipt": [
  85. ["Draft", None],
  86. ["To Bill", "eval:self.per_billed < 100 and self.docstatus == 1"],
  87. ["Return Issued", "eval:self.per_returned == 100 and self.docstatus == 1"],
  88. ["Completed", "eval:self.per_billed == 100 and self.docstatus == 1"],
  89. ["Cancelled", "eval:self.docstatus==2"],
  90. ["Closed", "eval:self.status=='Closed' and self.docstatus != 2"],
  91. ],
  92. "Material Request": [
  93. ["Draft", None],
  94. ["Stopped", "eval:self.status == 'Stopped'"],
  95. ["Cancelled", "eval:self.docstatus == 2"],
  96. ["Pending", "eval:self.status != 'Stopped' and self.per_ordered == 0 and self.docstatus == 1"],
  97. [
  98. "Ordered",
  99. "eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Purchase'",
  100. ],
  101. [
  102. "Transferred",
  103. "eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Material Transfer'",
  104. ],
  105. [
  106. "Issued",
  107. "eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Material Issue'",
  108. ],
  109. [
  110. "Received",
  111. "eval:self.status != 'Stopped' and self.per_received == 100 and self.docstatus == 1 and self.material_request_type == 'Purchase'",
  112. ],
  113. [
  114. "Partially Received",
  115. "eval:self.status != 'Stopped' and self.per_received > 0 and self.per_received < 100 and self.docstatus == 1 and self.material_request_type == 'Purchase'",
  116. ],
  117. [
  118. "Partially Ordered",
  119. "eval:self.status != 'Stopped' and self.per_ordered < 100 and self.per_ordered > 0 and self.docstatus == 1",
  120. ],
  121. [
  122. "Manufactured",
  123. "eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Manufacture'",
  124. ],
  125. ],
  126. "Bank Transaction": [
  127. ["Unreconciled", "eval:self.docstatus == 1 and self.unallocated_amount>0"],
  128. ["Reconciled", "eval:self.docstatus == 1 and self.unallocated_amount<=0"],
  129. ["Cancelled", "eval:self.docstatus == 2"],
  130. ],
  131. "POS Opening Entry": [
  132. ["Draft", None],
  133. ["Open", "eval:self.docstatus == 1 and not self.pos_closing_entry"],
  134. ["Closed", "eval:self.docstatus == 1 and self.pos_closing_entry"],
  135. ["Cancelled", "eval:self.docstatus == 2"],
  136. ],
  137. "POS Closing Entry": [
  138. ["Draft", None],
  139. ["Submitted", "eval:self.docstatus == 1"],
  140. ["Queued", "eval:self.status == 'Queued'"],
  141. ["Failed", "eval:self.status == 'Failed'"],
  142. ["Cancelled", "eval:self.docstatus == 2"],
  143. ],
  144. "Transaction Deletion Record": [
  145. ["Draft", None],
  146. ["Completed", "eval:self.docstatus == 1"],
  147. ],
  148. }
  149. class StatusUpdater(Document):
  150. """
  151. Updates the status of the calling records
  152. Delivery Note: Update Delivered Qty, Update Percent and Validate over delivery
  153. Sales Invoice: Update Billed Amt, Update Percent and Validate over billing
  154. Installation Note: Update Installed Qty, Update Percent Qty and Validate over installation
  155. """
  156. def update_prevdoc_status(self):
  157. self.update_qty()
  158. self.validate_qty()
  159. def set_status(self, update=False, status=None, update_modified=True):
  160. if self.is_new():
  161. if self.get("amended_from"):
  162. self.status = "Draft"
  163. return
  164. if self.doctype in status_map:
  165. _status = self.status
  166. if status and update:
  167. self.db_set("status", status)
  168. sl = status_map[self.doctype][:]
  169. sl.reverse()
  170. for s in sl:
  171. if not s[1]:
  172. self.status = s[0]
  173. break
  174. elif s[1].startswith("eval:"):
  175. if frappe.safe_eval(
  176. s[1][5:],
  177. None,
  178. {
  179. "self": self.as_dict(),
  180. "getdate": getdate,
  181. "nowdate": nowdate,
  182. "get_value": frappe.db.get_value,
  183. },
  184. ):
  185. self.status = s[0]
  186. break
  187. elif getattr(self, s[1])():
  188. self.status = s[0]
  189. break
  190. if self.status != _status and self.status not in (
  191. "Cancelled",
  192. "Partially Ordered",
  193. "Ordered",
  194. "Issued",
  195. "Transferred",
  196. ):
  197. self.add_comment("Label", _(self.status))
  198. if update:
  199. self.db_set("status", self.status, update_modified=update_modified)
  200. def validate_qty(self):
  201. """Validates qty at row level"""
  202. self.item_allowance = {}
  203. self.global_qty_allowance = None
  204. self.global_amount_allowance = None
  205. for args in self.status_updater:
  206. if "target_ref_field" not in args:
  207. # if target_ref_field is not specified, the programmer does not want to validate qty / amount
  208. continue
  209. # get unique transactions to update
  210. for d in self.get_all_children():
  211. if hasattr(d, "qty") and d.qty < 0 and not self.get("is_return"):
  212. frappe.throw(_("For an item {0}, quantity must be positive number").format(d.item_code))
  213. if hasattr(d, "qty") and d.qty > 0 and self.get("is_return"):
  214. frappe.throw(_("For an item {0}, quantity must be negative number").format(d.item_code))
  215. if d.doctype == args["source_dt"] and d.get(args["join_field"]):
  216. args["name"] = d.get(args["join_field"])
  217. # get all qty where qty > target_field
  218. item = frappe.db.sql(
  219. """select item_code, `{target_ref_field}`,
  220. `{target_field}`, parenttype, parent from `tab{target_dt}`
  221. where `{target_ref_field}` < `{target_field}`
  222. and name=%s and docstatus=1""".format(
  223. **args
  224. ),
  225. args["name"],
  226. as_dict=1,
  227. )
  228. if item:
  229. item = item[0]
  230. item["idx"] = d.idx
  231. item["target_ref_field"] = args["target_ref_field"].replace("_", " ")
  232. # if not item[args['target_ref_field']]:
  233. # msgprint(_("Note: System will not check over-delivery and over-booking for Item {0} as quantity or amount is 0").format(item.item_code))
  234. if args.get("no_allowance"):
  235. item["reduce_by"] = item[args["target_field"]] - item[args["target_ref_field"]]
  236. if item["reduce_by"] > 0.01:
  237. self.limits_crossed_error(args, item, "qty")
  238. elif item[args["target_ref_field"]]:
  239. self.check_overflow_with_allowance(item, args)
  240. def check_overflow_with_allowance(self, item, args):
  241. """
  242. Checks if there is overflow condering a relaxation allowance
  243. """
  244. qty_or_amount = "qty" if "qty" in args["target_ref_field"] else "amount"
  245. # check if overflow is within allowance
  246. (
  247. allowance,
  248. self.item_allowance,
  249. self.global_qty_allowance,
  250. self.global_amount_allowance,
  251. ) = get_allowance_for(
  252. item["item_code"],
  253. self.item_allowance,
  254. self.global_qty_allowance,
  255. self.global_amount_allowance,
  256. qty_or_amount,
  257. )
  258. role_allowed_to_over_deliver_receive = frappe.db.get_single_value(
  259. "Stock Settings", "role_allowed_to_over_deliver_receive"
  260. )
  261. role_allowed_to_over_bill = frappe.db.get_single_value(
  262. "Accounts Settings", "role_allowed_to_over_bill"
  263. )
  264. role = (
  265. role_allowed_to_over_deliver_receive if qty_or_amount == "qty" else role_allowed_to_over_bill
  266. )
  267. overflow_percent = (
  268. (item[args["target_field"]] - item[args["target_ref_field"]]) / item[args["target_ref_field"]]
  269. ) * 100
  270. if overflow_percent - allowance > 0.01:
  271. item["max_allowed"] = flt(item[args["target_ref_field"]] * (100 + allowance) / 100)
  272. item["reduce_by"] = item[args["target_field"]] - item["max_allowed"]
  273. if role not in frappe.get_roles():
  274. self.limits_crossed_error(args, item, qty_or_amount)
  275. else:
  276. self.warn_about_bypassing_with_role(item, qty_or_amount, role)
  277. def limits_crossed_error(self, args, item, qty_or_amount):
  278. """Raise exception for limits crossed"""
  279. if (
  280. self.doctype in ["Sales Invoice", "Delivery Note"]
  281. and qty_or_amount == "amount"
  282. and self.is_internal_customer
  283. ):
  284. return
  285. elif (
  286. self.doctype in ["Purchase Invoice", "Purchase Receipt"]
  287. and qty_or_amount == "amount"
  288. and self.is_internal_supplier
  289. ):
  290. return
  291. if qty_or_amount == "qty":
  292. action_msg = _(
  293. 'To allow over receipt / delivery, update "Over Receipt/Delivery Allowance" in Stock Settings or the Item.'
  294. )
  295. else:
  296. action_msg = _(
  297. 'To allow over billing, update "Over Billing Allowance" in Accounts Settings or the Item.'
  298. )
  299. frappe.throw(
  300. _(
  301. "This document is over limit by {0} {1} for item {4}. Are you making another {3} against the same {2}?"
  302. ).format(
  303. frappe.bold(_(item["target_ref_field"].title())),
  304. frappe.bold(item["reduce_by"]),
  305. frappe.bold(_(args.get("target_dt"))),
  306. frappe.bold(_(self.doctype)),
  307. frappe.bold(item.get("item_code")),
  308. )
  309. + "<br><br>"
  310. + action_msg,
  311. OverAllowanceError,
  312. title=_("Limit Crossed"),
  313. )
  314. def warn_about_bypassing_with_role(self, item, qty_or_amount, role):
  315. if qty_or_amount == "qty":
  316. msg = _("Over Receipt/Delivery of {0} {1} ignored for item {2} because you have {3} role.")
  317. else:
  318. msg = _("Overbilling of {0} {1} ignored for item {2} because you have {3} role.")
  319. frappe.msgprint(
  320. msg.format(
  321. _(item["target_ref_field"].title()),
  322. frappe.bold(item["reduce_by"]),
  323. frappe.bold(item.get("item_code")),
  324. role,
  325. ),
  326. indicator="orange",
  327. alert=True,
  328. )
  329. def update_qty(self, update_modified=True):
  330. """Updates qty or amount at row level
  331. :param update_modified: If true, updates `modified` and `modified_by` for target parent doc
  332. """
  333. for args in self.status_updater:
  334. # condition to include current record (if submit or no if cancel)
  335. if self.docstatus == 1:
  336. args["cond"] = " or parent='%s'" % self.name.replace('"', '"')
  337. else:
  338. args["cond"] = " and parent!='%s'" % self.name.replace('"', '"')
  339. self._update_children(args, update_modified)
  340. if "percent_join_field" in args or "percent_join_field_parent" in args:
  341. self._update_percent_field_in_targets(args, update_modified)
  342. def _update_children(self, args, update_modified):
  343. """Update quantities or amount in child table"""
  344. for d in self.get_all_children():
  345. if d.doctype != args["source_dt"]:
  346. continue
  347. self._update_modified(args, update_modified)
  348. # updates qty in the child table
  349. args["detail_id"] = d.get(args["join_field"])
  350. args["second_source_condition"] = ""
  351. if (
  352. args.get("second_source_dt")
  353. and args.get("second_source_field")
  354. and args.get("second_join_field")
  355. ):
  356. if not args.get("second_source_extra_cond"):
  357. args["second_source_extra_cond"] = ""
  358. args["second_source_condition"] = frappe.db.sql(
  359. """ select ifnull((select sum(%(second_source_field)s)
  360. from `tab%(second_source_dt)s`
  361. where `%(second_join_field)s`='%(detail_id)s'
  362. and (`tab%(second_source_dt)s`.docstatus=1)
  363. %(second_source_extra_cond)s), 0) """
  364. % args
  365. )[0][0]
  366. if args["detail_id"]:
  367. if not args.get("extra_cond"):
  368. args["extra_cond"] = ""
  369. args["source_dt_value"] = (
  370. frappe.db.sql(
  371. """
  372. (select ifnull(sum(%(source_field)s), 0)
  373. from `tab%(source_dt)s` where `%(join_field)s`='%(detail_id)s'
  374. and (docstatus=1 %(cond)s) %(extra_cond)s)
  375. """
  376. % args
  377. )[0][0]
  378. or 0.0
  379. )
  380. if args["second_source_condition"]:
  381. args["source_dt_value"] += flt(args["second_source_condition"])
  382. frappe.db.sql(
  383. """update `tab%(target_dt)s`
  384. set %(target_field)s = %(source_dt_value)s %(update_modified)s
  385. where name='%(detail_id)s'"""
  386. % args
  387. )
  388. def _update_percent_field_in_targets(self, args, update_modified=True):
  389. """Update percent field in parent transaction"""
  390. if args.get("percent_join_field_parent"):
  391. # if reference to target doc where % is to be updated, is
  392. # in source doc's parent form, consider percent_join_field_parent
  393. args["name"] = self.get(args["percent_join_field_parent"])
  394. self._update_percent_field(args, update_modified)
  395. else:
  396. distinct_transactions = set(
  397. d.get(args["percent_join_field"]) for d in self.get_all_children(args["source_dt"])
  398. )
  399. for name in distinct_transactions:
  400. if name:
  401. args["name"] = name
  402. self._update_percent_field(args, update_modified)
  403. def _update_percent_field(self, args, update_modified=True):
  404. """Update percent field in parent transaction"""
  405. self._update_modified(args, update_modified)
  406. if args.get("target_parent_field"):
  407. frappe.db.sql(
  408. """update `tab%(target_parent_dt)s`
  409. set %(target_parent_field)s = round(
  410. ifnull((select
  411. ifnull(sum(case when abs(%(target_ref_field)s) > abs(%(target_field)s) then abs(%(target_field)s) else abs(%(target_ref_field)s) end), 0)
  412. / sum(abs(%(target_ref_field)s)) * 100
  413. from `tab%(target_dt)s` where parent='%(name)s' and parenttype='%(target_parent_dt)s' having sum(abs(%(target_ref_field)s)) > 0), 0), 6)
  414. %(update_modified)s
  415. where name='%(name)s'"""
  416. % args
  417. )
  418. # update field
  419. if args.get("status_field"):
  420. frappe.db.sql(
  421. """update `tab%(target_parent_dt)s`
  422. set %(status_field)s = (case when %(target_parent_field)s<0.001 then 'Not %(keyword)s'
  423. else case when %(target_parent_field)s>=99.999999 then 'Fully %(keyword)s'
  424. else 'Partly %(keyword)s' end end)
  425. where name='%(name)s'"""
  426. % args
  427. )
  428. if update_modified:
  429. target = frappe.get_doc(args["target_parent_dt"], args["name"])
  430. target.set_status(update=True)
  431. target.notify_update()
  432. def _update_modified(self, args, update_modified):
  433. if not update_modified:
  434. args["update_modified"] = ""
  435. return
  436. args["update_modified"] = ", modified = {0}, modified_by = {1}".format(
  437. frappe.db.escape(now()), frappe.db.escape(frappe.session.user)
  438. )
  439. def update_billing_status_for_zero_amount_refdoc(self, ref_dt):
  440. ref_fieldname = frappe.scrub(ref_dt)
  441. ref_docs = [
  442. item.get(ref_fieldname) for item in (self.get("items") or []) if item.get(ref_fieldname)
  443. ]
  444. if not ref_docs:
  445. return
  446. zero_amount_refdocs = frappe.db.sql_list(
  447. """
  448. SELECT
  449. name
  450. from
  451. `tab{ref_dt}`
  452. where
  453. docstatus = 1
  454. and base_net_total = 0
  455. and name in %(ref_docs)s
  456. """.format(
  457. ref_dt=ref_dt
  458. ),
  459. {"ref_docs": ref_docs},
  460. )
  461. if zero_amount_refdocs:
  462. self.update_billing_status(zero_amount_refdocs, ref_dt, ref_fieldname)
  463. def update_billing_status(self, zero_amount_refdoc, ref_dt, ref_fieldname):
  464. for ref_dn in zero_amount_refdoc:
  465. ref_doc_qty = flt(
  466. frappe.db.sql(
  467. """select ifnull(sum(qty), 0) from `tab%s Item`
  468. where parent=%s"""
  469. % (ref_dt, "%s"),
  470. (ref_dn),
  471. )[0][0]
  472. )
  473. billed_qty = flt(
  474. frappe.db.sql(
  475. """select ifnull(sum(qty), 0)
  476. from `tab%s Item` where %s=%s and docstatus=1"""
  477. % (self.doctype, ref_fieldname, "%s"),
  478. (ref_dn),
  479. )[0][0]
  480. )
  481. per_billed = (min(ref_doc_qty, billed_qty) / ref_doc_qty) * 100
  482. ref_doc = frappe.get_doc(ref_dt, ref_dn)
  483. ref_doc.db_set("per_billed", per_billed)
  484. # set billling status
  485. if hasattr(ref_doc, "billing_status"):
  486. if ref_doc.per_billed < 0.001:
  487. ref_doc.db_set("billing_status", "Not Billed")
  488. elif ref_doc.per_billed > 99.999999:
  489. ref_doc.db_set("billing_status", "Fully Billed")
  490. else:
  491. ref_doc.db_set("billing_status", "Partly Billed")
  492. ref_doc.set_status(update=True)
  493. def get_allowance_for(
  494. item_code,
  495. item_allowance=None,
  496. global_qty_allowance=None,
  497. global_amount_allowance=None,
  498. qty_or_amount="qty",
  499. ):
  500. """
  501. Returns the allowance for the item, if not set, returns global allowance
  502. """
  503. if item_allowance is None:
  504. item_allowance = {}
  505. if qty_or_amount == "qty":
  506. if item_allowance.get(item_code, frappe._dict()).get("qty"):
  507. return (
  508. item_allowance[item_code].qty,
  509. item_allowance,
  510. global_qty_allowance,
  511. global_amount_allowance,
  512. )
  513. else:
  514. if item_allowance.get(item_code, frappe._dict()).get("amount"):
  515. return (
  516. item_allowance[item_code].amount,
  517. item_allowance,
  518. global_qty_allowance,
  519. global_amount_allowance,
  520. )
  521. qty_allowance, over_billing_allowance = frappe.db.get_value(
  522. "Item", item_code, ["over_delivery_receipt_allowance", "over_billing_allowance"]
  523. )
  524. if qty_or_amount == "qty" and not qty_allowance:
  525. if global_qty_allowance == None:
  526. global_qty_allowance = flt(
  527. frappe.db.get_single_value("Stock Settings", "over_delivery_receipt_allowance")
  528. )
  529. qty_allowance = global_qty_allowance
  530. elif qty_or_amount == "amount" and not over_billing_allowance:
  531. if global_amount_allowance == None:
  532. global_amount_allowance = flt(
  533. frappe.db.get_single_value("Accounts Settings", "over_billing_allowance")
  534. )
  535. over_billing_allowance = global_amount_allowance
  536. if qty_or_amount == "qty":
  537. allowance = qty_allowance
  538. item_allowance.setdefault(item_code, frappe._dict()).setdefault("qty", qty_allowance)
  539. else:
  540. allowance = over_billing_allowance
  541. item_allowance.setdefault(item_code, frappe._dict()).setdefault("amount", over_billing_allowance)
  542. return allowance, item_allowance, global_qty_allowance, global_amount_allowance