odoo_utility_scripts/post_depreciation.py
2026-01-21 17:03:32 +07:00

76 lines
2.5 KiB
Python

import sys
import os
from datetime import date
# ---------------- CONFIGURATION ----------------
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
# Change CWD to Project Root so relative paths in odoo.conf work
os.chdir(PROJECT_ROOT)
ODOO_PATH = os.path.join(PROJECT_ROOT, 'odoo')
CONF_FILE = os.path.join(PROJECT_ROOT, 'odoo.conf')
DB_NAME = 'kipasdbclone5'
POST_UP_TO_DATE = date(2026, 1, 21) # User specified "now"
if ODOO_PATH not in sys.path:
sys.path.append(ODOO_PATH)
import odoo
from odoo import api, SUPERUSER_ID
def post_depreciation():
print(f"Initializing Odoo Environment for database: {DB_NAME}...")
try:
odoo.tools.config.parse_config(['-c', CONF_FILE])
registry = odoo.registry(DB_NAME)
except Exception as e:
print(f"Error initializing Odoo: {e}")
return
with registry.cursor() as cr:
env = api.Environment(cr, SUPERUSER_ID, {})
print("Connected to Odoo.")
# Search for Draft Depreciation MOVES (account.move)
# Linked to an asset, in draft state, date <= target date
moves_to_post = env['account.move'].search([
('asset_id', '!=', False),
('state', '=', 'draft'),
('date', '<=', POST_UP_TO_DATE)
])
if not moves_to_post:
print(f"No draft depreciation entries found on or before {POST_UP_TO_DATE}.")
return
print(f"Found {len(moves_to_post)} moves to post up to {POST_UP_TO_DATE}.")
# Group by date for nicer logging
moves_by_date = {}
for move in moves_to_post:
d = move.date
if d not in moves_by_date:
moves_by_date[d] = []
moves_by_date[d].append(move)
count = 0
try:
for d in sorted(moves_by_date.keys()):
batch = moves_by_date[d]
batch_moves = env['account.move'].browse([m.id for m in batch])
print(f"Posting {len(batch)} entries for date {d}...")
batch_moves.action_post()
count += len(batch)
cr.commit()
print(f"Successfully posted {count} depreciation entries.")
except Exception as e:
cr.rollback()
print(f"An error occurred. Transaction rolled back.\nError: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
post_depreciation()