blob: 814657d5f5dbfa9114bbe4e27c88df2fec3376e9 [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
18from erpnext.stock.utils import get_incoming_rate
19
20
21class SubcontractingController(StockController):
s-aga-r6d89b2f2022-06-18 15:46:59 +053022 def __init__(self, *args, **kwargs):
23 super(SubcontractingController, self).__init__(*args, **kwargs)
24 if self.get("is_old_subcontracting_flow"):
25 self.subcontract_data = frappe._dict(
26 {
27 "order_doctype": "Purchase Order",
28 "order_field": "purchase_order",
29 "rm_detail_field": "po_detail",
30 "receipt_supplied_items_field": "Purchase Receipt Item Supplied",
31 "order_supplied_items_field": "Purchase Order Item Supplied",
32 }
33 )
34 else:
35 self.subcontract_data = frappe._dict(
36 {
37 "order_doctype": "Subcontracting Order",
38 "order_field": "subcontracting_order",
39 "rm_detail_field": "sco_rm_detail",
40 "receipt_supplied_items_field": "Subcontracting Receipt Supplied Item",
41 "order_supplied_items_field": "Subcontracting Order Supplied Item",
42 }
43 )
44
Sagar Sharma29a1cb82022-04-26 17:29:45 +053045 def before_validate(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +053046 if self.doctype in ["Subcontracting Order", "Subcontracting Receipt"]:
47 self.remove_empty_rows()
48 self.set_items_conversion_factor()
Sagar Sharma29a1cb82022-04-26 17:29:45 +053049
50 def validate(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +053051 if self.doctype in ["Subcontracting Order", "Subcontracting Receipt"]:
52 self.validate_items()
53 self.create_raw_materials_supplied()
Rohit Waghchaure674bd3e2023-03-17 16:42:59 +053054 for table_field in ["items", "supplied_items"]:
55 if self.get(table_field):
56 self.set_total_in_words(table_field)
s-aga-r6d89b2f2022-06-18 15:46:59 +053057 else:
58 super(SubcontractingController, self).validate()
Sagar Sharma29a1cb82022-04-26 17:29:45 +053059
60 def remove_empty_rows(self):
61 for key in ["service_items", "items", "supplied_items"]:
62 if self.get(key):
63 idx = 1
64 for item in self.get(key)[:]:
65 if not (item.get("item_code") or item.get("main_item_code")):
66 self.get(key).remove(item)
67 else:
68 item.idx = idx
69 idx += 1
70
71 def set_items_conversion_factor(self):
72 for item in self.get("items"):
73 if not item.conversion_factor:
74 item.conversion_factor = 1
75
76 def validate_items(self):
77 for item in self.items:
Sagar Sharmafa229062022-09-30 16:18:15 +053078 is_stock_item, is_sub_contracted_item = frappe.get_value(
79 "Item", item.item_code, ["is_stock_item", "is_sub_contracted_item"]
80 )
81
82 if not is_stock_item:
s-aga-rb26e96c2023-01-12 13:41:53 +053083 frappe.throw(_("Row {0}: Item {1} must be a stock item.").format(item.idx, item.item_name))
Sagar Sharmafa229062022-09-30 16:18:15 +053084
85 if not is_sub_contracted_item:
s-aga-rb26e96c2023-01-12 13:41:53 +053086 frappe.throw(
87 _("Row {0}: Item {1} must be a subcontracted item.").format(item.idx, item.item_name)
88 )
Sagar Sharmafa229062022-09-30 16:18:15 +053089
Sagar Sharma29a1cb82022-04-26 17:29:45 +053090 if item.bom:
91 bom = frappe.get_doc("BOM", item.bom)
92 if not bom.is_active:
s-aga-rb26e96c2023-01-12 13:41:53 +053093 frappe.throw(
94 _("Row {0}: Please select an active BOM for Item {1}.").format(item.idx, item.item_name)
95 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +053096 if bom.item != item.item_code:
s-aga-rb26e96c2023-01-12 13:41:53 +053097 frappe.throw(
98 _("Row {0}: Please select an valid BOM for Item {1}.").format(item.idx, item.item_name)
99 )
Sagar Sharma760c26e2022-11-05 15:50:39 +0530100 else:
s-aga-rb26e96c2023-01-12 13:41:53 +0530101 frappe.throw(_("Row {0}: Please select a BOM for Item {1}.").format(item.idx, item.item_name))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530102
103 def __get_data_before_save(self):
104 item_dict = {}
s-aga-r6d89b2f2022-06-18 15:46:59 +0530105 if (
106 self.doctype in ["Purchase Receipt", "Purchase Invoice", "Subcontracting Receipt"]
107 and self._doc_before_save
108 ):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530109 for row in self._doc_before_save.get("items"):
s-aga-r01f56c62022-11-15 14:32:16 +0530110 item_dict[row.name] = (row.item_code, row.qty)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530111
112 return item_dict
113
114 def __identify_change_in_item_table(self):
115 self.__changed_name = []
116 self.__reference_name = []
117
s-aga-r6d89b2f2022-06-18 15:46:59 +0530118 if self.doctype in ["Purchase Order", "Subcontracting Order"] or self.is_new():
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530119 self.set(self.raw_material_table, [])
120 return
121
122 item_dict = self.__get_data_before_save()
123 if not item_dict:
124 return True
125
126 for row in self.items:
127 self.__reference_name.append(row.name)
s-aga-r01f56c62022-11-15 14:32:16 +0530128 if (row.name not in item_dict) or (row.item_code, row.qty) != item_dict[row.name]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530129 self.__changed_name.append(row.name)
130
131 if item_dict.get(row.name):
132 del item_dict[row.name]
133
134 self.__changed_name.extend(item_dict.keys())
135
136 def __get_backflush_based_on(self):
137 self.backflush_based_on = frappe.db.get_single_value(
138 "Buying Settings", "backflush_raw_materials_of_subcontract_based_on"
139 )
140
141 def initialized_fields(self):
142 self.available_materials = frappe._dict()
143 self.__transferred_items = frappe._dict()
144 self.alternative_item_details = frappe._dict()
145 self.__get_backflush_based_on()
146
s-aga-r6d89b2f2022-06-18 15:46:59 +0530147 def __get_subcontract_orders(self):
148 self.subcontract_orders = []
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530149
s-aga-r6d89b2f2022-06-18 15:46:59 +0530150 if self.doctype in ["Purchase Order", "Subcontracting Order"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530151 return
152
s-aga-r6d89b2f2022-06-18 15:46:59 +0530153 self.subcontract_orders = [
154 item.get(self.subcontract_data.order_field)
155 for item in self.items
156 if item.get(self.subcontract_data.order_field)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530157 ]
158
159 def __get_pending_qty_to_receive(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530160 """Get qty to be received against the subcontract order."""
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530161
162 self.qty_to_be_received = defaultdict(float)
163
164 if (
s-aga-r6d89b2f2022-06-18 15:46:59 +0530165 self.doctype != self.subcontract_data.order_doctype
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530166 and self.backflush_based_on != "BOM"
s-aga-r6d89b2f2022-06-18 15:46:59 +0530167 and self.subcontract_orders
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530168 ):
169 for row in frappe.get_all(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530170 f"{self.subcontract_data.order_doctype} Item",
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530171 fields=["item_code", "(qty - received_qty) as qty", "parent", "name"],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530172 filters={"docstatus": 1, "parent": ("in", self.subcontract_orders)},
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530173 ):
174
175 self.qty_to_be_received[(row.item_code, row.parent)] += row.qty
176
177 def __get_transferred_items(self):
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530178 fields = [
179 f"`tabStock Entry`.`{self.subcontract_data.order_field}`",
180 "`tabStock Entry`.`name` as voucher_no",
181 ]
182
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530183 alias_dict = {
184 "item_code": "rm_item_code",
185 "subcontracted_item": "main_item_code",
186 "basic_rate": "rate",
187 }
188
189 child_table_fields = [
190 "item_code",
191 "item_name",
192 "description",
193 "qty",
194 "basic_rate",
195 "amount",
196 "serial_no",
197 "uom",
198 "subcontracted_item",
199 "stock_uom",
200 "batch_no",
201 "conversion_factor",
202 "s_warehouse",
203 "t_warehouse",
204 "item_group",
s-aga-r6d89b2f2022-06-18 15:46:59 +0530205 self.subcontract_data.rm_detail_field,
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530206 ]
207
208 if self.backflush_based_on == "BOM":
209 child_table_fields.append("original_item")
210
211 for field in child_table_fields:
212 fields.append(f"`tabStock Entry Detail`.`{field}` As {alias_dict.get(field, field)}")
213
214 filters = [
215 ["Stock Entry", "docstatus", "=", 1],
216 ["Stock Entry", "purpose", "=", "Send to Subcontractor"],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530217 ["Stock Entry", self.subcontract_data.order_field, "in", self.subcontract_orders],
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530218 ]
219
220 return frappe.get_all("Stock Entry", fields=fields, filters=filters)
221
222 def __set_alternative_item_details(self, row):
223 if row.get("original_item"):
224 self.alternative_item_details[row.get("original_item")] = row
225
226 def __get_received_items(self, doctype):
227 fields = []
s-aga-r6d89b2f2022-06-18 15:46:59 +0530228 for field in ["name", self.subcontract_data.order_field, "parent"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530229 fields.append(f"`tab{doctype} Item`.`{field}`")
230
231 filters = [
232 [doctype, "docstatus", "=", 1],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530233 [f"{doctype} Item", self.subcontract_data.order_field, "in", self.subcontract_orders],
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530234 ]
s-aga-r6d89b2f2022-06-18 15:46:59 +0530235 if doctype == "Purchase Invoice":
236 filters.append(["Purchase Invoice", "update_stock", "=", 1])
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530237
238 return frappe.get_all(f"{doctype}", fields=fields, filters=filters)
239
s-aga-r6d89b2f2022-06-18 15:46:59 +0530240 def __get_consumed_items(self, doctype, receipt_items):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530241 return frappe.get_all(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530242 self.subcontract_data.receipt_supplied_items_field,
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530243 fields=[
244 "serial_no",
245 "rm_item_code",
246 "reference_name",
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530247 "serial_and_batch_bundle",
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530248 "batch_no",
249 "consumed_qty",
250 "main_item_code",
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530251 "parent as voucher_no",
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530252 ],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530253 filters={"docstatus": 1, "reference_name": ("in", list(receipt_items)), "parenttype": doctype},
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530254 )
255
256 def __update_consumed_materials(self, doctype, return_consumed_items=False):
257 """Deduct the consumed materials from the available materials."""
258
s-aga-r6d89b2f2022-06-18 15:46:59 +0530259 receipt_items = self.__get_received_items(doctype)
260 if not receipt_items:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530261 return ([], {}) if return_consumed_items else None
262
s-aga-r6d89b2f2022-06-18 15:46:59 +0530263 receipt_items = {
264 item.name: item.get(self.subcontract_data.order_field) for item in receipt_items
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530265 }
s-aga-r6d89b2f2022-06-18 15:46:59 +0530266 consumed_materials = self.__get_consumed_items(doctype, receipt_items.keys())
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530267
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530268 voucher_nos = [d.voucher_no for d in consumed_materials if d.voucher_no]
269 voucher_bundle_data = get_voucher_wise_serial_batch_from_bundle(
270 voucher_no=voucher_nos,
271 is_outward=1,
272 get_subcontracted_item=("Subcontracting Receipt Supplied Item", "main_item_code"),
273 )
274
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530275 if return_consumed_items:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530276 return (consumed_materials, receipt_items)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530277
278 for row in consumed_materials:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530279 key = (row.rm_item_code, row.main_item_code, receipt_items.get(row.reference_name))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530280 if not self.available_materials.get(key):
281 continue
282
283 self.available_materials[key]["qty"] -= row.consumed_qty
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530284
285 bundle_key = (row.rm_item_code, row.main_item_code, self.supplier_warehouse, row.voucher_no)
286 consumed_bundles = voucher_bundle_data.get(bundle_key, frappe._dict())
287
288 if consumed_bundles.serial_nos:
289 self.available_materials[key]["serial_no"] = list(
290 set(self.available_materials[key]["serial_no"]) - set(consumed_bundles.serial_nos)
291 )
292
293 if consumed_bundles.batch_nos:
294 for batch_no, qty in consumed_bundles.batch_nos.items():
295 self.available_materials[key]["batch_no"][batch_no] -= abs(qty)
296
Rohit Waghchaure46704642023-03-23 11:41:20 +0530297 # Will be deprecated in v16
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530298 if row.serial_no:
299 self.available_materials[key]["serial_no"] = list(
300 set(self.available_materials[key]["serial_no"]) - set(get_serial_nos(row.serial_no))
301 )
302
Rohit Waghchaure46704642023-03-23 11:41:20 +0530303 # Will be deprecated in v16
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530304 if row.batch_no:
305 self.available_materials[key]["batch_no"][row.batch_no] -= row.consumed_qty
306
307 def get_available_materials(self):
308 """Get the available raw materials which has been transferred to the supplier.
309 available_materials = {
s-aga-r6d89b2f2022-06-18 15:46:59 +0530310 (item_code, subcontracted_item, subcontract_order): {
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530311 'qty': 1, 'serial_no': [ABC], 'batch_no': {'batch1': 1}, 'data': item_details
312 }
313 }
314 """
s-aga-r6d89b2f2022-06-18 15:46:59 +0530315 if not self.subcontract_orders:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530316 return
317
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530318 transferred_items = self.__get_transferred_items()
319
320 voucher_nos = [row.voucher_no for row in transferred_items]
321 voucher_bundle_data = get_voucher_wise_serial_batch_from_bundle(
322 voucher_no=voucher_nos,
323 is_outward=0,
324 get_subcontracted_item=("Stock Entry Detail", "subcontracted_item"),
325 )
326
327 for row in transferred_items:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530328 key = (row.rm_item_code, row.main_item_code, row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530329
330 if key not in self.available_materials:
331 self.available_materials.setdefault(
332 key,
333 frappe._dict(
334 {
335 "qty": 0,
336 "serial_no": [],
337 "batch_no": defaultdict(float),
338 "item_details": row,
s-aga-r6d89b2f2022-06-18 15:46:59 +0530339 f"{self.subcontract_data.rm_detail_field}s": [],
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530340 }
341 ),
342 )
343
344 details = self.available_materials[key]
345 details.qty += row.qty
s-aga-r6d89b2f2022-06-18 15:46:59 +0530346 details[f"{self.subcontract_data.rm_detail_field}s"].append(
347 row.get(self.subcontract_data.rm_detail_field)
348 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530349
350 if row.serial_no:
351 details.serial_no.extend(get_serial_nos(row.serial_no))
352
353 if row.batch_no:
354 details.batch_no[row.batch_no] += row.qty
355
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530356 if voucher_bundle_data:
357 bundle_key = (row.rm_item_code, row.main_item_code, row.t_warehouse, row.voucher_no)
358
359 bundle_data = voucher_bundle_data.get(bundle_key, frappe._dict())
360 if bundle_data.serial_nos:
361 details.serial_no.extend(bundle_data.serial_nos)
362
363 if bundle_data.batch_nos:
364 for batch_no, qty in bundle_data.batch_nos.items():
365 details.batch_no[batch_no] += qty
366
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530367 self.__set_alternative_item_details(row)
368
369 self.__transferred_items = copy.deepcopy(self.available_materials)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530370 if self.get("is_old_subcontracting_flow"):
371 for doctype in ["Purchase Receipt", "Purchase Invoice"]:
372 self.__update_consumed_materials(doctype)
373 else:
374 self.__update_consumed_materials("Subcontracting Receipt")
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530375
376 def __remove_changed_rows(self):
377 if not self.__changed_name:
378 return
379
380 i = 1
381 self.set(self.raw_material_table, [])
382 for item in self._doc_before_save.supplied_items:
383 if item.reference_name in self.__changed_name:
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530384 self.__remove_serial_and_batch_bundle(item)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530385 continue
386
387 if item.reference_name not in self.__reference_name:
388 continue
389
390 item.idx = i
391 self.append("supplied_items", item)
392
393 i += 1
394
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530395 def __remove_serial_and_batch_bundle(self, item):
396 if item.serial_and_batch_bundle:
397 frappe.delete_doc("Serial and Batch Bundle", item.serial_and_batch_bundle, force=True)
398
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530399 def __get_materials_from_bom(self, item_code, bom_no, exploded_item=0):
400 doctype = "BOM Item" if not exploded_item else "BOM Explosion Item"
401 fields = [f"`tab{doctype}`.`stock_qty` / `tabBOM`.`quantity` as qty_consumed_per_unit"]
402
403 alias_dict = {
404 "item_code": "rm_item_code",
405 "name": "bom_detail_no",
406 "source_warehouse": "reserve_warehouse",
407 }
408 for field in [
409 "item_code",
410 "name",
411 "rate",
412 "stock_uom",
413 "source_warehouse",
414 "description",
415 "item_name",
416 "stock_uom",
417 ]:
418 fields.append(f"`tab{doctype}`.`{field}` As {alias_dict.get(field, field)}")
419
420 filters = [
421 [doctype, "parent", "=", bom_no],
422 [doctype, "docstatus", "=", 1],
423 ["BOM", "item", "=", item_code],
424 [doctype, "sourced_by_supplier", "=", 0],
425 ]
426
427 return (
428 frappe.get_all("BOM", fields=fields, filters=filters, order_by=f"`tab{doctype}`.`idx`") or []
429 )
430
431 def __update_reserve_warehouse(self, row, item):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530432 if self.doctype == self.subcontract_data.order_doctype:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530433 row.reserve_warehouse = self.set_reserve_warehouse or item.warehouse
434
435 def __set_alternative_item(self, bom_item):
436 if self.alternative_item_details.get(bom_item.rm_item_code):
437 bom_item.update(self.alternative_item_details[bom_item.rm_item_code])
438
439 def __set_serial_nos(self, item_row, rm_obj):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530440 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 +0530441 if self.available_materials.get(key) and self.available_materials[key]["serial_no"]:
442 used_serial_nos = self.available_materials[key]["serial_no"][0 : cint(rm_obj.consumed_qty)]
443 rm_obj.serial_no = "\n".join(used_serial_nos)
444
445 # Removed the used serial nos from the list
446 for sn in used_serial_nos:
447 self.available_materials[key]["serial_no"].remove(sn)
448
449 def __set_batch_no_as_per_qty(self, item_row, rm_obj, batch_no, qty):
450 rm_obj.update(
451 {
452 "consumed_qty": qty,
453 "batch_no": batch_no,
454 "required_qty": qty,
s-aga-r6d89b2f2022-06-18 15:46:59 +0530455 self.subcontract_data.order_field: item_row.get(self.subcontract_data.order_field),
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530456 }
457 )
458
459 self.__set_serial_nos(item_row, rm_obj)
460
461 def __set_consumed_qty(self, rm_obj, consumed_qty, required_qty=0):
462 rm_obj.required_qty = required_qty
463 rm_obj.consumed_qty = consumed_qty
464
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530465 def __set_serial_and_batch_bundle(self, item_row, rm_obj, qty):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530466 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 +0530467 if not self.available_materials.get(key):
468 return
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530469
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530470 if (
471 not self.available_materials[key]["serial_no"] and not self.available_materials[key]["batch_no"]
472 ):
473 return
Rohit Waghchaure156e4592023-02-16 13:21:17 +0530474
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530475 bundle = frappe.get_doc(
476 {
477 "doctype": "Serial and Batch Bundle",
478 "company": self.company,
479 "item_code": rm_obj.rm_item_code,
480 "warehouse": self.supplier_warehouse,
481 "posting_date": self.posting_date,
482 "posting_time": self.posting_time,
483 "voucher_type": "Subcontracting Receipt",
484 "voucher_no": self.name,
485 "type_of_transaction": "Outward",
486 }
487 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530488
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530489 if self.available_materials.get(key) and self.available_materials[key]["serial_no"]:
490 self.__set_serial_nos_for_bundle(bundle, qty, key)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530491
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530492 elif self.available_materials.get(key) and self.available_materials[key]["batch_no"]:
493 self.__set_batch_nos_for_bundle(bundle, qty, key)
494
495 bundle.flags.ignore_links = True
496 bundle.flags.ignore_mandatory = True
497 bundle.save(ignore_permissions=True)
498 return bundle.name
499
500 def __set_batch_nos_for_bundle(self, bundle, qty, key):
501 bundle.has_batch_no = 1
502 for batch_no, batch_qty in self.available_materials[key]["batch_no"].items():
503 qty_to_consumed = 0
504 if qty > 0:
505 if batch_qty >= qty:
506 qty_to_consumed = qty
507 else:
508 qty_to_consumed = batch_qty
509
510 qty -= qty_to_consumed
511 if qty_to_consumed > 0:
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530512 bundle.append("entries", {"batch_no": batch_no, "qty": qty_to_consumed * -1})
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530513
514 def __set_serial_nos_for_bundle(self, bundle, qty, key):
515 bundle.has_serial_no = 1
516
517 used_serial_nos = self.available_materials[key]["serial_no"][0 : cint(qty)]
518
519 # Removed the used serial nos from the list
520 for sn in used_serial_nos:
521 batch_no = ""
522 if self.available_materials[key]["batch_no"]:
523 bundle.has_batch_no = 1
524 batch_no = frappe.get_cached_value("Serial No", sn, "batch_no")
525 if batch_no:
526 self.available_materials[key]["batch_no"][batch_no] -= 1
527
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530528 bundle.append("entries", {"serial_no": sn, "batch_no": batch_no, "qty": -1})
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530529
530 self.available_materials[key]["serial_no"].remove(sn)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530531
532 def __add_supplied_item(self, item_row, bom_item, qty):
533 bom_item.conversion_factor = item_row.conversion_factor
534 rm_obj = self.append(self.raw_material_table, bom_item)
535 rm_obj.reference_name = item_row.name
536
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530537 if self.doctype == self.subcontract_data.order_doctype:
538 rm_obj.required_qty = qty
539 rm_obj.amount = rm_obj.required_qty * rm_obj.rate
540 else:
541 rm_obj.consumed_qty = qty
542 rm_obj.required_qty = bom_item.required_qty or qty
543 setattr(
544 rm_obj, self.subcontract_data.order_field, item_row.get(self.subcontract_data.order_field)
545 )
546
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530547 if self.doctype == "Subcontracting Receipt":
548 args = frappe._dict(
549 {
550 "item_code": rm_obj.rm_item_code,
551 "warehouse": self.supplier_warehouse,
552 "posting_date": self.posting_date,
553 "posting_time": self.posting_time,
554 "qty": -1 * flt(rm_obj.consumed_qty),
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530555 "actual_qty": -1 * flt(rm_obj.consumed_qty),
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530556 "voucher_type": self.doctype,
557 "voucher_no": self.name,
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530558 "voucher_detail_no": item_row.name,
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530559 "company": self.company,
560 "allow_zero_valuation": 1,
561 }
562 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530563
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530564 rm_obj.serial_and_batch_bundle = self.__set_serial_and_batch_bundle(item_row, rm_obj, qty)
565
566 if rm_obj.serial_and_batch_bundle:
567 args["serial_and_batch_bundle"] = rm_obj.serial_and_batch_bundle
568
569 rm_obj.rate = bom_item.rate if self.backflush_based_on == "BOM" else get_incoming_rate(args)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530570
571 def __get_qty_based_on_material_transfer(self, item_row, transfer_item):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530572 key = (item_row.item_code, item_row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530573
s-aga-r01f56c62022-11-15 14:32:16 +0530574 if self.qty_to_be_received == item_row.qty:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530575 return transfer_item.qty
576
577 if self.qty_to_be_received:
s-aga-r01f56c62022-11-15 14:32:16 +0530578 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 +0530579 transfer_item.item_details.required_qty = transfer_item.qty
580
581 if transfer_item.serial_no or frappe.get_cached_value(
582 "UOM", transfer_item.item_details.stock_uom, "must_be_whole_number"
583 ):
584 return frappe.utils.ceil(qty)
585
586 return qty
587
588 def __set_supplied_items(self):
589 self.bom_items = {}
590
591 has_supplied_items = True if self.get(self.raw_material_table) else False
592 for row in self.items:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530593 if self.doctype != self.subcontract_data.order_doctype and (
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530594 (self.__changed_name and row.name not in self.__changed_name)
595 or (has_supplied_items and not self.__changed_name)
596 ):
597 continue
598
s-aga-r6d89b2f2022-06-18 15:46:59 +0530599 if self.doctype == self.subcontract_data.order_doctype or self.backflush_based_on == "BOM":
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530600 for bom_item in self.__get_materials_from_bom(
601 row.item_code, row.bom, row.get("include_exploded_items")
602 ):
s-aga-r01f56c62022-11-15 14:32:16 +0530603 qty = flt(bom_item.qty_consumed_per_unit) * flt(row.qty) * row.conversion_factor
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530604 bom_item.main_item_code = row.item_code
605 self.__update_reserve_warehouse(bom_item, row)
606 self.__set_alternative_item(bom_item)
607 self.__add_supplied_item(row, bom_item, qty)
608
609 elif self.backflush_based_on != "BOM":
610 for key, transfer_item in self.available_materials.items():
s-aga-r6d89b2f2022-06-18 15:46:59 +0530611 if (key[1], key[2]) == (
612 row.item_code,
613 row.get(self.subcontract_data.order_field),
614 ) and transfer_item.qty > 0:
Sagar Sharmaaddd7342022-08-19 11:46:27 +0530615 qty = flt(self.__get_qty_based_on_material_transfer(row, transfer_item))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530616 transfer_item.qty -= qty
617 self.__add_supplied_item(row, transfer_item.get("item_details"), qty)
618
619 if self.qty_to_be_received:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530620 self.qty_to_be_received[
621 (row.item_code, row.get(self.subcontract_data.order_field))
622 ] -= row.qty
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530623
624 def __prepare_supplied_items(self):
625 self.initialized_fields()
s-aga-r6d89b2f2022-06-18 15:46:59 +0530626 self.__get_subcontract_orders()
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530627 self.__get_pending_qty_to_receive()
628 self.get_available_materials()
629 self.__remove_changed_rows()
630 self.__set_supplied_items()
631
632 def __validate_batch_no(self, row, key):
633 if row.get("batch_no") and row.get("batch_no") not in self.__transferred_items.get(key).get(
634 "batch_no"
635 ):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530636 link = get_link_to_form(
637 self.subcontract_data.order_doctype, row.get(self.subcontract_data.order_field)
638 )
639 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 +0530640 frappe.throw(_(msg), title=_("Incorrect Batch Consumed"))
641
642 def __validate_serial_no(self, row, key):
643 if row.get("serial_no"):
644 serial_nos = get_serial_nos(row.get("serial_no"))
645 incorrect_sn = set(serial_nos).difference(self.__transferred_items.get(key).get("serial_no"))
646
647 if incorrect_sn:
648 incorrect_sn = "\n".join(incorrect_sn)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530649 link = get_link_to_form(
650 self.subcontract_data.order_doctype, row.get(self.subcontract_data.order_field)
651 )
652 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 +0530653 frappe.throw(_(msg), title=_("Incorrect Serial Number Consumed"))
654
655 def __validate_supplied_items(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530656 if self.doctype not in ["Purchase Invoice", "Purchase Receipt", "Subcontracting Receipt"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530657 return
658
659 for row in self.get(self.raw_material_table):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530660 key = (row.rm_item_code, row.main_item_code, row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530661 if not self.__transferred_items or not self.__transferred_items.get(key):
662 return
663
664 self.__validate_batch_no(row, key)
665 self.__validate_serial_no(row, key)
666
667 def set_materials_for_subcontracted_items(self, raw_material_table):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530668 if self.doctype == "Purchase Invoice" and not self.update_stock:
669 return
670
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530671 self.raw_material_table = raw_material_table
672 self.__identify_change_in_item_table()
673 self.__prepare_supplied_items()
674 self.__validate_supplied_items()
675
676 def create_raw_materials_supplied(self, raw_material_table="supplied_items"):
677 self.set_materials_for_subcontracted_items(raw_material_table)
678
s-aga-r6d89b2f2022-06-18 15:46:59 +0530679 if self.doctype in ["Subcontracting Receipt", "Purchase Receipt", "Purchase Invoice"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530680 for item in self.get("items"):
681 item.rm_supp_cost = 0.0
682
s-aga-r6d89b2f2022-06-18 15:46:59 +0530683 def __update_consumed_qty_in_subcontract_order(self, itemwise_consumed_qty):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530684 fields = ["main_item_code", "rm_item_code", "parent", "supplied_qty", "name"]
s-aga-r6d89b2f2022-06-18 15:46:59 +0530685 filters = {"docstatus": 1, "parent": ("in", self.subcontract_orders)}
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530686
687 for row in frappe.get_all(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530688 self.subcontract_data.order_supplied_items_field, fields=fields, filters=filters, order_by="idx"
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530689 ):
690 key = (row.rm_item_code, row.main_item_code, row.parent)
691 consumed_qty = itemwise_consumed_qty.get(key, 0)
692
693 if row.supplied_qty < consumed_qty:
694 consumed_qty = row.supplied_qty
695
696 itemwise_consumed_qty[key] -= consumed_qty
697 frappe.db.set_value(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530698 self.subcontract_data.order_supplied_items_field, row.name, "consumed_qty", consumed_qty
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530699 )
700
s-aga-r6d89b2f2022-06-18 15:46:59 +0530701 def set_consumed_qty_in_subcontract_order(self):
702 # Update consumed qty back in the subcontract order
703 if self.doctype in ["Subcontracting Order", "Subcontracting Receipt"] or self.get(
704 "is_old_subcontracting_flow"
705 ):
706 self.__get_subcontract_orders()
707 itemwise_consumed_qty = defaultdict(float)
708 if self.get("is_old_subcontracting_flow"):
709 doctypes = ["Purchase Receipt", "Purchase Invoice"]
710 else:
711 doctypes = ["Subcontracting Receipt"]
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530712
s-aga-r6d89b2f2022-06-18 15:46:59 +0530713 for doctype in doctypes:
714 consumed_items, receipt_items = self.__update_consumed_materials(
715 doctype, return_consumed_items=True
716 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530717
s-aga-r6d89b2f2022-06-18 15:46:59 +0530718 for row in consumed_items:
719 key = (row.rm_item_code, row.main_item_code, receipt_items.get(row.reference_name))
720 itemwise_consumed_qty[key] += row.consumed_qty
721
722 self.__update_consumed_qty_in_subcontract_order(itemwise_consumed_qty)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530723
724 def update_ordered_and_reserved_qty(self):
725 sco_map = {}
726 for item in self.get("items"):
727 if self.doctype == "Subcontracting Receipt" and item.subcontracting_order:
728 sco_map.setdefault(item.subcontracting_order, []).append(item.subcontracting_order_item)
729
730 for sco, sco_item_rows in sco_map.items():
731 if sco and sco_item_rows:
732 sco_doc = frappe.get_doc("Subcontracting Order", sco)
733
734 if sco_doc.status in ["Closed", "Cancelled"]:
735 frappe.throw(
736 _("{0} {1} is cancelled or closed").format(_("Subcontracting Order"), sco),
737 frappe.InvalidStatusError,
738 )
739
740 sco_doc.update_ordered_qty_for_subcontracting(sco_item_rows)
741 sco_doc.update_reserved_qty_for_subcontracting()
742
743 def make_sl_entries_for_supplier_warehouse(self, sl_entries):
744 if hasattr(self, "supplied_items"):
745 for item in self.get("supplied_items"):
746 # negative quantity is passed, as raw material qty has to be decreased
747 # when SCR is submitted and it has to be increased when SCR is cancelled
748 sl_entries.append(
749 self.get_sl_entries(
750 item,
751 {
752 "item_code": item.rm_item_code,
753 "warehouse": self.supplier_warehouse,
754 "actual_qty": -1 * flt(item.consumed_qty),
755 "dependant_sle_voucher_detail_no": item.reference_name,
756 },
757 )
758 )
759
760 def update_stock_ledger(self, allow_negative_stock=False, via_landed_cost_voucher=False):
761 self.update_ordered_and_reserved_qty()
762
763 sl_entries = []
764 stock_items = self.get_stock_items()
765
766 for item in self.get("items"):
767 if item.item_code in stock_items and item.warehouse:
768 scr_qty = flt(item.qty) * flt(item.conversion_factor)
769
770 if scr_qty:
Rohit Waghchaure16f26fb2023-03-20 22:56:06 +0530771 sle = self.get_sl_entries(item, {"actual_qty": flt(scr_qty)})
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530772 rate_db_precision = 6 if cint(self.precision("rate", item)) <= 6 else 9
773 incoming_rate = flt(item.rate, rate_db_precision)
774 sle.update(
775 {
776 "incoming_rate": incoming_rate,
777 "recalculate_rate": 1,
778 }
779 )
780 sl_entries.append(sle)
781
782 if flt(item.rejected_qty) != 0:
783 sl_entries.append(
784 self.get_sl_entries(
785 item,
786 {
787 "warehouse": item.rejected_warehouse,
788 "actual_qty": flt(item.rejected_qty) * flt(item.conversion_factor),
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530789 "incoming_rate": 0.0,
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530790 },
791 )
792 )
793
794 self.make_sl_entries_for_supplier_warehouse(sl_entries)
795 self.make_sl_entries(
796 sl_entries,
797 allow_negative_stock=allow_negative_stock,
798 via_landed_cost_voucher=via_landed_cost_voucher,
799 )
800
s-aga-r6d89b2f2022-06-18 15:46:59 +0530801 def get_supplied_items_cost(self, item_row_id, reset_outgoing_rate=True):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530802 supplied_items_cost = 0.0
803 for item in self.get("supplied_items"):
804 if item.reference_name == item_row_id:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530805 if (
806 self.get("is_old_subcontracting_flow")
807 and reset_outgoing_rate
808 and frappe.get_cached_value("Item", item.rm_item_code, "is_stock_item")
809 ):
810 rate = get_incoming_rate(
811 {
812 "item_code": item.rm_item_code,
813 "warehouse": self.supplier_warehouse,
814 "posting_date": self.posting_date,
815 "posting_time": self.posting_time,
816 "qty": -1 * item.consumed_qty,
Rohit Waghchaure46704642023-03-23 11:41:20 +0530817 "serial_and_batch_bundle": item.serial_and_batch_bundle,
s-aga-r6d89b2f2022-06-18 15:46:59 +0530818 }
819 )
820
821 if rate > 0:
822 item.rate = rate
823
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530824 item.amount = flt(flt(item.consumed_qty) * flt(item.rate), item.precision("amount"))
825 supplied_items_cost += item.amount
826
827 return supplied_items_cost
828
Sagar Sharma249726b2022-04-22 17:09:19 +0530829 def set_subcontracting_order_status(self):
830 if self.doctype == "Subcontracting Order":
831 self.update_status()
832 elif self.doctype == "Subcontracting Receipt":
s-aga-r6d89b2f2022-06-18 15:46:59 +0530833 self.__get_subcontract_orders
Sagar Sharma249726b2022-04-22 17:09:19 +0530834
s-aga-r6d89b2f2022-06-18 15:46:59 +0530835 if self.subcontract_orders:
836 for sco in set(self.subcontract_orders):
Sagar Sharma249726b2022-04-22 17:09:19 +0530837 sco_doc = frappe.get_doc("Subcontracting Order", sco)
838 sco_doc.update_status()
839
Sagar Sharmad6433f82023-05-12 11:45:33 +0530840 def calculate_additional_costs(self):
Sagar Sharmaea82fe52022-08-18 17:20:22 +0530841 self.total_additional_costs = sum(flt(item.amount) for item in self.get("additional_costs"))
842
843 if self.total_additional_costs:
844 if self.distribute_additional_costs_based_on == "Amount":
845 total_amt = sum(flt(item.amount) for item in self.get("items"))
846 for item in self.items:
847 item.additional_cost_per_qty = (
848 (item.amount * self.total_additional_costs) / total_amt
849 ) / item.qty
850 else:
851 total_qty = sum(flt(item.qty) for item in self.get("items"))
852 additional_cost_per_qty = self.total_additional_costs / total_qty
853 for item in self.items:
854 item.additional_cost_per_qty = additional_cost_per_qty
855 else:
856 for item in self.items:
857 item.additional_cost_per_qty = 0
858
s-aga-r6d89b2f2022-06-18 15:46:59 +0530859 @frappe.whitelist()
860 def get_current_stock(self):
861 if self.doctype in ["Purchase Receipt", "Subcontracting Receipt"]:
862 for item in self.get("supplied_items"):
863 if self.supplier_warehouse:
864 actual_qty = frappe.db.get_value(
865 "Bin",
866 {"item_code": item.rm_item_code, "warehouse": self.supplier_warehouse},
867 "actual_qty",
868 )
Sagar Sharmaaddd7342022-08-19 11:46:27 +0530869 item.current_stock = flt(actual_qty)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530870
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530871 @property
872 def sub_contracted_items(self):
873 if not hasattr(self, "_sub_contracted_items"):
874 self._sub_contracted_items = []
875 item_codes = list(set(item.item_code for item in self.get("items")))
876 if item_codes:
877 items = frappe.get_all(
878 "Item", filters={"name": ["in", item_codes], "is_sub_contracted_item": 1}
879 )
880 self._sub_contracted_items = [item.name for item in items]
881
882 return self._sub_contracted_items
s-aga-r6d89b2f2022-06-18 15:46:59 +0530883
884
885def get_item_details(items):
886 item = frappe.qb.DocType("Item")
887 item_list = (
888 frappe.qb.from_(item)
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530889 .select(item.item_code, item.item_name, item.description, item.allow_alternative_item)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530890 .where(item.name.isin(items))
891 .run(as_dict=True)
892 )
893
894 item_details = {}
895 for item in item_list:
896 item_details[item.item_code] = item
897
898 return item_details
899
900
901@frappe.whitelist()
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530902def make_rm_stock_entry(
903 subcontract_order, rm_items=None, order_doctype="Subcontracting Order", target_doc=None
904):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530905 if subcontract_order:
906 subcontract_order = frappe.get_doc(order_doctype, subcontract_order)
907
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530908 if not rm_items:
909 if not subcontract_order.supplied_items:
910 frappe.throw(_("No item available for transfer."))
s-aga-r6d89b2f2022-06-18 15:46:59 +0530911
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530912 rm_items = subcontract_order.supplied_items
s-aga-r6d89b2f2022-06-18 15:46:59 +0530913
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530914 fg_item_code_list = list(
915 set(item.get("main_item_code") or item.get("item_code") for item in rm_items)
916 )
s-aga-r6d89b2f2022-06-18 15:46:59 +0530917
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530918 if fg_item_code_list:
919 rm_item_code_list = tuple(set(item.get("rm_item_code") for item in rm_items))
920 item_wh = get_item_details(rm_item_code_list)
921
922 field_no_map, rm_detail_field = "purchase_order", "sco_rm_detail"
923 if order_doctype == "Purchase Order":
924 field_no_map, rm_detail_field = "subcontracting_order", "po_detail"
925
926 if target_doc and target_doc.get("items"):
927 target_doc.items = []
928
929 stock_entry = get_mapped_doc(
930 order_doctype,
931 subcontract_order.name,
932 {
933 order_doctype: {
934 "doctype": "Stock Entry",
935 "field_map": {
s-aga-r751bdc92022-12-31 17:17:22 +0530936 "supplier": "supplier",
937 "supplier_name": "supplier_name",
938 "supplier_address": "supplier_address",
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530939 "to_warehouse": "supplier_warehouse",
940 },
941 "field_no_map": [field_no_map],
942 "validation": {
943 "docstatus": ["=", 1],
944 },
945 },
946 },
947 target_doc,
948 ignore_child_tables=True,
949 )
950
951 stock_entry.purpose = "Send to Subcontractor"
952
953 if order_doctype == "Purchase Order":
954 stock_entry.purchase_order = subcontract_order.name
955 else:
956 stock_entry.subcontracting_order = subcontract_order.name
957
958 stock_entry.set_stock_entry_type()
959
960 for fg_item_code in fg_item_code_list:
961 for rm_item in rm_items:
962
Sagar Sharmaac7409b2022-09-28 16:46:48 +0530963 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 +0530964 rm_item_code = rm_item.get("rm_item_code")
965
966 items_dict = {
967 rm_item_code: {
968 rm_detail_field: rm_item.get("name"),
969 "item_name": rm_item.get("item_name")
970 or item_wh.get(rm_item_code, {}).get("item_name", ""),
971 "description": item_wh.get(rm_item_code, {}).get("description", ""),
972 "qty": rm_item.get("qty")
973 or max(rm_item.get("required_qty") - rm_item.get("total_supplied_qty"), 0),
974 "from_warehouse": rm_item.get("warehouse") or rm_item.get("reserve_warehouse"),
975 "to_warehouse": subcontract_order.supplier_warehouse,
976 "stock_uom": rm_item.get("stock_uom"),
977 "serial_no": rm_item.get("serial_no"),
978 "batch_no": rm_item.get("batch_no"),
979 "main_item_code": fg_item_code,
980 "allow_alternative_item": item_wh.get(rm_item_code, {}).get("allow_alternative_item"),
981 }
s-aga-r6d89b2f2022-06-18 15:46:59 +0530982 }
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530983
984 stock_entry.add_to_stock_entry_detail(items_dict)
985
986 if target_doc:
987 return stock_entry
988 else:
989 return stock_entry.as_dict()
990 else:
991 frappe.throw(_("No Items selected for transfer."))
s-aga-r6d89b2f2022-06-18 15:46:59 +0530992
993
994def add_items_in_ste(
995 ste_doc, row, qty, rm_details, rm_detail_field="sco_rm_detail", batch_no=None
996):
997 item = ste_doc.append("items", row.item_details)
998
999 rm_detail = list(set(row.get(f"{rm_detail_field}s")).intersection(rm_details))
1000 item.update(
1001 {
1002 "qty": qty,
1003 "batch_no": batch_no,
1004 "basic_rate": row.item_details["rate"],
1005 rm_detail_field: rm_detail[0] if rm_detail else "",
1006 "s_warehouse": row.item_details["t_warehouse"],
1007 "t_warehouse": row.item_details["s_warehouse"],
1008 "item_code": row.item_details["rm_item_code"],
1009 "subcontracted_item": row.item_details["main_item_code"],
1010 "serial_no": "\n".join(row.serial_no) if row.serial_no else "",
1011 }
1012 )
1013
1014
1015def make_return_stock_entry_for_subcontract(
1016 available_materials, order_doc, rm_details, order_doctype="Subcontracting Order"
1017):
Sagar Sharma008542b2022-09-07 10:15:43 +05301018 ste_doc = get_mapped_doc(
1019 order_doctype,
1020 order_doc.name,
1021 {
1022 order_doctype: {
1023 "doctype": "Stock Entry",
Sagar Sharmaccb28892022-09-08 16:04:08 +05301024 "field_no_map": ["purchase_order", "subcontracting_order"],
Sagar Sharma008542b2022-09-07 10:15:43 +05301025 },
1026 },
1027 ignore_child_tables=True,
1028 )
1029
s-aga-r6d89b2f2022-06-18 15:46:59 +05301030 ste_doc.purpose = "Material Transfer"
1031
1032 if order_doctype == "Purchase Order":
1033 ste_doc.purchase_order = order_doc.name
1034 rm_detail_field = "po_detail"
1035 else:
1036 ste_doc.subcontracting_order = order_doc.name
1037 rm_detail_field = "sco_rm_detail"
1038 ste_doc.company = order_doc.company
1039 ste_doc.is_return = 1
1040
1041 for key, value in available_materials.items():
1042 if not value.qty:
1043 continue
1044
1045 if value.batch_no:
1046 for batch_no, qty in value.batch_no.items():
1047 if qty > 0:
1048 add_items_in_ste(ste_doc, value, value.qty, rm_details, rm_detail_field, batch_no)
1049 else:
1050 add_items_in_ste(ste_doc, value, value.qty, rm_details, rm_detail_field)
1051
1052 ste_doc.set_stock_entry_type()
1053 ste_doc.calculate_rate_and_amount()
1054
1055 return ste_doc
1056
1057
1058@frappe.whitelist()
1059def get_materials_from_supplier(
1060 subcontract_order, rm_details, order_doctype="Subcontracting Order"
1061):
1062 if isinstance(rm_details, str):
1063 rm_details = json.loads(rm_details)
1064
1065 doc = frappe.get_cached_doc(order_doctype, subcontract_order)
1066 doc.initialized_fields()
1067 doc.subcontract_orders = [doc.name]
1068 doc.get_available_materials()
1069
1070 if not doc.available_materials:
1071 frappe.throw(
1072 _("Materials are already received against the {0} {1}").format(order_doctype, subcontract_order)
1073 )
1074
1075 return make_return_stock_entry_for_subcontract(
1076 doc.available_materials, doc, rm_details, order_doctype
1077 )