from __future__ import annotations from typing import Any from sqlalchemy import desc from app.models import ShippingTask, ShippingTaskEvent def serialize_task_summary(task: ShippingTask) -> dict[str, Any]: return { "id": task.id, "task_no": task.task_no, "source_type": task.source_type, "customer_name": task.customer_name, "process_status": task.process_status, "review_status": task.review_status, "match_status": task.match_status, "pending_human_reason": task.pending_human_reason, "conversation_id": task.conversation_id, "export_file_name": task.export_file_name, "freight_ref_no": task.freight_ref_no, "created_at": task.created_at.isoformat() if task.created_at else None, "updated_at": task.updated_at.isoformat() if task.updated_at else None, } def serialize_task_detail(task: ShippingTask) -> dict[str, Any]: data = serialize_task_summary(task) data.update({ "customer_code": task.customer_code, "ship_to": task.ship_to, "po_number": task.po_number, "required_date": task.required_date, "lines": task.lines_json or [], "shortage": task.shortage_json, "line_results": task.line_results_json or [], "parse_confidence": task.parse_confidence, "error_message": task.error_message, "events": [ { "event_type": e.event_type, "detail_json": e.detail_json, "created_at": e.created_at.isoformat() if e.created_at else None, } for e in sorted(task.events or [], key=lambda x: x.created_at or "") ], }) return data def list_tasks_for_user( user_id: int, *, process_status: str | None = None, limit: int = 100, ) -> list[dict[str, Any]]: q = ShippingTask.query.filter( (ShippingTask.user_id == user_id) | (ShippingTask.user_id.is_(None)) ) if process_status: q = q.filter(ShippingTask.process_status == process_status) rows = q.order_by(desc(ShippingTask.created_at)).limit(max(1, min(limit, 500))).all() return [serialize_task_summary(c) for c in rows] def get_task_for_user(task_no: str, user_id: int) -> ShippingTask | None: task = ShippingTask.query.filter_by(task_no=task_no).first() if not task: return None if task.user_id is not None and task.user_id != user_id: return None return task