test_find_po.py
13.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
# -*- coding: utf-8 -*-
"""找单(建单回查 / find_po / _find_po_row)与「已创建未提交的采购单」(list_drafts):用假会话,不需要模拟 DMS。
edge\\vendor\\python38\\python.exe -m unittest tests.test_find_po -v (在 edge 目录下)
"""
import os
import shutil
import sys
import tempfile
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
EDGE = os.path.dirname(HERE)
sys.path.insert(0, EDGE)
from edgeclient import actions # noqa: E402
from edgeclient.connectors.gtmc.api import ApiError # noqa: E402
from edgeclient.connectors.gtmc.client import NetworkError # noqa: E402
from edgeclient.core.tasks import REGISTRY, NullSteps # noqa: E402
from edgeclient.infra.localstore import RunDir # noqa: E402
from edgeclient.plugins import restock as restock_plugin # noqa: E402,F401 登记任务
def order(i, status="2", remark="", by="李四", t=None, supplier="APC40"):
"""第 i 张采购单(i 越小越新):创建时间按 i 递减。"""
return {"id": str(9000000 + i), "orderNo": "S20261109%04d" % i, "orderType": "S", "orderStatus": status,
"supplierCode": supplier, "createTime": t or "2026-11-09 %02d:%02d:00" % (23 - i // 60, 59 - i % 60),
"createByName": by, "itemNum": "1", "totalAmount": 10.0, "remark": remark}
class FakeSess(object):
"""按创建时间倒序分页的采购单列表。honor_no / honor_status:服务端单号 / 状态过滤是否生效。
info_error:详情接口一律抛这个异常(None = 正常:存在返回详情,不存在返回业务错误码)。"""
def __init__(self, orders, honor_no=True, honor_status=True, info_error=None):
self.orders = list(orders)
self.honor_no, self.honor_status, self.info_error = honor_no, honor_status, info_error
self.pages, self.infos, self.details = [], [], []
self.created = None # create_po 时插到列表的哪个位置
def ensure_valid(self):
return "reused"
def po_page(self, page=1, size=20, **f):
self.pages.append((page, size, dict(f)))
rows = self.orders
if f.get("orderNo") and self.honor_no:
rows = [o for o in rows if o["orderNo"] == f["orderNo"]]
if f.get("orderStatus") and self.honor_status:
rows = [o for o in rows if o["orderStatus"] == f["orderStatus"]]
return len(rows), [dict(o) for o in rows[(page - 1) * size: page * size]]
def po_info(self, oid):
self.infos.append(oid)
if self.info_error is not None:
raise self.info_error
o = next((o for o in self.orders if o["id"] == str(oid)), None)
if o is None:
raise ApiError("info-parts-po 失败: HTTP 200 code=50000003 message=单据不存在", "50000003")
return {"orderNo": o["orderNo"], "remark": o["remark"], "createTime": o["createTime"], "orderType": "S",
"createByName": o["createByName"], "totalPriceSum": "10.0",
"details": [{"partNo": "P%s" % o["id"], "partName": "件", "purchaseQty": 2.0}]}
def po_detail_all(self, row):
self.details.append(row["id"])
return 1, [{"itemNo": "1", "partNo": "P%s" % row["id"], "partName": "件", "purchaseQty": 2.0,
"cancelledQty": 0.0}]
def create_po(self, payload):
o = order(0, "1", payload.get("remark") or "", "张三")
o.update(id="7777", orderNo="S202611090999")
self.orders.insert(self.created, o)
return {"id": "7777", "validFlag": True}
def po_detail_all_for_create(self, row):
return 1, [{"partNo": "019990A115", "purchaseQty": 2.0}]
class Cfg(object):
supplier_code = "APC40"
page_size = 20
max_pages = 50
po_remark = "补货"
def __init__(self, data_dir):
self.data_dir = data_dir
class FindPoTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="edge_findpo_")
self.cfg = Cfg(self.tmp)
self._old = (actions.READ_RETRY_WAIT, actions.LOCATE_WAIT)
actions.READ_RETRY_WAIT = actions.LOCATE_WAIT = 0
def tearDown(self):
actions.READ_RETRY_WAIT, actions.LOCATE_WAIT = self._old
shutil.rmtree(self.tmp, ignore_errors=True)
# ---------------- list_drafts ----------------
def test_list_drafts_paging_and_local_status_filter(self):
"""服务端状态过滤没生效:本地按 orderStatus=1 筛、filter_trusted=False;翻到 since 为止;前 max_detail 张取明细。"""
orders = []
for i in range(100): # 每 3 张里 1 张待提交;前 45 张在 since 之后
st = "1" if i % 3 == 0 else "2"
remark = "补货Agent自动创建(定时)RP-20261109-1-%02d" % i if i % 2 == 0 else "店长手工建的"
orders.append(order(i, st, remark, "张三" if i % 2 == 0 else "邹新"))
since = orders[44]["createTime"]
s = FakeSess(orders, honor_status=False)
r = actions.list_drafts(self.cfg, s, "APC40", since, max_detail=3)
want = [o for o in orders[:45] if o["orderStatus"] == "1"]
self.assertEqual([d["order_no"] for d in r["drafts"]], [o["orderNo"] for o in want])
self.assertFalse(r["filter_trusted"])
self.assertTrue(r["truncated"])
self.assertEqual(r["scanned"], 80) # 第 4 页整页早于 since 后停止
self.assertEqual([p[0] for p in s.pages], [1, 2, 3, 4])
self.assertEqual(s.pages[0][2], {"supplierCode": "APC40", "orderStatus": "1"})
self.assertEqual([d["details"] is not None for d in r["drafts"]], [True] * 3 + [False] * (len(want) - 3))
d0 = r["drafts"][0]
self.assertEqual((d0["order_id"], d0["create_by"], d0["doc_no"]), ("9000000", "张三", "RP-20261109-1-00"))
self.assertEqual(d0["details"], [{"part_no": "P9000000", "name": "件", "qty": 2.0}])
self.assertEqual(r["drafts"][1]["doc_no"], "") # 手工建的单:备注里没有补货单号
for k in ("create_time", "remark", "item_num", "total_amount"):
self.assertIn(k, d0)
self.assertTrue(os.path.exists(os.path.join(r["dir"], "list_drafts.json")))
def test_list_drafts_trusted_filter(self):
orders = [order(i, "1" if i < 25 else "2", "补货 SP-20261109-1-01" if i == 3 else "") for i in range(40)]
s = FakeSess(orders)
r = actions.list_drafts(self.cfg, s, "APC40", "", max_detail=50)
self.assertTrue(r["filter_trusted"])
self.assertFalse(r["truncated"])
self.assertEqual((len(r["drafts"]), r["scanned"]), (25, 25))
self.assertEqual(r["drafts"][3]["doc_no"], "SP-20261109-1-01")
self.assertTrue(all(d["details"] for d in r["drafts"]))
def test_list_drafts_task_registered(self):
self.assertIn("restock.list_drafts", REGISTRY)
def test_doc_no_of(self):
self.assertEqual(actions.doc_no_of("补货Agent自动创建(定时)RP-20261108-1-01 "), "RP-20261108-1-01")
self.assertEqual(actions.doc_no_of("补货SP-X-1-010"), "SP-X-1-010")
self.assertEqual(actions.doc_no_of("补货Agent自动创建(批量)MP-20261126-1-01"), "MP-20261126-1-01")
self.assertEqual(actions.doc_no_of("GRP-1"), "")
self.assertEqual(actions.doc_no_of(None), "")
# ---------------- 建单后回查 ----------------
def _create(self, s):
rd = RunDir(self.cfg.data_dir, "create_po")
lines = [{"part_no": "019990A115", "qty": 2}]
masters = {"019990A115": {"partNo": "019990A115", "partName": "件", "unitPrice": "1.0"}}
return actions._create_after_validate(self.cfg, s, NullSteps(), lambda p, k: None, rd, lines, masters, [],
{}, "APC40", "S", "补货 SP-20261109-1-01")
def test_create_verify_info_fails_found_at_row_150(self):
"""建单后详情接口失败:翻列表按 id 在第 150 条找到(不再只看前 20 条)。"""
s = FakeSess([order(i) for i in range(1, 300)], info_error=NetworkError("info 网络失败"))
s.created = 149
s.po_detail_all = s.po_detail_all_for_create
r = self._create(s)
self.assertEqual((r["order_id"], r["order_no"]), ("7777", "S202611090999"))
self.assertEqual(r["mismatch"], [])
self.assertEqual([p[0] for p in s.pages], [1, 2, 3, 4, 5, 6, 7, 8])
def test_create_verify_by_info_order_no(self):
"""详情接口正常:按详情里的单号过滤 1 次就拿到列表行,不翻页。"""
s = FakeSess([order(i) for i in range(1, 300)])
s.created = 250
s.po_detail_all = s.po_detail_all_for_create
r = self._create(s)
self.assertEqual(r["order_no"], "S202611090999")
self.assertEqual(s.pages, [(1, 20, {"orderNo": "S202611090999"})])
def test_create_verify_not_found_is_unknown_with_order_id(self):
s = FakeSess([order(i) for i in range(1, 300)], info_error=NetworkError("info 网络失败"))
s.created = 250 # 在 200 条以外
with self.assertRaises(actions.UnknownResult) as cm:
self._create(s)
self.assertEqual(cm.exception.result.get("order_id"), "7777")
self.assertEqual(len(s.pages), actions.LOCATE_TRIES * 10)
# ---------------- _find_po_row ----------------
def test_find_po_row_filter_ignored_found_after_page_2(self):
orders = [order(i) for i in range(300)]
s = FakeSess(orders, honor_no=False)
row = actions._find_po_row(s, orders[65]["orderNo"], orders[65]["id"])
self.assertEqual(row["id"], orders[65]["id"])
self.assertEqual(s.infos, [orders[65]["id"]])
self.assertGreater(max(p[0] for p in s.pages), 2)
def test_find_po_row_missing_only_when_info_says_so(self):
orders = [order(i) for i in range(300)]
# 详情明确不存在 + 200 条内没有 → 找不到
s = FakeSess(orders, honor_no=False)
self.assertIsNone(actions._find_po_row(s, "S-GONE", "123"))
self.assertEqual(len([p for p in s.pages if not p[2].get("orderNo")]), 10) # 翻满 200 条才下结论
# 单在第 250 条(200 条以外)、详情说存在 → 不能当已删除
s = FakeSess(orders, honor_no=False)
with self.assertRaises(actions.PoLookupError):
actions._find_po_row(s, orders[250]["orderNo"], orders[250]["id"])
# 详情接口网络失败 → 直接抛出
s = FakeSess(orders, honor_no=False, info_error=NetworkError("断网"))
with self.assertRaises(NetworkError):
actions._find_po_row(s, "S-GONE", "123")
# 网关错误页(非 JSON,没有业务错误码)→ 直接抛出
s = FakeSess(orders, honor_no=False, info_error=ApiError("info-parts-po 返回非 JSON(HTTP 502)"))
with self.assertRaises(ApiError):
actions._find_po_row(s, "S-GONE", "123")
def test_find_po_row_scans_at_most_200(self):
s = FakeSess([order(i) for i in range(500)], honor_no=False)
self.assertIsNone(actions._find_po_row(s, "S-GONE", "123"))
scan = [p for p in s.pages if not p[2].get("orderNo")]
self.assertEqual(len(scan), actions.PO_LOOKBACK_ROWS // actions.PO_SCAN_PAGE)
def test_submit_missing_po_is_po_missing(self):
s = FakeSess([order(i) for i in range(30)], honor_no=False)
with self.assertRaises(actions.ActionError) as cm:
actions.submit_po(self.cfg, s, "123", "S-GONE", {"lines": [{"part_no": "X", "qty": 1}]})
self.assertEqual(cm.exception.code, "po_missing")
s = FakeSess([order(i) for i in range(30)], honor_no=False, info_error=NetworkError("断网"))
with self.assertRaises(NetworkError):
actions.submit_po(self.cfg, s, "123", "S-GONE", {"lines": [{"part_no": "X", "qty": 1}]})
# ---------------- find_po ----------------
def test_find_po_stops_at_200_rows(self):
s = FakeSess([order(i, remark="别的单") for i in range(500)])
r = actions.find_po(self.cfg, s, "APC40", "SP-20261109-1-01", "2026-01-01 00:00:00")
self.assertEqual((r["found"], r["scanned"], r["truncated"]), ([], 200, True))
self.assertEqual(len(s.pages), 10)
def test_find_po_by_order_id_first(self):
orders = [order(i, remark="补货 SP-20261109-1-01" if i == 120 else "") for i in range(300)]
s = FakeSess(orders)
r = actions.find_po(self.cfg, s, "APC40", "SP-20261109-1-01", "2026-01-01 00:00:00", order_id=orders[120]["id"])
self.assertEqual([(f["order_id"], f["order_no"], f["matched_by"]) for f in r["found"]],
[(orders[120]["id"], orders[120]["orderNo"], "id")])
self.assertEqual(r["found"][0]["details"][0]["partNo"], "P%s" % orders[120]["id"])
self.assertEqual(s.pages, [(1, 20, {"orderNo": orders[120]["orderNo"]})]) # 按 id 命中,不翻列表
def test_find_po_order_id_missing_falls_back_to_remark(self):
orders = [order(i, remark="补货 SP-20261109-1-01" if i == 30 else "") for i in range(100)]
s = FakeSess(orders)
r = actions.find_po(self.cfg, s, "APC40", "SP-20261109-1-01", "2026-01-01 00:00:00", order_id="404")
self.assertEqual([(f["order_no"], f["matched_by"]) for f in r["found"]], [(orders[30]["orderNo"], "remark")])
self.assertEqual(r["scanned"], 100)
s = FakeSess(orders, info_error=NetworkError("断网")) # 按 id 查失败:直接抛出(云端据此不建单)
with self.assertRaises(NetworkError):
actions.find_po(self.cfg, s, "APC40", "SP-20261109-1-01", "2026-01-01 00:00:00", order_id="404")
if __name__ == "__main__":
unittest.main()