1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
from django.core.management.base import BaseCommand
import json
from datetime import datetime
from budget.models import Transaction, Recurrence
DT_FMT: str = "%Y-%m-%dT%I:%M:%S.%fZ"
class Command(BaseCommand):
help = "Import existing budget transactions from a JSON file"
def add_arguments(self, parser):
parser.add_argument("budget-json", type=str)
def handle(self, *args, **options):
Transaction.objects.all().delete()
with open(options["budget-json"], "r") as f:
data = json.load(f)
for b in data:
if not b["date"]:
self.stdout.write(
self.style.WARNING(f'No date found for "{b["title"]}"')
)
continue
# 2023-01-01T06:00:00.000Z
dt = datetime.strptime(b["date"], DT_FMT)
amount = b["amount"]
if not amount:
amount = 0
Transaction.objects.create(
title=b["title"],
cents=float(amount) * 100,
date=dt,
recurrence=Recurrence.MONTH,
week=0,
is_income=False,
)
self.stdout.write(
self.style.SUCCESS(f"Successfully imported {len(data)} transactions")
)
|