# -*- coding: utf-8 -*- """服务端 API 客户端(与安卓版同一套接口)。 网络失败分类(对齐 ApiClient.failureCode): CODE_NETWORK_FAILURE = -1 连接未建立(DNS/Connect/路由/connect 超时)→ 服务端必然没收到,可安全重试 CODE_RESULT_UNKNOWN = -2 已发出但无响应(读超时/流中断/5xx/408)→ 结果不明,只查不重发 其他 HTTP 状态码 → 明确业务拒绝 mock=True 时用内置数据离线跑通全流程(P1/P2 验收用),接口签名与真实模式一致。 """ import hashlib import os import time import uuid import requests CODE_NETWORK_FAILURE = -1 CODE_RESULT_UNKNOWN = -2 _CONNECT_EXC = (requests.exceptions.ConnectionError, requests.exceptions.ConnectTimeout, requests.exceptions.Timeout,) class ApiError(Exception): def __init__(self, code, message, status=None): super().__init__(message) self.code = code # -1 / -2 / HTTP 状态 self.message = message self.status = status def new_operation_id(): return 'op-' + uuid.uuid4().hex[:24] def _iso_ms(epoch_sec): """与安卓 PickingPhotoContract.iso 同格式:2026-11-03T19:30:00.000+08:00""" t = time.localtime(epoch_sec) off = -(time.altzone if t.tm_isdst > 0 else time.timezone) sign = '+' if off >= 0 else '-' off = abs(int(off)) return '%s.%03d%s%02d:%02d' % ( time.strftime('%Y-%m-%dT%H:%M:%S', t), int((epoch_sec - int(epoch_sec)) * 1000), sign, off // 3600, (off % 3600) // 60) def _check_photo_ack(body, target_id, operation_id, client_photo_id): """按契约校验分拣照片回执(对齐 PickingPhotoApi.handleUploadResponse)。 只有 success=true + data.status='archived' + attachment_id 非空 (且回显一致)才算真的归档;否则抛错,让调用方重试或落队列, 绝不能像以前那样「HTTP 200 就记一句已上传」——那样服务端其实没收到。 """ root = body if isinstance(body, dict) else {} data = root.get('data') if not isinstance(data, dict): data = root success = bool(root.get('success', data.get('success', False))) if not success: raise ApiError(CODE_RESULT_UNKNOWN, '照片未确认成功:%s' % (root.get('message') or data.get('message') or 'success=false')) status = str(data.get('status') or '').strip().lower() if status != 'archived': raise ApiError(CODE_RESULT_UNKNOWN, '照片未归档(status=%s)' % (status or '缺失')) att = str(data.get('attachment_id') or data.get('attachmentId') or '').strip() if not att: raise ApiError(CODE_RESULT_UNKNOWN, '照片回执缺少 attachment_id') item = str(data.get('pick_item_id') or data.get('picking_item_id') or '').strip() if item and item != str(target_id): raise ApiError(409, '照片回显明细不一致:%s' % item) op_echo = str(data.get('client_operation_id') or '').strip() if op_echo and op_echo != str(operation_id): raise ApiError(409, '照片回显操作号不一致:%s' % op_echo) ph_echo = str(data.get('client_photo_id') or '').strip() if ph_echo and ph_echo != str(client_photo_id): raise ApiError(409, '照片回显照片号不一致:%s' % ph_echo) return body # ---------------------------------------------------------------- mock 数据 _MOCK_ROWS_PICKING = [ {'id': 'pk-001', 'order_code': 'D1129', 'sort_order': 1, 'sku_code': 'SKU1027', 'item_name': '马铃薯', 'spec': '散装', 'customer_name': '食堂一组', 'unit': '斤', 'required_qty': 5.0, 'requires_photo': False}, {'id': 'pk-002', 'order_code': 'D1131', 'sort_order': 2, 'sku_code': 'SKU1036', 'item_name': '水果黄瓜', 'spec': '散装', 'customer_name': '食堂二组', 'unit': '斤', 'required_qty': 4.0, 'requires_photo': False}, {'id': 'pk-003', 'order_code': 'D1142', 'sort_order': 3, 'sku_code': 'SKU1035', 'item_name': '旱黄瓜', 'spec': '散装', 'customer_name': '三号窗口', 'unit': '斤', 'required_qty': 2.0, 'requires_photo': False}, {'id': 'pk-004', 'order_code': 'D1143', 'sort_order': 4, 'sku_code': 'SKU1051', 'item_name': '红富士苹果', 'spec': '80#', 'customer_name': '水果组', 'unit': '斤', 'required_qty': 10.0, 'requires_photo': False}, ] _MOCK_ROWS_INSPECTION = [ {'id': 'ins-001', 'order_code': 'R2201', 'sort_order': 1, 'sku_code': 'SKU1027', 'item_name': '马铃薯', 'spec': '散装', 'supplier': '兴达蔬菜', 'unit': '斤', 'prepare_qty': 50.0, 'requires_photo_inspection': False}, {'id': 'ins-002', 'order_code': 'R2202', 'sort_order': 2, 'sku_code': 'SKU1051', 'item_name': '红富士苹果', 'spec': '80#', 'supplier': '红果贸易', 'unit': '斤', 'prepare_qty': 100.0, 'requires_photo_inspection': False}, ] _MOCK_CONFIG = { 'weigh_match_tolerance_mode': 'percent', 'weigh_match_tolerance_value': 10, 'picking_label_print_enabled': True, 'inbound_label_print_enabled': False, } # 离线演示的待办数据外置:现场想换商品/客户直接改 data/mock_rows.json, # 不用重新打包。文件不存在或格式不对就回退上面内置的几条。 MOCK_ROWS_FILE = 'data/mock_rows.json' def _mock_rows_file(station): """读 data/mock_rows.json({'picking': [...], 'inspection': [...]}) 只做最必要的校验(是列表、每行有 id 和 item_name),坏行跳过 —— 演示数据是手改的,格式错一个逗号不该让整个界面起不来。 """ if not os.path.isfile(MOCK_ROWS_FILE): return None try: import json with open(MOCK_ROWS_FILE, encoding='utf-8') as f: data = json.load(f) except Exception: return None rows = data.get(station) if isinstance(data, dict) else data if not isinstance(rows, list): return None out = [] for i, r in enumerate(rows): if not isinstance(r, dict) or not r.get('item_name'): continue r = dict(r) r.setdefault('id', 'mock-%s-%03d' % (station, i + 1)) r.setdefault('unit', '斤') r.setdefault('spec', '散装') out.append(r) return out or None class ApiClient: def __init__(self, cfg): self.cfg = cfg.get('server', {}) 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 拿(顶栏显示用) # 登录后从 profile.branch_code 拿:送审回执要核对自己落在哪个分公司, # 换分公司却没换号会把不同公司的照片混进同一个训练库 self.review_branch = '' # 账号开关 profiles.inbound_auto_submit:默认关(入库必须手动点确认); # 仅 mock/演示时回退到本地 config(flow.inbound_auto_submit,默认 True) self.inbound_auto_submit = bool(self._flow_cfg.get('inbound_auto_submit', True)) self._session = requests.Session() # 禁用系统代理,直连服务器(避免HTTP代理无法处理HTTPS) self._session.trust_env = False self._mock_committed = set() # ------------------------------------------------ 登录/待办 def login(self): if self.mock: self.token = 'mock-token-' + self.user_id self.inbound_auto_submit = bool( self._flow_cfg.get('inbound_auto_submit', True)) return {'user_id': self.user_id, 'role': self.account.get('role')} # role_type 服务端取 picker / inspector(与安卓端一致); # 兼容旧配置里误写成 picking / inspection 的情况 role = str(self.account.get('role') or '').strip() role = {'picking': 'picker', 'inspection': 'inspector'}.get(role, role) try: r = self._request('POST', '/mobile/login', body={ 'username': self.account.get('username'), 'password': self.account.get('password'), 'role_type': role}) except ApiError as e: # 登录页要给现场看得懂的话 if e.code in (401, 403): raise ApiError(e.code, '账号或密码错误,或该账号没有此工位权限') if e.code == CODE_NETWORK_FAILURE: raise ApiError(e.code, '连不上服务器,请检查网络与服务器地址') if e.code == CODE_RESULT_UNKNOWN: raise ApiError(e.code, '服务器无响应,请稍后重试') raise # 真实服务端返回的是 OAuth2 风格:access_token + token_type=bearer, # 没有 token 字段;两者都兼容,否则 token 为空 → 后续接口 401 self.token = (r.get('access_token') or r.get('token') or '').strip() if not self.token: raise ApiError(-4, '登录成功但服务端没返回访问令牌' '(access_token),请联系管理员') # 顶栏要显示的名字:真实服务端放在 profile 里,也兼容直接给 user_name prof = r.get('profile') or {} self.account_name = (r.get('user_name') or prof.get('full_name') or prof.get('username') or '').strip() # 2026-11-29:账号级「入库自动提交」开关(服务端 profiles.inbound_auto_submit) # 缺省/旧服务端/未下发 ⇒ False ⇒ 入库必须手动点「确认记账」 self.inbound_auto_submit = bool(prof.get('inbound_auto_submit')) self.user_id = prof.get('id') or self.user_id self.review_branch = str(prof.get('branch_code') or '').strip() return r def pending(self, station, timeout=None): """拉待办(timeout 可传,后台轮询用短超时:服务端卡住别拖死主循环)""" if self.mock: rows = _mock_rows_file(station) if rows is None: rows = list(_MOCK_ROWS_PICKING if station == 'picking' else _MOCK_ROWS_INSPECTION) else: rows = list(rows) if station == 'picking': rows = [r for r in rows if r['id'] not in self._mock_committed] cfg = dict(_MOCK_CONFIG) return {'rows': rows, 'config': cfg, 'account_name': self.account.get('username', 'demo')} path = ('/mobile/picking/weigh-station/pending?mode=full' if station == 'picking' else '/mobile/inspection/weigh-station/pending?mode=full') r = self._request('GET', path, timeout=timeout) # 真实服务端是扁平结构 {"data": [行...], "config": {...}, "tasks": [...]}; # 老版本/部分环境是 {"data": {"rows": [...], "config": {...}}},两种都吃 data = r.get('data') if isinstance(r, dict) else r if isinstance(data, list): rows = data conf = (r.get('config') or {}) if isinstance(r, dict) else {} elif isinstance(data, dict): rows = data.get('rows') or data.get('items') or [] conf = (data.get('config') or (r.get('config') if isinstance(r, dict) else None) or {}) else: rows, conf = [], {} 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, }) # 组内可能同时有「独立入库·加工原材料」和普通订单行:把两边的量 # 算出来挂在行上,卡片才能分开显示(以前只挂一个“独立入库”标签, # 32 斤看着像全是原料)。 try: from core.matching.engine import is_independent_inbound except Exception: # noqa: BLE001 def is_independent_inbound(_r): # type: ignore return False parts = {} for i in ids: fr = flat_by_id.get(i) or {} kind = ('independent' if is_independent_inbound(fr) else 'normal') try: q = float(fr.get('remaining_qty') or fr.get('required_qty') or fr.get('prepare_qty') or 0) except (TypeError, ValueError): q = 0.0 p = parts.setdefault(kind, {'kind': kind, 'qty': 0.0, 'rows': 0}) p['qty'] += q p['rows'] += 1 if parts: row['group_parts'] = [parts[k] for k in ('independent', 'normal') if k in parts] # 独立入库在分组键里带 independent 段;服务端没回 processing_details # 时靠它识别。但组里混有普通订单行时不能把整组标成独立入库。 gkey = str(g.get('group_key') or '').lower() only_indep = bool(parts) and all( p['kind'] == 'independent' for p in parts.values()) mixed = bool(parts) and not only_indep if mixed: # 组里混有普通订单行:整组不能当“独立入库”去走单行结案。 # 标记是从首行(flat base)继承过来的,得清掉。 pd = row.get('processing_details') if isinstance(pd, dict): pd = dict(pd) pd['independent_inbound'] = False row['processing_details'] = pd else: row.pop('processing_details', None) row.pop('independent_inbound', None) elif (not row.get('processing_details')) and 'independent' in gkey \ and (only_indep or not parts): 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): """拉识别提示词**原文**(未渲染,占位符保留)。 服务端只开放 weigh.recognize.* 前缀;返回 {'items': [{feature_key, system_template, version, source}], 'branch_code'} 端上拿模板自己塞名单,再直连豆包 —— 提示词改在后台,不用重打包。 """ if self.mock: return {'items': [], 'branch_code': None} q = requests.utils.quote(','.join(str(k) for k in keys), safe=',') r = self._request('GET', '/mobile/ai-prompts?keys=' + q) data = r.get('data') if isinstance(r, dict) else None if not isinstance(data, dict): data = r if isinstance(r, dict) else {} items = data.get('items') return {'items': items if isinstance(items, list) else [], 'branch_code': data.get('branch_code')} def recognize(self, station, image_b64, rows): """服务端多模态识别(限名单)。mock 模式本地不调用。""" if self.mock: return {'name': None} path = ('/mobile/picking/weigh-station/recognize' if station == 'picking' else '/mobile/inspection/weigh-station/recognize') return self._request('POST', path, body={ 'image_base64': image_b64, 'names': [r.get('item_name') for r in rows]}) # ------------------------------------------------ 提交 def commit_picking(self, row, qty, weight, operation_id, photo_expected): if self.mock: self._mock_committed.add(row['id']) # 模拟服务端也返回容器码:标签二维码只认这个字段, # 不返回的话演示模式永远打不出可扫的标签。 code = str(row.get('container_code') or row.get('pick_code') or row['id']) return {'operation_status': 'committed_by_this_operation', 'client_operation_id': operation_id, 'pick_item_id': row['id'], 'container_code': 'CT-' + code} # 服务端 commit 必带 pick_code(安卓 WeighStationApi.commit 一直传): # 只传 pick_item_id 时实测回 400「缺少拣货明细」——分拣一单都提交不了。 pick_code = str(row.get('pick_code') or '').strip() if not pick_code: raise ApiError(-3, '待拣行缺少拣货单号(pick_code),本次未发送') body = {'client_operation_id': operation_id, 'pick_item_id': row['id'], 'pick_code': pick_code, 'picked_qty': qty, 'picked_weight': weight, 'photo_expected': bool(photo_expected)} unit = str(row.get('unit') or '').strip() if unit: body['unit'] = unit return self._request('POST', '/mobile/picking/weigh-station/commit', body=body) def picking_pending_has(self, target_id): """分拣这行还在不在待拣列表里。 分拣没有 commit-status 接口(实测 GET .../commit-status 返回 404), 安卓端同样只靠待拣列表判断:行消失 = 只解除本机锁,不当作提交成功。 返回 True/False;拉不到列表返回 None(调用方按“无结论”处理)。 """ if self.mock: return str(target_id) not in self._mock_committed try: data = self.pending('picking') except Exception: return None ids = {str(r.get('id')) for r in (data.get('rows') or [])} return str(target_id) in ids def preview_merge_scope(self, inspection_id, inspection_ids): """严格入库第一步:范围预览,换取一次性 scope_token。 请求 { "id": 选中待验ID, "inspection_ids": [纳入本次范围的待验ID] } 返回 data{ strict_capable, strict_write_enabled, scope_token, expires_at, selected_ids, lines, total_qty, unit, ... } 服务端未声明严格能力 / 未给凭据 → ApiError(-5),绝不带着空凭据去提交。 """ if self.mock: return {'scope_token': 'mock-scope-token', 'strict_write_enabled': True} r = self._request('POST', '/mobile/inspection/merge-scope-preview', body={'id': inspection_id, 'inspection_ids': list(inspection_ids)}) data = r.get('data') if isinstance(r, dict) else None if not isinstance(data, dict): data = r if isinstance(r, dict) else {} if not data.get('strict_capable'): raise ApiError(-5, '服务端未开启严格入库能力' '(strict_capable=false),无法提交') token = str(data.get('scope_token') or '').strip() if not token: raise ApiError(-5, '服务端未返回范围凭据(scope_token),未发送') if not data.get('strict_write_enabled', True): # 不是网络/数据问题,是服务端把这台机器的「严格入库写入」关了。 # 客户端不发(发了也写不进去,还会留下未决提交);把处置动作写清楚, # 免得现场以为是自己操作错了。 raise ApiError(-5, '服务端严格写入开关未开启' '(strict_write_enabled=false),本次未提交;' '请管理员在服务端开启「严格入库写入」后重试') return {'scope_token': token, 'strict_write_enabled': True, 'expires_at': data.get('expires_at') or '', # 供提交前核对:服务端确认的本次范围与明细(缺失则不做校验) 'selected_ids': [str(x) for x in (data.get('selected_ids') or [])], 'lines': data.get('lines') or [], 'total_qty': data.get('total_qty'), 'unit': str(data.get('unit') or '')} def commit_inspection(self, rows, qty, weight, operation_id, scope_token=None, quality_rating=None, force_complete=False): if self.mock: return {'operation_status': 'committed_by_this_operation', 'client_operation_id': operation_id} # 严格提交:先拿范围凭据,没有凭据绝不发送(绝不回退旧接口) if not scope_token: raise ApiError(-3, '缺少收货范围核验凭据,未发送') # quality_rating 必须是中文「合格 / 不合格」——安卓端 buildBody 传的就是 # InspectionWeighActivity 的中文字面值;传英文 qualified 服务端会当没传, # 回 400 inspection_rating_required「请选择验收结果(合格/不合格)」。 rating = (quality_rating or self.cfg.get('inspection_quality_rating') or '合格') # 请求体与安卓 buildStrictBody 对齐(范围由凭据锁定,不再传 ids) body = { 'operation_id': operation_id, 'scope_token': scope_token, 'actual_qty': qty, 'actual_weight': weight, 'quality_rating': rating, 'force_complete': bool(force_complete), } # complete-merge-strict 端点只解析 force_complete,不支持原料批次结案; # 独立原料永远走 complete-merge-group 或 /inspection/complete 单行路径。 return self._request( 'POST', '/mobile/inspection/complete-merge-strict', body=body) def commit_inspection_group(self, row, qty, weight_kg, operation_id, force_complete=False, quality_rating=None, force_close_raw_batch=False): """同商品多订单整组入库(安卓 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 # 偏差入库/短收结案:强制结束独立原料采购批次,服务端不再派生续验单。 # 普通整组入库不传该字段,行为与旧版一致。 if force_close_raw_batch: body['force_close_raw_batch'] = 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,成功响应即本次入账。 # 短收部分成功(2026-11-22 方案 A,见 docs/design/20261122-weigh-group-partial-inbound.md): # 后端 200 + partialGroup/remainingQty(已入 N 行、剩余行继续待验),这里把关键字段带出来 # 供 UI 提示「下次再称」,并提示不要拿旧组重试。 d = data if isinstance(data, dict) else {} return {'operation_status': 'committed_by_this_operation', 'client_operation_id': operation_id, 'data': d, 'group_hash': group_hash, 'partial_group': bool(d.get('partialGroup')), 'merged_count': d.get('mergedCount'), 'remaining_qty': d.get('remainingQty'), 'unallocated_lines': d.get('unallocatedLines') or []} def commit_inspection_single(self, row, qty, weight_kg, operation_id, force_complete=False, force_close_raw_batch=False): """无单自采行(independent_inbound)单行验收结案。 为什么单独一个方法:这类行(后台「新增自采商品/加单独立入库」建的 待验单,processing_details.independent_inbound=true、无订单收货链) 拿去调 complete-merge-strict / merge-scope-preview,服务端一律 400 independent_inbound_not_mergeable「独立入库没有订单收货链」。 服务端给它们准备的是单行结案接口 /mobile/inspection/complete, 安卓称重端(InspectionApi.complete)走的就是它。 请求体与安卓对齐: id / actual_qty(行单位数量,件行就是件数)/ actual_weight(秤读数, 斤口径,>0 才发)/ quality_rating(中文「合格」)/ loss_qty=0 / unit / purchase_price(行上登记价,>0 才发) 幂等性:这个接口没有操作号/幂等键,所以**结果不明时绝不自动重发**, 由 flow._recover 走「查待办列表」核实(该行还在 = 没收到,安全)。 服务端对独立行的特殊规则(inspectionComplianceService): - actual_qty 必须 > 0(「独立入库请先称重再入库」); - 不拆 partial(isPartialInbound 排除独立行),有量即整行结案; - 成本价:请求没带就用行上登记价,登记价也没有且未开零成本开关 → 400 invalid_cost「成本价须大于 0」。 """ if self.mock: return {'operation_status': 'committed_by_this_operation', 'client_operation_id': operation_id, 'data': {'result': {'effect': 'independent_inbound'}}} rating = (self.cfg.get('inspection_quality_rating') or '合格') body = {'id': str(row.get('id') or ''), 'actual_qty': round(float(qty or 0), 3), 'quality_rating': rating, 'loss_qty': 0} if force_complete: body['force_complete'] = True if force_close_raw_batch: body['force_close_raw_batch'] = True w = float(weight_kg or 0) if w > 0: # 秤读数记斤(与安卓端一致:kg×2);只作留档参考,不参与记账 body['actual_weight'] = round(w * 2.0, 3) unit = str(row.get('unit') or '').strip() if unit: body['unit'] = unit try: price = float(row.get('purchase_price') or 0) except (TypeError, ValueError): price = 0.0 if price > 0: body['purchase_price'] = round(price, 4) r = self._request('POST', '/mobile/inspection/complete', body=body) # 归一化成 _verify 认识的形态:单行结案是同步接口,success=true 即 # 本请求已入账(没有 operation_status/operation_id 回显)。 if isinstance(r, dict) and r.get('success') is False: raise ApiError(-5, '服务端未入账:%s' % (r.get('error_description') or r.get('error') or r)) return {'operation_status': 'committed_by_this_operation', 'client_operation_id': operation_id, 'raw': r} def stock_in(self, sku_code, qty, unit, unit_cost=0.0, production_date=None, remark='', image_b64=None): """独立入库(无单):POST /mobile/inventory/stock-in,按 SKU 直接进库存。 与安卓 InventoryInboundApi.stockIn 同一份请求体: sku_code / qty / unit / unit_cost(必填)、production_date、 remark、image_base64(可选) 这个接口**没有幂等键**:任何自动重试都可能把同一批货入两次库存。 所以失败一律按「结果不明」处理(只核实、不重发),由调用方决定 什么时候能继续 —— 与安卓端 postStrict 的策略一致。 """ sku = str(sku_code or '').strip() if not sku: raise ApiError(-3, '这一行没有 SKU 编码,不能走独立入库') if self.mock: return {'stock_in': True, 'sku_code': sku, 'qty': float(qty or 0), 'unit': unit or ''} body = {'sku_code': sku, 'qty': round(float(qty or 0), 3), 'unit': str(unit or '').strip() or '斤', 'unit_cost': round(float(unit_cost or 0), 4)} if production_date: body['production_date'] = str(production_date) if remark: body['remark'] = str(remark)[:200] if image_b64: body['image_base64'] = image_b64 return self._request('POST', '/mobile/inventory/stock-in', body=body) def query_operation(self, operation_id, station): """按原操作号核实(结果不明时只查不重发)""" if self.mock: return {'operation_status': 'committed_by_this_operation', 'client_operation_id': operation_id} path = ('/mobile/picking/weigh-station/commit-status?operation_id=' if station == 'picking' else '/mobile/inspection/merge-operation/') + operation_id return self._request('GET', path) def upload_photo(self, station, target_id, operation_id, client_photo_id, path, captured_at=None): if self.mock: return {'success': True, 'data': {'status': 'archived', 'attachment_id': 'mock-att', 'pick_item_id': target_id, 'client_operation_id': operation_id, 'client_photo_id': client_photo_id}} with open(path, 'rb') as f: data = f.read() if station == 'inspection': # 入库验收照片:与安卓 InspectionApi.uploadPhoto 一致—— # JSON {id, content(base64), ext},不是 multipart。 # 服务端在严格提交前会校验「这行有没有照片」,没传就 400 # inspection_photo_required「请先拍照验收」。 import base64 return self._request( 'POST', '/mobile/inspection/photo', body={'id': target_id, 'content': base64.b64encode(data).decode('ascii'), 'ext': 'jpg'}) # 分拣照片:契约 POST /mobile/picking/weigh-station/photo(multipart), # 字段 photo / pick_item_id / client_operation_id / client_photo_id / captured_at。 # 只有 success=true + data.status=archived + attachment_id 非空才算传成功, # 光看 HTTP 200 会把「服务端没归档」当成成功(照片就永远缺了)。 files = {'photo': ('photo.jpg', data, 'image/jpeg')} fields = {'pick_item_id': str(target_id), 'client_operation_id': str(operation_id), 'client_photo_id': str(client_photo_id)} if captured_at: fields['captured_at'] = _iso_ms(captured_at) url = self.base_url.rstrip('/') + '/mobile/picking/weigh-station/photo' try: r = self._session.post(url, files=files, data=fields, headers=self._auth(), timeout=(3, 90)) except _CONNECT_EXC: raise ApiError(CODE_NETWORK_FAILURE, '照片上传连接失败') except requests.exceptions.RequestException as e: raise ApiError(CODE_RESULT_UNKNOWN, '照片上传中断: %s' % e) if r.status_code in (401, 403): raise ApiError(CODE_RESULT_UNKNOWN, '照片上传暂停(HTTP %d,登录/权限问题)' % r.status_code) if r.status_code >= 500 or r.status_code == 408: raise ApiError(CODE_RESULT_UNKNOWN, '照片上传服务端 %d(可重试)' % r.status_code) if r.status_code == 409: # photo_conflict:同一照片号已有不同内容,不覆盖也不换号绕过 raise ApiError(409, '照片冲突(同一照片号已有不同内容)') if r.status_code >= 400: # 剩余 4xx 是明确拒绝,重传也没用,保留本地照片交人工 raise ApiError(r.status_code, '照片被拒绝 %d: %s' % (r.status_code, r.text[:120])) try: body = r.json() except ValueError: raise ApiError(CODE_RESULT_UNKNOWN, '照片上传响应解析失败') return _check_photo_ack(body, target_id, operation_id, client_photo_id) def upload_review_sample(self, fields, image): """把入库照片送后台「识别样本」待审核(数据飞轮第二步)。 契约:POST /mobile/recognition/samples(multipart),字段 image + 业务字段。 幂等靠 sample_id / event_id(都填操作号):同号同图服务端回 duplicate。 失败分类沿用 _request 的规矩,只是这里自己发 multipart: -1 连接未建立 → 可安全重试;-2 已发出无响应 → 也重试(同号同图不产生第二条); 4xx → 明确拒绝(数据本身有问题),交人工。 """ if self.mock: return {'sample_id': fields.get('sample_id'), 'image_sha256': fields.get('image_sha256', ''), 'event_id': fields.get('event_id'), 'duplicate': False} url = self.base_url.rstrip('/') + '/mobile/recognition/samples' files = {'image': ('scale.jpg', image, 'image/jpeg')} try: r = self._session.post(url, files=files, data=fields, headers=self._auth(), timeout=(3, 45), allow_redirects=False) except (requests.exceptions.ConnectionError, requests.exceptions.ConnectTimeout): raise ApiError(CODE_NETWORK_FAILURE, '识别样本连接失败') except requests.exceptions.RequestException as e: raise ApiError(CODE_RESULT_UNKNOWN, '识别样本上传中断: %s' % e) if r.status_code in (401, 403): raise ApiError(r.status_code, '识别样本被拒绝(登录/权限,%d)' % r.status_code) if r.status_code >= 500 or r.status_code == 408: raise ApiError(CODE_RESULT_UNKNOWN, '识别样本服务端 %d' % r.status_code) if r.status_code >= 400: raise ApiError(r.status_code, '识别样本被拒绝 %d: %s' % (r.status_code, r.text[:160])) try: body = r.json() except ValueError: raise ApiError(CODE_RESULT_UNKNOWN, '识别样本回执解析失败') data = body.get('data') if isinstance(body, dict) else None if not isinstance(data, dict) or not data.get('sample_id'): raise ApiError(CODE_RESULT_UNKNOWN, '识别样本回执缺样本号') return data def cls_model_manifest(self): """问服务端要本地识别模型(YOLO-cls)的当前版本清单。 契约:GET /mobile/weigh/cls-model/manifest 200 → data{version, created_at, imgsz, class_count, notes, files:[{name, sha256, size, url}]} 404 → 服务器还没发布模型(返回 None,不算错误) 除 404 外的非 200、或回执字段不可用,一律抛 ApiError:交给 ModelSync 记一行日志、保持现有版本 —— 拿不准的时候绝不动本地模型文件。 """ if self.mock: return None url = self.base_url.rstrip('/') + '/mobile/weigh/cls-model/manifest' try: r = self._session.get(url, headers=self._auth(), timeout=(3, 10), allow_redirects=False) except (requests.exceptions.ConnectionError, requests.exceptions.ConnectTimeout): raise ApiError(CODE_NETWORK_FAILURE, '模型清单连接失败') except requests.exceptions.RequestException as e: raise ApiError(CODE_RESULT_UNKNOWN, '模型清单请求中断: %s' % e) if r.status_code == 404: return None if r.status_code in (401, 403): raise ApiError(r.status_code, '模型清单被拒绝(登录/权限,%d)' % r.status_code) if r.status_code >= 400: raise ApiError(CODE_RESULT_UNKNOWN, '模型清单不可用(%d)' % r.status_code) try: body = r.json() except ValueError: raise ApiError(CODE_RESULT_UNKNOWN, '模型清单解析失败') data = body.get('data') if isinstance(body, dict) else None return data if isinstance(data, dict) else None def download_cls_model_file(self, name, dest_path, sha256='', size=0, timeout=None): """把一个模型文件流式写到 dest_path,并按 sha256/大小校验。 先写 `.part`、验过才 `os.replace`:半个 onnx 比没有 onnx 更坏 —— cv2 读得进来、推理结果却全是错的,而且不会报任何错。 """ if self.mock: raise ApiError(CODE_RESULT_UNKNOWN, 'mock 模式不下载模型') url = (self.base_url.rstrip('/') + '/mobile/weigh/cls-model/file/' + str(name)) tmp = dest_path + '.part' digest = hashlib.sha256() got = 0 try: try: r = self._session.get(url, headers=self._auth(), timeout=timeout or (5, 180), stream=True, allow_redirects=False) except (requests.exceptions.ConnectionError, requests.exceptions.ConnectTimeout): raise ApiError(CODE_NETWORK_FAILURE, '模型下载连接失败') except requests.exceptions.RequestException as e: raise ApiError(CODE_RESULT_UNKNOWN, '模型下载中断: %s' % e) if r.status_code != 200: raise ApiError(r.status_code if r.status_code >= 400 else CODE_RESULT_UNKNOWN, '模型下载被拒绝 %d' % r.status_code) with open(tmp, 'wb') as f: try: for chunk in r.iter_content(1 << 16): if not chunk: continue f.write(chunk) digest.update(chunk) got += len(chunk) except requests.exceptions.RequestException as e: raise ApiError(CODE_RESULT_UNKNOWN, '模型下载中断: %s' % e) f.flush() os.fsync(f.fileno()) if size and got != int(size): raise ApiError(CODE_RESULT_UNKNOWN, '模型大小不符(%d/%d)' % (got, int(size))) hex_digest = digest.hexdigest() if sha256 and hex_digest.lower() != str(sha256).strip().lower(): raise ApiError(CODE_RESULT_UNKNOWN, '模型 sha256 不符(%s…)' % hex_digest[:12]) os.replace(tmp, dest_path) return {'bytes': got, 'sha256': hex_digest} finally: if os.path.exists(tmp): try: os.remove(tmp) except OSError: pass # ------------------------------------------------ 内部 def _auth(self): h = {} if self.token: h['Authorization'] = 'Bearer ' + self.token return h def _request(self, method, path, body=None, timeout=None): url = self.base_url.rstrip('/') + path try: r = self._session.request( method, url, json=body, headers=self._auth(), # 禁用自动重发(结果不明只查不重发) timeout=timeout or (3, 10), allow_redirects=False) except (requests.exceptions.ConnectionError, requests.exceptions.ConnectTimeout): raise ApiError(CODE_NETWORK_FAILURE, '连接未建立') except (requests.exceptions.ReadTimeout, requests.exceptions.Timeout): raise ApiError(CODE_RESULT_UNKNOWN, '已发出但无响应(读超时)') except requests.exceptions.RequestException as e: raise ApiError(CODE_RESULT_UNKNOWN, '请求中断: %s' % e) if r.status_code >= 500 or r.status_code == 408: raise ApiError(CODE_RESULT_UNKNOWN, '服务端 %d' % r.status_code) if r.status_code >= 400: raise ApiError(r.status_code, '业务拒绝 %d: %s' % (r.status_code, r.text[:120])) return r.json()