Update delivered / ordered qty in sales/purchase order from return entry

Reserved Qty logic cleaned up
This commit is contained in:
Nabin Hait 2015-08-24 14:32:38 +05:30 committed by Anand Doshi
parent ddd79f43d2
commit 1f94fa25a8
9 changed files with 117 additions and 163 deletions

View File

@ -81,9 +81,13 @@ class SalesInvoice(SellingController):
self.check_prev_docstatus()
if self.is_return:
self.status_updater = []
self.update_status_updater_args()
self.update_prevdoc_status()
if not self.is_return:
self.update_status_updater_args()
self.update_prevdoc_status()
self.update_billing_status_for_zero_amount_refdoc("Sales Order")
self.check_credit_limit()
@ -107,9 +111,13 @@ class SalesInvoice(SellingController):
from erpnext.accounts.utils import remove_against_link_from_jv
remove_against_link_from_jv(self.doctype, self.name)
if self.is_return:
self.status_updater = []
self.update_status_updater_args()
self.update_prevdoc_status()
if not self.is_return:
self.update_status_updater_args()
self.update_prevdoc_status()
self.update_billing_status_for_zero_amount_refdoc("Sales Order")
self.validate_c_form_on_cancel()
@ -294,8 +302,6 @@ class SalesInvoice(SellingController):
def so_dn_required(self):
"""check in manage account if sales order / delivery note required or not."""
if self.is_return:
return
dic = {'Sales Order':'so_required','Delivery Note':'dn_required'}
for i in dic:
if frappe.db.get_value('Selling Settings', None, dic[i]) == 'Yes':
@ -408,35 +414,11 @@ class SalesInvoice(SellingController):
def check_prev_docstatus(self):
for d in self.get('items'):
if d.sales_order:
submitted = frappe.db.sql("""select name from `tabSales Order`
where docstatus = 1 and name = %s""", d.sales_order)
if not submitted:
frappe.throw(_("Sales Order {0} is not submitted").format(d.sales_order))
if d.sales_order and frappe.db.get_value("Sales Order", d.sales_order, "docstatus") != 1:
frappe.throw(_("Sales Order {0} is not submitted").format(d.sales_order))
if d.delivery_note:
submitted = frappe.db.sql("""select name from `tabDelivery Note`
where docstatus = 1 and name = %s""", d.delivery_note)
if not submitted:
throw(_("Delivery Note {0} is not submitted").format(d.delivery_note))
def update_stock_ledger(self):
sl_entries = []
for d in self.get_item_list():
if frappe.db.get_value("Item", d.item_code, "is_stock_item") == 1 and d.warehouse and flt(d['qty']):
self.update_reserved_qty(d)
incoming_rate = 0
if cint(self.is_return) and self.return_against and self.docstatus==1:
incoming_rate = self.get_incoming_rate_for_sales_return(d.item_code,
self.return_against)
sl_entries.append(self.get_sl_entries(d, {
"actual_qty": -1*flt(d.qty),
"stock_uom": frappe.db.get_value("Item", d.item_code, "stock_uom"),
"incoming_rate": incoming_rate
}))
self.make_sl_entries(sl_entries)
if d.delivery_note and frappe.db.get_value("Delivery Note", d.delivery_note, "docstatus") != 1:
throw(_("Delivery Note {0} is not submitted").format(d.delivery_note))
def make_gl_entries(self, repost_future_gle=True):
gl_entries = self.get_gl_entries()

View File

@ -9,6 +9,7 @@ from frappe import msgprint, _, throw
from frappe.model.mapper import get_mapped_doc
from erpnext.controllers.buying_controller import BuyingController
from erpnext.stock.doctype.item.item import get_last_purchase_details
from erpnext.utilities.repost_stock import update_bin_qty, get_ordered_qty
form_grid_templates = {
@ -136,20 +137,6 @@ class PurchaseOrder(BuyingController):
def update_ordered_qty(self, po_item_rows=None):
"""update requested qty (before ordered_qty is updated)"""
from erpnext.stock.utils import get_bin
def _update_ordered_qty(item_code, warehouse):
ordered_qty = frappe.db.sql("""
select sum((po_item.qty - ifnull(po_item.received_qty, 0))*po_item.conversion_factor)
from `tabPurchase Order Item` po_item, `tabPurchase Order` po
where po_item.item_code=%s and po_item.warehouse=%s
and po_item.qty > ifnull(po_item.received_qty, 0) and po_item.parent=po.name
and po.status!='Stopped' and po.docstatus=1""", (item_code, warehouse))
bin_doc = get_bin(item_code, warehouse)
bin_doc.ordered_qty = flt(ordered_qty[0][0]) if ordered_qty else 0
bin_doc.save()
item_wh_list = []
for d in self.get("items"):
if (not po_item_rows or d.name in po_item_rows) and [d.item_code, d.warehouse] not in item_wh_list \
@ -157,7 +144,9 @@ class PurchaseOrder(BuyingController):
item_wh_list.append([d.item_code, d.warehouse])
for item_code, warehouse in item_wh_list:
_update_ordered_qty(item_code, warehouse)
update_bin_qty(item_code, warehouse, {
"ordered_qty": get_ordered_qty(item_code, warehouse)
})
def check_modified_date(self):
mod_db = frappe.db.sql("select modified from `tabPurchase Order` where name = %s",

View File

@ -137,9 +137,24 @@ def make_return_doc(doctype, source_name, target_doc=None):
target_doc.qty = -1* source_doc.qty
if doctype == "Purchase Receipt":
target_doc.received_qty = -1* source_doc.qty
target_doc.prevdoc_doctype = source_doc.prevdoc_doctype
target_doc.prevdoc_docname = source_doc.prevdoc_docname
target_doc.prevdoc_detail_docname = source_doc.prevdoc_detail_docname
elif doctype == "Purchase Invoice":
target_doc.purchase_order = source_doc.purchase_order
target_doc.purchase_receipt = source_doc.purchase_receipt
target_doc.po_detail = source_doc.po_detail
target_doc.pr_detail = source_doc.pr_detail
elif doctype == "Delivery Note":
target_doc.against_sales_order = source_doc.against_sales_order
target_doc.against_sales_invoice = source_doc.against_sales_invoice
target_doc.so_detail = source_doc.so_detail
target_doc.si_detail = source_doc.si_detail
elif doctype == "Sales Invoice":
target_doc.sales_order = source_doc.sales_order
target_doc.delivery_note = source_doc.delivery_note
target_doc.so_detail = source_doc.so_detail
target_doc.dn_detail = source_doc.dn_detail
doclist = get_mapped_doc(doctype, source_name, {
doctype: {
@ -152,8 +167,6 @@ def make_return_doc(doctype, source_name, target_doc=None):
doctype +" Item": {
"doctype": doctype + " Item",
"field_map": {
"purchase_order": "purchase_order",
"purchase_receipt": "purchase_receipt",
"serial_no": "serial_no",
"batch_no": "batch_no"
},

View File

@ -163,42 +163,17 @@ class SellingController(StockController):
def get_item_list(self):
il = []
for d in self.get("items"):
reserved_warehouse = ""
reserved_qty_for_main_item = 0
if d.qty is None:
frappe.throw(_("Row {0}: Qty is mandatory").format(d.idx))
if self.doctype == "Sales Order":
reserved_warehouse = d.warehouse
if flt(d.qty) > flt(d.delivered_qty):
reserved_qty_for_main_item = flt(d.qty) - flt(d.delivered_qty)
elif (((self.doctype == "Delivery Note" and d.against_sales_order)
or (self.doctype == "Sales Invoice" and d.sales_order and self.update_stock))
and not self.is_return):
# if SO qty is 10 and there is tolerance of 20%, then it will allow DN of 12.
# But in this case reserved qty should only be reduced by 10 and not 12
already_delivered_qty = self.get_already_delivered_qty(self.name,
d.against_sales_order if self.doctype=="Delivery Note" else d.sales_order, d.so_detail)
so_qty, reserved_warehouse = self.get_so_qty_and_warehouse(d.so_detail)
if already_delivered_qty + d.qty > so_qty:
reserved_qty_for_main_item = -(so_qty - already_delivered_qty)
else:
reserved_qty_for_main_item = -flt(d.qty)
if self.has_product_bundle(d.item_code):
for p in self.get("packed_items"):
if p.parent_detail_docname == d.name and p.parent_item == d.item_code:
# the packing details table's qty is already multiplied with parent's qty
il.append(frappe._dict({
'warehouse': p.warehouse,
'reserved_warehouse': reserved_warehouse,
'item_code': p.item_code,
'qty': flt(p.qty),
'reserved_qty': (flt(p.qty)/flt(d.qty)) * reserved_qty_for_main_item,
'uom': p.uom,
'batch_no': cstr(p.batch_no).strip(),
'serial_no': cstr(p.serial_no).strip(),
@ -207,10 +182,8 @@ class SellingController(StockController):
else:
il.append(frappe._dict({
'warehouse': d.warehouse,
'reserved_warehouse': reserved_warehouse,
'item_code': d.item_code,
'qty': d.qty,
'reserved_qty': reserved_qty_for_main_item,
'uom': d.stock_uom,
'stock_uom': d.stock_uom,
'batch_no': cstr(d.get("batch_no")).strip(),

View File

@ -6,11 +6,9 @@ import frappe
from frappe.utils import cint, flt, cstr
from frappe import msgprint, _
import frappe.defaults
from erpnext.accounts.general_ledger import make_gl_entries, delete_gl_entries, process_gl_map
from erpnext.controllers.accounts_controller import AccountsController
from erpnext.accounts.general_ledger import make_gl_entries, delete_gl_entries, process_gl_map
from erpnext.stock.utils import update_bin
class StockController(AccountsController):
def make_gl_entries(self, repost_future_gle=True):
@ -229,23 +227,44 @@ class StockController(AccountsController):
incoming_rate = incoming_rate[0][0] if incoming_rate else 0.0
return incoming_rate
def update_reserved_qty(self):
so_map = {}
for d in self.get("items"):
if d.so_detail:
if self.doctype == "Delivery Note" and d.against_sales_order:
so_map.setdefault(d.against_sales_order, []).append(d.so_detail)
elif self.doctype == "Sales Invoice" and d.sales_order and self.update_stock:
so_map.setdefault(d.sales_order, []).append(d.so_detail)
def update_reserved_qty(self, d):
if d['reserved_qty'] < 0 :
# Reduce reserved qty from reserved warehouse mentioned in so
if not d["reserved_warehouse"]:
frappe.throw(_("Delivery Warehouse is missing in Sales Order"))
for so, so_item_rows in so_map.items():
if so and so_item_rows:
sales_order = frappe.get_doc("Sales Order", so)
args = {
"item_code": d['item_code'],
"warehouse": d["reserved_warehouse"],
"voucher_type": self.doctype,
"voucher_no": self.name,
"reserved_qty": (self.docstatus==1 and 1 or -1)*flt(d['reserved_qty']),
"posting_date": self.posting_date,
"is_amended": self.amended_from and 'Yes' or 'No'
}
update_bin(args)
if sales_order.status in ["Stopped", "Cancelled"]:
frappe.throw(_("Sales Order {0} is cancelled or stopped").format(so), frappe.InvalidStatusError)
sales_order.update_reserved_qty(so_item_rows)
def update_stock_ledger(self):
self.update_reserved_qty()
sl_entries = []
for d in self.get_item_list():
if frappe.db.get_value("Item", d.item_code, "is_stock_item") == 1 \
and d.warehouse and flt(d['qty']):
incoming_rate = 0
if cint(self.is_return) and self.return_against and self.docstatus==1:
incoming_rate = self.get_incoming_rate_for_sales_return(d.item_code, self.return_against)
sl_entries.append(self.get_sl_entries(d, {
"actual_qty": -1*flt(d['qty']),
"stock_uom": frappe.db.get_value("Item", d.item_code, "stock_uom"),
"incoming_rate": incoming_rate
}))
self.make_sl_entries(sl_entries)
def update_gl_entries_after(posting_date, posting_time, for_warehouses=None, for_items=None,
warehouse_account=None):

View File

@ -8,6 +8,7 @@ import frappe.utils
from frappe.utils import cstr, flt, getdate, comma_and
from frappe import _
from frappe.model.mapper import get_mapped_doc
from erpnext.utilities.repost_stock import update_bin_qty, get_reserved_qty
from erpnext.controllers.selling_controller import SellingController
@ -151,7 +152,7 @@ class SalesOrder(SellingController):
super(SalesOrder, self).on_submit()
self.check_credit_limit()
self.update_stock_ledger(update_stock = 1)
self.update_reserved_qty()
frappe.get_doc('Authorization Control').validate_approving_authority(self.doctype, self.base_grand_total, self)
@ -164,7 +165,7 @@ class SalesOrder(SellingController):
frappe.throw(_("Stopped order cannot be cancelled. Unstop to cancel."))
self.check_nextdoc_docstatus()
self.update_stock_ledger(update_stock = -1)
self.update_reserved_qty()
self.update_prevdoc_status('cancel')
@ -213,32 +214,38 @@ class SalesOrder(SellingController):
def stop_sales_order(self):
self.check_modified_date()
self.update_stock_ledger(-1)
self.update_reserved_qty()
frappe.db.set(self, 'status', 'Stopped')
frappe.msgprint(_("{0} {1} status is Stopped").format(self.doctype, self.name))
self.notify_modified()
def unstop_sales_order(self):
self.check_modified_date()
self.update_stock_ledger(1)
self.update_reserved_qty()
frappe.db.set(self, 'status', 'Submitted')
frappe.msgprint(_("{0} {1} status is Unstopped").format(self.doctype, self.name))
def update_reserved_qty(self, so_item_rows=None):
"""update requested qty (before ordered_qty is updated)"""
item_wh_list = []
def _valid_for_reserve(item_code, warehouse):
if item_code and warehouse and [item_code, warehouse] not in item_wh_list \
and frappe.db.get_value("Item", item_code, "is_stock_item"):
item_wh_list.append([item_code, warehouse])
for d in self.get("items"):
if (not so_item_rows or d.name in so_item_rows):
_valid_for_reserve(d.item_code, d.warehouse)
if self.has_product_bundle(d.item_code):
for p in self.get("packed_items"):
if p.parent_detail_docname == d.name and p.parent_item == d.item_code:
_valid_for_reserve(p.item_code, p.warehouse)
def update_stock_ledger(self, update_stock):
from erpnext.stock.utils import update_bin
for d in self.get_item_list():
if frappe.db.get_value("Item", d['item_code'], "is_stock_item")==1:
args = {
"item_code": d['item_code'],
"warehouse": d['reserved_warehouse'],
"reserved_qty": flt(update_stock) * flt(d['reserved_qty']),
"posting_date": self.transaction_date,
"voucher_type": self.doctype,
"voucher_no": self.name,
"is_amended": self.amended_from and 'Yes' or 'No'
}
update_bin(args)
for item_code, warehouse in item_wh_list:
update_bin_qty(item_code, warehouse, {
"reserved_qty": get_reserved_qty(item_code, warehouse)
})
def on_update(self):
pass

View File

@ -83,7 +83,7 @@ class DeliveryNote(SellingController):
def so_required(self):
"""check in manage account if sales order required or not"""
if not self.is_return and frappe.db.get_value("Selling Settings", None, 'so_required') == 'Yes':
if frappe.db.get_value("Selling Settings", None, 'so_required') == 'Yes':
for d in self.get('items'):
if not d.against_sales_order:
frappe.throw(_("Sales Order required for Item {0}").format(d.item_code))
@ -174,10 +174,10 @@ class DeliveryNote(SellingController):
# Check for Approving Authority
frappe.get_doc('Authorization Control').validate_approving_authority(self.doctype, self.company, self.base_grand_total, self)
# update delivered qty in sales order
self.update_prevdoc_status()
if not self.is_return:
# update delivered qty in sales order
self.update_prevdoc_status()
self.check_credit_limit()
self.update_stock_ledger()
@ -190,8 +190,7 @@ class DeliveryNote(SellingController):
self.check_stop_sales_order("against_sales_order")
self.check_next_docstatus()
if not self.is_return:
self.update_prevdoc_status()
self.update_prevdoc_status()
self.update_stock_ledger()
@ -242,25 +241,6 @@ class DeliveryNote(SellingController):
ps.cancel()
frappe.msgprint(_("Packing Slip(s) cancelled"))
def update_stock_ledger(self):
sl_entries = []
for d in self.get_item_list():
if frappe.db.get_value("Item", d.item_code, "is_stock_item") == 1 \
and d.warehouse and flt(d['qty']):
self.update_reserved_qty(d)
incoming_rate = 0
if cint(self.is_return) and self.return_against and self.docstatus==1:
incoming_rate = self.get_incoming_rate_for_sales_return(d.item_code, self.return_against)
sl_entries.append(self.get_sl_entries(d, {
"actual_qty": -1*flt(d['qty']),
"incoming_rate": incoming_rate
}))
self.make_sl_entries(sl_entries)
def get_list_context(context=None):
from erpnext.controllers.website_list_for_contact import get_list_context
list_context = get_list_context(context)

View File

@ -10,9 +10,11 @@ import frappe
from frappe.utils import cstr, flt, getdate
from frappe import _
from frappe.model.mapper import get_mapped_doc
from erpnext.utilities.repost_stock import update_bin_qty, get_indented_qty
from erpnext.controllers.buying_controller import BuyingController
form_grid_templates = {
"items": "templates/form_grid/material_request_grid.html"
}
@ -136,19 +138,6 @@ class MaterialRequest(BuyingController):
def update_requested_qty(self, mr_item_rows=None):
"""update requested qty (before ordered_qty is updated)"""
from erpnext.stock.utils import get_bin
def _update_requested_qty(item_code, warehouse):
requested_qty = frappe.db.sql("""select sum(mr_item.qty - ifnull(mr_item.ordered_qty, 0))
from `tabMaterial Request Item` mr_item, `tabMaterial Request` mr
where mr_item.item_code=%s and mr_item.warehouse=%s
and mr_item.qty > ifnull(mr_item.ordered_qty, 0) and mr_item.parent=mr.name
and mr.status!='Stopped' and mr.docstatus=1""", (item_code, warehouse))
bin_doc = get_bin(item_code, warehouse)
bin_doc.indented_qty = flt(requested_qty[0][0]) if requested_qty else 0
bin_doc.save()
item_wh_list = []
for d in self.get("items"):
if (not mr_item_rows or d.name in mr_item_rows) and [d.item_code, d.warehouse] not in item_wh_list \
@ -156,7 +145,9 @@ class MaterialRequest(BuyingController):
item_wh_list.append([d.item_code, d.warehouse])
for item_code, warehouse in item_wh_list:
_update_requested_qty(item_code, warehouse)
update_bin_qty(item_code, warehouse, {
"indented_qty": get_indented_qty(item_code, warehouse)
})
def update_completed_and_requested_qty(stock_entry, method):
if stock_entry.doctype == "Stock Entry":

View File

@ -117,7 +117,7 @@ class PurchaseReceipt(BuyingController):
self.validate_rate_with_reference_doc([["Purchase Order", "prevdoc_docname", "prevdoc_detail_docname"]])
def po_required(self):
if not self.is_return and frappe.db.get_value("Buying Settings", None, "po_required") == 'Yes':
if frappe.db.get_value("Buying Settings", None, "po_required") == 'Yes':
for d in self.get('items'):
if not d.prevdoc_docname:
frappe.throw(_("Purchase Order number required for Item {0}").format(d.item_code))
@ -221,9 +221,10 @@ class PurchaseReceipt(BuyingController):
# Set status as Submitted
frappe.db.set(self, 'status', 'Submitted')
self.update_prevdoc_status()
self.update_ordered_qty()
if not self.is_return:
self.update_prevdoc_status()
self.update_ordered_qty()
purchase_controller.update_last_purchase_rate(self, 1)
self.update_stock_ledger()
@ -257,12 +258,11 @@ class PurchaseReceipt(BuyingController):
self.update_stock_ledger()
self.update_prevdoc_status()
# Must be called after updating received qty in PO
self.update_ordered_qty()
if not self.is_return:
self.update_prevdoc_status()
# Must be called after updating received qty in PO
self.update_ordered_qty()
pc_obj.update_last_purchase_rate(self, 0)
self.make_gl_entries_on_cancel()