blob: 05754293b7765967b1c8f5eb2dd8cdc6d19e0a88 [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:
s-aga-rb26e96c2023-01-12 13:41:53 +053077 frappe.throw(_("Row {0}: Item {1} must be a stock item.").format(item.idx, item.item_name))
Sagar Sharmafa229062022-09-30 16:18:15 +053078
79 if not is_sub_contracted_item:
s-aga-rb26e96c2023-01-12 13:41:53 +053080 frappe.throw(
81 _("Row {0}: Item {1} must be a subcontracted item.").format(item.idx, item.item_name)
82 )
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:
s-aga-rb26e96c2023-01-12 13:41:53 +053087 frappe.throw(
88 _("Row {0}: Please select an active BOM for Item {1}.").format(item.idx, item.item_name)
89 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +053090 if bom.item != item.item_code:
s-aga-rb26e96c2023-01-12 13:41:53 +053091 frappe.throw(
92 _("Row {0}: Please select an valid BOM for Item {1}.").format(item.idx, item.item_name)
93 )
Sagar Sharma760c26e2022-11-05 15:50:39 +053094 else:
s-aga-rb26e96c2023-01-12 13:41:53 +053095 frappe.throw(_("Row {0}: Please select a BOM for Item {1}.").format(item.idx, item.item_name))
Sagar Sharma29a1cb82022-04-26 17:29:45 +053096
97 def __get_data_before_save(self):
98 item_dict = {}
s-aga-r6d89b2f2022-06-18 15:46:59 +053099 if (
100 self.doctype in ["Purchase Receipt", "Purchase Invoice", "Subcontracting Receipt"]
101 and self._doc_before_save
102 ):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530103 for row in self._doc_before_save.get("items"):
s-aga-r01f56c62022-11-15 14:32:16 +0530104 item_dict[row.name] = (row.item_code, row.qty)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530105
106 return item_dict
107
108 def __identify_change_in_item_table(self):
109 self.__changed_name = []
110 self.__reference_name = []
111
s-aga-r6d89b2f2022-06-18 15:46:59 +0530112 if self.doctype in ["Purchase Order", "Subcontracting Order"] or self.is_new():
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530113 self.set(self.raw_material_table, [])
114 return
115
116 item_dict = self.__get_data_before_save()
117 if not item_dict:
118 return True
119
120 for row in self.items:
121 self.__reference_name.append(row.name)
s-aga-r01f56c62022-11-15 14:32:16 +0530122 if (row.name not in item_dict) or (row.item_code, row.qty) != item_dict[row.name]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530123 self.__changed_name.append(row.name)
124
125 if item_dict.get(row.name):
126 del item_dict[row.name]
127
128 self.__changed_name.extend(item_dict.keys())
129
130 def __get_backflush_based_on(self):
131 self.backflush_based_on = frappe.db.get_single_value(
132 "Buying Settings", "backflush_raw_materials_of_subcontract_based_on"
133 )
134
135 def initialized_fields(self):
136 self.available_materials = frappe._dict()
137 self.__transferred_items = frappe._dict()
138 self.alternative_item_details = frappe._dict()
139 self.__get_backflush_based_on()
140
s-aga-r6d89b2f2022-06-18 15:46:59 +0530141 def __get_subcontract_orders(self):
142 self.subcontract_orders = []
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530143
s-aga-r6d89b2f2022-06-18 15:46:59 +0530144 if self.doctype in ["Purchase Order", "Subcontracting Order"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530145 return
146
s-aga-r6d89b2f2022-06-18 15:46:59 +0530147 self.subcontract_orders = [
148 item.get(self.subcontract_data.order_field)
149 for item in self.items
150 if item.get(self.subcontract_data.order_field)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530151 ]
152
153 def __get_pending_qty_to_receive(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530154 """Get qty to be received against the subcontract order."""
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530155
156 self.qty_to_be_received = defaultdict(float)
157
158 if (
s-aga-r6d89b2f2022-06-18 15:46:59 +0530159 self.doctype != self.subcontract_data.order_doctype
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530160 and self.backflush_based_on != "BOM"
s-aga-r6d89b2f2022-06-18 15:46:59 +0530161 and self.subcontract_orders
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530162 ):
163 for row in frappe.get_all(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530164 f"{self.subcontract_data.order_doctype} Item",
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530165 fields=["item_code", "(qty - received_qty) as qty", "parent", "name"],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530166 filters={"docstatus": 1, "parent": ("in", self.subcontract_orders)},
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530167 ):
168
169 self.qty_to_be_received[(row.item_code, row.parent)] += row.qty
170
171 def __get_transferred_items(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530172 fields = [f"`tabStock Entry`.`{self.subcontract_data.order_field}`"]
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530173 alias_dict = {
174 "item_code": "rm_item_code",
175 "subcontracted_item": "main_item_code",
176 "basic_rate": "rate",
177 }
178
179 child_table_fields = [
180 "item_code",
181 "item_name",
182 "description",
183 "qty",
184 "basic_rate",
185 "amount",
186 "serial_no",
187 "uom",
188 "subcontracted_item",
189 "stock_uom",
190 "batch_no",
191 "conversion_factor",
192 "s_warehouse",
193 "t_warehouse",
194 "item_group",
s-aga-r6d89b2f2022-06-18 15:46:59 +0530195 self.subcontract_data.rm_detail_field,
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530196 ]
197
198 if self.backflush_based_on == "BOM":
199 child_table_fields.append("original_item")
200
201 for field in child_table_fields:
202 fields.append(f"`tabStock Entry Detail`.`{field}` As {alias_dict.get(field, field)}")
203
204 filters = [
205 ["Stock Entry", "docstatus", "=", 1],
206 ["Stock Entry", "purpose", "=", "Send to Subcontractor"],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530207 ["Stock Entry", self.subcontract_data.order_field, "in", self.subcontract_orders],
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530208 ]
209
210 return frappe.get_all("Stock Entry", fields=fields, filters=filters)
211
212 def __set_alternative_item_details(self, row):
213 if row.get("original_item"):
214 self.alternative_item_details[row.get("original_item")] = row
215
216 def __get_received_items(self, doctype):
217 fields = []
s-aga-r6d89b2f2022-06-18 15:46:59 +0530218 for field in ["name", self.subcontract_data.order_field, "parent"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530219 fields.append(f"`tab{doctype} Item`.`{field}`")
220
221 filters = [
222 [doctype, "docstatus", "=", 1],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530223 [f"{doctype} Item", self.subcontract_data.order_field, "in", self.subcontract_orders],
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530224 ]
s-aga-r6d89b2f2022-06-18 15:46:59 +0530225 if doctype == "Purchase Invoice":
226 filters.append(["Purchase Invoice", "update_stock", "=", 1])
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530227
228 return frappe.get_all(f"{doctype}", fields=fields, filters=filters)
229
s-aga-r6d89b2f2022-06-18 15:46:59 +0530230 def __get_consumed_items(self, doctype, receipt_items):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530231 return frappe.get_all(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530232 self.subcontract_data.receipt_supplied_items_field,
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530233 fields=[
234 "serial_no",
235 "rm_item_code",
236 "reference_name",
237 "batch_no",
238 "consumed_qty",
239 "main_item_code",
240 ],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530241 filters={"docstatus": 1, "reference_name": ("in", list(receipt_items)), "parenttype": doctype},
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530242 )
243
244 def __update_consumed_materials(self, doctype, return_consumed_items=False):
245 """Deduct the consumed materials from the available materials."""
246
s-aga-r6d89b2f2022-06-18 15:46:59 +0530247 receipt_items = self.__get_received_items(doctype)
248 if not receipt_items:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530249 return ([], {}) if return_consumed_items else None
250
s-aga-r6d89b2f2022-06-18 15:46:59 +0530251 receipt_items = {
252 item.name: item.get(self.subcontract_data.order_field) for item in receipt_items
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530253 }
s-aga-r6d89b2f2022-06-18 15:46:59 +0530254 consumed_materials = self.__get_consumed_items(doctype, receipt_items.keys())
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530255
256 if return_consumed_items:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530257 return (consumed_materials, receipt_items)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530258
259 for row in consumed_materials:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530260 key = (row.rm_item_code, row.main_item_code, receipt_items.get(row.reference_name))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530261 if not self.available_materials.get(key):
262 continue
263
264 self.available_materials[key]["qty"] -= row.consumed_qty
265 if row.serial_no:
266 self.available_materials[key]["serial_no"] = list(
267 set(self.available_materials[key]["serial_no"]) - set(get_serial_nos(row.serial_no))
268 )
269
270 if row.batch_no:
271 self.available_materials[key]["batch_no"][row.batch_no] -= row.consumed_qty
272
273 def get_available_materials(self):
274 """Get the available raw materials which has been transferred to the supplier.
275 available_materials = {
s-aga-r6d89b2f2022-06-18 15:46:59 +0530276 (item_code, subcontracted_item, subcontract_order): {
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530277 'qty': 1, 'serial_no': [ABC], 'batch_no': {'batch1': 1}, 'data': item_details
278 }
279 }
280 """
s-aga-r6d89b2f2022-06-18 15:46:59 +0530281 if not self.subcontract_orders:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530282 return
283
284 for row in self.__get_transferred_items():
s-aga-r6d89b2f2022-06-18 15:46:59 +0530285 key = (row.rm_item_code, row.main_item_code, row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530286
287 if key not in self.available_materials:
288 self.available_materials.setdefault(
289 key,
290 frappe._dict(
291 {
292 "qty": 0,
293 "serial_no": [],
294 "batch_no": defaultdict(float),
295 "item_details": row,
s-aga-r6d89b2f2022-06-18 15:46:59 +0530296 f"{self.subcontract_data.rm_detail_field}s": [],
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530297 }
298 ),
299 )
300
301 details = self.available_materials[key]
302 details.qty += row.qty
s-aga-r6d89b2f2022-06-18 15:46:59 +0530303 details[f"{self.subcontract_data.rm_detail_field}s"].append(
304 row.get(self.subcontract_data.rm_detail_field)
305 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530306
307 if row.serial_no:
308 details.serial_no.extend(get_serial_nos(row.serial_no))
309
310 if row.batch_no:
311 details.batch_no[row.batch_no] += row.qty
312
313 self.__set_alternative_item_details(row)
314
315 self.__transferred_items = copy.deepcopy(self.available_materials)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530316 if self.get("is_old_subcontracting_flow"):
317 for doctype in ["Purchase Receipt", "Purchase Invoice"]:
318 self.__update_consumed_materials(doctype)
319 else:
320 self.__update_consumed_materials("Subcontracting Receipt")
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530321
322 def __remove_changed_rows(self):
323 if not self.__changed_name:
324 return
325
326 i = 1
327 self.set(self.raw_material_table, [])
328 for item in self._doc_before_save.supplied_items:
329 if item.reference_name in self.__changed_name:
330 continue
331
332 if item.reference_name not in self.__reference_name:
333 continue
334
335 item.idx = i
336 self.append("supplied_items", item)
337
338 i += 1
339
340 def __get_materials_from_bom(self, item_code, bom_no, exploded_item=0):
341 doctype = "BOM Item" if not exploded_item else "BOM Explosion Item"
342 fields = [f"`tab{doctype}`.`stock_qty` / `tabBOM`.`quantity` as qty_consumed_per_unit"]
343
344 alias_dict = {
345 "item_code": "rm_item_code",
346 "name": "bom_detail_no",
347 "source_warehouse": "reserve_warehouse",
348 }
349 for field in [
350 "item_code",
351 "name",
352 "rate",
353 "stock_uom",
354 "source_warehouse",
355 "description",
356 "item_name",
357 "stock_uom",
358 ]:
359 fields.append(f"`tab{doctype}`.`{field}` As {alias_dict.get(field, field)}")
360
361 filters = [
362 [doctype, "parent", "=", bom_no],
363 [doctype, "docstatus", "=", 1],
364 ["BOM", "item", "=", item_code],
365 [doctype, "sourced_by_supplier", "=", 0],
366 ]
367
368 return (
369 frappe.get_all("BOM", fields=fields, filters=filters, order_by=f"`tab{doctype}`.`idx`") or []
370 )
371
372 def __update_reserve_warehouse(self, row, item):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530373 if self.doctype == self.subcontract_data.order_doctype:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530374 row.reserve_warehouse = self.set_reserve_warehouse or item.warehouse
375
376 def __set_alternative_item(self, bom_item):
377 if self.alternative_item_details.get(bom_item.rm_item_code):
378 bom_item.update(self.alternative_item_details[bom_item.rm_item_code])
379
380 def __set_serial_nos(self, item_row, rm_obj):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530381 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 +0530382 if self.available_materials.get(key) and self.available_materials[key]["serial_no"]:
383 used_serial_nos = self.available_materials[key]["serial_no"][0 : cint(rm_obj.consumed_qty)]
384 rm_obj.serial_no = "\n".join(used_serial_nos)
385
386 # Removed the used serial nos from the list
387 for sn in used_serial_nos:
388 self.available_materials[key]["serial_no"].remove(sn)
389
390 def __set_batch_no_as_per_qty(self, item_row, rm_obj, batch_no, qty):
391 rm_obj.update(
392 {
393 "consumed_qty": qty,
394 "batch_no": batch_no,
395 "required_qty": qty,
s-aga-r6d89b2f2022-06-18 15:46:59 +0530396 self.subcontract_data.order_field: item_row.get(self.subcontract_data.order_field),
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530397 }
398 )
399
400 self.__set_serial_nos(item_row, rm_obj)
401
402 def __set_consumed_qty(self, rm_obj, consumed_qty, required_qty=0):
403 rm_obj.required_qty = required_qty
404 rm_obj.consumed_qty = consumed_qty
405
406 def __set_batch_nos(self, bom_item, item_row, rm_obj, qty):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530407 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 +0530408
409 if self.available_materials.get(key) and self.available_materials[key]["batch_no"]:
410 new_rm_obj = None
411 for batch_no, batch_qty in self.available_materials[key]["batch_no"].items():
Rohit Waghchaure156e4592023-02-16 13:21:17 +0530412 if batch_qty >= qty or (
413 rm_obj.consumed_qty == 0
414 and self.backflush_based_on == "BOM"
415 and len(self.available_materials[key]["batch_no"]) == 1
416 ):
417 if rm_obj.consumed_qty == 0:
418 self.__set_consumed_qty(rm_obj, qty)
419
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530420 self.__set_batch_no_as_per_qty(item_row, rm_obj, batch_no, qty)
421 self.available_materials[key]["batch_no"][batch_no] -= qty
422 return
423
424 elif qty > 0 and batch_qty > 0:
425 qty -= batch_qty
426 new_rm_obj = self.append(self.raw_material_table, bom_item)
427 new_rm_obj.reference_name = item_row.name
428 self.__set_batch_no_as_per_qty(item_row, new_rm_obj, batch_no, batch_qty)
429 self.available_materials[key]["batch_no"][batch_no] = 0
430
431 if abs(qty) > 0 and not new_rm_obj:
432 self.__set_consumed_qty(rm_obj, qty)
433 else:
434 self.__set_consumed_qty(rm_obj, qty, bom_item.required_qty or qty)
435 self.__set_serial_nos(item_row, rm_obj)
436
437 def __add_supplied_item(self, item_row, bom_item, qty):
438 bom_item.conversion_factor = item_row.conversion_factor
439 rm_obj = self.append(self.raw_material_table, bom_item)
440 rm_obj.reference_name = item_row.name
441
442 if self.doctype == "Subcontracting Receipt":
443 args = frappe._dict(
444 {
445 "item_code": rm_obj.rm_item_code,
446 "warehouse": self.supplier_warehouse,
447 "posting_date": self.posting_date,
448 "posting_time": self.posting_time,
449 "qty": -1 * flt(rm_obj.consumed_qty),
450 "serial_no": rm_obj.serial_no,
451 "batch_no": rm_obj.batch_no,
452 "voucher_type": self.doctype,
453 "voucher_no": self.name,
454 "company": self.company,
455 "allow_zero_valuation": 1,
456 }
457 )
Sagar Sharma867d8982023-03-28 18:45:16 +0530458 rm_obj.rate = bom_item.rate if self.backflush_based_on == "BOM" else get_incoming_rate(args)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530459
s-aga-r6d89b2f2022-06-18 15:46:59 +0530460 if self.doctype == self.subcontract_data.order_doctype:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530461 rm_obj.required_qty = qty
462 rm_obj.amount = rm_obj.required_qty * rm_obj.rate
463 else:
464 rm_obj.consumed_qty = 0
s-aga-r6d89b2f2022-06-18 15:46:59 +0530465 setattr(
466 rm_obj, self.subcontract_data.order_field, item_row.get(self.subcontract_data.order_field)
467 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530468 self.__set_batch_nos(bom_item, item_row, rm_obj, qty)
469
470 def __get_qty_based_on_material_transfer(self, item_row, transfer_item):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530471 key = (item_row.item_code, item_row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530472
s-aga-r01f56c62022-11-15 14:32:16 +0530473 if self.qty_to_be_received == item_row.qty:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530474 return transfer_item.qty
475
476 if self.qty_to_be_received:
s-aga-r01f56c62022-11-15 14:32:16 +0530477 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 +0530478 transfer_item.item_details.required_qty = transfer_item.qty
479
480 if transfer_item.serial_no or frappe.get_cached_value(
481 "UOM", transfer_item.item_details.stock_uom, "must_be_whole_number"
482 ):
483 return frappe.utils.ceil(qty)
484
485 return qty
486
487 def __set_supplied_items(self):
488 self.bom_items = {}
489
490 has_supplied_items = True if self.get(self.raw_material_table) else False
491 for row in self.items:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530492 if self.doctype != self.subcontract_data.order_doctype and (
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530493 (self.__changed_name and row.name not in self.__changed_name)
494 or (has_supplied_items and not self.__changed_name)
495 ):
496 continue
497
s-aga-r6d89b2f2022-06-18 15:46:59 +0530498 if self.doctype == self.subcontract_data.order_doctype or self.backflush_based_on == "BOM":
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530499 for bom_item in self.__get_materials_from_bom(
500 row.item_code, row.bom, row.get("include_exploded_items")
501 ):
s-aga-r01f56c62022-11-15 14:32:16 +0530502 qty = flt(bom_item.qty_consumed_per_unit) * flt(row.qty) * row.conversion_factor
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530503 bom_item.main_item_code = row.item_code
504 self.__update_reserve_warehouse(bom_item, row)
505 self.__set_alternative_item(bom_item)
506 self.__add_supplied_item(row, bom_item, qty)
507
508 elif self.backflush_based_on != "BOM":
509 for key, transfer_item in self.available_materials.items():
s-aga-r6d89b2f2022-06-18 15:46:59 +0530510 if (key[1], key[2]) == (
511 row.item_code,
512 row.get(self.subcontract_data.order_field),
513 ) and transfer_item.qty > 0:
Sagar Sharmaaddd7342022-08-19 11:46:27 +0530514 qty = flt(self.__get_qty_based_on_material_transfer(row, transfer_item))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530515 transfer_item.qty -= qty
516 self.__add_supplied_item(row, transfer_item.get("item_details"), qty)
517
518 if self.qty_to_be_received:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530519 self.qty_to_be_received[
520 (row.item_code, row.get(self.subcontract_data.order_field))
521 ] -= row.qty
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530522
523 def __prepare_supplied_items(self):
524 self.initialized_fields()
s-aga-r6d89b2f2022-06-18 15:46:59 +0530525 self.__get_subcontract_orders()
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530526 self.__get_pending_qty_to_receive()
527 self.get_available_materials()
528 self.__remove_changed_rows()
529 self.__set_supplied_items()
530
531 def __validate_batch_no(self, row, key):
532 if row.get("batch_no") and row.get("batch_no") not in self.__transferred_items.get(key).get(
533 "batch_no"
534 ):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530535 link = get_link_to_form(
536 self.subcontract_data.order_doctype, row.get(self.subcontract_data.order_field)
537 )
538 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 +0530539 frappe.throw(_(msg), title=_("Incorrect Batch Consumed"))
540
541 def __validate_serial_no(self, row, key):
542 if row.get("serial_no"):
543 serial_nos = get_serial_nos(row.get("serial_no"))
544 incorrect_sn = set(serial_nos).difference(self.__transferred_items.get(key).get("serial_no"))
545
546 if incorrect_sn:
547 incorrect_sn = "\n".join(incorrect_sn)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530548 link = get_link_to_form(
549 self.subcontract_data.order_doctype, row.get(self.subcontract_data.order_field)
550 )
551 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 +0530552 frappe.throw(_(msg), title=_("Incorrect Serial Number Consumed"))
553
554 def __validate_supplied_items(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530555 if self.doctype not in ["Purchase Invoice", "Purchase Receipt", "Subcontracting Receipt"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530556 return
557
558 for row in self.get(self.raw_material_table):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530559 key = (row.rm_item_code, row.main_item_code, row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530560 if not self.__transferred_items or not self.__transferred_items.get(key):
561 return
562
563 self.__validate_batch_no(row, key)
564 self.__validate_serial_no(row, key)
565
566 def set_materials_for_subcontracted_items(self, raw_material_table):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530567 if self.doctype == "Purchase Invoice" and not self.update_stock:
568 return
569
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530570 self.raw_material_table = raw_material_table
571 self.__identify_change_in_item_table()
572 self.__prepare_supplied_items()
573 self.__validate_supplied_items()
574
575 def create_raw_materials_supplied(self, raw_material_table="supplied_items"):
576 self.set_materials_for_subcontracted_items(raw_material_table)
577
s-aga-r6d89b2f2022-06-18 15:46:59 +0530578 if self.doctype in ["Subcontracting Receipt", "Purchase Receipt", "Purchase Invoice"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530579 for item in self.get("items"):
580 item.rm_supp_cost = 0.0
581
s-aga-r6d89b2f2022-06-18 15:46:59 +0530582 def __update_consumed_qty_in_subcontract_order(self, itemwise_consumed_qty):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530583 fields = ["main_item_code", "rm_item_code", "parent", "supplied_qty", "name"]
s-aga-r6d89b2f2022-06-18 15:46:59 +0530584 filters = {"docstatus": 1, "parent": ("in", self.subcontract_orders)}
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530585
586 for row in frappe.get_all(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530587 self.subcontract_data.order_supplied_items_field, fields=fields, filters=filters, order_by="idx"
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530588 ):
589 key = (row.rm_item_code, row.main_item_code, row.parent)
590 consumed_qty = itemwise_consumed_qty.get(key, 0)
591
592 if row.supplied_qty < consumed_qty:
593 consumed_qty = row.supplied_qty
594
595 itemwise_consumed_qty[key] -= consumed_qty
596 frappe.db.set_value(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530597 self.subcontract_data.order_supplied_items_field, row.name, "consumed_qty", consumed_qty
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530598 )
599
s-aga-r6d89b2f2022-06-18 15:46:59 +0530600 def set_consumed_qty_in_subcontract_order(self):
601 # Update consumed qty back in the subcontract order
602 if self.doctype in ["Subcontracting Order", "Subcontracting Receipt"] or self.get(
603 "is_old_subcontracting_flow"
604 ):
605 self.__get_subcontract_orders()
606 itemwise_consumed_qty = defaultdict(float)
607 if self.get("is_old_subcontracting_flow"):
608 doctypes = ["Purchase Receipt", "Purchase Invoice"]
609 else:
610 doctypes = ["Subcontracting Receipt"]
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530611
s-aga-r6d89b2f2022-06-18 15:46:59 +0530612 for doctype in doctypes:
613 consumed_items, receipt_items = self.__update_consumed_materials(
614 doctype, return_consumed_items=True
615 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530616
s-aga-r6d89b2f2022-06-18 15:46:59 +0530617 for row in consumed_items:
618 key = (row.rm_item_code, row.main_item_code, receipt_items.get(row.reference_name))
619 itemwise_consumed_qty[key] += row.consumed_qty
620
621 self.__update_consumed_qty_in_subcontract_order(itemwise_consumed_qty)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530622
623 def update_ordered_and_reserved_qty(self):
624 sco_map = {}
625 for item in self.get("items"):
626 if self.doctype == "Subcontracting Receipt" and item.subcontracting_order:
627 sco_map.setdefault(item.subcontracting_order, []).append(item.subcontracting_order_item)
628
629 for sco, sco_item_rows in sco_map.items():
630 if sco and sco_item_rows:
631 sco_doc = frappe.get_doc("Subcontracting Order", sco)
632
633 if sco_doc.status in ["Closed", "Cancelled"]:
634 frappe.throw(
635 _("{0} {1} is cancelled or closed").format(_("Subcontracting Order"), sco),
636 frappe.InvalidStatusError,
637 )
638
639 sco_doc.update_ordered_qty_for_subcontracting(sco_item_rows)
640 sco_doc.update_reserved_qty_for_subcontracting()
641
642 def make_sl_entries_for_supplier_warehouse(self, sl_entries):
643 if hasattr(self, "supplied_items"):
644 for item in self.get("supplied_items"):
645 # negative quantity is passed, as raw material qty has to be decreased
646 # when SCR is submitted and it has to be increased when SCR is cancelled
647 sl_entries.append(
648 self.get_sl_entries(
649 item,
650 {
651 "item_code": item.rm_item_code,
652 "warehouse": self.supplier_warehouse,
653 "actual_qty": -1 * flt(item.consumed_qty),
654 "dependant_sle_voucher_detail_no": item.reference_name,
655 },
656 )
657 )
658
659 def update_stock_ledger(self, allow_negative_stock=False, via_landed_cost_voucher=False):
660 self.update_ordered_and_reserved_qty()
661
662 sl_entries = []
663 stock_items = self.get_stock_items()
664
665 for item in self.get("items"):
666 if item.item_code in stock_items and item.warehouse:
667 scr_qty = flt(item.qty) * flt(item.conversion_factor)
668
669 if scr_qty:
670 sle = self.get_sl_entries(
671 item, {"actual_qty": flt(scr_qty), "serial_no": cstr(item.serial_no).strip()}
672 )
673 rate_db_precision = 6 if cint(self.precision("rate", item)) <= 6 else 9
674 incoming_rate = flt(item.rate, rate_db_precision)
675 sle.update(
676 {
677 "incoming_rate": incoming_rate,
678 "recalculate_rate": 1,
679 }
680 )
681 sl_entries.append(sle)
682
683 if flt(item.rejected_qty) != 0:
684 sl_entries.append(
685 self.get_sl_entries(
686 item,
687 {
688 "warehouse": item.rejected_warehouse,
689 "actual_qty": flt(item.rejected_qty) * flt(item.conversion_factor),
690 "serial_no": cstr(item.rejected_serial_no).strip(),
691 "incoming_rate": 0.0,
692 "recalculate_rate": 1,
693 },
694 )
695 )
696
697 self.make_sl_entries_for_supplier_warehouse(sl_entries)
698 self.make_sl_entries(
699 sl_entries,
700 allow_negative_stock=allow_negative_stock,
701 via_landed_cost_voucher=via_landed_cost_voucher,
702 )
703
s-aga-r6d89b2f2022-06-18 15:46:59 +0530704 def get_supplied_items_cost(self, item_row_id, reset_outgoing_rate=True):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530705 supplied_items_cost = 0.0
706 for item in self.get("supplied_items"):
707 if item.reference_name == item_row_id:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530708 if (
709 self.get("is_old_subcontracting_flow")
710 and reset_outgoing_rate
711 and frappe.get_cached_value("Item", item.rm_item_code, "is_stock_item")
712 ):
713 rate = get_incoming_rate(
714 {
715 "item_code": item.rm_item_code,
716 "warehouse": self.supplier_warehouse,
717 "posting_date": self.posting_date,
718 "posting_time": self.posting_time,
719 "qty": -1 * item.consumed_qty,
720 "serial_no": item.serial_no,
721 "batch_no": item.batch_no,
722 }
723 )
724
725 if rate > 0:
726 item.rate = rate
727
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530728 item.amount = flt(flt(item.consumed_qty) * flt(item.rate), item.precision("amount"))
729 supplied_items_cost += item.amount
730
731 return supplied_items_cost
732
Sagar Sharma249726b2022-04-22 17:09:19 +0530733 def set_subcontracting_order_status(self):
734 if self.doctype == "Subcontracting Order":
735 self.update_status()
736 elif self.doctype == "Subcontracting Receipt":
s-aga-r6d89b2f2022-06-18 15:46:59 +0530737 self.__get_subcontract_orders
Sagar Sharma249726b2022-04-22 17:09:19 +0530738
s-aga-r6d89b2f2022-06-18 15:46:59 +0530739 if self.subcontract_orders:
740 for sco in set(self.subcontract_orders):
Sagar Sharma249726b2022-04-22 17:09:19 +0530741 sco_doc = frappe.get_doc("Subcontracting Order", sco)
742 sco_doc.update_status()
743
Sagar Sharmaea82fe52022-08-18 17:20:22 +0530744 def set_missing_values_in_additional_costs(self):
745 self.total_additional_costs = sum(flt(item.amount) for item in self.get("additional_costs"))
746
747 if self.total_additional_costs:
748 if self.distribute_additional_costs_based_on == "Amount":
749 total_amt = sum(flt(item.amount) for item in self.get("items"))
750 for item in self.items:
751 item.additional_cost_per_qty = (
752 (item.amount * self.total_additional_costs) / total_amt
753 ) / item.qty
754 else:
755 total_qty = sum(flt(item.qty) for item in self.get("items"))
756 additional_cost_per_qty = self.total_additional_costs / total_qty
757 for item in self.items:
758 item.additional_cost_per_qty = additional_cost_per_qty
759 else:
760 for item in self.items:
761 item.additional_cost_per_qty = 0
762
s-aga-r6d89b2f2022-06-18 15:46:59 +0530763 @frappe.whitelist()
764 def get_current_stock(self):
765 if self.doctype in ["Purchase Receipt", "Subcontracting Receipt"]:
766 for item in self.get("supplied_items"):
767 if self.supplier_warehouse:
768 actual_qty = frappe.db.get_value(
769 "Bin",
770 {"item_code": item.rm_item_code, "warehouse": self.supplier_warehouse},
771 "actual_qty",
772 )
Sagar Sharmaaddd7342022-08-19 11:46:27 +0530773 item.current_stock = flt(actual_qty)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530774
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530775 @property
776 def sub_contracted_items(self):
777 if not hasattr(self, "_sub_contracted_items"):
778 self._sub_contracted_items = []
779 item_codes = list(set(item.item_code for item in self.get("items")))
780 if item_codes:
781 items = frappe.get_all(
782 "Item", filters={"name": ["in", item_codes], "is_sub_contracted_item": 1}
783 )
784 self._sub_contracted_items = [item.name for item in items]
785
786 return self._sub_contracted_items
s-aga-r6d89b2f2022-06-18 15:46:59 +0530787
788
789def get_item_details(items):
790 item = frappe.qb.DocType("Item")
791 item_list = (
792 frappe.qb.from_(item)
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530793 .select(item.item_code, item.item_name, item.description, item.allow_alternative_item)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530794 .where(item.name.isin(items))
795 .run(as_dict=True)
796 )
797
798 item_details = {}
799 for item in item_list:
800 item_details[item.item_code] = item
801
802 return item_details
803
804
805@frappe.whitelist()
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530806def make_rm_stock_entry(
807 subcontract_order, rm_items=None, order_doctype="Subcontracting Order", target_doc=None
808):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530809 if subcontract_order:
810 subcontract_order = frappe.get_doc(order_doctype, subcontract_order)
811
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530812 if not rm_items:
813 if not subcontract_order.supplied_items:
814 frappe.throw(_("No item available for transfer."))
s-aga-r6d89b2f2022-06-18 15:46:59 +0530815
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530816 rm_items = subcontract_order.supplied_items
s-aga-r6d89b2f2022-06-18 15:46:59 +0530817
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530818 fg_item_code_list = list(
819 set(item.get("main_item_code") or item.get("item_code") for item in rm_items)
820 )
s-aga-r6d89b2f2022-06-18 15:46:59 +0530821
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530822 if fg_item_code_list:
823 rm_item_code_list = tuple(set(item.get("rm_item_code") for item in rm_items))
824 item_wh = get_item_details(rm_item_code_list)
825
826 field_no_map, rm_detail_field = "purchase_order", "sco_rm_detail"
827 if order_doctype == "Purchase Order":
828 field_no_map, rm_detail_field = "subcontracting_order", "po_detail"
829
830 if target_doc and target_doc.get("items"):
831 target_doc.items = []
832
833 stock_entry = get_mapped_doc(
834 order_doctype,
835 subcontract_order.name,
836 {
837 order_doctype: {
838 "doctype": "Stock Entry",
839 "field_map": {
s-aga-r751bdc92022-12-31 17:17:22 +0530840 "supplier": "supplier",
841 "supplier_name": "supplier_name",
842 "supplier_address": "supplier_address",
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530843 "to_warehouse": "supplier_warehouse",
844 },
845 "field_no_map": [field_no_map],
846 "validation": {
847 "docstatus": ["=", 1],
848 },
849 },
850 },
851 target_doc,
852 ignore_child_tables=True,
853 )
854
855 stock_entry.purpose = "Send to Subcontractor"
856
857 if order_doctype == "Purchase Order":
858 stock_entry.purchase_order = subcontract_order.name
859 else:
860 stock_entry.subcontracting_order = subcontract_order.name
861
862 stock_entry.set_stock_entry_type()
863
864 for fg_item_code in fg_item_code_list:
865 for rm_item in rm_items:
866
Sagar Sharmaac7409b2022-09-28 16:46:48 +0530867 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 +0530868 rm_item_code = rm_item.get("rm_item_code")
869
870 items_dict = {
871 rm_item_code: {
872 rm_detail_field: rm_item.get("name"),
873 "item_name": rm_item.get("item_name")
874 or item_wh.get(rm_item_code, {}).get("item_name", ""),
875 "description": item_wh.get(rm_item_code, {}).get("description", ""),
876 "qty": rm_item.get("qty")
877 or max(rm_item.get("required_qty") - rm_item.get("total_supplied_qty"), 0),
878 "from_warehouse": rm_item.get("warehouse") or rm_item.get("reserve_warehouse"),
879 "to_warehouse": subcontract_order.supplier_warehouse,
880 "stock_uom": rm_item.get("stock_uom"),
881 "serial_no": rm_item.get("serial_no"),
882 "batch_no": rm_item.get("batch_no"),
883 "main_item_code": fg_item_code,
884 "allow_alternative_item": item_wh.get(rm_item_code, {}).get("allow_alternative_item"),
885 }
s-aga-r6d89b2f2022-06-18 15:46:59 +0530886 }
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530887
888 stock_entry.add_to_stock_entry_detail(items_dict)
889
890 if target_doc:
891 return stock_entry
892 else:
893 return stock_entry.as_dict()
894 else:
895 frappe.throw(_("No Items selected for transfer."))
s-aga-r6d89b2f2022-06-18 15:46:59 +0530896
897
898def add_items_in_ste(
899 ste_doc, row, qty, rm_details, rm_detail_field="sco_rm_detail", batch_no=None
900):
901 item = ste_doc.append("items", row.item_details)
902
903 rm_detail = list(set(row.get(f"{rm_detail_field}s")).intersection(rm_details))
904 item.update(
905 {
906 "qty": qty,
907 "batch_no": batch_no,
908 "basic_rate": row.item_details["rate"],
909 rm_detail_field: rm_detail[0] if rm_detail else "",
910 "s_warehouse": row.item_details["t_warehouse"],
911 "t_warehouse": row.item_details["s_warehouse"],
912 "item_code": row.item_details["rm_item_code"],
913 "subcontracted_item": row.item_details["main_item_code"],
914 "serial_no": "\n".join(row.serial_no) if row.serial_no else "",
915 }
916 )
917
918
919def make_return_stock_entry_for_subcontract(
920 available_materials, order_doc, rm_details, order_doctype="Subcontracting Order"
921):
Sagar Sharma008542b2022-09-07 10:15:43 +0530922 ste_doc = get_mapped_doc(
923 order_doctype,
924 order_doc.name,
925 {
926 order_doctype: {
927 "doctype": "Stock Entry",
Sagar Sharmaccb28892022-09-08 16:04:08 +0530928 "field_no_map": ["purchase_order", "subcontracting_order"],
Sagar Sharma008542b2022-09-07 10:15:43 +0530929 },
930 },
931 ignore_child_tables=True,
932 )
933
s-aga-r6d89b2f2022-06-18 15:46:59 +0530934 ste_doc.purpose = "Material Transfer"
935
936 if order_doctype == "Purchase Order":
937 ste_doc.purchase_order = order_doc.name
938 rm_detail_field = "po_detail"
939 else:
940 ste_doc.subcontracting_order = order_doc.name
941 rm_detail_field = "sco_rm_detail"
942 ste_doc.company = order_doc.company
943 ste_doc.is_return = 1
944
945 for key, value in available_materials.items():
946 if not value.qty:
947 continue
948
949 if value.batch_no:
950 for batch_no, qty in value.batch_no.items():
951 if qty > 0:
952 add_items_in_ste(ste_doc, value, value.qty, rm_details, rm_detail_field, batch_no)
953 else:
954 add_items_in_ste(ste_doc, value, value.qty, rm_details, rm_detail_field)
955
956 ste_doc.set_stock_entry_type()
957 ste_doc.calculate_rate_and_amount()
958
959 return ste_doc
960
961
962@frappe.whitelist()
963def get_materials_from_supplier(
964 subcontract_order, rm_details, order_doctype="Subcontracting Order"
965):
966 if isinstance(rm_details, str):
967 rm_details = json.loads(rm_details)
968
969 doc = frappe.get_cached_doc(order_doctype, subcontract_order)
970 doc.initialized_fields()
971 doc.subcontract_orders = [doc.name]
972 doc.get_available_materials()
973
974 if not doc.available_materials:
975 frappe.throw(
976 _("Materials are already received against the {0} {1}").format(order_doctype, subcontract_order)
977 )
978
979 return make_return_stock_entry_for_subcontract(
980 doc.available_materials, doc, rm_details, order_doctype
981 )