stock_inventory_backdate/models/stock_quant.py
2025-12-06 19:03:29 +07:00

54 lines
2.1 KiB
Python

from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class StockQuant(models.Model):
_inherit = 'stock.quant'
force_inventory_date = fields.Date(
string="Force Inventory Date",
help="Choose a specific date for the inventory adjustment. "
"If set, the stock move will be created with this date."
)
force_valuation_date = fields.Date(
string="Force Valuation Date",
help="Choose a specific date for the stock valuation. "
"If set, the valuation layer will be created with this date."
)
@api.model
def _get_inventory_fields_create(self):
""" Allow the new fields to be set during inventory creation """
res = super(StockQuant, self)._get_inventory_fields_create()
res += ['force_inventory_date', 'force_valuation_date']
return res
@api.model
def _get_inventory_fields_write(self):
""" Allow the new fields to be set during inventory write """
res = super(StockQuant, self)._get_inventory_fields_write()
res += ['force_inventory_date', 'force_valuation_date']
return res
def _apply_inventory(self):
"""Override to pass forced dates to the context"""
# We need to handle quants with different forced dates separately
# Group by (force_inventory_date, force_valuation_date)
# If no forced date, key is (False, False)
grouped_quants = {}
for quant in self:
key = (quant.force_inventory_date, quant.force_valuation_date)
if key not in grouped_quants:
grouped_quants[key] = self.env['stock.quant']
grouped_quants[key] |= quant
for (force_inventory_date, force_valuation_date), quants in grouped_quants.items():
ctx = dict(self.env.context)
if force_inventory_date:
ctx['force_inventory_date'] = force_inventory_date
if force_valuation_date:
ctx['force_valuation_date'] = force_valuation_date
super(StockQuant, quants.with_context(ctx))._apply_inventory()