|
| 1 | +from pathlib import Path |
| 2 | +from sqlite3 import IntegrityError |
| 3 | +from fastapi import APIRouter, Depends, HTTPException |
| 4 | +from fastapi.responses import FileResponse |
| 5 | +from sqlmodel import Session, select |
| 6 | +from api.deps import get_db |
| 7 | +from api.schemas.report_class import ( |
| 8 | + ReportSchemaCreate, |
| 9 | + ReportSchemaUpdate, |
| 10 | + ReportSchemaResponse, |
| 11 | + TemplateAssociation, |
| 12 | + SchemaFieldResponse, |
| 13 | + SchemaFieldUpdate, |
| 14 | + CanonicalSchema, |
| 15 | + ReportFill, |
| 16 | + ReportFillResponse, |
| 17 | + FormSubmissionResponse, |
| 18 | +) |
| 19 | +from api.db import repositories as repo |
| 20 | +from api.db.models import ReportSchema |
| 21 | +from src.report_schema import ReportSchemaProcessor |
| 22 | +from src.controller import Controller |
| 23 | +from api.db.models import FormSubmission, ReportSchemaTemplate |
| 24 | +from sqlalchemy.exc import IntegrityError |
| 25 | + |
| 26 | +router = APIRouter(prefix="/schemas", tags=["schemas"]) |
| 27 | + |
| 28 | + |
| 29 | +@router.post("/create", response_model=ReportSchemaResponse) |
| 30 | +def create_schema(data: ReportSchemaCreate, db: Session = Depends(get_db)): |
| 31 | + schema = ReportSchema(**data.model_dump()) |
| 32 | + try: |
| 33 | + return repo.create_report_schema(db, schema) |
| 34 | + except IntegrityError: |
| 35 | + raise HTTPException( |
| 36 | + status_code=409, |
| 37 | + detail="A schema with this name already exists" |
| 38 | + ) |
| 39 | + |
| 40 | +@router.get("/", response_model=list[ReportSchemaResponse]) |
| 41 | +def list_schemas(db: Session = Depends(get_db)): |
| 42 | + return repo.list_report_schemas(db) |
| 43 | + |
| 44 | +@router.get("/{schema_id}", response_model=ReportSchemaResponse) |
| 45 | +def get_schema(schema_id: int, db: Session = Depends(get_db)): |
| 46 | + schema = repo.get_report_schema(db, schema_id) |
| 47 | + if not schema: |
| 48 | + raise HTTPException(status_code=404, detail="Schema not found") |
| 49 | + return schema |
| 50 | + |
| 51 | +@router.put("/{schema_id}", response_model=ReportSchemaResponse) |
| 52 | +def update_schema(schema_id: int, data: ReportSchemaUpdate, db: Session = Depends(get_db)): |
| 53 | + updates = data.model_dump(exclude_none=True) |
| 54 | + schema = repo.update_report_schema(db, schema_id, updates) |
| 55 | + if not schema: |
| 56 | + raise HTTPException(status_code=404, detail="Schema not found") |
| 57 | + return schema |
| 58 | + |
| 59 | +@router.delete("/{schema_id}") |
| 60 | +def delete_schema(schema_id: int, db: Session = Depends(get_db)): |
| 61 | + deleted = repo.delete_report_schema(db, schema_id) |
| 62 | + if not deleted: |
| 63 | + raise HTTPException(status_code=404, detail="Schema not found") |
| 64 | + return {"detail": "Schema deleted"} |
| 65 | + |
| 66 | + |
| 67 | +@router.post("/{schema_id}/templates", response_model=list[SchemaFieldResponse]) |
| 68 | +def add_template(schema_id: int, data: TemplateAssociation, db: Session = Depends(get_db)): |
| 69 | + """Associate a template with a schema. |
| 70 | +
|
| 71 | + Auto-creates SchemaField entries from template.fields and returns them. |
| 72 | + """ |
| 73 | + try: |
| 74 | + repo.add_template_to_schema(db, schema_id, data.template_id) |
| 75 | + except IntegrityError: |
| 76 | + raise HTTPException(status_code=409, detail="Template is already added to schema") |
| 77 | + except ValueError as e: |
| 78 | + raise HTTPException(status_code=404, detail=str(e)) |
| 79 | + return repo.get_schema_fields(db, schema_id) |
| 80 | + |
| 81 | +@router.delete("/{schema_id}/templates/{template_id}") |
| 82 | +def remove_template(schema_id: int, template_id: int, db: Session = Depends(get_db)): |
| 83 | + removed = repo.remove_template_from_schema(db, schema_id, template_id) |
| 84 | + if not removed: |
| 85 | + raise HTTPException(status_code=404, detail="Template association not found") |
| 86 | + return {"detail": "Template disassociated"} |
| 87 | + |
| 88 | + |
| 89 | + |
| 90 | +@router.get("/{schema_id}/fields", response_model=list[SchemaFieldResponse]) |
| 91 | +def list_fields(schema_id: int, db: Session = Depends(get_db)): |
| 92 | + return repo.get_schema_fields(db, schema_id) |
| 93 | + |
| 94 | +@router.put("/{schema_id}/fields/{field_id}", response_model=SchemaFieldResponse) |
| 95 | +def update_field(schema_id: int, field_id: int, data: SchemaFieldUpdate, db: Session = Depends(get_db)): |
| 96 | + updates = data.model_dump(exclude_none=True) |
| 97 | + field = repo.update_schema_field(db, schema_id, field_id, updates) |
| 98 | + if not field: |
| 99 | + raise HTTPException(status_code=404, detail="Field not found or does not belong to this schema") |
| 100 | + return field |
| 101 | + |
| 102 | + |
| 103 | +@router.post("/{schema_id}/canonize", response_model=CanonicalSchema) |
| 104 | +def canonize_schema(schema_id: int, db: Session = Depends(get_db)): |
| 105 | + """Trigger canonization: group fields, assign canonical names, generate field mappings.""" |
| 106 | + schema = repo.get_report_schema(db, schema_id) |
| 107 | + if not schema: |
| 108 | + raise HTTPException(status_code=404, detail="Schema not found") |
| 109 | + |
| 110 | + return ReportSchemaProcessor.canonize(db, schema_id) |
| 111 | + |
| 112 | +@router.get("/mapping/{schema_id}/{template_id}") |
| 113 | +def get_schema_template_mapping(schema_id: int, template_id: int, db: Session = Depends(get_db)): |
| 114 | + return repo.get_field_mapping(db, schema_id, template_id) |
| 115 | + |
| 116 | +@router.post("/{schema_id}/fill", response_model=ReportFillResponse) |
| 117 | +def fill_schema(schema_id: int, data: ReportFill, db: Session = Depends(get_db)): |
| 118 | + """ |
| 119 | + End-to-end report generation. |
| 120 | + Takes a single transcript, extracts canonical fields, distributes to |
| 121 | + all schema templates, fills them, and logs the submissions. |
| 122 | + """ |
| 123 | + schema = repo.get_report_schema(db, schema_id) |
| 124 | + if not schema: |
| 125 | + raise HTTPException(status_code=404, detail="Schema not found") |
| 126 | + |
| 127 | + controller = Controller() |
| 128 | + |
| 129 | + output_paths = controller.fill_report(db, data.input_text, schema_id) |
| 130 | + |
| 131 | + # Log submissions |
| 132 | + submission_ids: list[int] = [] |
| 133 | + for template_id, path in output_paths.items(): |
| 134 | + submission = FormSubmission( |
| 135 | + template_id=template_id, |
| 136 | + report_schema_id=schema_id, |
| 137 | + name=data.name, |
| 138 | + input_text=data.input_text, |
| 139 | + output_pdf_path=path |
| 140 | + ) |
| 141 | + db.add(submission) |
| 142 | + db.flush() |
| 143 | + submission_ids.append(submission.id) # type: ignore |
| 144 | + |
| 145 | + db.commit() |
| 146 | + |
| 147 | + return ReportFillResponse( |
| 148 | + schema_id=schema_id, |
| 149 | + input_text=data.input_text, |
| 150 | + output_pdf_paths=list(output_paths.values()), |
| 151 | + submission_ids=submission_ids, |
| 152 | + ) |
| 153 | + |
| 154 | + |
| 155 | +@router.get("/{schema_id}/submissions", response_model=list[FormSubmissionResponse]) |
| 156 | +def list_submissions(schema_id: int, db: Session = Depends(get_db)): |
| 157 | + """List all form submissions for a given schema.""" |
| 158 | + return db.exec( |
| 159 | + select(FormSubmission) |
| 160 | + .where(FormSubmission.report_schema_id == schema_id) |
| 161 | + .order_by(FormSubmission.created_at.desc()) # type: ignore |
| 162 | + ).all() |
| 163 | + |
| 164 | + |
| 165 | +@router.get("/submissions/{submission_id}/pdf") |
| 166 | +def get_submission_pdf(submission_id: int, db: Session = Depends(get_db)): |
| 167 | + """Serve a filled PDF for a given form submission.""" |
| 168 | + submission = db.get(FormSubmission, submission_id) |
| 169 | + if not submission: |
| 170 | + raise HTTPException(status_code=404, detail="Submission not found") |
| 171 | + path = Path(submission.output_pdf_path).resolve() |
| 172 | + if not path.is_file(): |
| 173 | + raise HTTPException(status_code=404, detail="PDF file missing on disk") |
| 174 | + return FileResponse( |
| 175 | + path, |
| 176 | + media_type="application/pdf", |
| 177 | + filename=f"submission_{submission_id}.pdf", |
| 178 | + ) |
0 commit comments