__init__.py 7.04 KB
"""业务功能登记处。一个功能 = 一组定时任务 + 对话技能(skills.py)+ 话术 + 后台接口 + 取数端任务类型,并声明支持哪些厂商系统。

门店开通某个功能 = atrs_sys_store_feature 里一行(enabled + 参数)。给另一家卖同品牌的门店开通,只需要打开开关、
填好该门店的厂商账号和功能参数即可。现在只有一个功能:restock 库存补货。
"""
from __future__ import annotations

import datetime as dt
import time
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Awaitable, Callable

from ..core import db
from ..core.db import insert, select, update
from ..models import store_features_t

if TYPE_CHECKING:
    from fastapi import APIRouter
    from pydantic import BaseModel

    from .skills import Skill


@dataclass
class ToolResult:
    """智能体工具的返回。replied=True 表示工具已经直接给计划员发了消息,智能体不再追加回复。
    ref:这次操作涉及的单据(如 restock:run:12),智能体的决策留痕带上它,单据的审计时间线里能看到。"""
    text: str
    replied: bool = True
    ref: str = ""


@dataclass(frozen=True)
class AgentTool:
    """暴露给智能体的工具。handler(store_id, actor, target, **args) -> ToolResult;parameters 为 JSON Schema。"""
    name: str
    description: str
    parameters: dict
    handler: Callable[..., Awaitable[ToolResult]]


@dataclass
class ChatContext:
    """某个功能在收到一句话时的状态。state:给大模型看的「当前状态」(以它为准);
    ref:这句话关联的单据(审计、消息记录挂到这张单上);data:技能自己用的附加数据。"""
    state: str = ""
    ref: str = ""
    data: Any = None


@dataclass
class SandboxBox:
    """试聊沙盒的一局:助手按顺序「发出」的消息 + 各功能自己的沙盒状态。工具只往这里写,不碰 DMS、不发企微。"""
    store_id: int
    messages: list[dict] = field(default_factory=list)
    state: dict[str, Any] = field(default_factory=dict)
    history: list[dict] = field(default_factory=list)     # 这局试聊的收发记录(给大模型当「最近聊天记录」)

    def say(self, text: str, kind: str = "message") -> None:
        self.messages.append({"text": text, "kind": kind})


@dataclass(frozen=True)
class JobSpec:
    """在门店本地时间的某些时刻执行一次的定时任务;同一门店同一天同一时刻只触发一次(跨重启)。
    weekdays 返回 None = 每天;返回 [0, 3] = 只在周一、周四(0 = 周一 … 6 = 周日)。"""
    key: str
    title: str
    times: Callable[[Any], list[str]]
    handler: Callable[[int, dt.datetime, str], Awaitable[None]]   # (store_id, now, slot "HH:MM")
    deadline: Callable[[Any], str | None] = lambda cfg: None
    weekdays: Callable[[Any], list[int] | None] = lambda cfg: None


class Feature:
    key: str = ""
    name: str = ""
    description: str = ""
    dms: tuple[str, ...] = ()                   # 支持的厂商系统(连接器代码)
    config_model: type["BaseModel"] | None = None
    edge_tasks: tuple[str, ...] = ()

    async def on_startup(self) -> None: ...

    def router(self) -> "APIRouter | None":
        return None

    def public_router(self) -> "APIRouter | None":
        return None

    def skills(self) -> list["Skill"]:
        """这个功能提供的对话技能(单次补货、定时补货进度 …)。会话里的一句话由技能接手,见 features/skills.py。"""
        return []

    def jobs(self) -> list[JobSpec]:
        return []

    async def on_tick(self, store_id: int, now: dt.datetime) -> None: ...


FEATURES: dict[str, Feature] = {}
_cache: dict[tuple[int, str], tuple[float, dict | None]] = {}


def register(f: Feature) -> Feature:
    FEATURES[f.key] = f
    return f


def load_all() -> None:
    from . import skills
    from .restock import feature as _restock  # noqa: F401  导入即登记
    skills.load(FEATURES.values())


def get(key: str) -> Feature:
    return FEATURES[key]


def _row(store_id: int, key: str) -> dict | None:
    hit = _cache.get((store_id, key))
    if hit and time.time() - hit[0] < 5:
        return hit[1]
    r = db.one(select(store_features_t).where(store_features_t.c.store_id == store_id,
                                              store_features_t.c.feature == key))
    _cache[(store_id, key)] = (time.time(), r)
    return r


def is_enabled(store_id: int, key: str) -> bool:
    r = _row(store_id, key)
    return bool(r and r["enabled"])


def enabled_features(store_id: int) -> list[str]:
    return [k for k in FEATURES if is_enabled(store_id, k)]


def enabled_stores(key: str) -> list[int]:
    from ..services import stores
    active = {s["id"] for s in stores.stores(active_only=True)}
    return [r["store_id"] for r in db.rows(select(store_features_t.c.store_id).where(
        store_features_t.c.feature == key, store_features_t.c.enabled.is_(True))) if r["store_id"] in active]


def config(store_id: int, key: str):
    f = FEATURES[key]
    r = _row(store_id, key)
    vals = db.jload(r["config"], {}) if r else {}
    try:
        return f.config_model(**(vals or {}))
    except Exception:  # noqa: BLE001  库里的值不合法(参数定义改过):退回默认,不让流程停摆
        return f.config_model()


def save(store_id: int, key: str, *, enabled: bool | None = None, values: dict | None = None,
         by: str = "") -> tuple[dict, dict]:
    """保存开通状态与参数(values 合并到现有参数后整体校验)。返回 (改前, 改后)。"""
    f = FEATURES[key]
    cur = _row(store_id, key)
    before_cfg = config(store_id, key).model_dump(mode="json")
    before = {"enabled": bool(cur and cur["enabled"]), "config": before_cfg}
    # 只切换开通(values=None)时沿用已存参数,不做保存校验:旧参数碰上新加的校验规则也不至于开 / 关不了
    cfg = before_cfg if values is None else \
        f.config_model.model_validate(before_cfg | values, context={"saving": True}).model_dump(mode="json")
    en = before["enabled"] if enabled is None else bool(enabled)
    with db.tx() as c:
        if cur:
            c.execute(update(store_features_t).where(store_features_t.c.store_id == store_id,
                                                     store_features_t.c.feature == key)
                      .values(enabled=en, config=cfg, updated_by=by, updated_at=db.now()))
        else:
            c.execute(insert(store_features_t).values(store_id=store_id, feature=key, enabled=en, config=cfg,
                                                      updated_by=by, updated_at=db.now()))
    _cache.clear()
    from ..services import stores
    stores.bump_config(store_id)              # 功能参数也随配置下发给取数端(本地菜单用)
    return before, {"enabled": en, "config": cfg}


def catalog(store_id: int) -> list[dict]:
    return [{"key": k, "name": f.name, "description": f.description, "dms": list(f.dms),
             "enabled": is_enabled(store_id, k)} for k, f in FEATURES.items()]