"""用户的退网评估接口:单个提交、导入清单、查看进度、下载结果。""" from __future__ import annotations from datetime import date from pathlib import Path from urllib.parse import quote from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile from fastapi.responses import FileResponse, Response from sqlalchemy import delete, select from sqlalchemy.orm import Session from app.api.deps import Actor, current_actor from app.db import get_session from app.evaluate.compute import NEIGHBOR_SITES from app.evaluate.demand import ( CGI_PATTERN, KIND_LABELS, MAX_BYTES, ORDER_TYPES, DemandError, DemandRow, SiteGroup, group_rows, kind_of, parse_demand, summarize, template_workbook, ) from app.evaluate.runner import JOB_FINAL, create_job, dispatch, remove_files, result_path from app.evaluate.sources import METRICS_MOCKED from app.models import EvalJob, EvalTask, GongcanSnapshot, NqiAccount router = APIRouter(prefix="/api/eval") db_session = Depends(get_session, scope="function") XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" MAX_SINGLE_CELLS = 100 MAX_LIST_SITES = 1000 def _bad(message: str, status: int = 400) -> HTTPException: return HTTPException(status_code=status, detail=message) def _user(actor: Actor) -> Actor: if actor.role == "admin": raise _bad("管理员不在这里提交任务", 403) return actor def _short_city(name: str) -> str: text = (name or "").strip() for suffix in ("分公司", "市"): if text.endswith(suffix) and len(text) > len(suffix): text = text[: -len(suffix)] return text def _default_city(session: Session, actor: Actor) -> str: if actor.kind == "nqi": account = session.scalar(select(NqiAccount).where(NqiAccount.login_id == actor.id)) if account is not None and account.city_name: return _short_city(account.city_name) pooled = session.scalar(select(NqiAccount.city_name).where(NqiAccount.city_name != "").order_by(NqiAccount.saved_at.desc())) if pooled: return _short_city(pooled) return session.scalar(select(GongcanSnapshot.city).order_by(GongcanSnapshot.id.desc())) or "" def _check_city(value: object) -> str: city = _short_city(str(value or "")) if not city: raise _bad("请填写地市") if len(city) > 32: raise _bad("地市名称过长") return city def _text(value: object, limit: int, label: str) -> str: result = str(value or "").strip() if len(result) > limit: raise _bad(f"{label}过长") return result @router.get("/options") def options(actor: Actor = Depends(current_actor), session: Session = db_session) -> dict: _user(actor) return { "city": _default_city(session, actor), "applicant": actor.name, "orderTypes": list(ORDER_TYPES), "neighbors": NEIGHBOR_SITES, "metricsMocked": METRICS_MOCKED, } @router.get("/template") def demand_template(actor: Actor = Depends(current_actor)) -> Response: _user(actor) return Response( content=template_workbook(), media_type=XLSX, headers={"Content-Disposition": f"attachment; filename*=UTF-8''{quote('拆站清单模板.xlsx')}"}, ) def _read_upload(file: UploadFile): content = file.file.read(MAX_BYTES + 1) try: return parse_demand(file.filename or "", content) except DemandError as exc: raise _bad(str(exc)) from exc @router.post("/preview") def preview(file: UploadFile = File(...), actor: Actor = Depends(current_actor)) -> dict: _user(actor) sheet = _read_upload(file) groups = group_rows(sheet.rows) return { "sheet": sheet.sheet, "rows": [row.to_json() for row in sheet.rows[:500]], "total": len(sheet.rows), "errors": sheet.errors[:500], "errorCount": len(sheet.errors), "summary": summarize(groups), } @router.post("/jobs/list") def submit_list( file: UploadFile = File(...), city: str = Form(""), skipErrors: bool = Form(False), actor: Actor = Depends(current_actor), session: Session = db_session, ) -> dict: _user(actor) city_name = _check_city(city) sheet = _read_upload(file) if sheet.errors and not skipErrors: raise _bad(f"清单有 {len(sheet.errors)} 行有问题,请修改后再导入,或选择跳过这些行") groups = group_rows(sheet.rows) if not groups: raise _bad("清单里没有可评估的行") if len(groups) > MAX_LIST_SITES: raise _bad(f"一次最多评估 {MAX_LIST_SITES} 个逻辑站点") title = Path(file.filename or "清单").stem or "清单" return _start(session, actor, "list", title, city_name, groups, source_name=file.filename or "") @router.post("/jobs/single") def submit_single(body: dict, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict: _user(actor) order_type = _text(body.get("orderType"), 64, "退网工单类型") if not order_type: raise _bad("请选择退网工单类型") try: removal = date.fromisoformat(str(body.get("removalDate") or "")) except ValueError as exc: raise _bad("请选择拆除日期") from exc city = _check_city(body.get("city")) template = DemandRow( line=0, cgi="", order_type=order_type, need_date=removal, county=_text(body.get("county"), 64, "区县"), applicant=_text(body.get("applicant"), 64, "申请人") or actor.name, retire_reason=_text(body.get("retireReason"), 255, "退网原因"), ) if body.get("mode") == "site": site = _text(body.get("site"), 128, "站点名称") if not site: raise _bad("请填写站点名称") group = SiteGroup(key=site, kind=kind_of(order_type), order_type=order_type, removal=removal, rows=[template], site=site) return _start(session, actor, "single", site, city, [group]) rows: list[DemandRow] = [] seen: set[str] = set() for index, item in enumerate(body.get("cells") or [], start=1): item = item if isinstance(item, dict) else {} cgi = str(item.get("cgi") or "").strip() if not cgi: continue if not CGI_PATTERN.match(cgi): raise _bad(f"CGI 格式不对:{cgi}") if cgi in seen: raise _bad(f"CGI 重复:{cgi}") seen.add(cgi) rows.append( DemandRow( line=index, cgi=cgi, order_type=order_type, need_date=removal, cell_name=_text(item.get("cellName"), 128, "小区名称"), county=template.county, applicant=template.applicant, retire_reason=template.retire_reason, ) ) if not rows: raise _bad("请至少填写一个小区 CGI") if len(rows) > MAX_SINGLE_CELLS: raise _bad(f"单个提交最多 {MAX_SINGLE_CELLS} 个小区,更多请导入清单") groups = group_rows(rows) title = groups[0].key if len(groups) == 1 else f"{groups[0].key} 等 {len(groups)} 个站点" return _start(session, actor, "single", title, city, groups) def _start(session: Session, actor: Actor, mode: str, title: str, city: str, groups: list[SiteGroup], source_name: str = "") -> dict: job = create_job( session, owner_kind=actor.kind, owner_id=actor.id, owner_name=actor.name, mode=mode, title=title, city=city, groups=groups, source_name=source_name, ) job_id = job.id session.commit() dispatch(job_id) session.refresh(job) return {"job": _public_job(job)} def _owned_job(session: Session, actor: Actor, job_id: int) -> EvalJob: job = session.get(EvalJob, job_id) if job is None or job.owner_kind != actor.kind or job.owner_id != actor.id: raise _bad("任务不存在", 404) return job @router.get("/jobs") def list_jobs(actor: Actor = Depends(current_actor), session: Session = db_session) -> dict: _user(actor) jobs = session.scalars( select(EvalJob) .where(EvalJob.owner_kind == actor.kind, EvalJob.owner_id == actor.id) .order_by(EvalJob.id.desc()) .limit(200) ).all() kinds: dict[int, dict] = {} if jobs: for job_id, kind in session.execute(select(EvalTask.job_id, EvalTask.kind).where(EvalTask.job_id.in_([job.id for job in jobs]))): counter = kinds.setdefault(job_id, {"pinduan": 0, "dixiao": 0}) counter[kind] = counter.get(kind, 0) + 1 return {"jobs": [_public_job(job, kinds.get(job.id)) for job in jobs]} @router.get("/jobs/{job_id}") def job_detail(job_id: int, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict: _user(actor) job = _owned_job(session, actor, job_id) tasks = session.scalars(select(EvalTask).where(EvalTask.job_id == job.id).order_by(EvalTask.seq)).all() counts = {"pinduan": 0, "dixiao": 0} for task in tasks: counts[task.kind] = counts.get(task.kind, 0) + 1 return {"job": _public_job(job, counts), "tasks": [_public_task(task) for task in tasks]} @router.get("/jobs/{job_id}/files/{kind}") def download(job_id: int, kind: str, actor: Actor = Depends(current_actor), session: Session = db_session) -> FileResponse: _user(actor) job = _owned_job(session, actor, job_id) entry = next((item for item in job.results or [] if item.get("kind") == kind), None) path = result_path(entry) if entry else None if path is None or not path.is_file(): raise _bad("结果还不能下载", 404) return FileResponse(path, media_type=XLSX, filename=entry["name"]) @router.delete("/jobs/{job_id}") def delete_job(job_id: int, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict: _user(actor) job = _owned_job(session, actor, job_id) if job.status not in JOB_FINAL: raise _bad("任务还在进行,结束后才能删除") session.execute(delete(EvalTask).where(EvalTask.job_id == job.id)) session.delete(job) session.commit() remove_files(job_id) return {"ok": True} def _iso(value) -> str | None: return value.isoformat() if value else None def _public_job(job: EvalJob, kinds: dict | None = None) -> dict: return { "id": job.id, "mode": job.mode, "title": job.title, "city": job.city, "sourceName": job.source_name, "status": job.status, "total": job.total, "finished": job.finished, "failed": job.failed, "kinds": kinds or {}, "results": [{"kind": item.get("kind"), "label": item.get("label") or KIND_LABELS.get(item.get("kind"), ""), "name": item.get("name")} for item in job.results or []], "warnings": list(job.warnings or []), "error": job.error, "createdAt": _iso(job.created_at), "finishedAt": _iso(job.finished_at), } def _public_task(task: EvalTask) -> dict: payload = task.payload or {} return { "id": task.id, "seq": task.seq, "site": payload.get("site") or task.site_key, "kind": task.kind, "orderType": task.order_type, "removalDate": _iso(task.removal_date), "status": task.status, "stage": task.stage, "beforeDate": _iso(task.before_date), "afterDate": _iso(task.after_date), "afterPresent": task.after_present, "cells": [{"cgi": item.get("cgi"), "cellName": item.get("cellName")} for item in (payload.get("rows") or task.rows or [])], "neighbors": payload.get("neighbors", []), "windows": payload.get("windows"), "notes": payload.get("notes", []), "error": task.error, }