main.py
15.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
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
# -*- coding: utf-8 -*-
"""门店取数端入口(Python 3.8 标准库;Win7 用自带的 python38\\python.exe 运行)。
python main.py 交互菜单(start.bat 双击即进入)
python main.py check 只读自检:登录 / 库存 / 期望件主数据+全国仓 / 采购单列表 / 列表页截图
python main.py sync-stock 全量库存 → edge_data\\...\\stock_full.csv
python main.py scan 按 expected.csv 扫描期望件(库存、当日可订、全国仓)
python main.py create-po [--lines 019990A115:2,0400007516:2] [--yes]
在真实 DMS 创建采购单(待提交,不提交);不给 --lines 则用最近一次 scan 的建议
python main.py screenshot [--order-no S2026...] 截采购单列表页 + 详情页
python main.py field-test 现场一键测试:自检 → 查补货 → 建单(需 YES)→ 截图,生成汇总页
python main.py serve 连接云端,常驻拉任务
python main.py netdiag 网络诊断:DMS 各域名与云端的 DNS / TCP / TLS / HTTP(不登录)
退出码:0 成功 / 2 失败 / 3 配置错误 / 130 中断
"""
import argparse
import glob
import json
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE) # 嵌入式 Python 不会自动把脚本目录加入 sys.path
from edgeclient import __version__, actions, cloud, logs, netdiag # noqa: E402
from edgeclient.config import ConfigError, load_config, load_expected # noqa: E402
from edgeclient.dms_api import DmsSession # noqa: E402
from edgeclient.dmsfetch.auth import LoginError, LoginRejected # noqa: E402
BANNER = "=" * 60
def _say(text=""):
try:
print(text, flush=True)
except UnicodeEncodeError:
print(text.encode("gbk", "replace").decode("gbk"), flush=True)
def _latest_scan(cfg):
files = sorted(glob.glob(os.path.join(cfg.data_dir, "*", "*_scan", "summary.json")))
for f in reversed(files):
with open(f, encoding="utf-8") as fh:
s = json.load(fh)
if s.get("items"):
return f, s
return None, None
def suggest_lines(items):
"""本地独立模式的建议量(与云端 planner 同口径):缺口 → 两仓无货不订 → 超当日剩余可订按上限。"""
out = []
for it in items:
if it.get("error") or not it.get("shortage"):
continue
if it.get("warehouses") and sum(it["warehouses"].values()) <= 0:
_say(" 跳过 %s %s:关注仓都无货" % (it["part_no"], it.get("name")))
continue
qty = int(round(it["shortage"]))
cap = it.get("daily_surplus")
if cap is not None and qty > cap:
_say(" %s %s:缺 %d,当日剩余可订仅 %d,按上限订" % (it["part_no"], it.get("name"), qty, cap))
qty = cap
if qty > 0:
out.append({"part_no": it["part_no"], "name": it.get("name"), "qty": qty})
return out
def _parse_lines(text):
""""019990A115:2,0400007516:2" → [{part_no, qty}];格式不对抛 ValueError。"""
out = []
for part in (text or "").replace(",", ",").replace(":", ":").split(","):
if not part.strip():
continue
pn, sep, q = part.partition(":")
if not sep or not pn.strip():
raise ValueError("格式应为 配件码:数量,例如 019990A115:2(出错的部分:%s)" % part.strip())
qty = int(q.strip())
if qty <= 0:
raise ValueError("%s 的数量必须大于 0" % pn.strip())
out.append({"part_no": pn.strip(), "qty": qty})
if not out:
raise ValueError("没有输入任何配件")
return out
def _default_lines(cfg):
"""建单默认数量:最近一次扫描的建议;没有扫描或建议为空时,用期望表里的期望数量(现场测试:卡子、用户手册各 2)。"""
f, s = _latest_scan(cfg)
if s:
lines = suggest_lines(s["items"])
if lines:
_say("默认数量来自最近一次扫描的补货建议(%s)" % os.path.dirname(f))
return lines
_say("最近一次扫描没有需要补货的配件(库存可能已够);默认改用期望表里的期望数量。")
else:
_say("还没有扫描结果;默认使用期望表里的期望数量。")
return [{"part_no": e["part_no"], "name": e["name"], "qty": e["expected"]}
for e in load_expected(cfg.expected_file) if e["expected"] > 0]
def do_create(cfg, sess, lines_text=None, yes=False, interactive=True):
"""建采购单(待提交)+ 自动截图。返回 (退出码, {create, screenshot})。"""
if lines_text:
lines = _parse_lines(lines_text)
else:
lines = _default_lines(cfg)
if interactive:
_say("默认建单数量:" + ",".join("%s %s × %d" % (l["part_no"], l.get("name") or "", l["qty"]) for l in lines))
while True:
txt = input("直接回车 = 按上面的数量;或输入自定义(例如 019990A115:2,0400007516:2):").strip()
if not txt:
break
try:
names = {l["part_no"]: l.get("name") for l in lines}
lines = _parse_lines(txt)
for l in lines:
l["name"] = names.get(l["part_no"], "")
break
except ValueError as e:
_say("[输入有误] %s,请重新输入" % e)
if not lines:
_say("没有要订的配件,不建单。")
return 0, {}
_say(BANNER)
_say("即将在【真实 DMS】创建 1 张采购单(状态:待提交,不会提交):")
_say(" 供应商 %s 订单类型 %s 备注 %s" % (cfg.supplier_code, cfg.order_type, cfg.po_remark))
for l in lines:
_say(" %s %s × %d" % (l["part_no"], l.get("name") or "", l["qty"]))
_say(BANNER)
if not yes:
ans = input("确认请输入 YES(大写),其它任意键取消:").strip()
if ans != "YES":
_say("已取消,未建单。")
return 0, {"cancelled": True}
r = actions.create_po(cfg, sess, lines)
_say("[完成] 已创建采购单 %s(待提交)" % r["order_no"])
if r.get("mismatch"):
_say("[注意] 明细与请求不一致:%s" % ";".join(r["mismatch"]))
_say("建单结果目录:%s" % r["dir"])
_say("接下来自动截图……")
try:
sh = actions.screenshot_po(cfg, sess, row=r["row"], part_nos=[l["part_no"] for l in lines])
_say("[完成] 截图完成:%s" % ",".join(sh["files"]))
except Exception as e: # noqa: BLE001 截图失败不影响已建好的单,只报错
_say("[失败] 采购单已建好,但截图失败:%s" % e)
sh = {"ok": False, "error": str(e)}
_say("[注意] 这是真实单据(待提交)。程序到此停止,不会提交;演示完请人工到 DMS 处理/删除。")
return 0, {"create": r, "screenshot": sh}
def field_test(cfg, sess):
"""现场一键测试:自检 → 查期望件补货 → 建单(需 YES)→ 截图。每步结果写进一个汇总页。"""
from edgeclient.localstore import RunDir
rd = RunDir(cfg.data_dir, "field_test")
steps = []
def record(name, ok, detail, link=None):
steps.append({"step": name, "ok": "通过" if ok else "失败", "detail": detail,
"link": os.path.relpath(os.path.join(link, "index.html"), rd.path) if link else ""})
_say("[%s] %s:%s" % ("通过" if ok else "失败", name, detail))
_say(BANNER)
_say(" 现场一键测试:自检 → 查期望件补货 → 建单(需输入 YES)→ 截图")
_say(BANNER)
try:
r = actions.check(cfg, sess, load_expected(cfg.expected_file))
bad = [x["step"] for x in r["steps"] if not x["ok"]]
record("1 自检", r["ok"], "全部通过" if r["ok"] else "失败项:" + "、".join(bad), r["dir"])
if not r["ok"] and input("自检有失败项,仍要继续吗?输入 Y 继续,其它键停止:").strip().upper() != "Y":
return _finish_field(rd, steps)
except Exception as e: # noqa: BLE001
record("1 自检", False, "%s: %s" % (type(e).__name__, e))
return _finish_field(rd, steps)
try:
r = actions.scan(cfg, sess, load_expected(cfg.expected_file))
detail = ";".join("%s %s 库存%g 在途%g 期望%s 缺%g 仓%s%s" % (
it["part_no"], it.get("name"), it.get("stock") or 0, it.get("in_transit") or 0, it["expected"],
it.get("shortage") or 0, it.get("warehouses") or "-", (" 错误:" + it["error"]) if it.get("error") else "")
for it in r["items"])
record("2 查期望件补货信息", r["ok"], detail, r["dir"])
except Exception as e: # noqa: BLE001
record("2 查期望件补货信息", False, "%s: %s" % (type(e).__name__, e))
try:
code, res = do_create(cfg, sess)
if not res or res.get("cancelled"):
record("3 建采购单", False, "没有建单(取消或无配件)")
else:
c = res["create"]
record("3 建采购单(待提交)", True, "单号 %s,id %s%s" % (
c["order_no"], c["order_id"],
";明细不一致:" + ";".join(c["mismatch"]) if c.get("mismatch") else ",明细核对一致"), c["dir"])
sh = res["screenshot"]
if sh.get("ok"):
record("4 截图", True, "2 张:采购订单列表 + 详情", sh["dir"])
else:
record("4 截图", False, sh.get("error") or "失败")
except Exception as e: # noqa: BLE001
record("3 建采购单", False, "%s: %s" % (type(e).__name__, e))
return _finish_field(rd, steps)
def _finish_field(rd, steps):
import html as _h
ok = bool(steps) and all(x["ok"] == "通过" for x in steps)
rows = "".join("<tr><td>%s</td><td class=%s>%s</td><td>%s</td><td>%s</td></tr>" % (
_h.escape(x["step"]), "ok" if x["ok"] == "通过" else "err", x["ok"], _h.escape(x["detail"]),
'<a href="%s">查看</a>' % x["link"].replace(os.sep, "/") if x["link"] else "") for x in steps)
rd.sections.append(("测试步骤", "<table><tr><th>步骤</th><th>结果</th><th>说明</th><th>详情</th></tr>%s</table>" % rows))
page = rd.finish(ok, {"message": "全部通过" if ok else "有失败步骤", "steps": steps})
_say(BANNER)
_say("现场测试%s。汇总页:%s" % ("全部通过" if ok else "有失败步骤", page))
_say("请把整个 edge_data 和 logs 目录拷回来核对。")
return 0 if ok else 2
def run(cmd, cfg, log, args):
sess = DmsSession(cfg)
if cmd == "check":
r = actions.check(cfg, sess, load_expected(cfg.expected_file))
_say("自检%s,详见:%s" % ("全部通过" if r["ok"] else "有失败项", os.path.join(r["dir"], "index.html")))
return 0 if r["ok"] else 2
if cmd == "sync-stock":
r = actions.sync_stock_full(cfg, sess)
_say("全量库存 %d 行(%s),CSV:%s" % (r["rows"], r["status"], r["csv"]))
return 0
if cmd == "scan":
r = actions.scan(cfg, sess, load_expected(cfg.expected_file))
for it in r["items"]:
_say(" %s %s:库存 %g 在途 %g 期望 %s → 缺 %g 当日剩余可订 %s 关注仓 %s %s" % (
it["part_no"], it.get("name"), it.get("stock") or 0, it.get("in_transit") or 0, it["expected"],
it.get("shortage") or 0, it.get("daily_surplus"), it.get("warehouses") or "-", it.get("error") or ""))
_say("详见:%s" % os.path.join(r["dir"], "index.html"))
return 0 if r["ok"] else 2
if cmd == "create-po":
lines = getattr(args, "lines", None)
return do_create(cfg, sess, lines, getattr(args, "yes", False), interactive=not lines)[0]
if cmd == "field-test":
return field_test(cfg, sess)
if cmd == "screenshot":
r = actions.screenshot_po(cfg, sess, getattr(args, "order_no", None))
_say("截图完成:%s" % ",".join(r["files"]))
return 0
if cmd == "serve":
return cloud.serve(cfg)
if cmd == "netdiag":
rows = netdiag.run(cfg, sess.client)
_say("网络诊断%s(详细见上面各行;日志 logs\\edge.log)" % ("全部正常" if all(r["ok"] for r in rows) else "有异常项"))
return 0 if all(r["ok"] for r in rows) else 2
raise ConfigError("未知命令 %s" % cmd)
MENU = [("1", "自检(只读:登录 / 库存 / 全国仓 / 采购单列表截图)", "check"),
("2", "同步全量库存(约 2 分钟)", "sync-stock"),
("3", "查期望件补货信息(按 expected.csv)", "scan"),
("4", "建采购单(待提交,可改数量,需输入 YES 确认)+ 自动截图", "create-po"),
("5", "截图最新采购单", "screenshot"),
("6", "打开本地结果目录", "open"),
("7", "连接云端(常驻)", "serve"),
("8", "现场一键测试(自检 → 查补货 → 建单(需 YES) → 截图)", "field-test"),
("9", "网络诊断(DMS 各域名 + 云端:DNS / TCP / TLS / HTTP,不登录)", "netdiag"),
("0", "退出", "exit")]
def menu(cfg, log):
while True:
_say("")
_say(BANNER)
_say(" 门店取数端 v%s DMS:%s" % (__version__, cfg.dms_url))
_say(" 云端:%s %s" % (cfg.cloud_env_label, cfg.cloud_url or "(未配置)"))
_say(" 结果目录:%s" % cfg.data_dir)
_say(BANNER)
for k, label, _ in MENU:
_say(" %s. %s" % (k, label))
try:
choice = input("请输入编号后回车:").strip()
except EOFError:
return 0
cmd = next((c for k, _, c in MENU if k == choice), None)
if cmd is None:
continue
if cmd == "exit":
return 0
if cmd == "open":
os.makedirs(cfg.data_dir, exist_ok=True)
idx = os.path.join(cfg.data_dir, "index.html")
os.startfile(idx if os.path.exists(idx) else cfg.data_dir) # noqa: S606(Windows)
continue
safe_run(cmd, cfg, log, argparse.Namespace())
def safe_run(cmd, cfg, log, args):
try:
return run(cmd, cfg, log, args)
except LoginRejected as e:
log.error("登录被拒绝:%s(不会自动重试,避免锁号。请先在浏览器确认账号状态)", e)
except LoginError as e:
log.error("登录失败:%s", e)
log.error("排查:菜单 9 网络诊断;菜单 1 自检的结果页里有每个登录请求的轨迹(logs\\edge.log 里也有 HTTP 记录)")
except ConfigError as e:
log.error("配置错误:%s", e)
return 3
except KeyboardInterrupt:
log.warning("已中断")
return 130
except Exception as e: # noqa: BLE001
log.error("执行失败:%s: %s", type(e).__name__, e)
return 2
def main(argv=None):
for s in (sys.stdout, sys.stderr):
try:
s.reconfigure(errors="replace")
except Exception:
pass
ap = argparse.ArgumentParser(description="门店取数端")
ap.add_argument("--config", default=os.path.join(HERE, "config.ini"))
sub = ap.add_subparsers(dest="cmd")
for c in ("menu", "check", "sync-stock", "scan", "serve", "field-test", "netdiag"):
sub.add_parser(c)
pc = sub.add_parser("create-po")
pc.add_argument("--lines", help="配件码:数量,配件码:数量(不给则用最近一次 scan 的建议)")
pc.add_argument("--yes", action="store_true", help="跳过 YES 确认(慎用)")
ps = sub.add_parser("screenshot")
ps.add_argument("--order-no")
args = ap.parse_args(argv)
try:
cfg = load_config(args.config)
except ConfigError as e:
_say("配置错误:%s" % e)
return 3
log = logs.setup(cfg.log_dir, cfg.log_level)
cmd = args.cmd or "menu"
if cmd == "menu":
return menu(cfg, log)
return safe_run(cmd, cfg, log, args)
if __name__ == "__main__":
sys.exit(main())