odoo_utility_scripts/delete_all_assets.py

86 lines
2.9 KiB
Python

import sys
import os
import argparse
def main():
parser = argparse.ArgumentParser(description="Delete All Fixed Assets from Odoo")
parser.add_argument("odoo_bin_path", help="Path to odoo-bin executable")
parser.add_argument("conf_path", help="Path to odoo.conf")
parser.add_argument("db_name", help="Database name")
args = parser.parse_args()
odoo_bin_path = os.path.abspath(args.odoo_bin_path)
conf_path = os.path.abspath(args.conf_path)
db_name = args.db_name
# Add Odoo to sys.path
odoo_root = os.path.dirname(odoo_bin_path)
if odoo_root not in sys.path:
sys.path.append(odoo_root)
# Change CWD to config directory to handle relative paths in config
os.chdir(os.path.dirname(conf_path))
try:
import odoo
from odoo import api, SUPERUSER_ID
except ImportError:
print(f"Error: Could not import 'odoo' module from {odoo_root}. Make sure odoo-bin path is correct.")
sys.exit(1)
print(f"Initializing Odoo Environment for database: {db_name}...")
try:
odoo.tools.config.parse_config(['-c', conf_path])
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
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__":
main()