import sys import os # ---------------- CONFIGURATION ---------------- PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) os.chdir(PROJECT_ROOT) ODOO_PATH = os.path.join(PROJECT_ROOT, 'odoo') CONF_FILE = os.path.join(PROJECT_ROOT, 'odoo.conf') DB_NAME = 'kipasdbclone5' if ODOO_PATH not in sys.path: sys.path.append(ODOO_PATH) import odoo from odoo import api, SUPERUSER_ID def delete_assets(): 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.") # 1. Search for non-model assets assets = env['account.asset'].search([('state', '!=', 'model')]) print(f"Found {len(assets)} assets to delete.") if not assets: print("No assets to delete.") return try: # 2. Find and Delete Linked Depreciation Moves moves = assets.mapped('depreciation_move_ids') posted_moves = moves.filtered(lambda m: m.state == 'posted') if posted_moves: print(f"Resetting {len(posted_moves)} posted moves to draft...") posted_moves.button_draft() if moves: print(f"Deleting {len(moves)} depreciation moves...") moves.unlink() # Deleting moves first cleans up the relation # 3. Reset Assets to Draft # Some assets might be 'open' or 'close' or 'cancelled'. # To delete, they often need to be in draft or cancelled state depending on logic, # but unlink() in Odoo 17 account_asset usually checks if they are NOT in open/paused/close. # So we must write state = draft. # Check for assets that are not draft non_draft_assets = assets.filtered(lambda a: a.state != 'draft') if non_draft_assets: print(f"Setting {len(non_draft_assets)} assets to draft state...") non_draft_assets.write({'state': 'draft'}) # 4. Delete Assets print(f"Deleting {len(assets)} assets...") assets.unlink() cr.commit() print("Successfully deleted all assets and related 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__": delete_assets()