Debian Codegraph @

addons/stock_account/models/stock_move.py

raw symbols SCIP
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 from collections import defaultdict
4
5 from odoo import api, fields, models, _, Command
6 from odoo.fields import Domain
7 from odoo.tools import OrderedSet
8 from odoo.exceptions import UserError
9
10 VALUATION_DICT = {
11 'value': 0,
12 'quantity': 0,
13 'description': False,
14 }
15
16
17 class StockMove(models.Model):
18 _inherit = "stock.move"
19
20 to_refund = fields.Boolean(
21 "Update quantities on SO/PO", copy=True, default=True,
22 help='Trigger a decrease of the delivered/received quantity in the associated Sale Order/Purchase Order')
23 company_currency_id = fields.Many2one('res.currency', related='company_id.currency_id', string='Company Currency', readonly=True)
24 value = fields.Monetary(
25 "Value", currency_field='company_currency_id',
26 help="The current value of the move. It's zero if the move is not valued.")
27 value_justification = fields.Text(
28 "Value Description", compute="_compute_value_justification")
29 value_computed_justification = fields.Text(
30 "Computed Value Description", compute="_compute_value_justification")
31 # Useful for testing and custom valuation
32 value_manual = fields.Monetary(
33 "Manual Value", currency_field='company_currency_id',
34 compute="_compute_value_manual", inverse="_inverse_value_manual")
35 standard_price = fields.Float(related='product_id.standard_price', string='Standard Price')
36
37 # To remove and only use value
38 price_unit = fields.Float("Price Unit")
39 is_in = fields.Boolean(string='Is Incoming (valued)', compute='_compute_is_in', store=True)
40 is_out = fields.Boolean(string='Is Outgoing (valued)', compute='_compute_is_out', store=True)
41 is_dropship = fields.Boolean(string='Is Dropship', compute='_compute_is_dropship', store=True)
42 is_valued = fields.Boolean(string='Is Valued', compute='_compute_is_valued')
43
44 remaining_qty = fields.Float(
45 string='Remaining Quantity', compute='_compute_remaining_qty', search='search_remaining_qty')
46 remaining_value = fields.Monetary(
47 currency_field='company_currency_id',
48 string='Remaining Value', compute='_compute_remaining_value')
49
50 analytic_account_line_ids = fields.Many2many('account.analytic.line', copy=False)
51 account_move_id = fields.Many2one('account.move', 'stock_move_id', copy=False, index="btree_not_null")
52
53 def search_remaining_qty(self, operator, value):
54 if operator != '=' or not isinstance(value, bool) or value is not True:
55 raise UserError(_("Only is set (= True) is supported in search for remaining_qty."))
56 products = 'default_product_id' in self.env.context and self.env['product.product'].browse(self.env.context['default_product_id']) or self.env['product.product']
57 if not products:
58 products = self.env['product.product'].search([('is_storable', '=', True), ('qty_available', '>', 0)])
59 move_ids = []
60 for qty_by_move in products._get_remaining_moves().values():
61 for move in qty_by_move:
62 move_ids.append(move.id)
63 return [('id', 'in', move_ids)]
64
65 @api.depends('state', 'move_line_ids')
66 def _compute_is_in(self):
67 for move in self:
68 if move.state != 'done':
69 move.is_in = False
70 continue
71 move.is_in = move._is_in()
72
73 @api.depends('state', 'move_line_ids')
74 def _compute_is_out(self):
75 for move in self:
76 if move.state != 'done':
77 move.is_out = False
78 continue
79 move.is_out = move._is_out()
80
81 @api.depends('state')
82 def _compute_is_dropship(self):
83 for move in self:
84 if move.state != 'done':
85 move.is_dropship = False
86 continue
87 move.is_dropship = move._is_dropshipped() or move._is_dropshipped_returned()
88
89 @api.depends('state', 'move_line_ids')
90 def _compute_is_valued(self):
91 for move in self:
92 move.is_valued = move.is_in or move.is_out
93
94 def _compute_value_manual(self):
95 for move in self:
96 move.value_manual = move.value
97
98 def _compute_value_justification(self):
99 self.value_justification = False
100 self.value_computed_justification = False
101 for move in self:
102 if not move.is_in:
103 continue
104 move.value_justification = move._get_value_data()['description']
105 computed_value_data = move._get_value_data(ignore_manual_update=True)
106 if computed_value_data['description'] == move.value_justification:
107 move.value_computed_justification = False
108 else:
109 value = move.company_currency_id.format(computed_value_data['value'])
110 move.value_computed_justification = self.env._(
111 'Computed value: %(value)s\n%(description)s',
112 value=value, description=computed_value_data['description'])
113
114 @api.depends('quantity', 'product_id.stock_move_ids.value')
115 def _compute_remaining_qty(self):
116 products = self.product_id
117 remaining_by_product = products._get_remaining_moves()
118
119 for move in self:
120 move.remaining_qty = remaining_by_product.get(move.product_id, {}).get(move, 0)
121
122 @api.depends('value', 'remaining_qty')
123 def _compute_remaining_value(self):
124 for move in self:
125 if not move.is_in:
126 move.remaining_value = 0
127 continue
128 ratio = move.remaining_qty / move.quantity if move.quantity else 0
129 if move.product_id.cost_method == 'fifo':
130 move.remaining_value = ratio * move.value if ratio else 0
131 else:
132 move.remaining_value = move.remaining_qty * move.with_company(move.company_id).standard_price
133
134 def _inverse_picked(self):
135 super()._inverse_picked()
136 self.sudo()._create_analytic_move()
137
138 def _inverse_value_manual(self):
139 for move in self:
140 if move.value_manual == move.value:
141 continue
142 self.env['product.value'].create({
143 'move_id': move.id,
144 'value': move.value_manual,
145 'company_id': move.company_id.id,
146 })
147
148 def action_adjust_valuation(self):
149 if len(self) != 1:
150 raise UserError(_("You can only adjust valuation for one move at a time."))
151 action = self.env['ir.actions.act_window']._for_xml_id("stock_account.product_value_action")
152 product = self.product_id if len(self.product_id) == 1 else False
153 if product:
154 action['name'] = _('Adjust Valuation: %(product)s', product=product.display_name)
155 action['target'] = 'new'
156 action['context'] = {
157 'default_move_id': self.id,
158 }
159 return action
160
161 def _action_done(self, cancel_backorder=False):
162 # Use _is_out() instead of is_out since the move is not done
163 # It's called before action_done since we need the current fifo
164 # stack. Limitation when validating at same time out and in.s
165 moves_out = self.filtered(lambda m: m._is_out())
166 moves_out._set_value()
167 moves = super()._action_done(cancel_backorder=cancel_backorder)
168 moves_in = moves.filtered(lambda m: m.is_in or m.is_dropship)
169 moves_in._set_value()
170 moves._create_account_move()
171 # Update standard price on outgoing fifo products
172 moves_out.product_id.filtered(lambda p: p.cost_method == 'fifo')._update_standard_price()
173 (moves_in | moves_out).sudo()._create_analytic_move()
174 return moves
175
176 def _create_account_move(self):
177 """ Create account move for specific location or analytic."""
178 aml_vals_list = []
179 move_to_link = set()
180 for move in self:
181 if move._should_create_account_move():
182 aml_vals_list += move._get_account_move_line_vals()
183 move_to_link.add(move.id)
184 if not aml_vals_list:
185 return self.env['account.move']
186 account_move = self.env['account.move'].sudo().create({
187 'journal_id': self.company_id.account_stock_journal_id.id,
188 'line_ids': [Command.create(aml_vals) for aml_vals in aml_vals_list],
189 'date': self.env.context.get('force_period_date') or fields.Date.context_today(self),
190 })
191 self.env['stock.move'].browse(move_to_link).account_move_id = account_move.id
192 account_move._post()
193 return account_move
194
195 def _create_analytic_move(self):
196 for move in self:
197 analytic_line_vals = move._prepare_analytic_lines()
198 if analytic_line_vals:
199 move.analytic_account_line_ids += self.env['account.analytic.line'].sudo().create(analytic_line_vals)
200
201 def _get_account_move_line_vals(self):
202 if self.location_id.valuation_account_id:
203 debit_acc = self.product_id._get_product_accounts()['stock_valuation']
204 credit_acc = self.location_id.valuation_account_id
205 else:
206 debit_acc = self.location_dest_id.valuation_account_id
207 credit_acc = self.product_id._get_product_accounts()['stock_valuation']
208 value = self._get_aml_value()
209 return [{
210 'account_id': credit_acc.id,
211 'name': self.reference + ' - ' + self.product_id.name,
212 'debit': 0,
213 'credit': value,
214 'product_id': self.product_id.id,
215 }, {
216 'account_id': debit_acc.id,
217 'name': self.reference + ' - ' + self.product_id.name,
218 'debit': value,
219 'credit': 0,
220 'product_id': self.product_id.id,
221 }]
222
223 def _get_aml_value(self):
224 self.ensure_one()
225 return self.value
226
227 def _get_analytic_distribution(self):
228 return {}
229
230 def _get_price_unit(self):
231 """ Returns the unit price to value this stock move """
232 if len(self.product_id) > 1:
233 return 0
234 total_value = sum(self.mapped('value'))
235 total_qty = sum(m._get_valued_qty() for m in self)
236 return total_value / total_qty if total_qty else 0
237
238 def _get_cogs_price_unit(self, quantity=0):
239 """ Returns the COGS unit price to value this stock move
240 quantity should be given in product uom """
241
242 total_qty = sum(m._get_valued_qty() for m in self)
243 if not total_qty:
244 return 0
245 return sum(self.mapped('value')) / total_qty if self.product_id.cost_method == 'fifo' else self.product_id.standard_price
246
247 @api.model
248 def _get_valued_types(self):
249 """Returns a list of `valued_type` as strings. During `action_done`, we'll call
250 `_is_[valued_type]'. If the result of this method is truthy, we'll consider the move to be
251 valued.
252
253 :returns: a list of `valued_type`
254 :rtype: list
255 """
256 return ['in', 'out', 'dropshipped', 'dropshipped_returned']
257
258 def _set_value(self, correction_quantity=None):
259 """Set the value of the move.
260
261 :param correction_quantity: if set, it means that the quantity of the move has been
262 changed by this amount (can be positive or negative). In that case, we just update
263 the value of the move based on the ratio of extra_quantity / quantity. It only applies
264 on out_move since their value is computed during action_done, and it's used to get a
265 more accurate value for COGS. In case of in move correction, you have to call _set_value
266 without arguments.
267 """
268 products_to_recompute = set()
269 lots_to_recompute = set()
270 fifo_qty_processed = defaultdict(float)
271
272 for move in self:
273 # Incoming moves
274 if move.is_dropship or move.is_in:
275 products_to_recompute.add(move.product_id.id)
276 if move.product_id.lot_valuated:
277 lots_to_recompute.update(move.move_line_ids.lot_id.ids)
278 if move.is_in:
279 move.value = move.sudo()._get_value()
280 continue
281 # Outgoing moves
282 if not move._is_out():
283 continue
284 if correction_quantity:
285 previous_qty = move.quantity - correction_quantity
286 ratio = correction_quantity / previous_qty if previous_qty else 0
287 move.value += ratio * move.value
288 continue
289 if move.product_id.lot_valuated:
290 value = 0.0
291 for move_line in move.move_line_ids:
292 if move_line.lot_id:
293 value += move_line.lot_id.standard_price * move_line.quantity_product_uom
294 else:
295 value += move.product_id.standard_price * move_line.quantity_product_uom
296 move.value = value
297 continue
298
299 if move.product_id.cost_method == 'fifo':
300 valued_qty = move._get_valued_qty()
301 move.value = move.product_id.with_context(fifo_qty_already_processed=fifo_qty_processed[move.product_id])._run_fifo(valued_qty)
302 fifo_qty_processed[move.product_id] += valued_qty
303 else:
304 move.value = move.product_id.standard_price * move._get_valued_qty()
305
306 # Recompute the standard price
307 self.env['product.product'].browse(products_to_recompute)._update_standard_price()
308 self.env['stock.lot'].browse(lots_to_recompute)._update_standard_price()
309
310 def _get_value(self, forced_std_price=False, at_date=False, ignore_manual_update=False):
311 return self._get_value_data(forced_std_price, at_date, ignore_manual_update)['value']
312
313 def _get_value_data(
314 self,
315 forced_std_price=False,
316 at_date=False,
317 ignore_manual_update=False,
318 add_extra_value=True,
319 ):
320 """Returns the value and the quantity valued on the move
321 In priority order:
322 - Take value from accounting documents (invoices, bills)
323 - Take value from quotations + landed costs
324 - Take value from product cost
325
326 Forced standard price is useful when we have to get the value
327 of a move in the past with the standard price at that time.
328 """
329 # TODO: Make multi
330 self.ensure_one()
331 # It probably needs a priority order:
332 # 1. take from Invoice/Bills
333 # 2. from SO/PO lines
334 # 3. standard_price
335
336 valued_qty = remaining_qty = self._get_valued_qty()
337 value = 0
338 descriptions = []
339
340 if not ignore_manual_update:
341 manual_data = self._get_manual_value(
342 remaining_qty, at_date)
343 # In case of manual update we will skip extra cost
344 if manual_data['quantity']:
345 add_extra_value = False
346 value += manual_data['value']
347 remaining_qty -= manual_data['quantity']
348 if manual_data.get('description'):
349 descriptions.append(manual_data['description'])
350
351 # 1. take from Invoice/Bills
352 if remaining_qty:
353 account_data = self._get_value_from_account_move(remaining_qty, at_date)
354 value += account_data['value']
355 remaining_qty -= account_data['quantity']
356 if account_data.get('description'):
357 descriptions.append(account_data['description'])
358
359 if remaining_qty:
360 production_data = self._get_value_from_production(remaining_qty, at_date)
361 value += production_data["value"]
362 remaining_qty -= production_data["quantity"]
363 if production_data.get("description"):
364 descriptions.append(production_data["description"])
365
366 # 2. from SO/PO lines
367 if remaining_qty:
368 quotation_data = self._get_value_from_quotation(remaining_qty, at_date)
369 value += quotation_data['value']
370 remaining_qty -= quotation_data['quantity']
371 if quotation_data.get('description'):
372 descriptions.append(quotation_data['description'])
373
374 # 3. from returns
375 if remaining_qty:
376 return_data = self._get_value_from_returns(remaining_qty, at_date)
377 value += return_data['value']
378 remaining_qty -= return_data['quantity']
379 if return_data.get('description'):
380 descriptions.append(return_data['description'])
381
382 # 4. standard_price
383 if remaining_qty:
384 std_price_data = self._get_value_from_std_price(remaining_qty, forced_std_price, at_date)
385 value += std_price_data['value']
386 descriptions.append(std_price_data.get('description'))
387
388 if add_extra_value:
389 extra_data = self._get_value_from_extra(valued_qty, at_date)
390 value += extra_data['value']
391 if extra_data.get('description'):
392 descriptions.append(extra_data['description'])
393
394 return {
395 'value': value,
396 'quantity': valued_qty,
397 'description': '\n'.join(descriptions),
398 }
399
400 def _get_valued_qty(self, lot=None):
401 self.ensure_one()
402 if self._is_in():
403 return sum(self._get_in_move_lines(lot).mapped('quantity_product_uom'))
404 if self._is_out():
405 return sum(self._get_out_move_lines(lot).mapped('quantity_product_uom'))
406 if self.is_dropship:
407 if lot:
408 return sum(self.move_line_ids.filtered(lambda ml: ml.lot_id == lot).mapped('quantity_product_uom'))
409 return self.product_uom._compute_quantity(self.quantity, self.product_id.uom_id)
410 return 0
411
412 def _get_manual_value(self, quantity, at_date=None):
413 valuation_data = dict(VALUATION_DICT)
414 domain = Domain([('move_id', '=', self.id)])
415 if at_date:
416 domain &= Domain([('date', '<=', at_date)])
417 manual_value = self.env['product.value'].sudo().search(domain, order="date desc, id desc", limit=1)
418 if manual_value:
419 valuation_data['value'] = manual_value.value
420 valuation_data['quantity'] = quantity
421 description = _("Adjusted on %(date)s by %(user)s",
422 date=manual_value.date,
423 user=manual_value.user_id.name,
424 )
425 if manual_value.description:
426 description += "\n" + manual_value.description
427 valuation_data['description'] = description
428 return valuation_data
429
430 def _get_value_from_account_move(self, quantity, at_date=None):
431 return dict(VALUATION_DICT)
432
433 def _get_value_from_production(self, quantity, at_date=None):
434 return dict(VALUATION_DICT)
435
436 def _get_value_from_quotation(self, quantity, at_date=None):
437 return dict(VALUATION_DICT)
438
439 def _get_value_from_returns(self, quantity, at_date=None):
440 if self.origin_returned_move_id and self.origin_returned_move_id.is_out:
441 origin_move = self.origin_returned_move_id
442 return {
443 'value': origin_move.value * quantity / origin_move._get_valued_qty(),
444 'quantity': quantity,
445 'description': _('Value based on original move %(reference)s', reference=origin_move.reference),
446 }
447 return dict(VALUATION_DICT)
448
449 def _get_value_from_std_price(self, quantity, std_price=False, at_date=None):
450 std_price = std_price if std_price else self.product_id.standard_price
451 if at_date and self.product_id.cost_method == 'standard':
452 std_price = std_price or self.product_id._get_standard_price_at_date(at_date)
453 # If multiple lots keep standard_price from product
454 elif self.product_id.lot_valuated and len(self.lot_ids) == 1:
455 std_price = self.lot_ids.standard_price
456 return {
457 'value': std_price * quantity,
458 'quantity': quantity,
459 'description': self.env._("%(quantity)s %(uom)s at product's cost",
460 quantity=quantity,
461 uom=self.product_id.uom_id.name,
462 ),
463 }
464
465 def _get_value_from_extra(self, quantity, at_date=None):
466 return dict(VALUATION_DICT)
467
468 def _get_move_directions(self):
469 move_in_ids = set()
470 move_out_ids = set()
471 locations_should_be_valued = (self.move_line_ids.location_id | self.move_line_ids.location_dest_id).filtered(lambda l: l._should_be_valued())
472 for record in self:
473 for move_line in record.move_line_ids:
474 if move_line._should_exclude_for_valuation() or not move_line.picked:
475 continue
476 if move_line.location_id not in locations_should_be_valued and move_line.location_dest_id in locations_should_be_valued:
477 move_in_ids.add(record.id)
478 if move_line.location_id in locations_should_be_valued and move_line.location_dest_id not in locations_should_be_valued:
479 move_out_ids.add(record.id)
480
481 move_directions = defaultdict(set)
482 for record in self:
483 if record.id in move_in_ids and not record._is_dropshipped_returned():
484 move_directions[record.id].add('in')
485
486 if record.id in move_out_ids and not record._is_dropshipped():
487 move_directions[record.id].add('out')
488
489 return move_directions
490
491 def _get_in_move_lines(self, lot=None):
492 """ Returns the `stock.move.line` records of `self` considered as incoming. It is done thanks
493 to the `_should_be_valued` method of their source and destionation location as well as their
494 owner.
495
496 :returns: a subset of `self` containing the incoming records
497 :rtype: recordset
498 """
499 res = OrderedSet()
500 for move_line in self.move_line_ids:
501 if lot and move_line.lot_id != lot:
502 continue
503 if not move_line.picked:
504 continue
505 if move_line._should_exclude_for_valuation():
506 continue
507 if not move_line.location_id._should_be_valued() and move_line.location_dest_id._should_be_valued():
508 res.add(move_line.id)
509 return self.env['stock.move.line'].browse(res)
510
511 def _is_in(self):
512 """Check if the move should be considered as entering the company so that the cost method
513 will be able to apply the correct logic.
514
515 :returns: True if the move is entering the company else False
516 :rtype: bool
517 """
518 self.ensure_one()
519 return self._get_in_move_lines() and not self._is_dropshipped_returned()
520
521 def _get_out_move_lines(self, lot=None):
522 """ Returns the `stock.move.line` records of `self` considered as outgoing. It is done thanks
523 to the `_should_be_valued` method of their source and destionation location as well as their
524 owner.
525
526 :returns: a subset of `self` containing the outgoing records
527 :rtype: recordset
528 """
529 res = self.env['stock.move.line']
530 for move_line in self.move_line_ids:
531 if lot and move_line.lot_id != lot:
532 continue
533 if not move_line.picked:
534 continue
535 if move_line._should_exclude_for_valuation():
536 continue
537 if move_line.location_id._should_be_valued() and not move_line.location_dest_id._should_be_valued():
538 res |= move_line
539 return res
540
541 def _is_out(self):
542 """Check if the move should be considered as leaving the company so that the cost method
543 will be able to apply the correct logic.
544
545 :returns: True if the move is leaving the company else False
546 :rtype: bool
547 """
548 self.ensure_one()
549 return self._get_out_move_lines() and not self._is_dropshipped()
550
551 def _is_dropshipped(self):
552 """Check if the move should be considered as a dropshipping move so that the cost method
553 will be able to apply the correct logic.
554
555 :returns: True if the move is a dropshipping one else False
556 :rtype: bool
557 """
558 self.ensure_one()
559 return (self.location_id.usage == 'supplier' or (self.location_id.usage == 'transit' and not self.location_id.company_id)) \
560 and (self.location_dest_id.usage == 'customer' or (self.location_dest_id.usage == 'transit' and not self.location_dest_id.company_id))
561
562 def _is_dropshipped_returned(self):
563 """Check if the move should be considered as a returned dropshipping move so that the cost
564 method will be able to apply the correct logic.
565
566 :returns: True if the move is a returned dropshipping one else False
567 :rtype: bool
568 """
569 self.ensure_one()
570 return (self.location_id.usage == 'customer' or (self.location_id.usage == 'transit' and not self.location_id.company_id)) \
571 and (self.location_dest_id.usage == 'supplier' or (self.location_dest_id.usage == 'transit' and not self.location_dest_id.company_id))
572
573 def _prepare_analytic_lines(self):
574 self.ensure_one()
575 if not self._get_analytic_distribution() and not self.analytic_account_line_ids:
576 return False
577
578 if self.state in ['cancel', 'draft']:
579 return False
580 amount, unit_amount = 0, 0
581
582 if self.state != 'done':
583 if self.picked:
584 unit_amount = self.product_uom._compute_quantity(
585 self.quantity, self.product_id.uom_id)
586 # Falsy in FIFO but since it's an estimation we don't require exact correct cost. Otherwise
587 # we would have to recompute all the analytic estimation at each out.
588 amount = unit_amount * self.product_id.standard_price
589 else:
590 return False
591 else:
592 amount = self.value
593 unit_amount = self._get_valued_qty()
594
595 if self._is_out():
596 amount = -amount
597
598 if self.analytic_account_line_ids and amount == 0 and unit_amount == 0:
599 self.analytic_account_line_ids.unlink()
600 return False
601
602 return self.env['account.analytic.account']._perform_analytic_distribution(
603 self._get_analytic_distribution(), amount, unit_amount, self.analytic_account_line_ids, self)
604
605 def _prepare_analytic_line_values(self, account_field_values, amount, unit_amount):
606 self.ensure_one()
607 return {
608 'name': self.reference,
609 'amount': amount,
610 **account_field_values,
611 'unit_amount': unit_amount,
612 'product_id': self.product_id.id,
613 'product_uom_id': self.product_id.uom_id.id,
614 'company_id': self.company_id.id,
615 'ref': self._description,
616 'category': 'other',
617 }
618
619 def _should_create_account_move(self):
620 """Determines if an account move should be created for this move.
621 :return: True if an account move should be created, False otherwise.
622 """
623 self.ensure_one()
624 return self.product_id.is_storable and self.is_valued\
625 and (self.location_dest_id.valuation_account_id or self.location_id.valuation_account_id)\
626 and self.product_id.valuation == 'real_time'
627
628 def _should_exclude_for_valuation(self):
629 """Determines if this move should be excluded from valuation based on its partner.
630 :return: True if the move's restrict_partner_id is different from the company's partner (indicating
631 it should be excluded from valuation), False otherwise.
632 """
633 self.ensure_one()
634 return self.restrict_partner_id and self.restrict_partner_id != self.company_id.partner_id
635
636 def _get_related_invoices(self): # To be overridden in purchase and sale_stock
637 """ This method is overrided in both purchase and sale_stock modules to adapt
638 to the way they mix stock moves with invoices.
639 """
640 return self.env['account.move']
641
642 def _is_returned(self, valued_type):
643 self.ensure_one()
644 if valued_type == 'in':
645 return self.location_id and self.location_id.usage == 'customer' # goods returned from customer
646 if valued_type == 'out':
647 return self.location_dest_id and self.location_dest_id.usage == 'supplier'
648 return bool(self.picking_id.return_picking_id)