diff --git a/core/api/client.py b/core/api/client.py index 6812e9f..5fafbd4 100644 --- a/core/api/client.py +++ b/core/api/client.py @@ -160,6 +160,7 @@ class ApiClient: self.account = cfg.get('account', {}) self.base_url = self.cfg.get('base_url', '') self.mock = bool(self.cfg.get('mock')) + self._flow_cfg = cfg.get('flow', {}) or {} self.token = '' self.user_id = 'user-' + self.account.get('username', 'demo') self.account_name = '' # 登录后从 profile 拿(顶栏显示用) @@ -238,9 +239,79 @@ class ApiClient: name = '' if isinstance(r, dict): name = r.get('user_name') or '' + if (station != 'picking' and not self.mock + and bool(self._flow_cfg.get('group_inbound', True))): + grouped = self.pending_grouped(flat_rows=rows, timeout=timeout) + if grouped: + return {'rows': grouped['rows'], + 'config': grouped.get('config') or conf, + 'account_name': name or self.account_name} return {'rows': rows, 'config': conf, 'account_name': name or self.account_name} + # ------------------------------------------------ 分组入库(安卓同款) + def _preview_group_rows(self, grouped_data, flat_rows): + """把 pending-grouped 的组转换成终端统一的行结构。 + + 安卓端 pending-grouped 每组一条;Windows 现有 UI/匹配都按“行”工作, + 所以这里把组映射成一行:id 取首张待验单,inspection_ids 保存整组, + prepare_qty/required_qty 用组内合计,group_key/group_hash 随行带上。 + """ + flat_by_id = {str(r.get('id') or ''): r for r in (flat_rows or [])} + out = [] + for g in grouped_data or []: + if not isinstance(g, dict): + continue + ids = [str(x) for x in (g.get('inspection_ids') or []) if str(x or '').strip()] + if not ids: + continue + lines = g.get('lines') if isinstance(g.get('lines'), list) else [] + first_line = lines[0] if lines and isinstance(lines[0], dict) else {} + base = flat_by_id.get(ids[0]) or {} + row = dict(base) + row.update({ + 'id': ids[0], + 'inspection_ids': ids, + 'group_key': str(g.get('group_key') or ''), + 'group_hash': str(g.get('group_hash') or ''), + 'group_order_count': int(g.get('order_count') or 0), + 'order_code': first_line.get('order_code') or g.get('order_code') or '', + 'sku_code': g.get('sku_code') or base.get('sku_code'), + 'item_name': g.get('item_name') or base.get('item_name'), + 'unit': g.get('unit') or base.get('unit'), + 'supplier_code': g.get('supplier_code') or base.get('supplier_code'), + 'supplier_name': g.get('supplier_name') or base.get('supplier_name'), + 'source_type': g.get('source_type') or base.get('source_type'), + 'branch_code': g.get('branch_code') or base.get('branch_code'), + 'prepare_qty': g.get('total_prepare_qty'), + 'required_qty': g.get('total_prepare_qty'), + 'remaining_qty': g.get('total_prepare_qty'), + 'requires_photo_inspection': bool(g.get('requires_photo_inspection') or base.get('requires_photo_inspection')), + 'requires_photo': bool(g.get('requires_photo_inspection') or base.get('requires_photo')), + 'grouped_inbound': True, + 'group_lines': lines, + }) + # 独立入库在分组键里带 independent 段;服务端没回 processing_details 时靠它识别。 + gkey = str(g.get('group_key') or '').lower() + if (not row.get('processing_details')) and 'independent' in gkey: + row['processing_details'] = {'independent_inbound': True} + out.append(row) + return out + + def pending_grouped(self, flat_rows=None, timeout=None): + """拉同商品多订单聚合待办(仅入库站);失败返回 None,由调用方回退逐行。""" + try: + r = self._request('GET', '/mobile/inspection/weigh-station/pending-grouped', + timeout=timeout) + except Exception: + return None + data = r.get('data') if isinstance(r, dict) else r + groups = data if isinstance(data, list) else [] + rows = self._preview_group_rows(groups, flat_rows or []) + if not rows: + return None + return {'rows': rows, 'config': (r.get('config') or {}) if isinstance(r, dict) else {}} + # ------------------------------------------------ 识别(服务端通道,可选) def get_prompts(self, keys): """拉识别提示词**原文**(未渲染,占位符保留)。 @@ -375,6 +446,48 @@ class ApiClient: 'quality_rating': rating, 'force_complete': bool(force_complete)}) + def commit_inspection_group(self, row, qty, weight_kg, operation_id, + force_complete=False, quality_rating=None): + """同商品多订单整组入库(安卓 complete-merge-group 同款)。 + + 一次称重提交整组 inspection_ids;服务端按组内待验量 FIFO 分摊。 + 该接口没有 operation_id 幂等键,结果不明时只能查待办核实,绝不换号重提。 + """ + ids = [str(x) for x in (row.get('inspection_ids') or []) if str(x or '').strip()] + if not ids: + raise ApiError(-3, '缺少整组待验明细,本次未发送') + if self.mock: + return {'operation_status': 'committed_by_this_operation', + 'client_operation_id': operation_id, + 'data': {'merged': True, 'mergedCount': len(ids)}} + body = { + 'inspection_ids': ids, + 'actual_qty': round(float(qty or 0), 3), + 'quality_rating': (quality_rating or self.cfg.get('inspection_quality_rating') or '合格'), + 'loss_qty': 0, + } + group_key = str(row.get('group_key') or '').strip() + group_hash = str(row.get('group_hash') or '').strip() + if group_key: + body['group_key'] = group_key + if group_hash: + body['group_hash'] = group_hash + w = float(weight_kg or 0) + if w > 0: + body['actual_weight'] = round(w, 4) + if force_complete: + body['force_complete'] = True + r = self._request('POST', '/mobile/inspection/complete-merge-group', body=body) + data = r.get('data') if isinstance(r, dict) else None + if isinstance(r, dict) and r.get('success') is False: + raise ApiError(-5, '服务端未入账:%s' + % (r.get('error_description') or r.get('error') or r)) + # 统一成 _verify 认识的形态:本接口没有 operation_id,成功响应即本次入账。 + return {'operation_status': 'committed_by_this_operation', + 'client_operation_id': operation_id, + 'data': data if isinstance(data, dict) else {}, + 'group_hash': group_hash} + def commit_inspection_single(self, row, qty, weight_kg, operation_id): """无单自采行(independent_inbound)单行验收结案。 diff --git a/core/flow.py b/core/flow.py index 8f2b479..5d31cb6 100644 --- a/core/flow.py +++ b/core/flow.py @@ -1973,7 +1973,14 @@ class FlowEngine: resp = self.api.commit_picking(row, business, api_w, op, photo_expected) else: - if M.is_independent_inbound(row): + if self._is_group_inbound(row): + # 安卓同口径:整组一次提交,服务端按组内待验量 FIFO 分摊。 + # force=True 即偏差入库/短收结案;批量入库由服务端分摊完成。 + resp = self.api.commit_inspection_group( + row, business, self._frozen_kg, op, + force_complete=force, + quality_rating=(self.cfg.get('inspection_quality_rating') or '合格')) + elif M.is_independent_inbound(row): # 无单自采行(v1.0.44):单行结案接口,merge-strict 会拒 resp = self.api.commit_inspection_single( row, business, @@ -2040,6 +2047,14 @@ class FlowEngine: (self._frozen_row or {}).get('unit', '')) else 0.0) resp = self.api.commit_picking( self._frozen_row, qty, api_w, op, True) + elif self._is_group_inbound(self._frozen_row): + # 分组行:整组重发(连接没建立,服务端必然没收到) + force_retry, _, _ = self._short_close_gap( + self._frozen_row, qty) + resp = self.api.commit_inspection_group( + self._frozen_row, qty, self._frozen_kg, op, + force_complete=force_retry, + quality_rating=(self.cfg.get('inspection_quality_rating') or '合格')) elif M.is_independent_inbound(self._frozen_row): # 无单自采行:单行结案重试(连接没建立,服务端必然没收到) wkg = (float(getattr(self, '_count_real_kg', 0) or 0) @@ -2109,6 +2124,9 @@ class FlowEngine: if self.station == 'picking': self._recover_picking(op) return + if self._is_group_inbound(self._frozen_row or {}): + self._recover_group(op) + return if M.is_independent_inbound(self._frozen_row or {}): self._recover_indep(op) return @@ -2151,6 +2169,49 @@ class FlowEngine: return True return False + def _recover_group(self, op): + """分组提交结果不明:只查待验列表,绝不换号重提。 + + - 整组 ID 全部消失:服务端已收(含 partial/偏差结案); + - 整组 ID 都还在:服务端没收到,安全判未提交; + - 部分消失:不猜,锁定等人工。 + """ + row = self._frozen_row or {} + ids = {str(x) for x in (row.get('inspection_ids') or []) if str(x or '').strip()} + if not ids: + self.emit('log', '分组行缺少 inspection_ids,无法核实,锁定等人工') + self.emit('result', (False, '分组提交结果待核实(缺少明细),已锁定')) + self._to_done() + return + business = M.scale_kg_to_business(self._frozen_kg, row.get('unit', '')) + for i in range(3): + time.sleep(2) + try: + data = self.api.pending('inspection') + except Exception as e: + self.emit('log', '分组核实第 %d 次失败: %s' % (i + 1, e)) + continue + present = set() + for r in (data or {}).get('rows') or []: + present.update(str(x) for x in (r.get('inspection_ids') or [])) + if r.get('id'): + present.add(str(r.get('id'))) + if not (ids & present): + self.journal.conclude(op, STATE_SUCCEEDED) + self._after_success(row, business, op, + {'qualified': False}, '核实', + extra='|整组提交已核实') + return + if ids <= present: + self.journal.conclude(op, STATE_REJECTED, '整组提交未生效') + self.emit('result', (False, '整组提交未生效(待办仍在),请重试')) + self._to_done() + return + # 部分消失:可能服务端已部分入库,不能重提 + break + self.emit('result', (False, '整组提交结果不明,已锁定新提交,请联系管理员')) + self._set_state('DONE') + def _recover_indep(self, op): """无单自采行的结果不明核实:单行结案接口没有操作号可查, 只能看「待办里这行还在不在」—— 和分拣的核实思路一致。 @@ -2328,6 +2389,17 @@ class FlowEngine: 'unit': result.get('unit') or '', 'follow_ups': result.get('follow_up_inspection_ids') or []} + def _is_group_inbound(self, row): + """这一行是否是服务端 grouping 后的整组待验行(安卓 complete-merge-group 口径)。""" + if not isinstance(row, dict): + return False + ids = row.get('inspection_ids') + if not isinstance(ids, (list, tuple)) or len(ids) < 1: + return False + if not str(row.get('group_hash') or '').strip(): + return False + return bool((self.cfg.get('flow') or {}).get('group_inbound', True)) + def _short_close_gap(self, row, business): """短收是否在「直接结案」容差内 → (bool, 差额, 差额百分比) diff --git a/docs/20261110-windows-group-inbound.md b/docs/20261110-windows-group-inbound.md new file mode 100644 index 0000000..5f44de0 --- /dev/null +++ b/docs/20261110-windows-group-inbound.md @@ -0,0 +1,68 @@ +# Windows 入库:分组合并 + 批量 + 偏差(v1.0.66) + +日期:2026-11-10 +范围:`windows-fenjian`(入库分拣工作站) + +## 背景 + +安卓秤端已经走: + +```text +pending-grouped +→ 同商品/来源/单位一组 +→ 一次称重 +→ complete-merge-group +→ 服务端按组内待验量 FIFO 分摊 +``` + +Windows 之前是: + +```text +pending?mode=full +→ 同名多行时客户端 _split_plan 拆单 +→ 逐行 complete-merge-strict / complete +``` + +效果相似,但不是真正的分组批量提交;同名多行、多来源、批量/偏差场景容易与安卓不一致。 + +## 本次改动 + +1. `core/api/client.py` + - `pending('inspection')` 先拉逐行待办作为元数据,再拉 `pending-grouped`,把组转换成终端行: + - `id` = 首个待验 ID + - `inspection_ids` = 整组 ID + - `required_qty/prepare_qty` = 组内合计 + - `group_key/group_hash` 随行携带 + - 新增 `commit_inspection_group()`,对齐安卓 + `POST /mobile/inspection/complete-merge-group`: + - `inspection_ids`、`group_key`、`group_hash` + - `actual_qty`(一次称重总量) + - `actual_weight` + - `quality_rating`(中文) + - `force_complete`(偏差入库/短收结案) + - 分组接口失败/旧服务端 → 自动回退原逐行路径。 +2. `core/flow.py` + - 分组行优先走整组提交;`force_complete` 继续由短收容差逻辑 + `_short_close_gap()` 计算,保留偏差入库。 + - 网络未连接重试也走整组接口。 + - 结果不明 `_recover_group()`:按待验列表核对整组 ID; + 整组消失=成功,整组仍在=未提交,部分消失=锁定人工,绝不换号重提。 + - 未分组行保持原来的严格入库/独立入库逐行路径。 +3. `ui/app.py` 版本 `1.0.66`。 + +## 批量与偏差 + +- 批量入库:服务端一次称重按整组 FIFO 分摊,客户端不再逐单 `_split_plan`。 +- 偏差入库:分组提交同样支持 `force_complete=true`;库存按实收写, + 差额由服务端短少结案,不会虚增库存。 +- 有单/无单分组由服务端按来源区分;跨来源不再由客户端拼单。 + +## 回退 + +配置: + +```json +"flow": { "group_inbound": false } +``` + +关闭后恢复 Windows 原有逐行 `_split_plan`/严格提交路径。 diff --git a/tools/_test_group_inbound.py b/tools/_test_group_inbound.py new file mode 100644 index 0000000..e08a5d1 --- /dev/null +++ b/tools/_test_group_inbound.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +"""Windows 分组入库(v1.0.66):pending-grouped 行转换 + complete-merge-group 请求体。""" +import os +import sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +from core.api.client import ApiClient, ApiError + +CFG = {'server': {'base_url': 'http://127.0.0.1:3001/api', 'mock': False}, + 'account': {'username': 'demo', 'password': 'x', 'role': 'inspector'}, + 'flow': {'group_inbound': True}} + +def check(name, cond, detail=''): + print(('PASS' if cond else 'FAIL'), name, detail) + if not cond: + sys.exit(1) + +api = ApiClient(CFG) +groups = [{ + 'group_key': 'BR003|-|purchase|order|SKU1|斤', + 'group_hash': 'gh-1', + 'branch_code': 'BR003', + 'supplier_code': None, + 'source_type': 'purchase', + 'sku_code': 'SKU1', + 'item_name': '土豆', + 'unit': '斤', + 'total_prepare_qty': 55, + 'order_count': 2, + 'inspection_ids': ['ins-1', 'ins-2'], + 'requires_photo_inspection': False, + 'lines': [ + {'inspection_id': 'ins-1', 'order_code': 'O1', 'prepare_qty': 17}, + {'inspection_id': 'ins-2', 'order_code': 'O2', 'prepare_qty': 38}, + ], +}] +flat = [{'id': 'ins-1', 'order_code': 'O1', 'customer_name': '客户A', + 'prepare_qty': 17, 'unit': '斤', 'requires_photo_inspection': False}, + {'id': 'ins-2', 'order_code': 'O2', 'customer_name': '客户B', + 'prepare_qty': 38, 'unit': '斤', 'requires_photo_inspection': False}] +rows = api._preview_group_rows(groups, flat) +check('一组转成一行', len(rows) == 1, str(rows)) +row = rows[0] +check('保存整组ID', row.get('inspection_ids') == ['ins-1', 'ins-2']) +check('组总量作为应量', row.get('required_qty') == 55 and row.get('prepare_qty') == 55) +check('组键/哈希带到行', row.get('group_key') and row.get('group_hash') == 'gh-1') +check('首行订单号/客户元数据保留', row.get('order_code') == 'O1' and row.get('customer_name') == '客户A') +check('组行标记', row.get('grouped_inbound') is True) + +# mock request capture +calls = [] +def fake_request(method, path, body=None, **kw): + calls.append((method, path, body)) + return {'success': True, 'data': {'merged': True, 'mergedCount': 2}} +api._request = fake_request +resp = api.commit_inspection_group(row, 55, 27.5, 'op-1', force_complete=True) +check('走分组接口', calls and calls[0][1] == '/mobile/inspection/complete-merge-group', str(calls)) +body = calls[0][2] +check('整组ID在请求体', body.get('inspection_ids') == ['ins-1', 'ins-2']) +check('批量实收一次传', body.get('actual_qty') == 55) +check('偏差入库 force_complete 透传', body.get('force_complete') is True) +check('质量中文', body.get('quality_rating') == '合格') +check('回包归一成功', resp.get('operation_status') == 'committed_by_this_operation') +print('ALL GROUP INBOUND CHECKS PASSED') diff --git a/ui/app.py b/ui/app.py index 0ea847a..14a8d3f 100644 --- a/ui/app.py +++ b/ui/app.py @@ -39,7 +39,7 @@ class _BoolVar: self._sw.set(v) -APP_VERSION = '1.0.64' +APP_VERSION = '1.0.66' FONT_BIG = ('Microsoft YaHei', 14) FONT_HUGE = ('Microsoft YaHei', 38, 'bold')