# -*- 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 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.token = '' self.user_id = 'user-' + self.account.get('username', 'demo') self.account_name = '' # 登录后从 profile 拿(顶栏显示用) 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 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() self.user_id = prof.get('id') or self.user_id 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 '' return {'rows': rows, 'config': conf, 'account_name': name or self.account_name} # ------------------------------------------------ 识别(服务端通道,可选) 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) return self._request( 'POST', '/mobile/inspection/complete-merge-strict', body={ 'operation_id': operation_id, 'scope_token': scope_token, 'actual_qty': qty, 'actual_weight': weight, 'quality_rating': rating, 'force_complete': bool(force_complete)}) def commit_inspection_single(self, row, qty, weight_kg, operation_id): """无单自采行(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} 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 _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()