Se creo la base del reporte
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
from typing import Dict, Any
|
||||
from fastapi import APIRouter, Depends, Query, Response, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from core.database import get_core_db
|
||||
from core.security import get_current_user, validate_access_to_resource
|
||||
from .service import PackingListService
|
||||
|
||||
router = APIRouter()
|
||||
service = PackingListService()
|
||||
|
||||
from celery.result import AsyncResult
|
||||
from core.celery_app import celery_app
|
||||
from .task import generar_packing_list_async
|
||||
|
||||
@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)
|
||||
|
||||
response = {
|
||||
"task_id": task_id,
|
||||
"state": task_result.state,
|
||||
"result": None,
|
||||
"info": None
|
||||
}
|
||||
|
||||
if task_result.state == 'FAILURE':
|
||||
response["result"] = str(task_result.result)
|
||||
elif task_result.state == 'SUCCESS':
|
||||
response["result"] = task_result.result
|
||||
elif task_result.state == 'PROCESSING':
|
||||
response["info"] = task_result.info
|
||||
|
||||
return response
|
||||
|
||||
@router.post("/{invoice_id}/download-async")
|
||||
async def trigger_download_packing_list(
|
||||
invoice_id: int,
|
||||
company_id: int = Query(..., description="ID de la empresa"),
|
||||
current_user: Dict[str, Any] = Depends(get_current_user),
|
||||
db: Session = Depends(get_core_db)
|
||||
):
|
||||
validate_access_to_resource(db, company_id, current_user)
|
||||
|
||||
task = generar_packing_list_async.delay(invoice_id, company_id)
|
||||
return {"task_id": task.id, "message": "Generación iniciada"}
|
||||
@@ -0,0 +1,88 @@
|
||||
from typing import List, Optional, Union, Any
|
||||
from pydantic import BaseModel, field_validator
|
||||
|
||||
class ClienteSchema(BaseModel):
|
||||
header: str
|
||||
nombre: str
|
||||
direccion: Optional[str] = ""
|
||||
num_exterior: Optional[str] = ""
|
||||
num_interior: Optional[str] = ""
|
||||
colonia: Optional[str] = ""
|
||||
codigo_postal: Optional[str] = ""
|
||||
ciudad: Optional[str] = ""
|
||||
estado: Optional[str] = ""
|
||||
pais: Optional[str] = ""
|
||||
tax_id: str
|
||||
programa: Optional[str] = ""
|
||||
autorizacion: Optional[str] = ""
|
||||
prosec: Optional[str] = ""
|
||||
reg_emp: Optional[str] = ""
|
||||
cert: Optional[str] = ""
|
||||
|
||||
@field_validator('direccion', 'nombre', mode='before')
|
||||
@classmethod
|
||||
def prevent_none(cls, v):
|
||||
return v or ""
|
||||
|
||||
class FacturaSchema(BaseModel):
|
||||
numero: str
|
||||
fecha: str
|
||||
tipo_cambio: Union[float, str]
|
||||
moneda: str
|
||||
pedimento: str = ""
|
||||
clave_pedimento: str = ""
|
||||
remesa: str = ""
|
||||
acuse_electronico: str = ""
|
||||
agente_aduanal: str = ""
|
||||
patente: str = ""
|
||||
precinto: str = ""
|
||||
regimen: str = ""
|
||||
transportista: str = ""
|
||||
scac: str = ""
|
||||
caat: str = ""
|
||||
incoterm: str = ""
|
||||
transporte: str = ""
|
||||
num_transporte: str = ""
|
||||
placas: str = ""
|
||||
placas_remolque: str = ""
|
||||
licencia_conductor: str = ""
|
||||
aduana: str = ""
|
||||
destino: str = ""
|
||||
observaciones: str = ""
|
||||
|
||||
class PartidaSchema(BaseModel):
|
||||
numero_parte: str
|
||||
descripcion: str
|
||||
fraccion: str
|
||||
origen: str
|
||||
|
||||
advalorem:Optional[str] = ""
|
||||
preferencia:Optional[str] = ""
|
||||
|
||||
cantidad_importacion: Union[float, str]
|
||||
unidad_medida: str
|
||||
cantidad_bultos: int
|
||||
clave_bultos: str
|
||||
peso_neto: Union[float, str]
|
||||
peso_bruto: Union[float, str]
|
||||
valor_costo_unitario: Union[float, str] = ""
|
||||
valor_total: Union[float, str] = ""
|
||||
|
||||
class TotalesSchema(BaseModel):
|
||||
cantidad_total: Union[float, str]
|
||||
bultos_total: int
|
||||
clave_bultos: str = ""
|
||||
peso_neto_total: Union[float, str]
|
||||
peso_bruto_total: Union[float, str]
|
||||
valor_total_total: Union[float, str] = ""
|
||||
valor_total_dolares: Union[float, str] = ""
|
||||
|
||||
class PackingListSchema(BaseModel):
|
||||
cliente_proveedor: ClienteSchema
|
||||
cliente_vendido: ClienteSchema
|
||||
cliente_enviado: ClienteSchema
|
||||
factura: FacturaSchema
|
||||
partidas: List[PartidaSchema]
|
||||
totales: TotalesSchema
|
||||
logo_b64: Optional[str] = None
|
||||
|
||||
@@ -0,0 +1,364 @@
|
||||
import shutil
|
||||
import base64
|
||||
import pdfkit
|
||||
from pathlib import Path
|
||||
from decimal import Decimal
|
||||
from typing import Tuple, List, Callable, Optional, Dict
|
||||
|
||||
from jinja2 import Environment, FileSystemLoader, select_autoescape
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# --- MODELOS ---
|
||||
from api.v1.modules.a76.invoices.models import InvoiceHeader, InvoiceLogistics
|
||||
from api.v1.modules.a76.items.line_financials.models import LineFinancial
|
||||
from api.v1.modules.a76.items.line_quantities.models import LineQuantity
|
||||
from api.v1.modules.a76.items.line_items.models import LineItem
|
||||
from api.v1.modules.a76.clients_and_providers.models import (
|
||||
ClientProvider, ClientProviderAddress, ClientProviderPrograms
|
||||
)
|
||||
from api.v1.modules.a76.parts.models import Part
|
||||
from api.v1.modules.a76.pedmientos.models import Pedimentos
|
||||
from api.v1.modules.a76.general_catalogs.company.models import Company
|
||||
from api.v1.modules.a76.customs_brokers.models import CustomsBroker
|
||||
from api.v1.modules.a76.items.models import Item
|
||||
|
||||
# --- TRANSPORTATION MODELS ---
|
||||
from api.v1.modules.a76.transportation.transporters.models import Transporter
|
||||
from api.v1.modules.a76.transportation.vehicles.models import Vehicle
|
||||
from api.v1.modules.a76.transportation.trailers.models import Trailer
|
||||
from api.v1.modules.a76.transportation.drivers.models import Driver
|
||||
|
||||
# --- MODELO DE FRACCIONES ---
|
||||
from api.v1.modules.a76.general_catalogs.tariff_fractions.models import TariffFraction
|
||||
|
||||
# --- SCHEMAS ---
|
||||
from .schemas import (
|
||||
ClienteSchema, PartidaSchema, TotalesSchema,
|
||||
FacturaSchema, PackingListSchema
|
||||
)
|
||||
|
||||
class PackingListService:
|
||||
def __init__(self):
|
||||
self.template_dir = Path(__file__).parent / "templates"
|
||||
self.jinja_env = Environment(
|
||||
loader=FileSystemLoader(self.template_dir),
|
||||
autoescape=select_autoescape(['html', 'xml'])
|
||||
)
|
||||
self.template = self.jinja_env.get_template('packing_list.html')
|
||||
|
||||
def _get_wkhtmltopdf_config(self):
|
||||
# List of possible paths
|
||||
paths = [
|
||||
shutil.which("wkhtmltopdf"),
|
||||
"/usr/local/bin/wkhtmltopdf",
|
||||
"/usr/bin/wkhtmltopdf",
|
||||
"C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe"
|
||||
]
|
||||
|
||||
path = next((p for p in paths if p and Path(p).exists()), None)
|
||||
|
||||
if not path:
|
||||
# If we are in dev and cannot find it, try to mock it or raise clearer error
|
||||
if shutil.which("echo"):
|
||||
print("WARNING: wkhtmltopdf not found, PDF generation will fail.")
|
||||
raise RuntimeError(f"wkhtmltopdf binary not found. Searched in: {paths}")
|
||||
|
||||
return pdfkit.configuration(wkhtmltopdf=path)
|
||||
|
||||
def formatear_numero(self, valor, decimales: int = 2):
|
||||
if valor is None: return 0.0
|
||||
try:
|
||||
return round(float(valor), decimales)
|
||||
except: return 0.0
|
||||
|
||||
def _format_fraccion_fallback(self, fraccion_raw: str) -> str:
|
||||
if not fraccion_raw or len(fraccion_raw) < 8:
|
||||
return fraccion_raw or ""
|
||||
return f"{fraccion_raw[:4]}.{fraccion_raw[4:6]}.{fraccion_raw[6:]}"
|
||||
|
||||
def _obtener_datos_cliente(self, db: Session, client_id: int, rol: str) -> ClienteSchema:
|
||||
main = db.query(ClientProvider).filter(ClientProvider.id == client_id).first()
|
||||
if not main:
|
||||
return ClienteSchema(header=rol, nombre="Desconocido", direccion="", tax_id="", codigo_postal="", ciudad="", estado="", pais="MEX")
|
||||
|
||||
addr = db.query(ClientProviderAddress).filter(ClientProviderAddress.client_id == client_id).first()
|
||||
prog = db.query(ClientProviderPrograms).filter(ClientProviderPrograms.client_id == client_id).first()
|
||||
|
||||
return ClienteSchema(
|
||||
header=rol,
|
||||
nombre=(main.name or main.short_name) or "S/N",
|
||||
direccion=(addr.streets or "") if addr else "",
|
||||
num_exterior=(addr.exterior_number or "") if addr else "",
|
||||
num_interior=(addr.interior_number or "") if addr else "",
|
||||
colonia=(addr.neighborhood or "") if addr else "",
|
||||
codigo_postal=(addr.postal_code or "") if addr else "",
|
||||
ciudad=(addr.city or "") if addr else "",
|
||||
estado=(addr.state or "") if addr else "",
|
||||
pais=(addr.country or "MEX") if addr else "MEX",
|
||||
tax_id=prog.tax_id if (prog and prog.tax_id) else (getattr(main, 'rfc', "") or ""),
|
||||
programa="IMMEX" if (prog and prog.program) else "",
|
||||
autorizacion=prog.program_number if prog else "",
|
||||
prosec=prog.prosec_authorization if (prog and prog.prosec and prog.prosec_authorization) else "",
|
||||
reg_emp=prog.val_certified_company_registry if (prog and hasattr(prog, 'val_certified_company_registry')) else (
|
||||
prog.certified_company_registry if (prog and prog.certified_company_registry) else ""
|
||||
),
|
||||
cert=prog.is_certified_company if (prog and prog.is_certified_company) else ""
|
||||
)
|
||||
|
||||
def get_packing_list_data(self, db: Session, invoice_id: int, company_id: int, progress_callback: Optional[Callable] = None) -> PackingListSchema:
|
||||
try:
|
||||
if progress_callback: progress_callback(10, "Buscando factura...")
|
||||
header = db.query(InvoiceHeader).filter(InvoiceHeader.id == invoice_id, InvoiceHeader.company_id == company_id).first()
|
||||
if not header: raise HTTPException(status_code=404, detail="Factura no encontrada")
|
||||
|
||||
compliance = header.compliance_mx
|
||||
logistics = header.logistics if header.logistics else None
|
||||
financials = header.financials if header.financials else None
|
||||
|
||||
if progress_callback: progress_callback(20, "Obteniendo datos de pedimento...")
|
||||
pedimento_id = compliance.pedimento_id if (compliance and compliance.pedimento_id) else header.related_doc_id
|
||||
pedimento = db.query(Pedimentos).filter(Pedimentos.id == pedimento_id).first() if pedimento_id else None
|
||||
|
||||
if progress_callback: progress_callback(30, "Obteniendo cliente y proveedor...")
|
||||
proveedor_id = compliance.provider_id if compliance else None
|
||||
cliente_proveedor = self._obtener_datos_cliente(db, proveedor_id, "Proveedor / supplier:") if proveedor_id else ClienteSchema(header="Proveedor", nombre="No Asignado", direccion="", tax_id="", codigo_postal="", ciudad="", estado="", pais="")
|
||||
|
||||
nombre_agente = ""
|
||||
if compliance and compliance.customs_broker_id:
|
||||
broker = db.query(CustomsBroker).filter(CustomsBroker.id == compliance.customs_broker_id).first()
|
||||
if broker: nombre_agente = broker.name
|
||||
|
||||
company = db.query(Company).filter(Company.id == header.company_id).first()
|
||||
# Datos Default (Company/Importer)
|
||||
cliente_default = ClienteSchema(
|
||||
header="Importador / consignatario:",
|
||||
nombre=getattr(company, 'name', "Empresa Local"),
|
||||
direccion="DOMICILIO FISCAL",
|
||||
num_exterior="", colonia="", codigo_postal="", ciudad="", estado="", pais="MEX",
|
||||
tax_id=getattr(company, 'rfc', ""),
|
||||
programa=getattr(company, 'program', "IMMEX"), autorizacion=getattr(company, 'program_number', "")
|
||||
)
|
||||
|
||||
# Left Side Logic (Consignatario / Sold To)
|
||||
cliente_vendido = cliente_default
|
||||
if compliance and compliance.sold_to_id:
|
||||
raw_header = compliance.sold_to_header or "CONSIGNATARIO"
|
||||
clean_header = raw_header.replace("_", " ").capitalize() + ":"
|
||||
cliente_vendido = self._obtener_datos_cliente(db, compliance.sold_to_id, clean_header)
|
||||
|
||||
# Right Side Logic (Enviado A / Shipped To)
|
||||
cliente_enviado = cliente_default
|
||||
if compliance and compliance.shipped_to_id:
|
||||
raw_header_shipped = compliance.shipped_to_header or "DESTINATARIO"
|
||||
clean_header_shipped = raw_header_shipped.replace("_", " ").capitalize() + ":"
|
||||
cliente_enviado = self._obtener_datos_cliente(db, compliance.shipped_to_id, clean_header_shipped)
|
||||
|
||||
remesa_valor = str(compliance.remesa) if (compliance and compliance.remesa) else ""
|
||||
acuse_valor = str(compliance.edocument) if (compliance and compliance.edocument) else "N/A"
|
||||
|
||||
patente_val = ""
|
||||
if pedimento and pedimento.license:
|
||||
patente_val = pedimento.license
|
||||
elif 'broker' in locals() and broker and broker.license:
|
||||
patente_val = broker.license
|
||||
|
||||
# --- Transport Data Fetching ---
|
||||
transporte_txt = str(logistics.transport_type) if (logistics and logistics.transport_type) else ""
|
||||
num_transporte_val = (logistics.trailer_num or "") if logistics else ""
|
||||
|
||||
placas_val = (logistics.license_plate or "") if logistics else ""
|
||||
placas_remolque_val = ""
|
||||
transportista_val = (logistics.carrier_id or "") if logistics else ""
|
||||
caat_val = ""
|
||||
scac_val = ""
|
||||
licencia_cond_val = ""
|
||||
|
||||
if logistics:
|
||||
# 1. Transporter (CAAT / SCAC)
|
||||
if logistics.carrier_id:
|
||||
transporter_obj = db.query(Transporter).filter(Transporter.transporter_key == logistics.carrier_id).first()
|
||||
if transporter_obj:
|
||||
caat_val = transporter_obj.caat_code or ""
|
||||
scac_val = transporter_obj.transport_code or ""
|
||||
transportista_val = transporter_obj.name or logistics.carrier_id
|
||||
|
||||
# 2. Vehicle (Placas Tracto)
|
||||
if logistics.transport_id:
|
||||
veh_obj = db.query(Vehicle).filter(Vehicle.vehicle_key == logistics.transport_id).first()
|
||||
if veh_obj:
|
||||
placas_val = veh_obj.plate_number or placas_val
|
||||
elif logistics.vehicle_num:
|
||||
veh_obj = db.query(Vehicle).filter(Vehicle.vehicle_key == logistics.vehicle_num).first()
|
||||
if veh_obj:
|
||||
placas_val = veh_obj.plate_number or placas_val
|
||||
|
||||
# 3. Trailer (Placas Remolque)
|
||||
if logistics.trailer_num:
|
||||
trl_obj = db.query(Trailer).filter(Trailer.trailer_number == logistics.trailer_num).first()
|
||||
if trl_obj:
|
||||
placas_remolque_val = trl_obj.plate_number or ""
|
||||
|
||||
# 4. Driver (License)
|
||||
if logistics.carrier_id and logistics.driver_name:
|
||||
drv_obj = db.query(Driver).filter(
|
||||
Driver.transporter_key == logistics.carrier_id,
|
||||
Driver.driver_name == logistics.driver_name
|
||||
).first()
|
||||
if drv_obj:
|
||||
licencia_cond_val = drv_obj.license_number or ""
|
||||
|
||||
factura_schema = FacturaSchema(
|
||||
numero=header.invoice_number or "S/N",
|
||||
fecha=str(header.invoice_date) if header.invoice_date else "",
|
||||
tipo_cambio=float(financials.exchange_rate) if (financials and financials.exchange_rate) else (float(pedimento.exchange_rate) if pedimento and pedimento.exchange_rate else 1.0),
|
||||
moneda=getattr(header, 'currency', "USD") or "USD",
|
||||
incoterm=(logistics.incoterm or "") if logistics else "",
|
||||
observaciones=header.observation_es or header.observation_en or "",
|
||||
pedimento=f"{pedimento.year} {pedimento.customs_office[:2] if pedimento.customs_office else ''} {pedimento.license} {pedimento.pedimento_number}" if pedimento else "",
|
||||
clave_pedimento=pedimento.pedimento_code if pedimento else "",
|
||||
regimen=header.document_type or "",
|
||||
patente=patente_val,
|
||||
agente_aduanal=nombre_agente,
|
||||
transporte=transporte_txt,
|
||||
num_transporte=num_transporte_val,
|
||||
placas=placas_val,
|
||||
placas_remolque=placas_remolque_val,
|
||||
transportista=transportista_val,
|
||||
caat=caat_val,
|
||||
scac=scac_val,
|
||||
licencia_conductor=licencia_cond_val,
|
||||
aduana=compliance.aduana if (compliance and compliance.aduana) else (pedimento.customs_office[:2] if (pedimento and pedimento.customs_office) else ""),
|
||||
precinto=(logistics.seal_number or "") if logistics else "",
|
||||
destino=(logistics.destination_goods or "") if logistics else "",
|
||||
remesa=remesa_valor, acuse_electronico=acuse_valor
|
||||
)
|
||||
|
||||
if progress_callback: progress_callback(50, "Procesando partidas...")
|
||||
lines = db.query(LineItem).join(Item, LineItem.item_id == Item.id).filter(Item.invoice_id == header.id).all()
|
||||
partidas_list = []
|
||||
|
||||
for line in lines:
|
||||
qty = db.query(LineQuantity).filter(LineQuantity.item_line_id == line.id).first()
|
||||
part_master = db.query(Part).filter(Part.id == line.part_number).first()
|
||||
|
||||
desc_final = "S/D"
|
||||
num_parte_final = str(line.part_number or "S/N")
|
||||
fraccion_raw = ""
|
||||
origen_final = "MEX"
|
||||
|
||||
if part_master:
|
||||
desc_final = part_master.description_spanish or part_master.description_english or "Sin Desc."
|
||||
num_parte_final = part_master.part_number
|
||||
fraccion_raw = part_master.fraction if part_master.fraction else ""
|
||||
|
||||
if part_master.fa_data and part_master.fa_data.origin_country:
|
||||
origen_final = part_master.fa_data.origin_country
|
||||
|
||||
fraccion_limpia = fraccion_raw.replace(".", "").strip()
|
||||
if fraccion_limpia:
|
||||
fraccion_limpia = fraccion_limpia[:8].zfill(8)
|
||||
|
||||
fraccion_db = db.query(TariffFraction).filter(TariffFraction.code == fraccion_limpia).first()
|
||||
|
||||
fraccion_imprimir = fraccion_raw
|
||||
if fraccion_db:
|
||||
fraccion_imprimir = fraccion_db.fraction or fraccion_raw
|
||||
else:
|
||||
fraccion_imprimir = self._format_fraccion_fallback(fraccion_limpia)
|
||||
|
||||
# FOR PACKING LIST: FINANCIALS ARE HIDDEN/EMPTY
|
||||
v_unitario = ""
|
||||
v_total = ""
|
||||
|
||||
partidas_list.append(PartidaSchema(
|
||||
numero_parte=num_parte_final,
|
||||
descripcion=desc_final,
|
||||
fraccion=fraccion_imprimir,
|
||||
origen=origen_final,
|
||||
advalorem="", # Hidden
|
||||
preferencia="", # Hidden
|
||||
cantidad_importacion=qty.quantity if qty else 0,
|
||||
unidad_medida=qty.weight_unit if qty else "PZA",
|
||||
cantidad_bultos=int(qty.package_quantity) if qty and qty.package_quantity else 0,
|
||||
clave_bultos=(qty.package_key or "") if qty else "",
|
||||
peso_neto=qty.net_weight if qty else 0,
|
||||
peso_bruto=qty.gross_weight if qty else 0,
|
||||
valor_costo_unitario=v_unitario, # Hidden
|
||||
valor_total=v_total # Hidden
|
||||
))
|
||||
|
||||
totales = self.calcular_totales(partidas_list, Decimal(factura_schema.tipo_cambio))
|
||||
|
||||
return PackingListSchema(
|
||||
cliente_proveedor=cliente_proveedor, cliente_vendido=cliente_vendido,
|
||||
cliente_enviado=cliente_enviado, factura=factura_schema,
|
||||
partidas=partidas_list, totales=totales
|
||||
)
|
||||
|
||||
except ValidationError as e:
|
||||
print(f"Validation Error: {e.json()}")
|
||||
raise HTTPException(status_code=500, detail=f"Schema Error: {e}")
|
||||
except Exception as e:
|
||||
print(f"Error Service A76: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
|
||||
|
||||
def calcular_totales(self, partidas: List[PartidaSchema], tipo_cambio: Decimal) -> TotalesSchema:
|
||||
cant = sum(float(p.cantidad_importacion) for p in partidas)
|
||||
# Financial totals hidden
|
||||
peso_n = sum(float(p.peso_neto) for p in partidas)
|
||||
peso_b = sum(float(p.peso_bruto) for p in partidas)
|
||||
bultos = sum(p.cantidad_bultos for p in partidas)
|
||||
|
||||
claves = [p.clave_bultos for p in partidas if p.clave_bultos]
|
||||
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"
|
||||
|
||||
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="", valor_total_dolares=""
|
||||
)
|
||||
|
||||
def generate_pdf(self, db: Session, invoice_id: int, company_id: int, progress_callback: Optional[Callable] = None) -> Tuple[bytes, str]:
|
||||
if progress_callback: progress_callback(5, "Iniciando servicio de reporte...")
|
||||
data = self.get_packing_list_data(db, invoice_id, company_id, progress_callback)
|
||||
|
||||
if progress_callback: progress_callback(80, "Renderizando plantilla...")
|
||||
|
||||
# LOGO LOGIC
|
||||
logo_b64 = None
|
||||
try:
|
||||
comp_logo = db.query(Company).filter(Company.id == company_id).first()
|
||||
if comp_logo and comp_logo.logo:
|
||||
p = Path(comp_logo.logo)
|
||||
target_path = p
|
||||
if not target_path.exists():
|
||||
fallback = Path(f"app_data/logos/{company_id}") / p.name
|
||||
if fallback.exists():
|
||||
target_path = fallback
|
||||
|
||||
if target_path.exists():
|
||||
with open(target_path, "rb") as image_file:
|
||||
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
|
||||
mime = "image/png"
|
||||
if target_path.suffix.lower() in ['.jpg', '.jpeg']: mime = "image/jpeg"
|
||||
logo_b64 = f"data:{mime};base64,{encoded_string}"
|
||||
except Exception as e:
|
||||
print(f"Error loading logo: {e}")
|
||||
|
||||
data.logo_b64 = logo_b64 # Assign logo to schema
|
||||
|
||||
context = data.model_dump()
|
||||
html_content = self.template.render(**context)
|
||||
|
||||
if progress_callback: progress_callback(90, "Generando PDF final...")
|
||||
|
||||
options = {'page-size': 'Letter', 'margin-top': '0.5in', 'margin-right': '0.5in', 'margin-bottom': '0.5in', 'margin-left': '0.5in', 'encoding': "UTF-8", 'enable-local-file-access': None}
|
||||
pdf = pdfkit.from_string(html_content, False, options=options, configuration=self._get_wkhtmltopdf_config())
|
||||
|
||||
if progress_callback: progress_callback(100, "Completado")
|
||||
|
||||
filename = f"PackingList_{data.factura.numero}.pdf"
|
||||
return pdf, filename
|
||||
@@ -0,0 +1,51 @@
|
||||
import base64
|
||||
from core.celery_app import celery_app
|
||||
from core.database import CoreSessionLocal
|
||||
from .service import PackingListService
|
||||
|
||||
@celery_app.task(bind=True)
|
||||
def generar_packing_list_async(self, invoice_id: int, company_id: int):
|
||||
"""
|
||||
Tarea asíncrona para generar el Packing List
|
||||
"""
|
||||
db = CoreSessionLocal()
|
||||
try:
|
||||
service = PackingListService()
|
||||
|
||||
def update_progress(percent, message):
|
||||
self.update_state(
|
||||
state='PROCESSING',
|
||||
meta={
|
||||
'current': percent,
|
||||
'total': 100,
|
||||
'status': message
|
||||
}
|
||||
)
|
||||
|
||||
pdf_bytes, filename = service.generate_pdf(db, invoice_id, company_id, update_progress)
|
||||
|
||||
# Codificar a base64 para enviar por JSON
|
||||
pdf_b64 = base64.b64encode(pdf_bytes).decode('utf-8')
|
||||
|
||||
return {
|
||||
'status': 'success',
|
||||
'file_name': filename,
|
||||
'content': pdf_b64,
|
||||
'media_type': 'application/pdf'
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error en tarea Packing List: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
self.update_state(
|
||||
state='FAILURE',
|
||||
meta={
|
||||
'exc_type': type(e).__name__,
|
||||
'exc_message': str(e),
|
||||
'custom': 'Error generating PDF'
|
||||
}
|
||||
)
|
||||
raise e
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,615 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="es" xml:lang="es">
|
||||
|
||||
<head>
|
||||
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
|
||||
<title>Packing List - {{ factura.numero }}</title>
|
||||
<style type="text/css">
|
||||
/* ESTILOS EXACTOS DE SCAPII PARA MANTENER EL FORMATO */
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-family: Tahoma, sans-serif;
|
||||
color: black;
|
||||
}
|
||||
|
||||
.titulo {
|
||||
font-size: 14pt;
|
||||
padding: 3pt 0 0 6pt;
|
||||
}
|
||||
|
||||
.grande {
|
||||
font-size: 13pt;
|
||||
padding-left: 5pt;
|
||||
}
|
||||
|
||||
.medio-bold {
|
||||
font-size: 9pt;
|
||||
font-weight: bold;
|
||||
padding: 3pt 0 0 3pt;
|
||||
}
|
||||
|
||||
.normal {
|
||||
font-size: 8pt;
|
||||
}
|
||||
|
||||
.small-bold {
|
||||
font-size: 8pt;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.tiny-bold {
|
||||
font-size: 7pt;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.tiny {
|
||||
font-size: 7pt;
|
||||
}
|
||||
|
||||
.mini {
|
||||
font-size: 5pt;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-weight: bold;
|
||||
font-size: 8pt;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 7pt;
|
||||
}
|
||||
|
||||
.cliente {
|
||||
border-bottom: 1pt solid black;
|
||||
text-decoration: none;
|
||||
display: block;
|
||||
width: 100%
|
||||
}
|
||||
|
||||
.center {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.right {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.border {
|
||||
border: 1pt solid #808080;
|
||||
}
|
||||
|
||||
.p-t-1 {
|
||||
padding-top: 1pt;
|
||||
}
|
||||
|
||||
.p-t-2 {
|
||||
padding-top: 2pt;
|
||||
}
|
||||
|
||||
.p-t-3 {
|
||||
padding-top: 3pt;
|
||||
}
|
||||
|
||||
.p-t-4 {
|
||||
padding-top: 4pt;
|
||||
}
|
||||
|
||||
.p-t-5 {
|
||||
padding-top: 5pt;
|
||||
}
|
||||
|
||||
.p-t-8 {
|
||||
padding-top: 8pt;
|
||||
}
|
||||
|
||||
.p-t-9 {
|
||||
padding-top: 9pt;
|
||||
}
|
||||
|
||||
.p-l-2 {
|
||||
padding-left: 2pt;
|
||||
}
|
||||
|
||||
.p-l-3 {
|
||||
padding-left: 3pt;
|
||||
}
|
||||
|
||||
.p-l-5 {
|
||||
padding-left: 5pt;
|
||||
}
|
||||
|
||||
.p-l-6 {
|
||||
padding-left: 6pt;
|
||||
}
|
||||
|
||||
.p-l-7 {
|
||||
padding-left: 7pt;
|
||||
}
|
||||
|
||||
.p-l-8 {
|
||||
padding-left: 8pt;
|
||||
}
|
||||
|
||||
.p-l-9 {
|
||||
padding-left: 9pt;
|
||||
}
|
||||
|
||||
.p-l-10 {
|
||||
padding-left: 10pt;
|
||||
}
|
||||
|
||||
.p-r-1 {
|
||||
padding-right: 1pt;
|
||||
}
|
||||
|
||||
.p-r-2 {
|
||||
padding-right: 2pt;
|
||||
}
|
||||
|
||||
.p-r-4 {
|
||||
padding-right: 4pt;
|
||||
}
|
||||
|
||||
.p-r-5 {
|
||||
padding-right: 5pt;
|
||||
}
|
||||
|
||||
.p-r-9 {
|
||||
padding-right: 9pt;
|
||||
}
|
||||
|
||||
.p-b-1 {
|
||||
padding-bottom: 1pt;
|
||||
}
|
||||
|
||||
.h-10 {
|
||||
height: 10pt;
|
||||
}
|
||||
|
||||
.h-11 {
|
||||
height: 11pt;
|
||||
}
|
||||
|
||||
.h-14 {
|
||||
height: 14pt;
|
||||
}
|
||||
|
||||
.h-15 {
|
||||
height: 15pt;
|
||||
}
|
||||
|
||||
.h-18 {
|
||||
height: 18pt;
|
||||
}
|
||||
|
||||
.h-22 {
|
||||
height: 22pt;
|
||||
}
|
||||
|
||||
.h-82 {
|
||||
height: 82pt;
|
||||
}
|
||||
|
||||
.h-384 {
|
||||
height: 384pt;
|
||||
}
|
||||
|
||||
.line-1 {
|
||||
line-height: 1pt;
|
||||
}
|
||||
|
||||
.line-7 {
|
||||
line-height: 7pt;
|
||||
}
|
||||
|
||||
.line-8 {
|
||||
line-height: 8pt;
|
||||
}
|
||||
|
||||
.line-9 {
|
||||
line-height: 9pt;
|
||||
}
|
||||
|
||||
.line-10 {
|
||||
line-height: 10pt;
|
||||
}
|
||||
|
||||
.m-l-3 {
|
||||
margin-left: 3pt;
|
||||
}
|
||||
|
||||
.m-l-5 {
|
||||
margin-left: 5.74pt;
|
||||
}
|
||||
|
||||
.flex-container {
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.flex-container-end {
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.width-48 {
|
||||
width: 48%;
|
||||
float: left;
|
||||
}
|
||||
|
||||
.width-48-right {
|
||||
width: 48%;
|
||||
float: right;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.position-relative-centered {
|
||||
position: relative;
|
||||
width: 48%;
|
||||
float: left;
|
||||
}
|
||||
|
||||
.full-width-block {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.clearfix::after {
|
||||
content: "";
|
||||
display: table;
|
||||
clear: both;
|
||||
}
|
||||
|
||||
table,
|
||||
tbody {
|
||||
vertical-align: top;
|
||||
overflow: visible;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<header>
|
||||
<div class="flex-container clearfix">
|
||||
<div class="width-48" style="position: relative;">
|
||||
<p class="titulo">PACKING LIST / LISTA DE EMPAQUE</p>
|
||||
<div class="cliente" style="height: 1px;"></div>
|
||||
<p class="cliente p-t-1 p-b-1"></p>
|
||||
</div>
|
||||
<div class="width-48-right">
|
||||
<p class="p-l-5 line-1"><span></span></p>
|
||||
<p class="p-t-2"><br></p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-container-end clearfix" style="overflow: visible;">
|
||||
<div class="position-relative-centered">
|
||||
{% if logo_b64 %}
|
||||
<div style="position: absolute; top: 10pt; left: 0;">
|
||||
<img src="{{ logo_b64 }}" style="max-height: 70pt; max-width: 120pt;" />
|
||||
</div>
|
||||
{% endif %}
|
||||
<div style="margin-left: 130pt; padding-top: 25pt; text-align: left;">
|
||||
<h1 class="cliente">{{ cliente_proveedor.header }}</h1>
|
||||
<p>{{ cliente_proveedor.nombre }}</p>
|
||||
<p>{{ cliente_proveedor.direccion }}
|
||||
{% if cliente_proveedor.num_exterior %} Ext: {{ cliente_proveedor.num_exterior }}{% endif %}
|
||||
{% if cliente_proveedor.num_interior %} Int: {{ cliente_proveedor.num_interior }}{% endif %}
|
||||
</p>
|
||||
<p>{{ cliente_proveedor.colonia }} {% if cliente_proveedor.codigo_postal %} CP: {{
|
||||
cliente_proveedor.codigo_postal }}{% endif %}</p>
|
||||
<p>{{ cliente_proveedor.ciudad }}, {{ cliente_proveedor.estado }}, {{ cliente_proveedor.pais }}</p>
|
||||
<p>TAX ID: {{ cliente_proveedor.tax_id }}
|
||||
{% if cliente_proveedor.programa and cliente_proveedor.programa != 'Ninguno' %}
|
||||
{{ cliente_proveedor.programa }}: {{ cliente_proveedor.autorizacion }}
|
||||
{% endif %}
|
||||
</p>
|
||||
<p><br></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="position: relative;">
|
||||
<table cellspacing="0" class="m-l-3" style="float: right; text-align: left;">
|
||||
<tbody>
|
||||
<tr class="h-18">
|
||||
<td bgcolor="#E4E4E4" class="border" style="width:52pt">
|
||||
<p class="medio-bold">FACTURA:</p>
|
||||
</td>
|
||||
<td class="border" colspan="3" style="width:176pt">
|
||||
<p class="grande">{{ factura.numero }}</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="h-11">
|
||||
<td bgcolor="#E4E4E4" class="border" style="width:52pt">
|
||||
<p class="normal p-l-3 line-9">Fecha:</p>
|
||||
</td>
|
||||
<td class="border" style="width:72pt">
|
||||
<p class="normal p-l-2 line-9">{{ factura.fecha }}</p>
|
||||
</td>
|
||||
<td bgcolor="#E4E4E4" class="border" style="width:52pt">
|
||||
<p class="normal p-l-2 line-9">T. Cambio:</p>
|
||||
</td>
|
||||
<td class="border" style="width:52pt">
|
||||
<p class="normal center line-9">{{ factura.tipo_cambio }}</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="h-11">
|
||||
<td bgcolor="#E4E4E4" class="border" style="width:52pt">
|
||||
<p class="small-bold p-l-3 line-9">Pedimento:</p>
|
||||
</td>
|
||||
<td class="border" colspan="1" style="width:109pt">
|
||||
<p class="normal p-l-3 line-9">{{ factura.pedimento or '' }}</p>
|
||||
</td>
|
||||
<td bgcolor="#E4E4E4" class="border">
|
||||
<p class="normal p-l-3 line-9">Clave:</p>
|
||||
</td>
|
||||
<td class="border" style="width:37pt">
|
||||
<p class="normal p-r-2 line-9 center">{{ factura.clave_pedimento or '' }}</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="h-11">
|
||||
<td bgcolor="#E4E4E4" class="border" style="width:52pt">
|
||||
<p class="normal p-l-3 line-9">Remesa:</p>
|
||||
</td>
|
||||
<td class="border" style="width:38pt">
|
||||
<p class="normal p-l-10 line-9">{{ factura.remesa or '' }}</p>
|
||||
</td>
|
||||
<td bgcolor="#E4E4E4" class="border" style="width:79pt">
|
||||
<p class="normal p-l-6 line-9">Acuse:</p>
|
||||
</td>
|
||||
<td class="border" style="width:59pt">
|
||||
<p class="normal p-l-6 line-9">{{ factura.acuse_electronico or 'N/A' }}</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="h-22">
|
||||
<td class="border" colspan="4" style="width:228pt">
|
||||
<p class="small-bold p-l-3 line-7">Agente Aduanal:</p>
|
||||
<p class="normal p-l-3 line-7">{{ factura.agente_aduanal or '' }}</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="h-15">
|
||||
<td class="border" colspan="2">
|
||||
<p><span class="small-bold p-l-3 line-7">Patente: </span><span
|
||||
class="normal p-l-3 line-7">{{ factura.patente or '' }}</span></p>
|
||||
</td>
|
||||
<td class="border">
|
||||
<span class="tiny-bold p-l-3 line-7">Regimen:</span><span class="tiny p-l-3 line-7">{{
|
||||
factura.regimen or '' }}</span>
|
||||
</td>
|
||||
<td class="border">
|
||||
<p class="tiny-bold p-l-3 line-7">INCOTERM:</p>
|
||||
<p class="tiny p-l-3 line-7">{{ factura.incoterm or '' }}</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="border" colspan="2">
|
||||
{% if factura.precinto %}
|
||||
<p class="tiny-bold p-l-3 line-7">Precinto: {{ factura.precinto }}</p>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td class="border">
|
||||
<p class="tiny-bold p-l-3 line-7">Aduana: {{ factura.aduana or '' }}</p>
|
||||
</td>
|
||||
<td class="border">
|
||||
{% if factura.destino %}
|
||||
<p class="tiny-bold p-l-3 line-7">Destino: {{ factura.destino }}</p>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex-container clearfix">
|
||||
<div class="width-48">
|
||||
<h1 class="p-t-5 p-l-5 line-10 cliente">{{ cliente_vendido.header }}</h1>
|
||||
<p class="p-l-5 line-8">{{ cliente_vendido.nombre }}</p>
|
||||
<p class="p-l-5">{{ cliente_vendido.direccion }}
|
||||
{% if cliente_vendido.num_exterior %} Ext: {{ cliente_vendido.num_exterior }}{% endif %}
|
||||
{% if cliente_vendido.num_interior %} Int: {{ cliente_vendido.num_interior }}{% endif %}
|
||||
</p>
|
||||
<p class="p-l-5">{{ cliente_vendido.colonia }} {% if cliente_vendido.codigo_postal %} CP: {{
|
||||
cliente_vendido.codigo_postal }}{% endif %}</p>
|
||||
<p class="p-l-5">{{ cliente_vendido.ciudad }}, {{ cliente_vendido.estado }}, {{ cliente_vendido.pais }}
|
||||
</p>
|
||||
<p class="p-l-5">RFC: {{ cliente_vendido.tax_id }}
|
||||
{% if cliente_vendido.programa and cliente_vendido.programa != 'Ninguno' %}
|
||||
{{ cliente_vendido.programa }}: {{ cliente_vendido.autorizacion }}
|
||||
{% endif %}
|
||||
</p>
|
||||
<p class="p-l-5">
|
||||
{% if cliente_vendido.prosec %}PROSEC: {{ cliente_vendido.prosec }} {% endif %}
|
||||
{% if cliente_vendido.reg_emp %}REG EMP: {{ cliente_vendido.reg_emp }} {% endif %}
|
||||
{% if cliente_vendido.cert %}CERT: {{ cliente_vendido.cert }}{% endif %}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="width-48-right" style="text-align: left;">
|
||||
<h1 class="p-t-5 p-l-5 line-10 cliente full-width-block">{{ cliente_enviado.header }}</h1>
|
||||
<p class="p-l-5 line-8">{{ cliente_enviado.nombre }}</p>
|
||||
<p class="p-l-5">{{ cliente_enviado.direccion }}
|
||||
{% if cliente_enviado.num_exterior %} Ext: {{ cliente_enviado.num_exterior }}{% endif %}
|
||||
{% if cliente_enviado.num_interior %} Int: {{ cliente_enviado.num_interior }}{% endif %}
|
||||
</p>
|
||||
<p class="p-l-5">{{ cliente_enviado.colonia }} {% if cliente_enviado.codigo_postal %} CP: {{
|
||||
cliente_enviado.codigo_postal }}{% endif %}</p>
|
||||
<p class="p-l-5">{{ cliente_enviado.ciudad }}, {{ cliente_enviado.estado }}, {{ cliente_enviado.pais }}
|
||||
</p>
|
||||
<p class="p-l-5">RFC: {{ cliente_enviado.tax_id }}
|
||||
{% if cliente_enviado.programa and cliente_enviado.programa != 'Ninguno' %}
|
||||
{{ cliente_enviado.programa }}: {{ cliente_enviado.autorizacion }}
|
||||
{% endif %}
|
||||
</p>
|
||||
<p class="p-l-5">
|
||||
{% if cliente_enviado.prosec %}PROSEC: {{ cliente_enviado.prosec }} {% endif %}
|
||||
{% if cliente_enviado.reg_emp %}REG EMP: {{ cliente_enviado.reg_emp }} {% endif %}
|
||||
{% if cliente_enviado.cert %}CERT: {{ cliente_enviado.cert }}{% endif %}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<p class="p-t-8"><br /></p>
|
||||
</header>
|
||||
|
||||
<table cellspacing="0" class="m-l-5" style="width: 99%; max-width: 580pt;">
|
||||
<thead>
|
||||
<tr class="h-10">
|
||||
<td bgcolor="#E4E4E4" class="border" style="width:60pt">
|
||||
<p class="tiny line-9">Transportista:</p>
|
||||
</td>
|
||||
<td class="border" colspan="4" style="width:120pt">
|
||||
<p class="tiny">{{ factura.transportista or '' }}</p>
|
||||
</td>
|
||||
<td class="border" style="width:40pt">
|
||||
<p class="tiny">SCAC: {{ factura.scac or '' }}</p>
|
||||
</td>
|
||||
<td bgcolor="#E4E4E4" class="border" style="width:40pt">
|
||||
<p class="tiny">INCOTERM:</p>
|
||||
</td>
|
||||
<td class="border" style="width:40pt">
|
||||
<p class="tiny">{{ factura.incoterm or '' }}</p>
|
||||
</td>
|
||||
<td class="border" colspan="2" style="width:70pt">
|
||||
<p class="tiny line-9">Aduana: <span class="mini">{{ factura.aduana or '' }}</span></p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="h-10">
|
||||
<td bgcolor="#E4E4E4" class="border" style="width:60pt">
|
||||
<p class="tiny line-9">Transporte:</p>
|
||||
</td>
|
||||
<td class="border" colspan="4" style="width:120pt">
|
||||
<p class="tiny">{{ factura.transporte or '' }}: {{ factura.num_transporte or '' }}</p>
|
||||
</td>
|
||||
<td class="border" colspan="3" style="width:80pt">
|
||||
<p class="tiny">CAAT: {{ factura.caat or '' }}</p>
|
||||
</td>
|
||||
<td class="border" colspan="2" style="width:100pt">
|
||||
<p class="tiny p-t-1 line-8">Placas: {{ factura.placas or '' }} / Rem: {{ factura.placas_remolque or
|
||||
'' }}</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="h-10">
|
||||
<td bgcolor="#E4E4E4" class="border" colspan="2" style="width:80pt">
|
||||
<p class="tiny p-l-1 line-9">Chofer/Licencia:</p>
|
||||
</td>
|
||||
<td class="border" colspan="8">
|
||||
<p class="tiny p-l-3">{{ factura.licencia_conductor or 'N/A' }}</p>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr class="h-10">
|
||||
<td class="border" rowspan="2">
|
||||
<p class="tiny-bold p-t-5 center">Línea</p>
|
||||
</td>
|
||||
<td class="border" rowspan="2" colspan="2">
|
||||
<p class="tiny-bold p-l-2 line-10">Número de Parte</p>
|
||||
<p class="tiny-bold p-l-2 line-10">Descripción</p>
|
||||
</td>
|
||||
<td class="border" colspan="2">
|
||||
<p class="tiny-bold center line-9">Comercial</p>
|
||||
</td>
|
||||
<td class="border" style="width:50pt">
|
||||
<p class="tiny-bold center line-9">Empaque</p>
|
||||
</td>
|
||||
<td class="border" colspan="2">
|
||||
<p class="tiny-bold center line-9">Peso (KGS)</p>
|
||||
</td>
|
||||
<!-- COLUMNA VALORES REMOVIDA -->
|
||||
</tr>
|
||||
<tr class="h-11">
|
||||
<!-- Subheaders -->
|
||||
<td class="border center">
|
||||
<p class="mini p-l-2">Cantidad</p>
|
||||
</td>
|
||||
<td class="border center">
|
||||
<p class="mini p-l-1">U.M.</p>
|
||||
</td>
|
||||
<td class="border">
|
||||
<p class="mini center">Tipo</p>
|
||||
</td>
|
||||
<td class="border">
|
||||
<p class="mini center">Neto</p>
|
||||
</td>
|
||||
<td class="border">
|
||||
<p class="mini center">Bruto</p>
|
||||
</td>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody class="h-384" style="width: 100%;">
|
||||
{% for partida in partidas %}
|
||||
<tr>
|
||||
<td class="border" style="width: 25pt;">
|
||||
<p class="mini p-t-3 center">{{ loop.index }}</p>
|
||||
</td>
|
||||
<td class="border" colspan="2">
|
||||
<p class="mini p-t-1" style="font-weight: bold;">{{ partida.numero_parte }}</p>
|
||||
<p class="mini">{{ partida.descripcion }}</p>
|
||||
</td>
|
||||
<td class="border">
|
||||
<p class="mini p-t-2 center">{{ partida.cantidad_importacion }}</p>
|
||||
</td>
|
||||
<td class="border">
|
||||
<p class="mini p-t-2 center">{{ partida.unidad_medida }}</p>
|
||||
</td>
|
||||
<td class="border">
|
||||
<p class="mini p-t-2 center">
|
||||
{% if partida.cantidad_bultos != 0 %}{{ partida.cantidad_bultos }}{% endif %}
|
||||
{{ partida.clave_bultos }}
|
||||
</p>
|
||||
</td>
|
||||
<td class="border">
|
||||
<p class="mini p-t-3 center">{{ partida.peso_neto }}</p>
|
||||
</td>
|
||||
<td class="border">
|
||||
<p class="mini p-t-3 center">{{ partida.peso_bruto }}</p>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
|
||||
<tfoot>
|
||||
<tr class="h-14">
|
||||
<td bgcolor="#E4E4E4" class="border" colspan="3" style="width:123pt">
|
||||
<p class="small-bold p-t-2 p-l-3 line-10">
|
||||
<span>Observaciones:</span>
|
||||
<span class="small-bold" style="float: right; margin-right: 2pt;">TOTALES</span>
|
||||
</p>
|
||||
</td>
|
||||
<td class="border" style="width:40pt">
|
||||
<p class="tiny p-t-5 p-r-1 line-8 center">{{ totales.cantidad_total }}</p>
|
||||
</td>
|
||||
<td class="border" style="width:22pt"></td>
|
||||
<td class="border" style="width:40pt">
|
||||
<p class="tiny p-t-4 center line-8">
|
||||
{% if totales.bultos_total != 0 %}{{ totales.bultos_total }}{% endif %}
|
||||
<span>{{ totales.clave_bultos or '' }}</span>
|
||||
</p>
|
||||
</td>
|
||||
<td class="border" style="width:40pt">
|
||||
<p class="tiny p-t-5 center line-8">{{ totales.peso_neto_total }}</p>
|
||||
</td>
|
||||
<td class="border" style="width:40pt">
|
||||
<p class="tiny p-t-5 center line-8">{{ totales.peso_bruto_total }}</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="3" class="border" style="height: 100pt; text-align:start; vertical-align: top;">
|
||||
<p class="mini p-l-2 p-t-2">{{ factura.observaciones }}</p>
|
||||
</td>
|
||||
<td colspan="5" style="width:336pt; vertical-align: bottom; height: 100%;">
|
||||
<p style="border-bottom: 1pt solid black; width: 80%; margin: 0 auto 2pt auto;"></p>
|
||||
<p class="normal center" style="margin-bottom: 0;">{{ cliente_proveedor.nombre }}</p>
|
||||
<p style="margin-bottom: 0;"><br /></p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="10" style="width:580pt; vertical-align: top; height: 100%;">
|
||||
<p class="p-t-8"><br /></p>
|
||||
</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -51,6 +51,8 @@ from api.v1.modules.public.reference_data.material_types.routes import router as
|
||||
# --- NUEVO IMPORT PARA REPORTES DE FACTURAS ---
|
||||
from .reports.importacion.facturas.routes import router as invoices_reports_router
|
||||
from .reports.importacion.consolidados.routes import router as consolidated_reports_router
|
||||
from .reports.importacion.packing_list.routes import router as packing_list_router
|
||||
|
||||
|
||||
|
||||
# Router principal
|
||||
@@ -130,4 +132,10 @@ router.include_router(
|
||||
consolidated_reports_router,
|
||||
prefix="/a76/reports/importacion/consolidados",
|
||||
tags=["a76 / reports"]
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
packing_list_router,
|
||||
prefix="/a76/reports/importacion/packing-lists",
|
||||
tags=["a76 / reports"]
|
||||
)
|
||||
@@ -10,7 +10,8 @@ celery_app = Celery(
|
||||
backend=valkey_url,
|
||||
include=[
|
||||
"api.v1.modules.a76.reports.importacion.facturas.task",
|
||||
"api.v1.modules.a76.reports.importacion.consolidados.task"
|
||||
"api.v1.modules.a76.reports.importacion.consolidados.task",
|
||||
"api.v1.modules.a76.reports.importacion.packing_list.task"
|
||||
] # Ruta al módulo donde están las tareas
|
||||
)
|
||||
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
|
||||
const BASE_URL = import.meta.env.VITE_API_URL || '';
|
||||
const BASE_URL = import.meta.env.VITE_API_URL || '';
|
||||
|
||||
export const invoicesReportsApi = {
|
||||
|
||||
|
||||
triggerPdfGeneration: async (invoiceId: number, companyId: number) => {
|
||||
const params = new URLSearchParams({ company_id: companyId.toString() });
|
||||
const endpoint = `${BASE_URL}/v1/a76/reports/importacion/facturas/${invoiceId}/download-async?${params.toString()}`;
|
||||
|
||||
|
||||
const token = localStorage.getItem('access_token');
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'Content-Type': 'application/json'
|
||||
@@ -17,12 +17,12 @@ export const invoicesReportsApi = {
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error('Error al iniciar la generación');
|
||||
return await response.json();
|
||||
return await response.json();
|
||||
},
|
||||
|
||||
getTaskStatus: async (taskId: string) => {
|
||||
const endpoint = `${BASE_URL}/v1/a76/reports/importacion/facturas/tasks/${taskId}`;
|
||||
|
||||
const endpoint = `${BASE_URL}/v1/a76/reports/importacion/facturas/tasks/${taskId}`;
|
||||
|
||||
const token = localStorage.getItem('access_token');
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'GET',
|
||||
@@ -31,5 +31,35 @@ export const invoicesReportsApi = {
|
||||
|
||||
if (!response.ok) throw new Error('Error al consultar estado');
|
||||
return await response.json();
|
||||
},
|
||||
|
||||
triggerPackingListGeneration: async (invoiceId: number, companyId: number) => {
|
||||
const params = new URLSearchParams({ company_id: companyId.toString() });
|
||||
const endpoint = `${BASE_URL}/v1/a76/reports/importacion/packing-lists/${invoiceId}/download-async?${params.toString()}`;
|
||||
|
||||
const token = localStorage.getItem('access_token');
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error('Error al iniciar la generación de Packing List');
|
||||
return await response.json();
|
||||
},
|
||||
|
||||
getPackingListTaskStatus: async (taskId: string) => {
|
||||
const endpoint = `${BASE_URL}/v1/a76/reports/importacion/packing-lists/tasks/${taskId}`;
|
||||
|
||||
const token = localStorage.getItem('access_token');
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'GET',
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error('Error al consultar estado de Packing List');
|
||||
return await response.json();
|
||||
}
|
||||
};
|
||||
@@ -63,9 +63,12 @@
|
||||
}
|
||||
else if (response.state === 'FAILURE') {
|
||||
hasError = true;
|
||||
statusMessage = "Error al generar el PDF";
|
||||
// Intenta mostrar el mensaje de error real si viene en 'result'
|
||||
const errMsg = response.result ? String(response.result) : "Error desconocido";
|
||||
statusMessage = `Error: ${errMsg}`;
|
||||
stopPolling();
|
||||
toast.error("Falló la generación del PDF");
|
||||
toast.error(`Falló la generación: ${errMsg}`);
|
||||
console.error("Task failed with result:", response);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error polling task status:", error);
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
import type { PageData } from './$types';
|
||||
import { browser } from '$app/environment';
|
||||
import { companyStore } from '$lib/stores/company.svelte';
|
||||
import { Plus, RefreshCw, FileText, RotateCcw, Boxes } from 'lucide-svelte';
|
||||
import { Plus, RefreshCw, FileText, RotateCcw, Boxes, Package } from 'lucide-svelte';
|
||||
|
||||
// IMPORTANTE: Asegúrate de tener instalada svelte-sonner para las notificaciones
|
||||
import { toast } from "svelte-sonner";
|
||||
@@ -394,6 +394,32 @@
|
||||
console.error(error);
|
||||
toast.error("No se pudo iniciar la descarga del consolidado");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
async function handleDownloadPackingList(invoice: any) {
|
||||
if (!companyStore.activeCompany) {
|
||||
toast.error("No hay empresa seleccionada");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 1. Trigger: Start task in Celery
|
||||
const { task_id } = await invoicesReportsApi.triggerPackingListGeneration(
|
||||
invoice.id,
|
||||
companyStore.activeCompany.id
|
||||
);
|
||||
|
||||
// 2. Open progress dialog
|
||||
currentTaskId = task_id;
|
||||
// Use the specific status function for Packing List
|
||||
currentStatusFunction = invoicesReportsApi.getPackingListTaskStatus;
|
||||
showProgressDialog = true;
|
||||
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
toast.error("No se pudo iniciar la descarga del Packing List");
|
||||
}
|
||||
}
|
||||
|
||||
function onPdfComplete(result: any) {
|
||||
@@ -633,6 +659,10 @@
|
||||
<Boxes class="h-4 w-4 mr-2" />
|
||||
Consolidado
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onclick={() => selectedInvoice && handleDownloadPackingList(selectedInvoice)} disabled={!selectedInvoice}>
|
||||
<Package class="h-4 w-4 mr-2" />
|
||||
Packing List
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
7
frontend/test_bits.js
Normal file
7
frontend/test_bits.js
Normal file
@@ -0,0 +1,7 @@
|
||||
import { Dialog } from "bits-ui";
|
||||
console.log("Dialog is:", Dialog);
|
||||
try {
|
||||
console.log("Dialog.Root is:", Dialog.Root);
|
||||
} catch (e) {
|
||||
console.log("Error accessing Dialog.Root:", e.message);
|
||||
}
|
||||
Reference in New Issue
Block a user