workflow.py
21.5 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
"""补货流程状态机(确定性,不依赖大模型)。Agent 的工具、单据页按钮都调这里。
idle → scanning → awaiting_confirm ──确认──▶ creating → screenshotting → done(终态:之后不再做任何操作)
└──今天不订──▶ cancelled 任一步失败 ──▶ error(终态)
DMS 相关动作全部下发给门店取数端(edge_hub),这里只编排、算量、发消息、落库。
"""
from __future__ import annotations
import asyncio
import datetime as dt
import os
import re
import secrets
import socket
from pathlib import Path
from . import db, events, planner
from .edge_hub import EdgeError, hub
from .im import gateway
from .settings import S
BUSY = ("scanning", "creating", "screenshotting")
STAGE_CN = {"scanning": "查询中", "awaiting_confirm": "待确认", "creating": "建单中", "screenshotting": "截图中",
"done": "已完成", "cancelled": "已取消", "error": "出错", "superseded": "已作废"}
TERMINAL = ("done", "cancelled", "error", "superseded")
FOLD = 10 # 补货清单超过这么多项时,微信里只列需要留意的项,完整清单看单据页
SCAN_SEC_PER_PART = 6 # 取数端每个配件 3 次请求(库存 / 主数据 / 全国仓),请求间隔 >= 1 秒
CREATE_SEC_PER_LINE = 4
def lan_ip() -> str:
"""本机局域网 IP,按"手机能连上的可能性"排序:192.168 > 10. > 172.16-31(多是 Docker/WSL 虚拟网卡)。"""
found: list[str] = []
try:
found += socket.gethostbyname_ex(socket.gethostname())[2]
except OSError:
pass
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect(("10.255.255.255", 1))
found.append(s.getsockname()[0])
except OSError:
pass
ips = [ip for ip in dict.fromkeys(found) if not ip.startswith(("127.", "169.254."))]
rank = lambda ip: 0 if ip.startswith("192.168.") else 1 if ip.startswith("10.") else 2 if ip.startswith("172.") else 3
return sorted(ips, key=rank)[0] if ips else "127.0.0.1"
def public_base() -> str:
# 设置页 > .env 的 PUBLIC_BASE_URL > config.toml > AUTO_BASE_URL(Docker 里由 start.sh 注入宿主机地址)> 局域网 IP
return (str(S.get("server.public_base_url") or "").rstrip("/")
or os.environ.get("AUTO_BASE_URL", "").rstrip("/")
or f"http://{lan_ip()}:{S.get('server.port')}")
def mock_tag() -> str:
return "【模拟DMS】" if S.get("business.dms_mode") == "mock" else ""
def normalize_said_time(said: str) -> str:
""""现在3点了" → "3点";"15:00" → "15:00";没说时间就用当前时间。"""
said = (said or "").strip()
m = re.search(r"(\d{1,2})\s*[::]\s*(\d{2})", said)
if m:
return f"{int(m.group(1))}:{m.group(2)}"
m = re.search(r"([0-9一二两三四五六七八九十]{1,3})\s*点\s*(半|\d{1,2}\s*分)?", said)
if m:
return m.group(0).replace(" ", "")
return dt.datetime.now().strftime("%H:%M")
class Workflow:
def __init__(self) -> None:
self.run_id: int | None = None
self.lines: list[planner.Line] = []
self._lock = asyncio.Lock()
self._task: asyncio.Task | None = None
# ---------------- 基础 ----------------
def run(self, run_id: int | None = None) -> dict | None:
rid = run_id or self.run_id
return db.one(db.select(db.runs_t).where(db.runs_t.c.id == rid)) if rid else None
@property
def stage(self) -> str:
r = self.run()
return r["status"] if r else "idle"
def _set(self, status: str, **kw) -> None:
db.q(db.update(db.runs_t).where(db.runs_t.c.id == self.run_id).values(status=status, updated_at=db.now(), **kw))
events.emit(f"状态 → {status}", run_id=self.run_id, source="flow")
def link(self, run: dict | None = None) -> str:
run = run or self.run()
return f"{public_base()}/o/{run['token']}"
def expected_link(self, run: dict | None = None) -> str:
run = run or self.run()
return f"{public_base()}/m/expected" + (f"?o={run['token']}" if run else "")
async def say(self, text: str) -> bool:
ok, err = await asyncio.to_thread(gateway.send_text, text)
if not ok and S.get("im.enabled"):
events.emit(f"⚠ 这条消息没发到微信:{err}", "error", run_id=self.run_id, source="im")
return ok
def _spawn(self, coro) -> None:
self._task = asyncio.create_task(self._guard(coro))
async def _guard(self, coro) -> None:
try:
await coro
except asyncio.CancelledError:
raise
except Exception as e: # noqa: BLE001
prev = self.stage
events.emit(f"流程出错({prev}):{type(e).__name__}: {e}", "error", run_id=self.run_id, source="flow")
self._set("error", message=f"{prev}: {e}")
hint = "\n建单结果请到 DMS「采购订单管理」核实,系统不会重试建单。" if prev == "creating" else ""
await self.say(f"❌ 补货流程出错({prev}):{str(e)[:120]}{hint}\n流程已停止,可重新发「帮我查一下库存补货信息」再试。")
def _load_lines(self) -> None:
self.lines = []
for r in db.rows(db.select(db.lines_t).where(db.lines_t.c.run_id == self.run_id).order_by(db.lines_t.c.id)):
self.lines.append(planner.Line(
part_no=r["part_no"], name=r["name"] or "", expected=r["expected"] or 0, stock=r["stock"] or 0,
trans_shipped=r["trans_shipped"] or 0, unreceived=r["unreceived"] or 0, in_transit=r["in_transit"] or 0,
suggested=r["suggested"] or 0, cap=r["cap"], final_qty=r["final_qty"] or 0, tag=r["tag"],
note=r["note"] or "", unit_price=r["unit_price"] or 0, wh=r["wh"] or {}, error=r["error"] or "",
seq=r["seq"]))
def _persist(self) -> None:
with db.engine.begin() as c:
c.execute(db.delete(db.lines_t).where(db.lines_t.c.run_id == self.run_id))
if self.lines:
c.execute(db.insert(db.lines_t), [{
"run_id": self.run_id, "seq": l.seq, "part_no": l.part_no, "name": l.name, "expected": l.expected,
"stock": l.stock, "trans_shipped": l.trans_shipped, "unreceived": l.unreceived,
"in_transit": l.in_transit, "suggested": l.suggested, "cap": l.cap, "final_qty": l.final_qty,
"tag": l.tag, "note": l.note, "unit_price": l.unit_price, "wh": l.wh, "error": l.error or None}
for l in self.lines])
def attach_latest(self) -> None:
"""服务重启后接上最近一条还在等确认的运行(单据页仍可确认)。"""
r = db.one(db.select(db.runs_t).order_by(db.runs_t.c.id.desc()).limit(1))
if r and r["status"] not in TERMINAL:
self.run_id = r["id"]
if r["status"] in BUSY:
self._set("error", message="服务重启时流程正在执行,结果请到 DMS 核实")
else:
self._load_lines()
# ---------------- 1. 触发 ----------------
async def start(self, said_time: str = "", trigger_text: str = "") -> str:
async with self._lock:
st = self.stage
if self.run_id and st in BUSY:
await self.say(f"上一轮补货还在进行中({st}),请稍等,完成后会通知你。")
return "busy"
if self.run_id and st == "awaiting_confirm":
self._set("superseded", message="收到新的查询,旧清单作废")
said = normalize_said_time(said_time or trigger_text)
online, eid, age = hub.online()
token = secrets.token_urlsafe(9)
r = db.q(db.insert(db.runs_t).values(token=token, doc_no="", status="scanning", trigger_text=trigger_text[:500],
said_time=said, dms_mode=str(S.get("business.dms_mode")),
created_at=db.now(), updated_at=db.now()))
self.run_id = r.inserted_primary_key[0]
doc = f"RP-{dt.date.today():%Y%m%d}-{self.run_id:03d}"
db.q(db.update(db.runs_t).where(db.runs_t.c.id == self.run_id).values(doc_no=doc))
self.lines = []
events.emit(f"收到补货查询({trigger_text or '页面触发'}),单据 {doc}", run_id=self.run_id, source="flow")
await self.say(f"现在已经{said},正在为你查询补货信息\n修改期望库存(改完补货单自动更新):{self.expected_link()}")
if not online:
why = f"门店取数端不在线(最后联系 {int(age)} 秒前)" if age else "门店取数端还没有连接过云端"
self._set("error", message=why)
await self.say(f"❌ {why},无法查询 DMS,请先启动门店取数端。")
return "edge_offline"
self._spawn(self._scan(doc))
return "started"
async def _scan(self, doc: str) -> None:
exp = db.expected_list(enabled_only=True)
if not exp:
raise RuntimeError("期望表是空的,请先在管理后台「期望值」页面填写")
events.emit(f"期望表 {len(exp)} 个配件:" + "、".join(f"{e['name']}({e['part_no']})={e['expected']}" for e in exp),
run_id=self.run_id, source="flow")
if len(exp) > 5:
await self.say(f"共 {len(exp)} 个配件,预计约 {max(1, round(len(exp) * 3.5 / 60))} 分钟查完。")
res = await hub.run("scan", {
"parts": [{"part_no": e["part_no"], "name": e["name"], "expected": e["expected"]} for e in exp],
"warehouses": S.list("business.warehouses"), "supplier_code": S.get("business.supplier_code"),
"order_type": S.get("business.order_type")}, self.run_id, extra_seconds=SCAN_SEC_PER_PART * len(exp))
latest = {e["part_no"]: e["expected"] for e in db.expected_list()} # 查询期间改过的期望值以最新为准
items = [dict(it, expected=latest.get(it.get("part_no"), it.get("expected"))) for it in res.get("items") or []]
field = str(S.get("business.in_transit_field") or "trans_shipped")
if field not in planner.IN_TRANSIT_LABEL:
raise RuntimeError(f"business.in_transit_field 配置不对:{field}(只能是 trans_shipped / unreceived / max)")
self.lines = planner.plan(items, field)
self._persist()
with db.engine.begin() as c:
nat = [{"run_id": self.run_id, "part_no": l.part_no, "warehouse": w, "qty": q, "queried_at": db.now()}
for l in self.lines for w, q in l.wh.items()]
if nat:
c.execute(db.insert(db.national_t), nat)
for l in self.lines:
events.emit(f"{l.name} {l.part_no}:期望 {l.expected} −(库存 {l.stock:g} + 在途 {l.in_transit:g})→ 建议 "
f"{l.suggested},订 {l.final_qty}" + (f"({l.note})" if l.note else "")
+ (f" 关注仓 {l.wh}" if l.wh else ""), "error" if l.error else "info", run_id=self.run_id, source="flow")
s = planner.summary(self.lines)
if s["order_count"] == 0:
self._set("done", message="无需补货")
await self.say(self._list_text(doc))
return
self._set("awaiting_confirm")
await self.say(self._list_text(doc))
@staticmethod
def _line_text(l: planner.Line) -> str:
if l.tag == "oos":
return f"{l.seq}. {l.name} ❌缺货不订"
if l.tag == "removed":
return f"{l.seq}. {l.name} 已剔除"
mark = ("(按当日上限)" if l.tag == "capped" else "(关注仓不够)" if l.wh_short
else "(订完仍不足)" if l.short_after else "")
return f"{l.seq}. {l.name} ×{l.final_qty}{mark}"
def _list_text(self, doc: str) -> str:
s = planner.summary(self.lines)
out = [f"📦 补货建议 {doc}{mock_tag()}"]
if s["order_count"] == 0:
out.append(f"查询 {s['total']} 个配件,今天无需补货,流程结束。"
+ (f"({len(s['errors'])} 项查询失败)" if s["errors"] else ""))
return "\n".join(out)
out.append(f"需补 {s['order_count']} 项 · 共 {s['order_qty']} 件 · ≈¥{s['amount']:.2f}")
numbered = [l for l in self.lines if l.seq]
out += [self._line_text(l) for l in numbered[:FOLD]]
rest = []
if len(numbered) > FOLD:
rest.append(f"还有 {len(numbered) - FOLD} 项见补货单")
ok_n = sum(1 for l in self.lines if not l.seq and l.tag != "error")
if ok_n:
rest.append(f"{ok_n} 项库存充足")
if s["errors"]:
rest.append(f"{len(s['errors'])} 项查询失败")
if rest:
out.append("另:" + ",".join(rest))
out += [f"核对/改数量:{self.link()}", "回复「确认」即在 DMS 建待提交单"]
return "\n".join(out)
# ---------------- 2. 调整 / 取消 ----------------
def by_seq(self, seq: int) -> planner.Line | None:
return next((l for l in self.lines if l.seq == seq), None)
async def adjust(self, seq: int, qty: int) -> str:
if self.stage != "awaiting_confirm":
return f"当前没有待确认的补货清单(状态 {self.stage})"
ln = self.by_seq(seq)
if not ln:
return f"没有第 {seq} 项"
before = ln.final_qty
try:
note = planner.set_qty(ln, qty)
except ValueError as e:
return str(e)
self._persist()
events.emit(f"计划员调整:第 {seq} 项 {ln.name} {before} → {ln.final_qty} {note}", run_id=self.run_id, source="flow")
s = planner.summary(self.lines)
return (f"已改:{ln.name} {before} → {ln.final_qty}" + (f"({note})" if note and note != "计划员调整" else "")
+ f"\n现订 {s['order_count']} 项 / {s['order_qty']} 件,回复「确认」下单")
def on_expected_changed(self, part_no: str, expected: int) -> bool:
"""期望值被修改:当前清单待确认时,用本次查到的库存 / 在途 / 仓库数据重算这一行(不重查 DMS)。"""
if not self.run_id or self.stage != "awaiting_confirm":
return False
ln = next((l for l in self.lines if l.part_no == part_no), None)
if not ln or ln.tag == "error" or ln.expected == expected:
return False
field = str(S.get("business.in_transit_field") or "trans_shipped")
new = planner.plan_item({"part_no": ln.part_no, "name": ln.name, "expected": expected, "stock": ln.stock,
"trans_shipped": ln.trans_shipped, "unreceived": ln.unreceived,
"unit_price": ln.unit_price, "daily_surplus": ln.cap, "warehouses": ln.wh}, field)
if new.suggested > 0:
new.seq = ln.seq or max([l.seq or 0 for l in self.lines] + [0]) + 1
self.lines[self.lines.index(ln)] = new
self._persist()
events.emit(f"期望值修改:{ln.name} {ln.expected} → {expected},订购 {ln.final_qty} → {new.final_qty}",
run_id=self.run_id, source="flow")
return True
async def cancel(self) -> str:
if self.stage != "awaiting_confirm":
return f"当前没有待确认的补货清单(状态 {self.stage})"
self._set("cancelled", message="计划员:今天不订")
await self.say("好的,今天不订,流程结束。")
return "cancelled"
# ---------------- 3. 确认 → 建单 → 截图 → 结束 ----------------
async def confirm(self, qty_map: dict[str, int] | None = None, source: str = "微信") -> tuple[bool, str]:
async with self._lock:
if self.stage != "awaiting_confirm":
return False, f"这张清单当前不能确认(状态:{self.stage})"
for l in self.lines:
if qty_map and l.part_no in qty_map and l.tag not in ("oos", "error"):
if int(qty_map[l.part_no]) != l.final_qty:
planner.set_qty(l, int(qty_map[l.part_no]))
self._persist()
ok = [l for l in self.lines if l.orderable]
if not ok:
return False, "没有可订的配件;如果今天不订,请点「今天不订」"
if not hub.online()[0]:
return False, "门店取数端不在线,暂时不能建单"
self._set("creating")
s = planner.summary(self.lines)
await self.say(f"✅ 已确认 {s['order_count']} 项 / {s['order_qty']} 件,正在 DMS 建单(待提交)…")
self._spawn(self._create(ok))
return True, "已收到,正在创建采购单"
async def _create(self, ok_lines: list[planner.Line]) -> None:
res = await hub.run("create_po", {
"lines": [{"part_no": l.part_no, "name": l.name, "qty": l.final_qty} for l in ok_lines],
"supplier_code": S.get("business.supplier_code"), "order_type": S.get("business.order_type"),
"remark": S.get("business.po_remark")}, self.run_id, extra_seconds=CREATE_SEC_PER_LINE * len(ok_lines))
row = res.get("row") or {}
order_no = res.get("order_no")
db.q(db.insert(db.po_t).values(run_id=self.run_id, order_id=res.get("order_id"), order_no=order_no,
supplier_code=row.get("supplierCode"), order_type=row.get("orderType"),
status="待提交", item_num=str(row.get("itemNum") or ""),
total_amount=row.get("totalAmount"), lines=res.get("details"), shots=[],
created_at=db.now()))
self._set("screenshotting", order_no=order_no, order_id=res.get("order_id"))
if res.get("mismatch"):
events.emit("⚠ DMS 回查明细与请求不一致:" + ";".join(res["mismatch"]), "warn", run_id=self.run_id)
shot_err, files = "", []
try:
sres = await hub.run("screenshot_po", {"order_no": order_no, "row": row,
"part_nos": [l.part_no for l in ok_lines]}, self.run_id)
files = sres.get("files") or []
if not files:
shot_err = "取数端说截图成功,但没有收到图片文件"
except EdgeError as e:
shot_err = str(e)
db.q(db.update(db.po_t).where(db.po_t.c.run_id == self.run_id, db.po_t.c.order_no == order_no).values(shots=files))
sent = 0
for f in files:
ok, err = await asyncio.to_thread(gateway.send_image, S.data_dir() / "shots" / f["file"],
public_base() + f["url"])
sent += ok
if not ok:
shot_err = shot_err or f"截图已生成,但发微信失败:{err}"
msg = [f"✅ 已经创建好采购单 {order_no}(待提交),请验收{mock_tag()}",
f"{len(ok_lines)} 项 · ¥{row.get('totalAmount')}" + (f" · 截图 {sent} 张见上" if sent and not shot_err else "")]
if shot_err:
msg.append(f"❌ 截图未发出:{shot_err[:80]}\n详情:{self.link()}")
msg.append("流程结束,未提交;演示单请到 DMS 人工删除。" if S.get("business.dms_mode") != "mock" else "流程结束(模拟 DMS)。")
await self.say("\n".join(msg))
self._set("done", message=("截图失败:" + shot_err) if shot_err else "完成")
events.emit(f"流程结束:采购单 {order_no}" + (f";截图问题:{shot_err}" if shot_err else ""),
"warn" if shot_err else "ok", run_id=self.run_id, source="flow")
# ---------------- 查询 ----------------
def status_text(self) -> str:
r = self.run()
if not r:
return "当前没有补货单,发「帮我查一下库存补货信息」开始。"
s = planner.summary(self.lines) if self.lines else {}
return (f"{r['doc_no']}:{STAGE_CN.get(r['status'], r['status'])}"
+ (f",采购单 {r['order_no']}" if r.get("order_no") else "")
+ (f",可订 {s.get('order_count')} 项 / {s.get('order_qty')} 件" if s else "")
+ f"\n{self.link(r)}")
def page_state(self, token: str) -> dict | None:
r = db.one(db.select(db.runs_t).where(db.runs_t.c.token == token))
if not r:
return None
lines = [planner.Line(**{k: v for k, v in x.items() if k in planner.Line.__dataclass_fields__})
for x in db.rows(db.select(db.lines_t).where(db.lines_t.c.run_id == r["id"]).order_by(db.lines_t.c.id))]
for l in lines:
l.wh = l.wh or {}
po = db.one(db.select(db.po_t).where(db.po_t.c.run_id == r["id"]).order_by(db.po_t.c.id.desc()).limit(1))
evs = [e for e in events.recent(run_id=r["id"], limit=120) if e["source"] in ("flow", "edge", "im")][-40:]
return {"run": {k: (str(v) if isinstance(v, dt.datetime) else v) for k, v in r.items()},
"is_current": r["id"] == self.run_id, "lines": [l.to_dict() for l in lines],
"summary": planner.summary(lines), "po": po and {**po, "created_at": str(po["created_at"])},
"events": [{"ts": str(e["ts"]), "level": e["level"], "detail": e["detail"]} for e in evs],
"mock": S.get("business.dms_mode") == "mock", "cutoff": S.get("business.cutoff"),
"in_transit_label": planner.IN_TRANSIT_LABEL.get(str(S.get("business.in_transit_field")), "调拨在途")}
wf = Workflow()