blob: 837969728b044ce88b8cd7b1f24f245a1e478e1b [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-ra33b75f2023-08-24 16:37:57 +0530100 if not item.is_scrap_item:
101 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
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530629 def __modify_serial_and_batch_bundle(self):
630 if self.is_new():
631 return
632
633 if self.doctype != "Subcontracting Receipt":
634 return
635
636 for item_row in self.items:
637 if self.__changed_name and item_row.name in self.__changed_name:
638 continue
639
640 modified_data = self.__get_bundle_to_modify(item_row.name)
641 if modified_data:
642 serial_nos = []
643 batches = frappe._dict({})
644 key = (
645 modified_data.rm_item_code,
646 item_row.item_code,
647 item_row.get(self.subcontract_data.order_field),
648 )
649
650 if self.available_materials.get(key) and self.available_materials[key]["serial_no"]:
651 serial_nos = self.__get_serial_nos_for_bundle(modified_data.consumed_qty, key)
652
653 elif self.available_materials.get(key) and self.available_materials[key]["batch_no"]:
654 batches = self.__get_batch_nos_for_bundle(modified_data.consumed_qty, key)
655
656 SerialBatchCreation(
657 {
658 "item_code": modified_data.rm_item_code,
659 "warehouse": self.supplier_warehouse,
660 "serial_and_batch_bundle": modified_data.serial_and_batch_bundle,
661 "type_of_transaction": "Outward",
662 "serial_nos": serial_nos,
663 "batches": batches,
664 "qty": modified_data.consumed_qty * -1,
665 }
666 ).update_serial_and_batch_entries()
667
668 def __get_bundle_to_modify(self, name):
669 for row in self.get("supplied_items"):
670 if row.reference_name == name and row.serial_and_batch_bundle:
671 if row.consumed_qty != abs(
672 frappe.get_cached_value("Serial and Batch Bundle", row.serial_and_batch_bundle, "total_qty")
673 ):
674 return row
675
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530676 def __prepare_supplied_items(self):
677 self.initialized_fields()
s-aga-r6d89b2f2022-06-18 15:46:59 +0530678 self.__get_subcontract_orders()
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530679 self.__get_pending_qty_to_receive()
680 self.get_available_materials()
681 self.__remove_changed_rows()
682 self.__set_supplied_items()
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530683 self.__modify_serial_and_batch_bundle()
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530684
685 def __validate_batch_no(self, row, key):
686 if row.get("batch_no") and row.get("batch_no") not in self.__transferred_items.get(key).get(
687 "batch_no"
688 ):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530689 link = get_link_to_form(
690 self.subcontract_data.order_doctype, row.get(self.subcontract_data.order_field)
691 )
692 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 +0530693 frappe.throw(_(msg), title=_("Incorrect Batch Consumed"))
694
695 def __validate_serial_no(self, row, key):
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530696 if row.get("serial_and_batch_bundle") and self.__transferred_items.get(key).get("serial_no"):
697 serial_nos = get_serial_nos_from_bundle(row.get("serial_and_batch_bundle"))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530698 incorrect_sn = set(serial_nos).difference(self.__transferred_items.get(key).get("serial_no"))
699
700 if incorrect_sn:
701 incorrect_sn = "\n".join(incorrect_sn)
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 Serial Nos {incorrect_sn} has not supplied against the {self.subcontract_data.order_doctype} {link}"
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530706 frappe.throw(_(msg), title=_("Incorrect Serial Number Consumed"))
707
708 def __validate_supplied_items(self):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530709 if self.doctype not in ["Purchase Invoice", "Purchase Receipt", "Subcontracting Receipt"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530710 return
711
712 for row in self.get(self.raw_material_table):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530713 key = (row.rm_item_code, row.main_item_code, row.get(self.subcontract_data.order_field))
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530714 if not self.__transferred_items or not self.__transferred_items.get(key):
715 return
716
717 self.__validate_batch_no(row, key)
718 self.__validate_serial_no(row, key)
719
720 def set_materials_for_subcontracted_items(self, raw_material_table):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530721 if self.doctype == "Purchase Invoice" and not self.update_stock:
722 return
723
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530724 self.raw_material_table = raw_material_table
725 self.__identify_change_in_item_table()
726 self.__prepare_supplied_items()
727 self.__validate_supplied_items()
728
729 def create_raw_materials_supplied(self, raw_material_table="supplied_items"):
730 self.set_materials_for_subcontracted_items(raw_material_table)
731
s-aga-r6d89b2f2022-06-18 15:46:59 +0530732 if self.doctype in ["Subcontracting Receipt", "Purchase Receipt", "Purchase Invoice"]:
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530733 for item in self.get("items"):
734 item.rm_supp_cost = 0.0
735
s-aga-r6d89b2f2022-06-18 15:46:59 +0530736 def __update_consumed_qty_in_subcontract_order(self, itemwise_consumed_qty):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530737 fields = ["main_item_code", "rm_item_code", "parent", "supplied_qty", "name"]
s-aga-r6d89b2f2022-06-18 15:46:59 +0530738 filters = {"docstatus": 1, "parent": ("in", self.subcontract_orders)}
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530739
740 for row in frappe.get_all(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530741 self.subcontract_data.order_supplied_items_field, fields=fields, filters=filters, order_by="idx"
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530742 ):
743 key = (row.rm_item_code, row.main_item_code, row.parent)
744 consumed_qty = itemwise_consumed_qty.get(key, 0)
745
746 if row.supplied_qty < consumed_qty:
747 consumed_qty = row.supplied_qty
748
749 itemwise_consumed_qty[key] -= consumed_qty
750 frappe.db.set_value(
s-aga-r6d89b2f2022-06-18 15:46:59 +0530751 self.subcontract_data.order_supplied_items_field, row.name, "consumed_qty", consumed_qty
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530752 )
753
s-aga-r6d89b2f2022-06-18 15:46:59 +0530754 def set_consumed_qty_in_subcontract_order(self):
755 # Update consumed qty back in the subcontract order
756 if self.doctype in ["Subcontracting Order", "Subcontracting Receipt"] or self.get(
757 "is_old_subcontracting_flow"
758 ):
759 self.__get_subcontract_orders()
760 itemwise_consumed_qty = defaultdict(float)
761 if self.get("is_old_subcontracting_flow"):
762 doctypes = ["Purchase Receipt", "Purchase Invoice"]
763 else:
764 doctypes = ["Subcontracting Receipt"]
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530765
s-aga-r6d89b2f2022-06-18 15:46:59 +0530766 for doctype in doctypes:
767 consumed_items, receipt_items = self.__update_consumed_materials(
768 doctype, return_consumed_items=True
769 )
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530770
s-aga-r6d89b2f2022-06-18 15:46:59 +0530771 for row in consumed_items:
772 key = (row.rm_item_code, row.main_item_code, receipt_items.get(row.reference_name))
773 itemwise_consumed_qty[key] += row.consumed_qty
774
775 self.__update_consumed_qty_in_subcontract_order(itemwise_consumed_qty)
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530776
777 def update_ordered_and_reserved_qty(self):
778 sco_map = {}
779 for item in self.get("items"):
780 if self.doctype == "Subcontracting Receipt" and item.subcontracting_order:
781 sco_map.setdefault(item.subcontracting_order, []).append(item.subcontracting_order_item)
782
783 for sco, sco_item_rows in sco_map.items():
784 if sco and sco_item_rows:
785 sco_doc = frappe.get_doc("Subcontracting Order", sco)
786
787 if sco_doc.status in ["Closed", "Cancelled"]:
788 frappe.throw(
789 _("{0} {1} is cancelled or closed").format(_("Subcontracting Order"), sco),
790 frappe.InvalidStatusError,
791 )
792
793 sco_doc.update_ordered_qty_for_subcontracting(sco_item_rows)
794 sco_doc.update_reserved_qty_for_subcontracting()
795
796 def make_sl_entries_for_supplier_warehouse(self, sl_entries):
797 if hasattr(self, "supplied_items"):
798 for item in self.get("supplied_items"):
799 # negative quantity is passed, as raw material qty has to be decreased
800 # when SCR is submitted and it has to be increased when SCR is cancelled
801 sl_entries.append(
802 self.get_sl_entries(
803 item,
804 {
805 "item_code": item.rm_item_code,
806 "warehouse": self.supplier_warehouse,
807 "actual_qty": -1 * flt(item.consumed_qty),
808 "dependant_sle_voucher_detail_no": item.reference_name,
809 },
810 )
811 )
812
813 def update_stock_ledger(self, allow_negative_stock=False, via_landed_cost_voucher=False):
814 self.update_ordered_and_reserved_qty()
815
816 sl_entries = []
817 stock_items = self.get_stock_items()
818
819 for item in self.get("items"):
820 if item.item_code in stock_items and item.warehouse:
821 scr_qty = flt(item.qty) * flt(item.conversion_factor)
822
823 if scr_qty:
Rohit Waghchaure16f26fb2023-03-20 22:56:06 +0530824 sle = self.get_sl_entries(item, {"actual_qty": flt(scr_qty)})
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530825 rate_db_precision = 6 if cint(self.precision("rate", item)) <= 6 else 9
826 incoming_rate = flt(item.rate, rate_db_precision)
827 sle.update(
828 {
829 "incoming_rate": incoming_rate,
830 "recalculate_rate": 1,
831 }
832 )
833 sl_entries.append(sle)
834
835 if flt(item.rejected_qty) != 0:
836 sl_entries.append(
837 self.get_sl_entries(
838 item,
839 {
840 "warehouse": item.rejected_warehouse,
841 "actual_qty": flt(item.rejected_qty) * flt(item.conversion_factor),
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530842 "incoming_rate": 0.0,
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530843 },
844 )
845 )
846
847 self.make_sl_entries_for_supplier_warehouse(sl_entries)
848 self.make_sl_entries(
849 sl_entries,
850 allow_negative_stock=allow_negative_stock,
851 via_landed_cost_voucher=via_landed_cost_voucher,
852 )
853
s-aga-r6d89b2f2022-06-18 15:46:59 +0530854 def get_supplied_items_cost(self, item_row_id, reset_outgoing_rate=True):
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530855 supplied_items_cost = 0.0
856 for item in self.get("supplied_items"):
857 if item.reference_name == item_row_id:
s-aga-r6d89b2f2022-06-18 15:46:59 +0530858 if (
859 self.get("is_old_subcontracting_flow")
860 and reset_outgoing_rate
861 and frappe.get_cached_value("Item", item.rm_item_code, "is_stock_item")
862 ):
863 rate = get_incoming_rate(
864 {
865 "item_code": item.rm_item_code,
866 "warehouse": self.supplier_warehouse,
867 "posting_date": self.posting_date,
868 "posting_time": self.posting_time,
869 "qty": -1 * item.consumed_qty,
Rohit Waghchaure46704642023-03-23 11:41:20 +0530870 "serial_and_batch_bundle": item.serial_and_batch_bundle,
s-aga-r6d89b2f2022-06-18 15:46:59 +0530871 }
872 )
873
874 if rate > 0:
875 item.rate = rate
876
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530877 item.amount = flt(flt(item.consumed_qty) * flt(item.rate), item.precision("amount"))
878 supplied_items_cost += item.amount
879
880 return supplied_items_cost
881
Sagar Sharma249726b2022-04-22 17:09:19 +0530882 def set_subcontracting_order_status(self):
883 if self.doctype == "Subcontracting Order":
884 self.update_status()
885 elif self.doctype == "Subcontracting Receipt":
s-aga-r6d89b2f2022-06-18 15:46:59 +0530886 self.__get_subcontract_orders
Sagar Sharma249726b2022-04-22 17:09:19 +0530887
s-aga-r6d89b2f2022-06-18 15:46:59 +0530888 if self.subcontract_orders:
889 for sco in set(self.subcontract_orders):
Sagar Sharma249726b2022-04-22 17:09:19 +0530890 sco_doc = frappe.get_doc("Subcontracting Order", sco)
891 sco_doc.update_status()
892
Sagar Sharmad6433f82023-05-12 11:45:33 +0530893 def calculate_additional_costs(self):
Sagar Sharmaea82fe52022-08-18 17:20:22 +0530894 self.total_additional_costs = sum(flt(item.amount) for item in self.get("additional_costs"))
895
896 if self.total_additional_costs:
897 if self.distribute_additional_costs_based_on == "Amount":
898 total_amt = sum(flt(item.amount) for item in self.get("items"))
899 for item in self.items:
900 item.additional_cost_per_qty = (
901 (item.amount * self.total_additional_costs) / total_amt
902 ) / item.qty
903 else:
904 total_qty = sum(flt(item.qty) for item in self.get("items"))
905 additional_cost_per_qty = self.total_additional_costs / total_qty
906 for item in self.items:
907 item.additional_cost_per_qty = additional_cost_per_qty
908 else:
909 for item in self.items:
910 item.additional_cost_per_qty = 0
911
s-aga-r6d89b2f2022-06-18 15:46:59 +0530912 @frappe.whitelist()
913 def get_current_stock(self):
914 if self.doctype in ["Purchase Receipt", "Subcontracting Receipt"]:
915 for item in self.get("supplied_items"):
916 if self.supplier_warehouse:
917 actual_qty = frappe.db.get_value(
918 "Bin",
919 {"item_code": item.rm_item_code, "warehouse": self.supplier_warehouse},
920 "actual_qty",
921 )
Sagar Sharmaaddd7342022-08-19 11:46:27 +0530922 item.current_stock = flt(actual_qty)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530923
Sagar Sharma29a1cb82022-04-26 17:29:45 +0530924 @property
925 def sub_contracted_items(self):
926 if not hasattr(self, "_sub_contracted_items"):
927 self._sub_contracted_items = []
928 item_codes = list(set(item.item_code for item in self.get("items")))
929 if item_codes:
930 items = frappe.get_all(
931 "Item", filters={"name": ["in", item_codes], "is_sub_contracted_item": 1}
932 )
933 self._sub_contracted_items = [item.name for item in items]
934
935 return self._sub_contracted_items
s-aga-r6d89b2f2022-06-18 15:46:59 +0530936
937
938def get_item_details(items):
939 item = frappe.qb.DocType("Item")
940 item_list = (
941 frappe.qb.from_(item)
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530942 .select(item.item_code, item.item_name, item.description, item.allow_alternative_item)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530943 .where(item.name.isin(items))
944 .run(as_dict=True)
945 )
946
947 item_details = {}
948 for item in item_list:
949 item_details[item.item_code] = item
950
951 return item_details
952
953
954@frappe.whitelist()
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530955def make_rm_stock_entry(
956 subcontract_order, rm_items=None, order_doctype="Subcontracting Order", target_doc=None
957):
s-aga-r6d89b2f2022-06-18 15:46:59 +0530958 if subcontract_order:
959 subcontract_order = frappe.get_doc(order_doctype, subcontract_order)
960
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530961 if not rm_items:
962 if not subcontract_order.supplied_items:
963 frappe.throw(_("No item available for transfer."))
s-aga-r6d89b2f2022-06-18 15:46:59 +0530964
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530965 rm_items = subcontract_order.supplied_items
s-aga-r6d89b2f2022-06-18 15:46:59 +0530966
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530967 fg_item_code_list = list(
968 set(item.get("main_item_code") or item.get("item_code") for item in rm_items)
969 )
s-aga-r6d89b2f2022-06-18 15:46:59 +0530970
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530971 if fg_item_code_list:
972 rm_item_code_list = tuple(set(item.get("rm_item_code") for item in rm_items))
973 item_wh = get_item_details(rm_item_code_list)
974
975 field_no_map, rm_detail_field = "purchase_order", "sco_rm_detail"
976 if order_doctype == "Purchase Order":
977 field_no_map, rm_detail_field = "subcontracting_order", "po_detail"
978
979 if target_doc and target_doc.get("items"):
980 target_doc.items = []
981
982 stock_entry = get_mapped_doc(
983 order_doctype,
984 subcontract_order.name,
985 {
986 order_doctype: {
987 "doctype": "Stock Entry",
988 "field_map": {
s-aga-r751bdc92022-12-31 17:17:22 +0530989 "supplier": "supplier",
990 "supplier_name": "supplier_name",
991 "supplier_address": "supplier_address",
Sagar Sharma3a9c08e2022-09-19 18:47:46 +0530992 "to_warehouse": "supplier_warehouse",
993 },
994 "field_no_map": [field_no_map],
995 "validation": {
996 "docstatus": ["=", 1],
997 },
998 },
999 },
1000 target_doc,
1001 ignore_child_tables=True,
1002 )
1003
1004 stock_entry.purpose = "Send to Subcontractor"
1005
1006 if order_doctype == "Purchase Order":
1007 stock_entry.purchase_order = subcontract_order.name
1008 else:
1009 stock_entry.subcontracting_order = subcontract_order.name
1010
1011 stock_entry.set_stock_entry_type()
1012
1013 for fg_item_code in fg_item_code_list:
1014 for rm_item in rm_items:
1015
Sagar Sharmaac7409b2022-09-28 16:46:48 +05301016 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 +05301017 rm_item_code = rm_item.get("rm_item_code")
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301018 items_dict = {
1019 rm_item_code: {
1020 rm_detail_field: rm_item.get("name"),
1021 "item_name": rm_item.get("item_name")
1022 or item_wh.get(rm_item_code, {}).get("item_name", ""),
1023 "description": item_wh.get(rm_item_code, {}).get("description", ""),
1024 "qty": rm_item.get("qty")
1025 or max(rm_item.get("required_qty") - rm_item.get("total_supplied_qty"), 0),
1026 "from_warehouse": rm_item.get("warehouse") or rm_item.get("reserve_warehouse"),
1027 "to_warehouse": subcontract_order.supplier_warehouse,
1028 "stock_uom": rm_item.get("stock_uom"),
Rohit Waghchauree88c5d62023-04-05 20:03:44 +05301029 "serial_and_batch_bundle": rm_item.get("serial_and_batch_bundle"),
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301030 "main_item_code": fg_item_code,
1031 "allow_alternative_item": item_wh.get(rm_item_code, {}).get("allow_alternative_item"),
1032 }
s-aga-r6d89b2f2022-06-18 15:46:59 +05301033 }
Sagar Sharma3a9c08e2022-09-19 18:47:46 +05301034
1035 stock_entry.add_to_stock_entry_detail(items_dict)
1036
1037 if target_doc:
1038 return stock_entry
1039 else:
1040 return stock_entry.as_dict()
1041 else:
1042 frappe.throw(_("No Items selected for transfer."))
s-aga-r6d89b2f2022-06-18 15:46:59 +05301043
1044
1045def add_items_in_ste(
1046 ste_doc, row, qty, rm_details, rm_detail_field="sco_rm_detail", batch_no=None
1047):
1048 item = ste_doc.append("items", row.item_details)
1049
1050 rm_detail = list(set(row.get(f"{rm_detail_field}s")).intersection(rm_details))
1051 item.update(
1052 {
1053 "qty": qty,
1054 "batch_no": batch_no,
1055 "basic_rate": row.item_details["rate"],
1056 rm_detail_field: rm_detail[0] if rm_detail else "",
1057 "s_warehouse": row.item_details["t_warehouse"],
1058 "t_warehouse": row.item_details["s_warehouse"],
1059 "item_code": row.item_details["rm_item_code"],
1060 "subcontracted_item": row.item_details["main_item_code"],
1061 "serial_no": "\n".join(row.serial_no) if row.serial_no else "",
1062 }
1063 )
1064
1065
1066def make_return_stock_entry_for_subcontract(
1067 available_materials, order_doc, rm_details, order_doctype="Subcontracting Order"
1068):
Sagar Sharma008542b2022-09-07 10:15:43 +05301069 ste_doc = get_mapped_doc(
1070 order_doctype,
1071 order_doc.name,
1072 {
1073 order_doctype: {
1074 "doctype": "Stock Entry",
Sagar Sharmaccb28892022-09-08 16:04:08 +05301075 "field_no_map": ["purchase_order", "subcontracting_order"],
Sagar Sharma008542b2022-09-07 10:15:43 +05301076 },
1077 },
1078 ignore_child_tables=True,
1079 )
1080
s-aga-r6d89b2f2022-06-18 15:46:59 +05301081 ste_doc.purpose = "Material Transfer"
1082
1083 if order_doctype == "Purchase Order":
1084 ste_doc.purchase_order = order_doc.name
1085 rm_detail_field = "po_detail"
1086 else:
1087 ste_doc.subcontracting_order = order_doc.name
1088 rm_detail_field = "sco_rm_detail"
1089 ste_doc.company = order_doc.company
1090 ste_doc.is_return = 1
1091
1092 for key, value in available_materials.items():
1093 if not value.qty:
1094 continue
1095
1096 if value.batch_no:
1097 for batch_no, qty in value.batch_no.items():
1098 if qty > 0:
1099 add_items_in_ste(ste_doc, value, value.qty, rm_details, rm_detail_field, batch_no)
1100 else:
1101 add_items_in_ste(ste_doc, value, value.qty, rm_details, rm_detail_field)
1102
1103 ste_doc.set_stock_entry_type()
s-aga-r6d89b2f2022-06-18 15:46:59 +05301104
1105 return ste_doc
1106
1107
1108@frappe.whitelist()
1109def get_materials_from_supplier(
1110 subcontract_order, rm_details, order_doctype="Subcontracting Order"
1111):
1112 if isinstance(rm_details, str):
1113 rm_details = json.loads(rm_details)
1114
1115 doc = frappe.get_cached_doc(order_doctype, subcontract_order)
1116 doc.initialized_fields()
1117 doc.subcontract_orders = [doc.name]
1118 doc.get_available_materials()
1119
1120 if not doc.available_materials:
1121 frappe.throw(
1122 _("Materials are already received against the {0} {1}").format(order_doctype, subcontract_order)
1123 )
1124
1125 return make_return_stock_entry_for_subcontract(
1126 doc.available_materials, doc, rm_details, order_doctype
1127 )