blob: 9555902a74cd9defa8f4c5ee2d0aa2fd72a86aa6 [file] [log] [blame]
Sagar Sharma29a1cb82022-04-26 17:29:45 +05301# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
2# For license information, please see license.txt
3
4import copy
s-aga-r6d89b2f2022-06-18 15:46:59 +05305import json
Sagar Sharma29a1cb82022-04-26 17:29:45 +05306from collections import defaultdict
7
8import frappe
9from frappe import _
Sagar Sharma008542b2022-09-07 10:15:43 +053010from frappe.model.mapper import get_mapped_doc
Rohit Waghchaure16f26fb2023-03-20 22:56:06 +053011from frappe.utils import cint, flt, get_link_to_form
Sagar Sharma29a1cb82022-04-26 17:29:45 +053012
13from erpnext.controllers.stock_controller import StockController
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +053014from erpnext.stock.doctype.serial_and_batch_bundle.serial_and_batch_bundle import (
15 get_voucher_wise_serial_batch_from_bundle,
16)
Sagar Sharma29a1cb82022-04-26 17:29:45 +053017from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
Rohit Waghchauree88c5d62023-04-05 20:03:44 +053018from erpnext.stock.serial_batch_bundle import SerialBatchCreation, get_serial_nos_from_bundle
Sagar Sharma29a1cb82022-04-26 17:29:45 +053019from erpnext.stock.utils import get_incoming_rate
20
21
22class SubcontractingController(StockController):
s-aga-r6d89b2f2022-06-18 15:46:59 +053023 def __init__(self, *args, **kwargs):
24 super(SubcontractingController, self).__init__(*args, **kwargs)
25 if self.get("is_old_subcontracting_flow"):
26 self.subcontract_data = frappe._dict(
27 {
28 "order_doctype": "Purchase Order",
29 "order_field": "purchase_order",
30 "rm_detail_field": "po_detail",
31 "receipt_supplied_items_field": "Purchase Receipt Item Supplied",
32 "order_supplied_items_field": "Purchase Order Item Supplied",
33 }
34 )
35 else:
36 self.subcontract_data = frappe._dict(
37 {
38 "order_doctype": "Subcontracting Order",
39 "order_field": "subcontracting_order",
40 "rm_detail_field": "sco_rm_detail",
41 "receipt_supplied_items_field": "Subcontracting Receipt Supplied Item",
42 "order_supplied_items_field": "Subcontracting Order Supplied Item",
43 }
44 )
45
Sagar Sharma29a1cb82022-04-26 17:29:45 +053046 def before_validate(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +053047 if self.doctype in ["Subcontracting Order", "Subcontracting Receipt"]:
48 self.remove_empty_rows()
49 self.set_items_conversion_factor()
Sagar Sharma29a1cb82022-04-26 17:29:45 +053050
51 def validate(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +053052 if self.doctype in ["Subcontracting Order", "Subcontracting Receipt"]:
53 self.validate_items()
54 self.create_raw_materials_supplied()
55 else:
56 super(SubcontractingController, self).validate()
Sagar Sharma29a1cb82022-04-26 17:29:45 +053057
s-aga-ra33b75f2023-08-24 16:37:57 +053058 def validate_rejected_warehouse(self):
59 for item in self.get("items"):
60 if flt(item.rejected_qty) and not item.rejected_warehouse:
61 if self.rejected_warehouse:
62 item.rejected_warehouse = self.rejected_warehouse
63 else:
64 frappe.throw(
65 _("Row #{0}: Rejected Warehouse is mandatory for the rejected Item {1}").format(
66 item.idx, item.item_code
67 )
68 )
69
70 if item.get("rejected_warehouse") and (item.get("rejected_warehouse") == item.get("warehouse")):
71 frappe.throw(
72 _("Row #{0}: Accepted Warehouse and Rejected Warehouse cannot be same").format(item.idx)
73 )
74
Sagar Sharma29a1cb82022-04-26 17:29:45 +053075 def remove_empty_rows(self):
76 for key in ["service_items", "items", "supplied_items"]:
77 if self.get(key):
78 idx = 1
79 for item in self.get(key)[:]:
80 if not (item.get("item_code") or item.get("main_item_code")):
81 self.get(key).remove(item)
82 else:
83 item.idx = idx
84 idx += 1
85
86 def set_items_conversion_factor(self):
87 for item in self.get("items"):
88 if not item.conversion_factor:
89 item.conversion_factor = 1
90
91 def validate_items(self):
92 for item in self.items:
Sagar Sharmafa229062022-09-30 16:18:15 +053093 is_stock_item, is_sub_contracted_item = frappe.get_value(
94 "Item", item.item_code, ["is_stock_item", "is_sub_contracted_item"]
95 )
96
97 if not is_stock_item:
s-aga-rb26e96c2023-01-12 13:41:53 +053098 frappe.throw(_("Row {0}: Item {1} must be a stock item.").format(item.idx, item.item_name))
Sagar Sharmafa229062022-09-30 16:18:15 +053099
s-aga-rafd7d592023-08-26 13:10:47 +0530100 if not item.get("is_scrap_item"):
s-aga-ra33b75f2023-08-24 16:37:57 +0530101 if not is_sub_contracted_item:
102 frappe.throw(
103 _("Row {0}: Item {1} must be a subcontracted item.").format(item.idx, item.item_name)
104 )
Sagar Sharmafa229062022-09-30 16:18:15 +0530105
s-aga-ra33b75f2023-08-24 16:37:57 +0530106 if item.bom:
107 is_active, bom_item = frappe.get_value("BOM", item.bom, ["is_active", "item"])
108
109 if not is_active:
110 frappe.throw(
111 _("Row {0}: Please select an active BOM for Item {1}.").format(item.idx, item.item_name)
112 )
113 if bom_item != item.item_code:
114 frappe.throw(
115 _("Row {0}: Please select an valid BOM for Item {1}.").format(item.idx, item.item_name)
116 )
117 else:
118 frappe.throw(_("Row {0}: Please select a BOM for Item {1}.").format(item.idx, item.item_name))
Sagar Sharma760c26e2022-11-05 15:50:39 +0530119 else:
s-aga-ra33b75f2023-08-24 16:37:57 +0530120 item.bom = None
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530121
122 def __get_data_before_save(self):
123 item_dict = {}
s-aga-r6d89b2f2022-06-18 15:46:59 +0530124 if (
125 self.doctype in ["Purchase Receipt", "Purchase Invoice", "Subcontracting Receipt"]
126 and self._doc_before_save
127 ):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530128 for row in self._doc_before_save.get("items"):
s-aga-r01f56c62022-11-15 14:32:16 +0530129 item_dict[row.name] = (row.item_code, row.qty)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530130
131 return item_dict
132
133 def __identify_change_in_item_table(self):
134 self.__changed_name = []
135 self.__reference_name = []
136
s-aga-r6d89b2f2022-06-18 15:46:59 +0530137 if self.doctype in ["Purchase Order", "Subcontracting Order"] or self.is_new():
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530138 self.set(self.raw_material_table, [])
139 return
140
141 item_dict = self.__get_data_before_save()
142 if not item_dict:
143 return True
144
145 for row in self.items:
146 self.__reference_name.append(row.name)
s-aga-r01f56c62022-11-15 14:32:16 +0530147 if (row.name not in item_dict) or (row.item_code, row.qty) != item_dict[row.name]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530148 self.__changed_name.append(row.name)
149
150 if item_dict.get(row.name):
151 del item_dict[row.name]
152
153 self.__changed_name.extend(item_dict.keys())
154
155 def __get_backflush_based_on(self):
156 self.backflush_based_on = frappe.db.get_single_value(
157 "Buying Settings", "backflush_raw_materials_of_subcontract_based_on"
158 )
159
160 def initialized_fields(self):
161 self.available_materials = frappe._dict()
162 self.__transferred_items = frappe._dict()
163 self.alternative_item_details = frappe._dict()
164 self.__get_backflush_based_on()
165
s-aga-r6d89b2f2022-06-18 15:46:59 +0530166 def __get_subcontract_orders(self):
167 self.subcontract_orders = []
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530168
s-aga-r6d89b2f2022-06-18 15:46:59 +0530169 if self.doctype in ["Purchase Order", "Subcontracting Order"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530170 return
171
s-aga-r6d89b2f2022-06-18 15:46:59 +0530172 self.subcontract_orders = [
173 item.get(self.subcontract_data.order_field)
174 for item in self.items
175 if item.get(self.subcontract_data.order_field)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530176 ]
177
178 def __get_pending_qty_to_receive(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530179 """Get qty to be received against the subcontract order."""
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530180
181 self.qty_to_be_received = defaultdict(float)
182
183 if (
s-aga-r6d89b2f2022-06-18 15:46:59 +0530184 self.doctype != self.subcontract_data.order_doctype
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530185 and self.backflush_based_on != "BOM"
s-aga-r6d89b2f2022-06-18 15:46:59 +0530186 and self.subcontract_orders
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530187 ):
188 for row in frappe.get_all(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530189 f"{self.subcontract_data.order_doctype} Item",
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530190 fields=["item_code", "(qty - received_qty) as qty", "parent", "name"],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530191 filters={"docstatus": 1, "parent": ("in", self.subcontract_orders)},
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530192 ):
193
194 self.qty_to_be_received[(row.item_code, row.parent)] += row.qty
195
196 def __get_transferred_items(self):
s-aga-r2a608842023-06-29 18:59:18 +0530197 se = frappe.qb.DocType("Stock Entry")
198 se_detail = frappe.qb.DocType("Stock Entry Detail")
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530199
s-aga-r2a608842023-06-29 18:59:18 +0530200 query = (
201 frappe.qb.from_(se)
202 .inner_join(se_detail)
203 .on(se.name == se_detail.parent)
204 .select(
205 se[self.subcontract_data.order_field],
206 se.name.as_("voucher_no"),
207 se_detail.item_code.as_("rm_item_code"),
208 se_detail.item_name,
209 se_detail.description,
210 (
211 frappe.qb.terms.Case()
212 .when(((se.purpose == "Material Transfer") & (se.is_return == 1)), -1 * se_detail.qty)
213 .else_(se_detail.qty)
214 ).as_("qty"),
215 se_detail.basic_rate.as_("rate"),
216 se_detail.amount,
217 se_detail.serial_no,
218 se_detail.serial_and_batch_bundle,
219 se_detail.uom,
220 se_detail.subcontracted_item.as_("main_item_code"),
221 se_detail.stock_uom,
222 se_detail.batch_no,
223 se_detail.conversion_factor,
224 se_detail.s_warehouse,
225 se_detail.t_warehouse,
226 se_detail.item_group,
227 se_detail[self.subcontract_data.rm_detail_field],
228 )
229 .where(
230 (se.docstatus == 1)
231 & (se[self.subcontract_data.order_field].isin(self.subcontract_orders))
232 & (
233 (se.purpose == "Send to Subcontractor")
234 | ((se.purpose == "Material Transfer") & (se.is_return == 1))
235 )
236 )
237 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530238
239 if self.backflush_based_on == "BOM":
s-aga-r2a608842023-06-29 18:59:18 +0530240 query = query.select(se_detail.original_item)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530241
s-aga-r2a608842023-06-29 18:59:18 +0530242 return query.run(as_dict=True)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530243
244 def __set_alternative_item_details(self, row):
245 if row.get("original_item"):
246 self.alternative_item_details[row.get("original_item")] = row
247
248 def __get_received_items(self, doctype):
249 fields = []
s-aga-r6d89b2f2022-06-18 15:46:59 +0530250 for field in ["name", self.subcontract_data.order_field, "parent"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530251 fields.append(f"`tab{doctype} Item`.`{field}`")
252
253 filters = [
254 [doctype, "docstatus", "=", 1],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530255 [f"{doctype} Item", self.subcontract_data.order_field, "in", self.subcontract_orders],
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530256 ]
s-aga-r6d89b2f2022-06-18 15:46:59 +0530257 if doctype == "Purchase Invoice":
258 filters.append(["Purchase Invoice", "update_stock", "=", 1])
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530259
260 return frappe.get_all(f"{doctype}", fields=fields, filters=filters)
261
s-aga-r6d89b2f2022-06-18 15:46:59 +0530262 def __get_consumed_items(self, doctype, receipt_items):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530263 return frappe.get_all(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530264 self.subcontract_data.receipt_supplied_items_field,
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530265 fields=[
266 "serial_no",
267 "rm_item_code",
268 "reference_name",
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530269 "serial_and_batch_bundle",
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530270 "batch_no",
271 "consumed_qty",
272 "main_item_code",
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530273 "parent as voucher_no",
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530274 ],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530275 filters={"docstatus": 1, "reference_name": ("in", list(receipt_items)), "parenttype": doctype},
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530276 )
277
278 def __update_consumed_materials(self, doctype, return_consumed_items=False):
279 """Deduct the consumed materials from the available materials."""
280
s-aga-r6d89b2f2022-06-18 15:46:59 +0530281 receipt_items = self.__get_received_items(doctype)
282 if not receipt_items:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530283 return ([], {}) if return_consumed_items else None
284
s-aga-r6d89b2f2022-06-18 15:46:59 +0530285 receipt_items = {
286 item.name: item.get(self.subcontract_data.order_field) for item in receipt_items
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530287 }
s-aga-r6d89b2f2022-06-18 15:46:59 +0530288 consumed_materials = self.__get_consumed_items(doctype, receipt_items.keys())
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530289
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530290 voucher_nos = [d.voucher_no for d in consumed_materials if d.voucher_no]
291 voucher_bundle_data = get_voucher_wise_serial_batch_from_bundle(
292 voucher_no=voucher_nos,
293 is_outward=1,
294 get_subcontracted_item=("Subcontracting Receipt Supplied Item", "main_item_code"),
295 )
296
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530297 if return_consumed_items:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530298 return (consumed_materials, receipt_items)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530299
300 for row in consumed_materials:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530301 key = (row.rm_item_code, row.main_item_code, receipt_items.get(row.reference_name))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530302 if not self.available_materials.get(key):
303 continue
304
305 self.available_materials[key]["qty"] -= row.consumed_qty
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530306
307 bundle_key = (row.rm_item_code, row.main_item_code, self.supplier_warehouse, row.voucher_no)
308 consumed_bundles = voucher_bundle_data.get(bundle_key, frappe._dict())
309
310 if consumed_bundles.serial_nos:
311 self.available_materials[key]["serial_no"] = list(
312 set(self.available_materials[key]["serial_no"]) - set(consumed_bundles.serial_nos)
313 )
314
315 if consumed_bundles.batch_nos:
316 for batch_no, qty in consumed_bundles.batch_nos.items():
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530317 if qty:
318 # Conumed qty is negative therefore added it instead of subtracting
319 self.available_materials[key]["batch_no"][batch_no] += qty
320 consumed_bundles.batch_nos[batch_no] += abs(qty)
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530321
Rohit Waghchaure46704642023-03-23 11:41:20 +0530322 # Will be deprecated in v16
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530323 if row.serial_no:
324 self.available_materials[key]["serial_no"] = list(
325 set(self.available_materials[key]["serial_no"]) - set(get_serial_nos(row.serial_no))
326 )
327
Rohit Waghchaure46704642023-03-23 11:41:20 +0530328 # Will be deprecated in v16
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530329 if row.batch_no:
330 self.available_materials[key]["batch_no"][row.batch_no] -= row.consumed_qty
331
332 def get_available_materials(self):
333 """Get the available raw materials which has been transferred to the supplier.
334 available_materials = {
s-aga-r6d89b2f2022-06-18 15:46:59 +0530335 (item_code, subcontracted_item, subcontract_order): {
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530336 'qty': 1, 'serial_no': [ABC], 'batch_no': {'batch1': 1}, 'data': item_details
337 }
338 }
339 """
s-aga-r6d89b2f2022-06-18 15:46:59 +0530340 if not self.subcontract_orders:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530341 return
342
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530343 transferred_items = self.__get_transferred_items()
344
345 voucher_nos = [row.voucher_no for row in transferred_items]
346 voucher_bundle_data = get_voucher_wise_serial_batch_from_bundle(
347 voucher_no=voucher_nos,
348 is_outward=0,
349 get_subcontracted_item=("Stock Entry Detail", "subcontracted_item"),
350 )
351
352 for row in transferred_items:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530353 key = (row.rm_item_code, row.main_item_code, row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530354
355 if key not in self.available_materials:
356 self.available_materials.setdefault(
357 key,
358 frappe._dict(
359 {
360 "qty": 0,
361 "serial_no": [],
362 "batch_no": defaultdict(float),
363 "item_details": row,
s-aga-r6d89b2f2022-06-18 15:46:59 +0530364 f"{self.subcontract_data.rm_detail_field}s": [],
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530365 }
366 ),
367 )
368
369 details = self.available_materials[key]
370 details.qty += row.qty
s-aga-r6d89b2f2022-06-18 15:46:59 +0530371 details[f"{self.subcontract_data.rm_detail_field}s"].append(
372 row.get(self.subcontract_data.rm_detail_field)
373 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530374
375 if row.serial_no:
376 details.serial_no.extend(get_serial_nos(row.serial_no))
377
378 if row.batch_no:
379 details.batch_no[row.batch_no] += row.qty
380
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530381 if voucher_bundle_data:
382 bundle_key = (row.rm_item_code, row.main_item_code, row.t_warehouse, row.voucher_no)
383
384 bundle_data = voucher_bundle_data.get(bundle_key, frappe._dict())
385 if bundle_data.serial_nos:
386 details.serial_no.extend(bundle_data.serial_nos)
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530387 bundle_data.serial_nos = []
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530388
389 if bundle_data.batch_nos:
390 for batch_no, qty in bundle_data.batch_nos.items():
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530391 if qty > 0:
392 details.batch_no[batch_no] += qty
393 bundle_data.batch_nos[batch_no] -= qty
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530394
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530395 self.__set_alternative_item_details(row)
396
397 self.__transferred_items = copy.deepcopy(self.available_materials)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530398 if self.get("is_old_subcontracting_flow"):
399 for doctype in ["Purchase Receipt", "Purchase Invoice"]:
400 self.__update_consumed_materials(doctype)
401 else:
402 self.__update_consumed_materials("Subcontracting Receipt")
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530403
404 def __remove_changed_rows(self):
405 if not self.__changed_name:
406 return
407
408 i = 1
409 self.set(self.raw_material_table, [])
410 for item in self._doc_before_save.supplied_items:
411 if item.reference_name in self.__changed_name:
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530412 self.__remove_serial_and_batch_bundle(item)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530413 continue
414
415 if item.reference_name not in self.__reference_name:
416 continue
417
418 item.idx = i
419 self.append("supplied_items", item)
420
421 i += 1
422
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530423 def __remove_serial_and_batch_bundle(self, item):
424 if item.serial_and_batch_bundle:
425 frappe.delete_doc("Serial and Batch Bundle", item.serial_and_batch_bundle, force=True)
426
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530427 def __get_materials_from_bom(self, item_code, bom_no, exploded_item=0):
428 doctype = "BOM Item" if not exploded_item else "BOM Explosion Item"
429 fields = [f"`tab{doctype}`.`stock_qty` / `tabBOM`.`quantity` as qty_consumed_per_unit"]
430
431 alias_dict = {
432 "item_code": "rm_item_code",
433 "name": "bom_detail_no",
434 "source_warehouse": "reserve_warehouse",
435 }
436 for field in [
437 "item_code",
438 "name",
439 "rate",
440 "stock_uom",
441 "source_warehouse",
442 "description",
443 "item_name",
444 "stock_uom",
445 ]:
446 fields.append(f"`tab{doctype}`.`{field}` As {alias_dict.get(field, field)}")
447
448 filters = [
449 [doctype, "parent", "=", bom_no],
450 [doctype, "docstatus", "=", 1],
451 ["BOM", "item", "=", item_code],
452 [doctype, "sourced_by_supplier", "=", 0],
453 ]
454
455 return (
456 frappe.get_all("BOM", fields=fields, filters=filters, order_by=f"`tab{doctype}`.`idx`") or []
457 )
458
459 def __update_reserve_warehouse(self, row, item):
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 row.reserve_warehouse = self.set_reserve_warehouse or item.warehouse
462
463 def __set_alternative_item(self, bom_item):
464 if self.alternative_item_details.get(bom_item.rm_item_code):
465 bom_item.update(self.alternative_item_details[bom_item.rm_item_code])
466
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530467 def __set_serial_and_batch_bundle(self, item_row, rm_obj, qty):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530468 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 +0530469 if not self.available_materials.get(key):
470 return
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530471
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530472 if (
473 not self.available_materials[key]["serial_no"] and not self.available_materials[key]["batch_no"]
474 ):
475 return
Rohit Waghchaure156e4592023-02-16 13:21:17 +0530476
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530477 serial_nos = []
478 batches = frappe._dict({})
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530479
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530480 if self.available_materials.get(key) and self.available_materials[key]["serial_no"]:
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530481 serial_nos = self.__get_serial_nos_for_bundle(qty, key)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530482
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530483 elif self.available_materials.get(key) and self.available_materials[key]["batch_no"]:
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530484 batches = self.__get_batch_nos_for_bundle(qty, key)
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530485
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530486 bundle = SerialBatchCreation(
487 frappe._dict(
488 {
489 "company": self.company,
490 "item_code": rm_obj.rm_item_code,
491 "warehouse": self.supplier_warehouse,
492 "qty": qty,
493 "serial_nos": serial_nos,
494 "batches": batches,
495 "posting_date": self.posting_date,
496 "posting_time": self.posting_time,
497 "voucher_type": "Subcontracting Receipt",
498 "do_not_submit": True,
499 "type_of_transaction": "Outward" if qty > 0 else "Inward",
500 }
501 )
502 ).make_serial_and_batch_bundle()
503
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530504 return bundle.name
505
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530506 def __get_batch_nos_for_bundle(self, qty, key):
507 available_batches = defaultdict(float)
508
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530509 for batch_no, batch_qty in self.available_materials[key]["batch_no"].items():
510 qty_to_consumed = 0
511 if qty > 0:
512 if batch_qty >= qty:
513 qty_to_consumed = qty
514 else:
515 qty_to_consumed = batch_qty
516
517 qty -= qty_to_consumed
518 if qty_to_consumed > 0:
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530519 available_batches[batch_no] += qty_to_consumed
520 self.available_materials[key]["batch_no"][batch_no] -= qty_to_consumed
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530521
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530522 return available_batches
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530523
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530524 def __get_serial_nos_for_bundle(self, qty, key):
525 available_sns = sorted(self.available_materials[key]["serial_no"])[0 : cint(qty)]
526 serial_nos = []
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530527
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530528 for serial_no in available_sns:
529 serial_nos.append(serial_no)
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530530
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530531 self.available_materials[key]["serial_no"].remove(serial_no)
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530532
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530533 return serial_nos
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530534
535 def __add_supplied_item(self, item_row, bom_item, qty):
536 bom_item.conversion_factor = item_row.conversion_factor
537 rm_obj = self.append(self.raw_material_table, bom_item)
538 rm_obj.reference_name = item_row.name
539
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530540 if self.doctype == self.subcontract_data.order_doctype:
541 rm_obj.required_qty = qty
542 rm_obj.amount = rm_obj.required_qty * rm_obj.rate
543 else:
544 rm_obj.consumed_qty = qty
545 rm_obj.required_qty = bom_item.required_qty or qty
546 setattr(
547 rm_obj, self.subcontract_data.order_field, item_row.get(self.subcontract_data.order_field)
548 )
549
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530550 if self.doctype == "Subcontracting Receipt":
551 args = frappe._dict(
552 {
553 "item_code": rm_obj.rm_item_code,
554 "warehouse": self.supplier_warehouse,
555 "posting_date": self.posting_date,
556 "posting_time": self.posting_time,
557 "qty": -1 * flt(rm_obj.consumed_qty),
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530558 "actual_qty": -1 * flt(rm_obj.consumed_qty),
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530559 "voucher_type": self.doctype,
560 "voucher_no": self.name,
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530561 "voucher_detail_no": item_row.name,
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530562 "company": self.company,
563 "allow_zero_valuation": 1,
564 }
565 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530566
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530567 rm_obj.serial_and_batch_bundle = self.__set_serial_and_batch_bundle(
568 item_row, rm_obj, rm_obj.consumed_qty
569 )
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530570
571 if rm_obj.serial_and_batch_bundle:
572 args["serial_and_batch_bundle"] = rm_obj.serial_and_batch_bundle
573
s-aga-r758b31d2023-08-05 19:28:38 +0530574 rm_obj.rate = get_incoming_rate(args)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530575
576 def __get_qty_based_on_material_transfer(self, item_row, transfer_item):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530577 key = (item_row.item_code, item_row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530578
s-aga-r01f56c62022-11-15 14:32:16 +0530579 if self.qty_to_be_received == item_row.qty:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530580 return transfer_item.qty
581
582 if self.qty_to_be_received:
s-aga-r01f56c62022-11-15 14:32:16 +0530583 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 +0530584 transfer_item.item_details.required_qty = transfer_item.qty
585
586 if transfer_item.serial_no or frappe.get_cached_value(
587 "UOM", transfer_item.item_details.stock_uom, "must_be_whole_number"
588 ):
589 return frappe.utils.ceil(qty)
590
591 return qty
592
593 def __set_supplied_items(self):
594 self.bom_items = {}
595
596 has_supplied_items = True if self.get(self.raw_material_table) else False
597 for row in self.items:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530598 if self.doctype != self.subcontract_data.order_doctype and (
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530599 (self.__changed_name and row.name not in self.__changed_name)
600 or (has_supplied_items and not self.__changed_name)
601 ):
602 continue
603
s-aga-r6d89b2f2022-06-18 15:46:59 +0530604 if self.doctype == self.subcontract_data.order_doctype or self.backflush_based_on == "BOM":
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530605 for bom_item in self.__get_materials_from_bom(
606 row.item_code, row.bom, row.get("include_exploded_items")
607 ):
s-aga-r01f56c62022-11-15 14:32:16 +0530608 qty = flt(bom_item.qty_consumed_per_unit) * flt(row.qty) * row.conversion_factor
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530609 bom_item.main_item_code = row.item_code
610 self.__update_reserve_warehouse(bom_item, row)
611 self.__set_alternative_item(bom_item)
612 self.__add_supplied_item(row, bom_item, qty)
613
614 elif self.backflush_based_on != "BOM":
615 for key, transfer_item in self.available_materials.items():
s-aga-r6d89b2f2022-06-18 15:46:59 +0530616 if (key[1], key[2]) == (
617 row.item_code,
618 row.get(self.subcontract_data.order_field),
619 ) and transfer_item.qty > 0:
Sagar Sharmaaddd7342022-08-19 11:46:27 +0530620 qty = flt(self.__get_qty_based_on_material_transfer(row, transfer_item))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530621 transfer_item.qty -= qty
622 self.__add_supplied_item(row, transfer_item.get("item_details"), qty)
623
624 if self.qty_to_be_received:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530625 self.qty_to_be_received[
626 (row.item_code, row.get(self.subcontract_data.order_field))
627 ] -= row.qty
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530628
rohitwaghchaure3e77c0b2023-11-14 19:27:41 +0530629 def __set_rate_for_serial_and_batch_bundle(self):
630 if self.doctype != "Subcontracting Receipt":
631 return
632
633 for row in self.get(self.raw_material_table):
634 if not row.get("serial_and_batch_bundle"):
635 continue
636
637 row.rate = frappe.get_cached_value(
638 "Serial and Batch Bundle", row.serial_and_batch_bundle, "avg_rate"
639 )
640
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530641 def __modify_serial_and_batch_bundle(self):
642 if self.is_new():
643 return
644
645 if self.doctype != "Subcontracting Receipt":
646 return
647
648 for item_row in self.items:
649 if self.__changed_name and item_row.name in self.__changed_name:
650 continue
651
652 modified_data = self.__get_bundle_to_modify(item_row.name)
653 if modified_data:
654 serial_nos = []
655 batches = frappe._dict({})
656 key = (
657 modified_data.rm_item_code,
658 item_row.item_code,
659 item_row.get(self.subcontract_data.order_field),
660 )
661
662 if self.available_materials.get(key) and self.available_materials[key]["serial_no"]:
663 serial_nos = self.__get_serial_nos_for_bundle(modified_data.consumed_qty, key)
664
665 elif self.available_materials.get(key) and self.available_materials[key]["batch_no"]:
666 batches = self.__get_batch_nos_for_bundle(modified_data.consumed_qty, key)
667
668 SerialBatchCreation(
669 {
670 "item_code": modified_data.rm_item_code,
671 "warehouse": self.supplier_warehouse,
672 "serial_and_batch_bundle": modified_data.serial_and_batch_bundle,
673 "type_of_transaction": "Outward",
674 "serial_nos": serial_nos,
675 "batches": batches,
676 "qty": modified_data.consumed_qty * -1,
677 }
678 ).update_serial_and_batch_entries()
679
680 def __get_bundle_to_modify(self, name):
681 for row in self.get("supplied_items"):
682 if row.reference_name == name and row.serial_and_batch_bundle:
683 if row.consumed_qty != abs(
684 frappe.get_cached_value("Serial and Batch Bundle", row.serial_and_batch_bundle, "total_qty")
685 ):
686 return row
687
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530688 def __prepare_supplied_items(self):
689 self.initialized_fields()
s-aga-r6d89b2f2022-06-18 15:46:59 +0530690 self.__get_subcontract_orders()
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530691 self.__get_pending_qty_to_receive()
692 self.get_available_materials()
693 self.__remove_changed_rows()
694 self.__set_supplied_items()
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530695 self.__modify_serial_and_batch_bundle()
rohitwaghchaure3e77c0b2023-11-14 19:27:41 +0530696 self.__set_rate_for_serial_and_batch_bundle()
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530697
698 def __validate_batch_no(self, row, key):
699 if row.get("batch_no") and row.get("batch_no") not in self.__transferred_items.get(key).get(
700 "batch_no"
701 ):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530702 link = get_link_to_form(
703 self.subcontract_data.order_doctype, row.get(self.subcontract_data.order_field)
704 )
705 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 +0530706 frappe.throw(_(msg), title=_("Incorrect Batch Consumed"))
707
708 def __validate_serial_no(self, row, key):
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530709 if row.get("serial_and_batch_bundle") and self.__transferred_items.get(key).get("serial_no"):
710 serial_nos = get_serial_nos_from_bundle(row.get("serial_and_batch_bundle"))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530711 incorrect_sn = set(serial_nos).difference(self.__transferred_items.get(key).get("serial_no"))
712
713 if incorrect_sn:
714 incorrect_sn = "\n".join(incorrect_sn)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530715 link = get_link_to_form(
716 self.subcontract_data.order_doctype, row.get(self.subcontract_data.order_field)
717 )
718 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 +0530719 frappe.throw(_(msg), title=_("Incorrect Serial Number Consumed"))
720
721 def __validate_supplied_items(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530722 if self.doctype not in ["Purchase Invoice", "Purchase Receipt", "Subcontracting Receipt"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530723 return
724
725 for row in self.get(self.raw_material_table):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530726 key = (row.rm_item_code, row.main_item_code, row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530727 if not self.__transferred_items or not self.__transferred_items.get(key):
728 return
729
730 self.__validate_batch_no(row, key)
731 self.__validate_serial_no(row, key)
732
733 def set_materials_for_subcontracted_items(self, raw_material_table):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530734 if self.doctype == "Purchase Invoice" and not self.update_stock:
735 return
736
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530737 self.raw_material_table = raw_material_table
738 self.__identify_change_in_item_table()
739 self.__prepare_supplied_items()
740 self.__validate_supplied_items()
741
742 def create_raw_materials_supplied(self, raw_material_table="supplied_items"):
743 self.set_materials_for_subcontracted_items(raw_material_table)
744
s-aga-r6d89b2f2022-06-18 15:46:59 +0530745 if self.doctype in ["Subcontracting Receipt", "Purchase Receipt", "Purchase Invoice"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530746 for item in self.get("items"):
747 item.rm_supp_cost = 0.0
748
s-aga-r6d89b2f2022-06-18 15:46:59 +0530749 def __update_consumed_qty_in_subcontract_order(self, itemwise_consumed_qty):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530750 fields = ["main_item_code", "rm_item_code", "parent", "supplied_qty", "name"]
s-aga-r6d89b2f2022-06-18 15:46:59 +0530751 filters = {"docstatus": 1, "parent": ("in", self.subcontract_orders)}
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530752
753 for row in frappe.get_all(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530754 self.subcontract_data.order_supplied_items_field, fields=fields, filters=filters, order_by="idx"
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530755 ):
756 key = (row.rm_item_code, row.main_item_code, row.parent)
757 consumed_qty = itemwise_consumed_qty.get(key, 0)
758
759 if row.supplied_qty < consumed_qty:
760 consumed_qty = row.supplied_qty
761
762 itemwise_consumed_qty[key] -= consumed_qty
763 frappe.db.set_value(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530764 self.subcontract_data.order_supplied_items_field, row.name, "consumed_qty", consumed_qty
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530765 )
766
s-aga-r6d89b2f2022-06-18 15:46:59 +0530767 def set_consumed_qty_in_subcontract_order(self):
768 # Update consumed qty back in the subcontract order
769 if self.doctype in ["Subcontracting Order", "Subcontracting Receipt"] or self.get(
770 "is_old_subcontracting_flow"
771 ):
772 self.__get_subcontract_orders()
773 itemwise_consumed_qty = defaultdict(float)
774 if self.get("is_old_subcontracting_flow"):
775 doctypes = ["Purchase Receipt", "Purchase Invoice"]
776 else:
777 doctypes = ["Subcontracting Receipt"]
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530778
s-aga-r6d89b2f2022-06-18 15:46:59 +0530779 for doctype in doctypes:
780 consumed_items, receipt_items = self.__update_consumed_materials(
781 doctype, return_consumed_items=True
782 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530783
s-aga-r6d89b2f2022-06-18 15:46:59 +0530784 for row in consumed_items:
785 key = (row.rm_item_code, row.main_item_code, receipt_items.get(row.reference_name))
786 itemwise_consumed_qty[key] += row.consumed_qty
787
788 self.__update_consumed_qty_in_subcontract_order(itemwise_consumed_qty)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530789
790 def update_ordered_and_reserved_qty(self):
791 sco_map = {}
792 for item in self.get("items"):
793 if self.doctype == "Subcontracting Receipt" and item.subcontracting_order:
794 sco_map.setdefault(item.subcontracting_order, []).append(item.subcontracting_order_item)
795
796 for sco, sco_item_rows in sco_map.items():
797 if sco and sco_item_rows:
798 sco_doc = frappe.get_doc("Subcontracting Order", sco)
799
800 if sco_doc.status in ["Closed", "Cancelled"]:
801 frappe.throw(
802 _("{0} {1} is cancelled or closed").format(_("Subcontracting Order"), sco),
803 frappe.InvalidStatusError,
804 )
805
806 sco_doc.update_ordered_qty_for_subcontracting(sco_item_rows)
807 sco_doc.update_reserved_qty_for_subcontracting()
808
809 def make_sl_entries_for_supplier_warehouse(self, sl_entries):
810 if hasattr(self, "supplied_items"):
811 for item in self.get("supplied_items"):
812 # negative quantity is passed, as raw material qty has to be decreased
813 # when SCR is submitted and it has to be increased when SCR is cancelled
814 sl_entries.append(
815 self.get_sl_entries(
816 item,
817 {
818 "item_code": item.rm_item_code,
819 "warehouse": self.supplier_warehouse,
mergify[bot]d558ba22023-09-26 17:55:16 +0530820 "actual_qty": -1 * flt(item.consumed_qty, item.precision("consumed_qty")),
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530821 "dependant_sle_voucher_detail_no": item.reference_name,
822 },
823 )
824 )
825
826 def update_stock_ledger(self, allow_negative_stock=False, via_landed_cost_voucher=False):
827 self.update_ordered_and_reserved_qty()
828
829 sl_entries = []
830 stock_items = self.get_stock_items()
831
832 for item in self.get("items"):
833 if item.item_code in stock_items and item.warehouse:
834 scr_qty = flt(item.qty) * flt(item.conversion_factor)
835
836 if scr_qty:
Rohit Waghchaure16f26fb2023-03-20 22:56:06 +0530837 sle = self.get_sl_entries(item, {"actual_qty": flt(scr_qty)})
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530838 rate_db_precision = 6 if cint(self.precision("rate", item)) <= 6 else 9
839 incoming_rate = flt(item.rate, rate_db_precision)
840 sle.update(
841 {
842 "incoming_rate": incoming_rate,
843 "recalculate_rate": 1,
844 }
845 )
846 sl_entries.append(sle)
847
848 if flt(item.rejected_qty) != 0:
849 sl_entries.append(
850 self.get_sl_entries(
851 item,
852 {
853 "warehouse": item.rejected_warehouse,
854 "actual_qty": flt(item.rejected_qty) * flt(item.conversion_factor),
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530855 "incoming_rate": 0.0,
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530856 },
857 )
858 )
859
860 self.make_sl_entries_for_supplier_warehouse(sl_entries)
861 self.make_sl_entries(
862 sl_entries,
863 allow_negative_stock=allow_negative_stock,
864 via_landed_cost_voucher=via_landed_cost_voucher,
865 )
866
s-aga-r6d89b2f2022-06-18 15:46:59 +0530867 def get_supplied_items_cost(self, item_row_id, reset_outgoing_rate=True):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530868 supplied_items_cost = 0.0
869 for item in self.get("supplied_items"):
870 if item.reference_name == item_row_id:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530871 if (
872 self.get("is_old_subcontracting_flow")
873 and reset_outgoing_rate
874 and frappe.get_cached_value("Item", item.rm_item_code, "is_stock_item")
875 ):
876 rate = get_incoming_rate(
877 {
878 "item_code": item.rm_item_code,
879 "warehouse": self.supplier_warehouse,
880 "posting_date": self.posting_date,
881 "posting_time": self.posting_time,
882 "qty": -1 * item.consumed_qty,
rohitwaghchaure5e9016f2023-12-01 21:42:22 +0530883 "voucher_detail_no": item.name,
Rohit Waghchaure46704642023-03-23 11:41:20 +0530884 "serial_and_batch_bundle": item.serial_and_batch_bundle,
s-aga-r6d89b2f2022-06-18 15:46:59 +0530885 }
886 )
887
888 if rate > 0:
889 item.rate = rate
890
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530891 item.amount = flt(flt(item.consumed_qty) * flt(item.rate), item.precision("amount"))
892 supplied_items_cost += item.amount
893
894 return supplied_items_cost
895
Sagar Sharma249726b2022-04-22 17:09:19 +0530896 def set_subcontracting_order_status(self):
897 if self.doctype == "Subcontracting Order":
898 self.update_status()
899 elif self.doctype == "Subcontracting Receipt":
s-aga-r6d89b2f2022-06-18 15:46:59 +0530900 self.__get_subcontract_orders
Sagar Sharma249726b2022-04-22 17:09:19 +0530901
s-aga-r6d89b2f2022-06-18 15:46:59 +0530902 if self.subcontract_orders:
903 for sco in set(self.subcontract_orders):
Sagar Sharma249726b2022-04-22 17:09:19 +0530904 sco_doc = frappe.get_doc("Subcontracting Order", sco)
905 sco_doc.update_status()
906
Sagar Sharmad6433f82023-05-12 11:45:33 +0530907 def calculate_additional_costs(self):
Sagar Sharmaea82fe52022-08-18 17:20:22 +0530908 self.total_additional_costs = sum(flt(item.amount) for item in self.get("additional_costs"))
909
910 if self.total_additional_costs:
911 if self.distribute_additional_costs_based_on == "Amount":
s-aga-r1504ff82023-08-25 20:18:30 +0530912 total_amt = sum(
913 flt(item.amount) for item in self.get("items") if not item.get("is_scrap_item")
914 )
Sagar Sharmaea82fe52022-08-18 17:20:22 +0530915 for item in self.items:
s-aga-r1504ff82023-08-25 20:18:30 +0530916 if not item.get("is_scrap_item"):
917 item.additional_cost_per_qty = (
918 (item.amount * self.total_additional_costs) / total_amt
919 ) / item.qty
Sagar Sharmaea82fe52022-08-18 17:20:22 +0530920 else:
s-aga-r1504ff82023-08-25 20:18:30 +0530921 total_qty = sum(flt(item.qty) for item in self.get("items") if not item.get("is_scrap_item"))
Sagar Sharmaea82fe52022-08-18 17:20:22 +0530922 additional_cost_per_qty = self.total_additional_costs / total_qty
923 for item in self.items:
s-aga-r1504ff82023-08-25 20:18:30 +0530924 if not item.get("is_scrap_item"):
925 item.additional_cost_per_qty = additional_cost_per_qty
Sagar Sharmaea82fe52022-08-18 17:20:22 +0530926 else:
927 for item in self.items:
s-aga-r1504ff82023-08-25 20:18:30 +0530928 if not item.get("is_scrap_item"):
929 item.additional_cost_per_qty = 0
Sagar Sharmaea82fe52022-08-18 17:20:22 +0530930
s-aga-r6d89b2f2022-06-18 15:46:59 +0530931 @frappe.whitelist()
932 def get_current_stock(self):
933 if self.doctype in ["Purchase Receipt", "Subcontracting Receipt"]:
934 for item in self.get("supplied_items"):
935 if self.supplier_warehouse:
936 actual_qty = frappe.db.get_value(
937 "Bin",
938 {"item_code": item.rm_item_code, "warehouse": self.supplier_warehouse},
939 "actual_qty",
940 )
Sagar Sharmaaddd7342022-08-19 11:46:27 +0530941 item.current_stock = flt(actual_qty)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530942
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530943 @property
944 def sub_contracted_items(self):
945 if not hasattr(self, "_sub_contracted_items"):
946 self._sub_contracted_items = []
947 item_codes = list(set(item.item_code for item in self.get("items")))
948 if item_codes:
949 items = frappe.get_all(
950 "Item", filters={"name": ["in", item_codes], "is_sub_contracted_item": 1}
951 )
952 self._sub_contracted_items = [item.name for item in items]
953
954 return self._sub_contracted_items
s-aga-r6d89b2f2022-06-18 15:46:59 +0530955
Rohit Waghchaure691e3bb2023-11-30 10:25:22 +0530956 def update_requested_qty(self):
957 material_request_map = {}
958 for d in self.get("items"):
959 if d.material_request_item:
960 material_request_map.setdefault(d.material_request, []).append(d.material_request_item)
961
962 for mr, mr_item_rows in material_request_map.items():
963 if mr and mr_item_rows:
964 mr_obj = frappe.get_doc("Material Request", mr)
965
966 if mr_obj.status in ["Stopped", "Cancelled"]:
967 frappe.throw(
968 _("Material Request {0} is cancelled or stopped").format(mr), frappe.InvalidStatusError
969 )
970
971 mr_obj.update_requested_qty(mr_item_rows)
972
s-aga-r6d89b2f2022-06-18 15:46:59 +0530973
974def get_item_details(items):
975 item = frappe.qb.DocType("Item")
976 item_list = (
977 frappe.qb.from_(item)
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530978 .select(item.item_code, item.item_name, item.description, item.allow_alternative_item)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530979 .where(item.name.isin(items))
980 .run(as_dict=True)
981 )
982
983 item_details = {}
984 for item in item_list:
985 item_details[item.item_code] = item
986
987 return item_details
988
989
990@frappe.whitelist()
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530991def make_rm_stock_entry(
992 subcontract_order, rm_items=None, order_doctype="Subcontracting Order", target_doc=None
993):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530994 if subcontract_order:
995 subcontract_order = frappe.get_doc(order_doctype, subcontract_order)
996
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530997 if not rm_items:
998 if not subcontract_order.supplied_items:
999 frappe.throw(_("No item available for transfer."))
s-aga-r6d89b2f2022-06-18 15:46:59 +05301000
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301001 rm_items = subcontract_order.supplied_items
s-aga-r6d89b2f2022-06-18 15:46:59 +05301002
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301003 fg_item_code_list = list(
1004 set(item.get("main_item_code") or item.get("item_code") for item in rm_items)
1005 )
s-aga-r6d89b2f2022-06-18 15:46:59 +05301006
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301007 if fg_item_code_list:
1008 rm_item_code_list = tuple(set(item.get("rm_item_code") for item in rm_items))
1009 item_wh = get_item_details(rm_item_code_list)
1010
1011 field_no_map, rm_detail_field = "purchase_order", "sco_rm_detail"
1012 if order_doctype == "Purchase Order":
1013 field_no_map, rm_detail_field = "subcontracting_order", "po_detail"
1014
1015 if target_doc and target_doc.get("items"):
1016 target_doc.items = []
1017
1018 stock_entry = get_mapped_doc(
1019 order_doctype,
1020 subcontract_order.name,
1021 {
1022 order_doctype: {
1023 "doctype": "Stock Entry",
1024 "field_map": {
s-aga-r751bdc92022-12-31 17:17:22 +05301025 "supplier": "supplier",
1026 "supplier_name": "supplier_name",
1027 "supplier_address": "supplier_address",
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301028 "to_warehouse": "supplier_warehouse",
1029 },
1030 "field_no_map": [field_no_map],
1031 "validation": {
1032 "docstatus": ["=", 1],
1033 },
1034 },
1035 },
1036 target_doc,
1037 ignore_child_tables=True,
1038 )
1039
1040 stock_entry.purpose = "Send to Subcontractor"
1041
1042 if order_doctype == "Purchase Order":
1043 stock_entry.purchase_order = subcontract_order.name
1044 else:
1045 stock_entry.subcontracting_order = subcontract_order.name
1046
1047 stock_entry.set_stock_entry_type()
1048
1049 for fg_item_code in fg_item_code_list:
1050 for rm_item in rm_items:
1051
Sagar Sharmaac7409b2022-09-28 16:46:48 +05301052 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 +05301053 rm_item_code = rm_item.get("rm_item_code")
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301054 items_dict = {
1055 rm_item_code: {
1056 rm_detail_field: rm_item.get("name"),
1057 "item_name": rm_item.get("item_name")
1058 or item_wh.get(rm_item_code, {}).get("item_name", ""),
1059 "description": item_wh.get(rm_item_code, {}).get("description", ""),
1060 "qty": rm_item.get("qty")
1061 or max(rm_item.get("required_qty") - rm_item.get("total_supplied_qty"), 0),
1062 "from_warehouse": rm_item.get("warehouse") or rm_item.get("reserve_warehouse"),
1063 "to_warehouse": subcontract_order.supplier_warehouse,
1064 "stock_uom": rm_item.get("stock_uom"),
Rohit Waghchauree88c5d62023-04-05 20:03:44 +05301065 "serial_and_batch_bundle": rm_item.get("serial_and_batch_bundle"),
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301066 "main_item_code": fg_item_code,
1067 "allow_alternative_item": item_wh.get(rm_item_code, {}).get("allow_alternative_item"),
1068 }
s-aga-r6d89b2f2022-06-18 15:46:59 +05301069 }
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301070
1071 stock_entry.add_to_stock_entry_detail(items_dict)
1072
1073 if target_doc:
1074 return stock_entry
1075 else:
1076 return stock_entry.as_dict()
1077 else:
1078 frappe.throw(_("No Items selected for transfer."))
s-aga-r6d89b2f2022-06-18 15:46:59 +05301079
1080
1081def add_items_in_ste(
1082 ste_doc, row, qty, rm_details, rm_detail_field="sco_rm_detail", batch_no=None
1083):
1084 item = ste_doc.append("items", row.item_details)
1085
1086 rm_detail = list(set(row.get(f"{rm_detail_field}s")).intersection(rm_details))
1087 item.update(
1088 {
1089 "qty": qty,
1090 "batch_no": batch_no,
1091 "basic_rate": row.item_details["rate"],
1092 rm_detail_field: rm_detail[0] if rm_detail else "",
1093 "s_warehouse": row.item_details["t_warehouse"],
1094 "t_warehouse": row.item_details["s_warehouse"],
1095 "item_code": row.item_details["rm_item_code"],
1096 "subcontracted_item": row.item_details["main_item_code"],
1097 "serial_no": "\n".join(row.serial_no) if row.serial_no else "",
1098 }
1099 )
1100
1101
1102def make_return_stock_entry_for_subcontract(
1103 available_materials, order_doc, rm_details, order_doctype="Subcontracting Order"
1104):
Sagar Sharma008542b2022-09-07 10:15:43 +05301105 ste_doc = get_mapped_doc(
1106 order_doctype,
1107 order_doc.name,
1108 {
1109 order_doctype: {
1110 "doctype": "Stock Entry",
Sagar Sharmaccb28892022-09-08 16:04:08 +05301111 "field_no_map": ["purchase_order", "subcontracting_order"],
Sagar Sharma008542b2022-09-07 10:15:43 +05301112 },
1113 },
1114 ignore_child_tables=True,
1115 )
1116
s-aga-r6d89b2f2022-06-18 15:46:59 +05301117 ste_doc.purpose = "Material Transfer"
1118
1119 if order_doctype == "Purchase Order":
1120 ste_doc.purchase_order = order_doc.name
1121 rm_detail_field = "po_detail"
1122 else:
1123 ste_doc.subcontracting_order = order_doc.name
1124 rm_detail_field = "sco_rm_detail"
1125 ste_doc.company = order_doc.company
1126 ste_doc.is_return = 1
1127
1128 for key, value in available_materials.items():
1129 if not value.qty:
1130 continue
1131
1132 if value.batch_no:
1133 for batch_no, qty in value.batch_no.items():
1134 if qty > 0:
1135 add_items_in_ste(ste_doc, value, value.qty, rm_details, rm_detail_field, batch_no)
1136 else:
1137 add_items_in_ste(ste_doc, value, value.qty, rm_details, rm_detail_field)
1138
1139 ste_doc.set_stock_entry_type()
s-aga-r6d89b2f2022-06-18 15:46:59 +05301140
1141 return ste_doc
1142
1143
1144@frappe.whitelist()
1145def get_materials_from_supplier(
1146 subcontract_order, rm_details, order_doctype="Subcontracting Order"
1147):
1148 if isinstance(rm_details, str):
1149 rm_details = json.loads(rm_details)
1150
1151 doc = frappe.get_cached_doc(order_doctype, subcontract_order)
1152 doc.initialized_fields()
1153 doc.subcontract_orders = [doc.name]
1154 doc.get_available_materials()
1155
1156 if not doc.available_materials:
1157 frappe.throw(
1158 _("Materials are already received against the {0} {1}").format(order_doctype, subcontract_order)
1159 )
1160
1161 return make_return_stock_entry_for_subcontract(
1162 doc.available_materials, doc, rm_details, order_doctype
1163 )