diff --git a/erpnext/selling/doctype/sales_order/sales_order.py b/erpnext/selling/doctype/sales_order/sales_order.py index b6891930e42..f18b8762c7f 100755 --- a/erpnext/selling/doctype/sales_order/sales_order.py +++ b/erpnext/selling/doctype/sales_order/sales_order.py @@ -1176,6 +1176,17 @@ def make_sales_invoice(source_name, target_doc=None, ignore_permissions=False, a target.debit_to = get_party_account("Customer", source.customer, source.company) def update_item(source, target, source_parent): + def get_billed_qty(so_item_name): + from frappe.query_builder.functions import Sum + + table = frappe.qb.DocType("Sales Invoice Item") + query = ( + frappe.qb.from_(table) + .select(Sum(table.qty).as_("qty")) + .where((table.docstatus == 1) & (table.so_detail == so_item_name)) + ) + return query.run(pluck="qty")[0] or 0 + if source_parent.has_unit_price_items: # 0 Amount rows (as seen in Unit Price Items) should be mapped as it is pending_amount = flt(source.amount) - flt(source.billed_amt) @@ -1185,8 +1196,8 @@ def make_sales_invoice(source_name, target_doc=None, ignore_permissions=False, a target.base_amount = target.amount * flt(source_parent.conversion_rate) target.qty = ( - target.amount / flt(source.rate) - if (source.rate and source.billed_amt) + source.qty - get_billed_qty(source.name) + if (source.qty and source.billed_amt) else (source.qty if is_unit_price_row(source) else source.qty - source.returned_qty) )