Implementacion de celery y problemas con relacioines
This commit is contained in:
@@ -152,8 +152,7 @@ class FacturaImportacionMexService:
|
||||
num_parte_final = part_master.part_number
|
||||
fraccion_raw = part_master.fraction if part_master.fraction else ""
|
||||
|
||||
# --- LÓGICA DE FRACCIÓN DESDE BASE DE DATOS ---
|
||||
# Limpiar la fracción de la BD (quitar puntos y asegurar 8 dígitos)
|
||||
|
||||
fraccion_limpia = fraccion_raw.replace(".", "").strip()
|
||||
if fraccion_limpia:
|
||||
fraccion_limpia = fraccion_limpia[:8].zfill(8)
|
||||
@@ -161,9 +160,7 @@ class FacturaImportacionMexService:
|
||||
# Consultar tabla tariff_fractions
|
||||
fraccion_db = db.query(TariffFraction).filter(TariffFraction.code == fraccion_limpia).first()
|
||||
|
||||
# Reglas de negocio solicitadas:
|
||||
# 1. Preferencia default: "General"
|
||||
# 2. AdValorem default: "0%" si no existe o es vacío
|
||||
|
||||
preferencia_txt = "General"
|
||||
advalorem_txt = "0%"
|
||||
fraccion_imprimir = fraccion_raw
|
||||
@@ -178,7 +175,7 @@ class FacturaImportacionMexService:
|
||||
|
||||
fraccion_imprimir = fraccion_db.fraction or fraccion_raw
|
||||
else:
|
||||
# Si no existe en la tabla, aplicamos el fallback visual de puntos
|
||||
|
||||
fraccion_imprimir = self._format_fraccion_fallback(fraccion_limpia)
|
||||
|
||||
partidas_list.append(PartidaSchema(
|
||||
@@ -220,7 +217,7 @@ class FacturaImportacionMexService:
|
||||
clave_comun = max(set(claves), key=claves.count) if claves else ""
|
||||
if bultos > 1 and clave_comun and not clave_comun.endswith("S"): clave_comun += "S"
|
||||
tc = float(tipo_cambio) if tipo_cambio else 1.0
|
||||
return TotalesSchema(
|
||||
return TotalesSchema(
|
||||
cantidad_total=self.formatear_numero(cant), bultos_total=bultos, clave_bultos=clave_comun,
|
||||
peso_neto_total=self.formatear_numero(peso_n), peso_bruto_total=self.formatear_numero(peso_b),
|
||||
valor_total_total=self.formatear_numero(valor), valor_total_dolares=self.formatear_numero(valor / tc if tc > 0 else 0)
|
||||
|
||||
@@ -2,52 +2,44 @@ from enum import Enum
|
||||
from typing import Dict, Any
|
||||
from fastapi import APIRouter, Depends, Query, Response, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from celery.result import AsyncResult
|
||||
from core.celery_app import celery_app
|
||||
from core.database import get_core_db
|
||||
from core.security import get_current_user, validate_access_to_resource
|
||||
from .mex.service import FacturaImportacionMexService
|
||||
from .task import generar_pdf_factura_async
|
||||
|
||||
router = APIRouter()
|
||||
servicio_mex = FacturaImportacionMexService()
|
||||
|
||||
class TipoFactura(str, Enum):
|
||||
mexicana = "mex"
|
||||
@router.get("/tasks/{task_id}")
|
||||
async def get_task_status(
|
||||
task_id: str,
|
||||
current_user: Dict[str, Any] = Depends(get_current_user),
|
||||
db: Session = Depends(get_core_db)
|
||||
):
|
||||
task_result = AsyncResult(task_id, app=celery_app)
|
||||
|
||||
class Formato(str, Enum):
|
||||
html = "html"
|
||||
pdf = "pdf"
|
||||
response = {
|
||||
"task_id": task_id,
|
||||
"state": task_result.state,
|
||||
"result": None
|
||||
}
|
||||
|
||||
@router.get("/{invoice_id}/download")
|
||||
async def descargar_factura(
|
||||
if task_result.state == 'FAILURE':
|
||||
response["result"] = str(task_result.result)
|
||||
elif task_result.state == 'SUCCESS':
|
||||
response["result"] = task_result.result
|
||||
|
||||
return response
|
||||
|
||||
@router.post("/{invoice_id}/download-async")
|
||||
async def trigger_descarga_factura(
|
||||
invoice_id: int,
|
||||
company_id: int = Query(..., description="ID de la empresa"),
|
||||
tipo: TipoFactura = Query(TipoFactura.mexicana),
|
||||
formato: Formato = Query(Formato.pdf),
|
||||
db: Session = Depends(get_core_db),
|
||||
current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
current_user: Dict[str, Any] = Depends(get_current_user),
|
||||
db: Session = Depends(get_core_db)
|
||||
):
|
||||
# Validar que el usuario tiene acceso a esta empresa
|
||||
tenant_id = validate_access_to_resource(db, company_id, current_user)
|
||||
|
||||
if tipo == TipoFactura.mexicana:
|
||||
try:
|
||||
# Pasamos invoice_id Y company_id al servicio
|
||||
contenido, nombre, media_type = servicio_mex.generar_factura_completa(
|
||||
db=db,
|
||||
invoice_id=invoice_id,
|
||||
company_id=company_id,
|
||||
formato=formato.value
|
||||
)
|
||||
|
||||
return Response(
|
||||
content=contenido,
|
||||
media_type=media_type,
|
||||
headers={
|
||||
"Content-Disposition": f"attachment; filename={nombre}",
|
||||
"Access-Control-Expose-Headers": "Content-Disposition"
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
else:
|
||||
raise HTTPException(status_code=501, detail="Tipo no implementado")
|
||||
validate_access_to_resource(db, company_id, current_user)
|
||||
task = generar_pdf_factura_async.delay(invoice_id, company_id)
|
||||
return {"task_id": task.id, "message": "Generación iniciada"}
|
||||
@@ -2,6 +2,7 @@ import base64
|
||||
import logging
|
||||
from core.celery_app import celery_app
|
||||
from core.database import CoreSessionLocal
|
||||
|
||||
from .mex.service import FacturaImportacionMexService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
Reference in New Issue
Block a user