brotherton-erpnext/erpnext/controllers/status_updater.py

598 lines
18 KiB
Python
Raw Normal View History

# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
2014-02-14 10:17:51 +00:00
import frappe
2016-07-07 08:32:26 +00:00
from frappe import _
2014-04-21 09:36:56 +00:00
from frappe.model.document import Document
from frappe.utils import comma_or, flt, getdate, now, nowdate
2022-03-28 13:22:46 +00:00
class OverAllowanceError(frappe.ValidationError):
pass
2015-05-18 05:48:55 +00:00
def validate_status(status, options):
if status not in options:
frappe.throw(_("Status must be one of {0}").format(comma_or(options)))
2022-03-28 13:22:46 +00:00
status_map = {
"Lead": [
["Lost Quotation", "has_lost_quotation"],
["Opportunity", "has_opportunity"],
["Quotation", "has_quotation"],
["Converted", "has_customer"],
],
"Opportunity": [
2016-03-29 05:43:07 +00:00
["Lost", "eval:self.status=='Lost'"],
["Lost", "has_lost_quotation"],
2017-05-30 10:04:20 +00:00
["Quotation", "has_active_quotation"],
["Converted", "has_ordered_quotation"],
2022-03-28 13:22:46 +00:00
["Closed", "eval:self.status=='Closed'"],
],
"Quotation": [
2015-04-13 11:26:03 +00:00
["Draft", None],
["Open", "eval:self.docstatus==1"],
["Lost", "eval:self.status=='Lost'"],
["Ordered", "has_sales_order"],
["Cancelled", "eval:self.docstatus==2"],
],
"Sales Order": [
["Draft", None],
2022-03-28 13:22:46 +00:00
[
"To Deliver and Bill",
"eval:self.per_delivered < 100 and self.per_billed < 100 and self.docstatus == 1",
],
[
"To Bill",
"eval:(self.per_delivered == 100 or self.skip_delivery_note) and self.per_billed < 100 and self.docstatus == 1",
],
[
"To Deliver",
"eval:self.per_delivered < 100 and self.per_billed == 100 and self.docstatus == 1 and not self.skip_delivery_note",
],
[
"Completed",
"eval:(self.per_delivered == 100 or self.skip_delivery_note) and self.per_billed == 100 and self.docstatus == 1",
],
2015-10-02 07:12:48 +00:00
["Cancelled", "eval:self.docstatus==2"],
2015-10-19 08:47:52 +00:00
["Closed", "eval:self.status=='Closed'"],
2019-03-01 10:53:27 +00:00
["On Hold", "eval:self.status=='On Hold'"],
2015-10-02 07:12:48 +00:00
],
"Purchase Order": [
["Draft", None],
2022-03-28 13:22:46 +00:00
[
"To Receive and Bill",
"eval:self.per_received < 100 and self.per_billed < 100 and self.docstatus == 1",
],
["To Bill", "eval:self.per_received >= 100 and self.per_billed < 100 and self.docstatus == 1"],
2022-03-28 13:22:46 +00:00
[
"To Receive",
"eval:self.per_received < 100 and self.per_billed == 100 and self.docstatus == 1",
],
[
"Completed",
"eval:self.per_received >= 100 and self.per_billed == 100 and self.docstatus == 1",
],
["Delivered", "eval:self.status=='Delivered'"],
["Cancelled", "eval:self.docstatus==2"],
["On Hold", "eval:self.status=='On Hold'"],
2015-10-19 09:46:17 +00:00
["Closed", "eval:self.status=='Closed'"],
],
2015-05-18 05:48:55 +00:00
"Delivery Note": [
["Draft", None],
["To Bill", "eval:self.per_billed < 100 and self.docstatus == 1"],
2020-07-31 14:31:06 +00:00
["Return Issued", "eval:self.per_returned == 100 and self.docstatus == 1"],
["Completed", "eval:self.per_billed == 100 and self.docstatus == 1"],
2015-05-18 05:48:55 +00:00
["Cancelled", "eval:self.docstatus==2"],
["Closed", "eval:self.status=='Closed'"],
2015-05-18 05:48:55 +00:00
],
"Purchase Receipt": [
["Draft", None],
2015-12-30 13:38:11 +00:00
["To Bill", "eval:self.per_billed < 100 and self.docstatus == 1"],
2020-07-31 10:24:05 +00:00
["Return Issued", "eval:self.per_returned == 100 and self.docstatus == 1"],
2015-12-30 13:38:11 +00:00
["Completed", "eval:self.per_billed == 100 and self.docstatus == 1"],
2015-05-18 05:48:55 +00:00
["Cancelled", "eval:self.docstatus==2"],
["Closed", "eval:self.status=='Closed'"],
],
"Material Request": [
["Draft", None],
["Stopped", "eval:self.status == 'Stopped'"],
["Cancelled", "eval:self.docstatus == 2"],
["Pending", "eval:self.status != 'Stopped' and self.per_ordered == 0 and self.docstatus == 1"],
2022-03-28 13:22:46 +00:00
[
"Ordered",
"eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Purchase'",
],
[
"Transferred",
"eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Material Transfer'",
],
[
"Issued",
"eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Material Issue'",
],
[
"Received",
"eval:self.status != 'Stopped' and self.per_received == 100 and self.docstatus == 1 and self.material_request_type == 'Purchase'",
],
[
"Partially Received",
"eval:self.status != 'Stopped' and self.per_received > 0 and self.per_received < 100 and self.docstatus == 1 and self.material_request_type == 'Purchase'",
],
[
"Partially Ordered",
"eval:self.status != 'Stopped' and self.per_ordered < 100 and self.per_ordered > 0 and self.docstatus == 1",
],
[
"Manufactured",
"eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Manufacture'",
],
],
"Bank Transaction": [
["Unreconciled", "eval:self.docstatus == 1 and self.unallocated_amount>0"],
["Reconciled", "eval:self.docstatus == 1 and self.unallocated_amount<=0"],
2022-03-28 13:22:46 +00:00
["Cancelled", "eval:self.docstatus == 2"],
refactor: POS workflow (#20789) * refactor: add pos invoice doctype replacing sales invoice in POS * refactor: move pos.py to pos invoice * feat: add pos invoice merge log doctype * feat: ability to merge pos invoices into a sales invoice * feat: [wip] new ui for point of sale * fix: pos.py moved to pos_invoice * feat: loyalty points for POS Invoice * fix: loyalty points on merging * feat: return against pos invoices * Merge 'fork/serial-no-selector' into refactor-pos-invoice * chore: status fix and set warehouse from pos profile * fix: naming series * feat: merge pos returns into credit notes * feat: add pos list action for merging into sales invoices * feat[UX]: add shortcuts & focus on search after customer selection * feat: stock validation from previous pos transactions * Merge 'fork/serial-no-selector' into refactor-pos-invoice * chore: fix df not found for base_amount precision * feat: serial no validation from previous pos transactions * chore: move pos.py into pos page * feat: pos opening voucher * feat: link pos closing voucher with opening voucher * chore: use map_doc instead of get_mapped_doc for better perf * feat: enforce opening voucher on pos page * feat: [ui] [wip] point of sale beta ui refactor * fix: auto fetching serial nos with batch no * feat: [ui] item details section for new pos ui * feat: remove item from cart * refactor: [ui] [wip] split point_of_sale into components * new payment component * new numberpad * fix pos opening status * move from flex to grids * fix: search from item selector * feat: loyalty points as payment method * feat: pos invoice status * fix a bug with invalid JSON * fix: loyalty program ui fixes * feat: past order list and past order summary * feat: (minor) setting discount from item details * fix: adding item before customer selection * feat: post order submission summary * save and open draft orders * fix: item group filter * fix: item_det not defined while submitting sle * fix: minor bugs * fix: minor ux fixes * feat: show opening time in pos ui * feat: item and customer images * feat: emailing and printing an invoice * fix: item details field edit shows empty alert * fix: (minor) ux fixes * chore: rename pos opening voucher to pos opening entry * chore: (minor) rename pos closing voucher and sub doctypes * chore: add patch for renaming pos closing doctypes * fix: negative stock not allowed in pos invoices* default is_pos in pos invoices* fix: transalation * fix: invoices not getting fetched on pos closing * fix: indentation * feat: view / edit customer info * fix: minor bugs * fix: minor bug * fix: patch * fix: minor ux issues * fix: remove uppercase status * refactor: pos closing payment reconciliation * fix: move pos invoice print formats to pos invoice doctype * fix: ui issues * feat: new child doctype to store pos payment mode details * fix: add to patches.txt * feat: search by serial no * chore: [wip] code cleanup * fix: item not selectable from cart * chore: [wip] code cleanup * fix: minor issues * loyalty points transactions * default payment mode * fix: minor fixes * set correct mop amount with loaylty points * editing draft invoices from UI * chore: pos invoice merge log tests * fix: batch / serial validation in pos ui and on submission * feat: use onscan js for barcode scan events * fix: cart header with amount column * fix: validate batch no and qty in pos transactions * chore: do not fetch closing balances as opening balance * feat: show available qty in item selector * feat: shortcuts * fix: onscan.js not found * fix: onscan.js not found * fix: cannot return partial items * fix: neagtive stock indicator * feat: invoice discount * fix: change available stock on warehouse change * chore: cleanup code * fix: pos profile payment method table * feat: adding same item with different uom * fix: loyalty points deleted after consolidation * fix: enter loyalty amount instead of loyalty points * chore: return print format * feat: custom fields in pos view * chore: pos invoice test * chore: remove offline pos * fix: cyclic dependency * fix: cyclic dependency * patch: remove pos page and order fixes * chore: little fixes * fix: patch perf and plural naming * chore: tidy up pos invoice validation * chore: move pos closing to accounts * fix: move pos doctypes to accounts * fix: move pos doctypes to accounts * fix: item description in cart * fix: item description in cart * chore: loyalty tests * minor fixes * chore: rename point of sale beta to point of sale * chore: reset past order summary on filter change * chore: add point of sale to accounting desk * fix: payment reconciliation table in pos closing * fix: travis * Update accounting.json * fix: test cases * fix: tests * patch loyalty point entries * fix: remove test * default mode of payment is mandatory for pos transaction * chore: remove unused checks from pos profile * fix: loyalty point entry patch * fix: numpad reset and patches * fix: minor bugs * fix: travis * fix: travis * fix: travis * fix: travis Co-authored-by: Nabin Hait <nabinhait@gmail.com>
2020-07-23 13:21:26 +00:00
],
"POS Opening Entry": [
["Draft", None],
["Open", "eval:self.docstatus == 1 and not self.pos_closing_entry"],
["Closed", "eval:self.docstatus == 1 and self.pos_closing_entry"],
["Cancelled", "eval:self.docstatus == 2"],
],
"POS Closing Entry": [
["Draft", None],
["Submitted", "eval:self.docstatus == 1"],
["Queued", "eval:self.status == 'Queued'"],
["Failed", "eval:self.status == 'Failed'"],
["Cancelled", "eval:self.docstatus == 2"],
],
"Transaction Deletion Record": [
["Draft", None],
["Completed", "eval:self.docstatus == 1"],
2022-03-28 13:22:46 +00:00
],
}
2022-03-28 13:22:46 +00:00
2014-04-21 09:36:56 +00:00
class StatusUpdater(Document):
"""
2022-03-28 13:22:46 +00:00
Updates the status of the calling records
Delivery Note: Update Delivered Qty, Update Percent and Validate over delivery
Sales Invoice: Update Billed Amt, Update Percent and Validate over billing
Installation Note: Update Installed Qty, Update Percent Qty and Validate over installation
"""
def update_prevdoc_status(self):
self.update_qty()
self.validate_qty()
def set_status(self, update=False, status=None, update_modified=True):
2014-08-19 10:50:04 +00:00
if self.is_new():
2022-03-28 13:22:46 +00:00
if self.get("amended_from"):
self.status = "Draft"
return
if self.doctype in status_map:
2014-08-21 11:04:38 +00:00
_status = self.status
2015-11-04 09:50:50 +00:00
if status and update:
self.db_set("status", status)
sl = status_map[self.doctype][:]
2013-10-03 12:42:36 +00:00
sl.reverse()
for s in sl:
if not s[1]:
self.status = s[0]
break
2013-10-03 12:42:36 +00:00
elif s[1].startswith("eval:"):
2022-03-28 13:22:46 +00:00
if frappe.safe_eval(
s[1][5:],
None,
{
"self": self.as_dict(),
"getdate": getdate,
"nowdate": nowdate,
"get_value": frappe.db.get_value,
},
):
self.status = s[0]
break
elif getattr(self, s[1])():
self.status = s[0]
break
2022-03-28 13:22:46 +00:00
if self.status != _status and self.status not in (
"Cancelled",
"Partially Ordered",
"Ordered",
"Issued",
"Transferred",
):
self.add_comment("Label", _(self.status))
if update:
2022-03-28 13:22:46 +00:00
self.db_set("status", self.status, update_modified=update_modified)
def validate_qty(self):
2014-12-19 10:50:32 +00:00
"""Validates qty at row level"""
self.item_allowance = {}
self.global_qty_allowance = None
self.global_amount_allowance = None
for args in self.status_updater:
if "target_ref_field" not in args:
# if target_ref_field is not specified, the programmer does not want to validate qty / amount
continue
# get unique transactions to update
for d in self.get_all_children():
2022-03-28 13:22:46 +00:00
if hasattr(d, "qty") and d.qty < 0 and not self.get("is_return"):
frappe.throw(_("For an item {0}, quantity must be positive number").format(d.item_code))
2022-03-28 13:22:46 +00:00
if hasattr(d, "qty") and d.qty > 0 and self.get("is_return"):
frappe.throw(_("For an item {0}, quantity must be negative number").format(d.item_code))
2022-03-28 13:22:46 +00:00
if d.doctype == args["source_dt"] and d.get(args["join_field"]):
args["name"] = d.get(args["join_field"])
# get all qty where qty > target_field
2022-03-28 13:22:46 +00:00
item = frappe.db.sql(
"""select item_code, `{target_ref_field}`,
`{target_field}`, parenttype, parent from `tab{target_dt}`
where `{target_ref_field}` < `{target_field}`
2022-03-28 13:22:46 +00:00
and name=%s and docstatus=1""".format(
**args
),
args["name"],
as_dict=1,
)
if item:
item = item[0]
2022-03-28 13:22:46 +00:00
item["idx"] = d.idx
item["target_ref_field"] = args["target_ref_field"].replace("_", " ")
2016-07-07 08:32:26 +00:00
# if not item[args['target_ref_field']]:
# msgprint(_("Note: System will not check over-delivery and over-booking for Item {0} as quantity or amount is 0").format(item.item_code))
2022-03-28 13:22:46 +00:00
if args.get("no_allowance"):
item["reduce_by"] = item[args["target_field"]] - item[args["target_ref_field"]]
if item["reduce_by"] > 0.01:
self.limits_crossed_error(args, item, "qty")
2022-03-28 13:22:46 +00:00
elif item[args["target_ref_field"]]:
self.check_overflow_with_allowance(item, args)
def check_overflow_with_allowance(self, item, args):
"""
2022-03-28 13:22:46 +00:00
Checks if there is overflow condering a relaxation allowance
"""
2022-03-28 13:22:46 +00:00
qty_or_amount = "qty" if "qty" in args["target_ref_field"] else "amount"
# check if overflow is within allowance
2022-03-28 13:22:46 +00:00
(
allowance,
self.item_allowance,
self.global_qty_allowance,
self.global_amount_allowance,
) = get_allowance_for(
item["item_code"],
self.item_allowance,
self.global_qty_allowance,
self.global_amount_allowance,
qty_or_amount,
)
2022-03-28 13:22:46 +00:00
role_allowed_to_over_deliver_receive = frappe.db.get_single_value(
"Stock Settings", "role_allowed_to_over_deliver_receive"
)
role_allowed_to_over_bill = frappe.db.get_single_value(
"Accounts Settings", "role_allowed_to_over_bill"
)
role = (
role_allowed_to_over_deliver_receive if qty_or_amount == "qty" else role_allowed_to_over_bill
)
2022-03-28 13:22:46 +00:00
overflow_percent = (
(item[args["target_field"]] - item[args["target_ref_field"]]) / item[args["target_ref_field"]]
) * 100
2014-07-19 11:30:15 +00:00
if overflow_percent - allowance > 0.01:
2022-03-28 13:22:46 +00:00
item["max_allowed"] = flt(item[args["target_ref_field"]] * (100 + allowance) / 100)
item["reduce_by"] = item[args["target_field"]] - item["max_allowed"]
if role not in frappe.get_roles():
self.limits_crossed_error(args, item, qty_or_amount)
else:
self.warn_about_bypassing_with_role(item, qty_or_amount, role)
2016-07-07 08:32:26 +00:00
def limits_crossed_error(self, args, item, qty_or_amount):
2022-03-28 13:22:46 +00:00
"""Raise exception for limits crossed"""
if qty_or_amount == "qty":
2022-03-28 13:22:46 +00:00
action_msg = _(
'To allow over receipt / delivery, update "Over Receipt/Delivery Allowance" in Stock Settings or the Item.'
)
else:
2022-03-28 13:22:46 +00:00
action_msg = _(
'To allow over billing, update "Over Billing Allowance" in Accounts Settings or the Item.'
)
frappe.throw(
_(
"This document is over limit by {0} {1} for item {4}. Are you making another {3} against the same {2}?"
).format(
2016-07-07 08:32:26 +00:00
frappe.bold(_(item["target_ref_field"].title())),
frappe.bold(item["reduce_by"]),
2022-03-28 13:22:46 +00:00
frappe.bold(_(args.get("target_dt"))),
2016-07-07 08:32:26 +00:00
frappe.bold(_(self.doctype)),
2022-03-28 13:22:46 +00:00
frappe.bold(item.get("item_code")),
)
+ "<br><br>"
+ action_msg,
OverAllowanceError,
title=_("Limit Crossed"),
)
def warn_about_bypassing_with_role(self, item, qty_or_amount, role):
action = _("Over Receipt/Delivery") if qty_or_amount == "qty" else _("Overbilling")
2022-03-28 13:22:46 +00:00
msg = _("{} of {} {} ignored for item {} because you have {} role.").format(
action,
_(item["target_ref_field"].title()),
frappe.bold(item["reduce_by"]),
frappe.bold(item.get("item_code")),
role,
)
frappe.msgprint(msg, indicator="orange", alert=True)
def update_qty(self, update_modified=True):
"""Updates qty or amount at row level
2022-03-28 13:22:46 +00:00
:param update_modified: If true, updates `modified` and `modified_by` for target parent doc
"""
for args in self.status_updater:
# condition to include current record (if submit or no if cancel)
if self.docstatus == 1:
2022-03-28 13:22:46 +00:00
args["cond"] = ' or parent="%s"' % self.name.replace('"', '"')
else:
2022-03-28 13:22:46 +00:00
args["cond"] = ' and parent!="%s"' % self.name.replace('"', '"')
self._update_children(args, update_modified)
2020-07-31 10:24:05 +00:00
if "percent_join_field" in args or "percent_join_field_parent" in args:
self._update_percent_field_in_targets(args, update_modified)
def _update_children(self, args, update_modified):
"""Update quantities or amount in child table"""
for d in self.get_all_children():
2022-03-28 13:22:46 +00:00
if d.doctype != args["source_dt"]:
continue
self._update_modified(args, update_modified)
# updates qty in the child table
2022-03-28 13:22:46 +00:00
args["detail_id"] = d.get(args["join_field"])
args["second_source_condition"] = ""
if (
args.get("second_source_dt")
and args.get("second_source_field")
and args.get("second_join_field")
):
if not args.get("second_source_extra_cond"):
args["second_source_extra_cond"] = ""
2022-03-28 13:22:46 +00:00
args["second_source_condition"] = frappe.db.sql(
""" select ifnull((select sum(%(second_source_field)s)
from `tab%(second_source_dt)s`
where `%(second_join_field)s`="%(detail_id)s"
and (`tab%(second_source_dt)s`.docstatus=1)
2022-03-28 13:22:46 +00:00
%(second_source_extra_cond)s), 0) """
% args
)[0][0]
2022-03-28 13:22:46 +00:00
if args["detail_id"]:
if not args.get("extra_cond"):
args["extra_cond"] = ""
2022-03-28 13:22:46 +00:00
args["source_dt_value"] = (
frappe.db.sql(
"""
(select ifnull(sum(%(source_field)s), 0)
from `tab%(source_dt)s` where `%(join_field)s`="%(detail_id)s"
and (docstatus=1 %(cond)s) %(extra_cond)s)
2022-03-28 13:22:46 +00:00
"""
% args
)[0][0]
or 0.0
)
2022-03-28 13:22:46 +00:00
if args["second_source_condition"]:
args["source_dt_value"] += flt(args["second_source_condition"])
2022-03-28 13:22:46 +00:00
frappe.db.sql(
"""update `tab%(target_dt)s`
set %(target_field)s = %(source_dt_value)s %(update_modified)s
2022-03-28 13:22:46 +00:00
where name='%(detail_id)s'"""
% args
)
def _update_percent_field_in_targets(self, args, update_modified=True):
"""Update percent field in parent transaction"""
2022-03-28 13:22:46 +00:00
if args.get("percent_join_field_parent"):
2020-07-31 10:24:05 +00:00
# if reference to target doc where % is to be updated, is
# in source doc's parent form, consider percent_join_field_parent
2022-03-28 13:22:46 +00:00
args["name"] = self.get(args["percent_join_field_parent"])
2020-07-31 10:24:05 +00:00
self._update_percent_field(args, update_modified)
else:
2022-03-28 13:22:46 +00:00
distinct_transactions = set(
d.get(args["percent_join_field"]) for d in self.get_all_children(args["source_dt"])
)
2020-07-31 10:24:05 +00:00
for name in distinct_transactions:
if name:
2022-03-28 13:22:46 +00:00
args["name"] = name
2020-07-31 10:24:05 +00:00
self._update_percent_field(args, update_modified)
def _update_percent_field(self, args, update_modified=True):
2015-12-30 13:38:11 +00:00
"""Update percent field in parent transaction"""
self._update_modified(args, update_modified)
2022-03-28 13:22:46 +00:00
if args.get("target_parent_field"):
frappe.db.sql(
"""update `tab%(target_parent_dt)s`
2015-12-30 13:38:11 +00:00
set %(target_parent_field)s = round(
ifnull((select
ifnull(sum(if(abs(%(target_ref_field)s) > abs(%(target_field)s), abs(%(target_field)s), abs(%(target_ref_field)s))), 0)
/ sum(abs(%(target_ref_field)s)) * 100
from `tab%(target_dt)s` where parent="%(name)s" having sum(abs(%(target_ref_field)s)) > 0), 0), 6)
%(update_modified)s
2022-03-28 13:22:46 +00:00
where name='%(name)s'"""
% args
)
2015-12-30 13:38:11 +00:00
# update field
2022-03-28 13:22:46 +00:00
if args.get("status_field"):
frappe.db.sql(
"""update `tab%(target_parent_dt)s`
set %(status_field)s = if(%(target_parent_field)s<0.001,
'Not %(keyword)s', if(%(target_parent_field)s>=99.999999,
'Fully %(keyword)s', 'Partly %(keyword)s'))
2022-03-28 13:22:46 +00:00
where name='%(name)s'"""
% args
)
if update_modified:
target = frappe.get_doc(args["target_parent_dt"], args["name"])
target.set_status(update=True)
target.notify_update()
def _update_modified(self, args, update_modified):
if not update_modified:
2022-03-28 13:22:46 +00:00
args["update_modified"] = ""
return
2022-03-28 13:22:46 +00:00
args["update_modified"] = ", modified = {0}, modified_by = {1}".format(
frappe.db.escape(now()), frappe.db.escape(frappe.session.user)
)
def update_billing_status_for_zero_amount_refdoc(self, ref_dt):
2019-05-29 08:49:35 +00:00
ref_fieldname = frappe.scrub(ref_dt)
2022-03-28 13:22:46 +00:00
ref_docs = [
item.get(ref_fieldname) for item in (self.get("items") or []) if item.get(ref_fieldname)
]
2019-05-29 08:49:35 +00:00
if not ref_docs:
return
2022-03-28 13:22:46 +00:00
zero_amount_refdocs = frappe.db.sql_list(
"""
2019-05-29 08:49:35 +00:00
SELECT
name
from
`tab{ref_dt}`
where
docstatus = 1
and base_net_total = 0
and name in %(ref_docs)s
2022-03-28 13:22:46 +00:00
""".format(
ref_dt=ref_dt
),
{"ref_docs": ref_docs},
)
2019-05-29 08:49:35 +00:00
if zero_amount_refdocs:
self.update_billing_status(zero_amount_refdocs, ref_dt, ref_fieldname)
2015-11-04 09:50:50 +00:00
def update_billing_status(self, zero_amount_refdoc, ref_dt, ref_fieldname):
for ref_dn in zero_amount_refdoc:
2022-03-28 13:22:46 +00:00
ref_doc_qty = flt(
frappe.db.sql(
"""select ifnull(sum(qty), 0) from `tab%s Item`
where parent=%s"""
% (ref_dt, "%s"),
(ref_dn),
)[0][0]
)
billed_qty = flt(
frappe.db.sql(
"""select ifnull(sum(qty), 0)
from `tab%s Item` where %s=%s and docstatus=1"""
% (self.doctype, ref_fieldname, "%s"),
(ref_dn),
)[0][0]
)
per_billed = (min(ref_doc_qty, billed_qty) / ref_doc_qty) * 100
ref_doc = frappe.get_doc(ref_dt, ref_dn)
ref_doc.db_set("per_billed", per_billed)
# set billling status
2022-03-28 13:22:46 +00:00
if hasattr(ref_doc, "billing_status"):
if ref_doc.per_billed < 0.001:
ref_doc.db_set("billing_status", "Not Billed")
elif ref_doc.per_billed > 99.999999:
ref_doc.db_set("billing_status", "Fully Billed")
else:
ref_doc.db_set("billing_status", "Partly Billed")
ref_doc.set_status(update=True)
2022-03-28 13:22:46 +00:00
def get_allowance_for(
item_code,
item_allowance=None,
global_qty_allowance=None,
global_amount_allowance=None,
qty_or_amount="qty",
):
"""
2022-03-28 13:22:46 +00:00
Returns the allowance for the item, if not set, returns global allowance
"""
if item_allowance is None:
item_allowance = {}
if qty_or_amount == "qty":
if item_allowance.get(item_code, frappe._dict()).get("qty"):
2022-03-28 13:22:46 +00:00
return (
item_allowance[item_code].qty,
item_allowance,
global_qty_allowance,
global_amount_allowance,
)
else:
if item_allowance.get(item_code, frappe._dict()).get("amount"):
2022-03-28 13:22:46 +00:00
return (
item_allowance[item_code].amount,
item_allowance,
global_qty_allowance,
global_amount_allowance,
)
2022-03-28 13:22:46 +00:00
qty_allowance, over_billing_allowance = frappe.db.get_value(
"Item", item_code, ["over_delivery_receipt_allowance", "over_billing_allowance"]
)
if qty_or_amount == "qty" and not qty_allowance:
if global_qty_allowance == None:
2022-03-28 13:22:46 +00:00
global_qty_allowance = flt(
frappe.db.get_single_value("Stock Settings", "over_delivery_receipt_allowance")
)
qty_allowance = global_qty_allowance
elif qty_or_amount == "amount" and not over_billing_allowance:
if global_amount_allowance == None:
2022-03-28 13:22:46 +00:00
global_amount_allowance = flt(
frappe.db.get_single_value("Accounts Settings", "over_billing_allowance")
)
over_billing_allowance = global_amount_allowance
if qty_or_amount == "qty":
allowance = qty_allowance
item_allowance.setdefault(item_code, frappe._dict()).setdefault("qty", qty_allowance)
else:
allowance = over_billing_allowance
item_allowance.setdefault(item_code, frappe._dict()).setdefault("amount", over_billing_allowance)
return allowance, item_allowance, global_qty_allowance, global_amount_allowance