blob: fc66345aeee1775e159574978d9075c913459e64 [file] [log] [blame]
Sagar Sharma29a1cb82022-04-26 17:29:45 +05301# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
2# For license information, please see license.txt
3
4import copy
s-aga-r6d89b2f2022-06-18 15:46:59 +05305import json
Sagar Sharma29a1cb82022-04-26 17:29:45 +05306from collections import defaultdict
7
8import frappe
9from frappe import _
Sagar Sharma008542b2022-09-07 10:15:43 +053010from frappe.model.mapper import get_mapped_doc
Rohit Waghchaure16f26fb2023-03-20 22:56:06 +053011from frappe.utils import cint, flt, get_link_to_form
Sagar Sharma29a1cb82022-04-26 17:29:45 +053012
13from erpnext.controllers.stock_controller import StockController
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +053014from erpnext.stock.doctype.serial_and_batch_bundle.serial_and_batch_bundle import (
15 get_voucher_wise_serial_batch_from_bundle,
16)
Sagar Sharma29a1cb82022-04-26 17:29:45 +053017from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
Rohit Waghchauree88c5d62023-04-05 20:03:44 +053018from erpnext.stock.serial_batch_bundle import SerialBatchCreation, get_serial_nos_from_bundle
Sagar Sharma29a1cb82022-04-26 17:29:45 +053019from erpnext.stock.utils import get_incoming_rate
20
21
22class SubcontractingController(StockController):
s-aga-r6d89b2f2022-06-18 15:46:59 +053023 def __init__(self, *args, **kwargs):
Akhil Narang3effaf22024-03-27 11:37:26 +053024 super().__init__(*args, **kwargs)
s-aga-r6d89b2f2022-06-18 15:46:59 +053025 if self.get("is_old_subcontracting_flow"):
26 self.subcontract_data = frappe._dict(
27 {
28 "order_doctype": "Purchase Order",
29 "order_field": "purchase_order",
30 "rm_detail_field": "po_detail",
31 "receipt_supplied_items_field": "Purchase Receipt Item Supplied",
32 "order_supplied_items_field": "Purchase Order Item Supplied",
33 }
34 )
35 else:
36 self.subcontract_data = frappe._dict(
37 {
38 "order_doctype": "Subcontracting Order",
39 "order_field": "subcontracting_order",
40 "rm_detail_field": "sco_rm_detail",
41 "receipt_supplied_items_field": "Subcontracting Receipt Supplied Item",
42 "order_supplied_items_field": "Subcontracting Order Supplied Item",
43 }
44 )
45
Sagar Sharma29a1cb82022-04-26 17:29:45 +053046 def before_validate(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +053047 if self.doctype in ["Subcontracting Order", "Subcontracting Receipt"]:
48 self.remove_empty_rows()
49 self.set_items_conversion_factor()
Sagar Sharma29a1cb82022-04-26 17:29:45 +053050
51 def validate(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +053052 if self.doctype in ["Subcontracting Order", "Subcontracting Receipt"]:
53 self.validate_items()
54 self.create_raw_materials_supplied()
55 else:
Akhil Narang3effaf22024-03-27 11:37:26 +053056 super().validate()
Sagar Sharma29a1cb82022-04-26 17:29:45 +053057
s-aga-ra33b75f2023-08-24 16:37:57 +053058 def validate_rejected_warehouse(self):
59 for item in self.get("items"):
60 if flt(item.rejected_qty) and not item.rejected_warehouse:
61 if self.rejected_warehouse:
62 item.rejected_warehouse = self.rejected_warehouse
63 else:
64 frappe.throw(
65 _("Row #{0}: Rejected Warehouse is mandatory for the rejected Item {1}").format(
66 item.idx, item.item_code
67 )
68 )
69
70 if item.get("rejected_warehouse") and (item.get("rejected_warehouse") == item.get("warehouse")):
71 frappe.throw(
72 _("Row #{0}: Accepted Warehouse and Rejected Warehouse cannot be same").format(item.idx)
73 )
74
Sagar Sharma29a1cb82022-04-26 17:29:45 +053075 def remove_empty_rows(self):
76 for key in ["service_items", "items", "supplied_items"]:
77 if self.get(key):
78 idx = 1
79 for item in self.get(key)[:]:
80 if not (item.get("item_code") or item.get("main_item_code")):
81 self.get(key).remove(item)
82 else:
83 item.idx = idx
84 idx += 1
85
86 def set_items_conversion_factor(self):
87 for item in self.get("items"):
88 if not item.conversion_factor:
89 item.conversion_factor = 1
90
91 def validate_items(self):
92 for item in self.items:
Sagar Sharmafa229062022-09-30 16:18:15 +053093 is_stock_item, is_sub_contracted_item = frappe.get_value(
94 "Item", item.item_code, ["is_stock_item", "is_sub_contracted_item"]
95 )
96
97 if not is_stock_item:
s-aga-rb26e96c2023-01-12 13:41:53 +053098 frappe.throw(_("Row {0}: Item {1} must be a stock item.").format(item.idx, item.item_name))
Sagar Sharmafa229062022-09-30 16:18:15 +053099
s-aga-rafd7d592023-08-26 13:10:47 +0530100 if not item.get("is_scrap_item"):
s-aga-ra33b75f2023-08-24 16:37:57 +0530101 if not is_sub_contracted_item:
102 frappe.throw(
103 _("Row {0}: Item {1} must be a subcontracted item.").format(item.idx, item.item_name)
104 )
Sagar Sharmafa229062022-09-30 16:18:15 +0530105
s-aga-ra33b75f2023-08-24 16:37:57 +0530106 if item.bom:
107 is_active, bom_item = frappe.get_value("BOM", item.bom, ["is_active", "item"])
108
109 if not is_active:
110 frappe.throw(
Akhil Narang3effaf22024-03-27 11:37:26 +0530111 _("Row {0}: Please select an active BOM for Item {1}.").format(
112 item.idx, item.item_name
113 )
s-aga-ra33b75f2023-08-24 16:37:57 +0530114 )
115 if bom_item != item.item_code:
116 frappe.throw(
Akhil Narang3effaf22024-03-27 11:37:26 +0530117 _("Row {0}: Please select an valid BOM for Item {1}.").format(
118 item.idx, item.item_name
119 )
s-aga-ra33b75f2023-08-24 16:37:57 +0530120 )
121 else:
Akhil Narang3effaf22024-03-27 11:37:26 +0530122 frappe.throw(
123 _("Row {0}: Please select a BOM for Item {1}.").format(item.idx, item.item_name)
124 )
Sagar Sharma760c26e2022-11-05 15:50:39 +0530125 else:
s-aga-ra33b75f2023-08-24 16:37:57 +0530126 item.bom = None
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530127
128 def __get_data_before_save(self):
129 item_dict = {}
s-aga-r6d89b2f2022-06-18 15:46:59 +0530130 if (
131 self.doctype in ["Purchase Receipt", "Purchase Invoice", "Subcontracting Receipt"]
132 and self._doc_before_save
133 ):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530134 for row in self._doc_before_save.get("items"):
s-aga-r01f56c62022-11-15 14:32:16 +0530135 item_dict[row.name] = (row.item_code, row.qty)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530136
137 return item_dict
138
139 def __identify_change_in_item_table(self):
140 self.__changed_name = []
141 self.__reference_name = []
142
s-aga-r6d89b2f2022-06-18 15:46:59 +0530143 if self.doctype in ["Purchase Order", "Subcontracting Order"] or self.is_new():
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530144 self.set(self.raw_material_table, [])
145 return
146
147 item_dict = self.__get_data_before_save()
148 if not item_dict:
149 return True
150
151 for row in self.items:
152 self.__reference_name.append(row.name)
s-aga-r01f56c62022-11-15 14:32:16 +0530153 if (row.name not in item_dict) or (row.item_code, row.qty) != item_dict[row.name]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530154 self.__changed_name.append(row.name)
155
156 if item_dict.get(row.name):
157 del item_dict[row.name]
158
159 self.__changed_name.extend(item_dict.keys())
160
161 def __get_backflush_based_on(self):
162 self.backflush_based_on = frappe.db.get_single_value(
163 "Buying Settings", "backflush_raw_materials_of_subcontract_based_on"
164 )
165
166 def initialized_fields(self):
167 self.available_materials = frappe._dict()
168 self.__transferred_items = frappe._dict()
169 self.alternative_item_details = frappe._dict()
170 self.__get_backflush_based_on()
171
s-aga-r6d89b2f2022-06-18 15:46:59 +0530172 def __get_subcontract_orders(self):
173 self.subcontract_orders = []
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530174
s-aga-r6d89b2f2022-06-18 15:46:59 +0530175 if self.doctype in ["Purchase Order", "Subcontracting Order"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530176 return
177
s-aga-r6d89b2f2022-06-18 15:46:59 +0530178 self.subcontract_orders = [
179 item.get(self.subcontract_data.order_field)
180 for item in self.items
181 if item.get(self.subcontract_data.order_field)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530182 ]
183
184 def __get_pending_qty_to_receive(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530185 """Get qty to be received against the subcontract order."""
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530186
187 self.qty_to_be_received = defaultdict(float)
188
189 if (
s-aga-r6d89b2f2022-06-18 15:46:59 +0530190 self.doctype != self.subcontract_data.order_doctype
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530191 and self.backflush_based_on != "BOM"
s-aga-r6d89b2f2022-06-18 15:46:59 +0530192 and self.subcontract_orders
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530193 ):
194 for row in frappe.get_all(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530195 f"{self.subcontract_data.order_doctype} Item",
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530196 fields=["item_code", "(qty - received_qty) as qty", "parent", "name"],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530197 filters={"docstatus": 1, "parent": ("in", self.subcontract_orders)},
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530198 ):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530199 self.qty_to_be_received[(row.item_code, row.parent)] += row.qty
200
201 def __get_transferred_items(self):
s-aga-r2a608842023-06-29 18:59:18 +0530202 se = frappe.qb.DocType("Stock Entry")
203 se_detail = frappe.qb.DocType("Stock Entry Detail")
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530204
s-aga-r2a608842023-06-29 18:59:18 +0530205 query = (
206 frappe.qb.from_(se)
207 .inner_join(se_detail)
208 .on(se.name == se_detail.parent)
209 .select(
210 se[self.subcontract_data.order_field],
211 se.name.as_("voucher_no"),
212 se_detail.item_code.as_("rm_item_code"),
213 se_detail.item_name,
214 se_detail.description,
215 (
216 frappe.qb.terms.Case()
217 .when(((se.purpose == "Material Transfer") & (se.is_return == 1)), -1 * se_detail.qty)
218 .else_(se_detail.qty)
219 ).as_("qty"),
220 se_detail.basic_rate.as_("rate"),
221 se_detail.amount,
222 se_detail.serial_no,
223 se_detail.serial_and_batch_bundle,
224 se_detail.uom,
225 se_detail.subcontracted_item.as_("main_item_code"),
226 se_detail.stock_uom,
227 se_detail.batch_no,
228 se_detail.conversion_factor,
229 se_detail.s_warehouse,
230 se_detail.t_warehouse,
231 se_detail.item_group,
232 se_detail[self.subcontract_data.rm_detail_field],
233 )
234 .where(
235 (se.docstatus == 1)
236 & (se[self.subcontract_data.order_field].isin(self.subcontract_orders))
237 & (
238 (se.purpose == "Send to Subcontractor")
239 | ((se.purpose == "Material Transfer") & (se.is_return == 1))
240 )
241 )
242 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530243
244 if self.backflush_based_on == "BOM":
s-aga-r2a608842023-06-29 18:59:18 +0530245 query = query.select(se_detail.original_item)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530246
s-aga-r2a608842023-06-29 18:59:18 +0530247 return query.run(as_dict=True)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530248
249 def __set_alternative_item_details(self, row):
250 if row.get("original_item"):
251 self.alternative_item_details[row.get("original_item")] = row
252
253 def __get_received_items(self, doctype):
254 fields = []
s-aga-r6d89b2f2022-06-18 15:46:59 +0530255 for field in ["name", self.subcontract_data.order_field, "parent"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530256 fields.append(f"`tab{doctype} Item`.`{field}`")
257
258 filters = [
259 [doctype, "docstatus", "=", 1],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530260 [f"{doctype} Item", self.subcontract_data.order_field, "in", self.subcontract_orders],
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530261 ]
s-aga-r6d89b2f2022-06-18 15:46:59 +0530262 if doctype == "Purchase Invoice":
263 filters.append(["Purchase Invoice", "update_stock", "=", 1])
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530264
265 return frappe.get_all(f"{doctype}", fields=fields, filters=filters)
266
s-aga-r6d89b2f2022-06-18 15:46:59 +0530267 def __get_consumed_items(self, doctype, receipt_items):
rohitwaghchaure5cf47ae2024-01-29 20:41:26 +0530268 fields = [
269 "serial_no",
270 "rm_item_code",
271 "reference_name",
272 "batch_no",
273 "consumed_qty",
274 "main_item_code",
275 "parent as voucher_no",
276 ]
277
278 if self.subcontract_data.receipt_supplied_items_field != "Purchase Receipt Item Supplied":
279 fields.append("serial_and_batch_bundle")
280
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530281 return frappe.get_all(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530282 self.subcontract_data.receipt_supplied_items_field,
rohitwaghchaure5cf47ae2024-01-29 20:41:26 +0530283 fields=fields,
s-aga-r6d89b2f2022-06-18 15:46:59 +0530284 filters={"docstatus": 1, "reference_name": ("in", list(receipt_items)), "parenttype": doctype},
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530285 )
286
287 def __update_consumed_materials(self, doctype, return_consumed_items=False):
288 """Deduct the consumed materials from the available materials."""
289
s-aga-r6d89b2f2022-06-18 15:46:59 +0530290 receipt_items = self.__get_received_items(doctype)
291 if not receipt_items:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530292 return ([], {}) if return_consumed_items else None
293
Akhil Narang3effaf22024-03-27 11:37:26 +0530294 receipt_items = {item.name: item.get(self.subcontract_data.order_field) for item in receipt_items}
s-aga-r6d89b2f2022-06-18 15:46:59 +0530295 consumed_materials = self.__get_consumed_items(doctype, receipt_items.keys())
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530296
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530297 voucher_nos = [d.voucher_no for d in consumed_materials if d.voucher_no]
298 voucher_bundle_data = get_voucher_wise_serial_batch_from_bundle(
299 voucher_no=voucher_nos,
300 is_outward=1,
301 get_subcontracted_item=("Subcontracting Receipt Supplied Item", "main_item_code"),
302 )
303
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530304 if return_consumed_items:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530305 return (consumed_materials, receipt_items)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530306
307 for row in consumed_materials:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530308 key = (row.rm_item_code, row.main_item_code, receipt_items.get(row.reference_name))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530309 if not self.available_materials.get(key):
310 continue
311
312 self.available_materials[key]["qty"] -= row.consumed_qty
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530313
314 bundle_key = (row.rm_item_code, row.main_item_code, self.supplier_warehouse, row.voucher_no)
315 consumed_bundles = voucher_bundle_data.get(bundle_key, frappe._dict())
316
317 if consumed_bundles.serial_nos:
318 self.available_materials[key]["serial_no"] = list(
319 set(self.available_materials[key]["serial_no"]) - set(consumed_bundles.serial_nos)
320 )
321
322 if consumed_bundles.batch_nos:
323 for batch_no, qty in consumed_bundles.batch_nos.items():
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530324 if qty:
325 # Conumed qty is negative therefore added it instead of subtracting
326 self.available_materials[key]["batch_no"][batch_no] += qty
327 consumed_bundles.batch_nos[batch_no] += abs(qty)
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530328
Rohit Waghchaure46704642023-03-23 11:41:20 +0530329 # Will be deprecated in v16
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530330 if row.serial_no:
331 self.available_materials[key]["serial_no"] = list(
332 set(self.available_materials[key]["serial_no"]) - set(get_serial_nos(row.serial_no))
333 )
334
Rohit Waghchaure46704642023-03-23 11:41:20 +0530335 # Will be deprecated in v16
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530336 if row.batch_no:
337 self.available_materials[key]["batch_no"][row.batch_no] -= row.consumed_qty
338
339 def get_available_materials(self):
340 """Get the available raw materials which has been transferred to the supplier.
341 available_materials = {
s-aga-r6d89b2f2022-06-18 15:46:59 +0530342 (item_code, subcontracted_item, subcontract_order): {
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530343 'qty': 1, 'serial_no': [ABC], 'batch_no': {'batch1': 1}, 'data': item_details
344 }
345 }
346 """
s-aga-r6d89b2f2022-06-18 15:46:59 +0530347 if not self.subcontract_orders:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530348 return
349
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530350 transferred_items = self.__get_transferred_items()
351
352 voucher_nos = [row.voucher_no for row in transferred_items]
353 voucher_bundle_data = get_voucher_wise_serial_batch_from_bundle(
354 voucher_no=voucher_nos,
355 is_outward=0,
356 get_subcontracted_item=("Stock Entry Detail", "subcontracted_item"),
357 )
358
359 for row in transferred_items:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530360 key = (row.rm_item_code, row.main_item_code, row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530361
362 if key not in self.available_materials:
363 self.available_materials.setdefault(
364 key,
365 frappe._dict(
366 {
367 "qty": 0,
368 "serial_no": [],
369 "batch_no": defaultdict(float),
370 "item_details": row,
s-aga-r6d89b2f2022-06-18 15:46:59 +0530371 f"{self.subcontract_data.rm_detail_field}s": [],
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530372 }
373 ),
374 )
375
376 details = self.available_materials[key]
377 details.qty += row.qty
s-aga-r6d89b2f2022-06-18 15:46:59 +0530378 details[f"{self.subcontract_data.rm_detail_field}s"].append(
379 row.get(self.subcontract_data.rm_detail_field)
380 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530381
382 if row.serial_no:
383 details.serial_no.extend(get_serial_nos(row.serial_no))
384
Rohit Waghchaure34233342024-03-21 20:28:16 +0530385 elif row.batch_no:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530386 details.batch_no[row.batch_no] += row.qty
387
Rohit Waghchaure34233342024-03-21 20:28:16 +0530388 elif voucher_bundle_data:
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530389 bundle_key = (row.rm_item_code, row.main_item_code, row.t_warehouse, row.voucher_no)
390
391 bundle_data = voucher_bundle_data.get(bundle_key, frappe._dict())
392 if bundle_data.serial_nos:
393 details.serial_no.extend(bundle_data.serial_nos)
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530394 bundle_data.serial_nos = []
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530395
396 if bundle_data.batch_nos:
397 for batch_no, qty in bundle_data.batch_nos.items():
Rohit Waghchaure34233342024-03-21 20:28:16 +0530398 if qty < 0:
399 qty = abs(qty)
400
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530401 if qty > 0:
402 details.batch_no[batch_no] += qty
403 bundle_data.batch_nos[batch_no] -= qty
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530404
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530405 self.__set_alternative_item_details(row)
406
407 self.__transferred_items = copy.deepcopy(self.available_materials)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530408 if self.get("is_old_subcontracting_flow"):
409 for doctype in ["Purchase Receipt", "Purchase Invoice"]:
410 self.__update_consumed_materials(doctype)
411 else:
412 self.__update_consumed_materials("Subcontracting Receipt")
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530413
414 def __remove_changed_rows(self):
415 if not self.__changed_name:
416 return
417
418 i = 1
419 self.set(self.raw_material_table, [])
420 for item in self._doc_before_save.supplied_items:
421 if item.reference_name in self.__changed_name:
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530422 self.__remove_serial_and_batch_bundle(item)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530423 continue
424
425 if item.reference_name not in self.__reference_name:
426 continue
427
428 item.idx = i
429 self.append("supplied_items", item)
430
431 i += 1
432
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530433 def __remove_serial_and_batch_bundle(self, item):
434 if item.serial_and_batch_bundle:
435 frappe.delete_doc("Serial and Batch Bundle", item.serial_and_batch_bundle, force=True)
436
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530437 def __get_materials_from_bom(self, item_code, bom_no, exploded_item=0):
438 doctype = "BOM Item" if not exploded_item else "BOM Explosion Item"
439 fields = [f"`tab{doctype}`.`stock_qty` / `tabBOM`.`quantity` as qty_consumed_per_unit"]
440
441 alias_dict = {
442 "item_code": "rm_item_code",
443 "name": "bom_detail_no",
444 "source_warehouse": "reserve_warehouse",
445 }
446 for field in [
447 "item_code",
448 "name",
449 "rate",
450 "stock_uom",
451 "source_warehouse",
452 "description",
453 "item_name",
454 "stock_uom",
455 ]:
456 fields.append(f"`tab{doctype}`.`{field}` As {alias_dict.get(field, field)}")
457
458 filters = [
459 [doctype, "parent", "=", bom_no],
460 [doctype, "docstatus", "=", 1],
461 ["BOM", "item", "=", item_code],
462 [doctype, "sourced_by_supplier", "=", 0],
463 ]
464
Akhil Narang3effaf22024-03-27 11:37:26 +0530465 return frappe.get_all("BOM", fields=fields, filters=filters, order_by=f"`tab{doctype}`.`idx`") or []
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530466
467 def __update_reserve_warehouse(self, row, item):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530468 if self.doctype == self.subcontract_data.order_doctype:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530469 row.reserve_warehouse = self.set_reserve_warehouse or item.warehouse
470
471 def __set_alternative_item(self, bom_item):
472 if self.alternative_item_details.get(bom_item.rm_item_code):
473 bom_item.update(self.alternative_item_details[bom_item.rm_item_code])
474
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530475 def __set_serial_and_batch_bundle(self, item_row, rm_obj, qty):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530476 key = (rm_obj.rm_item_code, item_row.item_code, item_row.get(self.subcontract_data.order_field))
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530477 if not self.available_materials.get(key):
478 return
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530479
Akhil Narang3effaf22024-03-27 11:37:26 +0530480 if not self.available_materials[key]["serial_no"] and not self.available_materials[key]["batch_no"]:
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530481 return
Rohit Waghchaure156e4592023-02-16 13:21:17 +0530482
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530483 serial_nos = []
484 batches = frappe._dict({})
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530485
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530486 if self.available_materials.get(key) and self.available_materials[key]["serial_no"]:
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530487 serial_nos = self.__get_serial_nos_for_bundle(qty, key)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530488
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530489 elif self.available_materials.get(key) and self.available_materials[key]["batch_no"]:
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530490 batches = self.__get_batch_nos_for_bundle(qty, key)
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530491
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530492 bundle = SerialBatchCreation(
493 frappe._dict(
494 {
495 "company": self.company,
496 "item_code": rm_obj.rm_item_code,
497 "warehouse": self.supplier_warehouse,
498 "qty": qty,
499 "serial_nos": serial_nos,
500 "batches": batches,
501 "posting_date": self.posting_date,
502 "posting_time": self.posting_time,
503 "voucher_type": "Subcontracting Receipt",
504 "do_not_submit": True,
505 "type_of_transaction": "Outward" if qty > 0 else "Inward",
506 }
507 )
508 ).make_serial_and_batch_bundle()
509
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530510 return bundle.name
511
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530512 def __get_batch_nos_for_bundle(self, qty, key):
513 available_batches = defaultdict(float)
514
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530515 for batch_no, batch_qty in self.available_materials[key]["batch_no"].items():
516 qty_to_consumed = 0
517 if qty > 0:
518 if batch_qty >= qty:
519 qty_to_consumed = qty
520 else:
521 qty_to_consumed = batch_qty
522
523 qty -= qty_to_consumed
524 if qty_to_consumed > 0:
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530525 available_batches[batch_no] += qty_to_consumed
526 self.available_materials[key]["batch_no"][batch_no] -= qty_to_consumed
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530527
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530528 return available_batches
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530529
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530530 def __get_serial_nos_for_bundle(self, qty, key):
531 available_sns = sorted(self.available_materials[key]["serial_no"])[0 : cint(qty)]
532 serial_nos = []
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530533
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530534 for serial_no in available_sns:
535 serial_nos.append(serial_no)
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530536
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530537 self.available_materials[key]["serial_no"].remove(serial_no)
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530538
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530539 return serial_nos
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530540
541 def __add_supplied_item(self, item_row, bom_item, qty):
542 bom_item.conversion_factor = item_row.conversion_factor
543 rm_obj = self.append(self.raw_material_table, bom_item)
Rohit Waghchaure2fb04992024-02-15 14:58:34 +0530544 if rm_obj.get("qty"):
545 # Qty field not exists
546 rm_obj.qty = 0.0
547
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530548 rm_obj.reference_name = item_row.name
549
Rohit Waghchaure34233342024-03-21 20:28:16 +0530550 use_serial_batch_fields = frappe.db.get_single_value("Stock Settings", "use_serial_batch_fields")
551
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530552 if self.doctype == self.subcontract_data.order_doctype:
553 rm_obj.required_qty = qty
554 rm_obj.amount = rm_obj.required_qty * rm_obj.rate
555 else:
556 rm_obj.consumed_qty = qty
557 rm_obj.required_qty = bom_item.required_qty or qty
Rohit Waghchaure34233342024-03-21 20:28:16 +0530558 rm_obj.serial_and_batch_bundle = None
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530559 setattr(
560 rm_obj, self.subcontract_data.order_field, item_row.get(self.subcontract_data.order_field)
561 )
562
Rohit Waghchaure34233342024-03-21 20:28:16 +0530563 if use_serial_batch_fields:
564 rm_obj.use_serial_batch_fields = 1
565 self.__set_batch_nos(bom_item, item_row, rm_obj, qty)
566
567 if self.doctype == "Subcontracting Receipt" and not use_serial_batch_fields:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530568 args = frappe._dict(
569 {
570 "item_code": rm_obj.rm_item_code,
571 "warehouse": self.supplier_warehouse,
572 "posting_date": self.posting_date,
573 "posting_time": self.posting_time,
574 "qty": -1 * flt(rm_obj.consumed_qty),
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530575 "actual_qty": -1 * flt(rm_obj.consumed_qty),
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530576 "voucher_type": self.doctype,
577 "voucher_no": self.name,
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530578 "voucher_detail_no": item_row.name,
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530579 "company": self.company,
580 "allow_zero_valuation": 1,
581 }
582 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530583
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530584 rm_obj.serial_and_batch_bundle = self.__set_serial_and_batch_bundle(
585 item_row, rm_obj, rm_obj.consumed_qty
586 )
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530587
588 if rm_obj.serial_and_batch_bundle:
589 args["serial_and_batch_bundle"] = rm_obj.serial_and_batch_bundle
590
s-aga-r758b31d2023-08-05 19:28:38 +0530591 rm_obj.rate = get_incoming_rate(args)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530592
Rohit Waghchaure34233342024-03-21 20:28:16 +0530593 def __set_batch_nos(self, bom_item, item_row, rm_obj, qty):
594 key = (rm_obj.rm_item_code, item_row.item_code, item_row.get(self.subcontract_data.order_field))
595
596 if self.available_materials.get(key) and self.available_materials[key]["batch_no"]:
597 new_rm_obj = None
598 for batch_no, batch_qty in self.available_materials[key]["batch_no"].items():
599 if batch_qty >= qty or (
600 rm_obj.consumed_qty == 0
601 and self.backflush_based_on == "BOM"
602 and len(self.available_materials[key]["batch_no"]) == 1
603 ):
604 if rm_obj.consumed_qty == 0:
605 self.__set_consumed_qty(rm_obj, qty)
606
607 self.__set_batch_no_as_per_qty(item_row, rm_obj, batch_no, qty)
608 self.available_materials[key]["batch_no"][batch_no] -= qty
609 return
610
611 elif qty > 0 and batch_qty > 0:
612 qty -= batch_qty
613 new_rm_obj = self.append(self.raw_material_table, bom_item)
614 new_rm_obj.serial_and_batch_bundle = None
615 new_rm_obj.use_serial_batch_fields = 1
616 new_rm_obj.reference_name = item_row.name
617 self.__set_batch_no_as_per_qty(item_row, new_rm_obj, batch_no, batch_qty)
618 self.available_materials[key]["batch_no"][batch_no] = 0
619
620 if new_rm_obj:
621 self.remove(rm_obj)
622 elif abs(qty) > 0:
623 self.__set_consumed_qty(rm_obj, qty)
624
625 else:
626 self.__set_consumed_qty(rm_obj, qty, bom_item.required_qty or qty)
627 self.__set_serial_nos(item_row, rm_obj)
628
629 def __set_consumed_qty(self, rm_obj, consumed_qty, required_qty=0):
630 rm_obj.required_qty = required_qty
631 rm_obj.consumed_qty = consumed_qty
632
633 def __set_serial_nos(self, item_row, rm_obj):
634 key = (rm_obj.rm_item_code, item_row.item_code, item_row.get(self.subcontract_data.order_field))
635 if self.available_materials.get(key) and self.available_materials[key]["serial_no"]:
636 used_serial_nos = self.available_materials[key]["serial_no"][0 : cint(rm_obj.consumed_qty)]
637 rm_obj.serial_no = "\n".join(used_serial_nos)
638
639 # Removed the used serial nos from the list
640 for sn in used_serial_nos:
641 self.available_materials[key]["serial_no"].remove(sn)
642
643 def __set_batch_no_as_per_qty(self, item_row, rm_obj, batch_no, qty):
644 rm_obj.update(
645 {
646 "consumed_qty": qty,
647 "batch_no": batch_no,
648 "required_qty": qty,
649 self.subcontract_data.order_field: item_row.get(self.subcontract_data.order_field),
650 }
651 )
652
653 self.__set_serial_nos(item_row, rm_obj)
654
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530655 def __get_qty_based_on_material_transfer(self, item_row, transfer_item):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530656 key = (item_row.item_code, item_row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530657
s-aga-r01f56c62022-11-15 14:32:16 +0530658 if self.qty_to_be_received == item_row.qty:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530659 return transfer_item.qty
660
661 if self.qty_to_be_received:
s-aga-r01f56c62022-11-15 14:32:16 +0530662 qty = (flt(item_row.qty) * flt(transfer_item.qty)) / flt(self.qty_to_be_received.get(key, 0))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530663 transfer_item.item_details.required_qty = transfer_item.qty
664
665 if transfer_item.serial_no or frappe.get_cached_value(
666 "UOM", transfer_item.item_details.stock_uom, "must_be_whole_number"
667 ):
668 return frappe.utils.ceil(qty)
669
670 return qty
671
672 def __set_supplied_items(self):
673 self.bom_items = {}
674
675 has_supplied_items = True if self.get(self.raw_material_table) else False
676 for row in self.items:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530677 if self.doctype != self.subcontract_data.order_doctype and (
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530678 (self.__changed_name and row.name not in self.__changed_name)
679 or (has_supplied_items and not self.__changed_name)
680 ):
681 continue
682
s-aga-r6d89b2f2022-06-18 15:46:59 +0530683 if self.doctype == self.subcontract_data.order_doctype or self.backflush_based_on == "BOM":
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530684 for bom_item in self.__get_materials_from_bom(
685 row.item_code, row.bom, row.get("include_exploded_items")
686 ):
s-aga-r01f56c62022-11-15 14:32:16 +0530687 qty = flt(bom_item.qty_consumed_per_unit) * flt(row.qty) * row.conversion_factor
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530688 bom_item.main_item_code = row.item_code
689 self.__update_reserve_warehouse(bom_item, row)
690 self.__set_alternative_item(bom_item)
691 self.__add_supplied_item(row, bom_item, qty)
692
693 elif self.backflush_based_on != "BOM":
694 for key, transfer_item in self.available_materials.items():
s-aga-r6d89b2f2022-06-18 15:46:59 +0530695 if (key[1], key[2]) == (
696 row.item_code,
697 row.get(self.subcontract_data.order_field),
698 ) and transfer_item.qty > 0:
Sagar Sharmaaddd7342022-08-19 11:46:27 +0530699 qty = flt(self.__get_qty_based_on_material_transfer(row, transfer_item))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530700 transfer_item.qty -= qty
701 self.__add_supplied_item(row, transfer_item.get("item_details"), qty)
702
703 if self.qty_to_be_received:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530704 self.qty_to_be_received[
705 (row.item_code, row.get(self.subcontract_data.order_field))
706 ] -= row.qty
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530707
rohitwaghchaure3e77c0b2023-11-14 19:27:41 +0530708 def __set_rate_for_serial_and_batch_bundle(self):
709 if self.doctype != "Subcontracting Receipt":
710 return
711
712 for row in self.get(self.raw_material_table):
713 if not row.get("serial_and_batch_bundle"):
714 continue
715
716 row.rate = frappe.get_cached_value(
717 "Serial and Batch Bundle", row.serial_and_batch_bundle, "avg_rate"
718 )
719
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530720 def __modify_serial_and_batch_bundle(self):
721 if self.is_new():
722 return
723
724 if self.doctype != "Subcontracting Receipt":
725 return
726
727 for item_row in self.items:
728 if self.__changed_name and item_row.name in self.__changed_name:
729 continue
730
731 modified_data = self.__get_bundle_to_modify(item_row.name)
732 if modified_data:
733 serial_nos = []
734 batches = frappe._dict({})
735 key = (
736 modified_data.rm_item_code,
737 item_row.item_code,
738 item_row.get(self.subcontract_data.order_field),
739 )
740
741 if self.available_materials.get(key) and self.available_materials[key]["serial_no"]:
742 serial_nos = self.__get_serial_nos_for_bundle(modified_data.consumed_qty, key)
743
744 elif self.available_materials.get(key) and self.available_materials[key]["batch_no"]:
745 batches = self.__get_batch_nos_for_bundle(modified_data.consumed_qty, key)
746
747 SerialBatchCreation(
748 {
749 "item_code": modified_data.rm_item_code,
750 "warehouse": self.supplier_warehouse,
751 "serial_and_batch_bundle": modified_data.serial_and_batch_bundle,
752 "type_of_transaction": "Outward",
753 "serial_nos": serial_nos,
754 "batches": batches,
755 "qty": modified_data.consumed_qty * -1,
756 }
757 ).update_serial_and_batch_entries()
758
759 def __get_bundle_to_modify(self, name):
760 for row in self.get("supplied_items"):
761 if row.reference_name == name and row.serial_and_batch_bundle:
762 if row.consumed_qty != abs(
Akhil Narang3effaf22024-03-27 11:37:26 +0530763 frappe.get_cached_value(
764 "Serial and Batch Bundle", row.serial_and_batch_bundle, "total_qty"
765 )
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530766 ):
767 return row
768
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530769 def __prepare_supplied_items(self):
770 self.initialized_fields()
s-aga-r6d89b2f2022-06-18 15:46:59 +0530771 self.__get_subcontract_orders()
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530772 self.__get_pending_qty_to_receive()
773 self.get_available_materials()
774 self.__remove_changed_rows()
775 self.__set_supplied_items()
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530776 self.__modify_serial_and_batch_bundle()
rohitwaghchaure3e77c0b2023-11-14 19:27:41 +0530777 self.__set_rate_for_serial_and_batch_bundle()
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530778
779 def __validate_batch_no(self, row, key):
780 if row.get("batch_no") and row.get("batch_no") not in self.__transferred_items.get(key).get(
781 "batch_no"
782 ):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530783 link = get_link_to_form(
784 self.subcontract_data.order_doctype, row.get(self.subcontract_data.order_field)
785 )
786 msg = f'The Batch No {frappe.bold(row.get("batch_no"))} has not supplied against the {self.subcontract_data.order_doctype} {link}'
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530787 frappe.throw(_(msg), title=_("Incorrect Batch Consumed"))
788
789 def __validate_serial_no(self, row, key):
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530790 if row.get("serial_and_batch_bundle") and self.__transferred_items.get(key).get("serial_no"):
791 serial_nos = get_serial_nos_from_bundle(row.get("serial_and_batch_bundle"))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530792 incorrect_sn = set(serial_nos).difference(self.__transferred_items.get(key).get("serial_no"))
793
794 if incorrect_sn:
795 incorrect_sn = "\n".join(incorrect_sn)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530796 link = get_link_to_form(
797 self.subcontract_data.order_doctype, row.get(self.subcontract_data.order_field)
798 )
799 msg = f"The Serial Nos {incorrect_sn} has not supplied against the {self.subcontract_data.order_doctype} {link}"
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530800 frappe.throw(_(msg), title=_("Incorrect Serial Number Consumed"))
801
802 def __validate_supplied_items(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530803 if self.doctype not in ["Purchase Invoice", "Purchase Receipt", "Subcontracting Receipt"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530804 return
805
806 for row in self.get(self.raw_material_table):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530807 key = (row.rm_item_code, row.main_item_code, row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530808 if not self.__transferred_items or not self.__transferred_items.get(key):
809 return
810
811 self.__validate_batch_no(row, key)
812 self.__validate_serial_no(row, key)
813
814 def set_materials_for_subcontracted_items(self, raw_material_table):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530815 if self.doctype == "Purchase Invoice" and not self.update_stock:
816 return
817
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530818 self.raw_material_table = raw_material_table
819 self.__identify_change_in_item_table()
820 self.__prepare_supplied_items()
821 self.__validate_supplied_items()
822
823 def create_raw_materials_supplied(self, raw_material_table="supplied_items"):
824 self.set_materials_for_subcontracted_items(raw_material_table)
825
s-aga-r6d89b2f2022-06-18 15:46:59 +0530826 if self.doctype in ["Subcontracting Receipt", "Purchase Receipt", "Purchase Invoice"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530827 for item in self.get("items"):
828 item.rm_supp_cost = 0.0
829
s-aga-r6d89b2f2022-06-18 15:46:59 +0530830 def __update_consumed_qty_in_subcontract_order(self, itemwise_consumed_qty):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530831 fields = ["main_item_code", "rm_item_code", "parent", "supplied_qty", "name"]
s-aga-r6d89b2f2022-06-18 15:46:59 +0530832 filters = {"docstatus": 1, "parent": ("in", self.subcontract_orders)}
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530833
834 for row in frappe.get_all(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530835 self.subcontract_data.order_supplied_items_field, fields=fields, filters=filters, order_by="idx"
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530836 ):
837 key = (row.rm_item_code, row.main_item_code, row.parent)
838 consumed_qty = itemwise_consumed_qty.get(key, 0)
839
840 if row.supplied_qty < consumed_qty:
841 consumed_qty = row.supplied_qty
842
843 itemwise_consumed_qty[key] -= consumed_qty
844 frappe.db.set_value(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530845 self.subcontract_data.order_supplied_items_field, row.name, "consumed_qty", consumed_qty
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530846 )
847
s-aga-r6d89b2f2022-06-18 15:46:59 +0530848 def set_consumed_qty_in_subcontract_order(self):
849 # Update consumed qty back in the subcontract order
850 if self.doctype in ["Subcontracting Order", "Subcontracting Receipt"] or self.get(
851 "is_old_subcontracting_flow"
852 ):
853 self.__get_subcontract_orders()
854 itemwise_consumed_qty = defaultdict(float)
855 if self.get("is_old_subcontracting_flow"):
856 doctypes = ["Purchase Receipt", "Purchase Invoice"]
857 else:
858 doctypes = ["Subcontracting Receipt"]
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530859
s-aga-r6d89b2f2022-06-18 15:46:59 +0530860 for doctype in doctypes:
861 consumed_items, receipt_items = self.__update_consumed_materials(
862 doctype, return_consumed_items=True
863 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530864
s-aga-r6d89b2f2022-06-18 15:46:59 +0530865 for row in consumed_items:
866 key = (row.rm_item_code, row.main_item_code, receipt_items.get(row.reference_name))
867 itemwise_consumed_qty[key] += row.consumed_qty
868
869 self.__update_consumed_qty_in_subcontract_order(itemwise_consumed_qty)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530870
871 def update_ordered_and_reserved_qty(self):
872 sco_map = {}
873 for item in self.get("items"):
874 if self.doctype == "Subcontracting Receipt" and item.subcontracting_order:
875 sco_map.setdefault(item.subcontracting_order, []).append(item.subcontracting_order_item)
876
877 for sco, sco_item_rows in sco_map.items():
878 if sco and sco_item_rows:
879 sco_doc = frappe.get_doc("Subcontracting Order", sco)
880
881 if sco_doc.status in ["Closed", "Cancelled"]:
882 frappe.throw(
883 _("{0} {1} is cancelled or closed").format(_("Subcontracting Order"), sco),
884 frappe.InvalidStatusError,
885 )
886
887 sco_doc.update_ordered_qty_for_subcontracting(sco_item_rows)
888 sco_doc.update_reserved_qty_for_subcontracting()
889
890 def make_sl_entries_for_supplier_warehouse(self, sl_entries):
891 if hasattr(self, "supplied_items"):
892 for item in self.get("supplied_items"):
893 # negative quantity is passed, as raw material qty has to be decreased
894 # when SCR is submitted and it has to be increased when SCR is cancelled
895 sl_entries.append(
896 self.get_sl_entries(
897 item,
898 {
899 "item_code": item.rm_item_code,
900 "warehouse": self.supplier_warehouse,
mergify[bot]d558ba22023-09-26 17:55:16 +0530901 "actual_qty": -1 * flt(item.consumed_qty, item.precision("consumed_qty")),
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530902 "dependant_sle_voucher_detail_no": item.reference_name,
903 },
904 )
905 )
906
907 def update_stock_ledger(self, allow_negative_stock=False, via_landed_cost_voucher=False):
908 self.update_ordered_and_reserved_qty()
909
910 sl_entries = []
911 stock_items = self.get_stock_items()
912
913 for item in self.get("items"):
914 if item.item_code in stock_items and item.warehouse:
915 scr_qty = flt(item.qty) * flt(item.conversion_factor)
916
917 if scr_qty:
Rohit Waghchaure16f26fb2023-03-20 22:56:06 +0530918 sle = self.get_sl_entries(item, {"actual_qty": flt(scr_qty)})
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530919 rate_db_precision = 6 if cint(self.precision("rate", item)) <= 6 else 9
920 incoming_rate = flt(item.rate, rate_db_precision)
921 sle.update(
922 {
923 "incoming_rate": incoming_rate,
924 "recalculate_rate": 1,
925 }
926 )
927 sl_entries.append(sle)
928
929 if flt(item.rejected_qty) != 0:
930 sl_entries.append(
931 self.get_sl_entries(
932 item,
933 {
934 "warehouse": item.rejected_warehouse,
rohitwaghchaure01856a62024-03-07 14:14:19 +0530935 "serial_and_batch_bundle": item.get("rejected_serial_and_batch_bundle"),
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530936 "actual_qty": flt(item.rejected_qty) * flt(item.conversion_factor),
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530937 "incoming_rate": 0.0,
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530938 },
939 )
940 )
941
942 self.make_sl_entries_for_supplier_warehouse(sl_entries)
943 self.make_sl_entries(
944 sl_entries,
945 allow_negative_stock=allow_negative_stock,
946 via_landed_cost_voucher=via_landed_cost_voucher,
947 )
948
s-aga-r6d89b2f2022-06-18 15:46:59 +0530949 def get_supplied_items_cost(self, item_row_id, reset_outgoing_rate=True):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530950 supplied_items_cost = 0.0
951 for item in self.get("supplied_items"):
952 if item.reference_name == item_row_id:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530953 if (
954 self.get("is_old_subcontracting_flow")
955 and reset_outgoing_rate
956 and frappe.get_cached_value("Item", item.rm_item_code, "is_stock_item")
957 ):
958 rate = get_incoming_rate(
959 {
960 "item_code": item.rm_item_code,
961 "warehouse": self.supplier_warehouse,
962 "posting_date": self.posting_date,
963 "posting_time": self.posting_time,
964 "qty": -1 * item.consumed_qty,
rohitwaghchaure5e9016f2023-12-01 21:42:22 +0530965 "voucher_detail_no": item.name,
rohitwaghchaure67d828d2024-01-27 12:00:06 +0530966 "serial_and_batch_bundle": item.get("serial_and_batch_bundle"),
967 "serial_no": item.get("serial_no"),
968 "batch_no": item.get("batch_no"),
s-aga-r6d89b2f2022-06-18 15:46:59 +0530969 }
970 )
971
972 if rate > 0:
973 item.rate = rate
974
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530975 item.amount = flt(flt(item.consumed_qty) * flt(item.rate), item.precision("amount"))
976 supplied_items_cost += item.amount
977
978 return supplied_items_cost
979
Sagar Sharma249726b2022-04-22 17:09:19 +0530980 def set_subcontracting_order_status(self):
981 if self.doctype == "Subcontracting Order":
982 self.update_status()
983 elif self.doctype == "Subcontracting Receipt":
s-aga-r6d89b2f2022-06-18 15:46:59 +0530984 self.__get_subcontract_orders
Sagar Sharma249726b2022-04-22 17:09:19 +0530985
s-aga-r6d89b2f2022-06-18 15:46:59 +0530986 if self.subcontract_orders:
987 for sco in set(self.subcontract_orders):
Sagar Sharma249726b2022-04-22 17:09:19 +0530988 sco_doc = frappe.get_doc("Subcontracting Order", sco)
989 sco_doc.update_status()
990
Sagar Sharmad6433f82023-05-12 11:45:33 +0530991 def calculate_additional_costs(self):
Sagar Sharmaea82fe52022-08-18 17:20:22 +0530992 self.total_additional_costs = sum(flt(item.amount) for item in self.get("additional_costs"))
993
994 if self.total_additional_costs:
995 if self.distribute_additional_costs_based_on == "Amount":
s-aga-r1504ff82023-08-25 20:18:30 +0530996 total_amt = sum(
997 flt(item.amount) for item in self.get("items") if not item.get("is_scrap_item")
998 )
Sagar Sharmaea82fe52022-08-18 17:20:22 +0530999 for item in self.items:
s-aga-r1504ff82023-08-25 20:18:30 +05301000 if not item.get("is_scrap_item"):
1001 item.additional_cost_per_qty = (
1002 (item.amount * self.total_additional_costs) / total_amt
1003 ) / item.qty
Sagar Sharmaea82fe52022-08-18 17:20:22 +05301004 else:
s-aga-r1504ff82023-08-25 20:18:30 +05301005 total_qty = sum(flt(item.qty) for item in self.get("items") if not item.get("is_scrap_item"))
Sagar Sharmaea82fe52022-08-18 17:20:22 +05301006 additional_cost_per_qty = self.total_additional_costs / total_qty
1007 for item in self.items:
s-aga-r1504ff82023-08-25 20:18:30 +05301008 if not item.get("is_scrap_item"):
1009 item.additional_cost_per_qty = additional_cost_per_qty
Sagar Sharmaea82fe52022-08-18 17:20:22 +05301010 else:
1011 for item in self.items:
s-aga-r1504ff82023-08-25 20:18:30 +05301012 if not item.get("is_scrap_item"):
1013 item.additional_cost_per_qty = 0
Sagar Sharmaea82fe52022-08-18 17:20:22 +05301014
s-aga-r6d89b2f2022-06-18 15:46:59 +05301015 @frappe.whitelist()
1016 def get_current_stock(self):
1017 if self.doctype in ["Purchase Receipt", "Subcontracting Receipt"]:
1018 for item in self.get("supplied_items"):
1019 if self.supplier_warehouse:
1020 actual_qty = frappe.db.get_value(
1021 "Bin",
1022 {"item_code": item.rm_item_code, "warehouse": self.supplier_warehouse},
1023 "actual_qty",
1024 )
Sagar Sharmaaddd7342022-08-19 11:46:27 +05301025 item.current_stock = flt(actual_qty)
s-aga-r6d89b2f2022-06-18 15:46:59 +05301026
Sagar Sharma29a1cb82022-04-26 17:29:45 +05301027 @property
1028 def sub_contracted_items(self):
1029 if not hasattr(self, "_sub_contracted_items"):
1030 self._sub_contracted_items = []
1031 item_codes = list(set(item.item_code for item in self.get("items")))
1032 if item_codes:
1033 items = frappe.get_all(
1034 "Item", filters={"name": ["in", item_codes], "is_sub_contracted_item": 1}
1035 )
1036 self._sub_contracted_items = [item.name for item in items]
1037
1038 return self._sub_contracted_items
s-aga-r6d89b2f2022-06-18 15:46:59 +05301039
Rohit Waghchaure691e3bb2023-11-30 10:25:22 +05301040 def update_requested_qty(self):
1041 material_request_map = {}
1042 for d in self.get("items"):
1043 if d.material_request_item:
1044 material_request_map.setdefault(d.material_request, []).append(d.material_request_item)
1045
1046 for mr, mr_item_rows in material_request_map.items():
1047 if mr and mr_item_rows:
1048 mr_obj = frappe.get_doc("Material Request", mr)
1049
1050 if mr_obj.status in ["Stopped", "Cancelled"]:
1051 frappe.throw(
Akhil Narang3effaf22024-03-27 11:37:26 +05301052 _("Material Request {0} is cancelled or stopped").format(mr),
1053 frappe.InvalidStatusError,
Rohit Waghchaure691e3bb2023-11-30 10:25:22 +05301054 )
1055
1056 mr_obj.update_requested_qty(mr_item_rows)
1057
s-aga-r6d89b2f2022-06-18 15:46:59 +05301058
1059def get_item_details(items):
1060 item = frappe.qb.DocType("Item")
1061 item_list = (
1062 frappe.qb.from_(item)
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301063 .select(item.item_code, item.item_name, item.description, item.allow_alternative_item)
s-aga-r6d89b2f2022-06-18 15:46:59 +05301064 .where(item.name.isin(items))
1065 .run(as_dict=True)
1066 )
1067
1068 item_details = {}
1069 for item in item_list:
1070 item_details[item.item_code] = item
1071
1072 return item_details
1073
1074
1075@frappe.whitelist()
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301076def make_rm_stock_entry(
1077 subcontract_order, rm_items=None, order_doctype="Subcontracting Order", target_doc=None
1078):
s-aga-r6d89b2f2022-06-18 15:46:59 +05301079 if subcontract_order:
1080 subcontract_order = frappe.get_doc(order_doctype, subcontract_order)
1081
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301082 if not rm_items:
1083 if not subcontract_order.supplied_items:
1084 frappe.throw(_("No item available for transfer."))
s-aga-r6d89b2f2022-06-18 15:46:59 +05301085
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301086 rm_items = subcontract_order.supplied_items
s-aga-r6d89b2f2022-06-18 15:46:59 +05301087
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301088 fg_item_code_list = list(
1089 set(item.get("main_item_code") or item.get("item_code") for item in rm_items)
1090 )
s-aga-r6d89b2f2022-06-18 15:46:59 +05301091
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301092 if fg_item_code_list:
1093 rm_item_code_list = tuple(set(item.get("rm_item_code") for item in rm_items))
1094 item_wh = get_item_details(rm_item_code_list)
1095
1096 field_no_map, rm_detail_field = "purchase_order", "sco_rm_detail"
1097 if order_doctype == "Purchase Order":
1098 field_no_map, rm_detail_field = "subcontracting_order", "po_detail"
1099
1100 if target_doc and target_doc.get("items"):
1101 target_doc.items = []
1102
1103 stock_entry = get_mapped_doc(
1104 order_doctype,
1105 subcontract_order.name,
1106 {
1107 order_doctype: {
1108 "doctype": "Stock Entry",
1109 "field_map": {
s-aga-r751bdc92022-12-31 17:17:22 +05301110 "supplier": "supplier",
1111 "supplier_name": "supplier_name",
1112 "supplier_address": "supplier_address",
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301113 "to_warehouse": "supplier_warehouse",
1114 },
1115 "field_no_map": [field_no_map],
1116 "validation": {
1117 "docstatus": ["=", 1],
1118 },
1119 },
1120 },
1121 target_doc,
1122 ignore_child_tables=True,
1123 )
1124
1125 stock_entry.purpose = "Send to Subcontractor"
1126
1127 if order_doctype == "Purchase Order":
1128 stock_entry.purchase_order = subcontract_order.name
1129 else:
1130 stock_entry.subcontracting_order = subcontract_order.name
1131
1132 stock_entry.set_stock_entry_type()
1133
1134 for fg_item_code in fg_item_code_list:
1135 for rm_item in rm_items:
Akhil Narang3effaf22024-03-27 11:37:26 +05301136 if (
1137 rm_item.get("main_item_code") == fg_item_code
1138 or rm_item.get("item_code") == fg_item_code
1139 ):
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301140 rm_item_code = rm_item.get("rm_item_code")
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301141 items_dict = {
1142 rm_item_code: {
1143 rm_detail_field: rm_item.get("name"),
1144 "item_name": rm_item.get("item_name")
1145 or item_wh.get(rm_item_code, {}).get("item_name", ""),
1146 "description": item_wh.get(rm_item_code, {}).get("description", ""),
1147 "qty": rm_item.get("qty")
1148 or max(rm_item.get("required_qty") - rm_item.get("total_supplied_qty"), 0),
Akhil Narang3effaf22024-03-27 11:37:26 +05301149 "from_warehouse": rm_item.get("warehouse")
1150 or rm_item.get("reserve_warehouse"),
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301151 "to_warehouse": subcontract_order.supplier_warehouse,
1152 "stock_uom": rm_item.get("stock_uom"),
Rohit Waghchauree88c5d62023-04-05 20:03:44 +05301153 "serial_and_batch_bundle": rm_item.get("serial_and_batch_bundle"),
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301154 "main_item_code": fg_item_code,
Akhil Narang3effaf22024-03-27 11:37:26 +05301155 "allow_alternative_item": item_wh.get(rm_item_code, {}).get(
1156 "allow_alternative_item"
1157 ),
Rohit Waghchaure34233342024-03-21 20:28:16 +05301158 "use_serial_batch_fields": rm_item.get("use_serial_batch_fields"),
Akhil Narang3effaf22024-03-27 11:37:26 +05301159 "serial_no": rm_item.get("serial_no")
1160 if rm_item.get("use_serial_batch_fields")
1161 else None,
1162 "batch_no": rm_item.get("batch_no")
1163 if rm_item.get("use_serial_batch_fields")
1164 else None,
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301165 }
s-aga-r6d89b2f2022-06-18 15:46:59 +05301166 }
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301167
1168 stock_entry.add_to_stock_entry_detail(items_dict)
1169
1170 if target_doc:
1171 return stock_entry
1172 else:
1173 return stock_entry.as_dict()
1174 else:
1175 frappe.throw(_("No Items selected for transfer."))
s-aga-r6d89b2f2022-06-18 15:46:59 +05301176
1177
Akhil Narang3effaf22024-03-27 11:37:26 +05301178def add_items_in_ste(ste_doc, row, qty, rm_details, rm_detail_field="sco_rm_detail", batch_no=None):
s-aga-r6d89b2f2022-06-18 15:46:59 +05301179 item = ste_doc.append("items", row.item_details)
1180
1181 rm_detail = list(set(row.get(f"{rm_detail_field}s")).intersection(rm_details))
1182 item.update(
1183 {
1184 "qty": qty,
1185 "batch_no": batch_no,
1186 "basic_rate": row.item_details["rate"],
1187 rm_detail_field: rm_detail[0] if rm_detail else "",
1188 "s_warehouse": row.item_details["t_warehouse"],
1189 "t_warehouse": row.item_details["s_warehouse"],
1190 "item_code": row.item_details["rm_item_code"],
1191 "subcontracted_item": row.item_details["main_item_code"],
1192 "serial_no": "\n".join(row.serial_no) if row.serial_no else "",
1193 }
1194 )
1195
1196
1197def make_return_stock_entry_for_subcontract(
1198 available_materials, order_doc, rm_details, order_doctype="Subcontracting Order"
1199):
Sagar Sharma008542b2022-09-07 10:15:43 +05301200 ste_doc = get_mapped_doc(
1201 order_doctype,
1202 order_doc.name,
1203 {
1204 order_doctype: {
1205 "doctype": "Stock Entry",
Sagar Sharmaccb28892022-09-08 16:04:08 +05301206 "field_no_map": ["purchase_order", "subcontracting_order"],
Sagar Sharma008542b2022-09-07 10:15:43 +05301207 },
1208 },
1209 ignore_child_tables=True,
1210 )
1211
s-aga-r6d89b2f2022-06-18 15:46:59 +05301212 ste_doc.purpose = "Material Transfer"
1213
1214 if order_doctype == "Purchase Order":
1215 ste_doc.purchase_order = order_doc.name
1216 rm_detail_field = "po_detail"
1217 else:
1218 ste_doc.subcontracting_order = order_doc.name
1219 rm_detail_field = "sco_rm_detail"
1220 ste_doc.company = order_doc.company
1221 ste_doc.is_return = 1
1222
Akhil Narang3effaf22024-03-27 11:37:26 +05301223 for _key, value in available_materials.items():
s-aga-r6d89b2f2022-06-18 15:46:59 +05301224 if not value.qty:
1225 continue
1226
1227 if value.batch_no:
1228 for batch_no, qty in value.batch_no.items():
1229 if qty > 0:
1230 add_items_in_ste(ste_doc, value, value.qty, rm_details, rm_detail_field, batch_no)
1231 else:
1232 add_items_in_ste(ste_doc, value, value.qty, rm_details, rm_detail_field)
1233
1234 ste_doc.set_stock_entry_type()
s-aga-r6d89b2f2022-06-18 15:46:59 +05301235
1236 return ste_doc
1237
1238
1239@frappe.whitelist()
Akhil Narang3effaf22024-03-27 11:37:26 +05301240def get_materials_from_supplier(subcontract_order, rm_details, order_doctype="Subcontracting Order"):
s-aga-r6d89b2f2022-06-18 15:46:59 +05301241 if isinstance(rm_details, str):
1242 rm_details = json.loads(rm_details)
1243
1244 doc = frappe.get_cached_doc(order_doctype, subcontract_order)
1245 doc.initialized_fields()
1246 doc.subcontract_orders = [doc.name]
1247 doc.get_available_materials()
1248
1249 if not doc.available_materials:
1250 frappe.throw(
1251 _("Materials are already received against the {0} {1}").format(order_doctype, subcontract_order)
1252 )
1253
Akhil Narang3effaf22024-03-27 11:37:26 +05301254 return make_return_stock_entry_for_subcontract(doc.available_materials, doc, rm_details, order_doctype)