Debian Codegraph @

addons/purchase_stock/models/purchase_order_line.py

raw symbols SCIP
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 from dateutil.relativedelta import relativedelta
4
5 from odoo import SUPERUSER_ID, api, Command, fields, models, _
6 from odoo.tools.float_utils import float_compare, float_is_zero, float_round
7 from odoo.exceptions import UserError
8
9
10 class PurchaseOrderLine(models.Model):
11 _inherit = 'purchase.order.line'
12
13 def _ondelete_stock_moves(self):
14 modified_fields = ['qty_received_manual', 'qty_received_method']
15 self.flush_recordset(fnames=['qty_received', *modified_fields])
16 self.invalidate_recordset(fnames=modified_fields, flush=False)
17 query = f'''
18 UPDATE {self._table}
19 SET qty_received_manual = qty_received, qty_received_method = 'manual'
20 WHERE id IN %(ids)s
21 '''
22 self.env.cr.execute(query, {'ids': self._ids or (None,)})
23 self.modified(modified_fields)
24
25 qty_received_method = fields.Selection(selection_add=[('stock_moves', 'Stock Moves')],
26 ondelete={'stock_moves': _ondelete_stock_moves})
27
28 move_ids = fields.One2many('stock.move', 'purchase_line_id', string='Reservation', readonly=True, copy=False)
29 orderpoint_id = fields.Many2one('stock.warehouse.orderpoint', 'Orderpoint', copy=False, index='btree_not_null', ondelete='set null')
30 move_dest_ids = fields.Many2many('stock.move', 'stock_move_created_purchase_line_rel', 'created_purchase_line_id', 'move_id', 'Downstream moves alt')
31 product_description_variants = fields.Char('Custom Description')
32 propagate_cancel = fields.Boolean('Propagate cancellation', default=True)
33 forecasted_issue = fields.Boolean(compute='_compute_forecasted_issue')
34 is_storable = fields.Boolean(related='product_id.is_storable')
35 location_final_id = fields.Many2one('stock.location', 'Location from procurement')
36
37 def _compute_qty_received_method(self):
38 super(PurchaseOrderLine, self)._compute_qty_received_method()
39 for line in self.filtered(lambda l: not l.display_type):
40 if line.product_id.type == 'consu':
41 line.qty_received_method = 'stock_moves'
42
43 def _get_po_line_moves(self):
44 self.ensure_one()
45 moves = self.move_ids.filtered(lambda m: m.product_id == self.product_id)
46 if self.env.context.get('accrual_entry_date'):
47 accrual_date = fields.Date.from_string(self.env.context['accrual_entry_date'])
48 moves = moves.filtered(lambda r: fields.Date.context_today(r, r.date) <= accrual_date)
49 return moves
50
51 @api.depends('move_ids.state', 'move_ids.product_uom', 'move_ids.quantity')
52 def _compute_qty_received(self):
53 super()._compute_qty_received()
54
55 def _prepare_qty_received(self):
56 from_stock_lines = self.filtered(lambda order_line: order_line.qty_received_method == 'stock_moves')
57 received_qties = super(PurchaseOrderLine, self - from_stock_lines)._prepare_qty_received()
58 for line in self:
59 if line.qty_received_method == 'stock_moves':
60 total = 0.0
61 # In case of a BOM in kit, the products delivered do not correspond to the products in
62 # the PO. Therefore, we can skip them since they will be handled later on.
63 for move in line._get_po_line_moves():
64 if move.state == 'done':
65 if move._is_purchase_return():
66 if not move.origin_returned_move_id or move.to_refund:
67 total -= move.product_uom._compute_quantity(move.quantity, line.product_uom_id, rounding_method='HALF-UP')
68 elif move.origin_returned_move_id and move.origin_returned_move_id._is_dropshipped() and not move._is_dropshipped_returned():
69 # Edge case: the dropship is returned to the stock, no to the supplier.
70 # In this case, the received quantity on the PO is set although we didn't
71 # receive the product physically in our stock. To avoid counting the
72 # quantity twice, we do nothing.
73 pass
74 elif move.origin_returned_move_id and move.origin_returned_move_id._is_purchase_return() and not move.to_refund:
75 pass
76 else:
77 total += move.product_uom._compute_quantity(move.quantity, line.product_uom_id, rounding_method='HALF-UP')
78 line._track_qty_received(total)
79 received_qties[line] = total
80 return received_qties
81
82 @api.depends('product_uom_qty', 'date_planned')
83 def _compute_forecasted_issue(self):
84 for line in self:
85 warehouse = line.order_id.picking_type_id.warehouse_id
86 line.forecasted_issue = False
87 if line.product_id:
88 virtual_available = line.product_id.with_context(warehouse_id=warehouse.id, to_date=line.date_planned).virtual_available
89 if line.state == 'draft':
90 virtual_available += line.product_uom_qty
91 if virtual_available < 0:
92 line.forecasted_issue = True
93
94 @api.model_create_multi
95 def create(self, vals_list):
96 lines = super().create(vals_list)
97 lines.filtered(lambda l: l.order_id.state == 'purchase')._create_or_update_picking()
98 return lines
99
100 def write(self, vals):
101 values = vals
102 if values.get('date_planned'):
103 new_date = fields.Datetime.to_datetime(values['date_planned'])
104 self.filtered(lambda l: not l.display_type)._update_move_date_deadline(new_date)
105 lines = self.filtered(lambda l: l.order_id.state == 'purchase'
106 and not l.display_type)
107
108 previous_product_uom_qty = {line.id: line.product_uom_qty for line in lines}
109 previous_product_qty = {line.id: line.product_qty for line in lines}
110 result = super().write(values)
111 if 'price_unit' in values:
112 for line in lines:
113 # Avoid updating kit components' stock.move
114 moves = line.move_ids.filtered(lambda s: s.state not in ('cancel', 'done') and s.product_id == line.product_id)
115 moves.write({'price_unit': line._get_stock_move_price_unit()})
116 if 'product_qty' in values:
117 lines = lines.filtered(lambda l: l.product_uom_id.compare(previous_product_qty[l.id], l.product_qty) != 0)
118 lines.with_context(previous_product_qty=previous_product_uom_qty)._create_or_update_picking()
119 valuation_trigger = ['price_unit', 'product_qty', 'product_uom']
120 if any(field in valuation_trigger for field in values):
121 self.move_ids.filtered(lambda m: m.is_valued)._set_value()
122 return result
123
124 def action_product_forecast_report(self):
125 self.ensure_one()
126 action = self.product_id.action_product_forecast_report()
127 action['context'] = {
128 'active_id': self.product_id.id,
129 'active_model': 'product.product',
130 'move_to_match_ids': self.move_ids.filtered(lambda m: m.product_id == self.product_id).ids,
131 'purchase_line_to_match_id': self.id,
132 }
133 warehouse = self.order_id.picking_type_id.warehouse_id
134 if warehouse:
135 action['context']['warehouse_id'] = warehouse.id
136 return action
137
138 def unlink(self):
139 self.move_ids._action_cancel()
140
141 # Unlink move_dests that have other created_purchase_line_ids instead of cancelling them
142 for line in self:
143 moves_to_unlink = line.move_dest_ids.filtered(lambda m: len(m.created_purchase_line_ids.ids) > 1)
144 if moves_to_unlink:
145 moves_to_unlink.created_purchase_line_ids = [Command.unlink(line.id)]
146
147 ppg_cancel_lines = self.filtered(lambda line: line.propagate_cancel)
148 ppg_cancel_lines.move_dest_ids._action_cancel()
149
150 not_ppg_cancel_lines = self.filtered(lambda line: not line.propagate_cancel)
151 not_ppg_cancel_lines.move_dest_ids.write({'procure_method': 'make_to_stock'})
152 not_ppg_cancel_lines.move_dest_ids._recompute_state()
153
154 return super().unlink()
155
156 # --------------------------------------------------
157 # Business methods
158 # --------------------------------------------------
159
160 def _update_move_date_deadline(self, new_date):
161 """ Updates corresponding move picking line deadline dates that are not yet completed. """
162 moves_to_update = self.move_ids.filtered(lambda m: m.state not in ('done', 'cancel'))
163 if not moves_to_update:
164 moves_to_update = self.move_dest_ids.filtered(lambda m: m.state not in ('done', 'cancel'))
165 for move in moves_to_update:
166 move.date_deadline = new_date
167
168 def _create_or_update_picking(self):
169 for line in self:
170 if line.product_id and line.product_id.type == 'consu':
171 rounding = line.product_uom_id.rounding
172 if float_compare(line.product_qty, line.qty_invoiced, precision_rounding=rounding) < 0 and line.invoice_lines:
173 # If the quantity is now below the invoiced quantity, create an activity on the vendor bill
174 # inviting the user to create a refund.
175 line.invoice_lines[0].move_id.activity_schedule(
176 'mail.mail_activity_data_warning',
177 note=_('The quantities on your purchase order indicate less than billed. You should ask for a refund.'),
178 user_id=self.env.uid,
179 )
180
181 # If the user increased quantity of existing line or created a new line
182 # Give priority to the pickings related to the line
183 moves_to_assign = line.order_id.picking_ids.move_ids.filtered(lambda m: not m.purchase_line_id and line.product_id == m.product_id)
184 moves_to_assign.purchase_line_id = line.id
185 line_pickings = line.move_ids.picking_id.filtered(lambda p: p.state not in ('done', 'cancel') and p.location_dest_id.usage in ('internal', 'transit', 'customer'))
186 if line_pickings:
187 picking = line_pickings[0]
188 else:
189 pickings = line.order_id.picking_ids.filtered(lambda x: x.state not in ('done', 'cancel') and x.location_dest_id.usage in ('internal', 'transit', 'customer'))
190 picking = pickings and pickings[0] or False
191 if not picking:
192 if not line.product_qty > line.qty_received:
193 continue
194 res = line.order_id._prepare_picking()
195 picking = self.env['stock.picking'].create(res)
196
197 moves = line._create_stock_moves(picking)
198 moves._action_confirm()._action_assign()
199
200 def _get_move_dests_initial_demand(self, move_dests):
201 return self.product_id.uom_id._compute_quantity(
202 sum(move_dests.filtered(lambda m: m.state != 'cancel' and m.location_dest_id.usage != 'supplier').mapped('product_qty')),
203 self.product_uom_id, rounding_method='HALF-UP')
204
205 def _prepare_stock_moves(self, picking):
206 """ Prepare the stock moves data for one order line. This function returns a list of
207 dictionary ready to be used in stock.move's create()
208 """
209 self.ensure_one()
210 res = []
211 if self.product_id.type != 'consu':
212 return res
213
214 price_unit = self._get_stock_move_price_unit()
215 qty = self._get_qty_procurement()
216
217 move_dests = self.move_dest_ids or self.move_ids.move_dest_ids
218 move_dests = move_dests.filtered(lambda m: m.state != 'cancel' and not m._is_purchase_return())
219
220 if not move_dests:
221 qty_to_attach = 0
222 qty_to_push = self.product_qty - qty
223 else:
224 move_dests_initial_demand = self._get_move_dests_initial_demand(move_dests)
225 qty_to_attach = move_dests_initial_demand - qty
226 qty_to_push = self.product_qty - move_dests_initial_demand
227
228 if self.product_uom_id.compare(qty_to_attach, 0.0) > 0:
229 product_uom_qty, product_uom = self.product_uom_id._adjust_uom_quantities(qty_to_attach, self.product_id.uom_id)
230 res.append(self._prepare_stock_move_vals(picking, price_unit, product_uom_qty, product_uom))
231 if not self.product_uom_id.is_zero(qty_to_push):
232 product_uom_qty, product_uom = self.product_uom_id._adjust_uom_quantities(qty_to_push, self.product_id.uom_id)
233 extra_move_vals = self._prepare_stock_move_vals(picking, price_unit, product_uom_qty, product_uom)
234 extra_move_vals['move_dest_ids'] = False # don't attach
235 res.append(extra_move_vals)
236 return res
237
238 def _get_stock_move_price_unit(self):
239 self.ensure_one()
240 order = self.order_id
241 price_unit = self.price_unit_discounted
242 price_unit_prec = self.env['decimal.precision'].precision_get('Product Price')
243 if self.tax_ids:
244 qty = self.product_qty or 1
245 price_unit = self.tax_ids.compute_all(
246 price_unit,
247 currency=self.order_id.currency_id,
248 quantity=qty,
249 product=self.product_id,
250 partner=self.order_id.partner_id,
251 rounding_method="round_globally",
252 )['total_void']
253 price_unit = price_unit / qty
254 if self.product_uom_id.id != self.product_id.uom_id.id:
255 price_unit /= self.product_uom_id.factor
256 price_unit *= self.product_id.uom_id.factor
257 if order.currency_id != order.company_id.currency_id:
258 conversion_date = self.env.context.get('conversion_date', self.date_order) or fields.Date.today()
259 price_unit = order.currency_id._convert(
260 price_unit, order.company_id.currency_id, self.company_id, conversion_date, round=False)
261 return float_round(price_unit, precision_digits=price_unit_prec)
262
263 def _get_qty_procurement(self):
264 self.ensure_one()
265 qty = 0.0
266 outgoing_moves, incoming_moves = self._get_outgoing_incoming_moves()
267 for move in outgoing_moves:
268 qty_to_compute = move.quantity if move.state == 'done' else move.product_uom_qty
269 qty -= move.product_uom._compute_quantity(qty_to_compute, self.product_uom_id, rounding_method='HALF-UP')
270 for move in incoming_moves:
271 qty_to_compute = move.quantity if move.state == 'done' else move.product_uom_qty
272 qty += move.product_uom._compute_quantity(qty_to_compute, self.product_uom_id, rounding_method='HALF-UP')
273 return qty
274
275 def _check_orderpoint_picking_type(self):
276 warehouse_loc = self.order_id.picking_type_id.warehouse_id.view_location_id
277 dest_loc = self.move_dest_ids.location_id or self.orderpoint_id.location_id
278 if warehouse_loc and dest_loc and dest_loc.warehouse_id and not warehouse_loc.parent_path in dest_loc[0].parent_path:
279 raise UserError(_('The warehouse of operation type (%(operation_type)s) is inconsistent with location (%(location)s) of reordering rule (%(reordering_rule)s) for product %(product)s. Change the operation type or cancel the request for quotation.',
280 product=self.product_id.display_name, operation_type=self.order_id.picking_type_id.display_name, location=self.orderpoint_id.location_id.display_name, reordering_rule=self.orderpoint_id.display_name))
281
282 def _prepare_stock_move_vals(self, picking, price_unit, product_uom_qty, product_uom):
283 self.ensure_one()
284 self._check_orderpoint_picking_type()
285 product = self.product_id.with_context(lang=self.order_id.dest_address_id.lang or self.env.user.lang)
286 location_dest = self.env['stock.location'].browse(self.order_id._get_destination_location())
287 location_final = self.location_final_id or self.order_id._get_final_location_record()
288 if location_final and location_final._child_of(location_dest):
289 location_dest = location_final
290 date_planned = self.date_planned or self.order_id.date_planned
291 return {
292 'product_id': self.product_id.id,
293 'date': date_planned,
294 'date_deadline': date_planned,
295 'location_id': self.order_id.partner_id.property_stock_supplier.id,
296 'location_dest_id': location_dest.id,
297 'location_final_id': location_final.id,
298 'picking_id': picking.id,
299 'partner_id': self.order_id.dest_address_id.id,
300 'move_dest_ids': [(4, x) for x in self.move_dest_ids.ids],
301 'state': 'draft',
302 'purchase_line_id': self.id,
303 'company_id': self.order_id.company_id.id,
304 'price_unit': price_unit,
305 'picking_type_id': self.order_id.picking_type_id.id,
306 'reference_ids': [Command.set(self.order_id.reference_ids.ids)],
307 'origin': self.order_id.name,
308 'propagate_cancel': self.propagate_cancel,
309 'warehouse_id': self.order_id.picking_type_id.warehouse_id.id,
310 'product_uom_qty': product_uom_qty,
311 'product_uom': product_uom.id,
312 'sequence': self.sequence,
313 }
314
315 def _prepare_account_move_line(self, move=False):
316 res = super()._prepare_account_move_line(move=move)
317 if 'balance' not in res:
318 total_wo_tax = self.tax_ids.with_context(round=False, round_base=False).compute_all(
319 self.price_unit_discounted,
320 currency=self.order_id.currency_id,
321 quantity=self.qty_to_invoice,
322 product=self.product_id
323 )['total_excluded']
324 res['balance'] = self.currency_id._convert(
325 total_wo_tax,
326 self.company_id.currency_id,
327 round=False,
328 )
329 return res
330
331 @api.model
332 def _prepare_purchase_order_line_from_procurement(self, product_id, product_qty, product_uom, location_dest_id, name, origin, company_id, values, po):
333 line_description = ''
334 if values.get('product_description_variants'):
335 line_description = values['product_description_variants']
336 supplier = values.get('supplier')
337 if not values.get('force_uom') and supplier.product_uom_id != product_uom:
338 product_qty = product_uom._compute_quantity(product_qty, supplier.product_uom_id)
339 product_uom = supplier.product_uom_id
340 res = self.with_context(procurement_values=values)._prepare_purchase_order_line(product_id, product_qty, product_uom, company_id, supplier.partner_id, po)
341 # We need to keep the vendor name set in _prepare_purchase_order_line. To avoid redundancy
342 # in the line name, we add the line_description only if different from the product name.
343 # This way, we shoud not lose any valuable information.
344 if line_description and product_id.name != line_description:
345 res['name'] = (res['name'] + '\n' + line_description).strip()
346 res['date_planned'] = values.get('date_planned')
347 # The date must be day before or equal at the supplier target day
348 if po.partner_id.group_rfq == 'week' and po.partner_id.group_on != 'default':
349 delta_days = (7 + int(po.partner_id.group_on) - res['date_planned'].isoweekday()) % 7
350 res['date_planned'] = fields.Datetime.to_datetime(res['date_planned']) + relativedelta(days=delta_days)
351 if not po.date_planned or po.date_planned >= res['date_planned']:
352 # date_order was computed based on procurement date_planned. If the PO date_planned is
353 # shifted, we also need to shift the date_order.
354 po.date_order = fields.Datetime.to_datetime(po.date_order) + relativedelta(days=delta_days)
355 res['move_dest_ids'] = [(4, x.id) for x in values.get('move_dest_ids', [])]
356 res['location_final_id'] = location_dest_id.id
357 res['orderpoint_id'] = values.get('orderpoint_id', False) and values.get('orderpoint_id').id
358 res['propagate_cancel'] = values.get('propagate_cancel')
359 res['product_description_variants'] = values.get('product_description_variants')
360 res['product_no_variant_attribute_value_ids'] = values.get('never_product_template_attribute_value_ids')
361 return res
362
363 def _create_stock_moves(self, picking):
364 values = []
365 for line in self.filtered(lambda l: not l.display_type):
366 for val in line._prepare_stock_moves(picking):
367 values.append(val)
368
369 return self.env['stock.move'].create(values)
370
371 def _find_candidate(self, product_id, product_qty, product_uom, location_id, name, origin, company_id, values):
372 """ Return the record in self where the procument with values passed as
373 args can be merged. If it returns an empty record then a new line will
374 be created.
375 """
376 description_picking = ''
377 if values.get('product_description_variants'):
378 description_picking = values['product_description_variants']
379 lines = self.filtered(
380 lambda l: l.propagate_cancel == values['propagate_cancel']
381 and (l.orderpoint_id in [values['orderpoint_id'], False] if values['orderpoint_id'] and not values['move_dest_ids'] else True)
382 and (l.product_uom_id == product_uom if values.get('force_uom') else True)
383 )
384
385 # In case 'product_description_variants' is in the values, we also filter on the PO line
386 # name. This way, we can merge lines with the same description. To do so, we need the
387 # product name in the context of the PO partner.
388 if lines and values.get('product_description_variants'):
389 partner = self.mapped('order_id.partner_id')[:1]
390 product_lang = product_id.with_context(
391 lang=partner.lang,
392 partner_id=partner.id,
393 )
394 name = product_lang.display_name
395 if product_lang.description_purchase:
396 name += '\n' + product_lang.description_purchase
397 lines = lines.filtered(lambda l: (l.name == name + '\n' + description_picking) or (values.get('product_description_variants') in (product_lang.name, product_id.with_user(SUPERUSER_ID).name) and l.name == name))
398 return lines and lines.sorted(lambda l: l.orderpoint_id)[0] or self.env['purchase.order.line']
399
400 def _get_outgoing_incoming_moves(self):
401 outgoing_moves = self.env['stock.move']
402 incoming_moves = self.env['stock.move']
403
404 for move in self.move_ids.filtered(lambda r: r.state != 'cancel' and r.location_dest_usage != 'inventory' and self.product_id == r.product_id):
405 if move._is_purchase_return() and (move.to_refund or not move.origin_returned_move_id):
406 outgoing_moves |= move
407 elif move.location_dest_id.usage != "supplier":
408 if not move.origin_returned_move_id or (move.origin_returned_move_id and move.to_refund):
409 incoming_moves |= move
410
411 return outgoing_moves, incoming_moves
412
413 def _update_date_planned(self, updated_date):
414 move_to_update = self.move_ids.filtered(lambda m: m.state not in ['done', 'cancel'])
415 if not self.move_ids or move_to_update: # Only change the date if there is no move done or none
416 super()._update_date_planned(updated_date)
417 if move_to_update:
418 self._update_move_date_deadline(updated_date)
419
420 @api.model
421 def _update_qty_received_method(self):
422 """Update qty_received_method for old PO before install this module."""
423 self.search(['!', ('state', '=', 'purchase')])._compute_qty_received_method()
424
425 def _merge_po_line(self, rfq_line):
426 super()._merge_po_line(rfq_line)
427 self.move_dest_ids += rfq_line.move_dest_ids