test_restock_flow.py
73.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
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
"""库存补货全流程(取数端打桩,按任务类型返回结果):
定时补货(出库驱动):15:00 定时 / 后台按钮触发、出库 → 分组(在库分类表 ∪ 近 N 月 SO 单)→ 默认期望(推荐 / 上次)、
页面确认(有效期由服务端校验)、刷新整条链路重跑并保留人工修改、群里不能发起 / 确认、建单 + 截图(含兜底)→
单据页「确认提交」/「先不提交」、失败重试、提醒、紧急告警、截单收口、预检、审计(快照 / 出库明细 / 时间线);
单次补货:群里「零件号 数量」→ 查询 → 回「订」→ 建单截图 → 发起人回「确认」提交,不影响当天定时补货;
分类表维护、每周 SO 同步、调度器。"""
from __future__ import annotations
import datetime as dt
from urllib.parse import urlsplit
import pytest
from sqlalchemy import select
from app import features
from app.core import clock, db
from app.core.types import Actor, EdgeError, EdgeTimeout
from app.features.restock import service as restock_service
from app.models import (alerts_t, api_calls_t, outbound_rows_t, po_t, runs_t, schedule_marks_t, snapshots_t,
so_orders_t, so_parts_t, so_syncs_t)
from app.services import audit, edge, stores
from app.services.agent import assistant
from app.services.scheduler import scheduler
from tests.conftest import StoreKit, fake_now
PNG = b"\x89PNG\r\n\x1a\n" + b"0" * 64
# 出库明细(取数端已按零件汇总的纯牌净出库):机油、机滤在分类表里属常备分类;用户手册不在分类表、但近 3 个月 SO 里补过;
# 传感器固定件是钣喷件、银粉定色剂未分类 → 其他组;空调滤净出库 -1(退货冲销)→ 不进候选
PARTS = [
{"part_no": "0888080463", "name": "0W20机油4L装", "qty": 5, "rows": 5},
{"part_no": "90915YZZM3", "name": "机油滤清器滤芯", "qty": 18, "rows": 22},
{"part_no": "019990A115", "name": "用户手册", "qty": 2, "rows": 2},
{"part_no": "8934806270", "name": "后车角超声波传感器固", "qty": 3, "rows": 1},
{"part_no": "GPDL0WM001", "name": "银粉定色剂", "qty": 28, "rows": 2},
{"part_no": "8713906140", "name": "空调滤清器滤芯分总成", "qty": -1, "rows": 1},
]
FACTS = {
"0888080463": {"stock": 8, "trans_shipped": 0, "daily_surplus": 30, "unit_price": 338, "mad": 20.3},
"90915YZZM3": {"stock": 12, "trans_shipped": 0, "daily_surplus": 25, "unit_price": 39, "mad": 18.7},
"019990A115": {"stock": 0, "trans_shipped": 0, "daily_surplus": 4, "unit_price": 18.8, "mad": 4.0},
"8934806270": {"stock": 2, "trans_shipped": 0, "daily_surplus": 5, "unit_price": 31, "mad": 11.0},
"GPDL0WM001": {"stock": 485, "trans_shipped": 0, "daily_surplus": None, "unit_price": 460, "mad": 139.7},
"8713902280": {"stock": 6, "trans_shipped": 2, "daily_surplus": 30, "unit_price": 53.3, "mad": 15.3},
}
ROWS = [{"id": f"r{i}", "shipmentDate": "2026-10-22 09:0%d:00" % i, "workOrderNo": "P44BH0008454",
"shipmentBatchNo": f"44BH0{i}", "licensePlateNumber": "粤B-X739A", "mfr": "纯牌", "partNo": p["part_no"],
"partName": p["name"], "settlStatus": "1", "reqQty": "%.6f" % p["qty"], "partUnitPrice": 10.0,
"totalAmount": 10.0, "costPrice": 5.0, "totalCostPrice": 5.0} for i, p in enumerate(PARTS)]
ROWS.append(dict(ROWS[0], id="r9", mfr="非纯", partNo="ZCT001", partName="非纯养护品"))
class FakeEdge:
def __init__(self) -> None:
self.calls: list[str] = []
self.by_store: list[tuple[int, str]] = []
self.params: list[dict] = []
self.timeouts: dict[str, float] = {}
self.fail_scan = 0
self.check_ok = True
self.po_error: Exception | None = None
self.shot_fallback = ""
self.facts = {k: dict(v) for k, v in FACTS.items()}
self.parts = PARTS
self.so_details: dict | None = None
self.submit_error: Exception | None = None
self.submitted: list[str] = []
self.found: list[dict] = [] # restock.find_po 返回的命中单
self.find_error: Exception | None = None
self.po_state = "pending" # restock.po_status:pending / submitted / other / missing / error
async def __call__(self, store_id, type, params, *, timeout, feature="", ref="", step_timeouts=None,
idempotency_key=None, dms_code=""):
self.calls.append(type)
self.by_store.append((store_id, type))
self.params.append(dict(params, _dms=dms_code, _ref=ref))
self.timeouts[type] = timeout
if type == "restock.outbound":
assert step_timeouts and step_timeouts["login"] == 90 and step_timeouts["query_outbound"] == 300
if self.fail_scan:
self.fail_scan -= 1
raise EdgeError("DMS 登录失败(模拟)")
return {"ok": True, "message": "出库明细 7 行", "rows": ROWS, "parts": self.parts,
"stats": {"window_rows": 7, "pure_rows": 6, "mfr_counts": {"纯牌": 6, "非纯": 1}, "unknown_mfr": []},
"reconcile": {"ok": True}, "_task_id": "o" * 32}
if type == "restock.quote":
items = []
for p in params["parts"]:
f = self.facts.get(p["part_no"], {})
items.append(dict(f, part_no=p["part_no"], name=p.get("name") or "示例", unreceived=0,
national_queried=p["national"],
warehouses={"GTMC广州": 0, "华南GTMC": 1095} if p["national"] else {}))
return {"ok": True, "items": items, "_task_id": "q" * 32}
if type == "restock.so_sync" and self.so_details is not None:
heads = [{"orderNo": no, "createTime": "2026-10-%02d 09:00:00" % (i + 1), "orderStatus": "3",
"fp": "fp-" + no} for i, no in enumerate(sorted(self.so_details))]
fetched = {no: v for no, v in self.so_details.items() if params["known"].get(no) != "fp-" + no}
return {"ok": True, "message": "SO 同步完成", "orders": heads, "details": fetched, "parts": [],
"stats": {"orders": len(heads), "trusted": True, "fetched": len(fetched),
"reused": len(heads) - len(fetched)}, "_task_id": "s" * 32}
if type == "restock.so_sync":
return {"ok": True, "message": "SO 同步完成", "parts": [
{"part_no": "019990A115", "name": "用户手册", "order_count": 3, "qty_sum": 9, "order_nos": ["S1", "S2", "S3"],
"last_order_no": "S3", "last_order_date": "2026-10-20 09:00:00"}],
"stats": {"orders": 3, "lines": 3, "trusted": False, "pages": 18}, "_task_id": "s" * 32}
if type == "restock.create_po":
if self.po_error:
raise self.po_error
return {"order_id": "9001", "order_no": "S2026102201", "_task_id": "t" * 32,
"row": {"supplierCode": "APC40", "orderType": "S", "itemNum": len(params["lines"]), "totalAmount": 80.0},
"details": [{"partNo": l["part_no"], "purchaseQty": l["qty"]} for l in params["lines"]], "mismatch": []}
if type == "restock.screenshot_po":
names = ("po_list_fallback.png", "po_detail_fallback.png") if self.shot_fallback else ("po_list.png", "po_detail.png")
ids = [edge.save_evidence(store_id, None, n, PNG, "screenshot", "image/png")["id"] for n in names]
out = {"evidence": ids, "fallback": self.shot_fallback or False}
if self.shot_fallback:
out.update(fallback_reason="浏览器登录超时", details=[{"partNo": "90915YZZM3", "purchaseQty": 18}])
return out
if type == "restock.submit_po":
if self.submit_error:
raise self.submit_error
self.submitted.append(params["order_id"])
return {"ok": True, "order_id": params["order_id"], "order_no": params["order_no"], "status": "已提交",
"already": False, "apply_operator": "邹新", "apply_time": "2026-10-22 15:23:01",
"total_amount": 106.6, "_task_id": "u" * 32, "evidence": [],
"details": [{"partNo": l["part_no"], "partName": "空调滤清器滤芯分总成" if l["part_no"] == "8713902280"
else "零件" + l["part_no"][-3:], "purchaseQty": float(l["qty"]), "totalPrice": "53.3"}
for l in params["expect"]["lines"]]}
if type == "restock.find_po":
if self.find_error:
raise self.find_error
return {"ok": True, "found": self.found, "scanned": 7, "evidence": [], "_task_id": "f" * 32}
if type == "restock.po_status":
if self.po_state == "error":
raise EdgeError("DMS 采购单列表查询失败(模拟)")
status, cn = {"pending": ("1", "待提交"), "submitted": ("2", "已提交"), "other": ("4", "状态码 4"),
"missing": ("", "已删除")}[self.po_state]
return {"ok": True, "exists": self.po_state != "missing", "status": status, "status_cn": cn,
"row": {"id": params["order_id"], "orderNo": params["order_no"], "orderStatus": status}
if self.po_state != "missing" else None, "message": cn, "evidence": [], "_task_id": "p" * 32}
if type == "sys.check":
return {"ok": self.check_ok, "steps": [{"step": "登录 DMS", "ok": self.check_ok, "detail": "x"}]}
raise AssertionError(type)
@pytest.fixture()
def fake_edge(monkeypatch):
f = FakeEdge()
monkeypatch.setattr(edge, "run", f)
return f
def setup_store(client, admin, so=True, **cfg) -> StoreKit:
k = StoreKit(client, admin)
if so: # 近 3 个月 SO 单里补过用户手册
db.q(so_parts_t.insert().values(store_id=k.store_id, part_no="019990A115", name="用户手册", order_count=3,
qty_sum=9, order_nos=["S1"], last_order_no="S1", last_order_date="2026-10-01"))
if cfg:
assert client.put("/api/restock/config", json={"values": cfg}, headers=admin).status_code == 200
return k
def say(k: StoreKit, text: str, sender="zhangsan") -> dict:
return k.call(assistant.handle, k.target(), sender, "张三", text)
def settle(k: StoreKit) -> None:
k.call(k.svc().drain)
def group_msgs(k, outbox):
return outbox.to(k.group)
def open_alerts(k, kind=None):
st = select(alerts_t).where(alerts_t.c.store_id == k.store_id, alerts_t.c.status == "open")
if kind:
st = st.where(alerts_t.c.kind == kind)
return db.rows(st)
def push(k, hh=15, mm=0):
t = fake_now(hh=hh, mm=mm)
k.heartbeat()
k.call(k.svc().push, k.store_id, t, "15:00")
settle(k)
return k.svc().current(k.store_id)
def page(client, token) -> dict:
r = client.get(f"/api/public/restock/orders/{token}")
assert r.status_code == 200, r.text
return r.json()
def state_of(st: dict, **changes) -> list[dict]:
"""页面提交的整体状态:默认按页面当前值;changes = {part_no: {checked, expected}}(改了期望即 modified)。"""
out = []
for l in st["lines"]:
c = changes.get(l["part_no"], {})
out.append({"part_no": l["part_no"], "checked": c.get("checked", l["checked"]),
"expected": c.get("expected", l["expected"]), "modified": "expected" in c or l["modified"]})
return out
def confirm(client, token, lines):
return client.post(f"/api/public/restock/orders/{token}/confirm", json={"lines": lines})
def submit(client, token):
return client.post(f"/api/public/restock/orders/{token}/submit")
# ====================================================================== 定时补货全流程
def test_scheduled_flow_end_to_end(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
run = push(k)
assert run["kind"] == "scheduled" and run["trigger"] == "schedule" and run["status"] == "awaiting_confirm"
assert (run["window_start"], run["window_end"]) == (dt.datetime(2026, 10, 21, 15), dt.datetime(2026, 10, 22, 15))
ob = fake_edge.params[0]
assert ob["window_start"] == "2026-10-21 15:00:00" and ob["window_end"] == "2026-10-22 15:00:00"
assert ob["pure_label"] == "纯牌" and ob["_dms"] == "gtmc" and ob["_ref"] == f"restock:run:{run['id']}"
# 分组:分类表常备分类 ∪ SO 单 → 常备件(查全国仓);其余不查全国仓;净出库 <= 0 的不进候选
q = {p["part_no"]: p["national"] for p in fake_edge.params[1]["parts"]}
assert q == {"0888080463": True, "90915YZZM3": True, "019990A115": True, "8934806270": False, "GPDL0WM001": False}
msgs = group_msgs(k, outbox)
assert msgs[0].startswith("⏰ 到点了,正在拉今天的出库明细")
assert "请点开链接确认,不确认不会生成采购单" in msgs[1] and "/m/restock/order/" in msgs[1]
assert "共 5 种纯牌零件,其中常备件 3 种" in msgs[1] and "· " not in msgs[1] # 群里不列清单
assert outbox.texts[-1]["at"] == ["zhangsan"]
st = page(client, run["token"])
lines = {l["part_no"]: l for l in st["lines"]}
oil, filt, manual = lines["0888080463"], lines["90915YZZM3"], lines["019990A115"]
assert (oil["grp"], oil["category"], oil["checked"], oil["default_source"]) == ("stock", "机油", True, "recommend")
assert (oil["expected"], oil["final_qty"]) == (13, 5) # 推荐 = 库存 8 + 出库 5
assert (filt["expected"], filt["final_qty"]) == (30, 18)
assert manual["grp"] == "stock" and manual["so_hit"]["order_count"] == 3 and manual["final_qty"] == 2
assert (lines["8934806270"]["grp"], lines["8934806270"]["checked"], lines["8934806270"]["tag"]) == ("other", False, "unchecked")
assert lines["GPDL0WM001"]["category"] == "未分类"
assert st["can_confirm"] and 55 <= st["seconds_left"] <= 60 and st["valid_seconds"] == 60
assert st["summary"]["order_count"] == 3 and st["window"] == "10/21 15:00 — 10/22 15:00"
# 审计:出库明细原样存(含非纯)、推送的清单快照
assert len(db.rows(select(outbound_rows_t).where(outbound_rows_t.c.run_id == run["id"]))) == 7
snaps = db.rows(select(snapshots_t).where(snapshots_t.c.run_id == run["id"]))
assert [s["kind"] for s in snaps] == ["pushed"]
# 群里回「确认」不会建单(定时补货必须走页面)
d = say(k, "确认")
assert d["calls"][0]["tool"] == "confirm_order" and "请点开链接确认" in group_msgs(k, outbox)[-1]
assert "restock.create_po" not in fake_edge.calls
# 页面确认:改了机滤的期望、勾选了传感器固定件
clock.advance(seconds=20)
r = confirm(client, run["token"], state_of(st, **{"90915YZZM3": {"expected": 20},
"8934806270": {"checked": True}}))
assert r.status_code == 200, r.text
settle(k)
run = k.svc().run(run["id"])
assert run["status"] == "awaiting_submit" and run["order_no"] == "S2026102201" and run["confirmed_via"] == "order_page"
lines_po = {l["part_no"]: l["qty"] for l in fake_edge.params[2]["lines"]}
assert lines_po == {"0888080463": 5, "90915YZZM3": 8, "019990A115": 2, "8934806270": 3}
assert fake_edge.params[2]["order_type"] == "S" and fake_edge.params[2]["kind"] == "scheduled"
assert "(定时)" in fake_edge.params[2]["remark"]
done_msg = group_msgs(k, outbox)[-1]
assert len(outbox.images) == 2 and "单建好了:S2026102201(待提交)" in done_msg and "点「确认提交」" in done_msg
# 群里回「确认」不会提交定时补货(只回链接)
say(k, "没问题,提交吧")
assert "群里回复不会提交" in group_msgs(k, outbox)[-1] and "restock.submit_po" not in fake_edge.calls
st = page(client, run["token"])
assert st["can_submit"] and st["can_hold"] and "submit_seconds_left" not in st # 确认提交不过期
r = submit(client, run["token"])
assert r.status_code == 200, r.text
settle(k)
run = k.svc().run(run["id"])
assert run["status"] == "done" and run["submitted_via"] == "order_page" and fake_edge.submitted == ["9001"]
sp = next(p for p in fake_edge.params if "expect" in p)
assert sp["order_id"] == "9001" and sp["order_no"] == "S2026102201" and sp["kind"] == "scheduled"
assert {l["part_no"]: l["qty"] for l in sp["expect"]["lines"]} == lines_po and sp["expect"]["supplier_code"] == "APC40"
po = db.one(select(po_t).where(po_t.c.run_id == run["id"]))
assert po["status"] == "已提交" and po["apply_operator"] == "邹新" and po["submit_task_id"] == "u" * 32
receipt = group_msgs(k, outbox)[-1]
assert receipt.startswith("已提交 ✅") and "PO 单号 S2026102201" in receipt and "提交人 邹新" in receipt
assert "共 4 项 / 18 件" in receipt and "状态:已提交" in receipt
assert any("在单据页确认提交,正在 DMS 提交 S2026102201" in m for m in group_msgs(k, outbox))
assert submit(client, run["token"]).status_code == 409 # 已提交的不能再提交
conf = db.rows(select(snapshots_t).where(snapshots_t.c.run_id == run["id"], snapshots_t.c.kind == "confirmed"))
changes = {c["part_no"]: c for c in db.jload(conf[0]["data"], {})["changes"]}
assert changes["90915YZZM3"]["after"]["expected"] == 20 and changes["8934806270"]["after"]["checked"] is True
acts = [r["action"] for r in audit.query(store_ids=[k.store_id], limit=500)[1]]
for a in ("restock.run.start", "restock.run.confirm", "restock.po.created", "restock.run.chat_confirm_blocked",
"assistant.decision", "restock.run.submit_route", "restock.run.submit_confirm", "restock.po.submitted"):
assert a in acts, a
# 建过单后还能手动补充:重新按全天出库算,群消息提醒今天已经建过的采购单
assert k.call(k.svc().start, k.store_id, "console", Actor("user", "1", "店长")) == "started"
settle(k)
assert "今天已建采购单 S2026102201" in group_msgs(k, outbox)[-1]
extra = k.svc().current(k.store_id)
assert page(client, extra["token"])["today_orders"][0]["order_no"] == "S2026102201"
# 审计时间线:聊天、操作、流程、快照都在
tl = client.get(f"/api/restock/runs/{run['id']}/timeline?size=200", headers=k.h).json()["items"]
kinds = {x["kind"] for x in tl}
assert {"chat", "audit", "event", "snapshot"} <= kinds
assert any(x["kind"] == "chat" and "请点开链接确认" in x["text"] for x in tl) # 群里的引导回复也串进来了
assert any(x["kind"] == "audit" and "群里回确认" in x["title"] for x in tl)
assert client.get(f"/api/restock/runs/{run['id']}/timeline.csv", headers=k.h).status_code == 200
sid_ = next(x for x in tl if x["kind"] == "snapshot")["detail"]["snapshot_id"]
assert client.get(f"/api/restock/runs/{run['id']}/snapshots/{sid_}", headers=k.h).json()["kind"] == "pushed"
ob = client.get(f"/api/restock/runs/{run['id']}/outbound", headers=k.h).json()
assert len(ob["rows"]) == 7 and ob["fetch_seq"] == 1
# 第二天:机滤带「上次」人工修改的值 20
fake_now(d=23, hh=15)
k.heartbeat()
k.call(k.svc().push, k.store_id, clock.now(), "15:00")
settle(k)
st2 = page(client, k.svc().current(k.store_id)["token"])
filt2 = next(l for l in st2["lines"] if l["part_no"] == "90915YZZM3")
assert (filt2["default_source"], filt2["expected"], filt2["last_expected"]) == ("last", 20, 20)
oil2 = next(l for l in st2["lines"] if l["part_no"] == "0888080463")
assert oil2["default_source"] == "recommend" # 没改过的不会变成「上次」
def test_confirm_expires_and_refresh_reruns_chain(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
run = push(k)
st = page(client, run["token"])
mine = state_of(st, **{"0888080463": {"expected": 20}})
clock.advance(seconds=70) # 超过 60 秒有效期
st = page(client, run["token"])
assert st["seconds_left"] == 0 and not st["can_confirm"] and st["can_refresh"]
r = confirm(client, run["token"], mine)
assert r.status_code == 409 and "有效期" in r.json()["detail"]
fake_edge.facts["0888080463"]["trans_shipped"] = 4 # 有人下午手工补过一单:在途变了
r = client.post(f"/api/public/restock/orders/{run['token']}/refresh", json={"lines": mine})
assert r.status_code == 200, r.text
settle(k)
assert fake_edge.calls.count("restock.outbound") == 2 and fake_edge.calls.count("restock.quote") == 2
run = k.svc().run(run["id"])
assert (run["fetch_seq"], run["refresh_count"], run["status"]) == (2, 1, "awaiting_confirm")
st = page(client, run["token"])
oil = next(l for l in st["lines"] if l["part_no"] == "0888080463")
assert (oil["expected"], oil["modified"], oil["in_transit"], oil["final_qty"]) == (20, True, 4, 8) # 人改的保留
assert st["seconds_left"] >= 55
kinds = [s["kind"] for s in db.rows(select(snapshots_t).where(snapshots_t.c.run_id == run["id"]))]
assert kinds == ["pushed", "refreshed"]
assert len(db.rows(select(outbound_rows_t).where(outbound_rows_t.c.run_id == run["id"]))) == 14 # 两轮都留
assert confirm(client, run["token"], state_of(st)).status_code == 200
settle(k)
acts = [r["action"] for r in audit.query(store_ids=[k.store_id], actor_type="public", limit=50)[1]]
assert {"restock.run.confirm_rejected", "restock.run.refresh", "restock.run.confirm"} <= set(acts)
def test_chat_cannot_start_scheduled(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
fake_now(hh=15)
k.heartbeat()
d = say(k, "现在3点了,帮我查一下库存补货信息")
assert d["calls"][0]["tool"] == "scheduled_restock"
assert "不能在群里发起" in group_msgs(k, outbox)[-1] and fake_edge.calls == []
with pytest.raises(ValueError):
k.call(k.svc().start, k.store_id, "chat", Actor("planner_im", "x", "张三"))
def test_manual_run_does_not_affect_schedule(client, admin, outbox, fake_edge, monkeypatch):
"""手动补充(10:00 已建单)不影响 15:00 定时:定时照常按全天出库窗口新开一张,还能确认建单。"""
k = setup_store(client, admin)
fake_now(hh=10)
k.heartbeat()
assert client.post("/api/restock/runs/start", headers=k.h).json()["result"] == "started"
settle(k)
manual = k.svc().current(k.store_id)
assert manual["trigger"] == "console" and manual["status"] == "awaiting_confirm"
assert confirm(client, manual["token"], state_of(page(client, manual["token"]))).status_code == 200
settle(k)
assert k.svc().run(manual["id"])["order_no"] == "S2026102201"
run = push(k)
assert run["id"] != manual["id"] and run["trigger"] == "schedule" and run["status"] == "awaiting_confirm"
assert (run["window_start"], run["window_end"]) == (dt.datetime(2026, 10, 21, 15), dt.datetime(2026, 10, 22, 15))
assert "今天已建采购单 S2026102201" in group_msgs(k, outbox)[-1]
assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
settle(k)
assert k.svc().run(run["id"])["status"] == "awaiting_submit"
assert submit(client, run["token"]).status_code == 200 # 两张单各自按 token 提交
settle(k)
assert k.svc().run(run["id"])["status"] == "done" and k.svc().run(manual["id"])["status"] == "awaiting_submit"
sent = []
async def fake_send(sid, kind, severity, title, text, **kw):
sent.append(text)
monkeypatch.setattr(restock_service.notify, "send", fake_send)
k.call(k.svc().close, k.store_id, fake_now(hh=16), "16:00")
assert "(手动补充,待提交" in sent[-1] and "(定时推送,已提交)" in sent[-1]
def test_schedule_supersedes_pending_manual_and_waits_busy(client, admin, outbox, fake_edge, monkeypatch):
k = setup_store(client, admin)
fake_now(hh=10)
k.heartbeat()
client.post("/api/restock/runs/start", headers=k.h)
settle(k)
manual = k.svc().current(k.store_id)
run = push(k) # 手动单还在等确认 → 作废,定时单覆盖全天
assert k.svc().run(manual["id"])["status"] == "superseded" and run["trigger"] == "schedule"
r = client.post("/api/restock/runs/start", headers=k.h).json() # 手动不能作废待确认的定时单
assert r["result"] == "schedule_pending" and k.svc().run(run["id"])["status"] == "awaiting_confirm"
# 第二天:到点时手动单还在跑 → 等它跑完再开始,不会被丢掉
fake_now(d=23, hh=14, mm=59)
k.heartbeat()
busy = k.svc()._new_run(k.store_id, "scheduled", "console", Actor("user", "1", "店长"))
slept = []
async def fake_sleep(sec):
slept.append(sec)
db.q(runs_t.update().where(runs_t.c.id == busy).values(status="done"))
monkeypatch.setattr(restock_service.asyncio, "sleep", fake_sleep)
t = fake_now(d=23, hh=15)
k.heartbeat()
k.call(k.svc().push, k.store_id, t, "15:00")
settle(k)
run2 = k.svc().current(k.store_id)
assert slept and run2["id"] != busy and run2["trigger"] == "schedule" and run2["status"] == "awaiting_confirm"
def test_console_run_now_and_no_candidates(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
fake_now(hh=10)
k.heartbeat()
fake_edge.parts = []
r = client.post("/api/restock/runs/start", headers=k.h).json()
assert r["result"] == "started"
settle(k)
run = k.svc().current(k.store_id)
assert run["trigger"] == "console" and run["status"] == "done"
assert "没有纯牌零件出库" in group_msgs(k, outbox)[-1]
def test_page_events_and_cancel(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
run = push(k)
r = client.post(f"/api/public/restock/orders/{run['token']}/events",
json={"kind": "edit", "detail": {"part_no": "90915YZZM3", "field": "expected", "before": 30, "after": 25}})
assert r.status_code == 200
rows = audit.query(store_ids=[k.store_id], action="restock.page.edit", limit=5)[1]
assert rows and rows[0]["detail"]["after"] == 25 and rows[0]["ip"]
assert client.post(f"/api/public/restock/orders/{run['token']}/cancel").status_code == 200
assert k.svc().run(run["id"])["status"] == "cancelled"
assert client.get("/api/public/restock/orders/notatoken").status_code == 404
# ====================================================================== 截图兜底
def test_screenshot_fallback(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
run = push(k)
fake_edge.shot_fallback = "image"
assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
settle(k)
msgs = group_msgs(k, outbox)
note = next(m for m in msgs if "DMS 页面截图失败" in m)
assert "接口实际返回的数据渲染" in note and "不是 DMS 原页面" in note
assert "(接口数据渲染)" in msgs[-1] and len(outbox.images) == 2
po = db.one(select(po_t).where(po_t.c.run_id == run["id"]))
assert po["shots_fallback"] == "image" and po["fallback_reason"] == "浏览器登录超时"
assert open_alerts(k, "restock.screenshot_failed")
# ====================================================================== 单次补货
def test_single_restock_flow(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
fake_now(hh=15, mm=20)
k.heartbeat()
d = say(k, "@配件订货员 8713902280 空调滤 2 个")
assert d["calls"][0]["tool"] == "single_restock" and d["calls"][0]["args"] == {"part_no": "8713902280", "qty": 2}
settle(k)
q = fake_edge.params[0]
assert q["parts"] == [{"part_no": "8713902280", "name": "", "national": True}]
msg = group_msgs(k, outbox)[-1]
assert "查到 8713902280" in msg and "广州仓 0 · 华南仓 1095" in msg and "当日剩余可订 30" in msg and "回「订」建单" in msg
assert "GTMC" not in msg
single = k.svc().single_open(k.store_id)
assert single["kind"] == "single" and single["status"] == "awaiting_confirm"
say(k, "订", sender="lisi") # 别人回「订」不建单(只认发起人)
assert "需要 张三 本人 @我 回「订」" in group_msgs(k, outbox)[-1] and "restock.create_po" not in fake_edge.calls
rej = audit.query(store_ids=[k.store_id], action="restock.run.confirm_rejected", limit=1)[1][0]
assert rej["detail"]["reason"] == "不是发起人" and rej["detail"]["sender_id"] == "lisi"
say(k, "订")
settle(k)
run = k.svc().run(single["id"])
assert run["status"] == "awaiting_submit" and run["confirmed_via"] == "chat" and run["order_no"] == "S2026102201"
po = next(p for p in fake_edge.params if "lines" in p)
assert [(x["part_no"], x["qty"]) for x in po["lines"]] == [("8713902280", 2)] and po["remark"].endswith("(单次)" + run["doc_no"])
assert po["order_type"] == "S" and po["kind"] == "single"
done_msg = group_msgs(k, outbox)[-1]
assert "单建好了:S2026102201(待提交)" in done_msg and "请 张三 @我 回「确认提交」" in done_msg
say(k, "0888080463 5个") # 待确认提交:先查 DMS,仍是待提交 → 不接新单
assert "刚到 DMS 查过,这张单还是「待提交」" in group_msgs(k, outbox)[-1]
assert "回「确认提交」提交或「不提交」" in group_msgs(k, outbox)[-1]
assert k.svc().single_open(k.store_id)["id"] == single["id"]
for t in ("订", "好的", "确认", "OK"): # 待确认提交时没明确说「提交」:不提交
d = say(k, t)
assert d["calls"][0]["tool"] == "confirm_order", t
assert "@我 回「确认提交」" in group_msgs(k, outbox)[-1] and "restock.submit_po" not in fake_edge.calls
rej = audit.query(store_ids=[k.store_id], action="restock.run.submit_rejected", limit=1)[1][0]
assert rej["detail"]["reason"] == "未明确说提交"
say(k, "确认提交", sender="lisi") # 别人回「确认提交」不提交
assert "需要 张三 本人 @我 回「确认提交」" in group_msgs(k, outbox)[-1] and "restock.submit_po" not in fake_edge.calls
d = say(k, "可以,提交吧")
assert d["calls"][0]["tool"] == "submit_order"
settle(k)
run = k.svc().run(single["id"])
assert run["status"] == "done" and run["submitted_via"] == "chat" and run["submitted_by"] == "张三"
msgs = group_msgs(k, outbox)
assert "收到,正在 DMS 提交 S2026102201" in msgs[-2]
assert msgs[-1] == ("已提交 ✅\n————————\nPO 单号 S2026102201\n空调滤清器滤芯分总成 × 2\n"
"¥ 106.60 · 提交人 邹新\n————————\n状态:已提交")
say(k, "确认")
assert "没有待确认的单次补货" in group_msgs(k, outbox)[-1] and fake_edge.calls.count("restock.submit_po") == 1
# 单次补货不影响当天的定时补货
assert k.svc().ordered_today(k.store_id) is None and k.svc().current(k.store_id) is None
run_b = push(k, hh=15, mm=30)
assert run_b["status"] == "awaiting_confirm"
# 再来一单单次(不限次数),回「不订」取消
say(k, "8713902280 1个")
settle(k)
say(k, "不订")
assert "这单不订了" in group_msgs(k, outbox)[-1]
dec = audit.query(store_ids=[k.store_id], action="assistant.decision", limit=1)[1][0]
assert dec["ref"] and dec["ref"].startswith("restock:run:") # 决策留痕挂到单据上,时间线能看到
acts = [r["action"] for r in audit.query(store_ids=[k.store_id], limit=200)[1]]
assert acts.count("restock.run.start") == 3
def test_fallback_cancel_words_before_part_parse():
from app.features.restock.tools import fallback_intent
assert fallback_intent("不定")[0] == "cancel_order"
assert fallback_intent("先不订了")[0] == "cancel_order"
assert fallback_intent("不订 8713902280 2个")[0] == "cancel_order" # 不能当成新的单次补货去查 DMS
assert fallback_intent("8713902280 2个")[0] == "single_restock"
def test_single_cancel_while_querying(client, admin, outbox, fake_edge):
"""查询还没出结果就回「不订」:直接取消,查询结果回来后丢弃,不再推「回订 / 不订」。"""
k = setup_store(client, admin)
fake_now(hh=10)
k.heartbeat()
actor = Actor("planner_im", "zhangsan", "张三")
k.call(k.svc().single_request, k.store_id, actor, "8713902280", 2, "8713902280 2个")
single = k.svc().single_open(k.store_id)
assert single["status"] == "scanning"
assert k.call(k.svc().single_cancel, k.store_id, actor) == ""
assert k.svc().run(single["id"])["status"] == "cancelled"
n = len(group_msgs(k, outbox))
settle(k)
assert k.svc().run(single["id"])["status"] == "cancelled"
assert not any("回「订」建单" in m for m in group_msgs(k, outbox)[n:])
def test_single_restock_never_expires_and_capped(client, admin, outbox, fake_edge):
"""单次补货的查询结果不过期:隔了很久(tick 也跑过)再回「订」照常按查询结果建单。"""
k = setup_store(client, admin)
fake_now(hh=10)
k.heartbeat()
say(k, "8713902280 40个")
settle(k)
assert "你要 40 个" in group_msgs(k, outbox)[-1] and "只能按 30 个下单" in group_msgs(k, outbox)[-1]
t = clock.advance(hours=3)
k.call(k.svc().tick, k.store_id, t)
run = k.svc().single_open(k.store_id)
assert run and run["status"] == "awaiting_confirm"
k.heartbeat()
say(k, "订")
settle(k)
assert "restock.create_po" in fake_edge.calls
lines = next(p for p in fake_edge.params if "lines" in p)["lines"]
assert [(l["part_no"], l["qty"]) for l in lines] == [("8713902280", 30)]
assert k.svc().run(run["id"])["status"] == "awaiting_submit"
# ====================================================================== 确认提交(建单截图之后)
def single_created(k, outbox, text="8713902280 2个"):
"""单次补货走到「待确认提交」:报价 → 回「订」→ 建单截图。"""
fake_now(hh=15, mm=20)
k.heartbeat()
say(k, text)
settle(k)
say(k, "订")
settle(k)
run = k.svc().single_open(k.store_id)
assert run["status"] == "awaiting_submit"
return run
@pytest.fixture()
def switches():
from app.services import settings
yield lambda **kw: settings.save("edge_runtime", kw, "test")
settings.save("edge_runtime", {"allow_create_single": True, "allow_submit_single": True,
"allow_create_scheduled": True, "allow_submit_scheduled": True}, "test")
def test_single_not_submit_keeps_draft(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
run = single_created(k, outbox)
say(k, "不提交", sender="lisi") # 别人说不提交也不算
assert k.svc().run(run["id"])["status"] == "awaiting_submit"
d = say(k, "先不提交了")
assert d["calls"][0]["tool"] == "cancel_order"
r = k.svc().run(run["id"])
assert r["status"] == "cancelled" and "草稿" in r["message"]
assert "S2026102201 先不提交" in group_msgs(k, outbox)[-1] and "人工删除或提交" in group_msgs(k, outbox)[-1]
assert "restock.submit_po" not in fake_edge.calls
assert audit.query(store_ids=[k.store_id], action="restock.run.submit_cancel", limit=1)[1]
def test_submit_never_expires_and_checks_dms_first(client, admin, outbox, fake_edge):
"""建单后的确认提交不过期:两天后回「确认提交」照常提交,提交前先查 DMS 状态。"""
k = setup_store(client, admin)
run = single_created(k, outbox)
assert "前有效" not in group_msgs(k, outbox)[-1] and "不过期" in group_msgs(k, outbox)[-1]
t = clock.advance(days=2)
k.call(k.svc().tick, k.store_id, t)
assert k.svc().run(run["id"])["status"] == "awaiting_submit"
assert not open_alerts(k, "restock.submit_expired")
k.heartbeat()
say(k, "确认提交")
settle(k)
assert fake_edge.calls.index("restock.po_status") < fake_edge.calls.index("restock.submit_po")
assert k.svc().run(run["id"])["status"] == "done" and fake_edge.submitted == ["9001"]
assert audit.query(store_ids=[k.store_id], action="restock.po.status", limit=1)[1]
def test_submit_when_po_deleted_in_dms(client, admin, outbox, fake_edge):
"""DMS 里这张采购单已被删除:不提交,补货单收口(不订),群里如实说。之后可以发新的单次补货。"""
k = setup_store(client, admin)
run = single_created(k, outbox)
fake_edge.po_state = "missing"
say(k, "确认提交")
settle(k)
r = k.svc().run(run["id"])
assert r["status"] == "cancelled" and "已被删除" in r["message"]
assert "restock.submit_po" not in fake_edge.calls
assert "在 DMS 里已经被删除" in group_msgs(k, outbox)[-1]
assert k.svc().po_of(run["id"])["status"] == "已删除"
assert k.svc().single_open(k.store_id) is None
def test_submit_when_po_not_pending_in_dms(client, admin, outbox, fake_edge):
"""DMS 里这张单已经不是待提交(被别人处理过,如已完成):不提交,补货单收口(完成),回复当前状态。"""
k = setup_store(client, admin)
run = single_created(k, outbox)
fake_edge.po_state = "other"
say(k, "确认提交")
settle(k)
r = k.svc().run(run["id"])
assert r["status"] == "done" and "状态码 4" in r["message"]
assert "restock.submit_po" not in fake_edge.calls
assert "现在是「状态码 4」" in group_msgs(k, outbox)[-1]
def test_submit_when_po_already_submitted_or_status_unknown(client, admin, outbox, fake_edge):
"""已被别人提交 → 照样走 submit_po(取数端只回查不重复提交);查状态失败 → 也走 submit_po(提交前取数端会再核对)。"""
for state in ("submitted", "error"):
k = setup_store(client, admin)
fake_edge.calls.clear()
fake_edge.submitted.clear()
run = single_created(k, outbox)
fake_edge.po_state = state
say(k, "确认提交")
settle(k)
assert "restock.submit_po" in fake_edge.calls, state
assert k.svc().run(run["id"])["status"] == "done", state
fake_edge.po_state = "pending"
def _new_single_after(k, outbox, fake_edge, state):
"""上一单已建单待确认提交,DMS 里这张单处于 state 时,再发一单新的单次补货。返回 (旧单, 发完后的群消息)。"""
run = single_created(k, outbox)
fake_edge.po_state = state
n = len(group_msgs(k, outbox))
say(k, "0888080463 5个")
settle(k)
return run, group_msgs(k, outbox)[n:]
def test_new_single_when_prev_po_deleted(client, admin, outbox, fake_edge):
"""上一单在 DMS 里已被删除:上一单收口(不订),提示一句,接着给新零件报价。"""
k = setup_store(client, admin)
run, msgs = _new_single_after(k, outbox, fake_edge, "missing")
r = k.svc().run(run["id"])
assert r["status"] == "cancelled" and "已被删除" in r["message"]
assert any("上一单的采购单 S2026102201" in m and "已经被删除" in m and "收到,查一下 0888080463" in m for m in msgs)
new = k.svc().single_open(k.store_id)
assert new["id"] != run["id"] and new["status"] == "awaiting_confirm"
assert "restock.submit_po" not in fake_edge.calls
def test_new_single_when_prev_po_submitted_by_others(client, admin, outbox, fake_edge):
"""上一单在 DMS 里已经被别人提交:上一单收口(完成),说明状态,接着建新单;不会再去提交。"""
k = setup_store(client, admin)
run, msgs = _new_single_after(k, outbox, fake_edge, "submitted")
r = k.svc().run(run["id"])
assert r["status"] == "done" and "已提交" in r["message"]
assert any("在 DMS 里已经是「已提交」" in m for m in msgs)
assert k.svc().single_open(k.store_id)["id"] != run["id"]
assert "restock.submit_po" not in fake_edge.calls
def test_new_single_refused_when_prev_still_pending_or_unknown(client, admin, outbox, fake_edge):
"""上一单 DMS 里还是待提交 / 查不到状态:拒绝新单,上一单不动。"""
for state, word in (("pending", "刚到 DMS 查过,这张单还是「待提交」"), ("error", "暂时查不到 DMS 里这张单的状态")):
k = setup_store(client, admin)
run, msgs = _new_single_after(k, outbox, fake_edge, state)
assert word in msgs[-1] and "这次没有新建" in msgs[-1], state
assert k.svc().single_open(k.store_id)["id"] == run["id"], state
assert audit.query(store_ids=[k.store_id], action="restock.run.start_blocked", limit=1)[1], state
fake_edge.po_state = "pending"
def test_new_single_supersedes_pending_quote(client, admin, outbox, fake_edge):
"""上一单只报了价(DMS 里没有单):发新的就作废旧报价,接着查新零件;旧单之后回「订」也不会建单。"""
k = setup_store(client, admin)
fake_now(hh=15, mm=20)
k.heartbeat()
say(k, "8713902280 2个")
settle(k)
old = k.svc().single_open(k.store_id)
assert old["status"] == "awaiting_confirm"
say(k, "0888080463 5个", sender="lisi")
settle(k)
assert k.svc().run(old["id"])["status"] == "superseded"
assert any("(张三 发的)" in m and "已作废" in m for m in group_msgs(k, outbox))
new = k.svc().single_open(k.store_id)
assert new["id"] != old["id"] and new["triggered_by_id"] == "lisi"
assert "restock.po_status" not in fake_edge.calls and "restock.create_po" not in fake_edge.calls
def test_submit_po_missing_from_edge_verify(client, admin, outbox, fake_edge):
"""老流程兜底:取数端提交前核对时整张单找不到(po_missing)→ 也按已删除收口。"""
k = setup_store(client, admin)
run = single_created(k, outbox)
fake_edge.po_state = "error"
fake_edge.submit_error = EdgeError("提交前核对未通过,没有提交:DMS 采购单列表里找不到", code="po_missing")
say(k, "确认提交")
settle(k)
assert k.svc().run(run["id"])["status"] == "cancelled"
assert "在 DMS 里已经被删除" in group_msgs(k, outbox)[-1]
def test_scheduled_hold_and_expire(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
run = push(k)
assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
settle(k)
d = say(k, "不提交") # 群里说不提交:定时补货只引导去页面
assert "先不提交" in group_msgs(k, outbox)[-1] and "/m/restock/order/" in group_msgs(k, outbox)[-1]
assert k.svc().run(run["id"])["status"] == "awaiting_submit" and d["calls"][0]["tool"] == "cancel_order"
assert client.post(f"/api/public/restock/orders/{run['token']}/hold").status_code == 200
assert k.svc().run(run["id"])["status"] == "cancelled"
assert submit(client, run["token"]).status_code == 409
assert client.post(f"/api/public/restock/orders/{run['token']}/hold").status_code == 409
def test_submit_switches(client, admin, outbox, fake_edge, switches):
k = setup_store(client, admin)
run = single_created(k, outbox)
switches(allow_submit_single=False) # 建单后、确认前关掉提交
say(k, "确认提交")
assert "单次补货的提交功能已关闭" in group_msgs(k, outbox)[-1] and "restock.submit_po" not in fake_edge.calls
assert k.svc().run(run["id"])["status"] == "awaiting_submit"
blocked = audit.query(store_ids=[k.store_id], action="restock.run.submit_blocked", limit=1)[1][0]
assert blocked["detail"]["switches"]["allow_submit_single"] is False
switches(allow_submit_single=True)
say(k, "确认提交")
settle(k)
assert k.svc().run(run["id"])["status"] == "done"
# 建单开关:关掉单次补货的建单,回「订」不建单;定时补货不受影响
switches(allow_create_single=False)
say(k, "8713902280 1个")
settle(k)
say(k, "订")
assert "单次补货的建单功能已关闭" in group_msgs(k, outbox)[-1]
assert fake_edge.calls.count("restock.create_po") == 1
# 提交开关在建单时就是关的:建好单就结束,告诉人到 DMS 人工提交
switches(allow_submit_scheduled=False)
run2 = push(k, hh=15, mm=30)
assert confirm(client, run2["token"], state_of(page(client, run2["token"]))).status_code == 200
settle(k)
assert k.svc().run(run2["id"])["status"] == "done" and "提交功能已关闭" in group_msgs(k, outbox)[-1]
def test_submit_check_failed_then_retry(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
run = single_created(k, outbox)
fake_edge.submit_error = EdgeError("DMS 检查未通过,没有提交:accountBalanceFlag=false(疑似账户余额不足)",
"check_failed")
say(k, "确认提交")
settle(k)
r = k.svc().run(run["id"])
assert r["status"] == "awaiting_submit" and "疑似账户余额不足" in r["message"]
assert "没提交成功" in group_msgs(k, outbox)[-1] and "可以再 @我 回「确认提交」" in group_msgs(k, outbox)[-1]
assert open_alerts(k, "restock.submit_failed")
fake_edge.submit_error = None
clock.advance(seconds=5)
say(k, "确认提交")
settle(k)
assert k.svc().run(run["id"])["status"] == "done" and fake_edge.calls.count("restock.submit_po") == 2
assert not open_alerts(k, "restock.submit_failed")
keys = [p for p in fake_edge.params if "expect" in p]
assert len(keys) == 2
def test_submit_unknown_and_verify_failed(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
run = single_created(k, outbox)
fake_edge.submit_error = EdgeTimeout("取数端已领取任务,但没有回传结果", unknown=True)
say(k, "确认提交")
settle(k)
assert k.svc().run(run["id"])["status"] == "error"
assert open_alerts(k, "restock.submit_unknown")[0]["severity"] == "critical"
assert "系统不会自动重试" in group_msgs(k, outbox)[-1]
# 核对不一致(DMS 里的单被人改过):不提交,出错收口
fake_now(d=23, hh=10)
run2 = single_created(k, outbox, "8713902280 3个")
fake_edge.submit_error = EdgeError("提交前核对未通过,没有提交:8713902280 建单时 3 个,DMS 现在 5 个", "verify_failed")
say(k, "确认提交")
settle(k)
assert k.svc().run(run2["id"])["status"] == "error"
assert "和建单时不一致" in group_msgs(k, outbox)[-1]
def test_recover_submitting_is_unknown(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
run = single_created(k, outbox)
db.q(runs_t.update().where(runs_t.c.id == run["id"]).values(status="submitting"))
k.call(k.svc().recover)
assert k.svc().run(run["id"])["status"] == "error"
assert open_alerts(k, "restock.submit_unknown")
def test_fallback_submit_words():
from app.features.restock.tools import fallback_intent
for t in ("确认", "没问题", "好的 下单", "OK", "订", "可以"):
assert fallback_intent(t)[0] == "confirm_order", t
for t in ("可以,提交吧", "没问题,提交", "确认提交", "提交", "提交吧"):
assert fallback_intent(t)[0] == "submit_order", t
for t in ("不提交", "先不提交了", "别提交"):
assert fallback_intent(t)[0] == "cancel_order", t
assert fallback_intent("定时补货提交吧")[0] == "scheduled_restock"
assert fallback_intent("确认一下库存")[0] == "scheduled_restock"
def test_warehouse_labels():
from app.features.restock import planner
assert planner.wh_cn({"GTMC广州": 0, "华南GTMC": 5, "GTMC北京": 1}) == {"广州仓": 0, "华南仓": 5, "GTMC北京": 1}
ln = planner.plan_single({"part_no": "X1234567", "name": "x", "stock": 0, "warehouses": {"GTMC广州": 0, "华南GTMC": 0},
"national_queried": True, "daily_surplus": 10, "unit_price": 1}, 2, "trans_shipped")
assert ln.tag == "oos" and "关注仓(广州仓/华南仓)都没货" in ln.note
# ====================================================================== 重试 / 提醒 / 紧急 / 收口
def test_schedule_retry_remind_urgent_close(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
t = fake_now(hh=15, mm=0)
k.heartbeat()
fake_edge.fail_scan = 2
k.call(k.svc().push, k.store_id, t, "15:00")
settle(k)
run = k.svc().current(k.store_id)
assert run["status"] == "scan_retry" and run["trigger"] == "schedule"
assert "5 分钟后自动重试" in group_msgs(k, outbox)[1]
assert open_alerts(k, "restock.scan_failed")
for _ in range(2): # 第 2 次失败,第 3 次成功
t = clock.advance(minutes=5)
k.heartbeat()
k.call(k.svc().tick, k.store_id, t)
settle(k)
run = k.svc().current(k.store_id)
assert run["status"] == "awaiting_confirm" and run["scan_attempts"] == 3
assert not open_alerts(k, "restock.scan_failed")
reminders = []
for _ in range(5):
t = clock.advance(minutes=5)
k.call(k.svc().tick, k.store_id, t)
reminders = [m for m in group_msgs(k, outbox) if m.startswith("⏰ 今天的补货推荐还没确认")]
assert len(reminders) == 3 and "第 3/3 次提醒" in reminders[-1] and "/m/restock/order/" in reminders[-1]
clock.set_fake(dt.datetime(2026, 10, 22, 15, 46))
k.call(k.svc().tick, k.store_id, clock.now())
k.call(k.svc().tick, k.store_id, clock.now())
urgent = [m for m in outbox.to(k.contact) if "今天的定时补货还没有提交" in m]
assert len(urgent) == 1 and "紧急" in urgent[0]
clock.set_fake(dt.datetime(2026, 10, 22, 16, 0))
r = confirm(client, run["token"], [])
assert r.status_code == 409 and "截单" in r.json()["detail"]
k.call(k.svc().close, k.store_id, clock.now(), "16:00")
assert k.svc().run(run["id"])["status"] == "expired"
assert any("截单时间" in m for m in group_msgs(k, outbox))
def test_scan_final_failure_near_cutoff(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
fake_now(hh=15, mm=28)
k.heartbeat()
fake_edge.fail_scan = 9
k.call(k.svc().start, k.store_id, "console", Actor("user", "1", "店长"))
settle(k)
run = k.svc().current(k.store_id)
assert run["status"] == "error"
al = open_alerts(k, "restock.scan_failed")
assert al and al[0]["severity"] == "critical"
assert "已停止自动重试" in [m for m in group_msgs(k, outbox) if m.startswith("❌")][-1]
def test_edge_offline_at_push_retries(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
t = fake_now(hh=15) # 设备从来没心跳 → 不在线
k.call(k.svc().push, k.store_id, t, "15:00")
settle(k)
assert k.svc().current(k.store_id)["status"] == "scan_retry"
assert any("门店取数端不在线" in m for m in group_msgs(k, outbox))
assert fake_edge.calls == []
def _dms_po(run, lines, order_no="S2026102201", status="1"):
"""restock.find_po 命中的一张 DMS 采购单(备注以补货单号结尾)。"""
return {"order_id": "9001", "order_no": order_no,
"row": {"remark": "补货Agent自动创建(定时)" + run["doc_no"], "orderStatus": status, "supplierCode": "APC40",
"orderType": "S", "itemNum": len(lines), "totalAmount": 80.0, "createTime": "2026-10-22 15:01:00"},
"details": [{"partNo": l["part_no"], "purchaseQty": float(l["qty"])} for l in lines]}
def _single_unknown(k, fake_edge, text="8713902280 2个"):
"""单次补货:回「订」后建单结果未知。"""
fake_now(hh=15, mm=20)
k.heartbeat()
say(k, text)
settle(k)
fake_edge.po_error = EdgeTimeout("取数端已领取任务,但没有回传结果", unknown=True)
say(k, "订")
settle(k)
fake_edge.po_error = None
run = k.svc().single_open(k.store_id)
assert run["status"] == "awaiting_confirm" and run["create_unknown_at"]
return run
def test_po_unknown_reconcile_adopts_existing(client, admin, outbox, fake_edge):
"""定时补货建单结果未知:不终止、不自动重试;等够时间再确认 → 先核实,DMS 里已有就接管,不重复建单。"""
k = setup_store(client, admin)
run = push(k)
fake_edge.po_error = EdgeTimeout("取数端已领取任务,但没有回传结果", unknown=True)
assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
settle(k)
r = k.svc().run(run["id"])
assert r["status"] == "awaiting_confirm" and r["create_unknown_at"] and r["data_fetched_at"] is None
assert open_alerts(k, "restock.po_unknown")[0]["severity"] == "critical"
assert any("系统不会自动重试" in m and run["doc_no"] in m for m in group_msgs(k, outbox))
assert audit.query(store_ids=[k.store_id], action="restock.po.create_unknown", limit=1)[1]
first = next(p for p in fake_edge.params if "lines" in p)
assert first["remark"].endswith("(定时)" + run["doc_no"])
fake_edge.po_error = None
# 刷新后马上再确认:没等够 RECONCILE_WAIT_S,拒绝(防 DMS 晚落库)
assert client.post(f"/api/public/restock/orders/{run['token']}/refresh", json={"lines": []}).status_code == 200
settle(k)
resp = confirm(client, run["token"], state_of(page(client, run["token"])))
assert resp.status_code == 409 and "秒后再确认" in resp.json()["detail"]
rej = audit.query(store_ids=[k.store_id], action="restock.run.confirm_rejected", limit=1)[1][0]
assert "还要等" in rej["detail"]["reason"]
# 等够时间、刷新、再确认 → 核实命中 1 张 → 接管
clock.advance(seconds=125)
assert client.post(f"/api/public/restock/orders/{run['token']}/refresh", json={"lines": []}).status_code == 200
settle(k)
fake_edge.found = [_dms_po(run, first["lines"])]
assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
settle(k)
r = k.svc().run(run["id"])
assert r["status"] == "awaiting_submit" and r["order_no"] == "S2026102201" and r["create_unknown_at"] is None
assert fake_edge.calls.count("restock.create_po") == 1 and fake_edge.calls.count("restock.find_po") == 1
fp = next(p for p in fake_edge.params if "doc_no" in p)
assert fp["doc_no"] == run["doc_no"] and fp["supplier_code"] == "APC40"
assert not open_alerts(k, "restock.po_unknown")
assert any("上次其实已经建成采购单 S2026102201" in m for m in group_msgs(k, outbox))
res = audit.query(store_ids=[k.store_id], action="restock.po.reconcile_result", limit=1)[1][0]
assert res["detail"]["outcome"] == "adopt" and res["detail"]["found"][0]["order_no"] == "S2026102201"
assert audit.query(store_ids=[k.store_id], action="restock.po.adopted", limit=1)[1]
# 接管后照常确认提交,提交前核对按 DMS 里这张单的实际明细
assert submit(client, run["token"]).status_code == 200
settle(k)
assert k.svc().run(run["id"])["status"] == "done"
sp = next(p for p in fake_edge.params if "expect" in p)
assert sorted((x["part_no"], x["qty"]) for x in sp["expect"]["lines"]) == \
sorted((x["part_no"], float(x["qty"])) for x in first["lines"])
def test_po_unknown_single_reconcile_none_then_create(client, admin, outbox, fake_edge):
"""单次补货建单结果未知:不按时间过期、不接新单;再回「订」先核实,DMS 里没有才重新建。"""
k = setup_store(client, admin)
run = _single_unknown(k, fake_edge)
assert any("@我 再回「订」" in m for m in group_msgs(k, outbox))
say(k, "0888080463 5个") # 还没核实清楚:不接新单
assert "上一单单次补货还没处理完" in group_msgs(k, outbox)[-1]
assert "上次建单结果未知" in group_msgs(k, outbox)[-1] and run["doc_no"] in group_msgs(k, outbox)[-1]
assert k.svc().single_open(k.store_id)["id"] == run["id"]
t = clock.advance(minutes=11)
k.call(k.svc().tick, k.store_id, t)
assert k.svc().run(run["id"])["status"] == "awaiting_confirm" # 不按 10 分钟过期
k.heartbeat()
fake_edge.found = []
say(k, "订")
settle(k)
r = k.svc().run(run["id"])
assert r["status"] == "awaiting_submit" and r["create_unknown_at"] is None
assert fake_edge.calls.count("restock.create_po") == 2 and fake_edge.calls.count("restock.find_po") == 1
assert any("DMS 里没有本单" in m for m in group_msgs(k, outbox))
res = audit.query(store_ids=[k.store_id], action="restock.po.reconcile_result", limit=1)[1][0]
assert res["detail"]["outcome"] == "none"
def test_po_unknown_reconcile_failed_or_multi_never_creates(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
run = _single_unknown(k, fake_edge)
clock.advance(seconds=125)
fake_edge.find_error = EdgeError("访问 DMS 网络失败:timeout", "network")
say(k, "订")
settle(k)
r = k.svc().run(run["id"])
assert r["status"] == "awaiting_confirm" and r["create_unknown_at"] # 核实失败:不建单,标记保留
assert fake_edge.calls.count("restock.create_po") == 1
assert "这次没有建单" in group_msgs(k, outbox)[-1]
fake_edge.find_error = None
lines = [{"part_no": "8713902280", "qty": 2}]
fake_edge.found = [_dms_po(run, lines), _dms_po(run, lines, order_no="S2026102202")]
say(k, "订")
settle(k)
assert k.svc().run(run["id"])["status"] == "error"
assert fake_edge.calls.count("restock.create_po") == 1
assert "查到 2 张" in group_msgs(k, outbox)[-1]
assert open_alerts(k, "restock.po_unknown")[0]["severity"] == "critical"
def test_po_unknown_old_edge_cannot_reconcile(client, admin, outbox, fake_edge, monkeypatch):
k = setup_store(client, admin)
run = _single_unknown(k, fake_edge)
clock.advance(seconds=125)
monkeypatch.setattr(edge, "supports", lambda sid, t: t != "restock.find_po")
say(k, "订")
settle(k)
assert "取数端版本太旧" in group_msgs(k, outbox)[-1]
assert k.svc().run(run["id"])["status"] == "awaiting_confirm"
assert "restock.find_po" not in fake_edge.calls and fake_edge.calls.count("restock.create_po") == 1
def test_po_error_without_sent_flag_is_unknown(client, admin, outbox, fake_edge):
"""旧版取数端 / 请求发出后的任何错误(没有 sent=False 标记):一律按结果未知,不让直接重建。"""
k = setup_store(client, admin)
fake_now(hh=15, mm=20)
k.heartbeat()
say(k, "8713902280 2个")
settle(k)
fake_edge.po_error = EdgeError("DMS 接口报错:create-parts-po 返回非 JSON(HTTP 504)", "dms_error")
say(k, "订")
settle(k)
run = k.svc().single_open(k.store_id)
assert run["status"] == "awaiting_confirm" and run["create_unknown_at"]
det = audit.query(store_ids=[k.store_id], action="restock.po.create_unknown", limit=1)[1][0]["detail"]
assert det["code"] == "dms_error" and det["unknown"] is True
def test_cancel_after_unknown_warns_and_recover_creating(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
run = _single_unknown(k, fake_edge)
say(k, "不订")
assert k.svc().run(run["id"])["status"] == "cancelled"
assert "之前有一次建单结果未知" in group_msgs(k, outbox)[-1]
assert open_alerts(k, "restock.po_unknown") # 告警不关,等人工核实
# 服务重启时正在建单:回到待确认 + 标记(再确认先核实),不是直接出错
fake_now(d=23, hh=10)
k.heartbeat()
say(k, "8713902280 1个")
settle(k)
r2 = k.svc().single_open(k.store_id)
db.q(runs_t.update().where(runs_t.c.id == r2["id"]).values(status="creating"))
k.call(k.svc().recover)
r2 = k.svc().run(r2["id"])
assert r2["status"] == "awaiting_confirm" and r2["create_unknown_at"]
def test_po_definite_failure_requires_refresh(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
run = push(k)
fake_edge.po_error = EdgeError("建单前校验未通过:订购数不是包装数的整数倍", "action_error", {"sent": False})
assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
settle(k)
st = page(client, run["token"])
assert st["run"]["status"] == "awaiting_confirm" and not st["can_confirm"] # 数据作废,须刷新
assert "请在页面刷新后重新确认" in group_msgs(k, outbox)[-1]
fake_edge.po_error = None
assert client.post(f"/api/public/restock/orders/{run['token']}/refresh", json={"lines": []}).status_code == 200
settle(k)
assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
settle(k)
assert k.svc().run(run["id"])["status"] == "awaiting_submit"
# ====================================================================== 任务整体超时(页面可配)
def test_task_timeouts(client, admin, outbox, fake_edge):
k = setup_store(client, admin, task_timeouts={"scan_base": 500, "scan_per_part": 10, "create_base": 200,
"create_per_line": 5, "screenshot_extra": 30, "outbound": 700})
run = push(k)
assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
settle(k)
assert fake_edge.timeouts["restock.outbound"] == 700
assert fake_edge.timeouts["restock.quote"] == 500 + 10 * 5
assert fake_edge.timeouts["restock.create_po"] == 200 + 5 * 3
assert fake_edge.timeouts["restock.screenshot_po"] == 30 + 2 * 90 + 180
assert client.put("/api/restock/config", json={"values": {"task_timeouts": {"scan_per_part": 0}}},
headers=admin).status_code in (400, 422)
# ====================================================================== 预检
def test_preflight(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
t = fake_now(hh=14)
k.call(k.svc().preflight, k.store_id, t, "14:00")
assert open_alerts(k, "restock.preflight_failed") and "不在线" in outbox.to(k.contact)[-1]
k.heartbeat()
fake_edge.check_ok = False
k.call(k.svc().preflight, k.store_id, clock.advance(minutes=45), "14:45")
k.heartbeat()
fake_edge.check_ok = True
k.call(k.svc().preflight, k.store_id, clock.advance(minutes=1), "14:46")
assert fake_edge.params[-1]["parts"] == [{"part_no": "019990A115", "name": "用户手册"}] # 用 SO 常备件自检
assert not open_alerts(k, "restock.preflight_failed")
assert "已恢复" in outbox.to(k.contact)[-1]
# ====================================================================== 在库分类表 / SO 同步 / 留痕
def test_categories_seed_and_maintain(client, admin):
k = setup_store(client, admin)
r = client.get("/api/restock/categories", headers=k.h).json()
assert r["total"] == 234 and len(r["rows"]) == 50
assert client.get("/api/restock/categories?page=5&size=50", headers=k.h).json()["rows"][-1]["part_no"]
assert r["counts"] == {"保养零件": 113, "机油": 7, "轮胎": 10, "养护品": 8, "钣喷件": 10, "未分类": 86}
assert client.post("/api/restock/categories", json={"part_no": "gpdl0wm001", "name": "银粉定色剂", "category": "养护品"},
headers=k.h).status_code == 200
assert next(x for x in client.get("/api/restock/categories?q=GPDL0WM001", headers=k.h).json()["rows"])["category"] == "养护品"
r = client.post("/api/restock/categories/import",
json={"text": "零件号码,名称,分类\nA1,刹车片,保养零件\nB2\t机油格\t#N/A\nbad"}, headers=k.h).json()
assert r["imported"] == 2 and len(r["errors"]) == 1
assert next(x for x in client.get("/api/restock/categories?q=B2", headers=k.h).json()["rows"])["category"] == "未分类"
assert client.delete("/api/restock/categories/A1", headers=k.h).status_code == 200
assert "银粉定色剂" in client.get("/api/restock/categories.csv", headers=k.h).text
acts = {r["action"] for r in audit.query(store_ids=[k.store_id], action="restock.category", limit=50)[1]}
assert {"restock.category.seed", "restock.category.upsert", "restock.category.delete"} <= acts
def test_so_sync_replaces_table(client, admin, outbox, fake_edge):
k = setup_store(client, admin, so=False)
db.q(so_parts_t.insert().values(store_id=k.store_id, part_no="OLD", name="旧", order_count=1))
t = fake_now(y=2026, m=11, d=2, hh=9) # 周一
k.heartbeat()
k.call(k.svc().so_sync, k.store_id, t, "09:00")
p = next(x for x in fake_edge.params if "since" in x)
assert p["since"] == "2026-08-02" and p["order_type"] == "S" and p["exclude_status"] == ["1"]
parts = db.rows(select(so_parts_t).where(so_parts_t.c.store_id == k.store_id))
assert [x["part_no"] for x in parts] == ["019990A115"]
sync = db.one(select(so_syncs_t).where(so_syncs_t.c.store_id == k.store_id))
assert sync["status"] == "done" and sync["filter_trusted"] is False and sync["parts"] == 1
st = client.get("/api/restock/so", headers=k.h).json()
assert st["schedule"] == {"weekdays": [0], "time": "09:00", "months": 3} and st["last"]["status"] == "done"
assert st["part_count"] == 1 and not st["running"]
lst = client.get("/api/restock/so/syncs?page=1&size=10", headers=k.h).json()
assert lst["total"] == 1 and "stats" not in lst["rows"][0]
assert client.get(f"/api/restock/so/syncs/{lst['rows'][0]['id']}", headers=k.h).json()["stats"]["pages"] == 18
assert client.get("/api/restock/so/parts?q=0199", headers=k.h).json()["total"] == 1
def test_so_sync_incremental_merges_cache(client, admin, outbox, fake_edge):
k = setup_store(client, admin, so=False)
fake_edge.so_details = {"S1": [{"part_no": "A1", "name": "甲", "qty": 2}],
"S2": [{"part_no": "A1", "name": "甲", "qty": 3}, {"part_no": "B2", "name": "乙", "qty": 1}]}
t = fake_now(y=2026, m=11, d=2, hh=9)
k.heartbeat()
k.call(k.svc().so_sync, k.store_id, t, "09:00")
parts = {x["part_no"]: x for x in db.rows(select(so_parts_t).where(so_parts_t.c.store_id == k.store_id))}
assert (parts["A1"]["order_count"], parts["A1"]["qty_sum"], parts["A1"]["last_order_no"]) == (2, 5, "S2")
# 第二次:两张单都没变 → 不再取明细(known 带上指纹),S1 不在范围了 → 缓存删掉;新单 S3 只取它
fake_edge.so_details = {"S2": fake_edge.so_details["S2"], "S3": [{"part_no": "C3", "name": "丙", "qty": 4}]}
k.call(k.svc().so_sync, k.store_id, t, "09:00")
known = [x for x in fake_edge.params if "known" in x][-1]["known"]
assert known == {"S1": "fp-S1", "S2": "fp-S2"}
parts = {x["part_no"]: x for x in db.rows(select(so_parts_t).where(so_parts_t.c.store_id == k.store_id))}
assert set(parts) == {"A1", "B2", "C3"} and parts["A1"]["qty_sum"] == 3
cached = {r["order_no"] for r in db.rows(select(so_orders_t).where(so_orders_t.c.store_id == k.store_id))}
assert cached == {"S2", "S3"}
def test_api_calls_saved_from_task_result(client, admin):
k = setup_store(client, admin)
k.heartbeat()
tid = edge.submit(k.store_id, "restock.quote", {"parts": []}, timeout=60, feature="restock", ref="restock:run:1")
task = client.get("/api/edge/v1/tasks/next?wait=1", headers=k.eh).json()["task"]
assert task["id"] == tid
res = {"items": [], "api_trace_evidence": 7, "api_calls": [
{"seq": 1, "ts": "2026-10-22 15:00:01", "endpoint": "queryByPage", "method": "POST", "status": 200,
"code": "10000000", "message": "成功", "trace_id": "abc", "elapsed": 0.153, "rows": 1, "ok": True, "error": ""}]}
r = client.post(f"/api/edge/v1/tasks/{tid}/result", json={"ok": True, "result": res}, headers=k.eh)
assert r.status_code == 200, r.text
rows = db.rows(select(api_calls_t).where(api_calls_t.c.task_id == tid))
assert len(rows) == 1 and rows[0]["trace_id"] == "abc" and rows[0]["elapsed_ms"] == 153 and rows[0]["evidence_id"] == 7
def test_api_calls_clock_corrected(client, admin):
"""旧版取数端用本机时间记流水:本机时钟快了(流水时间晚于云端收到结果的时间)→ 整体往回挪;新版已对时的原样保存。"""
k = setup_store(client, admin)
clock.set_fake(dt.datetime(2026, 10, 22, 13, 40, 20))
k.heartbeat()
def send(res):
tid = edge.submit(k.store_id, "restock.quote", {"parts": []}, timeout=60, feature="restock", ref="restock:run:1")
client.get("/api/edge/v1/tasks/next?wait=1", headers=k.eh)
assert client.post(f"/api/edge/v1/tasks/{tid}/result", json={"ok": True, "result": res},
headers=k.eh).status_code == 200
return [r["ts"] for r in db.rows(select(api_calls_t).where(api_calls_t.c.task_id == tid)
.order_by(api_calls_t.c.seq))]
def call(seq, ts):
return {"seq": seq, "ts": ts, "endpoint": "queryByPage", "method": "POST", "status": 200, "ok": True}
calls = [call(1, "2026-10-22 13:40:22"), call(2, "2026-10-22 13:40:24")]
assert send({"api_calls": calls}) == [dt.datetime(2026, 10, 22, 13, 40, 18), dt.datetime(2026, 10, 22, 13, 40, 20)]
assert send({"api_calls": calls, "api_clock": "cloud"})[1] == dt.datetime(2026, 10, 22, 13, 40, 24)
def test_trace_csv(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
run = push(k)
assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
settle(k)
text = client.get("/api/restock/trace.csv", headers=k.h).text
assert "订购量" in text and "历史常备件" in text and "默认来源" in text
rows = k.svc().trace_rows(k.store_id, dt.date(2026, 1, 1), dt.date(2026, 12, 31))
filt = next(r for r in rows if r["配件码"] == "90915YZZM3")
assert (filt["订购量"], filt["采购单号"], filt["默认来源"]) == (18, "S2026102201", "推荐")
st = page(client, run["token"])
u = urlsplit(st["shots"][0]["url"])
assert client.get(u.path + "?" + u.query).status_code == 200 # 带签名的公开截图链接
assert client.get(u.path + "?sig=bad").status_code == 404
def test_config_validation_and_gating(client, admin):
k = setup_store(client, admin)
r = client.put("/api/restock/config", json={"values": {"push_time": "25:00"}}, headers=admin)
assert r.status_code == 400 and "push_time" in r.json()["detail"]
r = client.put("/api/restock/config", json={"values": {"push_time": "14:30", "confirm_valid_seconds": 90,
"so_sync_weekdays": [0, 3], "warehouses": ["GTMC广州"]}},
headers=admin)
assert r.status_code == 200 and r.json()["config"]["push_time"] == "14:30"
cfg = features.config(k.store_id, "restock")
assert (cfg.warehouses, cfg.confirm_valid_seconds, cfg.so_sync_weekdays) == (["GTMC广州"], 90, [0, 3])
assert client.put("/api/restock/config", json={"values": {"so_sync_weekdays": [7]}}, headers=admin).status_code == 400
# 时间线硬冲突:推送 / 预检不早于截单就永远不会触发,保存被拒
r = client.put("/api/restock/config", json={"values": {"push_time": "16:30"}}, headers=admin)
assert r.status_code == 400 and "push_time" in r.json()["detail"]
r = client.put("/api/restock/config", json={"values": {"preflight_times": ["14:00", "16:00"]}}, headers=admin)
assert r.status_code == 400 and "preflight_times" in r.json()["detail"]
assert client.put("/api/restock/config", json={"values": {"push_time": "16:30", "auto_push": False}},
headers=admin).status_code == 200 # 关了定时推送就不管推送时间
assert client.put("/api/restock/config", json={"enabled": False}, headers=admin).status_code == 200
assert client.get("/api/restock/categories", headers=admin).status_code == 403
assert client.get("/api/restock/today", headers=admin).json()["enabled"] is False
def test_history_export(client, admin, monkeypatch):
k = setup_store(client, admin)
k.heartbeat()
async def fake_wait(tid, timeout):
info = edge.save_evidence(k.store_id, tid, "stock_full.csv", "配件码,库存\nA,1\n".encode(), "export", "text/csv")
edge.db.q(edge.update(edge.tasks_t).where(edge.tasks_t.c.id == tid).values(
status="done", result=db.jdump({"evidence": [info["id"]], "summary": {"rows": 1, "total": 1}})))
return edge.task(tid)
monkeypatch.setattr(edge, "wait", fake_wait)
r = client.post("/api/restock/exports", json={"kind": "stock"}, headers=k.h)
assert r.status_code == 200, r.text
k.call(lambda: __import__("asyncio").sleep(0.3))
rows = client.get("/api/restock/exports", headers=k.h).json()["rows"]
assert rows[0]["status"] == "done" and rows[0]["files"][0]["name"] == "stock_full.csv"
assert client.post("/api/restock/exports", json={"kind": "po"}, headers=k.h).status_code == 409 # 缺年份
# ====================================================================== 调度器:只对开通的门店、每天只触发一次、按星期
def test_scheduler_fires_once_and_respects_feature(client, admin, outbox, fake_edge):
a = setup_store(client, admin)
other = stores.create_store("STORE-B", "没开通补货的门店") # 预留的多门店:没开通就不派发
fake_now(hh=14, mm=0)
a.heartbeat()
a.call(scheduler.tick, True)
a.call(scheduler.tick, True)
marks = db.rows(select(schedule_marks_t))
assert [(m["store_id"], m["job_key"], m["slot"]) for m in marks] == [(a.store_id, "preflight", "14:00")]
assert fake_edge.by_store.count((a.store_id, "sys.check")) == 1
assert not [x for x in fake_edge.by_store if x[0] == other]
def test_scheduler_weekly_so_sync(client, admin, outbox, fake_edge):
a = setup_store(client, admin, so=False)
fake_now(y=2026, m=10, d=27, hh=9, mm=0) # 周二:不同步
a.heartbeat()
a.call(scheduler.tick, True)
assert "restock.so_sync" not in fake_edge.calls
fake_now(y=2026, m=11, d=2, hh=9, mm=1) # 周一 09:00 后:同步一次
a.heartbeat()
a.call(scheduler.tick, True)
a.call(scheduler.tick, True)
assert fake_edge.calls.count("restock.so_sync") == 1
assert db.rows(select(runs_t)) == []