stock_inventory_scrap_backdate/models/stock_move.py
2026-06-17 14:59:07 +07:00

106 lines
3.8 KiB
Python

# -*- coding: utf-8 -*-
from odoo import models, fields
class StockMove(models.Model):
_inherit = 'stock.move'
def _post_process_validated_moves(self, backdate):
"""Handle backdating for a batch of moves, including valuation and accounting"""
if not self:
return True
# Flush all pending ORM operations to DB before running raw SQL
self.env.flush_all()
move_ids = tuple(self.ids)
# 1. Update stock move dates
self.env.cr.execute(
"UPDATE stock_move SET date = %s WHERE id IN %s",
(backdate, move_ids)
)
# 2. Update stock move line dates
self.env.cr.execute(
"UPDATE stock_move_line SET date = %s WHERE move_id IN %s",
(backdate, move_ids)
)
# 3. Update stock valuation layer (if the table stock_valuation_layer exists)
self.env.cr.execute("""
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'stock_valuation_layer'
);
""")
if self.env.cr.fetchone()[0]:
self.env.cr.execute(
"UPDATE stock_valuation_layer SET create_date = %s WHERE stock_move_id IN %s",
(backdate, move_ids)
)
# 4. Update product value (Odoo 19) (if the table product_value exists)
self.env.cr.execute("""
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'product_value'
);
""")
if self.env.cr.fetchone()[0]:
self.env.cr.execute(
"UPDATE product_value SET date = %s, create_date = %s WHERE move_id IN %s",
(backdate, backdate, move_ids)
)
# 5. Update account move dates (journal entries)
account_move_ids = []
# Check if stock_move has account_move_id column
self.env.cr.execute("""
SELECT EXISTS (
SELECT FROM information_schema.columns
WHERE table_name = 'stock_move'
AND column_name = 'account_move_id'
);
""")
if self.env.cr.fetchone()[0]:
self.env.cr.execute(
"SELECT account_move_id FROM stock_move WHERE id IN %s AND account_move_id IS NOT NULL",
(move_ids,)
)
account_move_ids.extend([row[0] for row in self.env.cr.fetchall()])
# Also check stock_valuation_layer if table exists
self.env.cr.execute("""
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'stock_valuation_layer'
);
""")
if self.env.cr.fetchone()[0]:
self.env.cr.execute(
"SELECT account_move_id FROM stock_valuation_layer WHERE stock_move_id IN %s AND account_move_id IS NOT NULL",
(move_ids,)
)
account_move_ids.extend([row[0] for row in self.env.cr.fetchall()])
account_move_ids = list(set(account_move_ids))
if account_move_ids:
# Update account_move date
self.env.cr.execute(
"UPDATE account_move SET date = %s WHERE id IN %s",
(backdate.date(), tuple(account_move_ids))
)
# Update account_move_line date
self.env.cr.execute(
"UPDATE account_move_line SET date = %s WHERE move_id IN %s",
(backdate.date(), tuple(account_move_ids))
)
# 6. Clear cache to reflect changes
self.env.invalidate_all()
return True