1+ import json
2+ from django .core .management .base import BaseCommand , CommandError
3+ from inventory .models import Asset
4+ from inventory .moneybird import MoneybirdAssetService
5+
6+
7+ class Command (BaseCommand ):
8+ help = "Update asset moneybird_asset_id from a JSON file"
9+
10+ def add_arguments (self , parser ):
11+ parser .add_argument (
12+ 'json_file' ,
13+ type = str ,
14+ help = 'Path to JSON file with asset moneybird IDs'
15+ )
16+
17+ def handle (self , * args , ** options ):
18+ json_file = options ['json_file' ]
19+
20+ try :
21+ with open (json_file , 'r' ) as f :
22+ data = json .load (f )
23+ except FileNotFoundError :
24+ raise CommandError (f'File "{ json_file } " not found' )
25+ except json .JSONDecodeError as e :
26+ raise CommandError (f'Invalid JSON file: { e } ' )
27+
28+ updated_count = 0
29+ not_found_count = 0
30+ skipped_count = 0
31+
32+ for asset_name , asset_data in data .items ():
33+ moneybird_id = asset_data .get ('moneybird_id' )
34+
35+ if not moneybird_id :
36+ self .stdout .write (
37+ self .style .WARNING (f'Skipping { asset_name } : no moneybird_id' )
38+ )
39+ skipped_count += 1
40+ continue
41+
42+ try :
43+ asset = Asset .objects .get (name = asset_name )
44+ asset .moneybird_asset_id = int (moneybird_id )
45+ asset .save (update_fields = ['moneybird_asset_id' ])
46+
47+ try :
48+ mb = MoneybirdAssetService ()
49+ mb .update_asset (asset_id = asset .moneybird_asset_id , name = str (asset ))
50+ asset .refresh_from_moneybird ()
51+ self .stdout .write (
52+ self .style .SUCCESS (f'Updated { asset_name } : { moneybird_id } , synced name to Moneybird, and refreshed data' )
53+ )
54+ except Exception as e :
55+ self .stdout .write (
56+ self .style .WARNING (f'Updated { asset_name } : { moneybird_id } but failed to sync: { e } ' )
57+ )
58+
59+ updated_count += 1
60+ except Asset .DoesNotExist :
61+ self .stdout .write (
62+ self .style .ERROR (f'Asset not found: { asset_name } ' )
63+ )
64+ not_found_count += 1
65+
66+ self .stdout .write (
67+ self .style .SUCCESS (
68+ f'\n Completed: { updated_count } updated, { not_found_count } not found, { skipped_count } skipped'
69+ )
70+ )
0 commit comments