blob: 7819fa586ca2021c55ca804c1ecc41fdb9ccc907 [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
Sagar Sharma29a1cb82022-04-26 17:29:45 +053011from frappe.utils import cint, cstr, flt, get_link_to_form
12
13from erpnext.controllers.stock_controller import StockController
14from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
15from erpnext.stock.utils import get_incoming_rate
16
17
18class SubcontractingController(StockController):
s-aga-r6d89b2f2022-06-18 15:46:59 +053019 def __init__(self, *args, **kwargs):
20 super(SubcontractingController, self).__init__(*args, **kwargs)
21 if self.get("is_old_subcontracting_flow"):
22 self.subcontract_data = frappe._dict(
23 {
24 "order_doctype": "Purchase Order",
25 "order_field": "purchase_order",
26 "rm_detail_field": "po_detail",
27 "receipt_supplied_items_field": "Purchase Receipt Item Supplied",
28 "order_supplied_items_field": "Purchase Order Item Supplied",
29 }
30 )
31 else:
32 self.subcontract_data = frappe._dict(
33 {
34 "order_doctype": "Subcontracting Order",
35 "order_field": "subcontracting_order",
36 "rm_detail_field": "sco_rm_detail",
37 "receipt_supplied_items_field": "Subcontracting Receipt Supplied Item",
38 "order_supplied_items_field": "Subcontracting Order Supplied Item",
39 }
40 )
41
Sagar Sharma29a1cb82022-04-26 17:29:45 +053042 def before_validate(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +053043 if self.doctype in ["Subcontracting Order", "Subcontracting Receipt"]:
44 self.remove_empty_rows()
45 self.set_items_conversion_factor()
Sagar Sharma29a1cb82022-04-26 17:29:45 +053046
47 def validate(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +053048 if self.doctype in ["Subcontracting Order", "Subcontracting Receipt"]:
49 self.validate_items()
50 self.create_raw_materials_supplied()
51 else:
52 super(SubcontractingController, self).validate()
Sagar Sharma29a1cb82022-04-26 17:29:45 +053053
54 def remove_empty_rows(self):
55 for key in ["service_items", "items", "supplied_items"]:
56 if self.get(key):
57 idx = 1
58 for item in self.get(key)[:]:
59 if not (item.get("item_code") or item.get("main_item_code")):
60 self.get(key).remove(item)
61 else:
62 item.idx = idx
63 idx += 1
64
65 def set_items_conversion_factor(self):
66 for item in self.get("items"):
67 if not item.conversion_factor:
68 item.conversion_factor = 1
69
70 def validate_items(self):
71 for item in self.items:
Sagar Sharmafa229062022-09-30 16:18:15 +053072 is_stock_item, is_sub_contracted_item = frappe.get_value(
73 "Item", item.item_code, ["is_stock_item", "is_sub_contracted_item"]
74 )
75
76 if not is_stock_item:
77 msg = f"Item {item.item_name} must be a stock item."
78 frappe.throw(_(msg))
79
80 if not is_sub_contracted_item:
Sagar Sharma29a1cb82022-04-26 17:29:45 +053081 msg = f"Item {item.item_name} must be a subcontracted item."
82 frappe.throw(_(msg))
Sagar Sharmafa229062022-09-30 16:18:15 +053083
Sagar Sharma29a1cb82022-04-26 17:29:45 +053084 if item.bom:
85 bom = frappe.get_doc("BOM", item.bom)
86 if not bom.is_active:
87 msg = f"Please select an active BOM for Item {item.item_name}."
88 frappe.throw(_(msg))
89 if bom.item != item.item_code:
90 msg = f"Please select an valid BOM for Item {item.item_name}."
91 frappe.throw(_(msg))
Sagar Sharma760c26e2022-11-05 15:50:39 +053092 else:
93 msg = f"Please select a BOM for Item {item.item_name}."
94 frappe.throw(_(msg))
Sagar Sharma29a1cb82022-04-26 17:29:45 +053095
96 def __get_data_before_save(self):
97 item_dict = {}
s-aga-r6d89b2f2022-06-18 15:46:59 +053098 if (
99 self.doctype in ["Purchase Receipt", "Purchase Invoice", "Subcontracting Receipt"]
100 and self._doc_before_save
101 ):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530102 for row in self._doc_before_save.get("items"):
Sagar Sharma70c9b8d2022-11-06 13:33:47 +0530103 item_dict[row.name] = (row.item_code, row.received_qty or row.qty)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530104
105 return item_dict
106
107 def __identify_change_in_item_table(self):
108 self.__changed_name = []
109 self.__reference_name = []
110
s-aga-r6d89b2f2022-06-18 15:46:59 +0530111 if self.doctype in ["Purchase Order", "Subcontracting Order"] or self.is_new():
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530112 self.set(self.raw_material_table, [])
113 return
114
115 item_dict = self.__get_data_before_save()
116 if not item_dict:
117 return True
118
119 for row in self.items:
120 self.__reference_name.append(row.name)
Sagar Sharma70c9b8d2022-11-06 13:33:47 +0530121 if (row.name not in item_dict) or (row.item_code, row.received_qty or row.qty) != item_dict[
122 row.name
123 ]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530124 self.__changed_name.append(row.name)
125
126 if item_dict.get(row.name):
127 del item_dict[row.name]
128
129 self.__changed_name.extend(item_dict.keys())
130
131 def __get_backflush_based_on(self):
132 self.backflush_based_on = frappe.db.get_single_value(
133 "Buying Settings", "backflush_raw_materials_of_subcontract_based_on"
134 )
135
136 def initialized_fields(self):
137 self.available_materials = frappe._dict()
138 self.__transferred_items = frappe._dict()
139 self.alternative_item_details = frappe._dict()
140 self.__get_backflush_based_on()
141
s-aga-r6d89b2f2022-06-18 15:46:59 +0530142 def __get_subcontract_orders(self):
143 self.subcontract_orders = []
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530144
s-aga-r6d89b2f2022-06-18 15:46:59 +0530145 if self.doctype in ["Purchase Order", "Subcontracting Order"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530146 return
147
s-aga-r6d89b2f2022-06-18 15:46:59 +0530148 self.subcontract_orders = [
149 item.get(self.subcontract_data.order_field)
150 for item in self.items
151 if item.get(self.subcontract_data.order_field)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530152 ]
153
154 def __get_pending_qty_to_receive(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530155 """Get qty to be received against the subcontract order."""
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530156
157 self.qty_to_be_received = defaultdict(float)
158
159 if (
s-aga-r6d89b2f2022-06-18 15:46:59 +0530160 self.doctype != self.subcontract_data.order_doctype
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530161 and self.backflush_based_on != "BOM"
s-aga-r6d89b2f2022-06-18 15:46:59 +0530162 and self.subcontract_orders
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530163 ):
164 for row in frappe.get_all(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530165 f"{self.subcontract_data.order_doctype} Item",
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530166 fields=["item_code", "(qty - received_qty) as qty", "parent", "name"],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530167 filters={"docstatus": 1, "parent": ("in", self.subcontract_orders)},
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530168 ):
169
170 self.qty_to_be_received[(row.item_code, row.parent)] += row.qty
171
172 def __get_transferred_items(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530173 fields = [f"`tabStock Entry`.`{self.subcontract_data.order_field}`"]
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530174 alias_dict = {
175 "item_code": "rm_item_code",
176 "subcontracted_item": "main_item_code",
177 "basic_rate": "rate",
178 }
179
180 child_table_fields = [
181 "item_code",
182 "item_name",
183 "description",
184 "qty",
185 "basic_rate",
186 "amount",
187 "serial_no",
188 "uom",
189 "subcontracted_item",
190 "stock_uom",
191 "batch_no",
192 "conversion_factor",
193 "s_warehouse",
194 "t_warehouse",
195 "item_group",
s-aga-r6d89b2f2022-06-18 15:46:59 +0530196 self.subcontract_data.rm_detail_field,
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530197 ]
198
199 if self.backflush_based_on == "BOM":
200 child_table_fields.append("original_item")
201
202 for field in child_table_fields:
203 fields.append(f"`tabStock Entry Detail`.`{field}` As {alias_dict.get(field, field)}")
204
205 filters = [
206 ["Stock Entry", "docstatus", "=", 1],
207 ["Stock Entry", "purpose", "=", "Send to Subcontractor"],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530208 ["Stock Entry", self.subcontract_data.order_field, "in", self.subcontract_orders],
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530209 ]
210
211 return frappe.get_all("Stock Entry", fields=fields, filters=filters)
212
213 def __set_alternative_item_details(self, row):
214 if row.get("original_item"):
215 self.alternative_item_details[row.get("original_item")] = row
216
217 def __get_received_items(self, doctype):
218 fields = []
s-aga-r6d89b2f2022-06-18 15:46:59 +0530219 for field in ["name", self.subcontract_data.order_field, "parent"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530220 fields.append(f"`tab{doctype} Item`.`{field}`")
221
222 filters = [
223 [doctype, "docstatus", "=", 1],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530224 [f"{doctype} Item", self.subcontract_data.order_field, "in", self.subcontract_orders],
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530225 ]
s-aga-r6d89b2f2022-06-18 15:46:59 +0530226 if doctype == "Purchase Invoice":
227 filters.append(["Purchase Invoice", "update_stock", "=", 1])
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530228
229 return frappe.get_all(f"{doctype}", fields=fields, filters=filters)
230
s-aga-r6d89b2f2022-06-18 15:46:59 +0530231 def __get_consumed_items(self, doctype, receipt_items):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530232 return frappe.get_all(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530233 self.subcontract_data.receipt_supplied_items_field,
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530234 fields=[
235 "serial_no",
236 "rm_item_code",
237 "reference_name",
238 "batch_no",
239 "consumed_qty",
240 "main_item_code",
241 ],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530242 filters={"docstatus": 1, "reference_name": ("in", list(receipt_items)), "parenttype": doctype},
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530243 )
244
245 def __update_consumed_materials(self, doctype, return_consumed_items=False):
246 """Deduct the consumed materials from the available materials."""
247
s-aga-r6d89b2f2022-06-18 15:46:59 +0530248 receipt_items = self.__get_received_items(doctype)
249 if not receipt_items:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530250 return ([], {}) if return_consumed_items else None
251
s-aga-r6d89b2f2022-06-18 15:46:59 +0530252 receipt_items = {
253 item.name: item.get(self.subcontract_data.order_field) for item in receipt_items
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530254 }
s-aga-r6d89b2f2022-06-18 15:46:59 +0530255 consumed_materials = self.__get_consumed_items(doctype, receipt_items.keys())
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530256
257 if return_consumed_items:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530258 return (consumed_materials, receipt_items)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530259
260 for row in consumed_materials:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530261 key = (row.rm_item_code, row.main_item_code, receipt_items.get(row.reference_name))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530262 if not self.available_materials.get(key):
263 continue
264
265 self.available_materials[key]["qty"] -= row.consumed_qty
266 if row.serial_no:
267 self.available_materials[key]["serial_no"] = list(
268 set(self.available_materials[key]["serial_no"]) - set(get_serial_nos(row.serial_no))
269 )
270
271 if row.batch_no:
272 self.available_materials[key]["batch_no"][row.batch_no] -= row.consumed_qty
273
274 def get_available_materials(self):
275 """Get the available raw materials which has been transferred to the supplier.
276 available_materials = {
s-aga-r6d89b2f2022-06-18 15:46:59 +0530277 (item_code, subcontracted_item, subcontract_order): {
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530278 'qty': 1, 'serial_no': [ABC], 'batch_no': {'batch1': 1}, 'data': item_details
279 }
280 }
281 """
s-aga-r6d89b2f2022-06-18 15:46:59 +0530282 if not self.subcontract_orders:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530283 return
284
285 for row in self.__get_transferred_items():
s-aga-r6d89b2f2022-06-18 15:46:59 +0530286 key = (row.rm_item_code, row.main_item_code, row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530287
288 if key not in self.available_materials:
289 self.available_materials.setdefault(
290 key,
291 frappe._dict(
292 {
293 "qty": 0,
294 "serial_no": [],
295 "batch_no": defaultdict(float),
296 "item_details": row,
s-aga-r6d89b2f2022-06-18 15:46:59 +0530297 f"{self.subcontract_data.rm_detail_field}s": [],
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530298 }
299 ),
300 )
301
302 details = self.available_materials[key]
303 details.qty += row.qty
s-aga-r6d89b2f2022-06-18 15:46:59 +0530304 details[f"{self.subcontract_data.rm_detail_field}s"].append(
305 row.get(self.subcontract_data.rm_detail_field)
306 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530307
308 if row.serial_no:
309 details.serial_no.extend(get_serial_nos(row.serial_no))
310
311 if row.batch_no:
312 details.batch_no[row.batch_no] += row.qty
313
314 self.__set_alternative_item_details(row)
315
316 self.__transferred_items = copy.deepcopy(self.available_materials)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530317 if self.get("is_old_subcontracting_flow"):
318 for doctype in ["Purchase Receipt", "Purchase Invoice"]:
319 self.__update_consumed_materials(doctype)
320 else:
321 self.__update_consumed_materials("Subcontracting Receipt")
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530322
323 def __remove_changed_rows(self):
324 if not self.__changed_name:
325 return
326
327 i = 1
328 self.set(self.raw_material_table, [])
329 for item in self._doc_before_save.supplied_items:
330 if item.reference_name in self.__changed_name:
331 continue
332
333 if item.reference_name not in self.__reference_name:
334 continue
335
336 item.idx = i
337 self.append("supplied_items", item)
338
339 i += 1
340
341 def __get_materials_from_bom(self, item_code, bom_no, exploded_item=0):
342 doctype = "BOM Item" if not exploded_item else "BOM Explosion Item"
343 fields = [f"`tab{doctype}`.`stock_qty` / `tabBOM`.`quantity` as qty_consumed_per_unit"]
344
345 alias_dict = {
346 "item_code": "rm_item_code",
347 "name": "bom_detail_no",
348 "source_warehouse": "reserve_warehouse",
349 }
350 for field in [
351 "item_code",
352 "name",
353 "rate",
354 "stock_uom",
355 "source_warehouse",
356 "description",
357 "item_name",
358 "stock_uom",
359 ]:
360 fields.append(f"`tab{doctype}`.`{field}` As {alias_dict.get(field, field)}")
361
362 filters = [
363 [doctype, "parent", "=", bom_no],
364 [doctype, "docstatus", "=", 1],
365 ["BOM", "item", "=", item_code],
366 [doctype, "sourced_by_supplier", "=", 0],
367 ]
368
369 return (
370 frappe.get_all("BOM", fields=fields, filters=filters, order_by=f"`tab{doctype}`.`idx`") or []
371 )
372
373 def __update_reserve_warehouse(self, row, item):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530374 if self.doctype == self.subcontract_data.order_doctype:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530375 row.reserve_warehouse = self.set_reserve_warehouse or item.warehouse
376
377 def __set_alternative_item(self, bom_item):
378 if self.alternative_item_details.get(bom_item.rm_item_code):
379 bom_item.update(self.alternative_item_details[bom_item.rm_item_code])
380
381 def __set_serial_nos(self, item_row, rm_obj):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530382 key = (rm_obj.rm_item_code, item_row.item_code, item_row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530383 if self.available_materials.get(key) and self.available_materials[key]["serial_no"]:
384 used_serial_nos = self.available_materials[key]["serial_no"][0 : cint(rm_obj.consumed_qty)]
385 rm_obj.serial_no = "\n".join(used_serial_nos)
386
387 # Removed the used serial nos from the list
388 for sn in used_serial_nos:
389 self.available_materials[key]["serial_no"].remove(sn)
390
391 def __set_batch_no_as_per_qty(self, item_row, rm_obj, batch_no, qty):
392 rm_obj.update(
393 {
394 "consumed_qty": qty,
395 "batch_no": batch_no,
396 "required_qty": qty,
s-aga-r6d89b2f2022-06-18 15:46:59 +0530397 self.subcontract_data.order_field: item_row.get(self.subcontract_data.order_field),
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530398 }
399 )
400
401 self.__set_serial_nos(item_row, rm_obj)
402
403 def __set_consumed_qty(self, rm_obj, consumed_qty, required_qty=0):
404 rm_obj.required_qty = required_qty
405 rm_obj.consumed_qty = consumed_qty
406
407 def __set_batch_nos(self, bom_item, item_row, rm_obj, qty):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530408 key = (rm_obj.rm_item_code, item_row.item_code, item_row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530409
410 if self.available_materials.get(key) and self.available_materials[key]["batch_no"]:
411 new_rm_obj = None
412 for batch_no, batch_qty in self.available_materials[key]["batch_no"].items():
413 if batch_qty >= qty:
414 self.__set_batch_no_as_per_qty(item_row, rm_obj, batch_no, qty)
415 self.available_materials[key]["batch_no"][batch_no] -= qty
416 return
417
418 elif qty > 0 and batch_qty > 0:
419 qty -= batch_qty
420 new_rm_obj = self.append(self.raw_material_table, bom_item)
421 new_rm_obj.reference_name = item_row.name
422 self.__set_batch_no_as_per_qty(item_row, new_rm_obj, batch_no, batch_qty)
423 self.available_materials[key]["batch_no"][batch_no] = 0
424
425 if abs(qty) > 0 and not new_rm_obj:
426 self.__set_consumed_qty(rm_obj, qty)
427 else:
428 self.__set_consumed_qty(rm_obj, qty, bom_item.required_qty or qty)
429 self.__set_serial_nos(item_row, rm_obj)
430
431 def __add_supplied_item(self, item_row, bom_item, qty):
432 bom_item.conversion_factor = item_row.conversion_factor
433 rm_obj = self.append(self.raw_material_table, bom_item)
434 rm_obj.reference_name = item_row.name
435
436 if self.doctype == "Subcontracting Receipt":
437 args = frappe._dict(
438 {
439 "item_code": rm_obj.rm_item_code,
440 "warehouse": self.supplier_warehouse,
441 "posting_date": self.posting_date,
442 "posting_time": self.posting_time,
443 "qty": -1 * flt(rm_obj.consumed_qty),
444 "serial_no": rm_obj.serial_no,
445 "batch_no": rm_obj.batch_no,
446 "voucher_type": self.doctype,
447 "voucher_no": self.name,
448 "company": self.company,
449 "allow_zero_valuation": 1,
450 }
451 )
452 rm_obj.rate = get_incoming_rate(args)
453
s-aga-r6d89b2f2022-06-18 15:46:59 +0530454 if self.doctype == self.subcontract_data.order_doctype:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530455 rm_obj.required_qty = qty
456 rm_obj.amount = rm_obj.required_qty * rm_obj.rate
457 else:
458 rm_obj.consumed_qty = 0
s-aga-r6d89b2f2022-06-18 15:46:59 +0530459 setattr(
460 rm_obj, self.subcontract_data.order_field, item_row.get(self.subcontract_data.order_field)
461 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530462 self.__set_batch_nos(bom_item, item_row, rm_obj, qty)
463
464 def __get_qty_based_on_material_transfer(self, item_row, transfer_item):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530465 key = (item_row.item_code, item_row.get(self.subcontract_data.order_field))
Sagar Sharma70c9b8d2022-11-06 13:33:47 +0530466 item_qty = item_row.received_qty or item_row.qty
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530467
Sagar Sharma70c9b8d2022-11-06 13:33:47 +0530468 if self.qty_to_be_received.get(key) == item_qty:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530469 return transfer_item.qty
470
471 if self.qty_to_be_received:
Sagar Sharma70c9b8d2022-11-06 13:33:47 +0530472 qty = (flt(item_qty) * flt(transfer_item.qty)) / flt(self.qty_to_be_received.get(key, 0))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530473 transfer_item.item_details.required_qty = transfer_item.qty
474
475 if transfer_item.serial_no or frappe.get_cached_value(
476 "UOM", transfer_item.item_details.stock_uom, "must_be_whole_number"
477 ):
478 return frappe.utils.ceil(qty)
479
480 return qty
481
482 def __set_supplied_items(self):
483 self.bom_items = {}
484
485 has_supplied_items = True if self.get(self.raw_material_table) else False
486 for row in self.items:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530487 if self.doctype != self.subcontract_data.order_doctype and (
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530488 (self.__changed_name and row.name not in self.__changed_name)
489 or (has_supplied_items and not self.__changed_name)
490 ):
491 continue
492
s-aga-r6d89b2f2022-06-18 15:46:59 +0530493 if self.doctype == self.subcontract_data.order_doctype or self.backflush_based_on == "BOM":
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530494 for bom_item in self.__get_materials_from_bom(
495 row.item_code, row.bom, row.get("include_exploded_items")
496 ):
Sagar Sharma70c9b8d2022-11-06 13:33:47 +0530497 qty = (
498 flt(bom_item.qty_consumed_per_unit)
499 * flt(row.received_qty or row.qty)
500 * row.conversion_factor
501 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530502 bom_item.main_item_code = row.item_code
503 self.__update_reserve_warehouse(bom_item, row)
504 self.__set_alternative_item(bom_item)
505 self.__add_supplied_item(row, bom_item, qty)
506
507 elif self.backflush_based_on != "BOM":
508 for key, transfer_item in self.available_materials.items():
s-aga-r6d89b2f2022-06-18 15:46:59 +0530509 if (key[1], key[2]) == (
510 row.item_code,
511 row.get(self.subcontract_data.order_field),
512 ) and transfer_item.qty > 0:
Sagar Sharmaaddd7342022-08-19 11:46:27 +0530513 qty = flt(self.__get_qty_based_on_material_transfer(row, transfer_item))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530514 transfer_item.qty -= qty
515 self.__add_supplied_item(row, transfer_item.get("item_details"), qty)
516
517 if self.qty_to_be_received:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530518 self.qty_to_be_received[
519 (row.item_code, row.get(self.subcontract_data.order_field))
520 ] -= row.qty
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530521
522 def __prepare_supplied_items(self):
523 self.initialized_fields()
s-aga-r6d89b2f2022-06-18 15:46:59 +0530524 self.__get_subcontract_orders()
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530525 self.__get_pending_qty_to_receive()
526 self.get_available_materials()
527 self.__remove_changed_rows()
528 self.__set_supplied_items()
529
530 def __validate_batch_no(self, row, key):
531 if row.get("batch_no") and row.get("batch_no") not in self.__transferred_items.get(key).get(
532 "batch_no"
533 ):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530534 link = get_link_to_form(
535 self.subcontract_data.order_doctype, row.get(self.subcontract_data.order_field)
536 )
537 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 +0530538 frappe.throw(_(msg), title=_("Incorrect Batch Consumed"))
539
540 def __validate_serial_no(self, row, key):
541 if row.get("serial_no"):
542 serial_nos = get_serial_nos(row.get("serial_no"))
543 incorrect_sn = set(serial_nos).difference(self.__transferred_items.get(key).get("serial_no"))
544
545 if incorrect_sn:
546 incorrect_sn = "\n".join(incorrect_sn)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530547 link = get_link_to_form(
548 self.subcontract_data.order_doctype, row.get(self.subcontract_data.order_field)
549 )
550 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 +0530551 frappe.throw(_(msg), title=_("Incorrect Serial Number Consumed"))
552
553 def __validate_supplied_items(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530554 if self.doctype not in ["Purchase Invoice", "Purchase Receipt", "Subcontracting Receipt"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530555 return
556
557 for row in self.get(self.raw_material_table):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530558 key = (row.rm_item_code, row.main_item_code, row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530559 if not self.__transferred_items or not self.__transferred_items.get(key):
560 return
561
562 self.__validate_batch_no(row, key)
563 self.__validate_serial_no(row, key)
564
565 def set_materials_for_subcontracted_items(self, raw_material_table):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530566 if self.doctype == "Purchase Invoice" and not self.update_stock:
567 return
568
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530569 self.raw_material_table = raw_material_table
570 self.__identify_change_in_item_table()
571 self.__prepare_supplied_items()
572 self.__validate_supplied_items()
573
574 def create_raw_materials_supplied(self, raw_material_table="supplied_items"):
575 self.set_materials_for_subcontracted_items(raw_material_table)
576
s-aga-r6d89b2f2022-06-18 15:46:59 +0530577 if self.doctype in ["Subcontracting Receipt", "Purchase Receipt", "Purchase Invoice"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530578 for item in self.get("items"):
579 item.rm_supp_cost = 0.0
580
s-aga-r6d89b2f2022-06-18 15:46:59 +0530581 def __update_consumed_qty_in_subcontract_order(self, itemwise_consumed_qty):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530582 fields = ["main_item_code", "rm_item_code", "parent", "supplied_qty", "name"]
s-aga-r6d89b2f2022-06-18 15:46:59 +0530583 filters = {"docstatus": 1, "parent": ("in", self.subcontract_orders)}
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530584
585 for row in frappe.get_all(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530586 self.subcontract_data.order_supplied_items_field, fields=fields, filters=filters, order_by="idx"
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530587 ):
588 key = (row.rm_item_code, row.main_item_code, row.parent)
589 consumed_qty = itemwise_consumed_qty.get(key, 0)
590
591 if row.supplied_qty < consumed_qty:
592 consumed_qty = row.supplied_qty
593
594 itemwise_consumed_qty[key] -= consumed_qty
595 frappe.db.set_value(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530596 self.subcontract_data.order_supplied_items_field, row.name, "consumed_qty", consumed_qty
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530597 )
598
s-aga-r6d89b2f2022-06-18 15:46:59 +0530599 def set_consumed_qty_in_subcontract_order(self):
600 # Update consumed qty back in the subcontract order
601 if self.doctype in ["Subcontracting Order", "Subcontracting Receipt"] or self.get(
602 "is_old_subcontracting_flow"
603 ):
604 self.__get_subcontract_orders()
605 itemwise_consumed_qty = defaultdict(float)
606 if self.get("is_old_subcontracting_flow"):
607 doctypes = ["Purchase Receipt", "Purchase Invoice"]
608 else:
609 doctypes = ["Subcontracting Receipt"]
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530610
s-aga-r6d89b2f2022-06-18 15:46:59 +0530611 for doctype in doctypes:
612 consumed_items, receipt_items = self.__update_consumed_materials(
613 doctype, return_consumed_items=True
614 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530615
s-aga-r6d89b2f2022-06-18 15:46:59 +0530616 for row in consumed_items:
617 key = (row.rm_item_code, row.main_item_code, receipt_items.get(row.reference_name))
618 itemwise_consumed_qty[key] += row.consumed_qty
619
620 self.__update_consumed_qty_in_subcontract_order(itemwise_consumed_qty)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530621
622 def update_ordered_and_reserved_qty(self):
623 sco_map = {}
624 for item in self.get("items"):
625 if self.doctype == "Subcontracting Receipt" and item.subcontracting_order:
626 sco_map.setdefault(item.subcontracting_order, []).append(item.subcontracting_order_item)
627
628 for sco, sco_item_rows in sco_map.items():
629 if sco and sco_item_rows:
630 sco_doc = frappe.get_doc("Subcontracting Order", sco)
631
632 if sco_doc.status in ["Closed", "Cancelled"]:
633 frappe.throw(
634 _("{0} {1} is cancelled or closed").format(_("Subcontracting Order"), sco),
635 frappe.InvalidStatusError,
636 )
637
638 sco_doc.update_ordered_qty_for_subcontracting(sco_item_rows)
639 sco_doc.update_reserved_qty_for_subcontracting()
640
641 def make_sl_entries_for_supplier_warehouse(self, sl_entries):
642 if hasattr(self, "supplied_items"):
643 for item in self.get("supplied_items"):
644 # negative quantity is passed, as raw material qty has to be decreased
645 # when SCR is submitted and it has to be increased when SCR is cancelled
646 sl_entries.append(
647 self.get_sl_entries(
648 item,
649 {
650 "item_code": item.rm_item_code,
651 "warehouse": self.supplier_warehouse,
652 "actual_qty": -1 * flt(item.consumed_qty),
653 "dependant_sle_voucher_detail_no": item.reference_name,
654 },
655 )
656 )
657
658 def update_stock_ledger(self, allow_negative_stock=False, via_landed_cost_voucher=False):
659 self.update_ordered_and_reserved_qty()
660
661 sl_entries = []
662 stock_items = self.get_stock_items()
663
664 for item in self.get("items"):
665 if item.item_code in stock_items and item.warehouse:
666 scr_qty = flt(item.qty) * flt(item.conversion_factor)
667
668 if scr_qty:
669 sle = self.get_sl_entries(
670 item, {"actual_qty": flt(scr_qty), "serial_no": cstr(item.serial_no).strip()}
671 )
672 rate_db_precision = 6 if cint(self.precision("rate", item)) <= 6 else 9
673 incoming_rate = flt(item.rate, rate_db_precision)
674 sle.update(
675 {
676 "incoming_rate": incoming_rate,
677 "recalculate_rate": 1,
678 }
679 )
680 sl_entries.append(sle)
681
682 if flt(item.rejected_qty) != 0:
683 sl_entries.append(
684 self.get_sl_entries(
685 item,
686 {
687 "warehouse": item.rejected_warehouse,
688 "actual_qty": flt(item.rejected_qty) * flt(item.conversion_factor),
689 "serial_no": cstr(item.rejected_serial_no).strip(),
690 "incoming_rate": 0.0,
691 "recalculate_rate": 1,
692 },
693 )
694 )
695
696 self.make_sl_entries_for_supplier_warehouse(sl_entries)
697 self.make_sl_entries(
698 sl_entries,
699 allow_negative_stock=allow_negative_stock,
700 via_landed_cost_voucher=via_landed_cost_voucher,
701 )
702
s-aga-r6d89b2f2022-06-18 15:46:59 +0530703 def get_supplied_items_cost(self, item_row_id, reset_outgoing_rate=True):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530704 supplied_items_cost = 0.0
705 for item in self.get("supplied_items"):
706 if item.reference_name == item_row_id:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530707 if (
708 self.get("is_old_subcontracting_flow")
709 and reset_outgoing_rate
710 and frappe.get_cached_value("Item", item.rm_item_code, "is_stock_item")
711 ):
712 rate = get_incoming_rate(
713 {
714 "item_code": item.rm_item_code,
715 "warehouse": self.supplier_warehouse,
716 "posting_date": self.posting_date,
717 "posting_time": self.posting_time,
718 "qty": -1 * item.consumed_qty,
719 "serial_no": item.serial_no,
720 "batch_no": item.batch_no,
721 }
722 )
723
724 if rate > 0:
725 item.rate = rate
726
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530727 item.amount = flt(flt(item.consumed_qty) * flt(item.rate), item.precision("amount"))
728 supplied_items_cost += item.amount
729
730 return supplied_items_cost
731
Sagar Sharma249726b2022-04-22 17:09:19 +0530732 def set_subcontracting_order_status(self):
733 if self.doctype == "Subcontracting Order":
734 self.update_status()
735 elif self.doctype == "Subcontracting Receipt":
s-aga-r6d89b2f2022-06-18 15:46:59 +0530736 self.__get_subcontract_orders
Sagar Sharma249726b2022-04-22 17:09:19 +0530737
s-aga-r6d89b2f2022-06-18 15:46:59 +0530738 if self.subcontract_orders:
739 for sco in set(self.subcontract_orders):
Sagar Sharma249726b2022-04-22 17:09:19 +0530740 sco_doc = frappe.get_doc("Subcontracting Order", sco)
741 sco_doc.update_status()
742
Sagar Sharmaea82fe52022-08-18 17:20:22 +0530743 def set_missing_values_in_additional_costs(self):
744 self.total_additional_costs = sum(flt(item.amount) for item in self.get("additional_costs"))
745
746 if self.total_additional_costs:
747 if self.distribute_additional_costs_based_on == "Amount":
748 total_amt = sum(flt(item.amount) for item in self.get("items"))
749 for item in self.items:
750 item.additional_cost_per_qty = (
751 (item.amount * self.total_additional_costs) / total_amt
752 ) / item.qty
753 else:
754 total_qty = sum(flt(item.qty) for item in self.get("items"))
755 additional_cost_per_qty = self.total_additional_costs / total_qty
756 for item in self.items:
757 item.additional_cost_per_qty = additional_cost_per_qty
758 else:
759 for item in self.items:
760 item.additional_cost_per_qty = 0
761
s-aga-r6d89b2f2022-06-18 15:46:59 +0530762 @frappe.whitelist()
763 def get_current_stock(self):
764 if self.doctype in ["Purchase Receipt", "Subcontracting Receipt"]:
765 for item in self.get("supplied_items"):
766 if self.supplier_warehouse:
767 actual_qty = frappe.db.get_value(
768 "Bin",
769 {"item_code": item.rm_item_code, "warehouse": self.supplier_warehouse},
770 "actual_qty",
771 )
Sagar Sharmaaddd7342022-08-19 11:46:27 +0530772 item.current_stock = flt(actual_qty)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530773
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530774 @property
775 def sub_contracted_items(self):
776 if not hasattr(self, "_sub_contracted_items"):
777 self._sub_contracted_items = []
778 item_codes = list(set(item.item_code for item in self.get("items")))
779 if item_codes:
780 items = frappe.get_all(
781 "Item", filters={"name": ["in", item_codes], "is_sub_contracted_item": 1}
782 )
783 self._sub_contracted_items = [item.name for item in items]
784
785 return self._sub_contracted_items
s-aga-r6d89b2f2022-06-18 15:46:59 +0530786
787
788def get_item_details(items):
789 item = frappe.qb.DocType("Item")
790 item_list = (
791 frappe.qb.from_(item)
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530792 .select(item.item_code, item.item_name, item.description, item.allow_alternative_item)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530793 .where(item.name.isin(items))
794 .run(as_dict=True)
795 )
796
797 item_details = {}
798 for item in item_list:
799 item_details[item.item_code] = item
800
801 return item_details
802
803
804@frappe.whitelist()
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530805def make_rm_stock_entry(
806 subcontract_order, rm_items=None, order_doctype="Subcontracting Order", target_doc=None
807):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530808 if subcontract_order:
809 subcontract_order = frappe.get_doc(order_doctype, subcontract_order)
810
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530811 if not rm_items:
812 if not subcontract_order.supplied_items:
813 frappe.throw(_("No item available for transfer."))
s-aga-r6d89b2f2022-06-18 15:46:59 +0530814
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530815 rm_items = subcontract_order.supplied_items
s-aga-r6d89b2f2022-06-18 15:46:59 +0530816
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530817 fg_item_code_list = list(
818 set(item.get("main_item_code") or item.get("item_code") for item in rm_items)
819 )
s-aga-r6d89b2f2022-06-18 15:46:59 +0530820
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530821 if fg_item_code_list:
822 rm_item_code_list = tuple(set(item.get("rm_item_code") for item in rm_items))
823 item_wh = get_item_details(rm_item_code_list)
824
825 field_no_map, rm_detail_field = "purchase_order", "sco_rm_detail"
826 if order_doctype == "Purchase Order":
827 field_no_map, rm_detail_field = "subcontracting_order", "po_detail"
828
829 if target_doc and target_doc.get("items"):
830 target_doc.items = []
831
832 stock_entry = get_mapped_doc(
833 order_doctype,
834 subcontract_order.name,
835 {
836 order_doctype: {
837 "doctype": "Stock Entry",
838 "field_map": {
839 "to_warehouse": "supplier_warehouse",
840 },
841 "field_no_map": [field_no_map],
842 "validation": {
843 "docstatus": ["=", 1],
844 },
845 },
846 },
847 target_doc,
848 ignore_child_tables=True,
849 )
850
851 stock_entry.purpose = "Send to Subcontractor"
852
853 if order_doctype == "Purchase Order":
854 stock_entry.purchase_order = subcontract_order.name
855 else:
856 stock_entry.subcontracting_order = subcontract_order.name
857
858 stock_entry.set_stock_entry_type()
859
860 for fg_item_code in fg_item_code_list:
861 for rm_item in rm_items:
862
Sagar Sharmaac7409b2022-09-28 16:46:48 +0530863 if rm_item.get("main_item_code") == fg_item_code or rm_item.get("item_code") == fg_item_code:
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530864 rm_item_code = rm_item.get("rm_item_code")
865
866 items_dict = {
867 rm_item_code: {
868 rm_detail_field: rm_item.get("name"),
869 "item_name": rm_item.get("item_name")
870 or item_wh.get(rm_item_code, {}).get("item_name", ""),
871 "description": item_wh.get(rm_item_code, {}).get("description", ""),
872 "qty": rm_item.get("qty")
873 or max(rm_item.get("required_qty") - rm_item.get("total_supplied_qty"), 0),
874 "from_warehouse": rm_item.get("warehouse") or rm_item.get("reserve_warehouse"),
875 "to_warehouse": subcontract_order.supplier_warehouse,
876 "stock_uom": rm_item.get("stock_uom"),
877 "serial_no": rm_item.get("serial_no"),
878 "batch_no": rm_item.get("batch_no"),
879 "main_item_code": fg_item_code,
880 "allow_alternative_item": item_wh.get(rm_item_code, {}).get("allow_alternative_item"),
881 }
s-aga-r6d89b2f2022-06-18 15:46:59 +0530882 }
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530883
884 stock_entry.add_to_stock_entry_detail(items_dict)
885
886 if target_doc:
887 return stock_entry
888 else:
889 return stock_entry.as_dict()
890 else:
891 frappe.throw(_("No Items selected for transfer."))
s-aga-r6d89b2f2022-06-18 15:46:59 +0530892
893
894def add_items_in_ste(
895 ste_doc, row, qty, rm_details, rm_detail_field="sco_rm_detail", batch_no=None
896):
897 item = ste_doc.append("items", row.item_details)
898
899 rm_detail = list(set(row.get(f"{rm_detail_field}s")).intersection(rm_details))
900 item.update(
901 {
902 "qty": qty,
903 "batch_no": batch_no,
904 "basic_rate": row.item_details["rate"],
905 rm_detail_field: rm_detail[0] if rm_detail else "",
906 "s_warehouse": row.item_details["t_warehouse"],
907 "t_warehouse": row.item_details["s_warehouse"],
908 "item_code": row.item_details["rm_item_code"],
909 "subcontracted_item": row.item_details["main_item_code"],
910 "serial_no": "\n".join(row.serial_no) if row.serial_no else "",
911 }
912 )
913
914
915def make_return_stock_entry_for_subcontract(
916 available_materials, order_doc, rm_details, order_doctype="Subcontracting Order"
917):
Sagar Sharma008542b2022-09-07 10:15:43 +0530918 ste_doc = get_mapped_doc(
919 order_doctype,
920 order_doc.name,
921 {
922 order_doctype: {
923 "doctype": "Stock Entry",
Sagar Sharmaccb28892022-09-08 16:04:08 +0530924 "field_no_map": ["purchase_order", "subcontracting_order"],
Sagar Sharma008542b2022-09-07 10:15:43 +0530925 },
926 },
927 ignore_child_tables=True,
928 )
929
s-aga-r6d89b2f2022-06-18 15:46:59 +0530930 ste_doc.purpose = "Material Transfer"
931
932 if order_doctype == "Purchase Order":
933 ste_doc.purchase_order = order_doc.name
934 rm_detail_field = "po_detail"
935 else:
936 ste_doc.subcontracting_order = order_doc.name
937 rm_detail_field = "sco_rm_detail"
938 ste_doc.company = order_doc.company
939 ste_doc.is_return = 1
940
941 for key, value in available_materials.items():
942 if not value.qty:
943 continue
944
945 if value.batch_no:
946 for batch_no, qty in value.batch_no.items():
947 if qty > 0:
948 add_items_in_ste(ste_doc, value, value.qty, rm_details, rm_detail_field, batch_no)
949 else:
950 add_items_in_ste(ste_doc, value, value.qty, rm_details, rm_detail_field)
951
952 ste_doc.set_stock_entry_type()
953 ste_doc.calculate_rate_and_amount()
954
955 return ste_doc
956
957
958@frappe.whitelist()
959def get_materials_from_supplier(
960 subcontract_order, rm_details, order_doctype="Subcontracting Order"
961):
962 if isinstance(rm_details, str):
963 rm_details = json.loads(rm_details)
964
965 doc = frappe.get_cached_doc(order_doctype, subcontract_order)
966 doc.initialized_fields()
967 doc.subcontract_orders = [doc.name]
968 doc.get_available_materials()
969
970 if not doc.available_materials:
971 frappe.throw(
972 _("Materials are already received against the {0} {1}").format(order_doctype, subcontract_order)
973 )
974
975 return make_return_stock_entry_for_subcontract(
976 doc.available_materials, doc, rm_details, order_doctype
977 )