blob: 57339bf4cafa8cd6f356764c45de67829967eb8e [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
58 def remove_empty_rows(self):
59 for key in ["service_items", "items", "supplied_items"]:
60 if self.get(key):
61 idx = 1
62 for item in self.get(key)[:]:
63 if not (item.get("item_code") or item.get("main_item_code")):
64 self.get(key).remove(item)
65 else:
66 item.idx = idx
67 idx += 1
68
69 def set_items_conversion_factor(self):
70 for item in self.get("items"):
71 if not item.conversion_factor:
72 item.conversion_factor = 1
73
74 def validate_items(self):
75 for item in self.items:
Sagar Sharmafa229062022-09-30 16:18:15 +053076 is_stock_item, is_sub_contracted_item = frappe.get_value(
77 "Item", item.item_code, ["is_stock_item", "is_sub_contracted_item"]
78 )
79
80 if not is_stock_item:
s-aga-rb26e96c2023-01-12 13:41:53 +053081 frappe.throw(_("Row {0}: Item {1} must be a stock item.").format(item.idx, item.item_name))
Sagar Sharmafa229062022-09-30 16:18:15 +053082
83 if not is_sub_contracted_item:
s-aga-rb26e96c2023-01-12 13:41:53 +053084 frappe.throw(
85 _("Row {0}: Item {1} must be a subcontracted item.").format(item.idx, item.item_name)
86 )
Sagar Sharmafa229062022-09-30 16:18:15 +053087
Sagar Sharma29a1cb82022-04-26 17:29:45 +053088 if item.bom:
89 bom = frappe.get_doc("BOM", item.bom)
90 if not bom.is_active:
s-aga-rb26e96c2023-01-12 13:41:53 +053091 frappe.throw(
92 _("Row {0}: Please select an active BOM for Item {1}.").format(item.idx, item.item_name)
93 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +053094 if bom.item != item.item_code:
s-aga-rb26e96c2023-01-12 13:41:53 +053095 frappe.throw(
96 _("Row {0}: Please select an valid BOM for Item {1}.").format(item.idx, item.item_name)
97 )
Sagar Sharma760c26e2022-11-05 15:50:39 +053098 else:
s-aga-rb26e96c2023-01-12 13:41:53 +053099 frappe.throw(_("Row {0}: Please select a BOM for Item {1}.").format(item.idx, item.item_name))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530100
101 def __get_data_before_save(self):
102 item_dict = {}
s-aga-r6d89b2f2022-06-18 15:46:59 +0530103 if (
104 self.doctype in ["Purchase Receipt", "Purchase Invoice", "Subcontracting Receipt"]
105 and self._doc_before_save
106 ):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530107 for row in self._doc_before_save.get("items"):
s-aga-r01f56c62022-11-15 14:32:16 +0530108 item_dict[row.name] = (row.item_code, row.qty)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530109
110 return item_dict
111
112 def __identify_change_in_item_table(self):
113 self.__changed_name = []
114 self.__reference_name = []
115
s-aga-r6d89b2f2022-06-18 15:46:59 +0530116 if self.doctype in ["Purchase Order", "Subcontracting Order"] or self.is_new():
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530117 self.set(self.raw_material_table, [])
118 return
119
120 item_dict = self.__get_data_before_save()
121 if not item_dict:
122 return True
123
124 for row in self.items:
125 self.__reference_name.append(row.name)
s-aga-r01f56c62022-11-15 14:32:16 +0530126 if (row.name not in item_dict) or (row.item_code, row.qty) != item_dict[row.name]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530127 self.__changed_name.append(row.name)
128
129 if item_dict.get(row.name):
130 del item_dict[row.name]
131
132 self.__changed_name.extend(item_dict.keys())
133
134 def __get_backflush_based_on(self):
135 self.backflush_based_on = frappe.db.get_single_value(
136 "Buying Settings", "backflush_raw_materials_of_subcontract_based_on"
137 )
138
139 def initialized_fields(self):
140 self.available_materials = frappe._dict()
141 self.__transferred_items = frappe._dict()
142 self.alternative_item_details = frappe._dict()
143 self.__get_backflush_based_on()
144
s-aga-r6d89b2f2022-06-18 15:46:59 +0530145 def __get_subcontract_orders(self):
146 self.subcontract_orders = []
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530147
s-aga-r6d89b2f2022-06-18 15:46:59 +0530148 if self.doctype in ["Purchase Order", "Subcontracting Order"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530149 return
150
s-aga-r6d89b2f2022-06-18 15:46:59 +0530151 self.subcontract_orders = [
152 item.get(self.subcontract_data.order_field)
153 for item in self.items
154 if item.get(self.subcontract_data.order_field)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530155 ]
156
157 def __get_pending_qty_to_receive(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530158 """Get qty to be received against the subcontract order."""
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530159
160 self.qty_to_be_received = defaultdict(float)
161
162 if (
s-aga-r6d89b2f2022-06-18 15:46:59 +0530163 self.doctype != self.subcontract_data.order_doctype
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530164 and self.backflush_based_on != "BOM"
s-aga-r6d89b2f2022-06-18 15:46:59 +0530165 and self.subcontract_orders
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530166 ):
167 for row in frappe.get_all(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530168 f"{self.subcontract_data.order_doctype} Item",
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530169 fields=["item_code", "(qty - received_qty) as qty", "parent", "name"],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530170 filters={"docstatus": 1, "parent": ("in", self.subcontract_orders)},
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530171 ):
172
173 self.qty_to_be_received[(row.item_code, row.parent)] += row.qty
174
175 def __get_transferred_items(self):
s-aga-r2a608842023-06-29 18:59:18 +0530176 se = frappe.qb.DocType("Stock Entry")
177 se_detail = frappe.qb.DocType("Stock Entry Detail")
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530178
s-aga-r2a608842023-06-29 18:59:18 +0530179 query = (
180 frappe.qb.from_(se)
181 .inner_join(se_detail)
182 .on(se.name == se_detail.parent)
183 .select(
184 se[self.subcontract_data.order_field],
185 se.name.as_("voucher_no"),
186 se_detail.item_code.as_("rm_item_code"),
187 se_detail.item_name,
188 se_detail.description,
189 (
190 frappe.qb.terms.Case()
191 .when(((se.purpose == "Material Transfer") & (se.is_return == 1)), -1 * se_detail.qty)
192 .else_(se_detail.qty)
193 ).as_("qty"),
194 se_detail.basic_rate.as_("rate"),
195 se_detail.amount,
196 se_detail.serial_no,
197 se_detail.serial_and_batch_bundle,
198 se_detail.uom,
199 se_detail.subcontracted_item.as_("main_item_code"),
200 se_detail.stock_uom,
201 se_detail.batch_no,
202 se_detail.conversion_factor,
203 se_detail.s_warehouse,
204 se_detail.t_warehouse,
205 se_detail.item_group,
206 se_detail[self.subcontract_data.rm_detail_field],
207 )
208 .where(
209 (se.docstatus == 1)
210 & (se[self.subcontract_data.order_field].isin(self.subcontract_orders))
211 & (
212 (se.purpose == "Send to Subcontractor")
213 | ((se.purpose == "Material Transfer") & (se.is_return == 1))
214 )
215 )
216 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530217
218 if self.backflush_based_on == "BOM":
s-aga-r2a608842023-06-29 18:59:18 +0530219 query = query.select(se_detail.original_item)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530220
s-aga-r2a608842023-06-29 18:59:18 +0530221 return query.run(as_dict=True)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530222
223 def __set_alternative_item_details(self, row):
224 if row.get("original_item"):
225 self.alternative_item_details[row.get("original_item")] = row
226
227 def __get_received_items(self, doctype):
228 fields = []
s-aga-r6d89b2f2022-06-18 15:46:59 +0530229 for field in ["name", self.subcontract_data.order_field, "parent"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530230 fields.append(f"`tab{doctype} Item`.`{field}`")
231
232 filters = [
233 [doctype, "docstatus", "=", 1],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530234 [f"{doctype} Item", self.subcontract_data.order_field, "in", self.subcontract_orders],
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530235 ]
s-aga-r6d89b2f2022-06-18 15:46:59 +0530236 if doctype == "Purchase Invoice":
237 filters.append(["Purchase Invoice", "update_stock", "=", 1])
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530238
239 return frappe.get_all(f"{doctype}", fields=fields, filters=filters)
240
s-aga-r6d89b2f2022-06-18 15:46:59 +0530241 def __get_consumed_items(self, doctype, receipt_items):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530242 return frappe.get_all(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530243 self.subcontract_data.receipt_supplied_items_field,
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530244 fields=[
245 "serial_no",
246 "rm_item_code",
247 "reference_name",
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530248 "serial_and_batch_bundle",
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530249 "batch_no",
250 "consumed_qty",
251 "main_item_code",
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530252 "parent as voucher_no",
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530253 ],
s-aga-r6d89b2f2022-06-18 15:46:59 +0530254 filters={"docstatus": 1, "reference_name": ("in", list(receipt_items)), "parenttype": doctype},
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530255 )
256
257 def __update_consumed_materials(self, doctype, return_consumed_items=False):
258 """Deduct the consumed materials from the available materials."""
259
s-aga-r6d89b2f2022-06-18 15:46:59 +0530260 receipt_items = self.__get_received_items(doctype)
261 if not receipt_items:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530262 return ([], {}) if return_consumed_items else None
263
s-aga-r6d89b2f2022-06-18 15:46:59 +0530264 receipt_items = {
265 item.name: item.get(self.subcontract_data.order_field) for item in receipt_items
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530266 }
s-aga-r6d89b2f2022-06-18 15:46:59 +0530267 consumed_materials = self.__get_consumed_items(doctype, receipt_items.keys())
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530268
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530269 voucher_nos = [d.voucher_no for d in consumed_materials if d.voucher_no]
270 voucher_bundle_data = get_voucher_wise_serial_batch_from_bundle(
271 voucher_no=voucher_nos,
272 is_outward=1,
273 get_subcontracted_item=("Subcontracting Receipt Supplied Item", "main_item_code"),
274 )
275
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530276 if return_consumed_items:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530277 return (consumed_materials, receipt_items)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530278
279 for row in consumed_materials:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530280 key = (row.rm_item_code, row.main_item_code, receipt_items.get(row.reference_name))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530281 if not self.available_materials.get(key):
282 continue
283
284 self.available_materials[key]["qty"] -= row.consumed_qty
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530285
286 bundle_key = (row.rm_item_code, row.main_item_code, self.supplier_warehouse, row.voucher_no)
287 consumed_bundles = voucher_bundle_data.get(bundle_key, frappe._dict())
288
289 if consumed_bundles.serial_nos:
290 self.available_materials[key]["serial_no"] = list(
291 set(self.available_materials[key]["serial_no"]) - set(consumed_bundles.serial_nos)
292 )
293
294 if consumed_bundles.batch_nos:
295 for batch_no, qty in consumed_bundles.batch_nos.items():
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530296 if qty:
297 # Conumed qty is negative therefore added it instead of subtracting
298 self.available_materials[key]["batch_no"][batch_no] += qty
299 consumed_bundles.batch_nos[batch_no] += abs(qty)
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530300
Rohit Waghchaure46704642023-03-23 11:41:20 +0530301 # Will be deprecated in v16
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530302 if row.serial_no:
303 self.available_materials[key]["serial_no"] = list(
304 set(self.available_materials[key]["serial_no"]) - set(get_serial_nos(row.serial_no))
305 )
306
Rohit Waghchaure46704642023-03-23 11:41:20 +0530307 # Will be deprecated in v16
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530308 if row.batch_no:
309 self.available_materials[key]["batch_no"][row.batch_no] -= row.consumed_qty
310
311 def get_available_materials(self):
312 """Get the available raw materials which has been transferred to the supplier.
313 available_materials = {
s-aga-r6d89b2f2022-06-18 15:46:59 +0530314 (item_code, subcontracted_item, subcontract_order): {
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530315 'qty': 1, 'serial_no': [ABC], 'batch_no': {'batch1': 1}, 'data': item_details
316 }
317 }
318 """
s-aga-r6d89b2f2022-06-18 15:46:59 +0530319 if not self.subcontract_orders:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530320 return
321
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530322 transferred_items = self.__get_transferred_items()
323
324 voucher_nos = [row.voucher_no for row in transferred_items]
325 voucher_bundle_data = get_voucher_wise_serial_batch_from_bundle(
326 voucher_no=voucher_nos,
327 is_outward=0,
328 get_subcontracted_item=("Stock Entry Detail", "subcontracted_item"),
329 )
330
331 for row in transferred_items:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530332 key = (row.rm_item_code, row.main_item_code, row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530333
334 if key not in self.available_materials:
335 self.available_materials.setdefault(
336 key,
337 frappe._dict(
338 {
339 "qty": 0,
340 "serial_no": [],
341 "batch_no": defaultdict(float),
342 "item_details": row,
s-aga-r6d89b2f2022-06-18 15:46:59 +0530343 f"{self.subcontract_data.rm_detail_field}s": [],
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530344 }
345 ),
346 )
347
348 details = self.available_materials[key]
349 details.qty += row.qty
s-aga-r6d89b2f2022-06-18 15:46:59 +0530350 details[f"{self.subcontract_data.rm_detail_field}s"].append(
351 row.get(self.subcontract_data.rm_detail_field)
352 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530353
354 if row.serial_no:
355 details.serial_no.extend(get_serial_nos(row.serial_no))
356
357 if row.batch_no:
358 details.batch_no[row.batch_no] += row.qty
359
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530360 if voucher_bundle_data:
361 bundle_key = (row.rm_item_code, row.main_item_code, row.t_warehouse, row.voucher_no)
362
363 bundle_data = voucher_bundle_data.get(bundle_key, frappe._dict())
364 if bundle_data.serial_nos:
365 details.serial_no.extend(bundle_data.serial_nos)
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530366 bundle_data.serial_nos = []
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530367
368 if bundle_data.batch_nos:
369 for batch_no, qty in bundle_data.batch_nos.items():
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530370 if qty > 0:
371 details.batch_no[batch_no] += qty
372 bundle_data.batch_nos[batch_no] -= qty
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530373
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530374 self.__set_alternative_item_details(row)
375
376 self.__transferred_items = copy.deepcopy(self.available_materials)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530377 if self.get("is_old_subcontracting_flow"):
378 for doctype in ["Purchase Receipt", "Purchase Invoice"]:
379 self.__update_consumed_materials(doctype)
380 else:
381 self.__update_consumed_materials("Subcontracting Receipt")
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530382
383 def __remove_changed_rows(self):
384 if not self.__changed_name:
385 return
386
387 i = 1
388 self.set(self.raw_material_table, [])
389 for item in self._doc_before_save.supplied_items:
390 if item.reference_name in self.__changed_name:
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530391 self.__remove_serial_and_batch_bundle(item)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530392 continue
393
394 if item.reference_name not in self.__reference_name:
395 continue
396
397 item.idx = i
398 self.append("supplied_items", item)
399
400 i += 1
401
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530402 def __remove_serial_and_batch_bundle(self, item):
403 if item.serial_and_batch_bundle:
404 frappe.delete_doc("Serial and Batch Bundle", item.serial_and_batch_bundle, force=True)
405
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530406 def __get_materials_from_bom(self, item_code, bom_no, exploded_item=0):
407 doctype = "BOM Item" if not exploded_item else "BOM Explosion Item"
408 fields = [f"`tab{doctype}`.`stock_qty` / `tabBOM`.`quantity` as qty_consumed_per_unit"]
409
410 alias_dict = {
411 "item_code": "rm_item_code",
412 "name": "bom_detail_no",
413 "source_warehouse": "reserve_warehouse",
414 }
415 for field in [
416 "item_code",
417 "name",
418 "rate",
419 "stock_uom",
420 "source_warehouse",
421 "description",
422 "item_name",
423 "stock_uom",
424 ]:
425 fields.append(f"`tab{doctype}`.`{field}` As {alias_dict.get(field, field)}")
426
427 filters = [
428 [doctype, "parent", "=", bom_no],
429 [doctype, "docstatus", "=", 1],
430 ["BOM", "item", "=", item_code],
431 [doctype, "sourced_by_supplier", "=", 0],
432 ]
433
434 return (
435 frappe.get_all("BOM", fields=fields, filters=filters, order_by=f"`tab{doctype}`.`idx`") or []
436 )
437
438 def __update_reserve_warehouse(self, row, item):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530439 if self.doctype == self.subcontract_data.order_doctype:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530440 row.reserve_warehouse = self.set_reserve_warehouse or item.warehouse
441
442 def __set_alternative_item(self, bom_item):
443 if self.alternative_item_details.get(bom_item.rm_item_code):
444 bom_item.update(self.alternative_item_details[bom_item.rm_item_code])
445
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530446 def __set_serial_and_batch_bundle(self, item_row, rm_obj, qty):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530447 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 +0530448 if not self.available_materials.get(key):
449 return
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530450
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530451 if (
452 not self.available_materials[key]["serial_no"] and not self.available_materials[key]["batch_no"]
453 ):
454 return
Rohit Waghchaure156e4592023-02-16 13:21:17 +0530455
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530456 serial_nos = []
457 batches = frappe._dict({})
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530458
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530459 if self.available_materials.get(key) and self.available_materials[key]["serial_no"]:
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530460 serial_nos = self.__get_serial_nos_for_bundle(qty, key)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530461
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530462 elif self.available_materials.get(key) and self.available_materials[key]["batch_no"]:
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530463 batches = self.__get_batch_nos_for_bundle(qty, key)
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530464
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530465 bundle = SerialBatchCreation(
466 frappe._dict(
467 {
468 "company": self.company,
469 "item_code": rm_obj.rm_item_code,
470 "warehouse": self.supplier_warehouse,
471 "qty": qty,
472 "serial_nos": serial_nos,
473 "batches": batches,
474 "posting_date": self.posting_date,
475 "posting_time": self.posting_time,
476 "voucher_type": "Subcontracting Receipt",
477 "do_not_submit": True,
478 "type_of_transaction": "Outward" if qty > 0 else "Inward",
479 }
480 )
481 ).make_serial_and_batch_bundle()
482
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530483 return bundle.name
484
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530485 def __get_batch_nos_for_bundle(self, qty, key):
486 available_batches = defaultdict(float)
487
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530488 for batch_no, batch_qty in self.available_materials[key]["batch_no"].items():
489 qty_to_consumed = 0
490 if qty > 0:
491 if batch_qty >= qty:
492 qty_to_consumed = qty
493 else:
494 qty_to_consumed = batch_qty
495
496 qty -= qty_to_consumed
497 if qty_to_consumed > 0:
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530498 available_batches[batch_no] += qty_to_consumed
499 self.available_materials[key]["batch_no"][batch_no] -= qty_to_consumed
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530500
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530501 return available_batches
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530502
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530503 def __get_serial_nos_for_bundle(self, qty, key):
504 available_sns = sorted(self.available_materials[key]["serial_no"])[0 : cint(qty)]
505 serial_nos = []
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530506
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530507 for serial_no in available_sns:
508 serial_nos.append(serial_no)
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530509
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530510 self.available_materials[key]["serial_no"].remove(serial_no)
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530511
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530512 return serial_nos
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530513
514 def __add_supplied_item(self, item_row, bom_item, qty):
515 bom_item.conversion_factor = item_row.conversion_factor
516 rm_obj = self.append(self.raw_material_table, bom_item)
517 rm_obj.reference_name = item_row.name
518
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530519 if self.doctype == self.subcontract_data.order_doctype:
520 rm_obj.required_qty = qty
521 rm_obj.amount = rm_obj.required_qty * rm_obj.rate
522 else:
523 rm_obj.consumed_qty = qty
524 rm_obj.required_qty = bom_item.required_qty or qty
525 setattr(
526 rm_obj, self.subcontract_data.order_field, item_row.get(self.subcontract_data.order_field)
527 )
528
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530529 if self.doctype == "Subcontracting Receipt":
530 args = frappe._dict(
531 {
532 "item_code": rm_obj.rm_item_code,
533 "warehouse": self.supplier_warehouse,
534 "posting_date": self.posting_date,
535 "posting_time": self.posting_time,
536 "qty": -1 * flt(rm_obj.consumed_qty),
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530537 "actual_qty": -1 * flt(rm_obj.consumed_qty),
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530538 "voucher_type": self.doctype,
539 "voucher_no": self.name,
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530540 "voucher_detail_no": item_row.name,
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530541 "company": self.company,
542 "allow_zero_valuation": 1,
543 }
544 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530545
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530546 rm_obj.serial_and_batch_bundle = self.__set_serial_and_batch_bundle(
547 item_row, rm_obj, rm_obj.consumed_qty
548 )
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530549
550 if rm_obj.serial_and_batch_bundle:
551 args["serial_and_batch_bundle"] = rm_obj.serial_and_batch_bundle
552
553 rm_obj.rate = bom_item.rate if self.backflush_based_on == "BOM" else get_incoming_rate(args)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530554
555 def __get_qty_based_on_material_transfer(self, item_row, transfer_item):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530556 key = (item_row.item_code, item_row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530557
s-aga-r01f56c62022-11-15 14:32:16 +0530558 if self.qty_to_be_received == item_row.qty:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530559 return transfer_item.qty
560
561 if self.qty_to_be_received:
s-aga-r01f56c62022-11-15 14:32:16 +0530562 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 +0530563 transfer_item.item_details.required_qty = transfer_item.qty
564
565 if transfer_item.serial_no or frappe.get_cached_value(
566 "UOM", transfer_item.item_details.stock_uom, "must_be_whole_number"
567 ):
568 return frappe.utils.ceil(qty)
569
570 return qty
571
572 def __set_supplied_items(self):
573 self.bom_items = {}
574
575 has_supplied_items = True if self.get(self.raw_material_table) else False
576 for row in self.items:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530577 if self.doctype != self.subcontract_data.order_doctype and (
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530578 (self.__changed_name and row.name not in self.__changed_name)
579 or (has_supplied_items and not self.__changed_name)
580 ):
581 continue
582
s-aga-r6d89b2f2022-06-18 15:46:59 +0530583 if self.doctype == self.subcontract_data.order_doctype or self.backflush_based_on == "BOM":
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530584 for bom_item in self.__get_materials_from_bom(
585 row.item_code, row.bom, row.get("include_exploded_items")
586 ):
s-aga-r01f56c62022-11-15 14:32:16 +0530587 qty = flt(bom_item.qty_consumed_per_unit) * flt(row.qty) * row.conversion_factor
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530588 bom_item.main_item_code = row.item_code
589 self.__update_reserve_warehouse(bom_item, row)
590 self.__set_alternative_item(bom_item)
591 self.__add_supplied_item(row, bom_item, qty)
592
593 elif self.backflush_based_on != "BOM":
594 for key, transfer_item in self.available_materials.items():
s-aga-r6d89b2f2022-06-18 15:46:59 +0530595 if (key[1], key[2]) == (
596 row.item_code,
597 row.get(self.subcontract_data.order_field),
598 ) and transfer_item.qty > 0:
Sagar Sharmaaddd7342022-08-19 11:46:27 +0530599 qty = flt(self.__get_qty_based_on_material_transfer(row, transfer_item))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530600 transfer_item.qty -= qty
601 self.__add_supplied_item(row, transfer_item.get("item_details"), qty)
602
603 if self.qty_to_be_received:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530604 self.qty_to_be_received[
605 (row.item_code, row.get(self.subcontract_data.order_field))
606 ] -= row.qty
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530607
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530608 def __modify_serial_and_batch_bundle(self):
609 if self.is_new():
610 return
611
612 if self.doctype != "Subcontracting Receipt":
613 return
614
615 for item_row in self.items:
616 if self.__changed_name and item_row.name in self.__changed_name:
617 continue
618
619 modified_data = self.__get_bundle_to_modify(item_row.name)
620 if modified_data:
621 serial_nos = []
622 batches = frappe._dict({})
623 key = (
624 modified_data.rm_item_code,
625 item_row.item_code,
626 item_row.get(self.subcontract_data.order_field),
627 )
628
629 if self.available_materials.get(key) and self.available_materials[key]["serial_no"]:
630 serial_nos = self.__get_serial_nos_for_bundle(modified_data.consumed_qty, key)
631
632 elif self.available_materials.get(key) and self.available_materials[key]["batch_no"]:
633 batches = self.__get_batch_nos_for_bundle(modified_data.consumed_qty, key)
634
635 SerialBatchCreation(
636 {
637 "item_code": modified_data.rm_item_code,
638 "warehouse": self.supplier_warehouse,
639 "serial_and_batch_bundle": modified_data.serial_and_batch_bundle,
640 "type_of_transaction": "Outward",
641 "serial_nos": serial_nos,
642 "batches": batches,
643 "qty": modified_data.consumed_qty * -1,
644 }
645 ).update_serial_and_batch_entries()
646
647 def __get_bundle_to_modify(self, name):
648 for row in self.get("supplied_items"):
649 if row.reference_name == name and row.serial_and_batch_bundle:
650 if row.consumed_qty != abs(
651 frappe.get_cached_value("Serial and Batch Bundle", row.serial_and_batch_bundle, "total_qty")
652 ):
653 return row
654
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530655 def __prepare_supplied_items(self):
656 self.initialized_fields()
s-aga-r6d89b2f2022-06-18 15:46:59 +0530657 self.__get_subcontract_orders()
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530658 self.__get_pending_qty_to_receive()
659 self.get_available_materials()
660 self.__remove_changed_rows()
661 self.__set_supplied_items()
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530662 self.__modify_serial_and_batch_bundle()
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530663
664 def __validate_batch_no(self, row, key):
665 if row.get("batch_no") and row.get("batch_no") not in self.__transferred_items.get(key).get(
666 "batch_no"
667 ):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530668 link = get_link_to_form(
669 self.subcontract_data.order_doctype, row.get(self.subcontract_data.order_field)
670 )
671 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 +0530672 frappe.throw(_(msg), title=_("Incorrect Batch Consumed"))
673
674 def __validate_serial_no(self, row, key):
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530675 if row.get("serial_and_batch_bundle") and self.__transferred_items.get(key).get("serial_no"):
676 serial_nos = get_serial_nos_from_bundle(row.get("serial_and_batch_bundle"))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530677 incorrect_sn = set(serial_nos).difference(self.__transferred_items.get(key).get("serial_no"))
678
679 if incorrect_sn:
680 incorrect_sn = "\n".join(incorrect_sn)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530681 link = get_link_to_form(
682 self.subcontract_data.order_doctype, row.get(self.subcontract_data.order_field)
683 )
684 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 +0530685 frappe.throw(_(msg), title=_("Incorrect Serial Number Consumed"))
686
687 def __validate_supplied_items(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530688 if self.doctype not in ["Purchase Invoice", "Purchase Receipt", "Subcontracting Receipt"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530689 return
690
691 for row in self.get(self.raw_material_table):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530692 key = (row.rm_item_code, row.main_item_code, row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530693 if not self.__transferred_items or not self.__transferred_items.get(key):
694 return
695
696 self.__validate_batch_no(row, key)
697 self.__validate_serial_no(row, key)
698
699 def set_materials_for_subcontracted_items(self, raw_material_table):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530700 if self.doctype == "Purchase Invoice" and not self.update_stock:
701 return
702
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530703 self.raw_material_table = raw_material_table
704 self.__identify_change_in_item_table()
705 self.__prepare_supplied_items()
706 self.__validate_supplied_items()
707
708 def create_raw_materials_supplied(self, raw_material_table="supplied_items"):
709 self.set_materials_for_subcontracted_items(raw_material_table)
710
s-aga-r6d89b2f2022-06-18 15:46:59 +0530711 if self.doctype in ["Subcontracting Receipt", "Purchase Receipt", "Purchase Invoice"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530712 for item in self.get("items"):
713 item.rm_supp_cost = 0.0
714
s-aga-r6d89b2f2022-06-18 15:46:59 +0530715 def __update_consumed_qty_in_subcontract_order(self, itemwise_consumed_qty):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530716 fields = ["main_item_code", "rm_item_code", "parent", "supplied_qty", "name"]
s-aga-r6d89b2f2022-06-18 15:46:59 +0530717 filters = {"docstatus": 1, "parent": ("in", self.subcontract_orders)}
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530718
719 for row in frappe.get_all(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530720 self.subcontract_data.order_supplied_items_field, fields=fields, filters=filters, order_by="idx"
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530721 ):
722 key = (row.rm_item_code, row.main_item_code, row.parent)
723 consumed_qty = itemwise_consumed_qty.get(key, 0)
724
725 if row.supplied_qty < consumed_qty:
726 consumed_qty = row.supplied_qty
727
728 itemwise_consumed_qty[key] -= consumed_qty
729 frappe.db.set_value(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530730 self.subcontract_data.order_supplied_items_field, row.name, "consumed_qty", consumed_qty
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530731 )
732
s-aga-r6d89b2f2022-06-18 15:46:59 +0530733 def set_consumed_qty_in_subcontract_order(self):
734 # Update consumed qty back in the subcontract order
735 if self.doctype in ["Subcontracting Order", "Subcontracting Receipt"] or self.get(
736 "is_old_subcontracting_flow"
737 ):
738 self.__get_subcontract_orders()
739 itemwise_consumed_qty = defaultdict(float)
740 if self.get("is_old_subcontracting_flow"):
741 doctypes = ["Purchase Receipt", "Purchase Invoice"]
742 else:
743 doctypes = ["Subcontracting Receipt"]
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530744
s-aga-r6d89b2f2022-06-18 15:46:59 +0530745 for doctype in doctypes:
746 consumed_items, receipt_items = self.__update_consumed_materials(
747 doctype, return_consumed_items=True
748 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530749
s-aga-r6d89b2f2022-06-18 15:46:59 +0530750 for row in consumed_items:
751 key = (row.rm_item_code, row.main_item_code, receipt_items.get(row.reference_name))
752 itemwise_consumed_qty[key] += row.consumed_qty
753
754 self.__update_consumed_qty_in_subcontract_order(itemwise_consumed_qty)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530755
756 def update_ordered_and_reserved_qty(self):
757 sco_map = {}
758 for item in self.get("items"):
759 if self.doctype == "Subcontracting Receipt" and item.subcontracting_order:
760 sco_map.setdefault(item.subcontracting_order, []).append(item.subcontracting_order_item)
761
762 for sco, sco_item_rows in sco_map.items():
763 if sco and sco_item_rows:
764 sco_doc = frappe.get_doc("Subcontracting Order", sco)
765
766 if sco_doc.status in ["Closed", "Cancelled"]:
767 frappe.throw(
768 _("{0} {1} is cancelled or closed").format(_("Subcontracting Order"), sco),
769 frappe.InvalidStatusError,
770 )
771
772 sco_doc.update_ordered_qty_for_subcontracting(sco_item_rows)
773 sco_doc.update_reserved_qty_for_subcontracting()
774
775 def make_sl_entries_for_supplier_warehouse(self, sl_entries):
776 if hasattr(self, "supplied_items"):
777 for item in self.get("supplied_items"):
778 # negative quantity is passed, as raw material qty has to be decreased
779 # when SCR is submitted and it has to be increased when SCR is cancelled
780 sl_entries.append(
781 self.get_sl_entries(
782 item,
783 {
784 "item_code": item.rm_item_code,
785 "warehouse": self.supplier_warehouse,
786 "actual_qty": -1 * flt(item.consumed_qty),
787 "dependant_sle_voucher_detail_no": item.reference_name,
788 },
789 )
790 )
791
792 def update_stock_ledger(self, allow_negative_stock=False, via_landed_cost_voucher=False):
793 self.update_ordered_and_reserved_qty()
794
795 sl_entries = []
796 stock_items = self.get_stock_items()
797
798 for item in self.get("items"):
799 if item.item_code in stock_items and item.warehouse:
800 scr_qty = flt(item.qty) * flt(item.conversion_factor)
801
802 if scr_qty:
Rohit Waghchaure16f26fb2023-03-20 22:56:06 +0530803 sle = self.get_sl_entries(item, {"actual_qty": flt(scr_qty)})
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530804 rate_db_precision = 6 if cint(self.precision("rate", item)) <= 6 else 9
805 incoming_rate = flt(item.rate, rate_db_precision)
806 sle.update(
807 {
808 "incoming_rate": incoming_rate,
809 "recalculate_rate": 1,
810 }
811 )
812 sl_entries.append(sle)
813
814 if flt(item.rejected_qty) != 0:
815 sl_entries.append(
816 self.get_sl_entries(
817 item,
818 {
819 "warehouse": item.rejected_warehouse,
820 "actual_qty": flt(item.rejected_qty) * flt(item.conversion_factor),
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530821 "incoming_rate": 0.0,
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530822 },
823 )
824 )
825
826 self.make_sl_entries_for_supplier_warehouse(sl_entries)
827 self.make_sl_entries(
828 sl_entries,
829 allow_negative_stock=allow_negative_stock,
830 via_landed_cost_voucher=via_landed_cost_voucher,
831 )
832
s-aga-r6d89b2f2022-06-18 15:46:59 +0530833 def get_supplied_items_cost(self, item_row_id, reset_outgoing_rate=True):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530834 supplied_items_cost = 0.0
835 for item in self.get("supplied_items"):
836 if item.reference_name == item_row_id:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530837 if (
838 self.get("is_old_subcontracting_flow")
839 and reset_outgoing_rate
840 and frappe.get_cached_value("Item", item.rm_item_code, "is_stock_item")
841 ):
842 rate = get_incoming_rate(
843 {
844 "item_code": item.rm_item_code,
845 "warehouse": self.supplier_warehouse,
846 "posting_date": self.posting_date,
847 "posting_time": self.posting_time,
848 "qty": -1 * item.consumed_qty,
Rohit Waghchaure46704642023-03-23 11:41:20 +0530849 "serial_and_batch_bundle": item.serial_and_batch_bundle,
s-aga-r6d89b2f2022-06-18 15:46:59 +0530850 }
851 )
852
853 if rate > 0:
854 item.rate = rate
855
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530856 item.amount = flt(flt(item.consumed_qty) * flt(item.rate), item.precision("amount"))
857 supplied_items_cost += item.amount
858
859 return supplied_items_cost
860
Sagar Sharma249726b2022-04-22 17:09:19 +0530861 def set_subcontracting_order_status(self):
862 if self.doctype == "Subcontracting Order":
863 self.update_status()
864 elif self.doctype == "Subcontracting Receipt":
s-aga-r6d89b2f2022-06-18 15:46:59 +0530865 self.__get_subcontract_orders
Sagar Sharma249726b2022-04-22 17:09:19 +0530866
s-aga-r6d89b2f2022-06-18 15:46:59 +0530867 if self.subcontract_orders:
868 for sco in set(self.subcontract_orders):
Sagar Sharma249726b2022-04-22 17:09:19 +0530869 sco_doc = frappe.get_doc("Subcontracting Order", sco)
870 sco_doc.update_status()
871
Sagar Sharmad6433f82023-05-12 11:45:33 +0530872 def calculate_additional_costs(self):
Sagar Sharmaea82fe52022-08-18 17:20:22 +0530873 self.total_additional_costs = sum(flt(item.amount) for item in self.get("additional_costs"))
874
875 if self.total_additional_costs:
876 if self.distribute_additional_costs_based_on == "Amount":
877 total_amt = sum(flt(item.amount) for item in self.get("items"))
878 for item in self.items:
879 item.additional_cost_per_qty = (
880 (item.amount * self.total_additional_costs) / total_amt
881 ) / item.qty
882 else:
883 total_qty = sum(flt(item.qty) for item in self.get("items"))
884 additional_cost_per_qty = self.total_additional_costs / total_qty
885 for item in self.items:
886 item.additional_cost_per_qty = additional_cost_per_qty
887 else:
888 for item in self.items:
889 item.additional_cost_per_qty = 0
890
s-aga-r6d89b2f2022-06-18 15:46:59 +0530891 @frappe.whitelist()
892 def get_current_stock(self):
893 if self.doctype in ["Purchase Receipt", "Subcontracting Receipt"]:
894 for item in self.get("supplied_items"):
895 if self.supplier_warehouse:
896 actual_qty = frappe.db.get_value(
897 "Bin",
898 {"item_code": item.rm_item_code, "warehouse": self.supplier_warehouse},
899 "actual_qty",
900 )
Sagar Sharmaaddd7342022-08-19 11:46:27 +0530901 item.current_stock = flt(actual_qty)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530902
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530903 @property
904 def sub_contracted_items(self):
905 if not hasattr(self, "_sub_contracted_items"):
906 self._sub_contracted_items = []
907 item_codes = list(set(item.item_code for item in self.get("items")))
908 if item_codes:
909 items = frappe.get_all(
910 "Item", filters={"name": ["in", item_codes], "is_sub_contracted_item": 1}
911 )
912 self._sub_contracted_items = [item.name for item in items]
913
914 return self._sub_contracted_items
s-aga-r6d89b2f2022-06-18 15:46:59 +0530915
916
917def get_item_details(items):
918 item = frappe.qb.DocType("Item")
919 item_list = (
920 frappe.qb.from_(item)
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530921 .select(item.item_code, item.item_name, item.description, item.allow_alternative_item)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530922 .where(item.name.isin(items))
923 .run(as_dict=True)
924 )
925
926 item_details = {}
927 for item in item_list:
928 item_details[item.item_code] = item
929
930 return item_details
931
932
933@frappe.whitelist()
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530934def make_rm_stock_entry(
935 subcontract_order, rm_items=None, order_doctype="Subcontracting Order", target_doc=None
936):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530937 if subcontract_order:
938 subcontract_order = frappe.get_doc(order_doctype, subcontract_order)
939
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530940 if not rm_items:
941 if not subcontract_order.supplied_items:
942 frappe.throw(_("No item available for transfer."))
s-aga-r6d89b2f2022-06-18 15:46:59 +0530943
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530944 rm_items = subcontract_order.supplied_items
s-aga-r6d89b2f2022-06-18 15:46:59 +0530945
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530946 fg_item_code_list = list(
947 set(item.get("main_item_code") or item.get("item_code") for item in rm_items)
948 )
s-aga-r6d89b2f2022-06-18 15:46:59 +0530949
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530950 if fg_item_code_list:
951 rm_item_code_list = tuple(set(item.get("rm_item_code") for item in rm_items))
952 item_wh = get_item_details(rm_item_code_list)
953
954 field_no_map, rm_detail_field = "purchase_order", "sco_rm_detail"
955 if order_doctype == "Purchase Order":
956 field_no_map, rm_detail_field = "subcontracting_order", "po_detail"
957
958 if target_doc and target_doc.get("items"):
959 target_doc.items = []
960
961 stock_entry = get_mapped_doc(
962 order_doctype,
963 subcontract_order.name,
964 {
965 order_doctype: {
966 "doctype": "Stock Entry",
967 "field_map": {
s-aga-r751bdc92022-12-31 17:17:22 +0530968 "supplier": "supplier",
969 "supplier_name": "supplier_name",
970 "supplier_address": "supplier_address",
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530971 "to_warehouse": "supplier_warehouse",
972 },
973 "field_no_map": [field_no_map],
974 "validation": {
975 "docstatus": ["=", 1],
976 },
977 },
978 },
979 target_doc,
980 ignore_child_tables=True,
981 )
982
983 stock_entry.purpose = "Send to Subcontractor"
984
985 if order_doctype == "Purchase Order":
986 stock_entry.purchase_order = subcontract_order.name
987 else:
988 stock_entry.subcontracting_order = subcontract_order.name
989
990 stock_entry.set_stock_entry_type()
991
992 for fg_item_code in fg_item_code_list:
993 for rm_item in rm_items:
994
Sagar Sharmaac7409b2022-09-28 16:46:48 +0530995 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 +0530996 rm_item_code = rm_item.get("rm_item_code")
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530997 items_dict = {
998 rm_item_code: {
999 rm_detail_field: rm_item.get("name"),
1000 "item_name": rm_item.get("item_name")
1001 or item_wh.get(rm_item_code, {}).get("item_name", ""),
1002 "description": item_wh.get(rm_item_code, {}).get("description", ""),
1003 "qty": rm_item.get("qty")
1004 or max(rm_item.get("required_qty") - rm_item.get("total_supplied_qty"), 0),
1005 "from_warehouse": rm_item.get("warehouse") or rm_item.get("reserve_warehouse"),
1006 "to_warehouse": subcontract_order.supplier_warehouse,
1007 "stock_uom": rm_item.get("stock_uom"),
Rohit Waghchauree88c5d62023-04-05 20:03:44 +05301008 "serial_and_batch_bundle": rm_item.get("serial_and_batch_bundle"),
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301009 "main_item_code": fg_item_code,
1010 "allow_alternative_item": item_wh.get(rm_item_code, {}).get("allow_alternative_item"),
1011 }
s-aga-r6d89b2f2022-06-18 15:46:59 +05301012 }
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301013
1014 stock_entry.add_to_stock_entry_detail(items_dict)
1015
1016 if target_doc:
1017 return stock_entry
1018 else:
1019 return stock_entry.as_dict()
1020 else:
1021 frappe.throw(_("No Items selected for transfer."))
s-aga-r6d89b2f2022-06-18 15:46:59 +05301022
1023
1024def add_items_in_ste(
1025 ste_doc, row, qty, rm_details, rm_detail_field="sco_rm_detail", batch_no=None
1026):
1027 item = ste_doc.append("items", row.item_details)
1028
1029 rm_detail = list(set(row.get(f"{rm_detail_field}s")).intersection(rm_details))
1030 item.update(
1031 {
1032 "qty": qty,
1033 "batch_no": batch_no,
1034 "basic_rate": row.item_details["rate"],
1035 rm_detail_field: rm_detail[0] if rm_detail else "",
1036 "s_warehouse": row.item_details["t_warehouse"],
1037 "t_warehouse": row.item_details["s_warehouse"],
1038 "item_code": row.item_details["rm_item_code"],
1039 "subcontracted_item": row.item_details["main_item_code"],
1040 "serial_no": "\n".join(row.serial_no) if row.serial_no else "",
1041 }
1042 )
1043
1044
1045def make_return_stock_entry_for_subcontract(
1046 available_materials, order_doc, rm_details, order_doctype="Subcontracting Order"
1047):
Sagar Sharma008542b2022-09-07 10:15:43 +05301048 ste_doc = get_mapped_doc(
1049 order_doctype,
1050 order_doc.name,
1051 {
1052 order_doctype: {
1053 "doctype": "Stock Entry",
Sagar Sharmaccb28892022-09-08 16:04:08 +05301054 "field_no_map": ["purchase_order", "subcontracting_order"],
Sagar Sharma008542b2022-09-07 10:15:43 +05301055 },
1056 },
1057 ignore_child_tables=True,
1058 )
1059
s-aga-r6d89b2f2022-06-18 15:46:59 +05301060 ste_doc.purpose = "Material Transfer"
1061
1062 if order_doctype == "Purchase Order":
1063 ste_doc.purchase_order = order_doc.name
1064 rm_detail_field = "po_detail"
1065 else:
1066 ste_doc.subcontracting_order = order_doc.name
1067 rm_detail_field = "sco_rm_detail"
1068 ste_doc.company = order_doc.company
1069 ste_doc.is_return = 1
1070
1071 for key, value in available_materials.items():
1072 if not value.qty:
1073 continue
1074
1075 if value.batch_no:
1076 for batch_no, qty in value.batch_no.items():
1077 if qty > 0:
1078 add_items_in_ste(ste_doc, value, value.qty, rm_details, rm_detail_field, batch_no)
1079 else:
1080 add_items_in_ste(ste_doc, value, value.qty, rm_details, rm_detail_field)
1081
1082 ste_doc.set_stock_entry_type()
s-aga-r6d89b2f2022-06-18 15:46:59 +05301083
1084 return ste_doc
1085
1086
1087@frappe.whitelist()
1088def get_materials_from_supplier(
1089 subcontract_order, rm_details, order_doctype="Subcontracting Order"
1090):
1091 if isinstance(rm_details, str):
1092 rm_details = json.loads(rm_details)
1093
1094 doc = frappe.get_cached_doc(order_doctype, subcontract_order)
1095 doc.initialized_fields()
1096 doc.subcontract_orders = [doc.name]
1097 doc.get_available_materials()
1098
1099 if not doc.available_materials:
1100 frappe.throw(
1101 _("Materials are already received against the {0} {1}").format(order_doctype, subcontract_order)
1102 )
1103
1104 return make_return_stock_entry_for_subcontract(
1105 doc.available_materials, doc, rm_details, order_doctype
1106 )