blob: 2f5bac91d37171ea46b2c5d6480049981ef29f6e [file] [log] [blame]
Anand Doshi885e0742015-03-03 14:55:30 +05301# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
Nabin Haiteea2b342013-10-11 18:31:33 +05302# License: GNU General Public License v3. See license.txt
3
Chillar Anand915b3432021-09-02 16:44:59 +05304
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05305import frappe
Devin Slauenwhitef3f26d22022-06-17 11:51:21 -04006from frappe.query_builder import DocType
7from frappe.query_builder.functions import Sum
8from frappe.query_builder.utils import Table
Ankush Menat77be9822022-02-11 11:29:37 +05309from frappe.utils import cstr, flt, now, nowdate, nowtime
Devin Slauenwhitef3f26d22022-06-17 11:51:21 -040010from pypika.queries import QueryBuilder
Chillar Anand915b3432021-09-02 16:44:59 +053011
Nabin Haita77b8c92020-12-21 14:45:50 +053012from erpnext.controllers.stock_controller import create_repost_item_valuation_entry
Chillar Anand915b3432021-09-02 16:44:59 +053013
Nabin Haiteea2b342013-10-11 18:31:33 +053014
Nabin Haitb7e46c42015-10-12 16:46:29 +053015def repost(only_actual=False, allow_negative_stock=False, allow_zero_rate=False, only_bin=False):
Nabin Haiteea2b342013-10-11 18:31:33 +053016 """
17 Repost everything!
18 """
Anand Doshie9baaa62014-02-26 12:35:33 +053019 frappe.db.auto_commit_on_many_writes = 1
Nabin Hait62985362014-04-04 12:05:16 +053020
Nabin Haitca471f42013-11-20 13:14:12 +053021 if allow_negative_stock:
Ankush Menat494bd9e2022-03-28 18:52:46 +053022 existing_allow_negative_stock = frappe.db.get_value(
23 "Stock Settings", None, "allow_negative_stock"
24 )
Nabin Hait249bbbc2014-11-26 15:35:08 +053025 frappe.db.set_value("Stock Settings", None, "allow_negative_stock", 1)
Nabin Hait62985362014-04-04 12:05:16 +053026
Ankush Menat494bd9e2022-03-28 18:52:46 +053027 item_warehouses = frappe.db.sql(
28 """
Nabin Hait001edb42019-09-26 16:44:35 +053029 select distinct item_code, warehouse
30 from
31 (select item_code, warehouse from tabBin
32 union
33 select item_code, warehouse from `tabStock Ledger Entry`) a
Ankush Menat494bd9e2022-03-28 18:52:46 +053034 """
35 )
Nabin Hait001edb42019-09-26 16:44:35 +053036 for d in item_warehouses:
37 try:
38 repost_stock(d[0], d[1], allow_zero_rate, only_actual, only_bin, allow_negative_stock)
39 frappe.db.commit()
Ankush Menat694ae812021-09-01 14:40:56 +053040 except Exception:
Nabin Hait001edb42019-09-26 16:44:35 +053041 frappe.db.rollback()
Nabin Hait62985362014-04-04 12:05:16 +053042
Nabin Haitca471f42013-11-20 13:14:12 +053043 if allow_negative_stock:
Ankush Menat494bd9e2022-03-28 18:52:46 +053044 frappe.db.set_value(
45 "Stock Settings", None, "allow_negative_stock", existing_allow_negative_stock
46 )
Anand Doshie9baaa62014-02-26 12:35:33 +053047 frappe.db.auto_commit_on_many_writes = 0
Nabin Haiteea2b342013-10-11 18:31:33 +053048
Ankush Menat494bd9e2022-03-28 18:52:46 +053049
50def repost_stock(
51 item_code,
52 warehouse,
53 allow_zero_rate=False,
54 only_actual=False,
55 only_bin=False,
56 allow_negative_stock=False,
57):
Nabin Hait001edb42019-09-26 16:44:35 +053058
Nabin Haitb7e46c42015-10-12 16:46:29 +053059 if not only_bin:
Nabin Hait001edb42019-09-26 16:44:35 +053060 repost_actual_qty(item_code, warehouse, allow_zero_rate, allow_negative_stock)
Nabin Hait62985362014-04-04 12:05:16 +053061
Nabin Hait2348a5f2014-10-15 15:31:33 +053062 if item_code and warehouse and not only_actual:
Nabin Haitb7e46c42015-10-12 16:46:29 +053063 qty_dict = {
Nabin Haiteea2b342013-10-11 18:31:33 +053064 "reserved_qty": get_reserved_qty(item_code, warehouse),
65 "indented_qty": get_indented_qty(item_code, warehouse),
66 "ordered_qty": get_ordered_qty(item_code, warehouse),
Ankush Menat494bd9e2022-03-28 18:52:46 +053067 "planned_qty": get_planned_qty(item_code, warehouse),
Nabin Haitb7e46c42015-10-12 16:46:29 +053068 }
69 if only_bin:
Ankush Menat494bd9e2022-03-28 18:52:46 +053070 qty_dict.update({"actual_qty": get_balance_qty_from_sle(item_code, warehouse)})
Rushabh Mehtac4d4c7f2015-10-14 17:37:28 +053071
Nabin Haitb7e46c42015-10-12 16:46:29 +053072 update_bin_qty(item_code, warehouse, qty_dict)
Nabin Haiteea2b342013-10-11 18:31:33 +053073
Ankush Menat494bd9e2022-03-28 18:52:46 +053074
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053075def repost_actual_qty(item_code, warehouse, allow_zero_rate=False, allow_negative_stock=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +053076 create_repost_item_valuation_entry(
77 {
78 "item_code": item_code,
79 "warehouse": warehouse,
80 "posting_date": "1900-01-01",
81 "posting_time": "00:01",
82 "allow_negative_stock": allow_negative_stock,
83 "allow_zero_rate": allow_zero_rate,
84 }
85 )
86
Rushabh Mehtac4d4c7f2015-10-14 17:37:28 +053087
Nabin Haitb7e46c42015-10-12 16:46:29 +053088def get_balance_qty_from_sle(item_code, warehouse):
Ankush Menat494bd9e2022-03-28 18:52:46 +053089 balance_qty = frappe.db.sql(
90 """select qty_after_transaction from `tabStock Ledger Entry`
Nabin Haita77b8c92020-12-21 14:45:50 +053091 where item_code=%s and warehouse=%s and is_cancelled=0
Aditya Hase0c164242019-01-07 22:07:13 +053092 order by posting_date desc, posting_time desc, creation desc
Ankush Menat494bd9e2022-03-28 18:52:46 +053093 limit 1""",
94 (item_code, warehouse),
95 )
Rushabh Mehtac4d4c7f2015-10-14 17:37:28 +053096
Nabin Haitb7e46c42015-10-12 16:46:29 +053097 return flt(balance_qty[0][0]) if balance_qty else 0.0
Nabin Hait62985362014-04-04 12:05:16 +053098
Ankush Menat494bd9e2022-03-28 18:52:46 +053099
Nabin Haiteea2b342013-10-11 18:31:33 +0530100def get_reserved_qty(item_code, warehouse):
Devin Slauenwhitef3f26d22022-06-17 11:51:21 -0400101 SalesOrder = DocType("Sales Order")
102 SalesOrderItem = DocType("Sales Order Item")
103 PackedItem = DocType("Packed Item")
104
105 def append_open_so_query(q: QueryBuilder, child_table: Table) -> QueryBuilder:
106 return (
107 q.inner_join(SalesOrder)
108 .on(SalesOrder.name == child_table.parent)
109 .where(SalesOrder.docstatus == 1)
110 .where(SalesOrder.status != "Closed")
111 )
112
113 tab = (
114 frappe.qb.from_(SalesOrderItem)
115 .select(
116 SalesOrderItem.stock_qty.as_("dnpi_qty"),
117 SalesOrderItem.qty.as_("so_item_qty"),
118 SalesOrderItem.delivered_qty.as_("so_item_delivered_qty"),
119 SalesOrderItem.returned_qty.as_("so_item_returned_qty"),
120 SalesOrderItem.parent,
121 SalesOrderItem.name,
122 )
123 .where(SalesOrderItem.item_code == item_code)
124 .where(SalesOrderItem.warehouse == warehouse)
125 )
126 tab = append_open_so_query(tab, SalesOrderItem)
127
128 dnpi = (
129 frappe.qb.from_(PackedItem)
130 .select(PackedItem.qty, PackedItem.parent_detail_docname, PackedItem.parent, PackedItem.name)
131 .where(PackedItem.item_code == item_code)
132 .where(PackedItem.warehouse == warehouse)
133 )
134 dnpi = append_open_so_query(dnpi, PackedItem)
135
136 qty_queries = {}
137 for key, so_item_field in [
138 ("so_item_qty", "qty"),
139 ("so_item_delivered_qty", "delivered_qty"),
140 ("so_item_returned_qty", "returned_qty"),
141 ]:
142 qty_queries.update(
143 {
144 key: (
145 frappe.qb.from_(SalesOrderItem)
146 .select(SalesOrderItem[so_item_field])
147 .where(SalesOrderItem.name == dnpi.parent_detail_docname)
148 .where(SalesOrderItem.delivered_by_supplier == 0)
149 )
150 }
151 )
152
153 dnpi_parent = frappe.qb.from_(dnpi).select(dnpi.qty.as_("dnpi_qty"))
154 for key, query in qty_queries.items():
155 dnpi_parent = dnpi_parent.select(query.as_(key))
156 dnpi_parent = dnpi_parent.select(dnpi.parent, dnpi.name)
157
158 dnpi_parent = dnpi_parent + tab
159
160 q = (
161 frappe.qb.from_(dnpi_parent)
162 .select(
163 Sum(
164 dnpi_parent.dnpi_qty
165 * (
Nabin Haiteea2b342013-10-11 18:31:33 +0530166 (
Devin Slauenwhitef3f26d22022-06-17 11:51:21 -0400167 dnpi_parent.so_item_qty
168 - dnpi_parent.so_item_delivered_qty
169 - dnpi_parent.so_item_returned_qty
170 )
171 / dnpi_parent.so_item_qty
172 )
173 )
174 )
175 .where(dnpi_parent.so_item_qty >= dnpi_parent.so_item_delivered_qty)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530176 )
Nabin Haiteea2b342013-10-11 18:31:33 +0530177
Devin Slauenwhitef3f26d22022-06-17 11:51:21 -0400178 reserved_qty = q.run()
Nabin Haiteea2b342013-10-11 18:31:33 +0530179 return flt(reserved_qty[0][0]) if reserved_qty else 0
Nabin Hait62985362014-04-04 12:05:16 +0530180
Ankush Menat494bd9e2022-03-28 18:52:46 +0530181
Nabin Haiteea2b342013-10-11 18:31:33 +0530182def get_indented_qty(item_code, warehouse):
Nabin Hait7eaa7f22020-04-17 10:52:28 +0530183 # Ordered Qty is always maintained in stock UOM
Ankush Menat494bd9e2022-03-28 18:52:46 +0530184 inward_qty = frappe.db.sql(
185 """
Nabin Hait03af0292020-04-16 20:11:32 +0530186 select sum(mr_item.stock_qty - mr_item.ordered_qty)
Nabin Hait4acd4312014-11-04 15:32:31 +0530187 from `tabMaterial Request Item` mr_item, `tabMaterial Request` mr
188 where mr_item.item_code=%s and mr_item.warehouse=%s
Nabin Hait7eaa7f22020-04-17 10:52:28 +0530189 and mr.material_request_type in ('Purchase', 'Manufacture', 'Customer Provided', 'Material Transfer')
Nabin Hait03af0292020-04-16 20:11:32 +0530190 and mr_item.stock_qty > mr_item.ordered_qty and mr_item.parent=mr.name
191 and mr.status!='Stopped' and mr.docstatus=1
Ankush Menat494bd9e2022-03-28 18:52:46 +0530192 """,
193 (item_code, warehouse),
194 )
Nabin Hait7eaa7f22020-04-17 10:52:28 +0530195 inward_qty = flt(inward_qty[0][0]) if inward_qty else 0
Nabin Hait62985362014-04-04 12:05:16 +0530196
Ankush Menat494bd9e2022-03-28 18:52:46 +0530197 outward_qty = frappe.db.sql(
198 """
Nabin Hait03af0292020-04-16 20:11:32 +0530199 select sum(mr_item.stock_qty - mr_item.ordered_qty)
200 from `tabMaterial Request Item` mr_item, `tabMaterial Request` mr
201 where mr_item.item_code=%s and mr_item.warehouse=%s
Nabin Hait7eaa7f22020-04-17 10:52:28 +0530202 and mr.material_request_type = 'Material Issue'
Nabin Hait03af0292020-04-16 20:11:32 +0530203 and mr_item.stock_qty > mr_item.ordered_qty and mr_item.parent=mr.name
204 and mr.status!='Stopped' and mr.docstatus=1
Ankush Menat494bd9e2022-03-28 18:52:46 +0530205 """,
206 (item_code, warehouse),
207 )
Nabin Hait7eaa7f22020-04-17 10:52:28 +0530208 outward_qty = flt(outward_qty[0][0]) if outward_qty else 0
marination815c36a2020-03-26 14:49:28 +0530209
Nabin Hait7eaa7f22020-04-17 10:52:28 +0530210 requested_qty = inward_qty - outward_qty
Nabin Hait03af0292020-04-16 20:11:32 +0530211
212 return requested_qty
Nabin Haiteea2b342013-10-11 18:31:33 +0530213
Ankush Menat494bd9e2022-03-28 18:52:46 +0530214
Nabin Haiteea2b342013-10-11 18:31:33 +0530215def get_ordered_qty(item_code, warehouse):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530216 ordered_qty = frappe.db.sql(
217 """
Anand Doshi602e8252015-11-16 19:05:46 +0530218 select sum((po_item.qty - po_item.received_qty)*po_item.conversion_factor)
Nabin Haiteea2b342013-10-11 18:31:33 +0530219 from `tabPurchase Order Item` po_item, `tabPurchase Order` po
Nabin Hait62985362014-04-04 12:05:16 +0530220 where po_item.item_code=%s and po_item.warehouse=%s
Anand Doshi602e8252015-11-16 19:05:46 +0530221 and po_item.qty > po_item.received_qty and po_item.parent=po.name
patilsangrambf2b5112016-02-22 16:24:23 +0530222 and po.status not in ('Closed', 'Delivered') and po.docstatus=1
Ankush Menat494bd9e2022-03-28 18:52:46 +0530223 and po_item.delivered_by_supplier = 0""",
224 (item_code, warehouse),
225 )
Nabin Hait62985362014-04-04 12:05:16 +0530226
Nabin Haiteea2b342013-10-11 18:31:33 +0530227 return flt(ordered_qty[0][0]) if ordered_qty else 0
Nabin Hait62985362014-04-04 12:05:16 +0530228
Ankush Menat494bd9e2022-03-28 18:52:46 +0530229
Nabin Haiteea2b342013-10-11 18:31:33 +0530230def get_planned_qty(item_code, warehouse):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530231 planned_qty = frappe.db.sql(
232 """
Zarrar13ddc7e2018-03-20 12:38:43 +0530233 select sum(qty - produced_qty) from `tabWork Order`
Anupam663a7af2021-11-09 10:50:38 +0530234 where production_item = %s and fg_warehouse = %s and status not in ("Stopped", "Completed", "Closed")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530235 and docstatus=1 and qty > produced_qty""",
236 (item_code, warehouse),
237 )
Nabin Haiteea2b342013-10-11 18:31:33 +0530238
239 return flt(planned_qty[0][0]) if planned_qty else 0
Nabin Hait62985362014-04-04 12:05:16 +0530240
241
Nabin Hait7f3f2a02014-09-01 18:16:05 +0530242def update_bin_qty(item_code, warehouse, qty_dict=None):
Rushabh Mehta1f847992013-12-12 19:12:19 +0530243 from erpnext.stock.utils import get_bin
Ankush Menat494bd9e2022-03-28 18:52:46 +0530244
Nabin Haiteea2b342013-10-11 18:31:33 +0530245 bin = get_bin(item_code, warehouse)
246 mismatch = False
marination815c36a2020-03-26 14:49:28 +0530247 for field, value in qty_dict.items():
248 if flt(bin.get(field)) != flt(value):
249 bin.set(field, flt(value))
Nabin Haiteea2b342013-10-11 18:31:33 +0530250 mismatch = True
Nabin Hait62985362014-04-04 12:05:16 +0530251
Ankush Menat77be9822022-02-11 11:29:37 +0530252 bin.modified = now()
Nabin Haiteea2b342013-10-11 18:31:33 +0530253 if mismatch:
Himanshu Mishraf56aac62018-08-08 18:32:03 +0530254 bin.set_projected_qty()
255 bin.db_update()
256 bin.clear_cache()
Nabin Hait62985362014-04-04 12:05:16 +0530257
Nabin Hait62985362014-04-04 12:05:16 +0530258
Ankush Menat494bd9e2022-03-28 18:52:46 +0530259def set_stock_balance_as_per_serial_no(
260 item_code=None, posting_date=None, posting_time=None, fiscal_year=None
261):
262 if not posting_date:
263 posting_date = nowdate()
264 if not posting_time:
265 posting_time = nowtime()
Nabin Hait62985362014-04-04 12:05:16 +0530266
Ankush Menat494bd9e2022-03-28 18:52:46 +0530267 condition = " and item.name='%s'" % item_code.replace("'", "'") if item_code else ""
268
269 bin = frappe.db.sql(
270 """select bin.item_code, bin.warehouse, bin.actual_qty, item.stock_uom
Nabin Hait62985362014-04-04 12:05:16 +0530271 from `tabBin` bin, tabItem item
Ankush Menat494bd9e2022-03-28 18:52:46 +0530272 where bin.item_code = item.name and item.has_serial_no = 1 %s"""
273 % condition
274 )
Nabin Hait62985362014-04-04 12:05:16 +0530275
276 for d in bin:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530277 serial_nos = frappe.db.sql(
278 """select count(name) from `tabSerial No`
279 where item_code=%s and warehouse=%s and docstatus < 2""",
280 (d[0], d[1]),
281 )
Nabin Hait62985362014-04-04 12:05:16 +0530282
Ankush Menat494bd9e2022-03-28 18:52:46 +0530283 sle = frappe.db.sql(
284 """select valuation_rate, company from `tabStock Ledger Entry`
Nabin Haita77b8c92020-12-21 14:45:50 +0530285 where item_code = %s and warehouse = %s and is_cancelled = 0
Ankush Menat494bd9e2022-03-28 18:52:46 +0530286 order by posting_date desc limit 1""",
287 (d[0], d[1]),
288 )
Nabin Hait62985362014-04-04 12:05:16 +0530289
290 sle_dict = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530291 "doctype": "Stock Ledger Entry",
292 "item_code": d[0],
293 "warehouse": d[1],
294 "transaction_date": nowdate(),
295 "posting_date": posting_date,
296 "posting_time": posting_time,
297 "voucher_type": "Stock Reconciliation (Manual)",
298 "voucher_no": "",
299 "voucher_detail_no": "",
300 "actual_qty": flt(serial_nos[0][0]) - flt(d[2]),
301 "stock_uom": d[3],
302 "incoming_rate": sle and flt(serial_nos[0][0]) > flt(d[2]) and flt(sle[0][0]) or 0,
303 "company": sle and cstr(sle[0][1]) or 0,
304 "batch_no": "",
305 "serial_no": "",
Nabin Hait62985362014-04-04 12:05:16 +0530306 }
307
308 sle_doc = frappe.get_doc(sle_dict)
Anand Doshi6dfd4302015-02-10 14:41:27 +0530309 sle_doc.flags.ignore_validate = True
310 sle_doc.flags.ignore_links = True
Nabin Hait62985362014-04-04 12:05:16 +0530311 sle_doc.insert()
312
313 args = sle_dict.copy()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530314 args.update({"sle_id": sle_doc.name})
Nabin Hait62985362014-04-04 12:05:16 +0530315
Ankush Menat494bd9e2022-03-28 18:52:46 +0530316 create_repost_item_valuation_entry(
317 {
318 "item_code": d[0],
319 "warehouse": d[1],
320 "posting_date": posting_date,
321 "posting_time": posting_time,
322 }
323 )
324
nabinhait5c384882014-07-14 11:43:00 +0530325
nabinhait7700c622014-07-14 14:21:21 +0530326def reset_serial_no_status_and_warehouse(serial_nos=None):
nabinhait5c384882014-07-14 11:43:00 +0530327 if not serial_nos:
Nabin Haitc865f222015-09-21 09:18:43 +0530328 serial_nos = frappe.db.sql_list("""select name from `tabSerial No` where docstatus = 0""")
nabinhait5c384882014-07-14 11:43:00 +0530329 for serial_no in serial_nos:
330 try:
331 sr = frappe.get_doc("Serial No", serial_no)
nabinhaitb0a8d002014-07-14 11:56:03 +0530332 last_sle = sr.get_last_sle()
333 if flt(last_sle.actual_qty) > 0:
334 sr.warehouse = last_sle.warehouse
Nabin Hait7f3f2a02014-09-01 18:16:05 +0530335
nabinhait5c384882014-07-14 11:43:00 +0530336 sr.via_stock_ledger = True
337 sr.save()
Ankush Menat694ae812021-09-01 14:40:56 +0530338 except Exception:
nabinhait5c384882014-07-14 11:43:00 +0530339 pass