multi_service.py
10.9 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
"""批量补货(会话里一次发多个「零件号 数量」)的流程:发起 / 查询 / 会话里的引导。
复用单次补货的查询链路(取数端 restock.quote:库存 / 在途 / 当日可订 / 关注仓 / 单价,planner 按单次补货的规则算量),
结果不在会话里逐个问「订不订」,而是做成单据页链接(同定时补货):页面上勾选、改数量 → 「确认,建单」→ 建好 DMS 待提交
采购单并把截图放进页面 → 核对后点「确认提交」才正式提交。确认 / 刷新 / 建单 / 截图 / 提交 / 不订都走 service.py 里
定时补货的单据页那套(kind in PAGE_KINDS)。
每个会话同时只开一张批量补货(trigger_target_id),和单次补货互不影响;消息只发回所属会话。
上一张批量补货只报了价(待确认)→ 发新的就作废它;已在建单 / 待确认提交 / 提交中 → 不新建,回上一张的链接。
RestockService 继承 MultiMixin,调用方式:svc.multi_request(...)。
"""
from __future__ import annotations
import asyncio
import logging
from ...core import db
from ...core.db import select, update
from ...core.types import Actor, EdgeError, EdgeTimeout
from ...models import runs_t
from ...services import edge
from . import planner
from .config import ORDER_TYPE
from .states import OPEN, STAGE_CN, _bool
log = logging.getLogger("server.restock")
class MultiMixin:
"""批量补货。依赖 RestockService 的基础方法(cfg / single_cfg / lock / run / lines / say / audit / emit / spawn …)。"""
def multi_open(self, sid: int, target_id: int | None = None) -> dict | None:
"""这个会话还没走完的批量补货(每个会话同时只有一张)。target_id 不传 = 本门店最近一张。"""
st = select(runs_t).where(runs_t.c.store_id == sid, runs_t.c.kind == "multi", runs_t.c.status.in_(OPEN))
if target_id:
st = st.where(runs_t.c.trigger_target_id == target_id)
return db.one(st.order_by(runs_t.c.id.desc()).limit(1))
async def multi_request(self, sid: int, actor: Actor, parts: list[tuple[str, int]], skipped: list[str],
text: str = "") -> str:
"""发起批量补货。parts = [(零件号, 数量)](数量 > 0,已去重);skipped = 没写数量、这次没纳入的零件号。
返回要回到会话里的话(「收到,查一下这 N 个零件…」或不能新建的原因)。"""
cfg = self.single_cfg(sid)
parts = [(p.strip().upper(), int(q)) for p, q in parts if p and int(q or 0) > 0]
if len(parts) > cfg.multi_max_parts:
return (f"一次发了 {len(parts)} 个零件,批量补货一次最多 {cfg.multi_max_parts} 个,请分几次发"
"(或在后台「智能助手 → 技能 → 单次补货」调整上限)")
over = [f"{p} × {q}" for p, q in parts if q > cfg.max_qty]
if over:
return (f"{'、'.join(over)} 超过单个零件的数量上限 {cfg.max_qty} 个,请确认数量后重新发"
"(或在后台「智能助手 → 技能 → 单次补货」调整上限)")
tid = self.session_of(actor)
prev = ""
async with self.lock(sid):
cur = self.multi_open(sid, tid)
if cur and cur["status"] == "awaiting_confirm" and not cur["create_unknown_at"]:
prev = self._supersede_multi(cur, actor)
elif cur:
self.audit(sid, actor, "run.start_blocked", target_type="run", target_id=str(cur["id"]),
ref=self.ref(cur["id"]), detail={"reason": "上一张批量补货还没走完", "kind": "multi",
"status": cur["status"], "text": text,
"parts": [{"part_no": p, "qty": q} for p, q in parts]})
return self.t(sid, "msg_multi_pending", doc=cur["doc_no"], status=cur["status"],
stage=STAGE_CN.get(cur["status"], cur["status"]), order_no=cur["order_no"] or "",
link=self.link(cur))
rid = self._new_run(sid, "multi", "chat", actor, text)
run = self.run(rid)
self.audit(sid, actor, "run.start", target_type="run", target_id=str(rid), ref=self.ref(rid),
detail={"kind": "multi", "text": text, "doc_no": run["doc_no"], "skipped": skipped,
"parts": [{"part_no": p, "qty": q} for p, q in parts]})
self.emit(f"批量补货({actor.name}):{len(parts)} 个零件,单据 {run['doc_no']}", store_id=sid,
ref=self.ref(rid))
self.spawn(self._multi_guard(rid, parts), f"restock-multi-{rid}")
msg = self.t(sid, "msg_multi_querying", parts=[{"part_no": p, "qty": q} for p, q in parts], skipped=skipped)
return f"{prev}\n\n{msg}" if prev else msg
def _supersede_multi(self, cur: dict, actor: Actor) -> str:
"""上一张批量补货只报了价(DMS 里没有单):发了新的就作废(调用方持锁)。返回拼在回复前面的话。"""
sid = cur["store_id"]
self._set(cur["id"], "superseded", message=f"{actor.name} 发了新的批量补货,这张清单作废(DMS 里没有建单)")
self.audit(sid, actor, "run.supersede", target_type="run", target_id=str(cur["id"]), ref=self.ref(cur["id"]),
detail={"reason": "发了新的批量补货", "owner": cur["triggered_by"],
"text": actor.extra.get("text", "")})
return self.t(sid, "msg_multi_superseded", doc=cur["doc_no"])
async def _multi_guard(self, rid: int, parts: list[tuple[str, int]] | None = None, state: dict | None = None,
refresh: bool = False) -> None:
try:
await self._multi_quote(rid, parts, state, refresh)
except asyncio.CancelledError:
raise
except (EdgeError, EdgeTimeout) as e:
await self._scan_failed(rid, str(e), refresh=refresh)
except Exception as e: # noqa: BLE001
log.exception("批量补货查询出错")
await self._scan_failed(rid, f"{type(e).__name__}: {e}", refresh=refresh)
async def _multi_quote(self, rid: int, parts: list[tuple[str, int]] | None = None, state: dict | None = None,
refresh: bool = False) -> None:
"""查全部零件(一个 restock.quote 任务)→ 按单次补货的规则算量 → 存清单 → 待确认,会话里发单据页链接。
refresh = 单据页「刷新」:零件和群里要的数量取自现有清单,页面上的勾选 / 改过的数量(state)保留,不再发群消息。"""
run = self.run(rid)
sid = run["store_id"]
cfg = self.cfg(sid)
ref = self.ref(rid)
expect = ("refreshing",) if refresh else ("scanning",)
if parts is None:
parts = [(l.part_no, int(l.default_expected or 0)) for l in self.lines(rid)]
online, _ = await edge.wait_online(sid, 30)
if not online:
raise EdgeError("门店取数端不在线")
q = await self.edge_run(sid, "restock.quote", {
"parts": [{"part_no": p, "name": "", "national": True} for p, _ in parts], "warehouses": cfg.warehouses,
"supplier_code": cfg.supplier_code, "order_type": ORDER_TYPE, "in_transit_field": cfg.in_transit_field},
timeout=cfg.task_timeouts.scan(len(parts)), ref=ref, step_timeouts=cfg.step_timeouts.model_dump())
if self.run(rid)["status"] not in expect: # 查询期间被取消 / 作废:结果丢弃
self.emit(f"批量补货 {run['doc_no']} 已不在查询中,查询结果不再处理", store_id=sid, ref=ref)
return
got = {str(it.get("part_no") or "").strip().upper(): it for it in q.get("items") or []}
lines = []
for pn, qty in parts:
it = got.get(pn) or {"part_no": pn, "error": "取数端没有返回这个零件"}
ln = planner.plan_multi(dict(it, part_no=pn), qty, cfg.in_transit_field)
s = (state or {}).get(pn)
if s is not None: # 刷新:保留页面上的勾选和改过的数量
ln.checked = _bool(s.get("checked"))
exp = s.get("expected")
if exp is not None and str(exp).strip() != "":
exp = max(int(float(exp)), 0)
ln.modified = exp != ln.default_expected
ln.expected = exp if ln.modified else ln.default_expected
planner.compute_multi(ln)
lines.append(ln)
planner.number(lines)
self.persist(rid, sid, lines)
db.q(update(runs_t).where(runs_t.c.id == rid).values(fetch_seq=(run["fetch_seq"] or 0) + 1,
data_fetched_at=self.now(sid)))
run = self.run(rid)
self.snapshot(run, "refreshed" if refresh else "multi_quote", lines,
extra={"requested": [{"part_no": p, "qty": q} for p, q in parts], "state": state or None})
s = planner.summary(lines)
bad = [l.to_dict() for l in lines if not l.orderable]
if not refresh and not s["order_count"]:
if self._transition(rid, "done", expect, message="查完都不能订:" + ";".join(
f"{b['part_no']} {b['note'] or b['label']}" for b in bad)[:480]):
await self.say(run, self.t(sid, "msg_multi_not_orderable", bad=bad, n=len(lines)))
return
if not self._transition(rid, "awaiting_confirm", expect, listed_at=db.now(), message=None):
return
if refresh:
self.emit(f"批量补货 {run['doc_no']} 刷新完成:可订 {s['order_count']} 项 · {s['order_qty']} 件",
store_id=sid, ref=ref)
return
await self.say(run, self.t(sid, "msg_multi_quote", s=s, n=len(lines), bad=bad, link=self.link(run),
valid_min=max(cfg.confirm_valid_seconds // 60, 1)))
# ---------------------------------------------------------------- 会话里的引导(批量补货只在单据页上操作)
def multi_link_text(self, sid: int, run: dict, action: str) -> str:
"""会话里对批量补货说了「订 / 提交 / 不订」:不改单据,回单据页链接(action = confirm / submit / cancel)。"""
return self.t(sid, "msg_multi_use_link", doc=run["doc_no"], status=run["status"],
stage=STAGE_CN.get(run["status"], run["status"]), order_no=run["order_no"] or "",
link=self.link(run), action=action)
def multi_status_text(self, sid: int, target_id: int | None) -> tuple[str, str]:
run = self.multi_open(sid, target_id)
if not run:
return "", ""
return self.multi_link_text(sid, run, "status"), self.ref(run["id"])