api.py 19.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
"""库存补货接口。

后台(/api/restock/*,需登录):补货单(含审计时间线 / 清单快照 / 出库明细)、立即执行补货、今日时间线、补货规则、
在库分类表维护、SO 单同步、历史导出、留痕导出。
免登录(/api/public/restock/*,靠补货单令牌):手机单据页(取数据、刷新、确认、今天不订、页面操作埋点)。
所有操作都写操作日志(免登录页面记录 IP / UA)。
"""
from __future__ import annotations

import datetime as dt

from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import Response
from pydantic import BaseModel

from ... import features
from ...api.deps import Scope, current_store, public_actor
from ...core import db
from ...core.db import func, select
from ...models import outbound_rows_t, runs_t
from ...services import alerts, audit, edge
from . import categories, exports, history, planner, timeline
from .service import KEY, KIND_CN, STAGE_CN, at, svc


class LineState(BaseModel):
    part_no: str
    checked: bool = False
    expected: int | None = None
    modified: bool = False


class PageIn(BaseModel):
    lines: list[LineState] = []


class EventIn(BaseModel):
    kind: str
    detail: dict = {}


class CategoryIn(BaseModel):
    part_no: str
    name: str = ""
    category: str
    note: str = ""


class ImportIn(BaseModel):
    text: str


class ConfigIn(BaseModel):
    enabled: bool | None = None
    values: dict = {}


class ExportIn(BaseModel):
    kind: str
    year: int | None = None


class UnknownCloseIn(BaseModel):
    conclusion: str = ""


def _feature_on(s: Scope = Depends(current_store)) -> Scope:
    if not features.is_enabled(s.store_id, KEY):
        raise HTTPException(403, "门店还没有开通「库存补货」(在「系统设置 → 功能开通」里打开)")
    return s


router = APIRouter(prefix="/api/restock", tags=["restock"])
public = APIRouter(prefix="/api/public/restock", tags=["restock-public"])


def _csv_response(text: str, filename: str) -> Response:
    from urllib.parse import quote
    return Response(text, media_type="text/csv; charset=utf-8",
                    headers={"Content-Disposition": f"attachment; filename*=UTF-8''{quote(filename)}"})


# ====================================================================== 补货规则(功能开关 + 参数)
@router.get("/config")
def get_config(s: Scope = Depends(current_store)):
    from .config import RestockConfig
    return {"enabled": features.is_enabled(s.store_id, KEY),
            "values": features.config(s.store_id, KEY).model_dump(mode="json"),
            "defaults": RestockConfig().model_dump(mode="json"),
            "in_transit_options": planner.IN_TRANSIT_LABEL}


@router.put("/config")
def put_config(body: ConfigIn, s: Scope = Depends(current_store)):
    try:
        before, after = features.save(s.store_id, KEY, enabled=body.enabled, values=body.values, by=s.actor.name)
    except Exception as e:  # noqa: BLE001  pydantic 校验
        msg = str(e)
        if hasattr(e, "errors"):
            msg = ";".join(f"{'.'.join(str(x) for x in er['loc'])}:{er['msg']}" for er in e.errors())  # type: ignore
        raise HTTPException(400, f"参数不合法:{msg}")
    audit.record(s.store_id, s.actor, "restock.config.update", target_type="feature", target_id=KEY,
                 before=before, after=after)
    return {"ok": True, **after}


# ====================================================================== 在库零件分类表
@router.get("/categories")
def list_categories(q: str = "", category: str = "", page: int = 1, size: int = 50, s: Scope = Depends(_feature_on)):
    return categories.paged(s.store_id, q, category, page, size) | {
        "counts": categories.counts(s.store_id), "known": list(categories.KNOWN),
        "stock_categories": svc.cfg(s.store_id).stock_categories}


@router.post("/categories")
def save_category(body: CategoryIn, s: Scope = Depends(_feature_on)):
    try:
        categories.upsert(s.store_id, s.actor, body.part_no, body.name, body.category, body.note)
    except ValueError as e:
        raise HTTPException(400, str(e))
    return {"ok": True}


@router.delete("/categories/{part_no}")
def delete_category(part_no: str, s: Scope = Depends(_feature_on)):
    try:
        categories.remove(s.store_id, s.actor, part_no)
    except ValueError as e:
        raise HTTPException(404, str(e))
    return {"ok": True}


@router.post("/categories/import")
def import_categories(body: ImportIn, s: Scope = Depends(_feature_on)):
    return categories.import_text(s.store_id, s.actor, body.text)


@router.get("/categories.csv")
def categories_csv(s: Scope = Depends(_feature_on)):
    rows = [{"零件号码": r["part_no"], "零件名称": r["name"] or "", "零件分类": r["category"], "备注": r["note"] or "",
             "来源": r["source"] or "", "最后修改人": r["updated_by"] or "", "最后修改时间": str(r["updated_at"] or "")}
            for r in categories.listing(s.store_id)]
    return _csv_response(svc.to_csv(rows), "在库零件分类.csv")


# ====================================================================== 近期 SO 单(每周同步)
@router.get("/so")
def so_state(s: Scope = Depends(_feature_on)):
    cfg = svc.cfg(s.store_id)
    run = history.running(s.store_id)
    last = history.last(s.store_id)
    return {"running": bool(run), "progress": history.progress(run["id"]) if run else None,
            "last": history.brief(last) if last else None, "part_count": history.part_count(s.store_id),
            "schedule": {"weekdays": cfg.so_sync_weekdays, "time": cfg.so_sync_time, "months": cfg.so_months}}


@router.get("/so/syncs")
def so_syncs(page: int = 1, size: int = 10, s: Scope = Depends(_feature_on)):
    return history.syncs(s.store_id, page, size)


@router.get("/so/syncs/{sync_id}")
def so_sync_detail(sync_id: int, s: Scope = Depends(_feature_on)):
    r = history.sync_row(s.store_id, sync_id)
    if not r:
        raise HTTPException(404, "同步记录不存在")
    return r


@router.get("/so/parts")
def so_parts(q: str = "", page: int = 1, size: int = 50, s: Scope = Depends(_feature_on)):
    return history.parts(s.store_id, q, page, size)


@router.post("/so/sync")
async def so_sync_now(s: Scope = Depends(_feature_on)):
    if history.running(s.store_id):
        raise HTTPException(409, "上一次同步还在进行中")
    svc.spawn(history.sync(s.store_id, "console", s.actor, svc.now(s.store_id).date()), "restock-so-sync")
    return {"ok": True, "message": "已下发给门店取数端,同步完成后刷新本页查看"}


# ====================================================================== 补货单
@router.get("/runs")
def runs(page: int = 1, size: int = 20, status: str = "", kind: str = "", s: Scope = Depends(_feature_on)):
    conds = [runs_t.c.store_id == s.store_id]
    if status:
        conds.append(runs_t.c.status == status)
    if kind:
        conds.append(runs_t.c.kind == ("scheduled" if kind == "batch" else kind))     # batch:改名前的旧链接
    res = db.paged(select(runs_t).where(*conds).order_by(runs_t.c.id.desc()), page, size)
    lines = svc.lines_many([x["id"] for x in res["rows"]])
    res["rows"] = [db.plain({k: v for k, v in x.items() if k != "token"}) | {
        "stage_cn": STAGE_CN.get(x["status"], x["status"]), "kind_cn": KIND_CN.get(x["kind"], ""),
        "summary": planner.summary(lines.get(x["id"], []))} for x in res["rows"]]
    return res


def _own(rid: int, s: Scope) -> dict:
    run = svc.run(rid)
    if not run or run["store_id"] != s.store_id:
        raise HTTPException(404, "补货单不存在")
    return run


@router.get("/runs/{rid}")
def run_detail(rid: int, s: Scope = Depends(_feature_on)):
    from ...services import events
    run = _own(rid, s)
    st = svc.page_state(run["token"])
    st["links"] = {"order": svc.link(run)}
    st["submit_shots"] = svc.submit_shots_state(rid)          # 提交后截图(审计留档):只在后台看
    st["events"] = events.recent(s.store_id, svc.ref(rid), 300)
    st["tasks"] = edge.tasks(s.store_id, 20, ref=svc.ref(rid))
    return st


@router.get("/runs/{rid}/timeline")
def run_timeline(rid: int, kinds: str = "", page: int = 1, size: int = 50, s: Scope = Depends(_feature_on)):
    items = timeline.build(_own(rid, s))
    counts: dict[str, int] = {}
    for x in items:
        counts[x["kind"]] = counts.get(x["kind"], 0) + 1
    want = {k for k in kinds.split(",") if k}
    if want:
        items = [x for x in items if x["kind"] in want]
    size, page = max(1, min(size, 200)), max(1, page)
    return {"items": items[(page - 1) * size:page * size], "total": len(items), "page": page, "size": size,
            "counts": counts}


@router.get("/runs/{rid}/timeline.csv")
def run_timeline_csv(rid: int, s: Scope = Depends(_feature_on)):
    run = _own(rid, s)
    rows = [{"时间": x["ts"], "类型": {"chat": "聊天", "audit": "操作", "event": "流程", "task": "取数端任务",
                                    "api": "DMS 接口", "snapshot": "清单快照"}[x["kind"]],
             "标题": x["title"], "内容": x["text"], "详情": str(x["detail"])} for x in timeline.build(run)]
    audit.record(s.store_id, s.actor, "restock.timeline.export", target_type="run", target_id=str(rid), ref=svc.ref(rid))
    return _csv_response(svc.to_csv(rows), f"补货单审计时间线_{run['doc_no']}.csv")


@router.get("/runs/{rid}/snapshots/{snap_id}")
def run_snapshot(rid: int, snap_id: int, s: Scope = Depends(_feature_on)):
    _own(rid, s)
    snap = timeline.snapshot(rid, snap_id)
    if not snap:
        raise HTTPException(404, "快照不存在")
    return snap


@router.get("/runs/{rid}/outbound")
def run_outbound(rid: int, fetch_seq: int | None = None, page: int = 1, size: int = 50,
                 s: Scope = Depends(_feature_on)):
    run = _own(rid, s)
    seq = fetch_seq or run["fetch_seq"]
    cols = [c for c in outbound_rows_t.c if c.name != "raw"]
    res = db.paged(select(*cols).where(outbound_rows_t.c.run_id == rid, outbound_rows_t.c.fetch_seq == seq)
                   .order_by(outbound_rows_t.c.id), page, size)
    return res | {"fetch_seq": seq, "stats": db.jload(run["outbound_stats"], {}),
                  "rows": [db.plain(r) for r in res["rows"]]}


@router.post("/runs/start")
async def start(s: Scope = Depends(_feature_on)):
    """后台「立即执行补货」:手动补充,和定时推送走同一条链路,不影响当天的定时推送(企微里不能发起定时补货)。"""
    res = await svc.start(s.store_id, "console", s.actor)
    return {"result": res, "message": {"started": "已开始取数,补货推荐会推送到企业微信",
                                       "busy": "上一轮还在进行中",
                                       "schedule_pending": "今天的定时补货单正在等确认,请先处理它"}.get(res, res)}


@router.post("/runs/{rid}/cancel")
async def cancel(rid: int, s: Scope = Depends(_feature_on)):
    run = _own(rid, s)
    ok, msg = await svc.cancel(run["token"], s.actor, "console")
    if not ok:
        raise HTTPException(409, msg)
    return {"ok": True, "message": msg}


class ReasonIn(BaseModel):
    reason: str = ""


@router.post("/runs/{rid}/terminate")
async def terminate(rid: int, body: ReasonIn, s: Scope = Depends(_feature_on)):
    """后台「强制终止」:取数一直失败、一直自动重试时停下来(建单 / 提交中的不能强停)。"""
    _own(rid, s)
    ok, msg = await svc.terminate(rid, s.actor, body.reason)
    if not ok:
        raise HTTPException(409, msg)
    return {"ok": True, "message": msg}


@router.post("/runs/{rid}/void")
async def void(rid: int, body: ReasonIn, s: Scope = Depends(_feature_on)):
    """后台「作废」单次补货:只报了价的作废;已建 DMS 草稿的不提交(草稿保留)。"""
    _own(rid, s)
    ok, msg = await svc.void(rid, s.actor, body.reason)
    if not ok:
        raise HTTPException(409, msg)
    return {"ok": True, "message": msg}


@router.post("/runs/{rid}/submit-shots")
async def submit_shots(rid: int, s: Scope = Depends(_feature_on)):
    """重新截「提交后截图」(审计留档):自动截图失败、或想按 DMS 现在的样子再留一份时用。"""
    _own(rid, s)
    ok, msg = await svc.submit_shots(rid, s.actor)
    if not ok:
        raise HTTPException(409, msg)
    return {"ok": True, "message": msg, "submit_shots": svc.submit_shots_state(rid)}


@router.post("/runs/{rid}/unknown-close")
async def unknown_close(rid: int, body: UnknownCloseIn, s: Scope = Depends(_feature_on)):
    """单次补货建单异常一直核实不了时:人到 DMS 按备注单号核实后,在后台关闭这张单(会话恢复可以补货)。"""
    run = _own(rid, s)
    ok, msg = await svc.unknown_close(run["token"], s.actor, body.conclusion)
    if not ok:
        raise HTTPException(409, msg)
    return {"ok": True, "message": msg}


# ====================================================================== 今日(工作台)
@router.get("/today")
def today(s: Scope = Depends(current_store)):
    sid = s.store_id
    cfg = svc.cfg(sid)
    now = svc.now(sid)
    enabled = features.is_enabled(sid, KEY)
    cur = svc.current(sid, now.date()) if enabled else None
    ordered = svc.ordered_today(sid, now.date()) if enabled else None
    steps = [{"time": t, "title": "预检", "kind": "preflight"} for t in cfg.preflight_times] if cfg.auto_push else []
    if cfg.auto_push:
        steps.append({"time": cfg.push_time, "title": "拉出库明细、推送补货推荐", "kind": "push"})
    if cfg.urgent_before_min:
        u = at(now.date(), cfg.cutoff) - dt.timedelta(minutes=cfg.urgent_before_min)
        steps.append({"time": u.strftime("%H:%M"), "title": "未下单紧急告警", "kind": "urgent"})
    steps.append({"time": cfg.cutoff, "title": "截单收口", "kind": "close"})
    if cfg.summary_enabled:
        steps.append({"time": cfg.summary_time, "title": "发今日补货小结", "kind": "summary"})
    if now.weekday() in cfg.so_sync_weekdays:
        steps.append({"time": cfg.so_sync_time, "title": "同步近期 SO 单", "kind": "so_sync"})
    for x in steps:
        x["passed"] = now >= at(now.date(), x["time"])
    steps.sort(key=lambda x: x["time"])
    online, info = edge.online(sid)
    run = None
    if cur:
        run = db.plain({k: v for k, v in cur.items() if k != "token"}) | {
            "stage_cn": STAGE_CN.get(cur["status"]), "link": svc.link(cur),
            "summary": planner.summary(svc.lines(cur["id"]))}
    week = db.rows(select(runs_t.c.biz_date, runs_t.c.status, runs_t.c.order_no).where(
        runs_t.c.store_id == sid, runs_t.c.kind == "scheduled", runs_t.c.biz_date >= now.date() - dt.timedelta(days=6),
        runs_t.c.status != "superseded").order_by(runs_t.c.id))
    days = {}
    for w in week:
        days[str(w["biz_date"])] = {"status": w["status"], "stage_cn": STAGE_CN.get(w["status"]),
                                    "order_no": w["order_no"]}
    singles = db.scalar(select(func.count()).select_from(runs_t).where(
        runs_t.c.store_id == sid, runs_t.c.kind.in_(("single", "multi")),
        runs_t.c.biz_date == now.date())) if enabled else 0
    last_sync = history.last(sid) if enabled else None
    return {"now": now.strftime("%Y-%m-%d %H:%M:%S"), "enabled": enabled, "config": cfg.model_dump(mode="json"),
            "timeline": steps, "run": run, "ordered": bool(ordered),
            "order_no": ordered["order_no"] if ordered else None, "edge": {"online": online, **info},
            "category_count": sum(categories.counts(sid).values()) if enabled else 0,
            "so_part_count": history.part_count(sid) if enabled else 0,
            "so_last_sync": db.plain(last_sync) if last_sync else None, "single_today": singles,
            "open_alerts": alerts.open_count(sid),
            "week": [{"date": str(now.date() - dt.timedelta(days=i)), **days.get(str(now.date() - dt.timedelta(days=i)), {})}
                     for i in range(6, -1, -1)]}


# ====================================================================== 留痕表 / 历史导出
@router.get("/trace.csv")
def trace_csv(since: dt.date | None = None, until: dt.date | None = None, s: Scope = Depends(_feature_on)):
    today_ = svc.now(s.store_id).date()
    rows = svc.trace_rows(s.store_id, since or today_ - dt.timedelta(days=30), until or today_)
    audit.record(s.store_id, s.actor, "restock.trace.export", detail={"since": str(since), "until": str(until)})
    return _csv_response(svc.to_csv(rows), "补货留痕表.csv")


@router.get("/exports")
def list_exports(page: int = 1, size: int = 20, s: Scope = Depends(_feature_on)):
    return exports.listing(s.store_id, page, size)


@router.post("/exports")
async def start_export(body: ExportIn, s: Scope = Depends(_feature_on)):
    try:
        eid = await exports.start(s.store_id, body.kind, body.year, s.actor)
    except ValueError as e:
        raise HTTPException(409, str(e))
    return {"id": eid, "message": "已下发给门店取数端,导出完成后可在这里下载"}


# ====================================================================== 免登录:手机单据页
def _run(token: str) -> dict:
    run = svc.run_by_token(token)
    if not run or not features.is_enabled(run["store_id"], KEY):
        raise HTTPException(404, "单据不存在或已失效")
    return run


def _state(body: PageIn) -> list[dict]:
    return [x.model_dump() for x in body.lines]


@public.get("/orders/{token}")
def order(token: str):
    _run(token)
    return svc.page_state(token)


@public.post("/orders/{token}/refresh")
async def p_refresh(token: str, body: PageIn, request: Request):
    _run(token)
    ok, msg = await svc.refresh(token, public_actor(request, via="order_page"), _state(body))
    if not ok:
        raise HTTPException(409, msg)
    return {"ok": True, "message": msg}


@public.post("/orders/{token}/confirm")
async def p_confirm(token: str, body: PageIn, request: Request):
    _run(token)
    ok, msg = await svc.confirm(token, public_actor(request, via="order_page"), "order_page", _state(body))
    if not ok:
        raise HTTPException(409, msg)
    return {"ok": True, "message": msg}


@public.post("/orders/{token}/cancel")
async def p_cancel(token: str, request: Request):
    _run(token)
    ok, msg = await svc.cancel(token, public_actor(request, via="order_page"), "order_page")
    if not ok:
        raise HTTPException(409, msg)
    return {"ok": True, "message": msg}


@public.post("/orders/{token}/submit")
async def p_submit(token: str, request: Request):
    """定时补货:建单截图后在单据页点「确认提交」(token 精确定位到这一张单,按建单时的 DMS 单据 id 提交)。"""
    _run(token)
    ok, msg = await svc.submit(token, public_actor(request, via="order_page"), "order_page")
    if not ok:
        raise HTTPException(409, msg)
    return {"ok": True, "message": msg}


@public.post("/orders/{token}/hold")
async def p_hold(token: str, request: Request):
    """定时补货:建单后「先不提交」。DMS 草稿保留「待提交」,由人工删除或提交。"""
    run = _run(token)
    if run["status"] != "awaiting_submit":
        raise HTTPException(409, f"这张单当前不是待确认提交({STAGE_CN.get(run['status'], run['status'])})")
    ok, msg = await svc.cancel(token, public_actor(request, via="order_page"), "order_page")
    if not ok:
        raise HTTPException(409, msg)
    return {"ok": True, "message": msg}


@public.post("/orders/{token}/events")
def p_event(token: str, body: EventIn, request: Request):
    """单据页操作埋点:打开页面、展开其他组、搜索、勾选、改期望(逐处,带改前改后)、倒计时归零……"""
    _run(token)
    svc.page_event(token, public_actor(request, via="order_page"), body.kind, body.detail)
    return {"ok": True}