Explorar o código

Exporto transacciones recurrentes y comando para importar

Celestino Rey hai 1 ano
pai
achega
daf85885bf

+ 83 - 0
src/finanzas/management/commands/importar_datos_json.py

@@ -0,0 +1,83 @@
+import json
+from django.core.management.base import BaseCommand
+from finanzas.models import Cuenta, Movimiento, MovimientoFrecuente, Categoria, TransaccionRecurrente
+from reymotausers.models import ReyMotaUser
+from django.utils.dateparse import parse_datetime, parse_date
+
+class Command(BaseCommand):
+    help = 'Importa datos desde un archivo JSON exportado por el API'
+
+    def add_arguments(self, parser):
+        parser.add_argument('ruta_json', type=str)
+
+    def handle(self, *args, **kwargs):
+        ruta = kwargs['ruta_json']
+        with open(ruta, 'r', encoding='utf-8') as f:
+            datos = json.load(f)
+
+        # Requiere un usuario por defecto
+        usuario = ReyMotaUser.objects.first()
+        if not usuario:
+            self.stdout.write(self.style.ERROR('No hay usuarios en la base de datos'))
+            return
+
+        # 1. Categorías
+        categorias = {}
+        for cat in datos.get("categorias", []):
+            obj, _ = Categoria.objects.get_or_create(nombre=cat["nombre"])
+            categorias[cat["nombre"]] = obj
+
+        # 2. Cuentas
+        cuentas = {}
+        for c in datos.get("cuentas", []):
+            obj, _ = Cuenta.objects.get_or_create(
+                nombre=c["nombre"],
+                usuario=usuario,
+                defaults={
+                    "tipo": c["tipo"],
+                    "saldo": c["saldo"],
+                    "favorita": c.get("favorita", False)
+                }
+            )
+            cuentas[c["nombre"]] = obj
+
+        # 3. Movimientos frecuentes
+        for mf in datos.get("movimientos_frecuentes", []):
+            MovimientoFrecuente.objects.get_or_create(
+                nombre=mf["nombre"],
+                cuenta_origen=cuentas.get(mf["cuenta_origen"]),
+                cuenta_destino=cuentas.get(mf["cuenta_destino"]),
+                categoria=categorias.get(mf.get("categoria")),
+                monto=mf["monto"],
+                descripcion=mf.get("descripcion", ""),
+                usuario=usuario,
+            )
+
+        # 4. Transacciones recurrentes
+        for tr in datos.get("movimientos_frecuentes", []):
+            TransaccionRecurrente.objects.get_or_create(
+                usuario=usuario,
+                cuenta_origen=cuentas.get(tr["cuenta_origen"]),
+                cuenta_destino=cuentas.get(tr["cuenta_destino"]),
+                monto=tr["monto"],
+                categoria=categorias.get(tr.get("categoria")),
+                descripcion=tr.get("descripcion", ""),
+                defaults={
+                    "frecuencia": tr.get("frecuencia", ""),
+                }
+            )
+
+        # 5. Movimientos
+        for m in datos.get("movimientos", []):
+            Movimiento.objects.get_or_create(
+                usuario=usuario,
+                cuenta_origen=cuentas.get(m["cuenta_origen"]),
+                cuenta_destino=cuentas.get(m["cuenta_destino"]),
+                monto=m["monto"],
+                fecha=parse_datetime(m["fecha"]) or parse_date(m["fecha"]),
+                descripcion=m.get("descripcion", ""),
+                categoria=categorias.get(m.get("categoria"))
+            )
+
+        self.stdout.write(self.style.SUCCESS("Datos importados correctamente."))
+

+ 1 - 0
src/finanzas/views.py

@@ -324,6 +324,7 @@ def api_datos_completos(request):
         'categorias': categorias,
         'movimientos': movimientos,
         'movimientos_frecuentes': movs_frecuentes,
+        'transacciones_recurrentes': movs_recurrentes,
     }, safe=False)