main.py
18 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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
"""云端入口:FastAPI。
python -m replenish_cloud.main (在 cloud/ 目录下;或双击项目根目录的 启动云端演示.bat)
页面:/ 管理总览(登录后) /expected 期望值 /stock 库存落库 /runs 补货记录
/settings 设置 /o/<token> 手机单据页(公开,微信里打开) /m/expected 手机期望值页(演示期公开)
接口:/api/admin/*(需登录) /api/order/*(单据页) /api/edge/*(门店取数端,X-Edge-Token 鉴权)
"""
from __future__ import annotations
import asyncio
import csv
import hashlib
import hmac
import io
import json
import secrets
from contextlib import asynccontextmanager
from pathlib import Path
from urllib.parse import quote
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response, StreamingResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from . import __version__, db, events
from .agent import ReplenishAgent
from .edge_hub import EdgeError, hub
from .im import gateway
from .im.poller import Poller
from .settings import EDITABLE, S
from .workflow import public_base, wf
WEB = Path(__file__).parent / "web"
templates = Jinja2Templates(directory=str(WEB / "templates"))
STATE: dict = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
events.setup()
db.init()
hub.startup()
wf.attach_latest()
STATE["agent"] = ReplenishAgent(say=wf.say)
STATE["poller"] = Poller(STATE["agent"].handle, asyncio.get_running_loop())
STATE["poller"].start()
events.emit(f"云端已启动 v{__version__}({S.env_label()}):管理后台 http://127.0.0.1:{S.get('server.port')}/ ,单据链接地址 {public_base()}",
"ok", source="cloud")
if S.get("business.dms_mode") == "mock":
events.emit("当前数据来源:模拟 DMS(business.dms_mode=mock)", "warn", source="cloud")
yield
STATE["poller"].stop()
app = FastAPI(title="库存补货云端", lifespan=lifespan)
app.mount("/static", StaticFiles(directory=WEB / "static"), name="static")
(S.data_dir() / "shots").mkdir(parents=True, exist_ok=True)
app.mount("/shots", StaticFiles(directory=S.data_dir() / "shots"), name="shots")
# ====================================================================== 鉴权
def _admin_sig() -> str:
pwd = S.env("ADMIN_PASSWORD", "admin123")
return hmac.new(pwd.encode(), b"replenish-admin", hashlib.sha256).hexdigest()
def is_admin(request: Request) -> bool:
return hmac.compare_digest(request.cookies.get("rp_admin", ""), _admin_sig())
def need_admin(request: Request) -> None:
if not is_admin(request):
raise HTTPException(401, "请先登录管理后台")
def need_edge(request: Request) -> str:
tok = S.env("EDGE_TOKEN")
if not tok or not hmac.compare_digest(request.headers.get("x-edge-token", ""), tok):
raise HTTPException(401, "取数端令牌不正确(X-Edge-Token)")
eid = request.headers.get("x-edge-id", "edge")[:60]
hub.touch(eid, request.headers.get("x-edge-version", ""))
return eid
def _safe_next(nxt: str | None) -> str:
"""登录后跳回的页面:只允许站内路径。"""
nxt = str(nxt or "/")
return nxt if nxt.startswith("/") and not nxt.startswith("//") else "/"
def _page(request: Request, name: str, **ctx):
if not is_admin(request):
return RedirectResponse("/login?next=" + quote(request.url.path), 303)
return templates.TemplateResponse(request, name, {"mock": S.get("business.dms_mode") == "mock", "page": name,
"env_label": S.env_label(), **ctx})
@app.get("/login")
def login_page(request: Request, next: str = "/"):
return templates.TemplateResponse(request, "login.html", {"next": _safe_next(next)})
@app.post("/login")
async def login(request: Request):
form = dict((await request.form()).items())
nxt = _safe_next(form.get("next"))
if not hmac.compare_digest(str(form.get("password", "")), S.env("ADMIN_PASSWORD", "admin123")):
return templates.TemplateResponse(request, "login.html", {"error": "密码不对", "next": nxt}, status_code=401)
r = RedirectResponse(nxt, 303)
r.set_cookie("rp_admin", _admin_sig(), httponly=True, max_age=7 * 86400, samesite="lax")
return r
@app.get("/logout")
def logout():
r = RedirectResponse("/login", 303)
r.delete_cookie("rp_admin")
return r
# ====================================================================== 管理页面
@app.get("/")
def dashboard(request: Request):
return _page(request, "dashboard.html")
@app.get("/expected")
def expected_page(request: Request):
return _page(request, "expected.html")
@app.get("/stock")
def stock_page(request: Request):
return _page(request, "stock.html")
@app.get("/runs")
def runs_page(request: Request):
return _page(request, "runs.html")
@app.get("/settings")
def settings_page(request: Request):
return _page(request, "settings.html")
# ====================================================================== 管理接口
def _jsonable(rows):
return json.loads(json.dumps(rows, ensure_ascii=False, default=str))
@app.get("/api/admin/overview")
def overview(request: Request):
need_admin(request)
online, eid, age = hub.online()
run = wf.run()
ag = STATE.get("agent")
return _jsonable({
"edge": {"online": online, "id": eid, "age": round(age, 1) if age is not None else None,
"version": hub.versions.get(eid, "")},
"im": {"enabled": S.get("im.enabled"), "bot_id": S.get("im.bot_id"), "contact_id": S.get("im.contact_id"),
"contact_name": S.get("im.contact_name"), "poller": STATE["poller"].status if STATE.get("poller") else {}},
"agent": {"ok": bool(ag and ag.agent), "model": S.get("llm.model"), "error": ag.init_error if ag else ""},
"run": run and {**run, "link": wf.link(run)}, "stage": wf.stage, "dms_mode": S.get("business.dms_mode"),
"public_base": public_base(), "version": __version__, "env": S.env_label(), "instance": db.INSTANCE})
@app.get("/api/admin/events")
def admin_events(request: Request, after: int = 0, run_id: int | None = None):
need_admin(request)
return _jsonable(events.recent(after, run_id))
@app.get("/api/admin/chat")
def admin_chat(request: Request, after: int = 0):
need_admin(request)
t = db.chat_t
st = db.select(t).where(t.c.id > after).order_by(t.c.id.desc()).limit(100)
return _jsonable(db.rows(st)[::-1])
@app.get("/api/admin/tasks")
def admin_tasks(request: Request):
need_admin(request)
t = db.tasks_t
rows = db.rows(db.select(t.c.id, t.c.type, t.c.status, t.c.run_id, t.c.edge_id, t.c.created_at, t.c.dispatched_at,
t.c.finished_at, t.c.error).order_by(t.c.created_at.desc()).limit(30))
return _jsonable(rows)
@app.post("/api/admin/simulate")
async def simulate(request: Request):
"""在网页上模拟计划员发一句话(回复照常发到企业微信)。"""
need_admin(request)
text = str((await request.json()).get("text") or "").strip()
if not text:
raise HTTPException(400, "内容不能为空")
gateway.record_incoming(text, "网页模拟", "")
events.emit(f"网页模拟计划员发送:{text}", source="web")
asyncio.create_task(STATE["agent"].handle(text, "计划员"))
return {"ok": True}
@app.post("/api/admin/test-send")
async def test_send(request: Request):
need_admin(request)
text = str((await request.json()).get("text") or "【测试】库存补货云端:看到这条说明企业微信已接通 ✅")
ok, err = await asyncio.to_thread(gateway.send_text, text)
return JSONResponse({"ok": ok, "error": err}, status_code=200 if ok else 502)
async def _edge_job(typ: str, params: dict, label: str) -> None:
try:
r = await hub.run(typ, params)
events.emit(f"{label}完成:{r.get('message') or r.get('status') or ''} {r.get('rows', '')}".strip(), "ok", source="edge")
except EdgeError as e:
events.emit(f"{label}失败:{e}", "error", source="edge")
@app.post("/api/admin/edge/{action}")
def edge_action(request: Request, action: str):
need_admin(request)
if not hub.online()[0]:
raise HTTPException(409, "门店取数端不在线")
if action == "sync-stock":
asyncio.run_coroutine_threadsafe(_edge_job("sync_stock_full", {}, "全量库存同步"), hub.loop)
elif action == "check":
parts = [{"part_no": e["part_no"], "name": e["name"], "expected": e["expected"]} for e in db.expected_list(True)]
asyncio.run_coroutine_threadsafe(_edge_job("check", {"parts": parts}, "取数端自检"), hub.loop)
else:
raise HTTPException(404, "未知动作")
return {"ok": True}
# ---------------- 期望表 ----------------
@app.get("/api/admin/expected")
def expected_get(request: Request):
need_admin(request)
rows = db.expected_list()
b = db.latest_batch()
if b and rows:
t = db.stock_rows_t
stock = {}
for r in db.rows(db.select(t.c.partNo, t.c.storageQty, t.c.partName).where(
t.c.batch_id == b["id"], t.c.partNo.in_([x["part_no"] for x in rows]))):
stock[r["partNo"]] = stock.get(r["partNo"], 0) + (r["storageQty"] or 0)
for x in rows:
x["snapshot_stock"] = stock.get(x["part_no"])
return _jsonable({"rows": rows, "batch": b})
@app.post("/api/admin/expected")
async def expected_post(request: Request):
need_admin(request)
b = await request.json()
pn = str(b.get("part_no") or "").strip()
if not pn:
raise HTTPException(400, "配件码必填")
try:
exp = int(b.get("expected"))
except (TypeError, ValueError):
raise HTTPException(400, "期望数量必须是整数")
if exp < 0:
raise HTTPException(400, "期望数量不能为负")
db.expected_upsert(pn, str(b.get("name") or "").strip(), exp, bool(b.get("enabled", True)), str(b.get("note") or ""))
events.emit(f"期望值更新:{pn} {b.get('name') or ''} = {exp}{'' if b.get('enabled', True) else '(停用)'}", source="web")
wf.on_expected_changed(pn, exp)
return {"ok": True}
@app.delete("/api/admin/expected/{part_no}")
def expected_del(request: Request, part_no: str):
need_admin(request)
db.expected_delete(part_no)
events.emit(f"期望值删除:{part_no}", source="web")
return {"ok": True}
# ---------------- 库存快照 ----------------
@app.get("/api/admin/stock/batches")
def stock_batches(request: Request):
need_admin(request)
return _jsonable(db.rows(db.select(db.batches_t).order_by(db.batches_t.c.id.desc()).limit(50)))
def _stock_query(batch_id: int, q: str):
t = db.stock_rows_t
st = db.select(t).where(t.c.batch_id == batch_id)
if q:
like = f"%{q}%"
st = st.where(t.c.partNo.like(like) | t.c.partName.like(like) | t.c.locationNo.like(like))
return st
@app.get("/api/admin/stock/rows")
def stock_rows(request: Request, batch_id: int | None = None, q: str = "", page: int = 1, size: int = 50,
positive: bool = False):
need_admin(request)
b = db.one(db.select(db.batches_t).where(db.batches_t.c.id == batch_id)) if batch_id else db.latest_batch()
if not b:
return {"batch": None, "rows": [], "total": 0}
st = _stock_query(b["id"], q.strip())
if positive:
st = st.where(db.stock_rows_t.c.storageQty > 0)
total = db.q(db.select(db.func.count()).select_from(st.subquery())).scalar()
rows = db.rows(st.order_by(db.stock_rows_t.c.id).offset((max(page, 1) - 1) * size).limit(min(size, 500)))
return _jsonable({"batch": b, "rows": rows, "total": total})
@app.get("/api/admin/stock/export.csv")
def stock_export(request: Request, batch_id: int):
need_admin(request)
rows = db.rows(_stock_query(batch_id, "").order_by(db.stock_rows_t.c.id))
buf = io.StringIO()
w = csv.writer(buf)
w.writerow(db.STOCK_FIELDS)
for r in rows:
w.writerow([r.get(f) if r.get(f) is not None else "" for f in db.STOCK_FIELDS])
return Response("" + buf.getvalue(), media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": f'attachment; filename="stock_batch_{batch_id}.csv"'})
# ---------------- 补货记录 ----------------
@app.get("/api/admin/runs")
def runs(request: Request):
need_admin(request)
return _jsonable(db.rows(db.select(db.runs_t).order_by(db.runs_t.c.id.desc()).limit(50)))
# ---------------- 设置 ----------------
@app.get("/api/admin/settings")
def settings_get(request: Request):
need_admin(request)
return _jsonable({"items": [{"key": k, "label": lbl, "value": S.get(k), "source": S.source(k)} for k, lbl in EDITABLE],
"config_file": str(S.config_path)})
@app.post("/api/admin/settings")
async def settings_post(request: Request):
need_admin(request)
b = await request.json()
keys = {k for k, _ in EDITABLE}
for k, v in (b.get("values") or {}).items():
if k not in keys:
raise HTTPException(400, f"不能修改 {k}")
db.save_setting(k, None if v is None else str(v).strip())
events.emit(f"设置修改:{k} = {S.get(k)}", source="web")
return {"ok": True}
# ====================================================================== 手机单据页(公开)
@app.get("/o/{token}")
def order_page(request: Request, token: str):
if not wf.page_state(token):
return HTMLResponse("<h3 style='font-family:sans-serif'>单据不存在或已过期</h3>", status_code=404)
name = "order_full.html" if S.get("web.order_style") == "full" else "order.html"
return templates.TemplateResponse(request, name, {"token": token})
@app.get("/api/order/{token}")
def order_state(token: str):
st = wf.page_state(token)
if not st:
raise HTTPException(404, "单据不存在")
return _jsonable(st)
@app.post("/api/order/{token}/confirm")
async def order_confirm(request: Request, token: str):
st = wf.page_state(token)
if not st:
raise HTTPException(404, "单据不存在")
if not st["is_current"]:
raise HTTPException(409, "这张单据已经不是当前单据(有更新的查询)")
b = await request.json()
qty = {str(k): int(v) for k, v in (b.get("qty") or {}).items()}
ok, msg = await wf.confirm(qty, source="单据页")
return JSONResponse({"ok": ok, "message": msg}, status_code=200 if ok else 409)
@app.post("/api/order/{token}/cancel")
async def order_cancel(token: str):
st = wf.page_state(token)
if not st or not st["is_current"]:
raise HTTPException(409, "这张单据已经不是当前单据")
r = await wf.cancel()
return JSONResponse({"ok": r == "cancelled", "message": r}, status_code=200 if r == "cancelled" else 409)
# ====================================================================== 手机期望值页(演示阶段公开,免登录)
@app.get("/m/expected")
def m_expected_page(request: Request, o: str = ""):
return templates.TemplateResponse(request, "m_expected.html", {"token": o if o.replace("-", "").replace("_", "").isalnum() else ""})
@app.get("/api/m/expected")
def m_expected_get():
return _jsonable([{k: r[k] for k in ("part_no", "name", "expected")} for r in db.expected_list(enabled_only=True)])
@app.post("/api/m/expected")
async def m_expected_post(request: Request):
b = await request.json()
pn = str(b.get("part_no") or "").strip()
row = next((r for r in db.expected_list() if r["part_no"] == pn), None)
if not row:
raise HTTPException(404, "期望表里没有这个配件")
try:
exp = int(b.get("expected"))
except (TypeError, ValueError):
raise HTTPException(400, "期望数量必须是整数")
if exp < 0:
raise HTTPException(400, "期望数量不能为负")
db.expected_upsert(pn, row["name"] or "", exp, bool(row["enabled"]), row["note"] or "")
events.emit(f"期望值更新(手机页):{pn} {row['name'] or ''} {row['expected']} → {exp}", source="web")
return {"ok": True, "recalculated": wf.on_expected_changed(pn, exp)}
# ====================================================================== 取数端接口
@app.get("/api/edge/tasks/next")
async def edge_next(request: Request, wait: int = 25):
eid = need_edge(request)
return {"task": await hub.next_task(eid, wait)}
@app.post("/api/edge/tasks/{tid}/result")
async def edge_result(request: Request, tid: str):
need_edge(request)
b = await request.json()
try:
hub.on_result(tid, bool(b.get("ok")), b.get("result") or {}, str(b.get("error") or ""), b.get("logs") or [])
except EdgeError as e:
raise HTTPException(404, str(e))
return {"ok": True}
@app.post("/api/edge/tasks/{tid}/file")
async def edge_file(request: Request, tid: str, name: str = "shot.png"):
need_edge(request)
data = await request.body()
if len(data) < 100 or data[:8] != b"\x89PNG\r\n\x1a\n":
raise HTTPException(400, "只接收 PNG 截图")
try:
return hub.on_file(tid, name, data)
except EdgeError as e:
raise HTTPException(404, str(e))
@app.post("/api/edge/tasks/{tid}/stock-page")
async def edge_stock_page(request: Request, tid: str):
need_edge(request)
b = await request.json()
try:
await asyncio.to_thread(hub.on_stock_page, tid, int(b["page"]), int(b.get("total") or 0), b.get("rows") or [])
except EdgeError as e:
raise HTTPException(404, str(e))
return {"ok": True}
def main() -> None:
import uvicorn
print("=" * 64)
print(f" 库存补货云端 v{__version__} 环境:{S.env_label()} 端口:{S.get('server.port')}({S.source('server.port')})")
print(f" 管理后台:http://127.0.0.1:{S.get('server.port')}/ (密码见 cloud/.env 的 ADMIN_PASSWORD)")
print(f" 手机单据链接地址:{public_base()}")
print("=" * 64, flush=True)
uvicorn.run(app, host=str(S.get("server.host")), port=int(S.get("server.port")), log_level="warning",
timeout_graceful_shutdown=2)
if __name__ == "__main__":
main()