workflow.py
20.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
"""补货 Agent 工作流(状态机)。
idle → fetching → awaiting_list ──(单据页确认)──▶ building → awaiting_submit ──(单据页确认提交)──▶ submitting → done
└──(今天不订)──▶ cancelled
个人微信只能发文字 + 链接,所以:
- 聊天里只发文字,并附一个「单据页」链接(/order/<token>);
- 清单确认 / 改数量 / 看系统截图 / 确认提交 / 下载订货明细,全部在单据页里完成;
- 单据页确认后,Agent 在聊天里回复「已收到订购信息」并继续执行。
两道闸:① 清单确认(先建单、后执行);② 建单后给系统截图,计划员确认才点「检查并提交」。
Agent 只通过 Channel 发文字,只通过浏览器与厂家 DMS 交互。
"""
import asyncio
import csv
import io
import os
import secrets
import time
from .. import db as D
from ..channel.base import Channel, UserEvent
from . import nlu, planner as P
from .browser_ops import DmsBrowser, DmsError
PLANNER = "张三"
CUTOFF_MIN = 60 # 演示时钟:15:00 推送,距 16:00 截单 60 分钟
BUSY_STAGES = ("fetching", "building", "submitting")
def auto_order() -> bool:
"""AUTO_ORDER=1 才继续自动建单/提交(需求文档的完整闭环);默认只做到「确认订购」为止。"""
return os.environ.get("AUTO_ORDER", "0") == "1"
def _hms() -> str:
return D.now().strftime("%H:%M:%S")
def public_base() -> str:
"""单据页链接的对外地址(手机微信要能打开):设置页 > 环境变量 PUBLIC_BASE_URL > 本机地址。"""
from ..im_server import store as im_store
return (im_store.get_setting("public_base_url") or os.environ.get("PUBLIC_BASE_URL")
or os.environ.get("DEMO_BASE_URL", "http://127.0.0.1:8000"))
def order_url(token: str) -> str:
return f"{public_base().rstrip('/')}/order/{token}"
def ledger_rows(lines: list[dict]) -> list[dict]:
"""订货明细表(含未下单行及原因)。lines 为 Line.to_dict() 或 replenish_lines 行。"""
out = []
for l in lines:
ordered = bool(l.get("po_no"))
if ordered:
status = "按可订上限" if l["tag"] == "capped" else "已提交"
else:
status = {"in_transit_ok": "在途已达标", "enough": "库存充足", "oos": "厂家缺货",
"removed": "计划员剔除"}.get(l["tag"], l.get("note") or "未下单")
out.append({
"po_no": l.get("po_no") or "——", "part_no": l["part_no"], "name": l["name"],
"qty": l["final_qty"] if ordered else 0, "stock": l["stock"], "in_transit": l["in_transit"],
"type": "SO" if ordered else "——", "time": (l.get("ordered_at") or "——") if ordered else "——",
"status": status,
})
return out
def _db_lines(run_id: int) -> list[dict]:
with D.db() as con:
return [dict(r) for r in con.execute("SELECT * FROM replenish_lines WHERE run_id=? ORDER BY seq", (run_id,))]
def ledger_csv(run_id: int) -> str:
buf = io.StringIO()
w = csv.writer(buf)
w.writerow(["PO单号", "配件码", "零件名称", "订购数量", "下单时库存", "在途", "订单类型", "下单时间", "状态"])
for r in ledger_rows(_db_lines(run_id)):
w.writerow([r["po_no"], r["part_no"], r["name"], r["qty"], r["stock"], r["in_transit"], r["type"], r["time"], r["status"]])
return buf.getvalue()
def find_run(token: str) -> dict | None:
with D.db() as con:
r = con.execute("SELECT * FROM replenish_runs WHERE token=?", (token,)).fetchone()
return dict(r) if r else None
def _latest_shot(run_id: int, label: str) -> str:
files = sorted(D.SHOT_DIR.glob(f"run{run_id}_{label}_*.png"))
return f"/shots/{files[-1].name}" if files else ""
def page_state(token: str, current_run_id: int | None) -> dict | None:
"""单据页数据:完全从 SQLite + 截图文件重建,服务重启后旧单据页仍可查看。"""
run = find_run(token)
if not run:
return None
rid = run["id"]
lines = []
for r in _db_lines(rid):
ln = P.Line(r["part_no"], r["name"], r["stock"], r["in_transit"], r["expected"], r["suggested"], r["cap"],
r["final_qty"], r["tag"], r["note"] or "", po_no=r["po_no"] or "", ordered_at=r["ordered_at"] or "")
lines.append(ln)
view, n = [], 0
for l in lines:
d = l.to_dict()
if l.suggested > 0:
n += 1
d["seq"] = n if l.suggested > 0 else None
view.append(d)
s = P.summary(lines)
caps = [{"seq": d["seq"], "name": d["name"], "cap": d["cap"], "diff": d["diff"], "want": d["suggested"]}
for d in view if d["tag"] == "capped"]
warnings = []
for d in view:
if d["tag"] == "capped":
warnings.append(f"第 {d['seq']} 项 {d['name']} 建议订 {d['suggested']},今日剩余可订仅 {d['cap']}")
elif d["tag"] == "oos":
warnings.append(f"第 {d['seq']} 项 {d['name']} 广州仓 / 华南仓均无货")
with D.db() as con:
events = [dict(e) for e in con.execute(
"SELECT ts, level, detail FROM agent_events WHERE run_id=? ORDER BY id DESC LIMIT 8", (rid,))][::-1]
ordered = [l for l in lines if l.po_no]
return {
"doc_no": run["doc_no"], "run_date": run["run_date"], "stage": run["status"],
"is_current": rid == current_run_id, "lines": view, "summary": s, "warnings": warnings, "caps": caps,
"minutes_left": CUTOFF_MIN,
"inventory_shot": _latest_shot(rid, "inventory"), "pending_shot": _latest_shot(rid, "pending"),
"submitted_shot": _latest_shot(rid, "submitted"),
"orders": [{"po_no": l.po_no, "name": l.name, "part_no": l.part_no, "qty": l.final_qty} for l in ordered],
"ledger": ledger_rows([l.to_dict() for l in lines]) if run["status"] == "done" else None,
"ledger_total": f"合计 {sum(l.final_qty for l in ordered)} 件 / {len(ordered)} 个零件 预计到货:明天上午",
"csv_url": f"/api/run/{rid}/ledger.csv", "events": events,
}
class Workflow:
def __init__(self, channel: Channel, base_url: str):
self.ch = channel
self.base_url = base_url
self.dms = DmsBrowser(base_url, D.DEMO_USER, D.DEMO_PASS, on_step=self._step)
self._stage = "idle"
self.run_id: int | None = None
self.doc_no = ""
self.token = ""
self.lines: list[P.Line] = []
self._task: asyncio.Task | None = None
channel.on_event(self.handle)
# ---------- 通用 ----------
@property
def stage(self) -> str:
return self._stage
@stage.setter
def stage(self, v: str) -> None:
self._stage = v
if self.run_id is not None and v != "idle":
with D.db() as con:
con.execute("UPDATE replenish_runs SET status=? WHERE id=?", (v, self.run_id))
self.ch.publish("stage", {"stage": v})
@property
def link(self) -> str:
return order_url(self.token)
async def _step(self, text: str) -> None:
ev = D.log_event(self.run_id, text)
self.ch.publish("agent_event", ev)
async def say(self, text: str, mention: bool = False) -> None:
await self.ch.send({"kind": "text", "text": text, "mention": PLANNER if mention else ""})
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
D.log_event(self.run_id, f"出错:{type(e).__name__}: {e}", "error")
self.ch.publish("agent_event", {"ts": D.ts(), "level": "error", "detail": f"出错:{e}"})
prev = self.stage
self.stage = "error"
await self.say(f"❌ 执行中断({prev}):{e}\n已停止。可点右上角「重置演示」后重新开始。")
def _shot_path(self, label: str):
return D.SHOT_DIR / f"run{self.run_id}_{label}_{int(time.time())}.png"
def _by_seq(self, seq: int) -> P.Line | None:
n = 0
for l in self.lines:
if l.suggested > 0:
n += 1
if n == seq:
return l
return None
def _persist(self) -> None:
with D.db() as con:
con.execute("DELETE FROM replenish_lines WHERE run_id=?", (self.run_id,))
for i, l in enumerate(self.lines, 1):
con.execute(
"INSERT INTO replenish_lines VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
(self.run_id, i, l.part_no, l.name, l.stock, l.in_transit, l.expected, l.suggested, l.cap,
l.final_qty, l.tag, l.note, l.po_no, l.ordered_at),
)
# ---------- 触发 / 重置 ----------
async def start_run(self) -> tuple[bool, str]:
if self.stage not in ("idle", "confirmed", "done", "cancelled", "error"):
return False, "已有进行中的补货单,请先处理或重置"
self.lines = []
self.token = secrets.token_urlsafe(8)
with D.db() as con:
cur = con.execute(
"INSERT INTO replenish_runs(doc_no,run_date,status,created_at,cutoff,token) VALUES('',?,?,?,?,?)",
(D.now().strftime("%Y-%m-%d"), "fetching", D.ts(), D.get_config("cutoff", "16:00"), self.token),
)
self.run_id = cur.lastrowid
self.doc_no = f"RP-{D.now().strftime('%Y%m%d')}-{self.run_id:02d}"
con.execute("UPDATE replenish_runs SET doc_no=? WHERE id=?", (self.doc_no, self.run_id))
self.stage = "fetching"
await self.dms.close() # 每次演示都用全新的 Chrome(上次的被关掉/卡住也不影响)
await self.say(f"⏰ {D.get_config('push_time', '15:00')} 到点了,开始登录厂家系统抓取门店实时库存(单据号 {self.doc_no}),请稍等…")
self._spawn(self._fetch())
return True, self.doc_no
async def reset(self) -> None:
if self._task and not self._task.done():
self._task.cancel()
await self.dms.close()
D.init(reset=True)
self._stage, self.run_id, self.lines, self.doc_no, self.token = "idle", None, [], "", ""
self.ch.publish("stage", {"stage": "idle"})
self.ch.publish("reset", {})
# ---------- 1. 取数 + 比对 + 推清单 ----------
async def _fetch(self) -> None:
store = await self.dms.read_store_inventory()
await self.dms.screenshot(self._shot_path("inventory"))
with D.db() as con:
expected = {r["part_no"]: r["expected"] for r in con.execute("SELECT * FROM expected_levels")}
await self._step(f"读取计划员设定的期望水位:{len(expected)} 个受管控零件")
lines = []
for r in store:
exp = expected.get(r["part_no"])
if exp is None:
continue
wh = None
if P.needs_warehouse_check(r["stock"], r["in_transit"], exp):
wh = await self.dms.query_warehouses(r["part_no"])
ln = P.plan_line(r["stock"], r["in_transit"], r["daily_remaining"], exp, r["part_no"], r["name"], wh)
await self._step(f"{r['name']}:期望 {exp} −(库存 {r['stock']} + 在途 {r['in_transit']})→ 建议 {ln.suggested}"
+ (f",{ln.note}" if ln.note else ""))
lines.append(ln)
self.lines = P.sort_lines(lines)
self._persist()
self.stage = "awaiting_list"
await self.say(self._list_text())
def _list_text(self) -> str:
s = P.summary(self.lines)
rows, warn, n = [], [], 0
for l in self.lines:
basis = f"库存{l.stock}+在途{l.in_transit},期望{l.expected}"
if l.suggested <= 0:
rows.append(f"— {l.name} 建议 0({l.note};{basis})")
continue
n += 1
if l.tag == "capped":
rows.append(f"{n}. {l.name} 建议 {l.suggested} → 订 {l.final_qty}(今日剩余可订仅 {l.cap})")
warn.append(f"· 第 {n} 项 {l.name} 建议订 {l.suggested},今日剩余可订仅 {l.cap}")
elif l.tag == "oos":
rows.append(f"{n}. {l.name} ❌ 厂家缺货,不订")
warn.append(f"· 第 {n} 项 {l.name} 广州仓 / 华南仓均无货")
else:
rows.append(f"{n}. {l.name} 订 {l.final_qty}({basis})")
parts = [f"📦 今日库存补货建议({self.doc_no})",
f"已同步门店实时库存,比对你设定的期望水位,共 {s['need_count']} 项需要补货:", "————————", *rows, "————————"]
if warn:
parts += [f"⚠️ {len(warn)} 项需你决策:", *warn]
parts += [f"小计:正常可订 {s['order_count']} 项 / {s['order_qty']} 件 距 16:00 截单还有 {CUTOFF_MIN} 分钟",
"👉 点开链接查看完整清单,可直接改数量,改完点「确认订购」:", self.link]
return "\n".join(parts)
# ---------- 聊天里的文字指令(兜底;主入口是单据页) ----------
async def handle(self, ev: UserEvent) -> None:
if ev.type != "text":
return
r = nlu.parse(ev.text)
it = r["intent"]
if self.stage in BUSY_STAGES:
await self.say("我正在处理上一步,请稍等几秒 ⏳")
return
if self.stage == "awaiting_list":
if it == "adjust":
await self._adjust_by_text(r["edits"])
elif it == "cancel":
await self.cancel()
elif it in ("confirm", "submit"):
await self.say(f"请打开单据页核对后点「确认订购」👉 {self.link}")
else:
await self.say(f"没太听懂 🤔 请打开单据页直接改数量并确认 👉 {self.link}\n也可以说「第 4 项不用订了」「今天不订了」。")
elif self.stage == "awaiting_submit":
await self.say(f"订单已在系统里建好(待提交)。请打开单据页核对系统截图,没问题点「确认提交」👉 {self.link}")
else:
await self.say("当前没有待处理的补货单。点右上角「▶ 立即触发推送」可以开始一次演示。")
async def _adjust_by_text(self, edits: list[tuple[int, int]]) -> None:
before = {l.part_no: l.final_qty for l in self.lines}
bad = []
for seq, qty in edits:
ln = self._by_seq(seq)
if not ln:
bad.append(seq)
continue
P.set_qty(ln, qty)
self._persist()
s = P.summary(self.lines)
out = ["收到,变更如下 👇", *self._diff_lines(before)]
if bad:
out.append(f"(没找到第 {'、'.join(map(str, bad))} 项,已忽略)")
out += ["————————", f"最终下单 {s['order_count']} 个零件 / {s['order_qty']} 件,订单类型 SO。",
f"请打开单据页核对后点「确认订购」👉 {self.link}"]
await self.say("\n".join(out))
def _diff_lines(self, before: dict[str, int]) -> list[str]:
out = []
for l in self.lines:
b = before.get(l.part_no, 0)
if l.suggested > 0 and b != l.final_qty:
why = "剔除" if l.final_qty == 0 else ("按可订上限" if l.tag == "capped" else "")
out.append(f"· {l.name} {b} → {l.final_qty}" + (f"({why})" if why else ""))
return out or ["· 没有改动"]
# ---------- 单据页回调 ----------
async def confirm_from_page(self, qty_map: dict[str, int], cap_ok: bool) -> tuple[bool, str]:
if self.stage != "awaiting_list":
return False, "这张单据已经处理过了,或当前阶段不能确认"
before = {l.part_no: l.final_qty for l in self.lines}
for l in self.lines:
if l.part_no in qty_map and l.suggested > 0 and l.tag in ("normal", "capped", "removed"):
if int(qty_map[l.part_no]) != l.final_qty:
P.set_qty(l, int(qty_map[l.part_no]))
capped = [l for l in self.lines if l.tag == "capped" and l.orderable]
if capped and not cap_ok:
self._persist()
return False, "有零件超出今日剩余可订上限,请先勾选「确认按上限订」"
if not any(l.orderable for l in self.lines):
self._persist()
return False, "没有可订的零件;如果今天不订,请点「今天不订」"
self._persist()
text = self._confirm_text(self._diff_lines(before))
if not auto_order():
self.stage = "confirmed"
await self.say(text)
return True, "已收到"
self.stage = "building"
await self.say(text + "\n(我去厂家系统建单,建好后发链接请你核对截图)")
self._spawn(self._build())
return True, "已收到"
def _confirm_text(self, changes: list[str]) -> str:
"""确认后的唯一一条回复:订了什么 + 你调整了什么。"""
ok = [l for l in self.lines if l.orderable]
s = P.summary(self.lines)
out = [f"✅ 已收到订购信息({self.doc_no})", "订购:", *[f"· {l.name} × {l.final_qty}" for l in ok],
f"共 {s['order_count']} 项 / {s['order_qty']} 件"]
out += ["调整:", *(changes if changes != ["· 没有改动"] else ["· 无"])]
return "\n".join(out)
async def cancel(self) -> tuple[bool, str]:
if self.stage != "awaiting_list":
return False, "当前阶段不能取消"
self.stage = "cancelled"
await self.say("好的,今天不订了。明天重新盘库后再推新的建议。")
return True, "已取消"
async def submit_from_page(self) -> tuple[bool, str]:
if self.stage != "awaiting_submit":
return False, "当前阶段不能提交"
self.stage = "submitting"
self._spawn(self._submit())
return True, "已收到"
# ---------- 建单 ----------
async def _build(self) -> None:
for l in [x for x in self.lines if x.orderable]:
try:
l.po_no = await self.dms.create_order(l.part_no, l.final_qty, l.name)
self._persist()
await self.say(f"🧾 已建单 {l.po_no} · {l.name} {l.part_no} × {l.final_qty}(待提交)")
except DmsError as e:
l.final_qty, l.tag, l.note = 0, "removed", f"建单失败:{e}"
await self.say(f"⚠️ {l.name} 建单失败,已跳过:{e}")
self._persist()
pos = [l.po_no for l in self.lines if l.po_no]
if not pos:
self.stage = "error"
await self.say("所有零件建单都失败了,请检查后重新触发。")
return
await self.dms.show_po_list()
await self.dms.screenshot(self._shot_path("pending"))
self.stage = "awaiting_submit"
await self.say(f"已按清单在系统里建好 {len(pos)} 张订单,状态都是「待提交」,还没真正下单。\n"
f"请打开链接核对系统截图,没问题点「确认提交」我才点下单 👇\n{self.link}\n"
"⏳ 系统对未提交订单有自动提交时限(超过 30 分钟系统会替人提交),请尽快核对。")
# ---------- 提交 → 留痕 ----------
async def _submit(self) -> None:
pos = [l.po_no for l in self.lines if l.po_no]
await self.say("收到「确认提交」✅ 我现在选中订单并点击「检查并提交」。")
await self.dms.submit_orders(pos)
t = _hms()
for l in self.lines:
if l.po_no:
l.ordered_at = t
await self.dms.screenshot(self._shot_path("submitted"))
done = [l for l in self.lines if l.po_no]
recv = "\n".join(f"✓ {l.po_no} {l.name} {l.part_no} × {l.final_qty} 已提交" for l in done)
qty = sum(l.final_qty for l in done)
self._persist()
self.stage = "done"
skipped = [l for l in self.lines if not l.po_no]
reason = {"removed": "计划员剔除", "oos": "厂家缺货"}
why = ";".join(f"{l.name}({reason.get(l.tag) or P.TAG_LABEL.get(l.tag) or l.note})" for l in skipped)
await self.say(f"已选中订单并点击「检查并提交」✅\n————————\n{recv}\n————————\n"
f"完成 · {len(done)} 单 / {qty} 件 订单类型 SO 预计 明天上午到货\n"
+ (f"未下单:{why}\n" if why else "")
+ f"📄 订货明细表(可下载存档)👉 {self.link}")