config.py 13.6 KB
"""库存补货:门店参数。

RestockConfig:功能参数(企业后台「补货规则」页修改,存 atrs_sys_store_feature.config)。
SingleConfig:对话技能参数(「智能助手 → 技能」页修改,存 atrs_sys_store_skill.config;页面按 schema 自动渲染,
json_schema_extra 里的 unit 是输入框后面的单位)。"""
from __future__ import annotations

import math
import re

from pydantic import BaseModel, Field, ValidationInfo, field_validator, model_validator

HHMM = re.compile(r"^([01]?\d|2[0-3]):[0-5]\d$")
DETAIL_PAGE_GUESS = 10    # 估算 DMS 采购单详情每页几项(截图超时按页数加时间用)
ORDER_TYPE = "S"            # 订单类型写死 SO(库存补充订单):后台、智能体都不能改(取数端同样写死)


class StepTimeouts(BaseModel):
    login: int = Field(90, title="登录 DMS(秒)", ge=10, le=600)
    query_part: int = Field(30, title="每个配件查询(秒)", ge=5, le=300)
    create_po: int = Field(120, title="创建采购单(秒)", ge=10, le=600)
    verify_po: int = Field(60, title="回查采购单(秒)", ge=10, le=600)
    submit_po: int = Field(120, title="提交采购单(秒)", ge=10, le=600)
    screenshot: int = Field(90, title="每张截图(秒)", ge=10, le=600)
    query_outbound: int = Field(300, title="拉零件出库明细(秒)", ge=30, le=1800)
    so_sync: int = Field(3000, title="SO 单同步(秒)", ge=60, le=7200)
    screenshot_fallback: int = Field(180, title="截图兜底渲染(秒)", ge=30, le=600)


class TaskTimeouts(BaseModel):
    """任务整体超时(云端等待取数端的最长时间)。不下发给取数端;超时后:没人领 → expired,领了没回结果 → unknown。"""
    scan_base: int = Field(300, title="查询:基础时间(秒)", ge=30, le=7200)
    scan_per_part: int = Field(6, title="查询:每个配件追加(秒)", ge=1, le=120)
    create_base: int = Field(300, title="建单:基础时间(秒)", ge=30, le=7200)
    create_per_line: int = Field(4, title="建单:每行追加(秒)", ge=1, le=120)
    screenshot_extra: int = Field(120, title="截图:额外时间(秒)", ge=0, le=1800,
                                  description="整体超时 = 额外时间 + 2 × 每张截图步骤超时 + 详情多出来的页数 × 每页追加")
    screenshot_per_page: int = Field(30, title="截图:详情每多一页追加(秒)", ge=5, le=600,
                                     description="采购单详情分页显示时要逐页翻页截图;按每页 10 项估算页数")
    submit: int = Field(300, title="提交(秒)", ge=60, le=1800, description="核对 + 检查 + 提交 + 回查")
    preflight: int = Field(300, title="预检(秒)", ge=30, le=1800)
    outbound: int = Field(600, title="出库明细(秒)", ge=60, le=3600)
    so_sync: int = Field(3600, title="SO 单同步(秒)", ge=300, le=14400)

    def scan(self, parts: int) -> int:
        return self.scan_base + self.scan_per_part * parts

    def create(self, lines: int) -> int:
        return self.create_base + self.create_per_line * lines

    def screenshot(self, step_screenshot: int, lines: int = 0) -> int:
        extra_pages = max(math.ceil(max(lines, 0) / DETAIL_PAGE_GUESS) - 1, 0)
        return self.screenshot_extra + 2 * step_screenshot + self.screenshot_per_page * extra_pages


def _mins(t: str) -> int:
    h, m = t.split(":")
    return int(h) * 60 + int(m)


class RestockConfig(BaseModel):
    # ---- 时间线 ----
    auto_push: bool = Field(True, title="每天自动执行定时补货",
                            description="到点预检 + 定时推送;关闭后仍可在后台「立即执行补货」手动跑。关闭时未确认提醒、截单提醒、"
                                        "截单前紧急告警都不再发送,每日小结、取数失败重试、口径照样生效")
    push_time: str = Field("15:00", title="定时推送时间", description="门店本地时间 HH:MM;到点拉出库明细、算补货清单、推链接")
    cutoff: str = Field("16:00", title="厂家截单时间",
                        description="只用来提示风险:临近 / 过了截单仍可确认、建单、提交,消息和单据页会说明实际提交可能超过截单时间")
    cutoff_hard: bool = Field(False, title="截单后禁止确认(旧规则)",
                              description="打开后恢复旧规则:过了截单不能刷新 / 确认,截单时把未完成的定时补货单作废。"
                                          "默认关闭:截单只提示风险,旧清单在下一张定时补货单生成时才作废")
    preflight_times: list[str] = Field(["14:00", "14:45"], title="预检时间",
                                       description="提前检查取数端在线 + DMS 登录状态,失败立即告警")
    remind_interval_min: int = Field(5, title="未确认提醒间隔(分钟)", ge=1, le=60)
    remind_max: int = Field(3, title="未确认最多提醒次数", ge=0, le=20)
    urgent_before_min: int = Field(15, title="截单前多少分钟还没建单就紧急告警", ge=0, le=120)
    scan_retry_interval_min: int = Field(10, title="查询失败自动重试间隔(分钟)", ge=1, le=60,
                                         description="取数(出库明细 + 库存 / 在途 / 可订)失败后每隔多久自动重跑一次;"
                                                     "只重试只读的取数,建单 / 提交从不自动重试")
    scan_retry_stop_before_min: int = Field(30, title="截单前多少分钟停止自动重试", ge=0, le=120)
    # ---- 定时补货(出库驱动)----
    window_cut: str = Field("15:00", title="出库窗口切点",
                            description="取「前一天这个时刻(含)~ 当天这个时刻(不含)」的出库明细")
    confirm_valid_seconds: int = Field(60, title="确认有效期(秒)", ge=15, le=1800,
                                       description="取数成功后开始倒计时,归零必须刷新(整条链路重跑)才能确认,防止重复采购")
    hide_zero_lines: bool = Field(False, title="自动过滤补货数量为 0 的零件",
                                  description="打开后单据页不显示补货数量为 0 的零件(库存够用、厂家缺货、当日可订为 0 等;"
                                              "没勾选的按勾选后会补的数判断),查询失败的照常显示。只影响单据页显示,不影响计算和建单")
    stock_categories: list[str] = Field(["保养零件", "机油", "轮胎", "养护品"], title="常备分类",
                                        description="在库分类表里属于这些分类的出库件进「历史常备件」组(默认勾选)")
    pure_label: str = Field("纯牌", title="纯牌的厂家分类取值", description="出库明细里厂家分类等于它的才参与补货")
    known_mfr: list[str] = Field(["纯牌", "非纯"], title="已知的厂家分类取值", description="出库明细里出现其它取值会告警")
    so_months: int = Field(3, title="SO 单回溯月数", ge=1, le=12, description="近 N 个月 SO(库存补充)单里补过的零件算历史常备件")
    so_sync_weekdays: list[int] = Field([0], title="SO 单同步星期", description="0 = 周一 … 6 = 周日")
    so_sync_time: str = Field("09:00", title="SO 单同步时间", description="门店本地时间 HH:MM")
    so_exclude_status: list[str] = Field(["1"], title="SO 同步排除的订单状态", description="1 = 待提交(还没正式下的单不算)")
    drafts_lookback_days: int = Field(30, title="未提交采购单回看天数", ge=1, le=180,
                                      description="定时补货取数时到 DMS 查最近这么多天里所有「待提交」的采购单(含他人创建),"
                                                  "只在清单和单据页上提示,不参与计算")
    # ---- 每日小结(定时 + 单次补货一起统计)----
    summary_enabled: bool = Field(True, title="发送今日补货小结")
    summary_time: str = Field("16:30", title="今日补货小结发送时间", description="门店本地时间 HH:MM,须晚于截单时间")
    # ---- 业务口径 ----
    warehouses: list[str] = Field(["GTMC广州", "华南GTMC"], title="关注仓", description="名字须与 DMS 全国仓库查询结果一致")
    supplier_code: str = Field("APC40", title="采购单供应商代码",
                               description="查订货主数据(可订 / 价格 / 起订量 / 包装)和建单都要带;广汽丰田原厂为 APC40")
    in_transit_field: str = Field("trans_shipped", title="在途口径",
                                  description="trans_shipped 在途数量(DMS 零件库存查询的「在途数量」)/ unreceived 未收货 / max 两者取大")
    po_remark: str = Field("补货Agent自动创建", title="采购单备注")
    query_fail_alert_ratio: float = Field(0.3, title="查询失败比例告警阈值", ge=0, le=1)
    step_timeouts: StepTimeouts = Field(default_factory=StepTimeouts, title="取数端各步骤超时")
    task_timeouts: TaskTimeouts = Field(default_factory=TaskTimeouts, title="任务整体超时")

    @field_validator("push_time", "cutoff", "window_cut", "so_sync_time", "summary_time")
    @classmethod
    def _hhmm(cls, v: str) -> str:
        v = v.strip().replace(":", ":")
        if not HHMM.match(v):
            raise ValueError("时间格式应为 HH:MM")
        h, m = v.split(":")
        return f"{int(h):02d}:{m}"

    @field_validator("preflight_times")
    @classmethod
    def _hhmm_list(cls, v: list[str]) -> list[str]:
        return [cls._hhmm(x) for x in v if str(x).strip()]

    @field_validator("in_transit_field")
    @classmethod
    def _field(cls, v: str) -> str:
        if v not in ("trans_shipped", "unreceived", "max"):
            raise ValueError("在途口径只能是 trans_shipped / unreceived / max")
        return v

    @field_validator("so_sync_weekdays")
    @classmethod
    def _weekdays(cls, v: list[int]) -> list[int]:
        out = sorted({int(x) for x in v})
        if any(x < 0 or x > 6 for x in out):
            raise ValueError("星期只能是 0(周一)~ 6(周日)")
        return out

    @field_validator("stock_categories", "known_mfr", "so_exclude_status")
    @classmethod
    def _strs(cls, v: list[str]) -> list[str]:
        return [str(x).strip() for x in v if str(x).strip()]

    @field_validator("warehouses")
    @classmethod
    def _wh(cls, v: list[str]) -> list[str]:
        out = [x.strip() for x in v if str(x).strip()]
        if not out:
            raise ValueError("至少要有一个关注仓")
        return out

    @model_validator(mode="after")
    def _timeline(self, info: ValidationInfo) -> "RestockConfig":
        """时间线节点之间的硬冲突(配了也永远不会触发)。只在保存时校验,库里已有的旧值照常加载。"""
        if not (info.context or {}).get("saving"):
            return self
        cut = _mins(self.cutoff)
        if self.auto_push and _mins(self.push_time) >= cut:
            raise ValueError(f"推送时间(push_time){self.push_time} 必须早于截单时间(cutoff){self.cutoff}")
        late = [t for t in self.preflight_times if _mins(t) >= cut] if self.auto_push else []
        if late:
            raise ValueError(f"预检时间(preflight_times){'、'.join(late)} 必须早于截单时间(cutoff){self.cutoff}")
        if self.summary_enabled and _mins(self.summary_time) <= cut:
            raise ValueError(f"小结发送时间(summary_time){self.summary_time} 必须晚于截单时间(cutoff){self.cutoff}")
        if self.scan_retry_stop_before_min > cut:
            raise ValueError("停止自动重试(scan_retry_stop_before_min)不能早于当天 00:00")
        if self.urgent_before_min > cut:
            raise ValueError("未下单紧急告警(urgent_before_min)不能早于当天 00:00")
        return self


class SingleConfig(BaseModel):
    """技能 restock.single 单次补货的参数(开关是技能本身的启用开关)。"""
    max_qty: int = Field(500, title="单次补货最大数量", ge=1, le=10000, json_schema_extra={"unit": "件"},
                         description="防群里手滑打错数量(多打一个 0、把零件号当数量)直接在 DMS 建出大单")
    unknown_retry_min: int = Field(2, title="建单异常:自动核实失败重试间隔", ge=1, le=60, json_schema_extra={"unit": "分钟"},
                                   description="建单结果未知时系统自动到 DMS 核实;取数端不在线或核实失败时隔这么久再试")
    unknown_remind_min: int = Field(30, title="建单异常:多久还没核实完就提醒", ge=5, le=600, json_schema_extra={"unit": "分钟"},
                                    description="超过这个时长:告警升级为严重,并在会话里提醒一次;之后每 2 小时最多再提醒一次")
    multi_enabled: bool = Field(True, title="一次发多个零件时走批量补货",
                                description="打开:一句话里有 2 个及以上带数量的零件 → 一起查询,结果做成单据页链接,"
                                            "在页面上勾选 / 改数量后建单、核对截图后确认提交;关闭:只处理第一个零件,其余提示逐个发")
    multi_max_parts: int = Field(50, title="批量补货一次最多几个零件", ge=2, le=200, json_schema_extra={"unit": "个"},
                                 description="零件太多时查询和建单都会很慢,超过就请对方分几次发")