mrp_report_bom_structure.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. # -*- coding: utf-8 -*-
  2. from collections import defaultdict, OrderedDict
  3. from datetime import date, timedelta
  4. import json
  5. from odoo import api, fields, models, _
  6. from odoo.tools import float_compare, float_round, format_date, float_is_zero
  7. class ReportBomStructure(models.AbstractModel):
  8. _name = 'report.mrp.report_bom_structure'
  9. _description = 'BOM Overview Report'
  10. @api.model
  11. def get_html(self, bom_id=False, searchQty=1, searchVariant=False):
  12. res = self._get_report_data(bom_id=bom_id, searchQty=searchQty, searchVariant=searchVariant)
  13. res['has_attachments'] = self._has_attachments(res['lines'])
  14. return res
  15. @api.model
  16. def get_warehouses(self):
  17. return self.env['stock.warehouse'].search_read([('company_id', '=', self.env.company.id)], fields=['id', 'name'])
  18. @api.model
  19. def _compute_current_production_capacity(self, bom_data):
  20. # Get the maximum amount producible product of the selected bom given each component's stock levels.
  21. components_qty_to_produce = defaultdict(lambda: 0)
  22. components_qty_available = {}
  23. for comp in bom_data.get('components', []):
  24. if comp['product'].type != 'product' or float_is_zero(comp['base_bom_line_qty'], precision_digits=comp['uom'].rounding):
  25. continue
  26. components_qty_to_produce[comp['product_id']] += comp['base_bom_line_qty']
  27. components_qty_available[comp['product_id']] = comp['quantity_available']
  28. producibles = [float_round(components_qty_available[p_id] / qty, precision_digits=0, rounding_method='DOWN') for p_id, qty in components_qty_to_produce.items()]
  29. return min(producibles) * bom_data['bom']['product_qty'] if producibles else 0
  30. @api.model
  31. def _compute_production_capacities(self, bom_qty, bom_data):
  32. date_today = self.env.context.get('from_date', fields.date.today())
  33. same_delay = bom_data['lead_time'] == bom_data['availability_delay']
  34. res = {}
  35. if bom_data.get('producible_qty', 0):
  36. # Check if something is producible today, at the earliest time possible considering product's lead time.
  37. res['earliest_capacity'] = bom_data['producible_qty']
  38. res['earliest_date'] = format_date(self.env, date_today + timedelta(days=bom_data['lead_time']))
  39. if bom_data['availability_state'] != 'unavailable':
  40. if same_delay:
  41. # Means that stock will be resupplied at date_today, so the whole manufacture can start at date_today.
  42. res['earliest_capacity'] = bom_qty
  43. res['earliest_date'] = format_date(self.env, date_today + timedelta(days=bom_data['lead_time']))
  44. else:
  45. res['leftover_capacity'] = bom_qty - bom_data.get('producible_qty', 0)
  46. res['leftover_date'] = format_date(self.env, date_today + timedelta(days=bom_data['availability_delay']))
  47. return res
  48. @api.model
  49. def _get_report_values(self, docids, data=None):
  50. docs = []
  51. for bom_id in docids:
  52. bom = self.env['mrp.bom'].browse(bom_id)
  53. variant = data.get('variant')
  54. candidates = variant and self.env['product.product'].browse(int(variant)) or bom.product_id or bom.product_tmpl_id.product_variant_ids
  55. quantity = float(data.get('quantity', bom.product_qty))
  56. if data.get('warehouse_id'):
  57. self = self.with_context(warehouse=int(data.get('warehouse_id')))
  58. for product_variant_id in candidates.ids:
  59. docs.append(self._get_pdf_doc(bom_id, data, quantity, product_variant_id))
  60. if not candidates:
  61. docs.append(self._get_pdf_doc(bom_id, data, quantity))
  62. return {
  63. 'doc_ids': docids,
  64. 'doc_model': 'mrp.bom',
  65. 'docs': docs,
  66. }
  67. @api.model
  68. def _get_pdf_doc(self, bom_id, data, quantity, product_variant_id=None):
  69. if data and data.get('unfolded_ids'):
  70. doc = self._get_pdf_line(bom_id, product_id=product_variant_id, qty=quantity, unfolded_ids=set(json.loads(data.get('unfolded_ids'))))
  71. else:
  72. doc = self._get_pdf_line(bom_id, product_id=product_variant_id, qty=quantity, unfolded=True)
  73. doc['show_availabilities'] = False if data and data.get('availabilities') == 'false' else True
  74. doc['show_costs'] = False if data and data.get('costs') == 'false' else True
  75. doc['show_operations'] = False if data and data.get('operations') == 'false' else True
  76. doc['show_lead_times'] = False if data and data.get('lead_times') == 'false' else True
  77. return doc
  78. @api.model
  79. def _get_report_data(self, bom_id, searchQty=0, searchVariant=False):
  80. lines = {}
  81. bom = self.env['mrp.bom'].browse(bom_id)
  82. bom_quantity = searchQty or bom.product_qty or 1
  83. bom_product_variants = {}
  84. bom_uom_name = ''
  85. if searchVariant:
  86. product = self.env['product.product'].browse(int(searchVariant))
  87. else:
  88. product = bom.product_id or bom.product_tmpl_id.product_variant_id
  89. if bom:
  90. bom_uom_name = bom.product_uom_id.name
  91. # Get variants used for search
  92. if not bom.product_id:
  93. for variant in bom.product_tmpl_id.product_variant_ids:
  94. bom_product_variants[variant.id] = variant.display_name
  95. if self.env.context.get('warehouse'):
  96. warehouse = self.env['stock.warehouse'].browse(self.env.context.get('warehouse'))
  97. else:
  98. warehouse = self.env['stock.warehouse'].browse(self.get_warehouses()[0]['id'])
  99. lines = self._get_bom_data(bom, warehouse, product=product, line_qty=bom_quantity, level=0)
  100. production_capacities = self._compute_production_capacities(bom_quantity, lines)
  101. lines.update(production_capacities)
  102. return {
  103. 'lines': lines,
  104. 'variants': bom_product_variants,
  105. 'bom_uom_name': bom_uom_name,
  106. 'bom_qty': bom_quantity,
  107. 'is_variant_applied': self.env.user.user_has_groups('product.group_product_variant') and len(bom_product_variants) > 1,
  108. 'is_uom_applied': self.env.user.user_has_groups('uom.group_uom'),
  109. 'precision': self.env['decimal.precision'].precision_get('Product Unit of Measure'),
  110. }
  111. @api.model
  112. def _get_components_closest_forecasted(self, lines, line_quantities, parent_bom, product_info, ignore_stock=False):
  113. """
  114. Returns a dict mapping products to a dict of their corresponding BoM lines,
  115. which are mapped to their closest date in the forecast report where consumed quantity >= forecasted quantity.
  116. E.g. {'product_1_id': {'line_1_id': date_1, line_2_id: date_2}, 'product_2': {line_3_id: date_3}, ...}.
  117. Note that
  118. - if a product is unavailable + not forecasted for a specific bom line => its date will be `date.max`
  119. - if a product's type is not `product` or is already in stock for a specific bom line => its date will be `date.min`.
  120. """
  121. if ignore_stock:
  122. return {}
  123. # Use defaultdict(OrderedDict) in case there are lines with the same component.
  124. closest_forecasted = defaultdict(OrderedDict)
  125. remaining_products = []
  126. product_quantities_info = defaultdict(OrderedDict)
  127. for line in lines:
  128. product = line.product_id
  129. quantities_info = self._get_quantities_info(product, line.product_uom_id, parent_bom, product_info)
  130. stock_loc = quantities_info['stock_loc']
  131. product_info[product.id]['consumptions'][stock_loc] += line_quantities.get(line.id, 0.0)
  132. product_quantities_info[product.id][line.id] = product_info[product.id]['consumptions'][stock_loc]
  133. if (product.detailed_type != 'product' or
  134. float_compare(product_info[product.id]['consumptions'][stock_loc], quantities_info['free_qty'], precision_rounding=product.uom_id.rounding) <= 0):
  135. # Use date.min as a sentinel value for _get_stock_availability
  136. closest_forecasted[product.id][line.id] = date.min
  137. elif stock_loc != 'in_stock':
  138. closest_forecasted[product.id][line.id] = date.max
  139. else:
  140. remaining_products.append(product.id)
  141. closest_forecasted[product.id][line.id] = None
  142. date_today = self.env.context.get('from_date', fields.date.today())
  143. domain = [('state', '=', 'forecast'), ('date', '>=', date_today), ('product_id', 'in', list(set(remaining_products)))]
  144. if self.env.context.get('warehouse'):
  145. domain.append(('warehouse_id', '=', self.env.context.get('warehouse')))
  146. if remaining_products:
  147. res = self.env['report.stock.quantity']._read_group(
  148. domain,
  149. ['min_date:min(date)', 'product_id', 'product_qty'],
  150. ['product_id', 'product_qty'],
  151. orderby='product_id asc, min_date asc', lazy=False
  152. )
  153. available_quantities = defaultdict(list)
  154. for group in res:
  155. product_id = group['product_id'][0]
  156. available_quantities[product_id].append([group['min_date'], group['product_qty']])
  157. for product_id in remaining_products:
  158. # Find the first empty line_id for the given product_id.
  159. line_id = next(filter(lambda k: not closest_forecasted[product_id][k], closest_forecasted[product_id].keys()), None)
  160. # Find the first available quantity for the given product and update closest_forecasted
  161. for min_date, product_qty in available_quantities[product_id]:
  162. if product_qty >= product_quantities_info[product_id][line_id]:
  163. closest_forecasted[product_id][line_id] = min_date
  164. break
  165. if not closest_forecasted[product_id][line_id]:
  166. closest_forecasted[product_id][line_id] = date.max
  167. return closest_forecasted
  168. @api.model
  169. def _get_bom_data(self, bom, warehouse, product=False, line_qty=False, bom_line=False, level=0, parent_bom=False, index=0, product_info=False, ignore_stock=False):
  170. """ Gets recursively the BoM and all its subassemblies and computes availibility estimations for each component and their disponibility in stock.
  171. Accepts specific keys in context that will affect the data computed :
  172. - 'minimized': Will cut all data not required to compute availability estimations.
  173. - 'from_date': Gives a single value for 'today' across the functions, as well as using this date in products quantity computes.
  174. """
  175. is_minimized = self.env.context.get('minimized', False)
  176. if not product:
  177. product = bom.product_id or bom.product_tmpl_id.product_variant_id
  178. if not line_qty:
  179. line_qty = bom.product_qty
  180. if not product_info:
  181. product_info = {}
  182. company = bom.company_id or self.env.company
  183. current_quantity = line_qty
  184. if bom_line:
  185. current_quantity = bom_line.product_uom_id._compute_quantity(line_qty, bom.product_uom_id) or 0
  186. prod_cost = 0
  187. attachment_ids = []
  188. if not is_minimized:
  189. if product:
  190. prod_cost = product.uom_id._compute_price(product.with_company(company).standard_price, bom.product_uom_id) * current_quantity
  191. attachment_ids = self.env['mrp.document'].search(['|', '&', ('res_model', '=', 'product.product'),
  192. ('res_id', '=', product.id), '&', ('res_model', '=', 'product.template'),
  193. ('res_id', '=', product.product_tmpl_id.id)]).ids
  194. else:
  195. # Use the product template instead of the variant
  196. prod_cost = bom.product_tmpl_id.uom_id._compute_price(bom.product_tmpl_id.with_company(company).standard_price, bom.product_uom_id) * current_quantity
  197. attachment_ids = self.env['mrp.document'].search([('res_model', '=', 'product.template'), ('res_id', '=', bom.product_tmpl_id.id)]).ids
  198. key = product.id
  199. bom_key = bom.id
  200. self._update_product_info(product, bom_key, product_info, warehouse, current_quantity, bom=bom, parent_bom=parent_bom)
  201. route_info = product_info[key].get(bom_key, {})
  202. quantities_info = {}
  203. if not ignore_stock:
  204. # Useless to compute quantities_info if it's not going to be used later on
  205. quantities_info = self._get_quantities_info(product, bom.product_uom_id, parent_bom, product_info)
  206. bom_report_line = {
  207. 'index': index,
  208. 'bom': bom,
  209. 'bom_id': bom and bom.id or False,
  210. 'bom_code': bom and bom.code or False,
  211. 'type': 'bom',
  212. 'quantity': current_quantity,
  213. 'quantity_available': quantities_info.get('free_qty', 0),
  214. 'quantity_on_hand': quantities_info.get('on_hand_qty', 0),
  215. 'base_bom_line_qty': bom_line.product_qty if bom_line else False, # bom_line isn't defined only for the top-level product
  216. 'name': product.display_name or bom.product_tmpl_id.display_name,
  217. 'uom': bom.product_uom_id if bom else product.uom_id,
  218. 'uom_name': bom.product_uom_id.name if bom else product.uom_id.name,
  219. 'route_type': route_info.get('route_type', ''),
  220. 'route_name': route_info.get('route_name', ''),
  221. 'route_detail': route_info.get('route_detail', ''),
  222. 'lead_time': route_info.get('lead_time', False),
  223. 'currency': company.currency_id,
  224. 'currency_id': company.currency_id.id,
  225. 'product': product,
  226. 'product_id': product.id,
  227. 'link_id': (product.id if product.product_variant_count > 1 else product.product_tmpl_id.id) or bom.product_tmpl_id.id,
  228. 'link_model': 'product.product' if product.product_variant_count > 1 else 'product.template',
  229. 'code': bom and bom.display_name or '',
  230. 'prod_cost': prod_cost,
  231. 'bom_cost': 0,
  232. 'level': level or 0,
  233. 'attachment_ids': attachment_ids,
  234. 'phantom_bom': bom.type == 'phantom',
  235. 'parent_id': parent_bom and parent_bom.id or False,
  236. }
  237. if not is_minimized:
  238. operations = self._get_operation_line(product, bom, float_round(current_quantity, precision_rounding=1, rounding_method='UP'), level + 1, index)
  239. bom_report_line['operations'] = operations
  240. bom_report_line['operations_cost'] = sum([op['bom_cost'] for op in operations])
  241. bom_report_line['operations_time'] = sum([op['quantity'] for op in operations])
  242. bom_report_line['bom_cost'] += bom_report_line['operations_cost']
  243. components = []
  244. no_bom_lines = self.env['mrp.bom.line']
  245. line_quantities = {}
  246. for line in bom.bom_line_ids:
  247. if product and line._skip_bom_line(product):
  248. continue
  249. line_quantity = (current_quantity / (bom.product_qty or 1.0)) * line.product_qty
  250. line_quantities[line.id] = line_quantity
  251. if not line.child_bom_id:
  252. no_bom_lines |= line
  253. # Update product_info for all the components before computing closest forecasted.
  254. self._update_product_info(line.product_id, bom.id, product_info, warehouse, line_quantity, bom=False, parent_bom=bom)
  255. components_closest_forecasted = self.with_context(parent_product_id=product.id)._get_components_closest_forecasted(no_bom_lines, line_quantities, bom, product_info, ignore_stock)
  256. for component_index, line in enumerate(bom.bom_line_ids):
  257. new_index = f"{index}{component_index}"
  258. if product and line._skip_bom_line(product):
  259. continue
  260. line_quantity = line_quantities.get(line.id, 0.0)
  261. if line.child_bom_id:
  262. component = self.with_context(parent_product_id=product.id)._get_bom_data(line.child_bom_id, warehouse, line.product_id, line_quantity, bom_line=line, level=level + 1, parent_bom=bom,
  263. index=new_index, product_info=product_info, ignore_stock=ignore_stock)
  264. else:
  265. component = self.with_context(
  266. parent_product_id=product.id,
  267. components_closest_forecasted=components_closest_forecasted,
  268. )._get_component_data(bom, warehouse, line, line_quantity, level + 1, new_index, product_info, ignore_stock)
  269. components.append(component)
  270. bom_report_line['bom_cost'] += component['bom_cost']
  271. bom_report_line['components'] = components
  272. bom_report_line['producible_qty'] = self._compute_current_production_capacity(bom_report_line)
  273. if not is_minimized:
  274. byproducts, byproduct_cost_portion = self._get_byproducts_lines(product, bom, current_quantity, level + 1, bom_report_line['bom_cost'], index)
  275. bom_report_line['byproducts'] = byproducts
  276. bom_report_line['cost_share'] = float_round(1 - byproduct_cost_portion, precision_rounding=0.0001)
  277. bom_report_line['byproducts_cost'] = sum(byproduct['bom_cost'] for byproduct in byproducts)
  278. bom_report_line['byproducts_total'] = sum(byproduct['quantity'] for byproduct in byproducts)
  279. bom_report_line['bom_cost'] *= bom_report_line['cost_share']
  280. availabilities = self._get_availabilities(product, current_quantity, product_info, bom_key, quantities_info, level, ignore_stock, components)
  281. bom_report_line.update(availabilities)
  282. if level == 0:
  283. # Gives a unique key for the first line that indicates if product is ready for production right now.
  284. bom_report_line['components_available'] = all([c['stock_avail_state'] == 'available' for c in components])
  285. return bom_report_line
  286. @api.model
  287. def _get_component_data(self, parent_bom, warehouse, bom_line, line_quantity, level, index, product_info, ignore_stock=False):
  288. company = parent_bom.company_id or self.env.company
  289. price = bom_line.product_id.uom_id._compute_price(bom_line.product_id.with_company(company).standard_price, bom_line.product_uom_id) * line_quantity
  290. rounded_price = company.currency_id.round(price)
  291. key = bom_line.product_id.id
  292. bom_key = parent_bom.id
  293. self._update_product_info(bom_line.product_id, bom_key, product_info, warehouse, line_quantity, bom=False, parent_bom=parent_bom)
  294. route_info = product_info[key].get(bom_key, {})
  295. quantities_info = {}
  296. if not ignore_stock:
  297. # Useless to compute quantities_info if it's not going to be used later on
  298. quantities_info = self._get_quantities_info(bom_line.product_id, bom_line.product_uom_id, parent_bom, product_info)
  299. availabilities = self._get_availabilities(bom_line.product_id, line_quantity, product_info, bom_key, quantities_info, level, ignore_stock, bom_line=bom_line)
  300. attachment_ids = []
  301. if not self.env.context.get('minimized', False):
  302. attachment_ids = self.env['mrp.document'].search(['|', '&', ('res_model', '=', 'product.product'), ('res_id', '=', bom_line.product_id.id),
  303. '&', ('res_model', '=', 'product.template'), ('res_id', '=', bom_line.product_id.product_tmpl_id.id)]).ids
  304. return {
  305. 'type': 'component',
  306. 'index': index,
  307. 'bom_id': False,
  308. 'product': bom_line.product_id,
  309. 'product_id': bom_line.product_id.id,
  310. 'link_id': bom_line.product_id.id if bom_line.product_id.product_variant_count > 1 else bom_line.product_id.product_tmpl_id.id,
  311. 'link_model': 'product.product' if bom_line.product_id.product_variant_count > 1 else 'product.template',
  312. 'name': bom_line.product_id.display_name,
  313. 'code': '',
  314. 'currency': company.currency_id,
  315. 'currency_id': company.currency_id.id,
  316. 'quantity': line_quantity,
  317. 'quantity_available': quantities_info.get('free_qty', 0),
  318. 'quantity_on_hand': quantities_info.get('on_hand_qty', 0),
  319. 'base_bom_line_qty': bom_line.product_qty,
  320. 'uom': bom_line.product_uom_id,
  321. 'uom_name': bom_line.product_uom_id.name,
  322. 'prod_cost': rounded_price,
  323. 'bom_cost': rounded_price,
  324. 'route_type': route_info.get('route_type', ''),
  325. 'route_name': route_info.get('route_name', ''),
  326. 'route_detail': route_info.get('route_detail', ''),
  327. 'lead_time': route_info.get('lead_time', False),
  328. 'stock_avail_state': availabilities['stock_avail_state'],
  329. 'resupply_avail_delay': availabilities['resupply_avail_delay'],
  330. 'availability_display': availabilities['availability_display'],
  331. 'availability_state': availabilities['availability_state'],
  332. 'availability_delay': availabilities['availability_delay'],
  333. 'parent_id': parent_bom.id,
  334. 'level': level or 0,
  335. 'attachment_ids': attachment_ids,
  336. }
  337. @api.model
  338. def _get_quantities_info(self, product, bom_uom, parent_bom, product_info):
  339. return {
  340. 'free_qty': product.uom_id._compute_quantity(product.free_qty, bom_uom) if product.detailed_type == 'product' else False,
  341. 'on_hand_qty': product.uom_id._compute_quantity(product.qty_available, bom_uom) if product.detailed_type == 'product' else False,
  342. 'stock_loc': 'in_stock',
  343. }
  344. @api.model
  345. def _update_product_info(self, product, bom_key, product_info, warehouse, quantity, bom, parent_bom):
  346. key = product.id
  347. if key not in product_info:
  348. product_info[key] = {'consumptions': {'in_stock': 0}}
  349. if not product_info[key].get(bom_key):
  350. product_info[key][bom_key] = self.with_context(
  351. product_info=product_info, parent_bom=parent_bom
  352. )._get_resupply_route_info(warehouse, product, quantity, bom)
  353. @api.model
  354. def _get_byproducts_lines(self, product, bom, bom_quantity, level, total, index):
  355. byproducts = []
  356. byproduct_cost_portion = 0
  357. company = bom.company_id or self.env.company
  358. byproduct_index = 0
  359. for byproduct in bom.byproduct_ids:
  360. if byproduct._skip_byproduct_line(product):
  361. continue
  362. line_quantity = (bom_quantity / (bom.product_qty or 1.0)) * byproduct.product_qty
  363. cost_share = byproduct.cost_share / 100
  364. byproduct_cost_portion += cost_share
  365. price = byproduct.product_id.uom_id._compute_price(byproduct.product_id.with_company(company).standard_price, byproduct.product_uom_id) * line_quantity
  366. byproducts.append({
  367. 'id': byproduct.id,
  368. 'index': f"{index}{byproduct_index}",
  369. 'type': 'byproduct',
  370. 'link_id': byproduct.product_id.id if byproduct.product_id.product_variant_count > 1 else byproduct.product_id.product_tmpl_id.id,
  371. 'link_model': 'product.product' if byproduct.product_id.product_variant_count > 1 else 'product.template',
  372. 'currency_id': company.currency_id.id,
  373. 'name': byproduct.product_id.display_name,
  374. 'quantity': line_quantity,
  375. 'uom_name': byproduct.product_uom_id.name,
  376. 'prod_cost': company.currency_id.round(price),
  377. 'parent_id': bom.id,
  378. 'level': level or 0,
  379. 'bom_cost': company.currency_id.round(total * cost_share),
  380. 'cost_share': cost_share,
  381. })
  382. byproduct_index += 1
  383. return byproducts, byproduct_cost_portion
  384. @api.model
  385. def _get_operation_line(self, product, bom, qty, level, index):
  386. operations = []
  387. total = 0.0
  388. qty = bom.product_uom_id._compute_quantity(qty, bom.product_tmpl_id.uom_id)
  389. company = bom.company_id or self.env.company
  390. operation_index = 0
  391. for operation in bom.operation_ids:
  392. if not product or operation._skip_operation_line(product):
  393. continue
  394. capacity = operation.workcenter_id._get_capacity(product)
  395. operation_cycle = float_round(qty / capacity, precision_rounding=1, rounding_method='UP')
  396. duration_expected = (operation_cycle * operation.time_cycle * 100.0 / operation.workcenter_id.time_efficiency) + \
  397. operation.workcenter_id._get_expected_duration(product)
  398. total = ((duration_expected / 60.0) * operation.workcenter_id.costs_hour)
  399. operations.append({
  400. 'type': 'operation',
  401. 'index': f"{index}{operation_index}",
  402. 'level': level or 0,
  403. 'operation': operation,
  404. 'link_id': operation.id,
  405. 'link_model': 'mrp.routing.workcenter',
  406. 'name': operation.name + ' - ' + operation.workcenter_id.name,
  407. 'uom_name': _("Minutes"),
  408. 'quantity': duration_expected,
  409. 'bom_cost': self.env.company.currency_id.round(total),
  410. 'currency_id': company.currency_id.id,
  411. 'model': 'mrp.routing.workcenter',
  412. })
  413. operation_index += 1
  414. return operations
  415. @api.model
  416. def _get_pdf_line(self, bom_id, product_id=False, qty=1, unfolded_ids=None, unfolded=False):
  417. if unfolded_ids is None:
  418. unfolded_ids = set()
  419. bom = self.env['mrp.bom'].browse(bom_id)
  420. if product_id:
  421. product = self.env['product.product'].browse(int(product_id))
  422. else:
  423. product = bom.product_id or bom.product_tmpl_id.product_variant_id or bom.product_tmpl_id.with_context(active_test=False).product_variant_id
  424. if self.env.context.get('warehouse'):
  425. warehouse = self.env['stock.warehouse'].browse(self.env.context.get('warehouse'))
  426. else:
  427. warehouse = self.env['stock.warehouse'].browse(self.get_warehouses()[0]['id'])
  428. level = 1
  429. data = self._get_bom_data(bom, warehouse, product=product, line_qty=qty, level=0)
  430. pdf_lines = self._get_bom_array_lines(data, level, unfolded_ids, unfolded, True)
  431. data['lines'] = pdf_lines
  432. return data
  433. @api.model
  434. def _get_bom_array_lines(self, data, level, unfolded_ids, unfolded, parent_unfolded=True):
  435. bom_lines = data['components']
  436. lines = []
  437. for bom_line in bom_lines:
  438. line_unfolded = ('bom_' + str(bom_line['index'])) in unfolded_ids
  439. line_visible = level == 1 or unfolded or parent_unfolded
  440. lines.append({
  441. 'bom_id': bom_line['bom_id'],
  442. 'name': bom_line['name'],
  443. 'type': bom_line['type'],
  444. 'quantity': bom_line['quantity'],
  445. 'quantity_available': bom_line['quantity_available'],
  446. 'quantity_on_hand': bom_line['quantity_on_hand'],
  447. 'producible_qty': bom_line.get('producible_qty', False),
  448. 'uom': bom_line['uom_name'],
  449. 'prod_cost': bom_line['prod_cost'],
  450. 'bom_cost': bom_line['bom_cost'],
  451. 'route_name': bom_line['route_name'],
  452. 'route_detail': bom_line['route_detail'],
  453. 'lead_time': bom_line['lead_time'],
  454. 'level': bom_line['level'],
  455. 'code': bom_line['code'],
  456. 'availability_state': bom_line['availability_state'],
  457. 'availability_display': bom_line['availability_display'],
  458. 'visible': line_visible,
  459. })
  460. if bom_line.get('components'):
  461. lines += self._get_bom_array_lines(bom_line, level + 1, unfolded_ids, unfolded, line_visible and line_unfolded)
  462. if data['operations']:
  463. lines.append({
  464. 'name': _('Operations'),
  465. 'type': 'operation',
  466. 'quantity': data['operations_time'],
  467. 'uom': _('minutes'),
  468. 'bom_cost': data['operations_cost'],
  469. 'level': level,
  470. 'visible': parent_unfolded,
  471. })
  472. operations_unfolded = unfolded or (parent_unfolded and ('operations_' + str(data['index'])) in unfolded_ids)
  473. for operation in data['operations']:
  474. lines.append({
  475. 'name': operation['name'],
  476. 'type': 'operation',
  477. 'quantity': operation['quantity'],
  478. 'uom': _('minutes'),
  479. 'bom_cost': operation['bom_cost'],
  480. 'level': level + 1,
  481. 'visible': operations_unfolded,
  482. })
  483. if data['byproducts']:
  484. lines.append({
  485. 'name': _('Byproducts'),
  486. 'type': 'byproduct',
  487. 'uom': False,
  488. 'quantity': data['byproducts_total'],
  489. 'bom_cost': data['byproducts_cost'],
  490. 'level': level,
  491. 'visible': parent_unfolded,
  492. })
  493. byproducts_unfolded = unfolded or (parent_unfolded and ('byproducts_' + str(data['index'])) in unfolded_ids)
  494. for byproduct in data['byproducts']:
  495. lines.append({
  496. 'name': byproduct['name'],
  497. 'type': 'byproduct',
  498. 'quantity': byproduct['quantity'],
  499. 'uom': byproduct['uom_name'],
  500. 'prod_cost': byproduct['prod_cost'],
  501. 'bom_cost': byproduct['bom_cost'],
  502. 'level': level + 1,
  503. 'visible': byproducts_unfolded,
  504. })
  505. return lines
  506. @api.model
  507. def _get_resupply_route_info(self, warehouse, product, quantity, bom=False):
  508. found_rules = []
  509. if self._need_special_rules(self.env.context.get('product_info'), self.env.context.get('parent_bom'), self.env.context.get('parent_product_id')):
  510. found_rules = self._find_special_rules(product, self.env.context.get('product_info'), self.env.context.get('parent_bom'), self.env.context.get('parent_product_id'))
  511. if not found_rules:
  512. found_rules = product._get_rules_from_location(warehouse.lot_stock_id)
  513. if not found_rules:
  514. return {}
  515. rules_delay = sum(rule.delay for rule in found_rules)
  516. return self._format_route_info(found_rules, rules_delay, warehouse, product, bom, quantity)
  517. @api.model
  518. def _need_special_rules(self, product_info, parent_bom=False, parent_product_id=False):
  519. return False
  520. @api.model
  521. def _find_special_rules(self, product, product_info, parent_bom=False, parent_product_id=False):
  522. return False
  523. @api.model
  524. def _format_route_info(self, rules, rules_delay, warehouse, product, bom, quantity):
  525. manufacture_rules = [rule for rule in rules if rule.action == 'manufacture' and bom]
  526. if manufacture_rules:
  527. # Need to get rules from Production location to get delays before production
  528. wh_manufacture_rules = product._get_rules_from_location(product.property_stock_production, route_ids=warehouse.route_ids)
  529. wh_manufacture_rules -= rules
  530. rules_delay += sum(rule.delay for rule in wh_manufacture_rules)
  531. manufacturing_lead = bom.company_id.manufacturing_lead if bom and bom.company_id else 0
  532. return {
  533. 'route_type': 'manufacture',
  534. 'route_name': manufacture_rules[0].route_id.display_name,
  535. 'route_detail': bom.display_name,
  536. 'lead_time': product.produce_delay + rules_delay + manufacturing_lead,
  537. 'manufacture_delay': product.produce_delay + rules_delay + manufacturing_lead,
  538. }
  539. return {}
  540. @api.model
  541. def _get_availabilities(self, product, quantity, product_info, bom_key, quantities_info, level, ignore_stock=False, components=False, bom_line=None):
  542. # Get availabilities according to stock (today & forecasted).
  543. stock_state, stock_delay = ('unavailable', False)
  544. if not ignore_stock:
  545. stock_state, stock_delay = self._get_stock_availability(product, quantity, product_info, quantities_info, bom_line=bom_line)
  546. # Get availabilities from applied resupply rules
  547. components = components or []
  548. route_info = product_info[product.id].get(bom_key)
  549. resupply_state, resupply_delay = ('unavailable', False)
  550. if product.detailed_type != 'product':
  551. resupply_state, resupply_delay = ('available', 0)
  552. elif route_info:
  553. resupply_state, resupply_delay = self._get_resupply_availability(route_info, components)
  554. base = {
  555. 'resupply_avail_delay': resupply_delay,
  556. 'stock_avail_state': stock_state,
  557. }
  558. if level != 0 and stock_state != 'unavailable':
  559. return {**base, **{
  560. 'availability_display': self._format_date_display(stock_state, stock_delay),
  561. 'availability_state': stock_state,
  562. 'availability_delay': stock_delay,
  563. }}
  564. return {**base, **{
  565. 'availability_display': self._format_date_display(resupply_state, resupply_delay),
  566. 'availability_state': resupply_state,
  567. 'availability_delay': resupply_delay,
  568. }}
  569. @api.model
  570. def _get_stock_availability(self, product, quantity, product_info, quantities_info, bom_line=None):
  571. closest_forecasted = None
  572. if bom_line:
  573. closest_forecasted = self.env.context.get('components_closest_forecasted', {}).get(product.id, {}).get(bom_line.id)
  574. if closest_forecasted == date.min:
  575. return ('available', 0)
  576. if closest_forecasted == date.max:
  577. return ('unavailable', False)
  578. date_today = self.env.context.get('from_date', fields.date.today())
  579. if product.detailed_type != 'product':
  580. return ('available', 0)
  581. stock_loc = quantities_info['stock_loc']
  582. product_info[product.id]['consumptions'][stock_loc] += quantity
  583. # Check if product is already in stock with enough quantity
  584. if float_compare(product_info[product.id]['consumptions'][stock_loc], quantities_info['free_qty'], precision_rounding=product.uom_id.rounding) <= 0:
  585. return ('available', 0)
  586. # No need to check forecast if the product isn't located in our stock
  587. if stock_loc == 'in_stock':
  588. domain = [('state', '=', 'forecast'), ('date', '>=', date_today), ('product_id', '=', product.id), ('product_qty', '>=', product_info[product.id]['consumptions'][stock_loc])]
  589. if self.env.context.get('warehouse'):
  590. domain.append(('warehouse_id', '=', self.env.context.get('warehouse')))
  591. # Seek the closest date in the forecast report where consummed quantity >= forecasted quantity
  592. if not closest_forecasted:
  593. closest_forecasted = self.env['report.stock.quantity']._read_group(domain, ['min_date:min(date)', 'product_id'], ['product_id'])
  594. closest_forecasted = closest_forecasted and closest_forecasted[0]['min_date']
  595. if closest_forecasted:
  596. days_to_forecast = (closest_forecasted - date_today).days
  597. return ('expected', days_to_forecast)
  598. return ('unavailable', False)
  599. @api.model
  600. def _get_resupply_availability(self, route_info, components):
  601. if route_info.get('route_type') == 'manufacture':
  602. max_component_delay = self._get_max_component_delay(components)
  603. if max_component_delay is False:
  604. return ('unavailable', False)
  605. produce_delay = route_info.get('manufacture_delay', 0) + max_component_delay
  606. return ('estimated', produce_delay)
  607. return ('unavailable', False)
  608. @api.model
  609. def _get_max_component_delay(self, components):
  610. max_component_delay = 0
  611. for component in components:
  612. line_delay = component.get('availability_delay', False)
  613. if line_delay is False:
  614. # This component isn't available right now and cannot be resupplied, so the manufactured product can't be resupplied either.
  615. return False
  616. max_component_delay = max(max_component_delay, line_delay)
  617. return max_component_delay
  618. @api.model
  619. def _format_date_display(self, state, delay):
  620. date_today = self.env.context.get('from_date', fields.date.today())
  621. if state == 'available':
  622. return _('Available')
  623. if state == 'unavailable':
  624. return _('Not Available')
  625. if state == 'expected':
  626. return _('Expected %s', format_date(self.env, date_today + timedelta(days=delay)))
  627. if state == 'estimated':
  628. return _('Estimated %s', format_date(self.env, date_today + timedelta(days=delay)))
  629. return ''
  630. @api.model
  631. def _has_attachments(self, data):
  632. return data['attachment_ids'] or any(self._has_attachments(component) for component in data.get('components', []))