| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
from collections import defaultdict |
| 5 |
|
| 6 |
from odoo import api, fields, models, tools, _ |
| 7 |
from odoo.exceptions import UserError |
| 8 |
from odoo.tools.float_utils import float_is_zero |
| 9 |
|
| 10 |
|
| 11 |
SPLIT_METHOD = [ |
| 12 |
('equal', 'Equal'), |
| 13 |
('by_quantity', 'By Quantity'), |
| 14 |
('by_current_cost_price', 'By Current Cost'), |
| 15 |
('by_weight', 'By Weight'), |
| 16 |
('by_volume', 'By Volume'), |
| 17 |
] |
| 18 |
|
| 19 |
|
| 20 |
class StockLandedCost(models.Model): |
| 21 |
_name = 'stock.landed.cost' |
| 22 |
_description = 'Stock Landed Cost' |
| 23 |
_inherit = ['mail.thread', 'mail.activity.mixin'] |
| 24 |
_order = 'date desc, id desc' |
| 25 |
|
| 26 |
def _default_account_journal_id(self): |
| 27 |
"""Take the journal configured in the company, else fallback on the stock journal.""" |
| 28 |
ProductCategory = self.env['product.category'] |
| 29 |
return self.env.company.lc_journal_id or ProductCategory._fields['property_stock_journal'].get_company_dependent_fallback(ProductCategory) |
| 30 |
|
| 31 |
name = fields.Char( |
| 32 |
'Name', default=lambda self: _('New'), |
| 33 |
copy=False, readonly=True, tracking=True) |
| 34 |
date = fields.Date( |
| 35 |
'Date', default=fields.Date.context_today, |
| 36 |
copy=False, required=True, tracking=True) |
| 37 |
target_model = fields.Selection( |
| 38 |
[('picking', 'Transfers')], string="Apply On", |
| 39 |
required=True, default='picking', |
| 40 |
copy=False) |
| 41 |
picking_ids = fields.Many2many( |
| 42 |
'stock.picking', string='Transfers', |
| 43 |
copy=False) |
| 44 |
cost_lines = fields.One2many( |
| 45 |
'stock.landed.cost.lines', 'cost_id', 'Cost Lines', |
| 46 |
copy=True) |
| 47 |
valuation_adjustment_lines = fields.One2many( |
| 48 |
'stock.valuation.adjustment.lines', 'cost_id', 'Valuation Adjustments',) |
| 49 |
description = fields.Text( |
| 50 |
'Item Description') |
| 51 |
amount_total = fields.Monetary( |
| 52 |
'Total', compute='_compute_total_amount', |
| 53 |
store=True, tracking=True) |
| 54 |
state = fields.Selection([ |
| 55 |
('draft', 'Draft'), |
| 56 |
('done', 'Posted'), |
| 57 |
('cancel', 'Cancelled')], 'State', default='draft', |
| 58 |
copy=False, readonly=True, tracking=True) |
| 59 |
account_move_id = fields.Many2one( |
| 60 |
'account.move', 'Journal Entry', |
| 61 |
index='btree_not_null', |
| 62 |
copy=False, readonly=True) |
| 63 |
account_journal_id = fields.Many2one( |
| 64 |
'account.journal', 'Account Journal', |
| 65 |
required=True, default=lambda self: self._default_account_journal_id()) |
| 66 |
company_id = fields.Many2one('res.company', string="Company", required=True, default=lambda self: self.env.company) |
| 67 |
vendor_bill_id = fields.Many2one( |
| 68 |
'account.move', 'Vendor Bill', copy=False, domain=[('move_type', '=', 'in_invoice')], index='btree_not_null') |
| 69 |
currency_id = fields.Many2one('res.currency', related='company_id.currency_id') |
| 70 |
|
| 71 |
@api.depends('cost_lines.price_unit') |
| 72 |
def _compute_total_amount(self): |
| 73 |
for cost in self: |
| 74 |
cost.amount_total = sum(line.price_unit for line in cost.cost_lines) |
| 75 |
|
| 76 |
@api.onchange('target_model') |
| 77 |
def _onchange_target_model(self): |
| 78 |
if self.target_model != 'picking': |
| 79 |
self.picking_ids = False |
| 80 |
|
| 81 |
@api.model_create_multi |
| 82 |
def create(self, vals_list): |
| 83 |
for vals in vals_list: |
| 84 |
if vals.get('name', _('New')) == _('New'): |
| 85 |
vals['name'] = self.env['ir.sequence'].next_by_code('stock.landed.cost') |
| 86 |
return super().create(vals_list) |
| 87 |
|
| 88 |
def unlink(self): |
| 89 |
self.button_cancel() |
| 90 |
return super().unlink() |
| 91 |
|
| 92 |
def _track_subtype(self, init_values): |
| 93 |
if 'state' in init_values and self.state == 'done': |
| 94 |
return self.env.ref('stock_landed_costs.mt_stock_landed_cost_open') |
| 95 |
return super()._track_subtype(init_values) |
| 96 |
|
| 97 |
def button_cancel(self): |
| 98 |
if any(cost.state == 'done' for cost in self): |
| 99 |
raise UserError( |
| 100 |
_('Validated landed costs cannot be cancelled, but you could create negative landed costs to reverse them')) |
| 101 |
return self.write({'state': 'cancel'}) |
| 102 |
|
| 103 |
def button_validate(self): |
| 104 |
self._check_can_validate() |
| 105 |
cost_without_adjusment_lines = self.filtered(lambda c: not c.valuation_adjustment_lines) |
| 106 |
if cost_without_adjusment_lines: |
| 107 |
cost_without_adjusment_lines.compute_landed_cost() |
| 108 |
if not self._check_sum(): |
| 109 |
raise UserError(_('Cost and adjustments lines do not match. You should maybe recompute the landed costs.')) |
| 110 |
|
| 111 |
for cost in self: |
| 112 |
cost = cost.with_company(cost.company_id) |
| 113 |
move = self.env['account.move'] |
| 114 |
move_vals = { |
| 115 |
'journal_id': cost.account_journal_id.id, |
| 116 |
'date': cost.date, |
| 117 |
'ref': cost.name, |
| 118 |
'line_ids': [], |
| 119 |
'move_type': 'entry', |
| 120 |
} |
| 121 |
for line in cost.valuation_adjustment_lines.filtered(lambda line: line.move_id): |
| 122 |
product = line.move_id.product_id |
| 123 |
|
| 124 |
if product.valuation != "real_time": |
| 125 |
continue |
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
remaining_qty = line.move_id.remaining_qty |
| 130 |
move_vals['line_ids'] += line._create_accounting_entries(remaining_qty) |
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
cost_vals = {'state': 'done'} |
| 146 |
if move_vals.get("line_ids"): |
| 147 |
move = move.create(move_vals) |
| 148 |
cost_vals.update({'account_move_id': move.id}) |
| 149 |
cost.write(cost_vals) |
| 150 |
if cost.account_move_id: |
| 151 |
move._post() |
| 152 |
cost.valuation_adjustment_lines.move_id._set_value() |
| 153 |
return True |
| 154 |
|
| 155 |
def get_valuation_lines(self): |
| 156 |
self.ensure_one() |
| 157 |
lines = [] |
| 158 |
|
| 159 |
for move in self._get_targeted_move_ids(): |
| 160 |
|
| 161 |
if move.product_id.cost_method not in ('fifo', 'average') or move.state == 'cancel' or not move.quantity: |
| 162 |
continue |
| 163 |
qty = move.product_uom._compute_quantity(move.quantity, move.product_id.uom_id) |
| 164 |
|
| 165 |
vals = { |
| 166 |
'product_id': move.product_id.id, |
| 167 |
'move_id': move.id, |
| 168 |
'quantity': qty, |
| 169 |
'former_cost': move._get_value(), |
| 170 |
'weight': move.product_id.weight * qty, |
| 171 |
'volume': move.product_id.volume * qty |
| 172 |
} |
| 173 |
lines.append(vals) |
| 174 |
|
| 175 |
if not lines: |
| 176 |
target_model_descriptions = dict(self._fields['target_model']._description_selection(self.env)) |
| 177 |
raise UserError(_("You cannot apply landed costs on the chosen %s(s). Landed costs can only be applied for products with FIFO or average costing method.", target_model_descriptions[self.target_model])) |
| 178 |
return lines |
| 179 |
|
| 180 |
def compute_landed_cost(self): |
| 181 |
AdjustementLines = self.env['stock.valuation.adjustment.lines'] |
| 182 |
AdjustementLines.search([('cost_id', 'in', self.ids)]).unlink() |
| 183 |
|
| 184 |
towrite_dict = {} |
| 185 |
for cost in self.filtered(lambda cost: cost._get_targeted_move_ids()): |
| 186 |
cost = cost.with_company(cost.company_id) |
| 187 |
rounding = cost.currency_id.rounding |
| 188 |
total_qty = 0.0 |
| 189 |
total_cost = 0.0 |
| 190 |
total_weight = 0.0 |
| 191 |
total_volume = 0.0 |
| 192 |
total_line = 0.0 |
| 193 |
all_val_line_values = cost.get_valuation_lines() |
| 194 |
for val_line_values in all_val_line_values: |
| 195 |
for cost_line in cost.cost_lines: |
| 196 |
val_line_values.update({'cost_id': cost.id, 'cost_line_id': cost_line.id}) |
| 197 |
self.env['stock.valuation.adjustment.lines'].create(val_line_values) |
| 198 |
total_qty += val_line_values.get('quantity', 0.0) |
| 199 |
total_weight += val_line_values.get('weight', 0.0) |
| 200 |
total_volume += val_line_values.get('volume', 0.0) |
| 201 |
|
| 202 |
former_cost = val_line_values.get('former_cost', 0.0) |
| 203 |
|
| 204 |
total_cost += cost.currency_id.round(former_cost) |
| 205 |
|
| 206 |
total_line += 1 |
| 207 |
|
| 208 |
for line in cost.cost_lines: |
| 209 |
value_split = 0.0 |
| 210 |
for valuation in cost.valuation_adjustment_lines: |
| 211 |
value = 0.0 |
| 212 |
if valuation.cost_line_id and valuation.cost_line_id.id == line.id: |
| 213 |
if line.split_method == 'by_quantity' and total_qty: |
| 214 |
per_unit = (line.price_unit / total_qty) |
| 215 |
value = valuation.quantity * per_unit |
| 216 |
elif line.split_method == 'by_weight' and total_weight: |
| 217 |
per_unit = (line.price_unit / total_weight) |
| 218 |
value = valuation.weight * per_unit |
| 219 |
elif line.split_method == 'by_volume' and total_volume: |
| 220 |
per_unit = (line.price_unit / total_volume) |
| 221 |
value = valuation.volume * per_unit |
| 222 |
elif line.split_method == 'equal': |
| 223 |
value = (line.price_unit / total_line) |
| 224 |
elif line.split_method == 'by_current_cost_price' and total_cost: |
| 225 |
per_unit = (line.price_unit / total_cost) |
| 226 |
value = valuation.former_cost * per_unit |
| 227 |
else: |
| 228 |
value = (line.price_unit / total_line) |
| 229 |
|
| 230 |
if rounding: |
| 231 |
value = tools.float_round(value, precision_rounding=rounding, rounding_method='HALF-UP') |
| 232 |
value_split += value |
| 233 |
|
| 234 |
if valuation.id not in towrite_dict: |
| 235 |
towrite_dict[valuation.id] = value |
| 236 |
else: |
| 237 |
towrite_dict[valuation.id] += value |
| 238 |
rounding_diff = cost.currency_id.round(line.price_unit - value_split) |
| 239 |
if not cost.currency_id.is_zero(rounding_diff): |
| 240 |
towrite_dict[max(towrite_dict.keys())] += rounding_diff |
| 241 |
for key, value in towrite_dict.items(): |
| 242 |
AdjustementLines.browse(key).write({'additional_landed_cost': value}) |
| 243 |
return True |
| 244 |
|
| 245 |
def _get_targeted_move_ids(self): |
| 246 |
return self.picking_ids.move_ids |
| 247 |
|
| 248 |
def _check_can_validate(self): |
| 249 |
if any(cost.state != 'draft' for cost in self): |
| 250 |
raise UserError(_('Only draft landed costs can be validated')) |
| 251 |
for cost in self: |
| 252 |
if not cost._get_targeted_move_ids(): |
| 253 |
target_model_descriptions = dict(self._fields['target_model']._description_selection(self.env)) |
| 254 |
raise UserError(_('Please define %s on which those additional costs should apply.', target_model_descriptions[cost.target_model])) |
| 255 |
|
| 256 |
def _check_sum(self): |
| 257 |
""" Check if each cost line its valuation lines sum to the correct amount |
| 258 |
and if the overall total amount is correct also """ |
| 259 |
for landed_cost in self: |
| 260 |
total_amount = sum(landed_cost.valuation_adjustment_lines.mapped('additional_landed_cost')) |
| 261 |
if not landed_cost.currency_id.is_zero(total_amount - landed_cost.amount_total): |
| 262 |
return False |
| 263 |
|
| 264 |
val_to_cost_lines = defaultdict(lambda: 0.0) |
| 265 |
for val_line in landed_cost.valuation_adjustment_lines: |
| 266 |
val_to_cost_lines[val_line.cost_line_id] += val_line.additional_landed_cost |
| 267 |
if any(not landed_cost.currency_id.is_zero(cost_line.price_unit - val_amount) |
| 268 |
for cost_line, val_amount in val_to_cost_lines.items()): |
| 269 |
return False |
| 270 |
return True |
| 271 |
|
| 272 |
|
| 273 |
class StockLandedCostLines(models.Model): |
| 274 |
_name = 'stock.landed.cost.lines' |
| 275 |
_description = 'Stock Landed Cost Line' |
| 276 |
|
| 277 |
name = fields.Char('Description') |
| 278 |
cost_id = fields.Many2one( |
| 279 |
'stock.landed.cost', 'Landed Cost', |
| 280 |
required=True, index=True, ondelete='cascade') |
| 281 |
product_id = fields.Many2one('product.product', 'Product', required=True) |
| 282 |
price_unit = fields.Monetary('Cost', required=True) |
| 283 |
split_method = fields.Selection( |
| 284 |
SPLIT_METHOD, |
| 285 |
string='Split Method', |
| 286 |
required=True, |
| 287 |
help="Equal: Cost will be equally divided.\n" |
| 288 |
"By Quantity: Cost will be divided according to product's quantity.\n" |
| 289 |
"By Current cost: Cost will be divided according to product's current cost.\n" |
| 290 |
"By Weight: Cost will be divided depending on its weight.\n" |
| 291 |
"By Volume: Cost will be divided depending on its volume.") |
| 292 |
account_id = fields.Many2one('account.account', 'Account') |
| 293 |
currency_id = fields.Many2one('res.currency', related='cost_id.currency_id') |
| 294 |
|
| 295 |
@api.onchange('product_id') |
| 296 |
def onchange_product_id(self): |
| 297 |
self.name = self.product_id.name or '' |
| 298 |
self.split_method = self.product_id.product_tmpl_id.split_method_landed_cost or self.split_method or 'equal' |
| 299 |
self.price_unit = self.product_id.standard_price or 0.0 |
| 300 |
accounts_data = self.product_id.product_tmpl_id.get_product_accounts() |
| 301 |
self.account_id = accounts_data['expense'] |
| 302 |
|
| 303 |
|
| 304 |
class StockValuationAdjustmentLines(models.Model): |
| 305 |
_name = 'stock.valuation.adjustment.lines' |
| 306 |
_description = 'Valuation Adjustment Lines' |
| 307 |
|
| 308 |
name = fields.Char( |
| 309 |
'Description', compute='_compute_name', store=True) |
| 310 |
cost_id = fields.Many2one( |
| 311 |
'stock.landed.cost', 'Landed Cost', |
| 312 |
ondelete='cascade', required=True, index=True) |
| 313 |
cost_line_id = fields.Many2one( |
| 314 |
'stock.landed.cost.lines', 'Cost Line', readonly=True) |
| 315 |
move_id = fields.Many2one('stock.move', 'Stock Move', readonly=True) |
| 316 |
product_id = fields.Many2one('product.product', 'Product', required=True) |
| 317 |
quantity = fields.Float( |
| 318 |
'Quantity', default=1.0, |
| 319 |
digits=0, required=True) |
| 320 |
weight = fields.Float( |
| 321 |
'Weight', default=1.0, |
| 322 |
digits='Stock Weight') |
| 323 |
volume = fields.Float( |
| 324 |
'Volume', default=1.0, digits='Volume') |
| 325 |
former_cost = fields.Monetary( |
| 326 |
'Original Value') |
| 327 |
additional_landed_cost = fields.Monetary( |
| 328 |
'Additional Landed Cost') |
| 329 |
final_cost = fields.Monetary( |
| 330 |
'New Value', compute='_compute_final_cost', |
| 331 |
store=True) |
| 332 |
currency_id = fields.Many2one('res.currency', related='cost_id.company_id.currency_id') |
| 333 |
|
| 334 |
@api.depends('cost_line_id.name', 'product_id.code', 'product_id.name') |
| 335 |
def _compute_name(self): |
| 336 |
for line in self: |
| 337 |
name = '%s - ' % (line.cost_line_id.name if line.cost_line_id else '') |
| 338 |
line.name = name + (line.product_id.code or line.product_id.name or '') |
| 339 |
|
| 340 |
@api.depends('former_cost', 'additional_landed_cost') |
| 341 |
def _compute_final_cost(self): |
| 342 |
for line in self: |
| 343 |
line.final_cost = line.former_cost + line.additional_landed_cost |
| 344 |
|
| 345 |
def _create_accounting_entries(self, remaining_qty): |
| 346 |
|
| 347 |
cost_product = self.cost_line_id.product_id |
| 348 |
if not cost_product: |
| 349 |
return False |
| 350 |
accounts = self.product_id.product_tmpl_id.get_product_accounts() |
| 351 |
|
| 352 |
debit_account_id = (accounts.get('stock_valuation') and accounts['stock_valuation'].id) or False |
| 353 |
credit_account_id = self.cost_line_id.account_id.id or cost_product._get_product_accounts()['expense'].id |
| 354 |
|
| 355 |
if not credit_account_id: |
| 356 |
raise UserError(_('Please configure Stock Expense Account for product: %s.', cost_product.name)) |
| 357 |
|
| 358 |
return self._create_account_move_line(credit_account_id, debit_account_id, remaining_qty) |
| 359 |
|
| 360 |
def _prepare_account_move_line_values(self): |
| 361 |
return { |
| 362 |
'name': self.name, |
| 363 |
'product_id': self.product_id.id, |
| 364 |
'quantity': 0, |
| 365 |
} |
| 366 |
|
| 367 |
def _create_account_move_line(self, credit_account_id, debit_account_id, remaining_qty): |
| 368 |
""" In real time the vendor bill for landed costs only balance the COGS account. |
| 369 |
We should credit what remains in stock and debit the stock valuation account. |
| 370 |
""" |
| 371 |
AccountMoveLine = [] |
| 372 |
if not remaining_qty: |
| 373 |
return AccountMoveLine |
| 374 |
base_line = self._prepare_account_move_line_values() |
| 375 |
debit_line = dict(base_line, account_id=debit_account_id) |
| 376 |
credit_line = dict(base_line, account_id=credit_account_id) |
| 377 |
diff = self.additional_landed_cost * (remaining_qty / self.quantity) |
| 378 |
if diff > 0: |
| 379 |
debit_line['debit'] = diff |
| 380 |
credit_line['credit'] = diff |
| 381 |
else: |
| 382 |
|
| 383 |
debit_line['credit'] = -diff |
| 384 |
credit_line['debit'] = -diff |
| 385 |
AccountMoveLine.append([0, 0, debit_line]) |
| 386 |
AccountMoveLine.append([0, 0, credit_line]) |
| 387 |
|
| 388 |
return AccountMoveLine |