Cooreegido la exportacion de pdf cuando se edita una checklist ahora si se edita algo de la inspeccion hecha se actualiza el PDF
This commit is contained in:
@@ -203,7 +203,7 @@ def send_completed_inspection_to_n8n(inspection, db):
|
||||
# No lanzamos excepción para no interrumpir el flujo normal
|
||||
|
||||
|
||||
BACKEND_VERSION = "1.0.25"
|
||||
BACKEND_VERSION = "1.0.27"
|
||||
app = FastAPI(title="Checklist Inteligente API", version=BACKEND_VERSION)
|
||||
|
||||
# S3/MinIO configuration
|
||||
@@ -1043,31 +1043,11 @@ def update_inspection(
|
||||
return db_inspection
|
||||
|
||||
|
||||
@app.post("/api/inspections/{inspection_id}/complete", response_model=schemas.Inspection)
|
||||
def complete_inspection(
|
||||
inspection_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: models.User = Depends(get_current_user)
|
||||
):
|
||||
inspection = db.query(models.Inspection).filter(
|
||||
models.Inspection.id == inspection_id
|
||||
).first()
|
||||
|
||||
if not inspection:
|
||||
raise HTTPException(status_code=404, detail="Inspección no encontrada")
|
||||
|
||||
# Calcular score
|
||||
answers = db.query(models.Answer).filter(models.Answer.inspection_id == inspection_id).all()
|
||||
total_score = sum(a.points_earned for a in answers)
|
||||
flagged_count = sum(1 for a in answers if a.is_flagged)
|
||||
|
||||
inspection.score = total_score
|
||||
inspection.percentage = (total_score / inspection.max_score * 100) if inspection.max_score > 0 else 0
|
||||
inspection.flagged_items_count = flagged_count
|
||||
inspection.status = "completed"
|
||||
inspection.completed_at = datetime.utcnow()
|
||||
|
||||
# Generar PDF profesional con diseño mejorado
|
||||
def generate_inspection_pdf(inspection_id: int, db: Session) -> str:
|
||||
"""
|
||||
Genera el PDF de una inspección y lo sube a S3.
|
||||
Retorna la URL del PDF generado.
|
||||
"""
|
||||
from reportlab.lib.pagesizes import A4
|
||||
from reportlab.lib import colors
|
||||
from reportlab.lib.units import inch, mm
|
||||
@@ -1077,6 +1057,10 @@ def complete_inspection(
|
||||
from io import BytesIO
|
||||
import requests
|
||||
|
||||
inspection = db.query(models.Inspection).filter(models.Inspection.id == inspection_id).first()
|
||||
if not inspection:
|
||||
raise HTTPException(status_code=404, detail="Inspección no encontrada")
|
||||
|
||||
buffer = BytesIO()
|
||||
doc = SimpleDocTemplate(
|
||||
buffer,
|
||||
@@ -1354,7 +1338,9 @@ def complete_inspection(
|
||||
print(f"❌ Error al generar PDF: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
raise HTTPException(status_code=500, detail=f"Error al generar PDF: {str(e)}")
|
||||
|
||||
# Subir a S3
|
||||
buffer.seek(0)
|
||||
now = datetime.now()
|
||||
folder = f"{now.year}/{now.month:02d}"
|
||||
@@ -1363,6 +1349,37 @@ def complete_inspection(
|
||||
buffer.seek(0)
|
||||
s3_client.upload_fileobj(buffer, S3_PDF_BUCKET, s3_key, ExtraArgs={"ContentType": "application/pdf"})
|
||||
pdf_url = f"{S3_ENDPOINT}/{S3_PDF_BUCKET}/{s3_key}"
|
||||
|
||||
print(f"✅ PDF generado y subido a S3: {pdf_url}")
|
||||
return pdf_url
|
||||
|
||||
|
||||
@app.post("/api/inspections/{inspection_id}/complete", response_model=schemas.Inspection)
|
||||
def complete_inspection(
|
||||
inspection_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: models.User = Depends(get_current_user)
|
||||
):
|
||||
inspection = db.query(models.Inspection).filter(
|
||||
models.Inspection.id == inspection_id
|
||||
).first()
|
||||
|
||||
if not inspection:
|
||||
raise HTTPException(status_code=404, detail="Inspección no encontrada")
|
||||
|
||||
# Calcular score
|
||||
answers = db.query(models.Answer).filter(models.Answer.inspection_id == inspection_id).all()
|
||||
total_score = sum(a.points_earned for a in answers)
|
||||
flagged_count = sum(1 for a in answers if a.is_flagged)
|
||||
|
||||
inspection.score = total_score
|
||||
inspection.percentage = (total_score / inspection.max_score * 100) if inspection.max_score > 0 else 0
|
||||
inspection.flagged_items_count = flagged_count
|
||||
inspection.status = "completed"
|
||||
inspection.completed_at = datetime.utcnow()
|
||||
|
||||
# Generar PDF usando función reutilizable
|
||||
pdf_url = generate_inspection_pdf(inspection_id, db)
|
||||
inspection.pdf_url = pdf_url
|
||||
db.commit()
|
||||
db.refresh(inspection)
|
||||
@@ -1492,6 +1509,14 @@ def update_answer(
|
||||
if not db_answer:
|
||||
raise HTTPException(status_code=404, detail="Respuesta no encontrada")
|
||||
|
||||
# Obtener la inspección para verificar si está completada
|
||||
inspection = db.query(models.Inspection).filter(
|
||||
models.Inspection.id == db_answer.inspection_id
|
||||
).first()
|
||||
|
||||
if not inspection:
|
||||
raise HTTPException(status_code=404, detail="Inspección no encontrada")
|
||||
|
||||
# Recalcular puntos si cambió el status
|
||||
if answer.status and answer.status != db_answer.status:
|
||||
question = db.query(models.Question).filter(
|
||||
@@ -1510,6 +1535,32 @@ def update_answer(
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_answer)
|
||||
|
||||
# Si la inspección está completada, regenerar PDF con los cambios
|
||||
if inspection.status == "completed":
|
||||
print(f"🔄 Regenerando PDF para inspección completada #{inspection.id}")
|
||||
|
||||
# Recalcular score de la inspección
|
||||
answers = db.query(models.Answer).filter(
|
||||
models.Answer.inspection_id == inspection.id
|
||||
).all()
|
||||
|
||||
inspection.score = sum(a.points_earned for a in answers)
|
||||
inspection.percentage = (inspection.score / inspection.max_score * 100) if inspection.max_score > 0 else 0
|
||||
inspection.flagged_items_count = sum(1 for a in answers if a.is_flagged)
|
||||
|
||||
# Regenerar PDF
|
||||
try:
|
||||
pdf_url = generate_inspection_pdf(inspection.id, db)
|
||||
inspection.pdf_url = pdf_url
|
||||
db.commit()
|
||||
print(f"✅ PDF regenerado exitosamente: {pdf_url}")
|
||||
except Exception as e:
|
||||
print(f"❌ Error regenerando PDF: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
# No lanzamos excepción para no interrumpir la actualización de la respuesta
|
||||
|
||||
return db_answer
|
||||
|
||||
|
||||
@@ -1646,6 +1697,35 @@ def admin_edit_answer(
|
||||
db.commit()
|
||||
db.refresh(db_answer)
|
||||
|
||||
# Si la inspección está completada, regenerar PDF con los cambios
|
||||
inspection = db.query(models.Inspection).filter(
|
||||
models.Inspection.id == db_answer.inspection_id
|
||||
).first()
|
||||
|
||||
if inspection and inspection.status == "completed":
|
||||
print(f"🔄 Regenerando PDF para inspección completada #{inspection.id} (admin-edit)")
|
||||
|
||||
# Recalcular score de la inspección
|
||||
answers = db.query(models.Answer).filter(
|
||||
models.Answer.inspection_id == inspection.id
|
||||
).all()
|
||||
|
||||
inspection.score = sum(a.points_earned for a in answers)
|
||||
inspection.percentage = (inspection.score / inspection.max_score * 100) if inspection.max_score > 0 else 0
|
||||
inspection.flagged_items_count = sum(1 for a in answers if a.is_flagged)
|
||||
|
||||
# Regenerar PDF
|
||||
try:
|
||||
pdf_url = generate_inspection_pdf(inspection.id, db)
|
||||
inspection.pdf_url = pdf_url
|
||||
db.commit()
|
||||
print(f"✅ PDF regenerado exitosamente: {pdf_url}")
|
||||
except Exception as e:
|
||||
print(f"❌ Error regenerando PDF: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
# No lanzamos excepción para no interrumpir la actualización de la respuesta
|
||||
|
||||
return db_answer
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user