Files

331 lines
12 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""v1.0.44 回归:空秤闸门 + 无单自采行(independent_inbound)上秤识别入库
现场反馈(2026-11-05):
1. 「画面有变动的就识别,称上明明都没放商品」—— 秤没识别到时状态停在
IDLE,称重让路闸门失效,画面一动就起免称重识别。新增空秤闸门:
秤在线且读数≈0 → 画面再怎么变也不识别。
2. 「没有依靠订单的商品现场识别不能入库」—— 无单自采行(服务端待验行带
independent_inbound 标记)以前被终端当「旧版独立入库行」剔除。现在:
识别绑定照常,提交改调单行结案接口 /mobile/inspection/complete。
3. 「计量单位不是重量的商品也能放到称上入库,靠识别来选择」—— 件行确认
时把秤上真实读数留档(actual_weight,斤口径)。
"""
import os
import sys
import time
import types
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from core.flow import FlowEngine
from core.api.client import ApiClient, ApiError
ok = fail = 0
def check(name, cond, extra=''):
global ok, fail
if cond:
ok += 1
print(' ✓', name)
else:
fail += 1
print(' ✗', name, extra)
class Fake(FlowEngine):
"""只搭被测路径需要的属性(不连设备、不起线程)"""
def __init__(self, noweigh_cfg=None, station='inspection'):
self.cfg = {'flow': {}, 'vision': {},
'noweigh': dict(noweigh_cfg or {})}
self.station = station
self.state = 'IDLE'
self.rows = []
self.logged_in = True
self.locked_msg = None
self._aborted = False
self._running = True
self._auto_last_at = 0.0
self._auto_base = None
self._auto_armed = False
self._auto_hits = 0
self._auto_moved_at = 0.0
self._auto_pre_sig = None
self._auto_fail_n = 0
self._auto_fail_sig = None
self._auto_ready_at = 0.0
self._auto_fires = []
self._auto_rate_log_at = 0.0
self.count_calls = []
self.logs = []
def emit(self, ev, payload=None):
if ev == 'log':
self.logs.append(str(payload))
def start_count_cycle(self, auto=False):
self.count_calls.append(auto)
return True, ''
def _frame_sig(self):
return getattr(self, 'sig', None)
def noweigh_rows(self):
return [r for r in self.rows if r.get('item_name')]
def mrow(rid='r1', name='自采核桃', unit='箱', indep=True, qty=5.0):
r = {'id': rid, 'item_name': name, 'unit': unit,
'prepare_qty': qty, 'required_qty': qty}
if indep:
r['processing_details'] = {'independent_inbound': True,
'purchase_code': 'RAW-1'}
r['order_code'] = None
return r
print('一、空秤闸门(画面识别必须秤上有货)')
e = Fake()
e.state = 'IDLE'
e.rows = [mrow()]
# 空秤:画面变了也不识别
e.sig = object() # 任意非 None,闸门要在比帧差之前就拦住
e._auto_scan(time.monotonic(), {'present': True, 'fresh': True, 'weight': 0.0})
check('空秤(0.0kg)画面变化不起识别', e.count_calls == [])
# 微小读数(空秤底噪)同样拦
e._auto_scan(time.monotonic(), {'present': True, 'fresh': True, 'weight': 0.01})
check('底噪 0.01kg 同样拦', e.count_calls == [])
# 秤上有货 → 放行(会走到帧比较/起识别,这里 sig=None 只-return,不算起)
e._auto_scan(time.monotonic(), {'present': True, 'fresh': True, 'weight': 3.2})
check('秤上有货放行进入后续判定', e.count_calls == []) # sig=None 不起轮,但没被闸门拦
e2 = Fake(noweigh_cfg={'auto_empty_scale_kg': 0})
e2.rows = [mrow()]
e2.sig = object()
e2._auto_scan(time.monotonic(), {'present': True, 'fresh': True, 'weight': 0.0})
check('auto_empty_scale_kg=0 时闸门关闭(回到旧行为)',
e2.count_calls == []) # sig=None 只是不会起轮;关键是没被闸门 return 掉
print('二、无单自采行提交路由(commit_inspection_single)')
c = ApiClient.__new__(ApiClient)
c.mock = False
c.cfg = {}
captured = {}
def fake_request(method, path, body=None, timeout=None):
captured['method'] = method
captured['path'] = path
captured['body'] = body
return {'success': True, 'data': {'result': {'effect': 'independent_inbound'}}}
c._request = fake_request
row = mrow()
row['purchase_price'] = 12.5
resp = c.commit_inspection_single(row, 5.0, 1.234, 'op-1')
check('调用 /mobile/inspection/complete',
captured['path'] == '/mobile/inspection/complete')
b = captured['body']
check('actual_qty=行单位数量(件数)', b.get('actual_qty') == 5.0)
check('actual_weight=秤读数折斤(kg×2)', b.get('actual_weight') == round(1.234 * 2, 3))
check('quality_rating=合格', b.get('quality_rating') == '合格')
check('loss_qty=0', b.get('loss_qty') == 0)
check('unit=行单位', b.get('unit') == '箱')
check('purchase_price=登记价', b.get('purchase_price') == 12.5)
check('回包归一化成 _verify 认识的形态',
resp.get('operation_status') == 'committed_by_this_operation'
and resp.get('client_operation_id') == 'op-1')
# 无重量 / 无登记价时不发这两个字段
row2 = mrow('r2')
row2.pop('purchase_price', None)
c.commit_inspection_single(row2, 3.0, 0.0, 'op-2')
b2 = captured['body']
check('秤读数 0 不带 actual_weight', 'actual_weight' not in b2)
check('无登记价不带 purchase_price', 'purchase_price' not in b2)
# success=false 要报错
def fail_request(method, path, body=None, timeout=None):
return {'success': False, 'error': 'invalid_cost',
'error_description': '成本价须大于 0'}
c._request = fail_request
try:
c.commit_inspection_single(row2, 3.0, 0.0, 'op-3')
check('success=false 必须报错', False, '竟然没抛')
except ApiError:
check('success=false 必须报错', True)
print('三、mock 客户端与 _verify 衔接')
cm = ApiClient.__new__(ApiClient)
cm.mock = True
cm.cfg = {}
r3 = cm.commit_inspection_single(row2, 3.0, 0.0, 'op-4')
check('mock 回 committed_by_this_operation',
r3.get('operation_status') == 'committed_by_this_operation')
print('四、确认流程放行无单自采行(不再拦「旧版独立入库」)')
class FakeConfirm(Fake):
def __init__(self):
super().__init__()
self.submit_calls = []
self._focus = None
self._frozen_kg = 0.0
self._frozen_row = None
self._count_mode = True
self._count_qty = 0.0
self._remove_submit = False
self._last_st = {'present': True, 'fresh': True, 'weight': 2.4}
def _row_by_id(self, rid):
for r in self.rows:
if r.get('id') == rid:
return r
return None
def _focus_payload(self):
return dict(self._focus or {})
def _clear_focus(self):
self._focus = None
def _start_submit(self, row, business, source):
self.submit_calls.append((row.get('id'), float(business), source))
ec = FakeConfirm()
ec.rows = [mrow()]
ec.state = 'CONFIRM'
ec._focus = {'mode': 'count', 'row_id': 'r1', 'business': 5.0, 'auto': True}
okc, msgc = ec.confirm_focus(auto_remove=False)
check('无单自采件行确认提交放行', okc and len(ec.submit_calls) == 1, msgc)
check('真实秤读数已留档(_count_real_kg=2.4)',
abs(getattr(ec, '_count_real_kg', 0) - 2.4) < 1e-9)
print('五、_submit_worker 分支(提交时按行标记改调单行结案)')
class FakeWorker(FakeConfirm):
def __init__(self):
super().__init__()
self.api = types.SimpleNamespace(
user_id='u1',
base_url='http://mock',
commit_inspection_single=self._fake_single,
preview_merge_scope=self._fail_scope)
self.journal = types.SimpleNamespace(
begin=lambda *a, **k: {'id': 'j1'},
update=lambda *a, **k: None,
conclude=lambda *a, **k: None,
has_unresolved=lambda: False)
self.frames = types.SimpleNamespace(
capture_confirmed=lambda: {'qualified': False, 'reason': 't',
'path': ''})
self._count_real_kg = 2.4
self.single_calls = []
def _fake_single(self, row, qty, wkg, op):
self.single_calls.append((row.get('id'), float(qty), float(wkg)))
return {'operation_status': 'committed_by_this_operation',
'client_operation_id': op}
def _fail_scope(self, *a, **k):
raise AssertionError('无单行不该走 merge-scope-preview')
def _snapshot_ok(self, row):
return True
def _handle_send_error(self, *a, **k):
pass
def _verify(self, resp, op):
return 'ok'
def _after_success(self, *a, **k):
pass
ew = FakeWorker()
ew._submit_worker(mrow(), 5.0, '测试')
check('无单行改调 commit_inspection_single',
len(ew.single_calls) == 1 and ew.single_calls[0][0] == 'r1')
check('actual_weight 用留档的真实秤读数',
abs(ew.single_calls[0][2] - 2.4) < 1e-9)
print('六、_recover:无单行按待办核实')
class FakeRecover(FakeConfirm):
def __init__(self, present):
super().__init__()
self.api = types.SimpleNamespace(
pending=lambda station: {'rows': ([] if not present else [mrow()])})
self.journal = types.SimpleNamespace(
conclude=lambda *a, **k: self.concludes.append(a[1]),
has_unresolved=lambda: False)
self.concludes = []
self.results = []
self.locked = False
self._frozen_row = mrow()
def emit(self, ev, payload=None):
if ev == 'log':
self.logs.append(str(payload))
elif ev == 'result':
self.results.append(payload)
elif ev == 'locked':
self.locked = True
def _to_done(self):
self.state = 'DONE'
er = FakeRecover(present=True)
er._recover_indep('op-9')
check('该行仍在待办 → 判「服务端没收到」',
er.concludes and er.results and '没有收到' in str(er.results[0]))
er2 = FakeRecover(present=False)
er2._recover_indep('op-9')
check('该行已不在待办 → 锁住等人工(不猜成功)', er2.locked)
print('七、按重量择行(同名多行,秤读数最近的优先)')
class FakePick(FakeConfirm):
"""复用确认引擎骨架,只测 _pick_by_weight 的判定"""
pass
ep = FakeConfirm()
ep.cfg['flow']['weight_pick_pct'] = 40
ep.cfg['noweigh'] = {'unit_weight_kg': {'SKU-A': 10.0, 'SKU-B': 2.0}}
ra = mrow('rA', '自采核桃', '箱', qty=5.0) # 应重 5×10=50kg
ra['sku_code'] = 'SKU-A'
rb = mrow('rB', '自采核桃', '箱', qty=5.0) # 应重 5×2=10kg
rb['sku_code'] = 'SKU-B'
rc = mrow('rC', '自采核桃', '箱', qty=3.0) # 应重 3×10=30kg
rc['sku_code'] = 'SKU-A'
ep.rows = [ra, rb, rc]
# 秤上 9.8kg → 跟 rB(应重10kg)最近
pick, note = ep._pick_by_weight([ra, rb, rc], 9.8)
check('秤 9.8kg 选中应重 10kg 的行', pick is not None and pick['id'] == 'rB', note)
# 秤 28kg → 跟 rC(应重30kg)最近
pick, note = ep._pick_by_weight([ra, rb, rc], 28.0)
check('秤 28kg 选中应重 30kg 的行', pick is not None and pick['id'] == 'rC', note)
# 秤 300kg → 跟谁都差太远(最近 rA 50kg 差 500%)→ 不猜
pick, note = ep._pick_by_weight([ra, rb, rc], 300.0)
check('差太远不猜(返回 None)', pick is None)
# 没配单件重量 → 算不出应重 → 不猜
ep2 = FakeConfirm()
pick, note = ep2._pick_by_weight([ra, rb, rc], 9.8)
check('没配单件重量不参与择行', pick is None)
# 斤行:应量 10 斤 = 5kg、4 斤 = 2kg;秤 2.1kg → 应选 4 斤那行
rj = mrow('rJ', '青笋', '斤', indep=False, qty=10.0)
rj2 = mrow('rK', '青笋', '斤', indep=False, qty=4.0)
pick, note = ep._pick_by_weight([rj, rj2], 2.1)
check('斤行按应量折 kg 比对', pick is not None and pick['id'] == 'rK', note)
# 关闭开关
ep3 = FakeConfirm()
ep3.cfg['flow']['weight_pick_pct'] = 0
pick, note = ep3._pick_by_weight([ra, rb, rc], 9.8)
check('weight_pick_pct=0 关闭择行', pick is None)
print()
print('通过 %d 项,失败 %d 项' % (ok, fail))
sys.exit(1 if fail else 0)