commit deb3e72750062044e19ad307e8cfa735a419f958 Author: Ubuntu Date: Thu Oct 8 17:35:43 2026 +0800 chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点 来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。 diff --git a/.assets_mapping b/.assets_mapping new file mode 100644 index 0000000..5ee074a --- /dev/null +++ b/.assets_mapping @@ -0,0 +1,3 @@ +AI生鲜系统开发设计文档_修订版.docx | 文档 | https://conversation.cdn.meoo.host/conversations/303721794349711360/file/2026-06-06/1780708312750-AI生鲜系统开发设计文档_修订版.docx?auth_key=3dc475b127ce61651117b30cfda25478c88c3f777d9227d7979d98147890b1c7 | /home/user-files/AI生鲜系统开发设计文档_修订版.docx +全链路完整流程图.html | 文档 | https://conversation.cdn.meoo.host/conversations/303721794349711360/file/2026-06-06/1780711724314-全链路完整流程图.html?auth_key=e342fcfb5c751528be11a006780d30ed0d56d354891dd36aedc71c4bacb181bc | /home/user-files/全链路完整流程图.html +全链路完整流程图-1.html | 文档 | https://conversation.cdn.meoo.host/conversations/303721794349711360/file/2026-06-06/1780731399662-全链路完整流程图.html?auth_key=15f748a7f57f4de152eb5105c3acdba8c7792e5267c2d9988ce7ad683b477187 | /home/user-files/全链路完整流程图-1.html diff --git a/.cursor/rules/00-project.mdc b/.cursor/rules/00-project.mdc new file mode 100644 index 0000000..a8dfd39 --- /dev/null +++ b/.cursor/rules/00-project.mdc @@ -0,0 +1,85 @@ +--- +description: 食堂配送项目全局约束(架构、文档权威、安全、订单状态) +alwaysApply: true +--- + +# canteen-delivery2 全局约束 + +## 产品与栈 + +- 业务:生鲜/食堂 B2B 配送全链路(建档→录单→分配→备货/采购→验收→分拣→配送→财务成本)。 +- 终端:Web(`src/`,开发 :3015)+ API(`server/`,:3001)+ 微信小程序(`miniprogram/`)。 +- 数据:PostgreSQL;迁移在 `migrations/*.sql`,经 `npm run db:migrate` / `server` migrate 执行。 +- 本地常用:`npm run dev:all`。 + +## 文档权威(以实现为准) + +| 主题 | 权威来源 | +|------|----------| +| 各业务模块实现与关联 | `docs/modules/`(索引 [README](docs/modules/README.md)) | +| 菜单/路由/权限 | `src/config/menuCatalog.ts`,对照 `docs/WEB_MODULES.md` | +| 架构与部署 | `docs/ARCHITECTURE.md`、`deploy/PRODUCTION.md` | +| 财务/成本已做未做 | `docs/财务结算模块实现对照.md`(含按钮审计 §8) | +| 分公司隔离 | `docs/数据隔离与共用关系图.md`、`tenantScope` | +| API 概览 | `docs/API.md`(以各 `*Routes.ts` 为准) | + +不要把已删除的愿景长文(旧「功能模块」、全链路 HTML、优先级路线图)当作已实现功能。 + +## 订单主状态(勿自造) + +合法推进链(`ORDER_STATUS_NEXT`):**20→30→40→45→50→60→90**。 + +| 状态 | 含义 | +|------|------| +| 20 | 待分配 | +| 30 | 待备货 | +| 40 | 待验收 | +| 45 | 待分拣 | +| 50 | 待配送 | +| 60 | 配送中 | +| 90 | 已完成 | + +- 无草稿态 10;财务态 70/80 已废弃(结算独立模块)。 +- **状态推进必须走后端 workflow / 注册 handler**,禁止前端直写 `orders.order_status` 旁路。 +- 文案以 `src/utils/orderStatusLabels.ts` 与小程序 `constants` 对齐。 + +## 模块化扩展 + +新业务能力优先挂注册表,勿再塞巨型 monolith: + +- 后端:`server/src/modules/businessModules.ts` + `workflow/routes/*` + `handlers/*` +- Web:`src/modules/businessModules.ts` + `routes.tsx` + `menuCatalog.ts` +- 小程序:`miniprogram/modules/registry.js` +- 全员助手能力:`server/src/capabilities/`(**不要**把助手模块 id 等同于上面三套 catalog),守则见 [assistant-capability.mdc](assistant-capability.mdc) + +## 安全与提交 + +- **未经人工直接命令,严禁部署上线到生产**(线上 API / 前端 / 生产库 / 迁移 / 线上 Nginx)。 + 推代码到 git 仓库不算部署。细则见 [deploy-authorization.mdc](deploy-authorization.mdc)。 +- **本地库禁止覆盖线上库**:任何「本地/开发库 → 线上库」的数据写入一律禁止(整库恢复、 + 定向覆盖 AI 配置与提示词、反向同步脚本);线上库只允许跑迁移。见 + [local-db-must-not-overwrite-prod.mdc](local-db-must-not-overwrite-prod.mdc)。 +- **财务逻辑冻结**:未经开发者明确批准不得改动财务口径与代码;只读分析照常,改动前须先 + 说明「改什么/为什么/影响面/回滚」并获批。见 [finance-freeze.mdc](finance-freeze.mdc)。 +- **前端文案不得擅自增删**:小字/提示语/tooltip/按钮标签等属产品决策,改动前须先获许可; + 发现文案有误只报告不动手。见 [frontend-copy-changes.mdc](frontend-copy-changes.mdc)。 +- **前端界面纪律**:改 A 不动 B、先复用再复制、写操作防抖节流、详情异步不得串单。见 [frontend-ui-discipline.mdc](frontend-ui-discipline.mdc)。 +- **禁止**提交或在文档/规则中粘贴:`server/.env`、生产密钥、SSH 私钥、`deploy/*密码*`、小程序 AppSecret。 +- `/api/data` 禁止对客户端开放任意 SQL `expr` 过滤器。 +- 敏感桶(验收照片、签收凭证、发票等)走签名 URL,勿改回长期公开直链。 +- 改菜单/权限时同步:`menuCatalog`、`permissionCatalog`/`seed-permissions`、必要时 `docs/WEB_MODULES.md`。 + +## 协作习惯 + +- **设计先行**:功能/行为变更须先写 `docs/design/` 设计文档,再编码,收工前对照验收标准验证。细则见 [design-before-code.mdc](design-before-code.mdc)。 +- **意图门禁**:动代码前须问清用户意图;问因/问漏默认只读;口径等敏感变更须明示批准。细则见 [diagnose-and-metrics-gate.mdc](diagnose-and-metrics-gate.mdc)。 +- 只改任务相关代码;不顺手大重构、不乱加文档除非要求(设计文档与任务明确要求除外)。 +- 未明确要求时不 `git commit` / `push`;不改 git config。 +- 财务缺口、固定成本录入未接通等:先查对照文档,勿宣称「已完整实现」。 +- 订单销售价/成本价口径冻结:见 [order-price-cost.mdc](order-price-cost.mdc);**改动前须向用户确认**。 +- 采购与备货冻结:见 [purchase-prep-freeze.mdc](purchase-prep-freeze.mdc);**禁止统一 `purchase_status` 谓词、禁止完成自采写成 30**。 +- 验收与加工冻结:见 [inspection-processing-freeze.mdc](inspection-processing-freeze.mdc);**不合格不得入库**;拒收 40→30 勿当缺陷改掉。 +- 分拣出库冻结:见 [picking-freeze.mdc](picking-freeze.mdc);**完成分拣不改订单计划量**;勿接 `customer` 拣货模式。 +- 全员助手框架冻结:见 [assistant-capability.mdc](assistant-capability.mdc) 与 `docs/design/20260908-assistant-preview-surfaces.md`;**改动前须向用户确认**。 +- 配送单浏览器打印通道冻结:见 [delivery-note-print.mdc](delivery-note-print.mdc);**改动前须向用户确认**。 +- 新页面 / 接口交付:见 [page-api-delivery.mdc](page-api-delivery.mdc)(完整通路、提交注明对接状态、`TODO: api` 须带预计完成时间)。 diff --git a/.cursor/rules/assistant-capability.mdc b/.cursor/rules/assistant-capability.mdc new file mode 100644 index 0000000..c1aadb3 --- /dev/null +++ b/.cursor/rules/assistant-capability.mdc @@ -0,0 +1,64 @@ +--- +description: 全员助手默认契约(模块路由、确认闸、查询卡/变更预览、才控页);改框架须先确认 +alwaysApply: true +--- + +# 全员助手 + +权威:[框架冻结](docs/design/20260903-assistant-framework-freeze.md) + [查询/预览表面](docs/design/20260908-assistant-preview-surfaces.md) + [写分级确认](docs/design/20260908-assistant-write-grades.md) + [草稿凭证](docs/design/20260908-assistant-draft-voucher.md)。 +实现:`server/src/capabilities/`、`server/src/mcp/orderEntryAgentHost.ts`。产品意图见 `docs/ai助手优化.md`(非编码权威)。 + +改路由方式、模块主键、开壳门槛、确认闸、表面、UI 意图、Web 提交路径前:先说明拟改点,**得到同意再改**。禁止未告知就改。加配送/财务/小程序:按模块登记,不必推翻 Host。 + +## 架构 + +``` +登录 → 权限×端过滤 → routeModules(text, visible, hint) → 专员只带这些工具 + → 能查清:show_query(不跳页;翻页/改筛 POST /browse,不调模型) + → 要人选一项:request_pick(POST /pick 校验 id,不写库) + → 要写库:handler 出 preview + need_confirm → 人点确认 → POST /confirm(会话 args,不调模型) + → 必须用页上控件:describe/set/run_page_action;navigate 最后手段 +``` + +- 选模块是服务端函数,不要做成 `load_modules`。 +- 模块 id 自有(`navigate`、`order-entry`…),不要 1:1 抄 Web `BUSINESS_MODULES.id`。 +- 新业务:`registerCapability` + `modules.ts`;占位可无 handler。 +- 禁止:`/api/data` 任意 SQL;助手写 `order_status`、改 `unit_cost` 口径。 + +## 开壳 ≠ 能调能力 + +- Chat / FAB:已登录即可(含供应商门户)。不要加回录单权限门槛。 +- 能力仍 `permissions` + `surfaces`(`web` | `miniprogram` | `api`)。`web_fab` 只作 `web` 别名。 +- 空 `permissions` = 任意已登录;打开页还须 `visible_pages`。 + +## 确认闸 + +- `toToolSchema` 不暴露 `confirm`。模型传入的 `confirm` 必须丢弃。 +- 写操作仅当 `POST /confirm` 的 `confirmed_action_id` **等于**会话 pending 能力名时执行。默认 args 只信会话。`/chat` 上的 `confirmed_action_id` 不再执行写。 +- 订单改单试点 `prepare_order_edit`:确认可带人改过的 `items`,须与 pending `order_code` 一致;禁止改单据号。其它能力仍忽略客户端 args。数量/售价/简单加删行走该草稿;新建商品、分类树、派供应商/自采、加工、单位、成本价回 `/orders` 抽屉(`search` + `open_order`,无独立详情 URL),禁止弹窗代做。 +- `need_confirm` 的预览由 **handler/服务端** 填进 `preview_change`(无 preview 函数则默认合成)。禁止模型自由拼变更单、不要第二套 `confirm_token`。订单改单草稿就是这一张 `preview_change`,不要查询卡兼编辑。 +- 标明「助手不代做」的能力(库存入库、市场排除、免入库开关等)不要改成弹窗代写。 +- 销售价仅该草稿由人确认后保存;禁止助手改 `unit_cost`。 + +```text +❌ 把 confirm 加进模型 schema,或一次塞全目录工具,或默认 open_page 跳转 +✅ 1~2 模块 + show_query / request_pick / preview_change + confirmed_action_id +``` + +## 端与 UI 意图 + +壳只渲染协议:`{ type, web?, miniprogram?, payload }`。 + +| type | 用途 | +|---|---| +| `show_query` | 展示 list/详情,不跳页;可 POST /browse 翻页/搜索/改日期 | +| `request_pick` | 人选一项(校验会话 ids);不是写库 | +| `preview_change` | 增删改预览(订单改单为可编辑草稿);确认回传该能力名 | +| `set_fields` / `run_action` | 控当前页已有控件 | +| `navigate` | 仅当必须打开页 | + +- 打开页仍 `list_pages` + `open_page`;**新列表页不要加 `open_*`**。已有捷径在 `OPEN_PAGE_BY_TOOL`。 +- 控页:通用 `describe_page` / `set_page_fields` / `run_page_action`。筛列表用 `createCopilotListAdapter`(snapshot 不带 `rows`)。不要用 `run_page_action` 代写库。 +- `list_*`:对话要数字且不能只靠查卡/改筛时再加。 +- `web` / `miniprogram` 不含 `submit_order`。Web 下单:录单页确认 + `POST /orders/submit`。 +- 隔离走现有 `tenantScope`。 diff --git a/.cursor/rules/backend.mdc b/.cursor/rules/backend.mdc new file mode 100644 index 0000000..677424a --- /dev/null +++ b/.cursor/rules/backend.mdc @@ -0,0 +1,40 @@ +--- +description: Express/PostgreSQL 后端约定(租户、workflow、迁移、服务层) +globs: server/**/*,migrations/**/*.sql +alwaysApply: false +--- + +# 后端约定 + +## 分层 + +- 路由薄:`server/src/routes/*` 与 `modules/workflow/routes/*` 负责鉴权、解析入参、调 service。 +- 业务在 `server/src/services/*`;订单推进在 `modules/handlers/*` + `kernel/withOrderLock`。 +- 新 workflow 端点优先放对应 `*Routes.ts` 并在 `businessModules` 挂载,少往 `legacyRoutes` 堆。 + +## 租户 / 分公司 + +- 业务读写经 `tenantScope`(或等价 scope)按 `branch_code` 隔离。 +- `super_admin` 做业务须选定操作分公司,禁止无分公司游离写订单/库存。 +- 平台级资源(如 `branches`、部分全局配置)与分公司业务表勿混写。 + +## 订单与事务 + +- 状态变更:`assertValidTransition` + 行锁(`withOrderLock` / `FOR UPDATE`),在事务内完成副作用。 +- 履约副作用(备货、验收、分拣、配送结案)跟对应 handler / fulfillment service,保持幂等。 + +## 数据与迁移 + +- Schema 变更只加新文件:`migrations/YYYYMMDD_description.sql`(时间戳递增,勿改已应用迁移)。 +- 查询用参数化 `$1…`;禁止拼接客户端输入为 SQL。 +- 列表/看板大查询注意索引与 branch 过滤;勿默认全表扫生产库。 + +## API 风格 + +- 业务写操作走 `/api/workflow/...`;通用表 CRUD 才用 `/api/data`。 +- 错误响应保持现有 `{ error, error_description }` 或 workflow `{ data, error }` 形态,前后端一致。 +- 财务路径前缀以 `financeRoutes.ts` 为准(如 `/finance/customer-statements/generate`,不要写已废弃的 `/statements/generate-customer`)。 + +## 测试 + +- 纯函数/服务逻辑优先加 `server/tests/*.test.ts`;改关键口径后至少保证 `npm --prefix server` 相关 typecheck/test 可过。 diff --git a/.cursor/rules/change-scope.mdc b/.cursor/rules/change-scope.mdc new file mode 100644 index 0000000..44313f1 --- /dev/null +++ b/.cursor/rules/change-scope.mdc @@ -0,0 +1,38 @@ +--- +description: 变更范围与变更清单:只改被要求的部分,越界先请示,完工列清单双核对 +alwaysApply: true +--- + +# 变更范围与变更清单(硬规则) + +## 规则一:只动被要求的地方 + +只修改用户在该轮对话中**明确要求**的文件与行为。不得以任何理由扩大范围,包括 +但不限于:「顺手修一下」「既然看到了就清理掉」「这里风格不一致顺便统一」 +「反正是死代码删了也没事」。看到范围外的问题,**只报告,不动手**。 + +## 规则二:越界必须先请示 + +确有必要修改范围外文件时(例如改函数签名必须同步改调用方),**先停下来**说明: +1. 要改哪个文件、改什么; +2. 为什么非改不可(不改会怎样); +3. 影响面与回滚方式。 +拿到用户明确许可后再动手。 + +## 规则三:完工必须给出变更清单(双核对) + +任务结束时必须输出变更文件清单,并同时提供**用户可自行执行**的核对命令, +使核对不依赖 AI 的自述: + +| 核对方 | 方式 | +|--------|------| +| ① AI 自核 | 对比任务前后的 `git status --porcelain`,逐条说明每个文件为何被改 | +| ② 用户核对 | 给出可直接粘贴执行的命令(`git status --porcelain` / `git diff --stat`)| + +清单须包含:文件路径、新增or修改or删除、改动意图、是否在授权范围内。 +**范围外的改动必须单独标注并说明何时获得的许可。** + +## 防止"自我报告不可信" + +任务开始时先记录基线(`git rev-parse HEAD` + `git status --porcelain`), +结束时用同一条命令重新采集并对比,给出**客观差异**而不是复述记忆。 diff --git a/.cursor/rules/customer-freeze.mdc b/.cursor/rules/customer-freeze.mdc new file mode 100644 index 0000000..77c4c3a --- /dev/null +++ b/.cursor/rules/customer-freeze.mdc @@ -0,0 +1,54 @@ +--- +description: 客户管理冻结;有历史订单拒删;删客户走 deleteCustomer 禁用 /api/data 直删;信用不拦单;客户门户表禁删 +alwaysApply: true +--- + +# 客户管理(冻结) + +权威:[docs/design/20260920-customer-freeze.md](../../docs/design/20260920-customer-freeze.md) +对照:[docs/todo/20260915-模块流转总图与设计对照.md](../../docs/todo/20260915-模块流转总图与设计对照.md) §9(**§9.2 第 8 行、§9.3c「唯一触发点」、§9.3 门户引用表均已过期**) +模块说明:`docs/modules/08-客户管理.md` + +**改下列任一行为前,必须先向用户说明拟改点并得到明确确认,禁止顺手改。** + +## 删除客户 + +- **有历史订单即拒绝删除**(400),不得改成软删/停用;守卫顺序(编码 → 存在性 → 分公司归属 → 订单数)不得调整。 +- 级联清单 12 张 + `customer_statements`(先清 `statement_disputes`/`statement_lines`)+ `customers` 本体;`orders`/`after_sales` 靠拒删保护;`parse_sessions`/`voice_recognition_logs` **有意保留**。 +- **新增含 `customer_code` 的表必须并入级联清单**(漏删会让同 `customer_code` 重建时旧数据「复活」)。 +- ⛔ **禁止用 `/api/data` 的 delete 直删 `customers`**:`customers` 在写白名单且不在禁写表;通用执行器对**任意表**都构造裸 `DELETE`(只特判了 `orders`)。该路径绕过拒删与级联。 + +## 空值与预算口径 + +- `delivery_time` **无默认值、可空**;空值**必须写 `NULL`,不得写空串**。读侧**只用** `deliveryDeadlineSql.ts` 的 `CASE` 短路实现,不要另写第二份。 +- `cost_budget` 与 `budget_amount` **成对写**;预警读取恒为 `COALESCE(cost_budget, budget_amount, 0)`。 +- `sales_budget` **已参与销售预警**(`isOver` 取成本/销售并集,`over_count` 计销售超标)——`customers.sales_budget` 的**列注释**与对照 §9 的「只存档、不做销售预警」已过期。 +- `used_budget` **无写入者**,是死字段,别当预算口径。 + +## 信用不拦单(已定稿) + +- `checkCustomerCredit` 在客户存在时**恒** `allowed: true`;**唯一 block 是「客户不存在」**。 +- **禁止**恢复「因 `credit_limit` / `credit_frozen` 拦单」——要恢复必须先拿产品决策。 +- 唯一写信用字段的是逾期扫描(≥30 天置 `credit_frozen`)。 + +## 不要当现网事实 + +- 报价**表**偏客户域、**写入接口挂商品模块**;`customerOps.ts` 只是 re-export 层。 +- 批量导入**无事务、逐行提交**、允许重复联系电话、客户编码在**客户端**生成——都是有意的。 +- 顺延是**三联动同事务**(快照历史单 → 顺延 + `rollover_count+1` → 同步 `customer_quote_versions`),不得拆开。 +- ⛔ **`customer_portal_users` 表不得 DROP、不得改名**:删号接口第一件事就查它,删表即 `relation does not exist` → 整个删号 500。 +- 对照 §9 引用的 `menuLayout.ts:91` / `UserManagement.tsx:277` 等**行号与文件已失效**,别按它定位。 + +## 已知异常(**不是**受保护口径) + +权威文 A1~A11(`/api/data` 直删旁路、改绑覆盖在途任务、收货人 update/delete 无分公司校验、删客户 TOCTOU、调度器共享连接并发、前后端折扣叠加分歧、早退漏同步、第二份 deadline SQL、`used_budget` 死字段、通知逃逸、小程序「预算不足」文案错位)**修与不修由开发者裁决**。禁止把它们当正确现状冻结,也禁止顺手一起改。 + +```text +❌ 去掉「有历史订单即拒绝删除」/ 改成软删 +❌ 用 /api/data 的 delete 直删 customers +❌ delivery_time 写空串 / 另写一份不做短路的 deadline SQL +❌ 恢复信用额度或冻结拦单 +❌ DROP 或改名 customer_portal_users +❌ 把 sales_budget 当「不参与预警」 +✅ 先说明拟改点、影响面与是否误伤删号/删客户链路;得同意后再改 +``` diff --git a/.cursor/rules/dashboard-freeze.mdc b/.cursor/rules/dashboard-freeze.mdc new file mode 100644 index 0000000..866035c --- /dev/null +++ b/.cursor/rules/dashboard-freeze.mdc @@ -0,0 +1,54 @@ +--- +description: 数据看板冻结;净利与成本账本口径属财务冻结;周期裁到 asOf;损耗只认加工;超管落地不得改回 /dashboard +alwaysApply: true +--- + +# 数据看板(冻结) + +权威:[docs/design/20260920-dashboard-freeze.md](../../docs/design/20260920-dashboard-freeze.md) +对照:[docs/todo/20260915-模块流转总图与设计对照.md](../../docs/todo/20260915-模块流转总图与设计对照.md) §14 +模块说明:`docs/modules/13-数据看板.md` + +**改下列任一行为前,必须先向用户说明拟改点并得到明确确认,禁止顺手改。** + +## 只读与财务口径 + +- **本模块纯只读**:不得新增任何写路径(不回写履约或结算)。 +- **净利润复用 `computeFinanceNetProfit`**(唯一实现 + `Object.freeze`);**禁止**在看板另写一份净利公式。 +- 成本 KPI 账本窗口 `getPurchaseCostLedgerWindow`:**排除** `inventory_holding` 与重复验收/加工占位行;**采购项以订单行口径替换**;`ledger_total = Σ构成`;**9 类与成本管理 `COST_CATEGORIES` 逐项一致**、0 金额也展示、前端不截断。 +- ⚠️ **以上三件(9 类 / 备本窗口排除项 / 订单行口径替换)与净利润都属 [finance-freeze](../../.cursor/rules/finance-freeze.mdc) 范围**——改动必须走财务冻结流程(附改前改后实测数字 + 影响面 + 回滚)。 + +## 周期与取数 + +- **未结束的快捷周期止日裁到 `asOf`**(`dateTo = min(自然止日, asOf 中国日)`);**自定义区间不裁切**;被裁时 label 改实际闭区间;`asOf < 周期起` 时 `dateTo = dateFrom`。 + 前后端**各有一份** `clipPeriodEndToAsOf` → **改必须两份同改**并跑 `server/tests/dashboardPeriod.test.ts`。 +- 汇总接口默认 **`period=day` / `date_field=delivery_date` / 页头当天**;周期为**中国日历闭区间**。 +- **损耗只认 `processing_tasks.loss_qty`(完工中国日)**,**禁止**改成验收 `inspections.loss_qty`(会让损耗恒为 0);**合批不拆损耗**不得改。 +- 需求预测**默认未选、不自动请求**;`category_codes`/`sku_codes` 并集过滤、分类含子类;**未传范围参数仍全量**(兼容其它调用方)。 +- 下钻**必须携带** `date_from`/`date_to`(`/orders` 另带 `date_field`;`/finance`、`/finance/costs` 另带兼容 `period=YYYY-MM`)。 + +## 落地路径(不变量) + +- 看板菜单守卫 **`roles: ['admin']`,不含 `super_admin`**。 +- **不变量:默认落地路径必须是该角色真能访问的路由。** 三处必须一致:`accountLoginService.resolveWebHomePath`、`src/utils/authRouting.ts`、`src/utils/unifiedLogin.ts`。 +- 现取值:**`super_admin → /system/config`**、`admin → /dashboard`。**禁止**把超管落地改回 `/dashboard`(会造成「无权限跳回默认首页」自环)。 +- 有钉子测试 `server/tests/homePathConsistency.test.ts`:改任一处必须三处同改并跑它。 + +## 已知异常(**不是**受保护口径) + +> ⚠️「**所有成本**」(成本构成聚合)与「**净利润**」(损益计算)**本就是不同口径,不相等是正常的**——**不要**拿「两张卡对不上」当缺陷依据。 + +**A0(待业务确认的口径差异,不是账错)**:净利要减的「期间费用」判定只看「这条成本**没有挂订单号**」,而「**库存持有**」(`inventory_holding`,盘盈/库存重估类)的行**恰好都没有订单号** → 被计入期间费用;可成本 KPI 一侧明确写了排除它(`excludeInventoryHoldingFromKpiSql`)。实测差额:BR002 cycle 202609 为 **148 行 / 1,627.03 元**(占期间固定 3.6%)。**两种可能都保留**(该不该算本期成本,需业务/财务确认),**不得当 bug 顺手修**——改动会同时影响看板净利、财务概览净利与客户预算预警,属 [finance-freeze](../../.cursor/rules/finance-freeze.mdc) 流程,改前必须先出对照数据。 + +权威文 A1~A9(成本归类未复用 `resolveCostBucketKey` 致非固定桶 **26.3%**、`asOf` 退化分支无单测、下钻 URL 内联无测试、**页头周期下拉已消失**故裁切仅 API 可达、聚合失败整页 500(预测子调用有降级)、账本聚合**性能实测 1,681 ms / 542k shared hit** 且 `recentOrders` 无 LIMIT、`asOf` 回传用服务器本地时区、9 类一致性**无测试钉住**、后端放行集合比菜单宽)**修与不修由开发者裁决**。**禁止**把归类偏差当正确口径冻结。 + +```text +❌ 在看板另写净利公式 / 自行改 9 类或账本窗口 +❌ 去掉周期裁切 / 在自定义区间上套裁切 / 只改一份 clipPeriodEndToAsOf +❌ 把损耗来源改成验收 loss_qty +❌ 需求预测改成自动请求 / 把「未传参数→全量」改成空集 +❌ 下钻丢区间 +❌ 把超管落地改回 /dashboard 或只改三处中的一处 +❌ 未经财务冻结流程去「修」A0 的期间固定谓词 +✅ 先说明拟改点、影响面(是否属财务口径);得同意后再改 +``` diff --git a/.cursor/rules/delivery-freeze.mdc b/.cursor/rules/delivery-freeze.mdc new file mode 100644 index 0000000..2d3991e --- /dev/null +++ b/.cursor/rules/delivery-freeze.mdc @@ -0,0 +1,61 @@ +--- +description: 配送履约冻结;发车只拦无核货明细;免入库必拍、加菜必拍;结案会生成结算单;卸货时长取同一任务两列 +alwaysApply: true +--- + +# 配送履约(冻结) + +权威:[docs/design/20260920-delivery-freeze.md](../../docs/design/20260920-delivery-freeze.md) +对照:[docs/todo/20260915-模块流转总图与设计对照.md](../../docs/todo/20260915-模块流转总图与设计对照.md) §6 +模块说明:`docs/modules/05-配送履约.md`(**§1/§5「不写结算单」为假**,以权威文为准) + +**改下列任一行为前,必须先向用户说明拟改点并得到明确确认,禁止顺手改。** + +## 发车与核货 + +- 50→60 只拦「无核货明细」`no_loading_items`。**库存不足不拦发车**,禁止改回硬拦。 +- 直送免入库发车同样须 `order_status >= 50`,不开旁路。 +- 核货明细跨 `pick_code` **按订单**取(合并多张拣货单);禁止改回「只取最新一张」。 +- 核货改实配**只写** `picking_items.loaded_qty` / `unit`;**不写** `order_items.quantity`。 + `applySkipInboundSettlementForOrder` 是空实现,禁止从发车路径加回回写。 +- 须拍而未拍:`skip_inbound` / `is_extra_dish` **恒拦发车**;加菜另拦「拍照送达」`extra_dish_photo_required`。 + +## 结案(60→90) + +- 顺序不可调:冻结实收 → 出库/释放预留 → 关任务 → 签收幂等 → 置 90 → 生成结算单。 +- `insertSignRecordIdempotent` 用 `SAVEPOINT` + 容忍 `23505`,禁止改裸 `INSERT`。 +- **结案会生成客户结算单 + 供应商结算单**(`ensureCustomerStatementAfterOrderComplete` / `ensureSupplierStatementsForOrder`)。 + 模块说明「不写结算单」已推翻,禁止照它删这两句;也禁止在配送模块新增写成本。 +- 已 90 不改(`WHERE order_status < 90`;`freezeOrderSettlementQtyOnComplete` 对 `>= 90` 直接返回)。 + +## 进圈与时长 + +- 首次进圈 `COALESCE(..., NOW()) ... AND geofence_entered_at IS NULL`,禁止去掉 `IS NULL` 守卫。 +- **卸货时长 = 本任务 `end_time` − 本任务 `geofence_entered_at`**(同一行),不是「− 下一站」。 +- 进圈:途中无未完成进圈时取半径内最近;已进圈未完成不新开第二段。结束配送把当前段归给本单(重叠先完成的拿走),不拦完成。一次定位最多 1 单;结束配送兜底写 `NOW()` 属有意设计。 +- 定位上报的 `order_code` 取自**请求体**(小程序恒不传)→ 那条把任务写成 20 的 `UPDATE` 是**热路径**,其 `AND task_status < 20` 守卫(2026-09-20 `98e1b775` 补)**勿删**。`/delivery/start` 的同名分支取自任务行 `order_code`(恒有值)= 死代码,**别当同类问题**。 +- 小程序「回前台补点」**绕过**客户侧节流与精度筛选,且不推进 filter 状态——别假设每个上报点都过了筛选。 + +## 不要当现网事实 + +- `delivery_tasks.order_code` **唯一** → 一订单一任务,**没有**「一单多车」。 +- `task_status` 只有 **10 / 20 / 30**,**没有 40**;界面「异常」筛选无数据来源,别去「补」状态。 +- `isDeliveryOnlineRequired()` **恒 false**:上下线门禁已退役,禁止以「在线」加回派单/发车门禁。 +- 排班只做「按人·按日·全天」,不做上下线、不做上/下午时段。 +- 小程序**不调** `wx.startLocationUpdate`(设计明示非目标),只 `getLocation` 回落 + `startLocationUpdateBackground`。 +- 模块说明里的 `docs/design/2026 08/09-*.md` 链接多已被 `edfb6da2` 删除,用 `git show edfb6da2^:docs/design/.md` 取回。 + +## 已知异常(**不是**受保护口径) + +权威文「已知异常」表列出的 14 项(非斤结算/出库优先级相反、免入库 `picked_qty` 播种为计划量、定位上报打回 20、改绑覆盖在途任务、打印扇出翻倍、排班先删后校验、准时率与看板不一致、Web 直写 `delivery_tasks`、加菜按钮拦死、发车取点无超时、路线 LIMIT 40 / `Date` 字符串排序、deadline 片段无短路)**修与不修由开发者裁决**。禁止把它们当「正确现状」去冻结,也禁止顺手一起改。 + +```text +❌ 库存不足硬拦发车 / 直送开旁路 +❌ 核货改实配回写 order_items / 恢复「发车写回实配」 +❌ 照「结案不写结算单」删掉结算单生成 +❌ 去掉进圈 IS NULL 守卫 / 把卸货时长改成「下一站」 +❌ 去掉定位上报 UPDATE 的 `task_status < 20` 守卫(会把已结束任务打回在途) +❌ 按「一单多车」「task_status=40」去改表或补状态 +❌ 以「在线」加回派单门禁 +✅ 先说明拟改点、影响面与是否误伤免入库/加菜闸门;得同意后再改 +``` diff --git a/.cursor/rules/delivery-note-print.mdc b/.cursor/rules/delivery-note-print.mdc new file mode 100644 index 0000000..9b687d4 --- /dev/null +++ b/.cursor/rules/delivery-note-print.mdc @@ -0,0 +1,32 @@ +--- +description: 配送单浏览器打印通道冻结;改通道须先告知并得到明确确认 +alwaysApply: true +--- + +# 配送单浏览器打印(冻结) + +权威设计:`docs/design/20260904-delivery-note-print-blank-fix.md`。 +实现:`src/utils/deliveryNotePrint.ts` 的 `printHtmlViaHiddenIframe`(函数名历史遗留)。 + +**改下列任一行为前,必须先向用户说明拟改点并得到明确确认,禁止顺手改。** + +## 冻结契约(浏览器通道) + +``` +完整单据 HTML → DOMParser → #canteen-delivery-print-host + 样式 +→ @media print 隐藏 body 其它子节点 → window.print() → 延后清理 +``` + +- **必须**:当前页宿主 + `window.print()`;`afterprint` 后延迟再卸宿主。 +- **禁止**(未获许可): + - 改回隐藏 / 屏外 / `opacity` / `0×0` iframe 作为打印源 + - 用 `blob:` / `srcdoc` iframe 嵌框打印(CSP `default-src 'self'` 会拦 `blob:` → 白纸) + - 为打印单独放宽 CSP `frame-src` / `blob:`(须另评) + - 恢复「全屏二次确认预览」作为默认浏览器路径(除非产品明确要求) + +热敏通道(`printDeliveryNotesToThermal` / QZ)不在本冻结范围内,但改浏览器通道时勿顺手改热敏。 + +```text +❌ 未告知就把 printHtmlViaHiddenIframe 改回 iframe / Blob +✅ 先说明原因并问「要不要改打印通道」;得同意后再改代码与设计 +``` diff --git a/.cursor/rules/deploy-authorization.mdc b/.cursor/rules/deploy-authorization.mdc new file mode 100644 index 0000000..7fd0e88 --- /dev/null +++ b/.cursor/rules/deploy-authorization.mdc @@ -0,0 +1,51 @@ +--- +description: 部署上线授权规则:未经人工直接命令,严禁向生产环境部署或发布 +alwaysApply: true +--- + +# 部署上线授权(硬规则) + +## 规则 + +**未经人工直接在对话中下达的部署命令,严禁以任何方式把代码、构建产物、配置或数据库变更 +发布到生产环境。** 没有例外,不因「任务上下文里隐含需要」「上次也这么做过」「看起来只是小改动」 +而放宽。 + +「人工直接命令」的判定标准:该轮对话中,用户本人明确说出要部署/上线/发布(如「部署上线」 +「发布到生产」「推上去」)。以下都**不**构成授权: + +- 用户只是让你改代码、修 bug、写完看看; +- 用户说「测试完毕」「我验收一下」——这只是他去看,不是让你发; +- 之前的会话或更早轮次里授权过一次部署,**不延续**到本次; +- 你自己判断「已经连续改了几处,顺手发一下」。 + +## 生产环境范围(受本规则约束的对象) + +| 目标 | 说明 | +|------|------| +| test-api `146.56.223.139` | 线上 API(`/opt/ai-fresh-delivery`,`ai-fresh-api.service`)| +| test-h5 `119.45.34.106` | 线上前端(`/opt/canteen-frontend`,Nginx)| +| 经 CLB 的 `https://www.xdjchuanhui.com` | 用户实际访问的线上入口 | +| 生产数据库 | `1.13.62.2:20538/ai_fresh_delivery` 及任何生产迁移执行 | + +涉及以上任一项的动作都算部署:`scp`/`rsync` 上传产物、远端 `prod-apply-backend.sh`、 +重启线上服务、执行生产迁移、改生产 Nginx、跑生产数据修复脚本。 + +## 允许直接做的事(无需额外授权) + +- 本地开发栈:`run-local.sh start|stop|status`、本地库迁移、本地构建与测试; +- 提交并推送代码到 git 仓库(Gitea)——推代码 ≠ 部署,线上不会因此变化; +- 在**本地或只读快照库**(`prod_*` 等)上查询与分析。 + +## 需要授权时该怎么做 + +1. 停下来,把「准备做什么、影响哪个环境、回滚点是什么」讲清楚,再问要不要发; +2. 拿到明确命令再执行; +3. 执行后报告验证结果与回滚方式。 + +**若已经因误判发出去了**:立刻停下后续动作并主动告知,给出回滚路径。 + +## 已发生过的违规(用于说明本规则的必要性) + +2026-09-13:连续多个修复完成后,未经用户直接命令自行部署了后端与前端到生产, +用户随后明确要求「后续严禁未经我的直接命令说明许可部署代码上线」。此条即为此而立。 diff --git a/.cursor/rules/design-before-code.mdc b/.cursor/rules/design-before-code.mdc new file mode 100644 index 0000000..aa7d758 --- /dev/null +++ b/.cursor/rules/design-before-code.mdc @@ -0,0 +1,45 @@ +--- +description: 写代码前先出设计文档,实现后对照设计文档验证 +alwaysApply: true +--- + +# 设计先行 · 实现校验 + +适用:**功能开发、缺陷修复(改行为)、接口/表结构变更、跨端改动**。 +不适用(可跳过设计文档):纯文案/样式微调、仅部署、仅依赖升级、按用户指示的机械重命名、一句话可说清的 typo。 + +## 流程(必须按序) + +1. **问清用户意图**(见 [diagnose-and-metrics-gate.mdc](diagnose-and-metrics-gate.mdc);含糊或超出字面须先确认)→ 2. **设计文档** → 3. **再写代码** → 4. **对照设计验证** →(有偏离则改文档或改代码,二者对齐后再收工) + +未写出设计文档之前,**禁止**直接改业务代码(可只读探查、可讨论)。 +用户未明确授权改代码时(含仅写了设计、未确认要改),**禁止**开始改业务代码。 + +## 设计文档放哪、写什么 + +- 路径:`docs/design/YYYYMMDD-<简述>.md`(例:`docs/design/20260715-dashboard-cost-overview.md`)。 +- 至少包含: + - **目标 / 非目标**(做什么、明确不做什么) + - **方案要点**(数据口径、接口、关键页面/表、状态机影响) + - **改动面**(预计涉及的目录/模块) + - **验收标准**(可勾选的完成条件) + - **风险与回滚**(一两句即可) +- 若只改某一业务模块且改动持久:可在对应 `docs/modules/*.md` 增补一节,并在设计文档里链过去;**不要只写在聊天里**。 + +## 编码中的约束 + +- 实现须贴近设计文档;发现设计有误时:**先更新设计文档,再改代码**(或写明「设计偏差」段落后再合入)。 +- 勿扩大范围到设计未写的需求。 + +## 写完代码后的验证(收工前) + +对照设计文档逐条核对验收标准,在回复或设计文档末尾用简短清单标明: + +```text +验证: +- [x] …验收项… +- [ ] …未完成项…(说明原因 / 下一步) +- 偏差:无 / 已更新设计 §… +``` + +无验证说明视为未完成交付。 diff --git a/.cursor/rules/diagnose-and-metrics-gate.mdc b/.cursor/rules/diagnose-and-metrics-gate.mdc new file mode 100644 index 0000000..b959d87 --- /dev/null +++ b/.cursor/rules/diagnose-and-metrics-gate.mdc @@ -0,0 +1,62 @@ +--- +description: 动代码前须问清用户意图;诊断默认只读;口径等敏感变更须明示批准 +alwaysApply: true +--- + +# 意图门禁 · 诊断只读 + +防止把「为什么 / 怎么回事 / 建议」误当成「请改代码」而擅自动手。 + +## 1. 动代码前须问清意图(适用于一切改动) + +在修改任何仓库文件(业务代码、规则、迁移、配置、文档落盘等)之前: + +1. **先判断用户是否在要求改东西**。若只是提问、抱怨现象、要解释、要方案对比 → **只读**,不改文件。 +2. 意图含糊、可多解、或你准备做的事**超出原话字面**(顺手修、对齐别处、重构、扩范围)→ **先用一两句话说明拟改点并问清**,得到明确同意后再动手。 +3. 仅当用户指令已足够明确(如:**修复 / 改成 / 按这个做 / 实现 / 回滚 / 写进规则**)且方案无歧义时,才可直接编码;仍须遵守 [design-before-code.mdc](design-before-code.mdc)(该出设计则先出设计)。 + +**禁止**:未确认就「看起来该修」;诊断后顺手提交修复;扩大到用户没点名的文件或需求。 + +## 2. 诊断默认只读 + +下列视为**只读探查**,禁止改业务代码(`src/`、`server/`、`miniprogram/`、`migrations/`): + +- 问原因、问为什么漏了/没了/不对、问是否包含某项、问当前行为/口径是什么 +- 仅要求解释、对照文档、定位根因、给可选方案 + +**允许**:读代码/文档、对比说明、在聊天里列方案(**不落业务改动**)。 + +## 3. 敏感变更仍须明示批准(口径等) + +下列变更除满足 §1 外,还必须先说明拟改点并得到**明确确认**(写出设计 ≠ 已批准): + +| 类别 | 示例 | +|------|------| +| 日期轴 | 入账日 vs 配送日/下单日/入库日;日历日 vs timestamptz 边界 | +| 成本桶 | 剔除/合并采购、自采与供应商、账本 vs 货值/商品预估 | +| 统计范围 | 订单状态门槛、孤儿成本、分公司过滤、完成单 vs 录单即计 | +| 展示叙事 | KPI 命名与构成条对应关系 | +| 公式 | 毛利/净利润/占比分母(另见 `finance-cost.mdc`、`order-price-cost.mdc`) | +| 权限/数据隔离 | 角色权限、tenant/分公司范围、RLS | +| 状态机/工作流 | 订单状态推进、旁路写库 | +| 采购单状态谓词 | 把 `purchase_status < 80` 等统一成 `IN (10,32)` 或给 ⛔ 站点补 `<> 40`(见 [purchase-prep-freeze.mdc](purchase-prep-freeze.mdc)) | +| 验收入库门槛 | 不合格仍入库、验收写损耗、改拒收 40→30(见 [inspection-processing-freeze.mdc](inspection-processing-freeze.mdc)) | +| 分拣完成/出库 | 完成分拣回写 `order_items` 计划量、接上 `customer` 拣货模式、出库加回主界面(见 [picking-freeze.mdc](picking-freeze.mdc)) | +| 配送单浏览器打印通道 | iframe/Blob/CSP/`window.print` 宿主方案(见 `delivery-note-print.mdc`) | + +## 4. 与设计先行的衔接 + +- 流程:**问清意图(§1)→ 用户确认 → 设计文档(若适用)→ 编码 → 对照验收**。 +- 订单销售价/成本价见 [order-price-cost.mdc](order-price-cost.mdc);财务账本见 [finance-cost.mdc](finance-cost.mdc)。 + +## 反例(禁止) + +```text +用户:账本成本构成为什么把采购成本漏掉了? +❌ 直接改代码(改口径或「顺手修」) +✅ 解释根因;若要改,先说明方案并问「要不要按 A/B 改」 + +用户:这个按钮有点奇怪 +❌ 直接改 UI / 逻辑 +✅ 先问:是文案、交互还是背后数据不对?打算怎么改? +``` diff --git a/.cursor/rules/finance-cost.mdc b/.cursor/rules/finance-cost.mdc new file mode 100644 index 0000000..9cd93de --- /dev/null +++ b/.cursor/rules/finance-cost.mdc @@ -0,0 +1,44 @@ +--- +description: 财务结算与成本核算数据口径与改动约束 +globs: src/pages/finance/**/*,server/src/modules/workflow/routes/financeRoutes.ts,server/src/services/**/*Cost*.ts,server/src/services/**/*cost*.ts,server/src/services/**/*Finance*.ts,server/src/services/**/*finance*.ts,server/src/services/**/*margin*.ts,server/src/services/inspectionComplianceService.ts,server/src/services/orderCostPostingService.ts,docs/财务结算模块实现对照.md +alwaysApply: false +--- + +# 财务 / 成本口径 + +权威说明:`docs/财务结算模块实现对照.md`。改口径前先读该文档。 + +动代码前须遵守 [diagnose-and-metrics-gate.mdc](diagnose-and-metrics-gate.mdc);改日期轴、成本桶等另须明示批准。 + +**一套账定稿**见 [20260810-single-cost-ledger](../../docs/design/20260810-single-cost-ledger.md):KPI 只读 `cost_details`;主文案「采购成本」;「所有成本」= 全账本。 +订单行 `unit_cost` 仅为写缓存,见 [order-price-cost.mdc](order-price-cost.mdc)。 + +## 采购成本(定版) + +- `cost_details` 中 `cost_type=purchase`:**每订单每 SKU 一行**(唯一键 `order_code + sku_code`,迁移 `20260759`)。 +- 写入主路径:验收合规 `writeInspectionCost`;金额 = 该 SKU **最近一次**验收 `actual_qty × purchase_price`(**覆盖**,非累加)。 +- `purchase_applied` 按 inspection id 幂等标记;查询毛利时排除 `purchase_applied`。 +- 同 SKU 重复验收不得把历史金额叠成「整单总额挂在某一 SKU」。 + +## 查询与概览 + +- SKU 直接成本:`GET /cost/sku-costs/:cycleCode`(`getSkuDirectCosts`),勿再使用启发式均摊虚构采购行。 +- 财务概览近 7 天:营收来自完成单;成本来自这些订单的 `cost_details`(口径见对照文档)。 +- 毛利关联订单时排除孤儿成本行(订单已不存在仍留 cost)。 +- **净利润公式已锁定**:只改 `server/src/services/financeNetProfitFormula.ts`(及对应单测);禁止在 `marginQueryService` / 前端内联另一套算术或期间固定谓词。见 `docs/design/20260809-lock-net-profit-formula.md`。 + +## 产品边界 + +- **不与税务系统对接**:不做税局 API、进项/销项自动验真开票、电子票回写;发票页仅本系统开票标记 + 离线导出。 +- 勿把 `invoice-ocr` / `invoices` 台账当作财务未完成项继续排期。 + +## 明确未做 / 部分做(勿假称完成) + +详细按钮审计与落地步骤见 `docs/财务结算模块实现对照.md` **§8**(已接通项以该文档为准)。 + +- 账龄催收推送、账单客户侧确认仍弱。 +- 供应商扣款编辑 / 行异议深度仍弱。 + +## 运维脚本 + +修数据优先用已有脚本(如 `repair-purchase-from-latest-inspection.cjs`、`backfill-purchase-cost-by-inspection.cjs`),写清影响范围;生产操作前先本地/备份确认。 diff --git a/.cursor/rules/finance-freeze.mdc b/.cursor/rules/finance-freeze.mdc new file mode 100644 index 0000000..c79f769 --- /dev/null +++ b/.cursor/rules/finance-freeze.mdc @@ -0,0 +1,75 @@ +--- +description: 财务逻辑冻结:未经开发者批准不得改动,动前必须先告知 +alwaysApply: true +--- + +# 财务逻辑冻结(硬规则) + +> 背景:2026-09-14 财务口径刚理顺(采购成本/所有成本/毛利/净利/仓内加工处理, +> 见下方「已定稿口径」)。**未经开发者明确批准,不得改动任何财务逻辑。** + +## 规则一:默认不许动 + +下列范围一律**只读**。不得以「顺手」「看着不一致」「为了统一口径」「反正是展示层」 +为由修改——这些正是本次搞乱过的理由。 + +| 层 | 冻结路径 | +|----|----------| +| 口径与聚合 | `server/src/services/marginQueryService.ts` | +| 净利公式 | `server/src/services/financeNetProfitFormula.ts` | +| 成本桶 | `server/src/services/purchaseCostBucketSql.ts` | +| 财务路由 | `server/src/modules/workflow/routes/financeRoutes.ts` | +| 成本写入 | `server/src/services/*Cost*.ts`、`*cost*.ts`、`*Finance*.ts`、`*finance*.ts`、`*margin*.ts`、`inspectionComplianceService.ts`、`orderCostPostingService.ts` | +| 前端 | `src/pages/finance/**`(含 `costAccounting/**`) | +| 看板财务 KPI | `src/pages/Dashboard.tsx` 的成本/毛利/净利相关卡片与 `costOverview` 绑定 | +| 概览接口 | `/api/dashboard/summary`、`/api/finance/overview`、`/cost/*` 系列 | + +**只读分析(不写库、不改码)永远允许**:查数、对账、解释某个数字怎么算出来的、 +指出不一致——这些请照做,而且鼓励做。 + +## 规则二:必须改时,先告知再动手 + +确有必要(例如线上出现明确的算错、且用户报障)时,**先停下来向开发者说明四件事**, +拿到明确批准后再改: + +1. **改什么**:文件 + 具体表达式/行; +2. **为什么非改不可**:不改会怎样,最好给出实测数字(改前/改后); +3. **影响面**:会连带影响哪些页面/口径/报表(尤其是否动到毛利、净利、结算); +4. **回滚方式**:回滚命令或反向改动。 + +**一律不得**:先改了再报告、边改边解释、把"告知"当成"已获批准"。 + +## 规则三:口径变更必须成对落地 + +财务口径不是单点,改一处必须同时处理: + +- 后端聚合 ↔ 前端展示(避免"同一页两个数字对不上"); +- 同步更新设计文档(`docs/design/`)与 `docs/财务结算模块实现对照.md`; +- 契约测试(如 `skuDirectCostsQtyTimesUnitCost.test.ts`)同步; +- 在提交信息里写清「改前 / 改后」实测数字。 + +## 已定稿口径(2026-09-14,勿回退) + +| 口径 | 定稿 | +|------|------| +| 「采购成本」「所有成本」数据源 | **订单行口径**(`quantity × unit_cost`),按所选日期字段;不再用账本 `cost_details` 直接汇总 | +| 净利 | `销售额 − 采购成本(订单行) − 期间固定 − 期间其他`,销售额与成本**必须同口径** | +| 仓内加工成品行 | **不另计入成本合计**:材料成本已由「独立自采入库」或「库存领用」承担(同一 SKU,计入即重复)
`getSkuDirectCostsPaged` 的 `excludeWarehouseProcessing` 用于合计;**排行展示层**仍按 `purchase_cost + settled_processing_cost` 显示(加工单完工回写 `order_items.processing_settled_unit_cost`)| +| 商品成本表归桶 | `GROUP BY sku_code, is_extra_dish, cost_bucket, is_warehouse_processing`(加工行单独成行)| +| 毛利率 | `(销售额 − 采购成本) / 销售额 × 100`。**禁止**写成 `采购/销售`(那是成本率,曾把「销售=采购」误显为 100%)| +| 准时履约 | 已送达单中「未设须送达时刻」或「实际送达 ≤ `customers.delivery_time`」的占比;未设置按准时计 | + +## 未决事项(改前必须问) + +- **商品成本表「表头合计」口径**:后端 paged 接口 `totals` 含仓内加工行(8,726.85), + 而「订单采购成本」卡与看板已排除(8,684.85),两者差 ¥42。 + **待开发者选定统一口径后再动**(代码注释已标注)。 + +## 相关文档 + +- [finance-cost.mdc](finance-cost.mdc):既有财务口径细则 +- [change-scope.mdc](change-scope.mdc):变更范围与变更清单 +- `docs/design/20260914-overview-cost-order-line-purchase.md` +- `docs/design/20260914-sku-cost-warehouse-processing-separate-row.md` +- `docs/design/20260914-sku-rank-warehouse-processing-cost.md` +- `docs/design/20260913-inspection-amend-by-admin.md` diff --git a/.cursor/rules/frontend-copy-changes.mdc b/.cursor/rules/frontend-copy-changes.mdc new file mode 100644 index 0000000..a2fc69b --- /dev/null +++ b/.cursor/rules/frontend-copy-changes.mdc @@ -0,0 +1,55 @@ +--- +description: 前端改动不得擅自增删界面文案与小字,需先获开发者许可 +alwaysApply: true +--- + +# 前端文案与小字:不得擅自增删(硬规则) + +> 起因:2026-09-15 用户明确要求 ——「**修改前端时,别未经许可擅自添加小字**」, +> 并当场要求删除订单详情里的一行说明小字 +> (`orders.detail.hintAdminQty`:「管理员可改各履约类型实收(自采/直送/不入仓/入仓)…」)。 + +## 规则一:界面文案属于产品决策,不属于实现细节 + +以下都算「文案」,**改动前必须先请示**,不得以"顺手"或"帮助用户理解"为由自行添加: + +| 类型 | 举例 | +|------|------| +| **说明小字 / 提示语** | 表单下方的解释、字段旁灰字、tooltip、空状态说明 | +| **副标题 / hint** | 卡片、页面标题下的补充说明 | +| **提示条 / 警告语** | 校验失败文案、操作确认文案、成功提示 | +| **按钮与标签文字** | 按钮名、标签、筛选项名称 | +| **新增 placeholder** | 输入框占位说明 | + +**反面案例(本仓库真实发生过)**: +- 我给供应商备货表加过「数据量过大,仅显示最近 N 条…」的提示条 —— 属于**自行增添文案**, + 且阈值设得不当导致正常业务也弹提示,用户随后要求调整与删除。 +- 同类还有:为解释实现细节而加的小字,会让界面变啰嗦,且**用户并未要求**。 + +## 规则二:删除文案同样要问清范围 + +删除一行小字时,**只删被指出的那一项**: + +- 若该文案与其它文案**共用同一段条件分支**(如三元表达式/嵌套三元), + **删掉分支后要让其余分支仍然正常显示**,不得顺手改掉其它提示; +- 删完后必须核对**同级其它状态是否还有提示**(避免出现"连提示都没有了"的退步)。 + +## 规则三:只报告,不动手 + +若在实现过程中**发现某处文案有误/多余/口径过时**(例如数字口径变了、功能已下线): + +> **在完工报告里指出,附位置与建议**,由开发者决定是否修改; +> **不要自己在实现里顺手改掉。** + +## 规则四:允许直接做的(无需额外许可) + +- 用户**明确要求**的文案改动(例如"把 X 改成 Y"); +- **多语言同步**:把用户已确认的中文改动,同步到 `en` / `id` 语言包; +- **纯代码注释**(开发者可见、用户不可见)—— 但注释应说明原因,不写无意义的话。 + +## 相关文档 + +- [change-scope.mdc](change-scope.mdc):只动被要求的地方,越界先请示 +- [frontend-ui-discipline.mdc](frontend-ui-discipline.mdc):改 A 不动 B、复用、防抖、详情不得串单 +- [web-frontend.mdc](web-frontend.mdc):前端相关约定 +- `src/i18n/locales/{zh-CN,en,id}/`:文案实际所在(三语言需同步) diff --git a/.cursor/rules/frontend-ui-discipline.mdc b/.cursor/rules/frontend-ui-discipline.mdc new file mode 100644 index 0000000..84dd69e --- /dev/null +++ b/.cursor/rules/frontend-ui-discipline.mdc @@ -0,0 +1,86 @@ +--- +description: 前端界面纪律:不擅自加小字、只改被点名的面、复用组件、防抖节流、详情不得串数据 +alwaysApply: true +--- + +# 前端界面纪律(Web + 小程序) + +改 `src/` 或 `miniprogram/` 的界面时适用。文案细则见 [frontend-copy-changes.mdc](frontend-copy-changes.mdc);改哪些文件见 [change-scope.mdc](change-scope.mdc)。端侧约定见 [web-frontend.mdc](web-frontend.mdc)、[miniprogram.mdc](miniprogram.mdc)。 + +写界面时按高级前端标准自检下面五条,缺一条就停手。 + +## 1. 改 A 面,不动 B 面 + +- 用户点名的页面 / 面板 / 行 / 按钮才是范围。看到「同类筛选」「同样的标题」**不得**顺手改另一个模块。 +- **共享组件会扩散**:改 `src/components/ui/*`、公共 `utils`、被首页多个 `*-panel` 引用的组件 = 同时改所有引用方。若只要 A 变、B 不变 → **抽变体或只改 A 的局部 wxml/tsx**,先说明再动共享层。 +- 不为「对齐」去改未点名的自采 / 备货 / 分拣 / 配送。对齐必须用户明说。 + +```text +❌ 改供备货表日期轴,把自采列表、订单列表一并改成同一套 +❌ 改首页分拣行文案,去改 Web 分拣页「让两端一致」 +✅ 只改被点名的面板;共享点先问「会不会伤到其它入口」 +``` + +## 2. 不擅自加小字与控件文案 + +界面上多出来的字都是产品决策。修改布局、修 bug、抽组件时 **默认不加** hint、灰字、tooltip、提示条、空状态说明、新 placeholder、新按钮名。 + +用户没写的字不要写。发现文案错了只在报告里指出。用户明确「去掉/改成」才动那一处。 + +## 3. 先复用,再复制,最后才新建 + +动手前用文件名 / 文案 / 路由搜现有实现(Web `src/components/ui`、PagePrimitives;小程序已有 `*-panel`、`utils/request.js`、日期与单位工具)。 + +| 情况 | 做法 | +|------|------| +| 已有同交互 | 复用或加参数,禁止再造一份日期轴 / 确认框 / 宫格 | +| 只有 70% 像 | 不要为了复用强行改公共组件(会伤 B 面);A 面本地实现或问要不要抽 | +| 两端都要 | 口径以服务端为准;UI 各用各端组件,禁止为复用把小程序逻辑塞进 Web 页 | + +禁止把页面拷成 `Xxx2` / `XxxCopy`。抽公共函数须仍被原调用方使用,不要抽完只留新调用、旧页行为漂移。 + +## 4. 按钮与请求:防抖、节流、互斥 + +每个会打接口或写库的入口都要有「连点不会连发」。优先用**进行中锁**(`submitting` / `saving`,按钮 `disabled` + 函数开头 `if (saving) return`),请求结束再解开(含失败)。不要只靠 CSS 防连点。 + +| 交互 | 默认 | +|------|------| +| 保存 / 确认 / 完成 / 无货 / 加单改单 / 登录 | 互斥锁,一次只允许一个在途写 | +| 搜索框 | 防抖(约 300ms)或只在确认/按钮时请求,禁止每个按键打接口 | +| 下拉刷新、进页 `show`、筛选连点 | 节流或合并;小程序进页用现成 `panelShowGate`(`beginPanelShow` / `endPanelShow`),不要再写一套 | +| 步进器、开关 | 以最后一次值为准,不要排队多次写 | + +禁止:无锁的 `bindtap` 连发 POST;列表 `useEffect` 无依赖乱刷;用 `setTimeout` 当业务锁却不清理。加载态必须在 `finally` 里按 **§5 代数** 收掉,避免旧请求把新页的 loading 关死。 + +## 5. 详情不得串行(过期响应禁写入) + +「详情串行」= 先开 A 再开 B,A 的慢请求后到,把 A 的明细/图/价写进 B,保存即改错单。真实事故见 `docs/design/20260911-order-detail-stale-fetch.md`(订单详情 `detailLoadGeneration`)。 + +凡是「按单据号 / 任务号 / 行 id 异步拉详情或子资源」,必须同时满足: + +1. **代数**:每次打开、切换、关闭递增 generation(或 AbortController)。 +2. **身份**:`await` 之后若 generation 已变、实体 id 已变、抽屉已关 → **不得** `setState` / `setData`。 +3. **保存**:明细仍在加载则拒绝;提交的 id 必须等于当前打开的 id。 +4. **列表**:筛选/翻页同样用 generation,禁止把上一页行渲染进下一页。 +5. **缓存**:按实体 id 分桶(如小程序 `itemsMap[pickCode]`),禁止一个全局 `detail` 对象不换 key 就灌数据。 + +```text +❌ open(A); 再 open(B); await A 的 items → setEditItems(B 的表被 A 污染) +❌ finally { setLoading(false) } 不看 generation(B 的 loading 被 A 关掉) +✅ const gen = ++ref; const code = x; await fetch; if (!isActive(gen, code)) return; +``` + +切 Tab、切首页模块、扫码换单、抽屉换行,都按同一条执行。 + +## 6. 收工前(改了界面就勾) + +- [ ] diff 里有没有用户没点名的页面 / 公共组件? +- [ ] 有没有多出来的小字、提示条、placeholder? +- [ ] 写操作有没有在途锁?搜索有没有防抖或确认才请求? +- [ ] 详情/列表异步回来有没有 generation + id 守卫? +- [ ] 能复用的组件有没有复制成第二份?共享组件会不会误伤 B 面? + +```text +❌ 为「更清楚」加灰字;改 A 顺手改 B;无锁连点保存;切单不丢弃过期请求;复制整页当复用 +✅ 只动 A;字用户点了才改;写操作有锁;过期响应当没发生;先搜现成组件 +``` diff --git a/.cursor/rules/inspection-processing-freeze.mdc b/.cursor/rules/inspection-processing-freeze.mdc new file mode 100644 index 0000000..2d3fd77 --- /dev/null +++ b/.cursor/rules/inspection-processing-freeze.mdc @@ -0,0 +1,43 @@ +--- +description: 验收与加工冻结;不合格不得入库;退回须拍照;验收不计损耗;勿改拒收 40→30 +alwaysApply: true +--- + +# 验收与加工(冻结) + +权威:[docs/design/20260918-inspection-processing-freeze.md](../../docs/design/20260918-inspection-processing-freeze.md) +对照:[docs/todo/20260915-模块流转总图与设计对照.md](../../docs/todo/20260915-模块流转总图与设计对照.md) §4 +硬门槛:`docs/design/20260915-inspection-inbound-requires-pass.md` + +**改下列任一行为前,必须先向用户说明拟改点并得到明确确认,禁止顺手改。** + +## 入库 + +- 评级**合格**才能入库;不合格未退回抛 `inspection_fail_cannot_inbound`。 +- 禁止恢复「不合格打标仍入库」。AI 仅初判,人工可改。 +- 点退回:订单 **40→30** 走重供;仓内加工成品不允许这条退回。 +- **退回也必须拍照**(2026-09-20 `6442b00d` 起):分类须拍又无照 → 400 `inspection_photo_required`「请先拍照验收」,**退回与入库同一门槛**,称台退回也不再跳过拍照。**禁止**把 `!isRejected` 加回闸门。合法豁免只有 `allowMissingPhotos: true` 三处:订单详情自动验收、待验补量回填、称台合并入库兄弟行。 +- 验收 **≠** 独立入库(无订单进仓不建 `inspections`)。 + +## 损耗 / 库存 / 采购单 + +- 验收 `loss_qty` 恒 0;损耗只在加工完工(毛重−净重)。 +- 仓内加工成品不入可领库存。 +- 合格→`purchase_status` 30,退回→32(与采购冻结一致)。 + +## 成本触发 + +`reconcileOrderPurchaseFromLatestInspections`:SKU×来源最近一次验收覆盖写入。验收不是账本唯一入口。改写入须同时过财务冻结。禁止再让 `coverUnfulfilledItemsAsInventoryForCompleted` 写 `stock_cover_qty`。 + +## 不要当待办 + +- 6 处直写 `order_status = 30` 的业务语义;「统一写入口」须单独立项。 +- 称重台改回 `weigh.recognize.catalog` 选择题。 +- 按已作废的「104 组超计」去改验收成本。 + +```text +❌ 不合格也能确认入库 +❌ 退回(拒收)免拍照 —— 与入库同门槛 +❌ 验收提交写损耗 +✅ 先说明拟改门槛/回退/入账;得同意后再改代码与本设计 +``` diff --git a/.cursor/rules/inventory-freeze.mdc b/.cursor/rules/inventory-freeze.mdc new file mode 100644 index 0000000..31fb461 --- /dev/null +++ b/.cursor/rules/inventory-freeze.mdc @@ -0,0 +1,63 @@ +--- +description: 库存管理冻结;流水类型无 CHECK 需同步 i18n;预留状态≠已扣库;pass_through 只读兼容;发车软库存不拦 +alwaysApply: true +--- + +# 库存管理(冻结) + +权威:[docs/design/20260920-inventory-freeze.md](../../docs/design/20260920-inventory-freeze.md) +对照:[docs/todo/20260915-模块流转总图与设计对照.md](../../docs/todo/20260915-模块流转总图与设计对照.md) §11 +模块说明:`docs/modules/10-库存管理.md` + +**改下列任一行为前,必须先向用户说明拟改点并得到明确确认,禁止顺手改。** + +## 入库 / 出库 + +- **入库唯一业务写入方是验收**(`inspection_in`);无订单走独立入库(`stock_in`,成本价必须 > 0)。 +- 出库:发车核货 `delivery_loading_out`(**幂等**)、分拣 `picking_out`、独立加工 `processing_out`、退货 `order_item_return`。 +- **发车扣库用 `softInventory`:库存不足不抛错、逐行尽量扣**——这是「库存不足不拦发车」的基础,**禁止改成硬拦**。 +- 结案出库:`ensureOrderInventorySettledOnComplete` **已有出库流水则不重复扣**,只消费预留;历史结案白名单路径**跳过 FIFO 只消费预留**。 + +## 流水类型(**无 DB CHECK**) + +- 新增类型**必须同一提交内**:① 在写入点显式使用;② 同步前端 `inventory.op.*` 三语文案(`zh-CN` / `en` / `id`)。 + ⚠️ 当前**缺** `order_item_return` / `return_undo` / `delivery_loading_restore` 三个 key → 流水页显示英文 key(按前端文案规则**只报告不擅自补**)。 +- **禁止**按「文档只列 6 种」去删在用的类型;**禁止**给该列加 CHECK 而不先清理历史遗留值。 +- 已知死代码/历史遗留:`delivery_loading_restore`(唯一写入方 `restoreInventoryForOrderDeparture` **无调用方**)、`return_undo`(代码已无写入方,库里有行)。**不要**据此认为「有恢复出库/撤销退货功能」。 + +## FIFO 与预留 + +- FIFO 顺序:`expiry_date ASC NULLS LAST, created_at ASC`;批次行 **`FOR UPDATE`**,影响行数为 0 时抛「库存并发冲突」。**禁止**去掉行锁或改成「先查后改」。 +- ⚠️ **库存不足时先部分扣减再抛错**(逐批 UPDATE + 写流水,之后才报错)——**调用方未包事务时已扣部分不可回退**;发车 `softInventory` 正是依赖这个语义。**不要**按「原子扣减」理解或改写。 +- 跳过两类行:**过手 SKU** 与 **本单该 SKU 曾走过手台账**(`orderSkuSkippedPassThroughLedger`,在发车扣库与分拣出库两条路径都生效)。 +- 预留状态:**`10` 待消费 / `20` 已消费或已扣库 / `30` 已消费或已覆盖**。 +- ⚠️ **`consumeReservationsForOrder` 只改 `status=20`,不写 `inventory_logs`、不扣库存**,且有 8 个调用点(含**分拣出库推进**,会在**发车之前**消费整单预留)。**禁止**把「预留已消费」当成「库存已扣」的证据(见 A1)。 +- 遗留清理 `cleanupStaleReservationsForCompletedOrders` 已接入 15 分钟 tick;**调用必须传 `branchCode`**(不传 WHERE 会退化为「本 schema 全部行」)。**禁止**删掉调度接入或去掉该传参。 + +## 过手 / 调整 / 权限 + +- `stock_mode` 只有 `pass_through` / `inventory`;**商品级过手 UI 已废弃(20260828),历史 `pass_through` 行只读兼容**——**禁止**把「过手」重新做成可选择项。 +- `POST /inventory/adjust`:**备注必填 + 双日志留痕**(`inventory_logs(adjust)` + `operation_logs(inventory_adjust)`);**已拣/已装车未出库时仍允许调高**(解除「出库缺库存 ↔ 禁止调高」死锁)——**这三条都不得移除**。 +- **库存表写权限已收窄**:经 `/api/data` 写 `inventory` / `inventory_logs` 须持 `inventory_manage` 或 `purchase_manage`;**禁止**把库存表加进「采购员账号整体放行」名单。 +- 注意:**改库存不止 `/inventory/adjust` 一条路**(通用数据接口在有权限时也能直写,会绕过备注必填与双日志)——见 A4。 + +## 溯源 + +- `/trace` 默认**当天入库日**(默认折叠),可切下单日;**独立入库只在入库日出现**;**服务端分页**;公开页 `/t/{批次号}` **无鉴权**。 +- 冻结:公开页**字段范围不得扩大**;内部页权限仅 `product_trace`。 + +## 已知异常(**不是**受保护口径) + +权威文 A1~A13(预留已消费但库存未扣的**出口** `consumed_only`、`/api/data` 可直改库存绕过审计、流水类型无 CHECK 持续漂移、发车兜底出库与结案取值优先级相反、`restoreInventoryForOrderDeparture` **死代码且类型名超列宽**、`stock_in_void`/`adjust` 归属写错、**缺口修补整个是死代码**、**`inventory_logs`/`inventory_reservations` 零 RLS**、FIFO 部分扣减语义、4 个服务裸事务、公开页泄露实际库存量、公开页 `outbound_count` 恒 0、表头 KPI 一半不随筛选)**修与不修由开发者裁决**。禁止把它们当正确现状冻结,也禁止顺手一起改。 + +```text +❌ 把发车扣库改成库存不足硬拦 +❌ 新增流水类型不同步 i18n / 按文档 6 种删在用类型 / 给该列加 CHECK +❌ 去掉 FIFO 的 FOR UPDATE / 把「部分扣减」当成原子语义 +❌ 把「预留已消费」当成库存已扣 +❌ 去掉遗留清理调度接入或 branchCode 传参 +❌ 移除 adjust 的备注必填 / 双日志 / 「已拣未出库允许调高」 +❌ 把「过手」做成可选 / 把库存表加进采购员整体放行 +❌ 接线 restoreInventoryForOrderDeparture 而不先扩 operation_type 列宽 +✅ 先说明拟改点、影响面(扣库 / 预留 / 台账 / 审计);得同意后再改 +``` diff --git a/.cursor/rules/local-db-must-not-overwrite-prod.mdc b/.cursor/rules/local-db-must-not-overwrite-prod.mdc new file mode 100644 index 0000000..e77bbfb --- /dev/null +++ b/.cursor/rules/local-db-must-not-overwrite-prod.mdc @@ -0,0 +1,85 @@ +--- +description: 严禁将本地/开发库数据写入线上库——整库恢复与定向覆盖一律禁止 +alwaysApply: true +--- + +# 本地库禁止覆盖线上库(硬规则) + +> 背景:AI 配置(模型参数)与 AI 提示词都存在**数据库**里,不是文件。 +> 一旦本地库内容被写进线上,会**静默覆盖**线上已调好的配置与提示词, +> 且当前**没有有效期内的审计可追溯**(`updated_by` 常为空),事后极难复原。 + +## 规则一:绝对禁止的方向 + +**任何「本地 / 开发 / 测试库 → 线上库」的数据写入,一律禁止。** 包括但不限于: + +| 禁止动作 | 说明 | +|----------|------| +| 整库恢复 | 把本地 `pg_dump` 用 `pg_restore` / `psql` 导入线上;`DROP DATABASE` + 重建 + 导入 | +| 定向覆盖 | 用本地查询结果 `UPDATE/INSERT` 线上 `system_configs`(含 `platform_llm_config`、`branch_llm_config`)与 AI 提示词表 | +| 批量数据搬运 | 任何把本地业务/配置数据"同步上去"的脚本或手工 SQL | +| 反向同步脚本 | 新增或改造出 `dev → prod` 方向的数据同步;**只允许 `prod → dev` 单向** | + +**唯一允许的数据库写入线上**:**迁移(`migrations/*.sql`)**。迁移只改结构/规则, +不得内嵌"用某份本地数据覆盖线上数据"的语句。 + +## 规则二:受保护对象(重点中的重点) + +线上这些位置**不得被本地内容覆盖**: + +| 对象 | 位置 | +|------|------| +| 平台模型参数 | `public.system_configs` 的 `platform_llm_config` | +| 分公司模型参数 | `<租户 schema>.system_configs` 的 `branch_llm_config`(及 `*_llm_config`) | +| AI 提示词(当前生效) | `<租户 schema>.ai_prompt_templates` | +| AI 提示词(版本历史) | `<租户 schema>.ai_prompt_revisions` | +| AI 提示词(分公司定制) | `<租户 schema>.ai_prompt_overrides` | +| 提示词内置默认值 | `server/src/prompts/defaults.ts`(**以 git 为准**,见规则三) | + +## 规则三:提示词的两处来源,改哪一处有讲究 + +提示词同时存在两处,取值优先级: + +``` +分公司覆盖(ai_prompt_overrides.enabled = true) + → 数据库已发布模板(ai_prompt_templates.status='published') + → 代码内置默认值(server/src/prompts/defaults.ts) +``` + +**改动规范**: + +- 改**内置默认值** → 只改 `server/src/prompts/defaults.ts`,走 git 评审与部署; +- 改**线上生效文案** → 必须走**发布流程**(升 `version`)。 + 因为 `ensureDefaultsSeeded` 的覆盖条件是: + + ```sql + WHEN status = 'published' AND version = 1 THEN <代码里的值> -- 会被部署覆盖 + ELSE system_template -- 保留库里的 + ``` + + 即 **`version = 1` 的提示词,每次部署都会被代码默认值覆盖**。直接在库里改却不升版本, + 改动会在下次部署时**静默丢失**。改完请确认 `version ≥ 2`。 + +## 规则四:动手前的强制确认清单 + +任何要写线上库的操作(含"看起来只是小修"),执行前必须逐条确认: + +1. 这是**迁移**吗?不是 → 停,先说明并取得明确批准。 +2. 涉及**规则二**列出的受保护对象吗?是 → 必须先备份目标行(含改前值)并写明回滚。 +3. 有**备份**吗?(`scripts/prod-backup-db.sh`)没有 → 先备份。 +4. 会执行 `DROP` / `TRUNCATE` / 无 `WHERE` 的 `UPDATE|DELETE` / `pg_restore` 吗? + 是 → **一律拒绝执行**,向开发者报告。 +5. 写完之后:`updated_by` / `updated_at` 是否被正确写入?(便于事后追溯) + +## 规则五:可以放心做的事 + +- `prod → dev` 单向同步(`sync-prod-to-dev.sh` / `sync-prod-db-to-local.ps1`); +- 对线上**只读**查询与分析(`SELECT`、`EXPLAIN`、查日志); +- 在本地库自由修改、测试 AI 配置与提示词(本地被覆盖无所谓,**线上不被覆盖才是底线**); +- 提交并推送代码到 git(推代码 ≠ 写线上库)。 + +## 相关文档 + +- [deploy-authorization.mdc](deploy-authorization.mdc):部署授权(未经命令不得上线) +- [finance-freeze.mdc](finance-freeze.mdc):财务逻辑冻结 +- [change-scope.mdc](change-scope.mdc):变更范围与变更清单 diff --git a/.cursor/rules/miniprogram.mdc b/.cursor/rules/miniprogram.mdc new file mode 100644 index 0000000..262f5fe --- /dev/null +++ b/.cursor/rules/miniprogram.mdc @@ -0,0 +1,25 @@ +--- +description: 微信小程序端约定(注册表、请求、角色入口) +globs: miniprogram/**/*.{js,json,wxml,wxss} +alwaysApply: false +--- + +# 小程序约定 + +## 结构 + +- 页面在 `miniprogram/pages/*`;首页入口注册:`miniprogram/modules/registry.js`。 +- 新功能:加页面四件套 → `app.json` pages → registry 按角色暴露。 +- 网络统一 `miniprogram/utils/request.js`;API 根地址来自 `config.js`(勿把生产密钥写进仓库)。 + +## 行为 + +- 登录态 JWT 与 Web 共用后端;401 引导重新登录,勿静默吞错导致白屏。 +- 订单状态文案与 `utils/constants.js` / Web `orderStatusLabels` 对齐(20–90;无 10)。 +- 仓配作业(备货/验收/分拣/配送/加工)以 `/api/mobile/*` 为准,业务规则在服务端,小程序只做展示与提交。 + +## 质量 + +- 避免未定义函数/缺失 util(历史 bug:如缺 `formatLocalDate` 导致加工页崩溃)。 +- 改权限开关时前后端一致:无权限隐藏入口,并禁用对应提交接口依赖的前端动作。 +- 界面改动遵守 [frontend-ui-discipline.mdc](frontend-ui-discipline.mdc);进页加载合并用 `utils/panelShowGate`。 diff --git a/.cursor/rules/ops-freeze.mdc b/.cursor/rules/ops-freeze.mdc new file mode 100644 index 0000000..6fa4484 --- /dev/null +++ b/.cursor/rules/ops-freeze.mdc @@ -0,0 +1,63 @@ +--- +description: 运营支撑冻结;售后自动单建单即终态不可再受理;异常工单≠订单状态;市场监控页面在运营接口在商品 +alwaysApply: true +--- + +# 运营支撑(冻结) + +权威:[docs/design/20260920-ops-freeze.md](../../docs/design/20260920-ops-freeze.md) +对照:[docs/todo/20260915-模块流转总图与设计对照.md](../../docs/todo/20260915-模块流转总图与设计对照.md) §12 +模块说明:`docs/modules/11-运营支撑.md` + +> ⚠️ **后端「有」`opsModule` 注册项,但它不挂任何路由**:`server/src/modules/businessModules.ts` 里确有 `export const opsModule`(`id: 'ops'`)并已并入 `ALL_BUSINESS_MODULES`;它**没有 `workflowApiPrefix`、没有 `mountWorkflowRoutes`**,所以**能力分挂订单 / 商品 / 平台三套路由**。**「后端没有注册项」是过期说法**——**不要新建第二个 ops 模块,也不要删这个注册项**。 + +**改下列任一行为前,必须先向用户说明拟改点并得到明确确认,禁止顺手改。** + +## 售后:三类自动单(建单即终态,不可再受理) + +| 类型 | 前缀 | 触发 | 锁定错误码 | +|---|---|---|---| +| 订单退货 | **`OIR_`** | 订单明细**入库后**退货 | **409 `order_return_locked`** | +| 独立入库作废 | **`SIV_`** | 独立入库未用删除 | **409 `spi_void_locked`** | +| 已入库改派 | **`OIS_`** | 已入库改派退供(采购红冲额,**不冲客户销售**) | **409 `inbound_switch_locked`** | + +- **建单即终态**:`status=30` + `handled_at` + `closed_at` 一次写齐;`handle_method` 实值为 **`order_item_return`**(「已红冲」只是 `reason` 文案)。 +- 锁定是**按类型判断**(`aftersale_type ∈ 三值`),状态判断只是兜底(「仅待受理可受理」);**三类错误码不同**——测试断言别写成统一码。 +- ⚠️ **该「不可再受理」不变量只在服务层成立**:`after_sales` 不在 `DENY_WRITE_TABLES`,经通用网关 `/api/data` 可裸 `UPDATE/DELETE` **绕过 409**;该旁路已被 `server/tests/routeLayerBoundary.test.ts` **pin 住**(要收紧须先裁决)。 +- **禁止**把三类改成可受理/可处理(意义就是**防二次冲账**);**禁止**改单号前缀;**禁止**改锁定码(会打断前端与测试)。 +- **日期口径两类**:客诉按**配送日**;三类自动单按**操作日 `created_at`**(保证当天做的操作当天可见)——**不得**把自动单改回按配送日。 +- 新增自动单类型必须同时定义:前缀、终态字段、锁定判定、日期口径。 + +## 售后:表与子表 + +- 主表是 **`after_sales`**(**不是** `after_sales_tickets`);子表 `after_sale_returns`(人工退货登记,`status` CHECK `10/20/90`)。 +- `after_sale_returns` **唯一写入方**为 `afterSaleLifecycleService.attachAfterSaleFulfillment`,**仅 `handle_method='return'` 触发**;**换货不进此表**。 +- 该表**全租户 0 行**(生产售后单全为系统自动单)→ 属「**表在、代码在、入口在,业务未走**」的**可用表**,**不得**据此删表或删代码。 +- **成本回冲 + 结算调整属 [finance-freeze](../../.cursor/rules/finance-freeze.mdc) 范围**——本模块只触发,改前必须走财务冻结流程。 + +## 异常 + +- 表 `exception_tickets`;**工单状态 ≠ 订单状态**,**不推进订单主状态**;异常与配送侧「异常」展示**可能并存但数据路径不同**(排查别混)。 +- 「不问数 / 补货建议 / AI 解析指标」小组件**已从异常页移除**(接口仍在平台路由)——**禁止**未获批准就加回(属前端功能/文案增删)。 + +## 市场监控(**页面在运营,接口在商品模块**) + +- 后端行情接口挂在**商品模块**;**不要在运营目录新建后端模块**。 +- 行情来源语义: + - 对照价默认由 **Ark** 按位置 + 商品名分批(**每批 ≤ 100**)估算,写 **`price_source='ai'`**; + - **只有 `external` / `supplier_avg` / `ai` 且未过期才黄橙红**;**`estimated` = 无可靠行情 → 不报警**; + - **刷新主路径不调 `MARKET_PRICE_API_URL`**;定时任务 **`rebase_only` 不调 Ark**。 +- **红灯阻断分配**开关:服务归属是 **`marketRedBlockConfigService`**(读写 `system_configs` 键 `market_red_block_enabled`,**默认开启**),`marketAllocationGuard` 只是**判定/读取方**;由**分配侧**读取——改判定要同时看 [订单与分配冻结对照](../../docs/订单与分配模块-冻结对照.md)。 +- 「我们的价格」可选手动监控**报价成本价或销售价**(`marketComparePriceBasisConfigService`,键 `market_compare_price_basis`,**默认 `cost`**)。 +- 三 Tab(价格指数 / 供应商趋势 / 当季推荐)+ 市场比价,共 **4** 个 tab;`tabChildren = ['', 'index', 'trend', 'recommend']`,按**经营分公司**打通。 +- ⚠️ `external` 是**休眠取值**(唯一写它的适配器全仓 0 导入,生产 0 行)——**不要**据「文档列了它」去实现外部行情接入。 + +```text +❌ 把三类自动单改成可受理 / 删 409 锁定 / 改单号前缀 +❌ 把自动单日期口径改回配送日 +❌ 把工单状态与订单状态合成一个状态机 +❌ 让 estimated 参与报警 / 让 rebase_only 调 Ark / 刷新主路径改回 MARKET_PRICE_API_URL +❌ 在运营目录新建后端模块 +❌ 未获批准加回异常页已移除的小组件 +✅ 先说明拟改点、影响面(是否触碰财务口径 / 分配);得同意后再改 +``` diff --git a/.cursor/rules/order-freeze.mdc b/.cursor/rules/order-freeze.mdc new file mode 100644 index 0000000..1fdbf60 --- /dev/null +++ b/.cursor/rules/order-freeze.mdc @@ -0,0 +1,64 @@ +--- +description: 订单与分配冻结;主链 20→30→40→45→50→60→90 勿自造;ORDER_STATUS_ALLOWED 的 40→30 异常边勿删;分配信号量重入检测与竞价 SAVEPOINT 勿回退 +alwaysApply: true +--- + +# 订单与分配(冻结) + +权威对照:[docs/订单与分配模块-冻结对照.md](../../docs/订单与分配模块-冻结对照.md)(模块冻结系列第 1 篇,**已定稿**) +对照权威:[docs/todo/20260915-模块流转总图与设计对照.md](../../docs/todo/20260915-模块流转总图与设计对照.md) §2 +模块说明:`docs/modules/01-订单与分配.md` +相关专项:[order-price-cost.mdc](./order-price-cost.mdc)(销售价 / 成本价,另一条独立冻结) + +**改下列任一行为前,必须先向用户说明拟改点并得到明确确认,禁止顺手改。** + +## 状态链(唯一权威 `server/src/modules/kernel/orderStatus.ts`) + +- 主链固定 **`20→30→40→45→50→60→90`**,**不得自造状态**;`70 / 80` 已废弃。 +- `ORDER_STATUS_ALLOWED` 里的 **`40: [45, 30]`**:`40→30` 是**合法的拒收回退异常边**,**勿删**。 + 历史教训:该边曾只存在于注释与裸 SQL 里,导致「按常量校验把真实流转拒掉」。 +- 校验入口唯一:`assertValidTransition(from, to)`,**仅** `orderWorkflowService.advanceOrderWorkflow` 调用; + 两个 HTTP 触发点:`orderRoutes.ts`(Web)、`mobileAdminRoutes.ts`(移动端管理)。 +- ⚠️ **45 与 50 都没有回退边**,而线上**真实存在**的回退走**裸 SQL、不经校验**: + `demotePrematureInspectionStatus`(50/45/40 → 30)、`repairMissingWarehousePickingForOrder`(50 → 45)。 + **禁止**把这两条回退接到 `advanceOrderWorkflow`(会立刻报「无法从状态 50 推进到 40」)。 + 要把回退边登记进常量,需先决策(这是 `40→30` 当年同一个坑)。 + +## 分配与竞价(两个 P0 的修复不得回退) + +- `withAllocationSlot` 有 **`AsyncLocalStorage` 重入检测**(重入时不再取信号量)——**勿删**;删了会重现「重入死锁 + 多占一槽」。 +- `tryAutoAwardAndAllocate` 在外层已有事务时改用 **SAVEPOINT**,无外层事务才 `BEGIN/COMMIT`——**禁止**改回裸 `BEGIN/COMMIT`(旧写法会把外层写入一起提交/冲掉)。 + +## 请求级共享连接(`TENANT_REQUEST_CLIENT=1`) + +- 路由/服务层**最外层**的裸 `BEGIN` 是安全的(租户中间件不开事务);但**内层**再 `BEGIN` 只会告警,裸 `ROLLBACK` 会**冲掉外层写入**。 +- 仓库已有三套**正确解药**,新增事务代码必须用其中之一,不要写第四种: + ① `if (ownsClient)` 守卫复用调用方连接;② `SAVEPOINT`(必须在外层事务内运行时);③ `getRawPoolConnect()` 拿独立连接。 +- 该 bug 类**全后端仍有约 97 处裸写法**未逐个甄别(权威文 §5.2)——**不得**当成「已清干净」,也**不得**在未获范围批准时批量改。 + +## 历史结案白名单(应急口子,勿扩大) + +- `server/src/config/historicalFinalizeAllowlist.json` 是**管理员白名单一键结案**:会把「不合格 + 有实收」的验收行**直接改判为合格**、**跳过**备货/签收闸门、强制推到 90。 +- 即:**白名单内的订单,「不合格不得入库」与「已入库 ⇒ 合格」这两个不变量对它不再成立**——这是**有意的例外**,不是「不合格不得入库」失效。 +- 白名单条目数**单调增长**(23 → 27),当前唯一守卫是一条**按精确条数**断言的测试。**禁止**擅自扩大;增删条目必须同步测试并说明原因。 + +## 死代码定性(待决,勿擅自处置) + +- `orderStatusDisplayService` 的 `computeEffectiveOrderStatus` 与 `pickDisplayOrderStatus` **生产调用方 0**(列表只返回存储态)。 + → 文档承诺的「45/50 展示层纠偏」**当前不生效**:误进的 40→50 在界面上没有任何遮挡。 +- 定性(有意移除 or 重构遗漏)**待开发者决定**;**禁止**擅自删除,也**禁止**擅自把调用加回去。 + +## 已知遗留(不是受保护口径) + +权威文 §4(P1 白名单治理、§4.4.2/§4.5 的 P1/P2)与 §5.3(过时测试断言、回退边登记、`bidAwardHoldSameTx.test.ts` 3500 字符窗口仅剩 52 字符余量、生产日志取证未做)**均未修**。禁止把它们当正确现状冻结,也禁止顺手一起改。 + +```text +❌ 自造状态 / 删掉 40→30 异常边 +❌ 把 50→30、50→45 的回退接到 advanceOrderWorkflow +❌ 删 withAllocationSlot 的重入检测 +❌ 把 tryAutoAwardAndAllocate 的 SAVEPOINT 改回裸 BEGIN/COMMIT +❌ 写第四种「共享连接下开事务」的写法 +❌ 把白名单当常规结案路径 / 擅自加条目 +❌ 擅自删或恢复 pickDisplayOrderStatus 调用 +✅ 先说明拟改点、影响面(状态流转 / 分配 / 竞价 / 白名单);得同意后再改 +``` diff --git a/.cursor/rules/order-price-cost.mdc b/.cursor/rules/order-price-cost.mdc new file mode 100644 index 0000000..2bc52f7 --- /dev/null +++ b/.cursor/rules/order-price-cost.mdc @@ -0,0 +1,36 @@ +--- +description: 订单销售价/成本价;成本 KPI 只认 cost_details 账本;unit_cost 为写缓存 +alwaysApply: true +--- + +# 订单销售价 / 成本价(一套账) + +权威设计:`docs/design/20260810-single-cost-ledger.md`(定稿)。 +旧文 `20260806-order-estimate-finance-overview.md` 中「KPI 读 unit_cost」**已废止**。 + +**改下列任一行为前,必须先向用户说明拟改点并得到明确确认,禁止顺手改。** + +## 销售价(落 `order_items`) + +- 展示:`COALESCE(NULLIF(locked_price,0), NULLIF(price,0), 0)` +- 权威列:`order_items.price` / `locked_price` +- 报价单改售价 **不** 回写已有订单行 + +## 成本(一套账) + +- **报表 / 看板 / 财务概览 / 成本管理 KPI 唯一权威:`cost_details`**(采购=`purchase`) +- `order_items.unit_cost`:**仅写缓存**(录单种子、备货/自采/验收/手工改价仍可写),经 `setOrderItemUnitCost*` 时同步 upsert 采购账本(`upsertOrderSkuPurchaseCostFromUnitCost`) +- 主文案统一「**采购成本**」;供应/自采拆分相加等于该数 +- 「所有成本」= 全账本合计(与看板同名同数) + +## 报价 `cost_price` 写回 + +| 入口 | 行为 | +|------|------| +| 备货改价等 | 仅补空报价;覆盖本单 `unit_cost` 并同步采购账 | +| 订单详情 / 录单手工改成本 | 可覆盖报价;写 `unit_cost` 并同步采购账 | + +## 改其它功能时 + +- 禁止再让概览/看板 KPI 读 `Σ qty×unit_cost` 作为商品成本。 +- 新写入成本须走 `setOrderItemUnitCost*` 或显式 `upsertOrderSkuPurchaseCostFromUnitCost`。 diff --git a/.cursor/rules/page-api-delivery.mdc b/.cursor/rules/page-api-delivery.mdc new file mode 100644 index 0000000..7c2d0cb --- /dev/null +++ b/.cursor/rules/page-api-delivery.mdc @@ -0,0 +1,49 @@ +--- +description: 新页面完整通路、提交注明接口对接、TODO: api 须带预计完成时间 +alwaysApply: true +--- + +# 页面与接口交付 + +## 新页面必须有完整通路 + +任何**新页面**提交时,必须至少包含一条「用户操作 → 前端调用 → 后端接口 → 数据返回 → 页面展示」的完整通路。 + +- 禁止只交静态壳 / Mock 占位却对外声称功能可用。 +- 若本期无法打通:页面不得合入「已完成」叙事;须在 PR 标明未对接,并按下方 `TODO: api` 规则标注预计完成时间。 + +```text +✅ 登录页:输入账号密码 → POST /api/login → 写 session → 跳转首页 +❌ 仅有登录 UI,按钮无请求或写死假数据且无接口说明 +``` + +## 提交信息须注明接口对接状态 + +commit message(及 PR 标题/摘要中对应条目)需写明对接状态,建议形如: + +```text +feat: 登录页,已对接 /api/login +feat: 成本总览 AI 根因,已对接 GET /api/workflow/cost/root-cause/:cycleCode +chore: 订单列表样式调整(无新接口) +``` + +- **已对接**:写出具体方法 + 路径(可多条)。 +- **无新接口**:写「无新接口」或「仅前端」。 +- **未对接/部分对接**:写清缺哪些接口,并配合 `TODO: api`。 + +## PR 中的 `TODO: api` 必须带预计完成时间 + +若 diff 出现 `// TODO: api`(或同等标记,如 `TODO(api)`、`FIXME: api`): + +1. 注释或 PR 描述中须附带**预计完成时间**(日期或里程碑,如 `预计 2026-07-20`)。 +2. 建议同时写清待接路径与阻塞原因。 + +```typescript +// ❌ BAD +// TODO: api + +// ✅ GOOD +// TODO: api 对接 POST /api/workflow/orders/export,预计 2026-07-20 +``` + +审查时:有 `TODO: api` 却无时间的,要求补全后再合入。 diff --git a/.cursor/rules/picking-freeze.mdc b/.cursor/rules/picking-freeze.mdc new file mode 100644 index 0000000..e978885 --- /dev/null +++ b/.cursor/rules/picking-freeze.mdc @@ -0,0 +1,40 @@ +--- +description: 分拣出库冻结;完成分拣不改订单计划量;不接 customer 拣货模式 +alwaysApply: true +--- + +# 分拣出库(冻结) + +权威:[docs/design/20260918-picking-freeze.md](../../docs/design/20260918-picking-freeze.md) +对照:[docs/todo/20260915-模块流转总图与设计对照.md](../../docs/todo/20260915-模块流转总图与设计对照.md) §5 +模块说明:`docs/modules/04-分拣出库.md` + +**改下列任一行为前,必须先向用户说明拟改点并得到明确确认,禁止顺手改。** + +## 完成分拣 + +- `confirmPickingComplete` **不写** `order_items.quantity` / `amount`,不在函数内改订单状态。 +- 推进 50 走 `tryAdvanceOrderToDelivery`。仓内行(含库存抵扣)必须挂拣货,直送核货单不算仓内完成。 + +## 模式与出库 + +- 拆单现码:`order` / `category` / `sku`。**禁止**再接 `customer` 拣货模式。 +- 分配规则的 `customer` 维可保留(按订单 ≈ 按客户)。 +- 界面无独立出库;`outbound-scan` 仅备用。发车兜底 `delivery_loading_out`。 +- 远程打印未完成单只写 progress,不 `complete`。 + +## 重量单位(「两」) + +- `isPickingWeightUnit` / 安卓 `WeighStationMatcher.isWeightUnit` / `src/utils/picking.ts` / `listUnpickedItems` 斤类 SQL **四处必须都认「两 / 市两」**(2026-09-20 `65e7c695` 补齐);称台 **1 kg = 20 两**。 +- 改任一处必须四处同改,并跑 `server/tests/pickingWeightUnit.test.ts`。残留仅 `jin`(不认,实测 0 行使用)。 + +## 不要当现网事实 + +- 对照曾写的容差 `value:80`、键 `picking_weigh_station_label_print`:无依据。缺省 percent 10%。 +- 历史库 `pick_status` 中间态为空:测 10/20/30 须造数。 + +```text +❌ 分拣完成回写订单计划量 +❌ 把出库步骤加回 Web 主流程 / 接上 customer 拆单 +✅ 先说明拟改点与是否误伤仓内拦门;得同意后再改 +``` diff --git a/.cursor/rules/platform-freeze.mdc b/.cursor/rules/platform-freeze.mdc new file mode 100644 index 0000000..84b205b --- /dev/null +++ b/.cursor/rules/platform-freeze.mdc @@ -0,0 +1,59 @@ +--- +description: 平台与系统冻结;新业务表必须进 tenant_business_tables(有迁移守卫);鉴权与数据访问策略;LLM/提示词读取顺序;落地路径一致 +alwaysApply: true +--- + +# 平台与系统(冻结) + +权威:[docs/design/20260920-platform-freeze.md](../../docs/design/20260920-platform-freeze.md) +对照:[docs/todo/20260915-模块流转总图与设计对照.md](../../docs/todo/20260915-模块流转总图与设计对照.md) §13 +模块说明:`docs/modules/12-平台与系统.md` + +> **本模块是分公司隔离与鉴权的配置中心——动它等于动所有模块。** 改下列任一行为前必须先说明并获明确确认,**禁止顺手改**。 + +## 租户与建号 + +- **新业务表必须写进 `public.tenant_business_tables()`**,不能只对存量 schema `CREATE TABLE`。 +- 迁移期**有断言守卫** `public.assert_tenant_template_matches_business_tables()`(失败即**中断迁移**,部署脚本不会重启 API)。历史事故:**BR004 曾少 3 张表**。**禁止**绕过或删除该断言。 + +## 鉴权与数据访问 + +- **客户门户(`@customer.meoo.local`)已彻底下线**:**禁止**恢复「零角色可登录」的例外(守卫已是 `assertHasRole`)。 +- 新增身份后缀/角色映射必须同时更新 `LOGIN_SUFFIXES` 与**落地路径**。 +- 四张名单分工:`ALLOWED_TABLES` / **`DENY_WRITE_TABLES`(禁写,即使有权限)** / `WRITE_PERMISSIONS` / `TENANT_PATH_TABLES`、`BRANCH_SCOPED_TABLES`。 +- ⚠️ **通用网关能写业务表(靠权限码,不是禁用路径)**,已知例子:`customers`(可绕过拒删与级联)、`inventory`/`inventory_logs`(可绕过备注必填与双日志)、`suppliers`。 + → **禁止**把「本应走专用接口」的表加进 `ALLOWED_TABLES` 而不先评估绕过面;**禁止**把已在 `DENY_WRITE_TABLES` 的结算/成本/退货类表移出。 +- 新增权限码必须同时更新权限目录与种子。 + +## LLM 配置与提示词 + +- LLM 运行时顺序固定:**分公司覆盖 → 平台默认 → `.env` 豆包 ARK(`ARK_*`)**。⚠️ **第三层不是 `LLM_*`(TokenHub)**——通用路径传的是 `envOpenAi: null` + `envArk`,读 `LLM_API_KEY`/`LLM_BASE_URL` 的兼容 runtime **除超管页展示外没有调用点**。平台默认**仅超管**可改。 +- 提示词解析顺序固定(`resolvePrompt`):**分公司覆盖 > 已发布 > 代码 DEFAULT**。 +- **线上生效文案必须走发布流程升 `version`**:`version = 1` 的提示词**每次部署都会被代码默认值覆盖**,直接改库不升版会**静默丢失**。内置默认值只改 `server/src/prompts/defaults.ts`。 +- `platform_llm_config` / `branch_llm_config` / `ai_prompt_*` 属**重点保护表**,禁止任何 dev → prod 数据写入(见 [local-db-must-not-overwrite-prod](../../.cursor/rules/local-db-must-not-overwrite-prod.mdc))。 + +## 落地路径与平台分公司 + +- 三处落地路径必须一致(`accountLoginService` / `authRouting.ts` / `unifiedLogin.ts`);**不变量:落地路径必须是该角色真能访问的路由**。现取值 **`super_admin → /system/config`**、`admin → /dashboard`。改任一处必须三处同改并跑 `server/tests/homePathConsistency.test.ts`。 +- **平台分公司禁止维护商品主数据与分类、禁止直接做业务录单**(两条路径都拦)。不得为方便测试放开;新增分公司数据表时必须同时纳入该拦截面。 + +## 其它 + +- **操作日志保留**:每日滚动删除 `operation_logs` 中早于一个月的行(默认 `calendar_month`,分批);**只删 `operation_logs`,不删 `inventory_logs`**(它是库存出库的唯一事实源)。**禁止**改为「一次全删」。 +- **字段级权限方案已移除且全仓无残留——除非产品明确重做,否则不得恢复。** +- 通知推送失败必须 `.catch` 记录,**不得吞掉调用方事务**。 + +## 已知异常(**不是**受保护口径) + +权威文 A1~A4(通用网关可绕专用接口、落地路径三处实现未合并、保留策略只覆盖 `operation_logs`、平台分公司拦截面可能漏挂)**修与不修由开发者裁决**。 + +```text +❌ 新增业务表不登记 tenant_business_tables / 删掉迁移名单守卫 +❌ 恢复客户门户登录或零角色例外 +❌ 把结算/成本表移出 DENY_WRITE_TABLES / 未评估就放行新表 +❌ 颠倒 LLM 或提示词读取顺序 / 直接改库让提示词生效 +❌ 把超管落地改回 /dashboard / 只改三处中的一处 +❌ 让平台分公司维护商品或录单 +❌ 把 inventory_logs 纳入操作日志保留删除 +✅ 先说明拟改点、影响面(影响全模块);得同意后再改 +``` diff --git a/.cursor/rules/product-freeze.mdc b/.cursor/rules/product-freeze.mdc new file mode 100644 index 0000000..ca33457 --- /dev/null +++ b/.cursor/rules/product-freeze.mdc @@ -0,0 +1,68 @@ +--- +description: 商品主数据冻结;档案不含价格;导入≤200串行无行数上限;触发器单向;共用范围权威在 share_mode +alwaysApply: true +--- + +# 商品主数据(冻结) + +权威:[docs/design/20260920-product-freeze.md](../../docs/design/20260920-product-freeze.md) +对照:[docs/todo/20260915-模块流转总图与设计对照.md](../../docs/todo/20260915-模块流转总图与设计对照.md) §8(**「未发现偏差」与「触发器双向同步 ✅」均为错**) +模块说明:`docs/modules/07-商品主数据.md` + +**改下列任一行为前,必须先向用户说明拟改点并得到明确确认,禁止顺手改。** + +## 档案与价格 + +- **商品档案不含销售价 / 成本价**:`skus` 与 `product_catalog` 实测**无** `sale_price` / `cost_price` 列,价格只在报价单条目表。**禁止**加回。 +- 前端 `SkuManagement.tsx` 有 `sale_price` / `cost_price` 死字段(10 处,写入恒被丢弃);同文件另 2 处属**报价单条目**,**不是**死字段,别一起删。 + +## 分公司隔离 + +- 分类编码强制 **`{branch_code}_` 前缀**(`ensureBranchCategoryCode`)。 +- **平台分公司(BR001)禁止维护商品与分类**(`platform_branch_no_product_catalog`),通用网关与 `catalog.ts` 两条路径都拦。 +- **禁止**去掉 `tenantScope.ts` 里 `sku_ai_image` 的 **7 处**专项隔离(去掉会跨分公司串读)。 + +## 批量导入(四条硬参数,勿改) + +- 写入分块 **≤200 条**;**串行**(`for await`,**禁止**改并发);单文件 **20MB**;**无行数上限**(有专门契约测试守着)。 +- 不导入编码、不导入成本价;分类不存在则去重后创建;同批同一发号。 + +## 口径与结构 + +- `pricing_unit` **服务端无写入点**(前端维护 + 触发器落 `skus`);回退链 `COALESCE(pc.pricing_unit, s.pricing_unit, pc.unit, s.unit, '斤')`,**注意空串 ≠ NULL**。 +- `pack_factors` 包装折算供备货单价归一。 +- `stock_mode` **只有 `pass_through` / `inventory` 可达**;「继承分类 `is_fresh`」**不可达**,别按它实现。 +- **`product_catalog` 是分类 + 商品同表**(`parent_code` 分层)→ 目录条数 ≥ `skus` 条数**属正常**。 +- 同步是**单向**:触发器只在 `product_catalog` 上;`skus` / `categories` 上**零触发器**。**禁止**加反向触发器。 +- **共用范围的权威在 `quality_reports.share_mode` / `share_key`**(由报告类型推导:检疫/检验/年检/批次 → `leaf_category`;农残 → `produce_day`;其余 `line`)。分类的 `quality_report_share_scope` 是**孤儿列**,不得当权威。 + +## 商品直送 + +- 谓词**两个条件同时成立、单客户维度**:`skus.direct_delivery = true` **且** `sku_direct_delivery_customers` 命中该订单客户。 +- 它同时决定「不进核货 / 不扣库 / 不建配送任务 / 走自采成本路径」——改谓词要连看配送与成本两份契约。 +- **商品直送 ≠ 供应商免入库**(`suppliers.skip_inbound`),**禁止**合并判定;**禁止**把客户名单改成全局生效。 + +## 删除商品 + +- **阻断 6 类**(`order_items`、`supplier_preparations`、`purchase_orders`、`inspections`、可用/在库>0 的 `inventory`、`customer_quote_sheet_items`)→ 409 `product_in_use`。 +- **清理 7 张**(`customer_sku_aliases`、`customer_processing_aliases`、`customer_sku_remarks`、`customer_skus`、`sku_suppliers`、零库存 `inventory`、`inventory_logs`)+ `product_catalog` + `skus`。 +- 新增含 `sku_code` 的表必须**并入阻断或清理清单之一**(实测库内 43 张,其余未处理)。 +- ⚠️ `safeDeleteBySku` 会**静默吞掉** `42P01` / `42703`——表名/列名写错不会报错,只会悄悄不清理。新增清理项**必须实测列存在**(`customer_processing_aliases` 就没有 `sku_code`,该项恒失败)。 + +## 不要当现网事实 + +- 「预置重量键只能停用」对 **DELETE** 成立(一律软删);但 `PUT /units/:unitCode` **原样透传** `is_weight` / `factor_to_base`,**无保护集校验**。 +- 重量单位在仓库里有**四套定义**:`unit_conversions.is_weight`、内置回退表、`isPickingWeightUnit`、`PROTECTED_WEIGHT_UNIT_CODES`。**「两」已于 2026-09-20 `65e7c695` 对齐**(`isPickingWeightUnit` 与称台均已认,三处都认,见 `docs/design/20260920-picking-liang-weight-unit.md`);残留只差 **`jin`**(`isPickingWeightUnit` 不认,三个租户实测 0 行使用)。大写 `KG` 各套都认(首行 `.toLowerCase()`)——此前写的「不认大写 `KG`」是**误报,已更正**。**禁止**新增第五套;改任一套前先裁决以哪套为准。 +- 对照 §8 的 `sku_ai_image` 七处**行号全错**、`pricing_unit` 空值数、死字段处数、表规模均**已漂移**,别按它核对。 +- 商品直送代码齐备但**零使用**(`direct_delivery=true` 0 条、名单 0 行)。 + +```text +❌ 把价格列加回 skus / product_catalog +❌ 把导入改成并发 / 加回行数上限 / 改 200 分块 +❌ 给 skus 或 categories 加反向触发器(改「双向」) +❌ 按分类的 quality_report_share_scope 判共用范围 +❌ 按「继承分类 is_fresh」实现 stock_mode +❌ 合并「商品直送」与「供应商免入库」 +❌ 新增第五套重量单位判定 +✅ 先说明拟改点、影响面(扣库/核货/成本/结案);得同意后再改 +``` diff --git a/.cursor/rules/purchase-prep-freeze.mdc b/.cursor/rules/purchase-prep-freeze.mdc new file mode 100644 index 0000000..db27cbe --- /dev/null +++ b/.cursor/rules/purchase-prep-freeze.mdc @@ -0,0 +1,37 @@ +--- +description: 采购与备货冻结;勿统一 purchase_status 谓词,完成自采写 20 而非 30 +alwaysApply: true +--- + +# 采购与备货(冻结) + +权威:[docs/design/20260918-purchase-prep-freeze.md](../../docs/design/20260918-purchase-prep-freeze.md) +对照:[docs/todo/20260915-模块流转总图与设计对照.md](../../docs/todo/20260915-模块流转总图与设计对照.md) §3 +模块说明:`docs/modules/02-采购与备货.md` + +**改下列任一行为前,必须先向用户说明拟改点并得到明确确认,禁止顺手改。** + +## 状态 + +- 完成自采 → `purchase_status = 20`(待验收),**不是 30**。 +- `30` / `32` 仅验收模块写(`inspectionComplianceService`)。运维脚本除外,勿当业务入口。 +- 待采可作废 = **10 或 32**(`isOpenPurchaseStatus`)。不要把 20/30/40 当待采。 + +## 谓词(2026-09-15 裁定:不是待修清单) + +四套 `purchase_status` 比较并存。**禁止**统一成 `IN (10,32)`(会把已完成采购误判为缺口)。 +对照标 ⛔ 的站点(分配补建自采、推进拦门、`po2` 展示兜底、复活作废单回 10)**不要**为「补 `<> 40`」而改。复活 40→10 是故意设计。 + +## 边界 + +- 不替代验收写库存入账 / 质检结果。 +- 不推进配送;订单主状态仍走 workflow。 +- Web 自采列表日期轴保持下单日;勿默改成配送日。 +- 仓内加工成品自采不可作废、列表成本展示 0。 +- 缺货转供勿编造未使用的 `source_type` 写入。 + +```text +❌ 把「有没有采购」改成只认 10/32 +❌ 完成自采直接写成 30 +✅ 先说明「改哪条谓词/状态、实测会误伤哪些行」;得同意后再改代码与本设计 +``` diff --git a/.cursor/rules/supplier-freeze.mdc b/.cursor/rules/supplier-freeze.mdc new file mode 100644 index 0000000..b9e8d94 --- /dev/null +++ b/.cursor/rules/supplier-freeze.mdc @@ -0,0 +1,58 @@ +--- +description: 供应商管理冻结;skip_inbound 与 direct_delivery 是两种货;经营品类无 branch_code;supplier_users 表禁删;无删除入口 +alwaysApply: true +--- + +# 供应商管理(冻结) + +权威:[docs/design/20260920-supplier-freeze.md](../../docs/design/20260920-supplier-freeze.md) +对照:[docs/todo/20260915-模块流转总图与设计对照.md](../../docs/todo/20260915-模块流转总图与设计对照.md) §10 +模块说明:`docs/modules/09-供应商管理.md` + +**改下列任一行为前,必须先向用户说明拟改点并得到明确确认,禁止顺手改。** + +## 隔离与主数据 + +- **`supplier_categories` 没有 `branch_code`**(实测列只有 id / supplier_code / category_code / is_primary / created_at)——分公司归属**经 `suppliers` 主表关联**实现。**禁止**给它加 `branch_code` 并据此改写分配查询。 +- ⚠️ **有删除入口,但无守卫、无级联**:前端 `handleDelete` 先删 `supplier_categories` 再删 `suppliers`,走 **`/api/data`**(`queryExecutor` 动态 `DELETE FROM`,所以 TS 源码 grep 不到字面量)。**没有**「有历史订单即拒删」、没有级联清单。 +- ⚠️ 前端注释「主档删除亦有 CASCADE」**在租户内不成立**(外键只有 `legacy_public` 有,`tenant_br*`/`tenant_template` 只有 pkey)→ 前端手动清品类那两行**是承重的,不得当冗余删掉**。 +- **扩大删除面必须先设计级联**(`supplier_statements` prod br002 441 行、`supplier_preparations`、`sku_suppliers`、`supplier_users` 都会成孤儿)。 +- ⛔ **`supplier_users` 表不得 DROP、不得改名**:删号链路先查/删它、再 `releaseSupplierIfOrphan`(其第一步又查该表),删表会让**整个删号接口 500**。 + +## 直送免入库(`skip_inbound`) + +- 它是**按供应商**的开关,**与商品级 `skus.direct_delivery` 是两种货,禁止合并判定**。 +- 三条同时成立、缺一即矛盾:**必拍照** / **不进验收待办** / **发车扣库跳过**。读取点分布在 `supplierSkipInbound.ts`(共享谓词)、`inventoryOutboundService`、`deliveryLoadingService`、`orderWorkflowFulfillmentService`、**`orderInspectionStateService`** —— 改谓词要**五处同看**。 + ⚠️ **不在** `inspectionComplianceService`(该文件实测 `skip_inbound` 出现 0 次),别去那里找。 +- ⚠️ **最高耦合面**:免入库备货完成可**间接推进订单状态并直接结案**(20→30→50→90),并触发**客户 + 供应商双边结算单**。改 `skip_inbound` 或备货完成判定前,必须同看配送与财务两份契约。 +- 免入库行**仍需 `order_status >= 50` 才能发车**,不得为直送开旁路。 + +## 分配与评分 + +- 经营品类是智能分配的**第三道滤网**(就近优先:本码 → 绑定码 → 一级分类);`sku_suppliers` 是**分类未命中时的兜底**。 +- ⚠️ **`sku_suppliers` 四个租户实测全 0 行** → 兜底路径当前**永不命中**。**禁止**因数据为空就删掉该查询分支(删了会让「分类未配置」的单彻底无供应商可选),也**禁止**未决定前给它补数据。 +- 综合分数:**列表页直接读快照,取不到就显示「—」**(`?? null` → `emDash`),**不显示等级回退值**;`GRADE_SCORE`(`S:98 A:95 B:85 C:75 D:50`,默认 75)**只用于 `supplierFulfillmentService` 的履约预测与分配降权**。 + ⚠️ **快照表实测 0 行** → 列表主指标当前对**所有**供应商都是「—」,不得当真实履约分使用。 +- 快照唯一写者是 `computeSupplierRatings`,唯一触发 `POST /workflow/supplier-rating/compute`(**无定时任务**),写入时顺带回写 `suppliers.rating`。 +- 六个分值列**只在快照表**,**禁止**写回 `suppliers` 主表新列(会造成双份真相)。 + +## 账号与停用 + +- `releaseSupplierIfOrphan` 三步前提**不得放宽**:① `supplier_users` 仍有绑定则**不释放**;② `company_name` **含「(供应商)」**才继续(只停用账号自动创建的主档);③ `UPDATE suppliers SET status = 0 WHERE status IN (1,10,20)`。 +- 集成 / 开放 API:**密钥类值不得**出现在日志、审计 `new_value`、前端响应或文档中;新增入口必须走既有鉴权中间件。 + +## 已知异常(**不是**受保护口径) + +权威文 A1~A8(评分快照 0 行致列表全显「—」、`sku_suppliers` 空转、**有删除入口但无守卫无级联**、停用前提保守、开放 API 未深审、经营品类无 `branch_code` 的改法陷阱、评分接口缺权限校验、`branch_code` 可空致快照重复累积)**修与不修由开发者裁决**。禁止把它们当正确现状冻结。 + +```text +❌ 合并「供应商免入库」与「商品直送」判定 +❌ 去掉免入库行的必拍 / 验收待办排除 / 扣库跳过任一条 +❌ 因 sku_suppliers 为空就删掉兜底查询分支 +❌ 把「综合分数」当真实履约分(列表实际显示「—」) +❌ 给 supplier_categories 加 branch_code 并改写分配 +❌ 扩大删除供应商的删除面而不先设计级联 +❌ 因前端注释说有 CASCADE 就删掉前端手动清品类那两行 +❌ DROP 或改名 supplier_users +✅ 先说明拟改点、影响面(分配 / 验收 / 扣库 / 结算);得同意后再改 +``` diff --git a/.cursor/rules/web-frontend.mdc b/.cursor/rules/web-frontend.mdc new file mode 100644 index 0000000..f911318 --- /dev/null +++ b/.cursor/rules/web-frontend.mdc @@ -0,0 +1,33 @@ +--- +description: React Web 管理端约定(菜单、权限、UI、数据访问) +globs: src/**/*,webpack.config.js +alwaysApply: false +--- + +# Web 前端约定 + +## 路由与菜单 + +- 页面入口:`src/modules/businessModules.ts` + `routes.tsx`;菜单权威 `src/config/menuCatalog.ts`。 +- 新增页面必须:menuKey、path、permission/roles、lazy page loader;改完同步 `docs/WEB_MODULES.md`。 +- 新增页面还必须满足 [page-api-delivery.mdc](page-api-delivery.mdc):至少一条用户操作到数据返回的完整通路;提交注明接口对接状态。 + +- 标题用 ``,勿写死与可配置菜单不一致的名字。 +- 受 `ProtectedRoute` / `PermissionGuard` 保护;权限码与 `permissionCatalog` / 后端种子一致。 + +## 数据访问 + +- 通过 `src/lib/localApiClient`(及现有 supabase 兼容层)访问 `/api/data`;复杂写走 `src/utils/workflowApi.ts`。 +- **禁止**用前端直写订单状态或绕过 workflow 做履约结案。 +- 列表请求注意竞态(generation / abort);删除确认用项目内 `confirmDialog`,勿新增裸 `window.confirm`。 +- 界面改动遵守 [frontend-ui-discipline.mdc](frontend-ui-discipline.mdc)(范围、复用、防抖、详情不得串单)。 + +## UI + +- 复用 `src/components/ui/*` 与现有 PagePrimitives;保持现有主题变量(含暗色),不另起一套设计体系。 +- 状态文案统一 `orderStatusLabels`;导出/打印与列表同一套标签。 +- 财务页缺口以 `docs/财务结算模块实现对照.md` 为准,勿在 UI 文案中夸大未实现能力(如完整发票中台、完整 GPS 轨迹)。 + +## 字段权限 + +- 字段级权限页面/服务已移除;不要恢复旧的 `FieldPermissionManagement` / `useFieldMask` 架构,除非产品明确重做。 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..1839600 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,26 @@ +# Docker 构建排除 +node_modules +.git +.gitignore +*.md +!DESIGN_SYSTEM.md +.env +.env.* +!.env.production +dist +server/dist +server/node_modules +server/uploads +server/.env +.todo +.plan +.idea +.vscode +*.log +.DS_Store +Thumbs.db +deploy +scripts +outputs +skills +ccf3bc4758e306cbe5b951165c84e0f8 diff --git a/.env.gitea.example b/.env.gitea.example new file mode 100644 index 0000000..e39ec20 --- /dev/null +++ b/.env.gitea.example @@ -0,0 +1,8 @@ +# Gitea push config (do not commit token to public repos) +# Copy to .env.gitea and fill in your values +GITEA_URL=https://git.xdjchuanhui.com +GITEA_USER=jxc +GITEA_PASS=awh20260815 +# GITEA_TOKEN also works as alias for GITEA_PASS +GITEA_REPO=ai-fresh-delivery +GITEA_COMMIT_MESSAGE=Update: your commit message \ No newline at end of file diff --git a/.env.production.example b/.env.production.example new file mode 100644 index 0000000..38ec2de --- /dev/null +++ b/.env.production.example @@ -0,0 +1,27 @@ +APP_PORT=8080 +POSTGRES_USER=canteen +POSTGRES_PASSWORD=CHANGE_ME_STRONG_PASSWORD +POSTGRES_DB=canteen_delivery +JWT_SECRET=CHANGE_ME_RANDOM_JWT_SECRET +LLM_PROVIDER=openai +LLM_BASE_URL=https://tokenhub.tencentmaas.com/v1 +LLM_API_KEY= +LLM_MODEL=deepseek/deepseek-v4-flash-vision-exp +LLM_VISION_MODEL=deepseek/deepseek-v4-flash-vision-exp +SPEECH_API_KEY= +ARK_API_KEY= +# ARK_API_KEYS=key1,key2 +# ARK_MODEL=doubao-seed-2-0-lite-260428 + +# 外部行情(生产对接第三方批发/农业部等) +# MARKET_PRICE_PROVIDER=generic_post +# MARKET_PRICE_API_URL=https://api.example.com/market/batch +# MARKET_PRICE_API_KEY= + +# 操作日志保留:不配按自然月。正整数按天(例 31)。0 关闭。不清理库存流水。 +# OPERATION_LOG_RETENTION_DAYS=31 + +# 发票验真(诺诺/阿里云/自建网关) +# INVOICE_VERIFY_PROVIDER=nuonuo +# INVOICE_VERIFY_API_URL=https://api.example.com/invoice/verify +# INVOICE_VERIFY_API_KEY= diff --git a/.env.split.example b/.env.split.example new file mode 100644 index 0000000..fd27bb4 --- /dev/null +++ b/.env.split.example @@ -0,0 +1,29 @@ +# 三端分离部署配置(局域网示例) +# 复制为 .env.split 后修改 IP 为实际局域网地址 + +# 前端 Nginx +WEB_PORT=8080 + +# 后端 API +API_PORT=3001 +# 浏览器访问的后端地址(必须是局域网内其他设备也能访问的 IP) +API_PUBLIC_URL=http://192.168.0.100:3001 +# 允许的前端来源,* 表示局域网调试方便;生产可改为 http://192.168.0.100:8080 +CORS_ORIGINS=* + +# 数据库(独立容器,仅 API 内网访问) +POSTGRES_USER=canteen +POSTGRES_PASSWORD=CHANGE_ME_STRONG_PASSWORD +POSTGRES_DB=canteen_delivery + +# 安全与 AI +JWT_SECRET=CHANGE_ME_RANDOM_JWT_SECRET +LLM_PROVIDER=openai +LLM_BASE_URL=https://tokenhub.tencentmaas.com/v1 +LLM_API_KEY= +LLM_MODEL=deepseek/deepseek-v4-flash-vision-exp +LLM_VISION_MODEL=deepseek/deepseek-v4-flash-vision-exp +SPEECH_API_KEY= +ARK_API_KEY= +# 操作日志保留:不配按自然月。正整数按天(例 31)。0 关闭。不清理库存流水。 +# OPERATION_LOG_RETENTION_DAYS=31 diff --git a/.env.tencent.example b/.env.tencent.example new file mode 100644 index 0000000..21259ca --- /dev/null +++ b/.env.tencent.example @@ -0,0 +1,14 @@ +# 腾讯云 API 密钥(CAM 子账号,最小权限) +# 复制为 .env.tencent 并填写,勿提交 Git +TENCENT_SECRET_ID=AKIDxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +TENCENT_SECRET_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + +# 生产 CVM(南京),由 tencent-prod-scan 自动发现后可选手填 +TENCENT_PROD_H5_IP=119.45.34.106 +TENCENT_PROD_API_IP=146.56.223.139 +# VPC 内网 IP(前端反代 API、后端连库均走内网) +TENCENT_PROD_H5_PRIVATE_IP=10.206.16.10 +TENCENT_PROD_API_PRIVATE_IP=10.206.16.9 +TENCENT_PROD_H5_INSTANCE=ins-9zdly5wm +TENCENT_PROD_API_INSTANCE=ins-dn3v0znu +TENCENT_REGION=ap-nanjing diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..eb8c0cf --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.sh text eol=lf diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..58d81b7 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,85 @@ +# 最小 CI 门禁(系统深度分析报告 P1-15 / A13) +# 门禁:server/web 双端 typecheck + vitest;小程序 JS 语法检查。 +# npm audit:critical 硬拦;high 仍观察(xlsx/传递依赖)。 +# lint:观察项,不硬拦存量 hooks 告警(C7 骨架)。 +name: CI + +on: + push: + branches: [main] + pull_request: + +jobs: + server: + name: server typecheck + tests + runs-on: ubuntu-latest + defaults: + run: + working-directory: server + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + cache-dependency-path: server/package-lock.json + - run: npm ci + - name: typecheck + run: npx tsc --noEmit + - name: vitest + run: npm test + + web: + name: web typecheck + tests + miniprogram syntax + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + cache-dependency-path: package-lock.json + - run: npm ci + - name: typecheck + run: npm run typecheck + - name: vitest + run: npm test + - name: miniprogram js syntax + run: find miniprogram -name '*.js' -not -path '*/node_modules/*' -print0 | xargs -0 -n 1 node --check + + # ESLint:存量 hooks warning 未清零前保持观察(continue-on-error)。 + # 约定:禁止靠抬高 max-warnings / 删除规则「变绿」;分批清零后在第四阶段再硬拦。 + lint: + name: eslint (观察项,C7 骨架) + runs-on: ubuntu-latest + continue-on-error: true + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + cache-dependency-path: package-lock.json + - run: npm ci + - name: lint + run: npm run lint + + # npm audit:critical 硬拦;high 及以下仍观察(xlsx/传递依赖) + audit: + name: npm audit (critical 硬拦) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - name: audit web (critical) + run: npm audit --audit-level=critical --package-lock-only + - name: audit server (critical) + run: cd server && npm audit --audit-level=critical --package-lock-only + - name: audit web (high 观察) + continue-on-error: true + run: npm audit --audit-level=high --package-lock-only + - name: audit server (high 观察) + continue-on-error: true + run: cd server && npm audit --audit-level=high --package-lock-only diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..660f5e1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,232 @@ +# 通用 +*.log +*.tmp +*.temp +*.swp +*.swo +*.bak +*.orig + +# 环境变量与密钥 +.env +.env.local +.env.*.local +.env.production +.env.split +.env.tencent +miniprogram/config.js +.env.gitea +server/.env +SecretKey.csv +*.csv.secret +id_rsa_tencent +id_rsa_tencent.pub +deploy/id_rsa_tencent +deploy/id_rsa_tencent.pub +deploy/小程序AppSecret.txt +deploy/*AppSecret* +.tools/ +*.pem +*.key + +# 系统文件 +.DS_Store +Thumbs.db + +# 编辑器与 IDE +.idea/ +.vscode/ + +# Node.js / JavaScript / TypeScript +node_modules/ +dist/ +build/ +server/uploads/ +.next/ +.nuxt/ +.cache/ +coverage/ +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +.pnpm-store/ +# npm 缓存目录(在 HOME 不可写的沙箱/CI 下用 npm_config_cache 指向仓库内) +.npm-cache/ + +# Python +__pycache__/ +*.py[cod] +*.pyo +*.pyd +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ +.venv/ +venv/ +env/ +ENV/ +pip-wheel-metadata/ +*.egg-info/ +.coverage +htmlcov/ + +# Java / Kotlin +target/ +*.class +*.jar +*.war +*.ear +.gradle/ +out/ +# 本地打称台 APK 时下载的 JDK / Gradle,不入库 +.tmp-android-build/ + +# Go +bin/ +*.test +coverage.out + +# C / C++ +*.o +*.obj +*.so +*.a +*.lib +*.dll +*.dylib +*.exe +CMakeFiles/ +CMakeCache.txt +cmake-build-*/ +compile_commands.json +Makefile + +# Rust +target/ + +# C# +*.user +*.suo +*.userosscache +*.sln.docstates +bin/ +obj/ + +# Ruby & PHP / Composer:`/vendor/` 仅忽略仓库根目录下的 vendor(不包含 src/pages/vendor/ 等) +.bundle/ +/vendor/ + +# OneDay 中间产物目录(文件处理时的临时文件,不需要持久化) +tmp/ + +# other +.stats +.config +.accesslog + +# 本地 SDK / 备份 / 探测(勿再入库) +UVCCamera-master/ +android-weigh-terminal.local-backup*/ +京源衡业称重系统Android SDK/ +.codebuddy/ +caprintutils/ +backups/ +stats.json +/tmp-*.js +server/scripts/_tmp-* +server/scripts/tmp-* +scripts/_tmp-* +server/*_backup_*.json + +# 示例/模板可入库;真实密钥永远忽略(勿用 ! 反忽略敏感文件) +!.env.tencent.example +!.env.gitea.example +!.env.production.example +!.env.split.example + +# 环境变量备份/临时副本:含真实密钥,一律忽略 +# (背景:server/.env.bak.<时间戳> 曾出现在工作区且未被覆盖,git add . 即会入库) +.env.bak +.env.bak.* +*.env.bak +*.env.bak.* +.env.old +.env.save +.env.tmp +.env.*.bak +.env.*.bak.* +server/.env.bak* +deploy/.env.bak* +tablet_logcat*.txt +carrot_test.* +last_capture.jpg +test_carrot_quality.js + +bench_models.js +bench_short.js +bench_floor.js +carrot_*.jpg + +.kimi-workflow-notes.md + +# Go 后端(server-go)与本地杂项 tools/;视觉数据集脚本放行 +tools/* +!tools/vision-dataset/ +!tools/vision-dataset/** +# 交付物与验证工具(2026-09-29):设计文档一致性的机械复验器 +# v3-flowmap = 功能全景图源码(data.js 是用户打开那份 HTML 的唯一数据源) +# design-consistency = check.py(60 条断言,把「正文+§十七+开工单 三处同改」变成门禁) +!tools/v3-flowmap/ +!tools/v3-flowmap/** +!tools/design-consistency/ +!tools/design-consistency/** +!tools/arch-diagram/ +!tools/arch-diagram/** +!tools/doc-preview/ +!tools/doc-preview/** +# 例外里再排掉 pyc:`!**` 会把 __pycache__ 也拉回来(曾误跟踪 check.cpython-312.pyc) +tools/design-consistency/__pycache__/ + +# 生产验收照导出的本地预训练数据(二进制,不入库) +datasets/ + +server-go/api.exe +server-go/server-go + +# 本地操作手册(勿入库) +操作文档.docx + +# 本地临时脚本与排查产物(不入库) +.local-scratch/ + +# 构建/日志/诊断产物(勿入库) +.gradle-home/ +.go-cache/ +.go/ +*.tar.gz +*.png +.log-analysis.txt +.tablet-full-logcat.txt +.tablet-full-logcat-utf8.txt +.tablet-logs-weigh.txt +serve-frontend.mjs +training-data/*.json + +# 本地 OTA/称端调试产物(勿入库) +.ota-staging/ + +# 部署前的临时备份目录(`*` 后缀命中不了 `deploy.bak.pre-sync/` 这种目录名) +# 背景:该目录 9 个文件里 8 个与已跟踪的 `deploy/` 逐字节相同, +# 唯一不同的 `PRODUCTION.md` 是**更旧**的「双活」版本(仓库版已是单活), +# 入库只会把文档改回错的版本。备份留在本地,勿提交。 +deploy.bak.*/ + +# 文档预览器(scripts/build-doc-view.py)的生成产物,勿入库: +# doc-view.html 由脚本从 docs/ 下的 md 生成 +# doc-view-stamp.txt 内容指纹,供页面轮询判断「文档已更新」 +# vendor/ 第三方库(mermaid.min.js,3.3MB)本地化,避免依赖 CDN +# 生成命令:python3 scripts/build-doc-view.py --watch +public/doc-view.html +public/doc-view-stamp.txt +public/vendor/ diff --git a/.gitkeep b/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..7549542 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +registry=https://registry.npmmirror.com diff --git a/.plan/68436d69-840d-47fe-b197-ff63a8c81047/plan.md b/.plan/68436d69-840d-47fe-b197-ff63a8c81047/plan.md new file mode 100644 index 0000000..0747761 --- /dev/null +++ b/.plan/68436d69-840d-47fe-b197-ff63a8c81047/plan.md @@ -0,0 +1,1102 @@ +# AI生鲜配送系统 - 详细开发计划 + +## 项目概述 + +**项目名称**: AI生鲜配送系统 +**目标用户**: 政企、学校、食堂等B2B客户 +**核心模式**: 周度/月度锁价模式,覆盖从客户下单到财务结算的全链路 +**技术栈**: React + Webpack + TypeScript + TailwindCSS + Meoo Cloud (Supabase) + +--- + +## 一、系统架构设计 + +### 1.1 多端架构 + +| 端 | 技术方案 | 登录方式 | 核心用户 | +|----|---------|---------|---------| +| 客户小程序 | React + 适配移动端 | 手机号一键登录 | 客户企业采购人员 | +| 供应商H5 | React + 响应式 | 手机号+密码/验证码 | 供应商发货人员 | +| 配送员H5/APP | React + PWA | 工号+验证码 | 配送员 | +| 管理端Web | React + 桌面布局 | 账号+密码+验证码 | 运营、财务、仓管等 | +| 超管独立端 | React + 安全加固 | 账号+密码+IP限制 | 系统管理员 | +| 审计只读端 | React + 只读视图 | 账号+密码+双因子 | 审计员 | + +### 1.2 核心数据主键体系 + +``` +cycle_code - 履约周期编码 (YYYY-WW / YYYY-MM) +order_code - 订单唯一编码 +customer_code - 客户企业编码 +supplier_code - 供应商编码 +sku_code - 商品标准编码 +purchase_code - 采购单编码 +statement_no - 结算单编码 +``` + +### 1.3 角色权限矩阵 (10个固定角色) + +| 角色 | 登录端 | 核心职责 | 账号管理权限 | +|-----|-------|---------|-------------| +| 客户 | 小程序 | 下单、签收、对账、售后 | 不可管理 | +| 供应商 | H5 | 接单、填采购成本、备货、发货 | 不可管理 | +| 采购员 | 管理端 | 紧急采购、补货、临时供应商对接 | 不可管理 | +| 分拣员 | 管理端/PDA | 验收4步、加工、损耗登记 | 不可管理 | +| 配送员 | H5/APP | 上架、GPS、签收、异常费用 | 不可管理 | +| 仓管员 | 管理端 | 库存盘点、报损、耗材领用 | 不可管理 | +| 财务/文员 | 管理端 | 成本核算、结算、发票 | 不可管理 | +| 运营管理员 | 管理端 | 流程管控、审核、配置 | 可管理客户、供应商、员工账号 | +| 超级管理员 | 独立端 | 系统配置、权限分配、数据修复 | 可管理所有账号 | +| 审计员 | 审计只读端 | 全量数据审计、合规检查 | 无任何写权限 | + +--- + +## 二、数据库设计 (核心表结构) + +### 2.1 用户与权限表 + +```sql +-- 用户角色表 +CREATE TABLE user_roles ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE, + role_type VARCHAR(20) NOT NULL, -- customer/supplier/purchaser/sorter/delivery/warehouse/finance/operator/superadmin/auditor + entity_code VARCHAR(50), -- 关联的客户/供应商编码 + created_at TIMESTAMPTZ DEFAULT NOW(), + updated_at TIMESTAMPTZ DEFAULT NOW() +); + +-- 客户企业表 +CREATE TABLE customers ( + customer_code VARCHAR(50) PRIMARY KEY, + company_name VARCHAR(200) NOT NULL, + unified_social_code VARCHAR(50) UNIQUE, + contact_name VARCHAR(100), + contact_phone VARCHAR(20), + address TEXT, + invoice_info JSONB, + status INTEGER DEFAULT 10, -- 10正常 20预算超额冻结 30逾期冻结 40禁用 50注销 + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- 供应商表 +CREATE TABLE suppliers ( + supplier_code VARCHAR(50) PRIMARY KEY, + company_name VARCHAR(200) NOT NULL, + contact_name VARCHAR(100), + contact_phone VARCHAR(20), + business_license_url TEXT, + food_license_url TEXT, + rating VARCHAR(5) DEFAULT 'B', -- S/A/B/C/D + quota_percent INTEGER DEFAULT 100, -- 配额百分比 + status INTEGER DEFAULT 10, -- 10正常 20冻结 30黑名单 + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- 供应商经营分类绑定 +CREATE TABLE supplier_categories ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + supplier_code VARCHAR(50) REFERENCES suppliers(supplier_code), + category_code VARCHAR(50) NOT NULL, + is_primary BOOLEAN DEFAULT false, + created_at TIMESTAMPTZ DEFAULT NOW() +); +``` + +### 2.2 商品与库存表 + +```sql +-- 商品分类表 +CREATE TABLE categories ( + category_code VARCHAR(50) PRIMARY KEY, + parent_code VARCHAR(50), -- 一级分类为空 + category_name VARCHAR(100) NOT NULL, + level INTEGER NOT NULL, -- 1一级 2二级 + sort_order INTEGER DEFAULT 0, + loss_threshold DECIMAL(5,2) DEFAULT 5.00, -- 损耗阈值% + is_fresh BOOLEAN DEFAULT true, -- 是否生鲜 + status INTEGER DEFAULT 1 +); + +-- SKU商品表 +CREATE TABLE skus ( + sku_code VARCHAR(50) PRIMARY KEY, + sku_name VARCHAR(200) NOT NULL, + category_code VARCHAR(50) REFERENCES categories(category_code), + unit VARCHAR(20) NOT NULL, -- 斤/公斤/个/袋/箱 + spec VARCHAR(100), -- 规格 + barcode VARCHAR(50), + image_url TEXT, + default_loss_threshold DECIMAL(5,2), + status INTEGER DEFAULT 1, -- 1启用 0停用 + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- 中标价格表 +CREATE TABLE bid_prices ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + bid_code VARCHAR(50) NOT NULL, + cycle_code VARCHAR(10) NOT NULL, + sku_code VARCHAR(50) REFERENCES skus(sku_code), + price DECIMAL(10,2) NOT NULL, + status INTEGER DEFAULT 1, -- 1生效 0失效 + created_by UUID, + created_at TIMESTAMPTZ DEFAULT NOW(), + UNIQUE(bid_code, cycle_code, sku_code) +); + +-- 商品映射库(别名映射) +CREATE TABLE sku_aliases ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + alias_name VARCHAR(100) NOT NULL, + sku_code VARCHAR(50) REFERENCES skus(sku_code), + is_primary BOOLEAN DEFAULT false, + usage_count INTEGER DEFAULT 0, + status INTEGER DEFAULT 1 +); + +-- 库存表 +CREATE TABLE inventory ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + sku_code VARCHAR(50) REFERENCES skus(sku_code), + batch_no VARCHAR(50) NOT NULL, + warehouse_code VARCHAR(50), + quantity DECIMAL(10,2) NOT NULL DEFAULT 0, + available_qty DECIMAL(10,2) NOT NULL DEFAULT 0, + production_date DATE, + expiry_date DATE, + supplier_code VARCHAR(50), + cost_price DECIMAL(10,2), + status INTEGER DEFAULT 1, + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- 库存流水表 +CREATE TABLE inventory_logs ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + sku_code VARCHAR(50), + batch_no VARCHAR(50), + operation_type VARCHAR(20), -- in/out/loss/adjust + quantity DECIMAL(10,2), + before_qty DECIMAL(10,2), + after_qty DECIMAL(10,2), + related_order_code VARCHAR(50), + operator_id UUID, + remark TEXT, + created_at TIMESTAMPTZ DEFAULT NOW() +); +``` + +### 2.3 订单与履约表 + +```sql +-- 订单主表 +CREATE TABLE orders ( + order_code VARCHAR(50) PRIMARY KEY, + cycle_code VARCHAR(10) NOT NULL, + bid_code VARCHAR(50) NOT NULL, + customer_code VARCHAR(50) REFERENCES customers(customer_code), + order_status INTEGER DEFAULT 10, -- 10待下单 20已下单待分配 30已分配待备货 40已备货待验收 50已验收待配送 60已配送待签收 70已签收待核算 80已核算待结算 90已结算 + total_amount DECIMAL(12,2) DEFAULT 0, + total_weight DECIMAL(10,2) DEFAULT 0, + delivery_address TEXT, + delivery_date DATE, + delivery_time_slot VARCHAR(50), -- 配送时段 + remark TEXT, + created_by UUID, + created_at TIMESTAMPTZ DEFAULT NOW(), + updated_at TIMESTAMPTZ DEFAULT NOW() +); + +-- 订单明细表 +CREATE TABLE order_items ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + order_code VARCHAR(50) REFERENCES orders(order_code), + sku_code VARCHAR(50) REFERENCES skus(sku_code), + quantity DECIMAL(10,2) NOT NULL, + unit VARCHAR(20), + price DECIMAL(10,2) NOT NULL, + amount DECIMAL(12,2) NOT NULL, + supplier_code VARCHAR(50), + item_status INTEGER DEFAULT 10, -- 10待分配 20已分配 30已备货 40已验收 50已配送 60已完成 + sort_order INTEGER DEFAULT 0, + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- 供应商备货记录 +CREATE TABLE supplier_preparations ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + order_code VARCHAR(50), + sku_code VARCHAR(50), + supplier_code VARCHAR(50), + prepare_qty DECIMAL(10,2), -- 备货数量 + purchase_price DECIMAL(10,2), -- 采购单价 + prepare_status INTEGER DEFAULT 10, -- 10待备货 20备货中 30已完成 + ai_review_status INTEGER DEFAULT 10, -- 10待审核 20通过 30驳回 + prepare_time TIMESTAMPTZ, + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- 验收记录表 +CREATE TABLE inspections ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + order_code VARCHAR(50), + sku_code VARCHAR(50), + batch_no VARCHAR(50), + supplier_code VARCHAR(50), + prepare_qty DECIMAL(10,2), -- 备货数量 + actual_qty DECIMAL(10,2), -- 实际验收数量 + quality_rating VARCHAR(5), -- A/B/C/D + loss_qty DECIMAL(10,2) DEFAULT 0, -- 损耗数量 + loss_reason VARCHAR(50), -- 自然/供应商/操作/异常 + inspection_photos TEXT[], -- 照片URL数组 + inspector_id UUID, + inspection_time TIMESTAMPTZ, + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- 加工记录表 +CREATE TABLE processing_logs ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + order_code VARCHAR(50), + sku_code VARCHAR(50), + gross_weight DECIMAL(10,2), -- 毛重 + net_weight DECIMAL(10,2), -- 净重 + yield_rate DECIMAL(5,2), -- 出成率% + process_fee DECIMAL(10,2), -- 加工费 + process_type VARCHAR(50), -- 清洗/切割/包装 + operator_id UUID, + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- 配送任务表 +CREATE TABLE delivery_tasks ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + task_code VARCHAR(50) UNIQUE NOT NULL, + order_code VARCHAR(50), + delivery_id UUID, -- 配送员ID + vehicle_code VARCHAR(50), + route_plan JSONB, -- 路线规划 + task_status INTEGER DEFAULT 10, -- 10待配送 20配送中 30已完成 + start_time TIMESTAMPTZ, + end_time TIMESTAMPTZ, + gps_track JSONB, -- GPS轨迹 + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- 签收记录表 +CREATE TABLE sign_records ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + order_code VARCHAR(50), + delivery_sign_time TIMESTAMPTZ, -- 配送员签收时间 + delivery_sign_photo TEXT, -- 配送员签收照片 + delivery_gps JSONB, -- 配送员GPS + customer_sign_time TIMESTAMPTZ, -- 客户签收时间 + customer_sign_method VARCHAR(20), -- 指纹/面容/密码 + sign_status INTEGER DEFAULT 10, -- 10待签收 20配送员已签 30客户已签 40双方已签 + created_at TIMESTAMPTZ DEFAULT NOW() +); +``` + +### 2.4 成本与财务表 + +```sql +-- 成本明细表 +CREATE TABLE cost_details ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + cycle_code VARCHAR(10) NOT NULL, + order_code VARCHAR(50), + cost_type VARCHAR(50) NOT NULL, -- purchase/supplier_emergency/self_base/rent/vehicle/salary/equipment/packaging/other + cost_subtype VARCHAR(50), + amount DECIMAL(12,2) NOT NULL, + allocation_method VARCHAR(20), -- amount/weight/mileage/quantity + allocation_ratio DECIMAL(5,2), + allocated_amount DECIMAL(12,2), + voucher_url TEXT, + inputter_id UUID, + auditor_id UUID, + status INTEGER DEFAULT 10, -- 10待审核 20已审核 30已锁定 + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- 固定成本录入表 +CREATE TABLE fixed_costs ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + cycle_code VARCHAR(10) NOT NULL, + cost_type VARCHAR(50) NOT NULL, + budget_amount DECIMAL(12,2), + actual_amount DECIMAL(12,2), + allocation_method VARCHAR(20), + voucher_urls TEXT[], + inputter_id UUID, + status INTEGER DEFAULT 10, + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- 客户结算单 +CREATE TABLE customer_statements ( + statement_no VARCHAR(50) PRIMARY KEY, + cycle_code VARCHAR(10) NOT NULL, + customer_code VARCHAR(50), + total_amount DECIMAL(12,2), + paid_amount DECIMAL(12,2) DEFAULT 0, + unpaid_amount DECIMAL(12,2), + statement_status INTEGER DEFAULT 10, -- 10待确认 20已确认 30已开票 40已收款 + due_date DATE, + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- 供应商结算单 +CREATE TABLE supplier_statements ( + statement_no VARCHAR(50) PRIMARY KEY, + cycle_code VARCHAR(10) NOT NULL, + supplier_code VARCHAR(50), + total_amount DECIMAL(12,2), + deduction_amount DECIMAL(12,2) DEFAULT 0, + payable_amount DECIMAL(12,2), + statement_status INTEGER DEFAULT 10, -- 10待确认 20已确认 30已开票 40已付款 + due_date DATE, + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- 发票记录表 +CREATE TABLE invoices ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + invoice_no VARCHAR(50) NOT NULL, + invoice_type VARCHAR(20), -- input/output + statement_no VARCHAR(50), + amount DECIMAL(12,2), + tax_rate DECIMAL(5,2), + tax_amount DECIMAL(12,2), + invoice_url TEXT, + ocr_data JSONB, + verify_status INTEGER DEFAULT 10, -- 10待核验 20已核验 30核验失败 + created_at TIMESTAMPTZ DEFAULT NOW() +); +``` + +### 2.5 售后与异常表 + +```sql +-- 售后单表 +CREATE TABLE after_sales ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + aftersale_code VARCHAR(50) UNIQUE NOT NULL, + order_code VARCHAR(50), + customer_code VARCHAR(50), + aftersale_type VARCHAR(20), -- shortage/damage/wrong/missing + sku_code VARCHAR(50), + quantity DECIMAL(10,2), + amount DECIMAL(12,2), + reason TEXT, + photos TEXT[], + responsibility VARCHAR(20), -- supplier/delivery/platform + handle_method VARCHAR(20), -- refund/replace/compensate + handle_amount DECIMAL(12,2), + status INTEGER DEFAULT 10, -- 10待处理 20处理中 30已完成 40已关闭 + created_at TIMESTAMPTZ DEFAULT NOW(), + closed_at TIMESTAMPTZ +); + +-- 异常工单表 +CREATE TABLE exception_tickets ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + ticket_code VARCHAR(50) UNIQUE NOT NULL, + ticket_type VARCHAR(50) NOT NULL, -- stockout/aftersale/inspection_diff/delivery_exception/cost_exception/overdue/settlement_dispute/purchase + related_order_code VARCHAR(50), + priority INTEGER DEFAULT 3, -- 1紧急 2高 3普通 + ticket_status INTEGER DEFAULT 10, -- 10待处理 20处理中 30已处理 + handler_id UUID, + handle_remark TEXT, + created_at TIMESTAMPTZ DEFAULT NOW(), + updated_at TIMESTAMPTZ DEFAULT NOW() +); +``` + +### 2.6 系统配置与日志表 + +```sql +-- 系统配置表 +CREATE TABLE system_configs ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + config_key VARCHAR(100) UNIQUE NOT NULL, + config_value JSONB NOT NULL, + config_group VARCHAR(50), -- purchase/order/cost/inventory/system + description TEXT, + updated_by UUID, + updated_at TIMESTAMPTZ DEFAULT NOW() +); + +-- 操作日志表 +CREATE TABLE operation_logs ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + operator_id UUID, + operator_name VARCHAR(100), + operator_role VARCHAR(20), + operation_type VARCHAR(50), + target_table VARCHAR(50), + target_id VARCHAR(50), + old_value JSONB, + new_value JSONB, + ip_address VARCHAR(50), + trace_id VARCHAR(100), + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- 消息通知表 +CREATE TABLE notifications ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID, + notify_type VARCHAR(50), + title VARCHAR(200), + content TEXT, + is_read BOOLEAN DEFAULT false, + related_order_code VARCHAR(50), + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- AI预测参数表 +CREATE TABLE ai_params ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + param_name VARCHAR(100) NOT NULL, + param_value JSONB NOT NULL, + version INTEGER DEFAULT 1, + is_active BOOLEAN DEFAULT true, + created_at TIMESTAMPTZ DEFAULT NOW() +); +``` + +--- + +## 三、分阶段开发计划 + +### Phase 1: 核心闭环 (第1-8周) + +**目标**: 实现"下单→配送→结算"最小闭环 + +#### Week 1-2: 基础架构与商品体系 + +**M18 商品分类管理模块** +- [ ] 分类层级管理页面 (一级/二级分类CRUD) +- [ ] 分类属性配置 (损耗阈值、默认供应商、效期管理) +- [ ] 分类排序与停用功能 +- [ ] 分类批量导入导出 + +**M19 商品基础管理模块** +- [ ] SKU基础属性管理 (编码、名称、单位、规格、条码) +- [ ] 商品图片上传与管理 +- [ ] 商品状态管理 (启用/停用) +- [ ] 商品批量导入模板下载与导入 + +**M20 商品映射库管理模块** +- [ ] 别名→SKU映射关系维护 +- [ ] 一对多映射冲突检测 +- [ ] 候选映射审核 (AI自学习结果) +- [ ] 映射使用频次统计 + +#### Week 3-4: 客户与供应商管理 + +**M16 客户管理模块** +- [ ] 客户企业档案创建 (企业名称、统一社会信用代码、联系人) +- [ ] 客户子账号管理 (主账号、子账号CRUD) +- [ ] 预算管控设置 (按客户+履约周期) +- [ ] 客户状态管理 (正常/冻结/禁用/注销) +- [ ] 账期配置 (30/45/60天) + +**M9 供应商管理模块** +- [ ] 供应商入驻流程 (资质提交→初审→实地考察→终审) +- [ ] 供应商资质管理 (营业执照、食品经营许可证) +- [ ] 供应商评级体系 (S/A/B/C/D五级) +- [ ] 供应商配额动态调整 +- [ ] 供应商黑名单管理 +- [ ] 供应商经营分类绑定 + +#### Week 5-6: 订单核心流程 + +**M1 客户下单模块 (小程序端)** +- [ ] 多渠道下单入口 (语音/文字/手动) +- [ ] AI商品匹配与预算校验 +- [ ] 履约周期价格锁定 +- [ ] 预算超额预警 (80%预警/95%拦截) +- [ ] 订单模板管理 (常用订单一键复用) +- [ ] 历史订单复购 +- [ ] 订单修改与版本管理 +- [ ] 订单打印功能 + +**M2 订单处理+智能采购模块 (管理端)** +- [ ] 订单智能拆合单 +- [ ] 按分类自动分配供应商 +- [ ] AI采购量测算 +- [ ] 缺货换品流程 (同品类/同价/同质) +- [ ] 防漏品检测机制 +- [ ] 分配明细预览与确认 + +**M3 供应商备货管控模块 (供应商H5)** +- [ ] 待接单任务列表 +- [ ] 备货中任务管理 +- [ ] 采购单价与备货数量录入 +- [ ] AI初审触发 +- [ ] 超时预警与违约记录 +- [ ] 换品申请发起 + +#### Week 7-8: 验收配送与结算 + +**M4 验收分拣+加工+损耗确权模块 (管理端/PDA)** +- [ ] 验收四步流程 (拍照→扫码分拣→加工→二次称重) +- [ ] 验收照片自动水印 +- [ ] AI质量评级 (A/B/C/D) +- [ ] 生鲜专项质检标准 +- [ ] 加工费用与出成率计算 +- [ ] 损耗确权判定 (自然/供应商/操作/异常) + +**M5 配送履约模块 (配送员H5/APP)** +- [ ] 配送任务分配与接收 +- [ ] 扫码出库核验 +- [ ] GPS轨迹实时采集 +- [ ] AI路径规划 +- [ ] 异常费用录入 +- [ ] 双签收机制 (配送员+客户) +- [ ] 配送实时追踪 + +**M8 财务结算模块 (管理端)** +- [ ] 客户月结/周结账单生成 +- [ ] 供应商结算单生成 +- [ ] 发票上传与OCR识别 +- [ ] 发票验真 +- [ ] 已付未付台账 +- [ ] 账龄分析 + +--- + +### Phase 2: 成本与财务 (第9-14周) + +**目标**: 全成本核算体系上线 + +#### Week 9-10: 成本核算体系 + +**M7 成本核算模块** +- [ ] 采购成本归集 (供应商+采购员录入) +- [ ] 运营间接成本归集 +- [ ] 成本分摊算法实现 (按金额/重量/里程) +- [ ] 订单毛利计算 +- [ ] 客户履约周期毛利汇总 +- [ ] 负毛利预警 +- [ ] 售后成本回冲机制 +- [ ] 实时成本贯通展示 + +**M29 固定成本录入模块 (财务专用)** +- [ ] 固定成本分类录入 (房租/车辆/工资/设备/耗材) +- [ ] 成本凭证上传 +- [ ] 预算vs实际对比 +- [ ] 成本追加与确认 + +**M30 成本调整与审批模块** +- [ ] 成本调整申请发起 +- [ ] 调整审批流程 +- [ ] 调整后毛利重算 +- [ ] 调整历史记录 + +#### Week 11-12: 库存与采购 + +**M10 库存周转与盘点模块** +- [ ] 入库管理 (自动入库/手动入库) +- [ ] 出库管理 (FIFO原则) +- [ ] 效期三级预警 (7天/3天/过期) +- [ ] 库存上下限预警 +- [ ] 盘点计划制定与执行 +- [ ] 盘点差异处理 +- [ ] 在库报损管理 +- [ ] 批次追溯查询 + +**M22 采购管理模块 (紧急/补货)** +- [ ] 采购单自动生成触发 +- [ ] 采购单执行流程 +- [ ] 临时供应商管理 +- [ ] 采购审批流程 +- [ ] 采购成本回写 + +#### Week 13-14: 发票与财务完善 + +**M11 发票管理模块** +- [ ] 进项发票管理 (供应商侧) +- [ ] 销项发票管理 (客户侧) +- [ ] 发票OCR识别 +- [ ] 发票验真对接 +- [ ] 发票红冲流程 +- [ ] 发票台账统计 +- [ ] 开票提醒与跟进 + +--- + +### Phase 3: AI与智能 (第15-20周) + +**目标**: AI辅助决策上线 + +#### Week 15-16: AI飞轮与数据看板 + +**AI数据飞轮实现** +- [ ] 实时数据采集与结构化 +- [ ] 每日凌晨批量建模 (季节系数/采购系数/评分权重) +- [ ] 智能参数落地应用 +- [ ] 业务结果反向回写 +- [ ] 模型版本管理与回滚 + +**M15 AI数据看板 & 履约周期复盘模块** +- [ ] 今日订单概览看板 +- [ ] 采购偏差监控 +- [ ] 损耗TOP榜 +- [ ] 成本结构饼图 +- [ ] 毛利排行 +- [ ] 指标下钻分析 +- [ ] 自动预警配置 +- [ ] AI复盘报告生成 (日报/周报/月报) + +#### Week 17-18: 消息与异常 + +**M12 消息通知中心** +- [ ] 消息模板管理 +- [ ] 多渠道通知 (站内信/短信/邮件/APP推送) +- [ ] 触发场景配置 +- [ ] 发送策略设置 (免打扰时段/失败重试) +- [ ] 发送记录查询 + +**M28 异常工单处理中心** +- [ ] 异常工单聚合展示 +- [ ] 优先级自动排序 +- [ ] 工单超时升级 +- [ ] 一键跳转处理 +- [ ] 工单转派与备注 +- [ ] 处理历史记录 + +#### Week 19-20: 售后与数据完善 + +**M6 售后客诉与退货管理模块** +- [ ] 售后单发起 (小程序端) +- [ ] 售后类型判定 (少货/坏货/错货/未配送) +- [ ] 责任方判定 +- [ ] 处理单生成 (补货/退款/扣款) +- [ ] 退货流程管理 + +--- + +### Phase 4: 完善与加固 (第21-26周) + +**目标**: 系统完善与安全加固 + +#### Week 21-22: 数据与文件管理 + +**M13 数据导入导出中心** +- [ ] 标准模板下载 +- [ ] Excel批量导入 (异步校验) +- [ ] 大数据量分批导出 +- [ ] 导入导出记录 + +**M14 操作日志审计模块** +- [ ] 全操作留痕记录 +- [ ] 日志加密存储 +- [ ] 多条件组合查询 +- [ ] 异常操作实时告警 +- [ ] 日志归档管理 + +**M24 文件管理模块** +- [ ] 云存储对接 (OSS/COS) +- [ ] 文件分类存储 +- [ ] 访问控制与防盗链 +- [ ] 敏感文件加密 +- [ ] 临时文件自动清理 + +#### Week 23-24: 系统配置与定时任务 + +**M23 系统配置管理模块** +- [ ] 核心配置项管理 (损耗阈值/异常阈值/评分权重) +- [ ] 配置分组展示 +- [ ] 配置变更日志 +- [ ] 一键恢复默认 + +**M25 定时任务管理模块** +- [ ] 定时任务列表展示 +- [ ] 任务手动触发 +- [ ] 任务暂停/恢复 +- [ ] 执行日志记录 +- [ ] 失败告警 + +**M26 数据归档清理模块** +- [ ] 归档策略配置 +- [ ] 自动归档执行 +- [ ] 归档数据查询 +- [ ] 数据清理审批 + +#### Week 25-26: 监控与降级 + +**M27 第三方接口监控模块** +- [ ] 接口调用日志记录 +- [ ] 接口性能监控 +- [ ] 错误率告警 +- [ ] 响应时间告警 + +**降级与应急设计** +- [ ] 四级降级策略实现 +- [ ] 各角色降级功能矩阵 +- [ ] 应急权限开放规则 +- [ ] 离线同步机制 +- [ ] 降级恢复数据补偿 +- [ ] 自动检测与恢复 + +--- + +### Phase 5: 验收上线 (第27-30周) + +**目标**: 全功能验收通过,正式投产 + +#### Week 27-28: 测试与优化 + +- [ ] 功能完整性测试 (30个模块全覆盖) +- [ ] 成本精准性测试 (手工核算对比) +- [ ] 权限隔离测试 (越权拦截验证) +- [ ] 异常场景测试 +- [ ] 日志完备性验证 +- [ ] 降级切换测试 +- [ ] 性能压力测试 +- [ ] 安全渗透测试 + +#### Week 29: UAT与数据迁移 + +- [ ] UAT环境部署 +- [ ] 用户验收测试 +- [ ] 历史数据迁移 +- [ ] 数据校验与对账 + +#### Week 30: 灰度上线 + +- [ ] 生产环境部署 +- [ ] 灰度发布策略 +- [ ] 监控与回滚预案 +- [ ] 正式上线 + +--- + +## 四、前端页面清单 + +### 4.1 客户小程序端 (Customer MiniApp) + +| 页面 | 功能描述 | 优先级 | +|-----|---------|-------| +| 登录页 | 手机号一键登录 | P0 | +| 首页 | 待签收订单、快捷下单入口 | P0 | +| 商品浏览 | 分类浏览、搜索、商品详情 | P0 | +| 语音下单 | 语音录入、AI识别确认 | P0 | +| 文字下单 | 文字录入、AI匹配确认 | P0 | +| 手动下单 | 商品选择、数量输入、购物车 | P0 | +| 订单确认 | 价格确认、配送地址、时间选择 | P0 | +| 订单列表 | 全部/待签收/已完成订单 | P0 | +| 订单详情 | 订单状态跟踪、商品明细 | P0 | +| 周期账单 | 履约周期账单查看、确认 | P0 | +| 售后申请 | 发起售后、上传凭证 | P0 | +| 售后记录 | 售后进度查询 | P1 | +| 个人中心 | 企业信息、子账号管理 | P1 | +| 订单模板 | 常用订单模板管理 | P1 | +| 消息通知 | 系统通知列表 | P1 | + +### 4.2 供应商H5端 (Supplier H5) + +| 页面 | 功能描述 | 优先级 | +|-----|---------|-------| +| 登录页 | 手机号+密码/验证码登录 | P0 | +| 首页 | 待接单任务、备货中任务、结算单 | P0 | +| 待接单 | 订单列表、接单/拒单操作 | P0 | +| 备货中 | 备货数量录入、采购成本填写 | P0 | +| 换品申请 | 缺货换品发起、客户确认 | P0 | +| 结算单 | 结算明细查看、对账确认 | P0 | +| 资质维护 | 资质证件上传、年检提醒 | P1 | +| 消息通知 | 任务提醒、结算通知 | P1 | + +### 4.3 配送员H5/APP端 (Delivery H5/APP) + +| 页面 | 功能描述 | 优先级 | +|-----|---------|-------| +| 登录页 | 工号+验证码登录 | P0 | +| 首页 | 待配送任务、已完成配送 | P0 | +| 任务列表 | 今日配送任务列表 | P0 | +| 配送详情 | 订单明细、客户信息、导航 | P0 | +| 扫码出库 | 扫码核验、出库确认 | P0 | +| GPS配送 | 实时定位、轨迹上传 | P0 | +| 签收确认 | 拍照签收、电子签名 | P0 | +| 异常上报 | 配送异常、费用录入 | P0 | +| 路线规划 | AI最优路线展示 | P1 | +| 消息通知 | 任务分配、异常提醒 | P1 | + +### 4.4 管理端Web (Management Web) + +#### 交易履约域 +| 页面 | 功能描述 | 优先级 | +|-----|---------|-------| +| 订单管理 | 订单列表、状态筛选、详情查看 | P0 | +| 订单分配 | 智能分配、手动调整、分配确认 | P0 | +| 验收管理 | 验收任务、照片查看、质量评级 | P0 | +| 分拣管理 | 分拣任务、扫码分拣、异常处理 | P0 | +| 加工管理 | 加工任务、出成率计算 | P0 | +| 配送管理 | 配送任务分配、轨迹查看、签收确认 | P0 | +| 售后管理 | 售后单处理、责任判定、退款处理 | P0 | + +#### 成本核算域 +| 页面 | 功能描述 | 优先级 | +|-----|---------|-------| +| 成本核算 | 订单成本明细、毛利计算 | P0 | +| 固定成本 | 周期固定成本录入、审核 | P0 | +| 成本调整 | 成本调整申请、审批 | P0 | +| 客户结算 | 客户账单生成、对账、收款 | P0 | +| 供应商结算 | 供应商账单生成、对账、付款 | P0 | +| 发票管理 | 发票录入、验真、红冲 | P0 | + +#### 商品与库存域 +| 页面 | 功能描述 | 优先级 | +|-----|---------|-------| +| 分类管理 | 商品分类CRUD、属性配置 | P0 | +| SKU管理 | 商品档案、价格维护、状态管理 | P0 | +| 映射库 | 别名映射维护、候选映射审核 | P0 | +| 库存管理 | 库存查询、预警、流水 | P0 | +| 入库管理 | 入库单、批次管理 | P0 | +| 出库管理 | 出库单、FIFO执行 | P0 | +| 盘点管理 | 盘点计划、执行、差异处理 | P0 | +| 报损管理 | 报损申请、审核、成本归集 | P0 | + +#### 供应商与客户域 +| 页面 | 功能描述 | 优先级 | +|-----|---------|-------| +| 客户管理 | 客户档案、子账号、预算、账期 | P0 | +| 供应商管理 | 供应商档案、资质、评级、配额 | P0 | +| 采购管理 | 采购单、紧急采购、临时供应商 | P0 | +| 配送员管理 | 配送员档案、排班、绩效 | P1 | + +#### 数据与智能域 +| 页面 | 功能描述 | 优先级 | +|-----|---------|-------| +| 数据看板 | 经营指标、趋势分析、预警 | P0 | +| AI复盘报告 | 日报/周报/月报生成与查看 | P0 | +| 异常工单 | 工单聚合、处理、升级 | P0 | +| 操作日志 | 全量日志查询、审计 | P0 | + +#### 系统运维域 +| 页面 | 功能描述 | 优先级 | +|-----|---------|-------| +| 系统配置 | 全局参数配置、变更日志 | P0 | +| 消息中心 | 消息模板、发送记录 | P0 | +| 导入导出 | 数据导入导出中心 | P0 | +| 文件管理 | 文件存储管理 | P0 | +| 定时任务 | 任务管理、执行日志 | P0 | +| 数据归档 | 归档策略、执行记录 | P0 | +| 接口监控 | 第三方接口状态监控 | P0 | + +### 4.5 超管独立端 (Super Admin) + +| 页面 | 功能描述 | 优先级 | +|-----|---------|-------| +| 登录页 | 账号+密码+IP限制 | P0 | +| 系统状态 | 服务状态监控、降级开关 | P0 | +| 账号管理 | 全量账号CRUD、权限分配 | P0 | +| 角色管理 | 角色权限配置 | P0 | +| 审计日志 | 全量操作审计 | P0 | +| 数据修复 | 数据修正工具 | P0 | +| 系统配置 | 全局系统参数 | P0 | + +### 4.6 审计只读端 (Audit Readonly) + +| 页面 | 功能描述 | 优先级 | +|-----|---------|-------| +| 登录页 | 账号+密码+双因子 | P0 | +| 审计日志 | 全量日志查询分析 | P0 | +| 归档数据 | 历史归档数据查询 | P0 | +| 合规报表 | 合规性检查报表 | P0 | + +--- + +## 五、核心功能详细设计 + +### 5.1 订单状态机 (硬编码) + +``` +正常流程: +10待下单 → 20已下单待分配 → 30已分配待备货 → 40已备货待验收 → 50已验收待配送 → 60已配送待签收 → 70已签收待核算 → 80已核算待结算 → 90已结算 + +异常分支: +→ 已取消 (客户取消) +→ 已作废 (运营作废) +→ 售后中 (售后处理中) +``` + +### 5.2 成本分摊算法 (硬编码) + +```typescript +// 订单直接成本 +orderDirectCost = Σ(商品采购成本单价 × 实际验收数量) + 专项费用 + +// 订单间接成本 (按金额) +orderIndirectCostByAmount = (周期间接成本总额) × (该订单金额 / 周期订单总金额) + +// 订单间接成本 (按重量) +orderIndirectCostByWeight = (周期间接成本总额) × (该订单总重量 / 周期总重量) + +// 订单间接成本 (按里程) +orderIndirectCostByMileage = (周期车辆总成本) × (该订单配送里程 / 周期总配送里程) + +// 订单总成本 +orderTotalCost = orderDirectCost + allocatedIndirectCost + +// 订单毛利 +orderProfit = customerSettlementPrice - orderTotalCost +``` + +### 5.3 AI核心公式 (硬编码) + +```typescript +// 采购量测算 +suggestedPurchaseQty = CEIL( + 近4周同期日均销量 × 季节系数 × 节假日权重 × (1 + 标准损耗率) +) +// 合规区间: ±5% + +// 供应商综合得分 +supplierScore = + 履约准时率 × 0.3 + + 质量合格率 × 0.3 + + 价格合规得分 × 0.2 + + 低损耗率 × 0.1 + + 无异常记录 × 0.1 + +// 异常订单识别 +isAbnormalOrder = |当日单品下单量 / 近4周同日均值 - 1| ≥ 0.3 +``` + +### 5.4 双签收机制 + +``` +1) 配送员APP签收: 拍照 + 电子签名 + GPS坐标 + 时间戳 +2) 客户小程序签收: 查看明细后确认 + 指纹/面容验证 + +处理规则: +- 仅配送员签收: 24小时后自动确认,标注"客户未确认" +- 仅客户签收: 以配送员最后GPS坐标+时间戳作为默认签收记录 +- 双方均签收: 视为无争议签收,数据锁定不可改 +- 争议处理: 签收后24小时内可发起售后,超时关闭 +``` + +--- + +## 六、技术实现要点 + +### 6.1 前端技术栈 + +- **框架**: React 18 + TypeScript +- **构建**: Webpack 5 +- **样式**: TailwindCSS +- **路由**: React Router (Hash模式) +- **状态**: React Context + Hooks +- **图表**: Recharts +- **动画**: Framer Motion +- **图标**: Lucide React +- **日期**: date-fns + +### 6.2 后端服务 (Meoo Cloud) + +- **数据库**: PostgreSQL (Supabase) +- **认证**: Supabase Auth (用户名+密码模式) +- **存储**: Supabase Storage (文件上传) +- **实时**: Supabase Realtime (消息推送) +- **边缘函数**: Edge Functions (AI接口、定时任务) + +### 6.3 安全与合规 + +- **数据防篡改**: 关键数据只允许追加,禁止编辑接口 +- **权限隔离**: 10大角色严格分离,所有动作留痕 +- **密码策略**: 8位以上,大小写+数字,历史5次不可重复 +- **会话管理**: 超管可强制下线任意用户 +- **审计日志**: 所有操作永久留存,加密存储 + +### 6.4 降级策略 + +| 级别 | 触发条件 | 核心影响 | +|-----|---------|---------| +| L1轻微 | 非核心服务超时 | 跳过服务,异步重试 | +| L2核心 | AI服务不可用 | 使用预设参数,转人工 | +| L3严重 | 数据库故障 | 应急数据暂存,恢复同步 | +| L4紧急 | 全链路不可用 | 离线PDA作业,本地存储 | + +--- + +## 七、交付物清单 + +### 7.1 文档交付物 + +1. 系统设计文档 (本文档) +2. 数据库设计文档 (ER图、表结构) +3. 接口API文档 (RESTful API规范) +4. 前端组件文档 (组件库使用说明) +5. 测试用例文档 +6. 部署运维手册 +7. 用户操作手册 + +### 7.2 代码交付物 + +1. 前端源代码 (React项目) +2. 数据库迁移脚本 +3. Edge Functions源代码 +4. 配置文件 (环境变量、系统配置) + +### 7.3 测试交付物 + +1. 单元测试报告 +2. 集成测试报告 +3. 性能测试报告 +4. 安全测试报告 +5. UAT验收报告 + +--- + +## 八、风险与应对 + +| 风险 | 影响 | 应对措施 | +|-----|------|---------| +| 需求变更频繁 | 进度延误 | 分阶段交付,每阶段验收后再进入下一阶段 | +| 成本核算复杂 | 数据不准确 | 建立测试数据集,手工核算对比验证 | +| 多角色权限复杂 | 安全漏洞 | 权限矩阵硬编码,越权测试100%覆盖 | +| AI模型不准确 | 采购偏差大 | 设置±5%容错区间,人工兜底机制 | +| 系统性能瓶颈 | 用户体验差 | 分页查询、数据归档、缓存优化 | +| 第三方服务不稳定 | 功能不可用 | 四级降级策略,离线作业能力 | + +--- + +## 九、验收标准 + +### 9.1 功能验收 + +- [ ] 所有30个模块按设计实现,无缺失 +- [ ] 10大角色权限隔离,越权测试100%被拦截 +- [ ] 订单全流程闭环:下单→分配→备货→验收→配送→签收→核算→结算 +- [ ] 成本核算精准:手工核算与系统结果误差≤0.01元 + +### 9.2 性能验收 + +- [ ] 订单提交响应时间 < 2秒 +- [ ] 报表导出 < 30秒 (万级数据) +- [ ] 并发用户支持 100+ +- [ ] 页面加载时间 < 3秒 + +### 9.3 安全验收 + +- [ ] 所有关键操作留痕,日志不可篡改 +- [ ] 密码策略强制执行 +- [ ] 会话管理完善,支持强制下线 +- [ ] 数据防篡改机制生效 + +### 9.4 可用性验收 + +- [ ] 降级切换测试通过,数据无丢失 +- [ ] 离线作业能力验证 +- [ ] 数据备份与恢复测试 +- [ ] 7×24小时监控告警 + +--- + +**计划制定日期**: 2026-06-06 +**计划版本**: V1.0 +**制定人**: AI开发助手 diff --git a/.todo/042ea5eb-ea98-49c2-8ee7-f335092e7234/todos.json b/.todo/042ea5eb-ea98-49c2-8ee7-f335092e7234/todos.json new file mode 100644 index 0000000..dac5f12 --- /dev/null +++ b/.todo/042ea5eb-ea98-49c2-8ee7-f335092e7234/todos.json @@ -0,0 +1,92 @@ +[ + { + "id": "1", + "content": "全面评估系统现状 - 检查所有模块完成度", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "订单管理模块 - 完善订单分配、竞价管理", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "采购管理模块 - 打通供应商备货到采购单流程", + "status": "completed", + "priority": "high" + }, + { + "id": "4", + "content": "验收管理模块 - 完整质检流程", + "status": "completed", + "priority": "high" + }, + { + "id": "5", + "content": "加工管理模块 - 加工流程跟踪", + "status": "completed", + "priority": "high" + }, + { + "id": "6", + "content": "配送管理模块 - 配送调度系统", + "status": "in_progress", + "priority": "high" + }, + { + "id": "7", + "content": "售后管理模块 - 售后处理流程", + "status": "completed", + "priority": "high" + }, + { + "id": "8", + "content": "异常管理模块 - 异常处理机制", + "status": "completed", + "priority": "high" + }, + { + "id": "9", + "content": "库存管理模块 - 库存追踪", + "status": "pending", + "priority": "high" + }, + { + "id": "10", + "content": "仓库管理模块 - 仓库操作", + "status": "pending", + "priority": "high" + }, + { + "id": "11", + "content": "财务管理模块 - 成本核算与结算", + "status": "completed", + "priority": "high" + }, + { + "id": "12", + "content": "AI功能模块 - 语音/图片识别", + "status": "pending", + "priority": "high" + }, + { + "id": "13", + "content": "系统管理模块 - 用户权限配置", + "status": "pending", + "priority": "high" + }, + { + "id": "14", + "content": "数据打通 - 确保全链路数据流转", + "status": "pending", + "priority": "high" + }, + { + "id": "15", + "content": "最终验证 - 全系统功能测试", + "status": "pending", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/0ebb73b9-56b1-4b43-a6fb-4e74978278b9/todos.json b/.todo/0ebb73b9-56b1-4b43-a6fb-4e74978278b9/todos.json new file mode 100644 index 0000000..e79a639 --- /dev/null +++ b/.todo/0ebb73b9-56b1-4b43-a6fb-4e74978278b9/todos.json @@ -0,0 +1,56 @@ +[ + { + "id": "1", + "content": "简化 AfterSalesManagement.tsx - 删除副标题和售后时效提醒", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "简化 ExceptionManagement.tsx - 删除副标题和优先级说明", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "检查并简化 FinanceOverview.tsx", + "status": "completed", + "priority": "high" + }, + { + "id": "4", + "content": "检查并简化 CostManagement.tsx", + "status": "completed", + "priority": "medium" + }, + { + "id": "5", + "content": "检查并简化 FixedCostManagement.tsx", + "status": "completed", + "priority": "medium" + }, + { + "id": "6", + "content": "检查并简化 CostAdjustmentManagement.tsx", + "status": "completed", + "priority": "medium" + }, + { + "id": "7", + "content": "检查并简化 CustomerStatements.tsx", + "status": "completed", + "priority": "medium" + }, + { + "id": "8", + "content": "检查并简化 SupplierStatements.tsx", + "status": "completed", + "priority": "medium" + }, + { + "id": "9", + "content": "检查并简化 InvoiceManagement.tsx", + "status": "completed", + "priority": "medium" + } +] \ No newline at end of file diff --git a/.todo/23167ead-f393-44f1-833f-b8ef7169cef9/todos.json b/.todo/23167ead-f393-44f1-833f-b8ef7169cef9/todos.json new file mode 100644 index 0000000..aaee40f --- /dev/null +++ b/.todo/23167ead-f393-44f1-833f-b8ef7169cef9/todos.json @@ -0,0 +1,38 @@ +[ + { + "id": "1", + "content": "替换Dashboard虚拟数据为真实数据", + "status": "in_progress", + "priority": "high" + }, + { + "id": "2", + "content": "替换订单管理虚拟数据", + "status": "pending", + "priority": "high" + }, + { + "id": "3", + "content": "替换验收管理虚拟数据", + "status": "pending", + "priority": "high" + }, + { + "id": "4", + "content": "替换采购管理虚拟数据", + "status": "pending", + "priority": "high" + }, + { + "id": "5", + "content": "替换配送管理虚拟数据", + "status": "pending", + "priority": "medium" + }, + { + "id": "6", + "content": "验证所有功能使用真实数据", + "status": "pending", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/263390ae-2d1c-4d11-b1db-9693ea8df5ea/todos.json b/.todo/263390ae-2d1c-4d11-b1db-9693ea8df5ea/todos.json new file mode 100644 index 0000000..f612e93 --- /dev/null +++ b/.todo/263390ae-2d1c-4d11-b1db-9693ea8df5ea/todos.json @@ -0,0 +1,26 @@ +[ + { + "id": "1", + "content": "简化 InventoryManagement.tsx - 删除第69行副标题", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "简化 DeliveryManagement.tsx - 删除副标题、功能卡片、地图说明、签收步骤说明", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "简化 DeliveryPersonManagement.tsx - 删除第58-60行副标题", + "status": "completed", + "priority": "high" + }, + { + "id": "4", + "content": "简化 WarehouseManagement.tsx - 删除第66-68行副标题", + "status": "completed", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/2af7e6fc-22c6-4a3b-ac30-b9047c6ab2d1/todos.json b/.todo/2af7e6fc-22c6-4a3b-ac30-b9047c6ab2d1/todos.json new file mode 100644 index 0000000..7a2eb6d --- /dev/null +++ b/.todo/2af7e6fc-22c6-4a3b-ac30-b9047c6ab2d1/todos.json @@ -0,0 +1,32 @@ +[ + { + "id": "1", + "status": "completed", + "content": "设计无货商品流转数据模型(供应商备货→采购单)", + "priority": "high" + }, + { + "id": "2", + "status": "completed", + "content": "修改供应商备货表,添加无货标记和流转功能", + "priority": "high" + }, + { + "id": "3", + "status": "completed", + "content": "完善采购单管理,接收无货流转商品", + "priority": "high" + }, + { + "id": "4", + "status": "completed", + "content": "实现成本关联计算逻辑", + "priority": "high" + }, + { + "id": "5", + "status": "completed", + "content": "验证数据一致性和流程闭环", + "priority": "medium" + } +] \ No newline at end of file diff --git a/.todo/2afb3baf-5c8c-4881-ac01-3d5e5ac5a8bf/todos.json b/.todo/2afb3baf-5c8c-4881-ac01-3d5e5ac5a8bf/todos.json new file mode 100644 index 0000000..bb3b1ff --- /dev/null +++ b/.todo/2afb3baf-5c8c-4881-ac01-3d5e5ac5a8bf/todos.json @@ -0,0 +1,86 @@ +[ + { + "id": "1", + "content": "订单录入页面 - 语音下单功能完整实现", + "status": "in_progress", + "priority": "high" + }, + { + "id": "2", + "content": "订单录入页面 - 图片识别下单功能完整实现", + "status": "pending", + "priority": "high" + }, + { + "id": "3", + "content": "订单录入页面 - 模板下单功能完整实现", + "status": "pending", + "priority": "high" + }, + { + "id": "4", + "content": "订单录入页面 - 历史复购功能完整实现", + "status": "pending", + "priority": "high" + }, + { + "id": "5", + "content": "订单管理 - 订单列表真实CRUD+分页筛选排序", + "status": "pending", + "priority": "high" + }, + { + "id": "6", + "content": "订单管理 - 订单状态流转完整实现", + "status": "pending", + "priority": "high" + }, + { + "id": "7", + "content": "客户管理 - 客户信息CRUD+分类管理", + "status": "pending", + "priority": "high" + }, + { + "id": "8", + "content": "商品管理 - SKU管理完整功能", + "status": "pending", + "priority": "high" + }, + { + "id": "9", + "content": "商品管理 - 分类管理完整功能", + "status": "pending", + "priority": "high" + }, + { + "id": "10", + "content": "商品管理 - 别名映射管理完整功能", + "status": "pending", + "priority": "high" + }, + { + "id": "11", + "content": "全局权限控制精确到按钮级别", + "status": "pending", + "priority": "high" + }, + { + "id": "12", + "content": "全局错误处理和加载状态统一封装", + "status": "pending", + "priority": "high" + }, + { + "id": "13", + "content": "表单验证和业务规则校验完整实现", + "status": "pending", + "priority": "high" + }, + { + "id": "14", + "content": "性能优化和代码质量检查", + "status": "pending", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/337360ad-a7c0-467c-81f9-e84069680813/todos.json b/.todo/337360ad-a7c0-467c-81f9-e84069680813/todos.json new file mode 100644 index 0000000..17577ed --- /dev/null +++ b/.todo/337360ad-a7c0-467c-81f9-e84069680813/todos.json @@ -0,0 +1,62 @@ +[ + { + "id": "1", + "content": "优化Dashboard仪表盘UI", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "优化订单管理模块UI", + "status": "in_progress", + "priority": "high" + }, + { + "id": "3", + "content": "优化采购管理模块UI", + "status": "pending", + "priority": "high" + }, + { + "id": "4", + "content": "优化验收管理模块UI", + "status": "pending", + "priority": "high" + }, + { + "id": "5", + "content": "优化配送管理模块UI", + "status": "pending", + "priority": "high" + }, + { + "id": "6", + "content": "优化库存管理模块UI", + "status": "pending", + "priority": "high" + }, + { + "id": "7", + "content": "优化财务管理模块UI", + "status": "pending", + "priority": "high" + }, + { + "id": "8", + "content": "优化系统管理模块UI", + "status": "pending", + "priority": "high" + }, + { + "id": "9", + "content": "优化Layout布局组件", + "status": "completed", + "priority": "high" + }, + { + "id": "10", + "content": "最终验证和测试", + "status": "pending", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/3928feb3-6834-4d72-9764-487495ada572/todos.json b/.todo/3928feb3-6834-4d72-9764-487495ada572/todos.json new file mode 100644 index 0000000..286a39b --- /dev/null +++ b/.todo/3928feb3-6834-4d72-9764-487495ada572/todos.json @@ -0,0 +1,44 @@ +[ + { + "id": "1", + "content": "替换Dashboard虚拟数据为真实数据", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "替换MarketMonitor虚拟数据", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "替换InspectionManagement虚拟数据(simulateAIAnalysis)", + "status": "completed", + "priority": "high" + }, + { + "id": "4", + "content": "替换PurchaseManagement虚拟数据(simulateAIReview)", + "status": "completed", + "priority": "high" + }, + { + "id": "5", + "content": "替换DeliveryManagement虚拟数据(MOCK_TASKS, MOCK_DELIVERY_PERSONS)", + "status": "completed", + "priority": "medium" + }, + { + "id": "6", + "content": "替换InvoiceManagement虚拟数据(simulateOCR和mock invoices)", + "status": "completed", + "priority": "medium" + }, + { + "id": "7", + "content": "验证所有功能使用真实数据", + "status": "in_progress", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/39c350cb-a4fc-433e-9dc1-13a2beadd88e/todos.json b/.todo/39c350cb-a4fc-433e-9dc1-13a2beadd88e/todos.json new file mode 100644 index 0000000..2a09720 --- /dev/null +++ b/.todo/39c350cb-a4fc-433e-9dc1-13a2beadd88e/todos.json @@ -0,0 +1,68 @@ +[ + { + "id": "1", + "content": "分析当前系统UI问题", + "status": "in_progress", + "priority": "high" + }, + { + "id": "2", + "content": "读取design-kungfu database.yaml进行风格打分", + "status": "pending", + "priority": "high" + }, + { + "id": "3", + "content": "选择最佳设计风格并读取完整规范", + "status": "pending", + "priority": "high" + }, + { + "id": "4", + "content": "生成完整设计系统文档(颜色、字体、组件、布局)", + "status": "pending", + "priority": "high" + }, + { + "id": "5", + "content": "重构全局CSS设计系统", + "status": "pending", + "priority": "high" + }, + { + "id": "6", + "content": "重构Layout布局组件", + "status": "pending", + "priority": "high" + }, + { + "id": "7", + "content": "重构Dashboard仪表盘", + "status": "pending", + "priority": "high" + }, + { + "id": "8", + "content": "重构订单管理模块", + "status": "pending", + "priority": "high" + }, + { + "id": "9", + "content": "重构采购管理模块", + "status": "pending", + "priority": "high" + }, + { + "id": "10", + "content": "重构配送/库存/财务/系统模块", + "status": "pending", + "priority": "high" + }, + { + "id": "11", + "content": "最终验证和测试", + "status": "pending", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/39d60083-531d-4da4-b6ef-f2d0f261ea81/todos.json b/.todo/39d60083-531d-4da4-b6ef-f2d0f261ea81/todos.json new file mode 100644 index 0000000..9dc138a --- /dev/null +++ b/.todo/39d60083-531d-4da4-b6ef-f2d0f261ea81/todos.json @@ -0,0 +1,86 @@ +[ + { + "id": "1", + "content": "修复 DeliveryPersonManagement.tsx 类型错误", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "修复 ExceptionManagement.tsx 类型错误", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "修复 CostAdjustmentManagement.tsx 类型错误", + "status": "completed", + "priority": "high" + }, + { + "id": "4", + "content": "修复 CostManagement.tsx 类型错误", + "status": "completed", + "priority": "high" + }, + { + "id": "5", + "content": "修复 FixedCostManagement.tsx 类型错误", + "status": "completed", + "priority": "high" + }, + { + "id": "6", + "content": "修复 InvoiceManagement.tsx 类型错误", + "status": "completed", + "priority": "high" + }, + { + "id": "7", + "content": "修复 InspectionManagement.tsx 类型错误", + "status": "completed", + "priority": "high" + }, + { + "id": "8", + "content": "修复 OrderManagement.tsx 类型错误", + "status": "completed", + "priority": "high" + }, + { + "id": "9", + "content": "修复 CategoryManagement.tsx 类型错误", + "status": "completed", + "priority": "high" + }, + { + "id": "10", + "content": "修复 PurchaseManagement.tsx 类型错误", + "status": "completed", + "priority": "high" + }, + { + "id": "11", + "content": "修复 SupplierManagement.tsx 类型错误", + "status": "completed", + "priority": "high" + }, + { + "id": "12", + "content": "修复 Notifications.tsx 类型错误", + "status": "completed", + "priority": "high" + }, + { + "id": "13", + "content": "修复 OperationLogs.tsx 类型错误", + "status": "completed", + "priority": "high" + }, + { + "id": "14", + "content": "修复 SystemConfig.tsx 类型错误", + "status": "completed", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/40557244-95a3-4cad-9ec7-2e98f9c2bd0c/todos.json b/.todo/40557244-95a3-4cad-9ec7-2e98f9c2bd0c/todos.json new file mode 100644 index 0000000..2d1ce58 --- /dev/null +++ b/.todo/40557244-95a3-4cad-9ec7-2e98f9c2bd0c/todos.json @@ -0,0 +1,50 @@ +[ + { + "id": "1", + "content": "加载meoo-cloud技能并阅读认证文档", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "创建用户表和角色权限表", + "status": "completed", + "priority": "high" + }, + { + "id": "5", + "content": "注入默认权限账号数据", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "创建权限管理页面", + "status": "completed", + "priority": "high" + }, + { + "id": "4", + "content": "创建登录认证系统", + "status": "completed", + "priority": "high" + }, + { + "id": "7", + "content": "实现页面级权限控制", + "status": "completed", + "priority": "high" + }, + { + "id": "6", + "content": "清理所有虚假/模拟数据代码", + "status": "completed", + "priority": "high" + }, + { + "id": "8", + "content": "验证完整权限流程", + "status": "completed", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/4551e6ad-6e93-42d4-b223-3e3c7057e4f2/todos.json b/.todo/4551e6ad-6e93-42d4-b223-3e3c7057e4f2/todos.json new file mode 100644 index 0000000..1a2cb36 --- /dev/null +++ b/.todo/4551e6ad-6e93-42d4-b223-3e3c7057e4f2/todos.json @@ -0,0 +1,74 @@ +[ + { + "id": "1", + "content": "读取Vercel Style设计规范", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "重构全局设计系统(颜色、字体、间距)", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "重设计Layout布局组件", + "status": "in_progress", + "priority": "high" + }, + { + "id": "4", + "content": "重设计Dashboard仪表盘", + "status": "pending", + "priority": "high" + }, + { + "id": "5", + "content": "重设计订单管理模块", + "status": "pending", + "priority": "high" + }, + { + "id": "6", + "content": "重设计采购管理模块", + "status": "pending", + "priority": "high" + }, + { + "id": "7", + "content": "重设计验收管理模块", + "status": "pending", + "priority": "high" + }, + { + "id": "8", + "content": "重设计配送管理模块", + "status": "pending", + "priority": "high" + }, + { + "id": "9", + "content": "重设计库存管理模块", + "status": "pending", + "priority": "high" + }, + { + "id": "10", + "content": "重设计财务管理模块", + "status": "pending", + "priority": "high" + }, + { + "id": "11", + "content": "重设计系统管理模块", + "status": "pending", + "priority": "high" + }, + { + "id": "12", + "content": "最终验证和测试", + "status": "pending", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/461a2ea0-43fd-448a-bf7b-900cf72391e8/todos.json b/.todo/461a2ea0-43fd-448a-bf7b-900cf72391e8/todos.json new file mode 100644 index 0000000..5b20e99 --- /dev/null +++ b/.todo/461a2ea0-43fd-448a-bf7b-900cf72391e8/todos.json @@ -0,0 +1,32 @@ +[ + { + "id": "1", + "content": "创建采购员用户关联表和RLS策略", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "创建配送员用户关联表和RLS策略", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "创建采购员登录页面", + "status": "completed", + "priority": "high" + }, + { + "id": "4", + "content": "创建配送员登录页面", + "status": "completed", + "priority": "high" + }, + { + "id": "5", + "content": "更新路由配置", + "status": "completed", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/469fd229-d182-4ec1-a1ff-6d99ac95b615/todos.json b/.todo/469fd229-d182-4ec1-a1ff-6d99ac95b615/todos.json new file mode 100644 index 0000000..d752eff --- /dev/null +++ b/.todo/469fd229-d182-4ec1-a1ff-6d99ac95b615/todos.json @@ -0,0 +1,32 @@ +[ + { + "id": "1", + "content": "创建客户商品关联表", + "status": "in_progress", + "priority": "high" + }, + { + "id": "2", + "content": "更新三层解析Edge Function支持客户商品库", + "status": "pending", + "priority": "high" + }, + { + "id": "3", + "content": "更新前端选择客户时加载对应商品库", + "status": "pending", + "priority": "high" + }, + { + "id": "4", + "content": "实现别名学习回写功能", + "status": "pending", + "priority": "high" + }, + { + "id": "5", + "content": "部署并测试", + "status": "pending", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/4c1cf8bf-dda0-45e6-8e11-56b5ed142462/todos.json b/.todo/4c1cf8bf-dda0-45e6-8e11-56b5ed142462/todos.json new file mode 100644 index 0000000..11851a9 --- /dev/null +++ b/.todo/4c1cf8bf-dda0-45e6-8e11-56b5ed142462/todos.json @@ -0,0 +1,86 @@ +[ + { + "id": "1", + "content": "订单录入页面 - 语音下单功能完整实现", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "订单录入页面 - 图片识别下单功能完整实现", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "订单录入页面 - 模板下单功能完整实现", + "status": "completed", + "priority": "high" + }, + { + "id": "4", + "content": "订单录入页面 - 历史复购功能完整实现", + "status": "completed", + "priority": "high" + }, + { + "id": "5", + "content": "订单管理 - 订单列表真实CRUD+分页筛选排序", + "status": "completed", + "priority": "high" + }, + { + "id": "6", + "content": "订单管理 - 订单状态流转完整实现", + "status": "completed", + "priority": "high" + }, + { + "id": "7", + "content": "客户管理 - 客户信息CRUD+分类管理", + "status": "completed", + "priority": "high" + }, + { + "id": "8", + "content": "商品管理 - SKU管理完整功能", + "status": "completed", + "priority": "high" + }, + { + "id": "9", + "content": "商品管理 - 分类管理完整功能", + "status": "completed", + "priority": "high" + }, + { + "id": "10", + "content": "商品管理 - 别名映射管理完整功能", + "status": "completed", + "priority": "high" + }, + { + "id": "11", + "content": "全局权限控制精确到按钮级别", + "status": "completed", + "priority": "high" + }, + { + "id": "12", + "content": "全局错误处理和加载状态统一封装", + "status": "completed", + "priority": "high" + }, + { + "id": "13", + "content": "表单验证和业务规则校验完整实现", + "status": "completed", + "priority": "high" + }, + { + "id": "14", + "content": "性能优化和代码质量检查", + "status": "completed", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/58c936e4-dc30-4eda-abd7-1d2924383a17/todos.json b/.todo/58c936e4-dc30-4eda-abd7-1d2924383a17/todos.json new file mode 100644 index 0000000..50ca4d1 --- /dev/null +++ b/.todo/58c936e4-dc30-4eda-abd7-1d2924383a17/todos.json @@ -0,0 +1,62 @@ +[ + { + "id": "1", + "content": "P0: 创建M31市场智能监控模块 - 市场比价/价格指数/三级预警", + "status": "in_progress", + "priority": "high" + }, + { + "id": "2", + "content": "P0: 完善AI质量评级功能 - 验收环节ABCD评级", + "status": "pending", + "priority": "high" + }, + { + "id": "3", + "content": "P0: 完善成本分摊算法 - 9类成本分摊计算", + "status": "pending", + "priority": "high" + }, + { + "id": "4", + "content": "P1: 增强订单管理 - 语音下单/三层解析/别名映射", + "status": "pending", + "priority": "high" + }, + { + "id": "5", + "content": "P1: 完善供应商备货 - AI初审/四视图/缺货换品", + "status": "pending", + "priority": "high" + }, + { + "id": "6", + "content": "P1: 增强验收管理 - 水印拍照/电子秤/加工明细", + "status": "pending", + "priority": "high" + }, + { + "id": "7", + "content": "P1: 完善财务管理 - 账龄分析/亮灯预警/OCR发票", + "status": "pending", + "priority": "medium" + }, + { + "id": "8", + "content": "P2: 增强配送管理 - GPS轨迹/路线规划/双签收", + "status": "pending", + "priority": "medium" + }, + { + "id": "9", + "content": "P2: 数据深度分析 - 成本趋势/损耗根因/客户画像", + "status": "pending", + "priority": "medium" + }, + { + "id": "10", + "content": "验证所有功能并运行测试", + "status": "pending", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/5b399373-f4ad-43eb-a158-6a8d9f066d1c/todos.json b/.todo/5b399373-f4ad-43eb-a158-6a8d9f066d1c/todos.json new file mode 100644 index 0000000..9474a18 --- /dev/null +++ b/.todo/5b399373-f4ad-43eb-a158-6a8d9f066d1c/todos.json @@ -0,0 +1,50 @@ +[ + { + "id": "1", + "content": "加载meoo-cloud技能并阅读认证文档", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "创建用户表和角色权限表", + "status": "in_progress", + "priority": "high" + }, + { + "id": "3", + "content": "创建权限管理页面", + "status": "pending", + "priority": "high" + }, + { + "id": "4", + "content": "创建登录认证系统", + "status": "pending", + "priority": "high" + }, + { + "id": "5", + "content": "注入默认权限账号数据", + "status": "pending", + "priority": "high" + }, + { + "id": "6", + "content": "清理所有虚假/模拟数据代码", + "status": "pending", + "priority": "high" + }, + { + "id": "7", + "content": "实现页面级权限控制", + "status": "pending", + "priority": "high" + }, + { + "id": "8", + "content": "验证完整权限流程", + "status": "pending", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/66a272e2-9414-4c8d-a8ff-2f3b3d23bbb8/todos.json b/.todo/66a272e2-9414-4c8d-a8ff-2f3b3d23bbb8/todos.json new file mode 100644 index 0000000..1313921 --- /dev/null +++ b/.todo/66a272e2-9414-4c8d-a8ff-2f3b3d23bbb8/todos.json @@ -0,0 +1,26 @@ +[ + { + "id": "1", + "content": "简化 PurchaseManagement.tsx - 删除副标题、功能卡片、VIEW_TYPES描述、AI审核说明", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "简化 SupplierPreparation.tsx - 删除副标题", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "简化 InspectionManagement.tsx - 删除副标题、流程卡片、评级卡片、简化各类说明文字", + "status": "completed", + "priority": "high" + }, + { + "id": "4", + "content": "简化 ProcessingManagement.tsx - 删除副标题、统计卡片", + "status": "completed", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/68436d69-840d-47fe-b197-ff63a8c81047/todos.json b/.todo/68436d69-840d-47fe-b197-ff63a8c81047/todos.json new file mode 100644 index 0000000..2637b44 --- /dev/null +++ b/.todo/68436d69-840d-47fe-b197-ff63a8c81047/todos.json @@ -0,0 +1,182 @@ +[ + { + "id": "1", + "content": "M18 商品分类管理模块 - 完整实现分类层级、属性配置、排序停用", + "status": "in_progress", + "priority": "high" + }, + { + "id": "2", + "content": "M19 商品基础管理模块 - 完整实现SKU属性、中标价格、批量导入", + "status": "pending", + "priority": "high" + }, + { + "id": "3", + "content": "M20 商品映射库管理模块 - 完整实现别名映射、冲突检测、AI自学习", + "status": "pending", + "priority": "high" + }, + { + "id": "4", + "content": "M16 客户管理模块 - 完整实现客户档案、预算管控、账期配置", + "status": "pending", + "priority": "high" + }, + { + "id": "5", + "content": "M9 供应商管理模块 - 完整实现入驻流程、评级体系、配额管理", + "status": "pending", + "priority": "high" + }, + { + "id": "6", + "content": "M1 客户下单模块 - 完整实现多渠道下单、AI匹配、预算校验", + "status": "pending", + "priority": "high" + }, + { + "id": "7", + "content": "M2 订单处理+智能采购模块 - 完整实现拆合单、自动分配、缺货换品", + "status": "pending", + "priority": "high" + }, + { + "id": "8", + "content": "M3 供应商备货管控模块 - 完整实现接单、成本录入、AI初审", + "status": "pending", + "priority": "high" + }, + { + "id": "9", + "content": "M4 验收分拣+加工+损耗确权模块 - 完整实现四步验收、AI评级、损耗判定", + "status": "pending", + "priority": "high" + }, + { + "id": "10", + "content": "M5 配送履约模块 - 完整实现任务分配、GPS轨迹、双签收", + "status": "pending", + "priority": "high" + }, + { + "id": "11", + "content": "M6 售后客诉与退货管理模块", + "status": "pending", + "priority": "high" + }, + { + "id": "12", + "content": "M7 成本核算模块 - 完整实现9类成本、分摊算法、毛利计算", + "status": "pending", + "priority": "high" + }, + { + "id": "13", + "content": "M8 财务结算模块 - 完整实现客户/供应商结算、发票管理", + "status": "pending", + "priority": "high" + }, + { + "id": "14", + "content": "M10 库存周转与盘点模块", + "status": "pending", + "priority": "high" + }, + { + "id": "15", + "content": "M11 发票管理模块", + "status": "pending", + "priority": "medium" + }, + { + "id": "16", + "content": "M12 消息通知中心", + "status": "pending", + "priority": "medium" + }, + { + "id": "17", + "content": "M13 数据导入导出中心", + "status": "pending", + "priority": "medium" + }, + { + "id": "18", + "content": "M14 操作日志审计模块", + "status": "pending", + "priority": "medium" + }, + { + "id": "19", + "content": "M15 AI数据看板 & 履约周期复盘", + "status": "pending", + "priority": "medium" + }, + { + "id": "20", + "content": "M17 配送员管理模块", + "status": "pending", + "priority": "medium" + }, + { + "id": "21", + "content": "M21 仓库/库位管理模块", + "status": "pending", + "priority": "medium" + }, + { + "id": "22", + "content": "M22 采购管理模块(紧急/补货)", + "status": "pending", + "priority": "medium" + }, + { + "id": "23", + "content": "M23 系统配置管理模块", + "status": "pending", + "priority": "medium" + }, + { + "id": "24", + "content": "M24 文件管理模块", + "status": "pending", + "priority": "medium" + }, + { + "id": "25", + "content": "M25 定时任务管理模块", + "status": "pending", + "priority": "low" + }, + { + "id": "26", + "content": "M26 数据归档清理模块", + "status": "pending", + "priority": "low" + }, + { + "id": "27", + "content": "M27 第三方接口监控模块", + "status": "pending", + "priority": "low" + }, + { + "id": "28", + "content": "M28 异常工单处理中心", + "status": "pending", + "priority": "medium" + }, + { + "id": "29", + "content": "M29 固定成本录入模块", + "status": "pending", + "priority": "medium" + }, + { + "id": "30", + "content": "M30 成本调整与审批模块", + "status": "pending", + "priority": "medium" + } +] \ No newline at end of file diff --git a/.todo/8919357c-3675-4ae6-927a-3b784b8f74a4/todos.json b/.todo/8919357c-3675-4ae6-927a-3b784b8f74a4/todos.json new file mode 100644 index 0000000..1641493 --- /dev/null +++ b/.todo/8919357c-3675-4ae6-927a-3b784b8f74a4/todos.json @@ -0,0 +1,32 @@ +[ + { + "id": "1", + "content": "创建客户图片映射表结构", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "创建客户映射库管理页面", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "实现图片上传和OCR识别功能", + "status": "completed", + "priority": "high" + }, + { + "id": "4", + "content": "在订单页面集成客户映射库选择", + "status": "completed", + "priority": "high" + }, + { + "id": "5", + "content": "验证功能完整可用", + "status": "completed", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/89386ad4-1397-47bf-a221-3e958a0c3a05/todos.json b/.todo/89386ad4-1397-47bf-a221-3e958a0c3a05/todos.json new file mode 100644 index 0000000..1bb92a4 --- /dev/null +++ b/.todo/89386ad4-1397-47bf-a221-3e958a0c3a05/todos.json @@ -0,0 +1,20 @@ +[ + { + "id": "1", + "content": "创建商品分类基础数据", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "导入SKU商品基础数据", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "导入商品别名映射数据", + "status": "completed", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/a129f9b5-3f0b-4623-80d3-76c15b2aeda6/todos.json b/.todo/a129f9b5-3f0b-4623-80d3-76c15b2aeda6/todos.json new file mode 100644 index 0000000..434a37a --- /dev/null +++ b/.todo/a129f9b5-3f0b-4623-80d3-76c15b2aeda6/todos.json @@ -0,0 +1,44 @@ +[ + { + "id": "1", + "content": "查看数据库表结构和现有数据", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "为categories表注入真实商品分类数据", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "为skus表注入真实商品数据", + "status": "completed", + "priority": "high" + }, + { + "id": "4", + "content": "为sku_aliases表注入真实别名映射数据", + "status": "completed", + "priority": "high" + }, + { + "id": "5", + "content": "为suppliers表注入真实供应商数据", + "status": "in_progress", + "priority": "medium" + }, + { + "id": "6", + "content": "为customers表注入真实客户数据", + "status": "pending", + "priority": "medium" + }, + { + "id": "7", + "content": "验证数据注入结果", + "status": "pending", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/a264a96e-e926-42da-b889-64df5f9c3c79/todos.json b/.todo/a264a96e-e926-42da-b889-64df5f9c3c79/todos.json new file mode 100644 index 0000000..2b07563 --- /dev/null +++ b/.todo/a264a96e-e926-42da-b889-64df5f9c3c79/todos.json @@ -0,0 +1,86 @@ +[ + { + "id": "1", + "content": "订单录入页面 - 语音下单功能完整实现", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "订单录入页面 - 图片识别下单功能完整实现", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "订单录入页面 - 模板下单功能完整实现", + "status": "completed", + "priority": "high" + }, + { + "id": "4", + "content": "订单录入页面 - 历史复购功能完整实现", + "status": "completed", + "priority": "high" + }, + { + "id": "5", + "content": "订单管理 - 订单列表真实CRUD+分页筛选排序", + "status": "completed", + "priority": "high" + }, + { + "id": "6", + "content": "订单管理 - 订单状态流转完整实现", + "status": "completed", + "priority": "high" + }, + { + "id": "7", + "content": "客户管理 - 客户信息CRUD+分类管理", + "status": "completed", + "priority": "high" + }, + { + "id": "8", + "content": "商品管理 - SKU管理完整功能", + "status": "in_progress", + "priority": "high" + }, + { + "id": "9", + "content": "商品管理 - 分类管理完整功能", + "status": "pending", + "priority": "high" + }, + { + "id": "10", + "content": "商品管理 - 别名映射管理完整功能", + "status": "pending", + "priority": "high" + }, + { + "id": "11", + "content": "全局权限控制精确到按钮级别", + "status": "pending", + "priority": "high" + }, + { + "id": "12", + "content": "全局错误处理和加载状态统一封装", + "status": "pending", + "priority": "high" + }, + { + "id": "13", + "content": "表单验证和业务规则校验完整实现", + "status": "pending", + "priority": "high" + }, + { + "id": "14", + "content": "性能优化和代码质量检查", + "status": "pending", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/b3778267-d6a5-470e-afe9-d3b51cbd74bf/todos.json b/.todo/b3778267-d6a5-470e-afe9-d3b51cbd74bf/todos.json new file mode 100644 index 0000000..9a21241 --- /dev/null +++ b/.todo/b3778267-d6a5-470e-afe9-d3b51cbd74bf/todos.json @@ -0,0 +1,7 @@ +[ + { + "id": "1", + "content": "优化统计卡片样式 - 使用白色背景、黑色数字、灰色标签", + "status": "completed" + } +] \ No newline at end of file diff --git a/.todo/beddb136-bde3-4718-9e8b-965b7896dfde/todos.json b/.todo/beddb136-bde3-4718-9e8b-965b7896dfde/todos.json new file mode 100644 index 0000000..8201b00 --- /dev/null +++ b/.todo/beddb136-bde3-4718-9e8b-965b7896dfde/todos.json @@ -0,0 +1,32 @@ +[ + { + "id": "1", + "content": "设计无货商品流转数据模型(供应商备货→采购单)", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "修改供应商备货表,添加无货标记和流转功能", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "完善采购单管理,接收无货流转商品", + "status": "completed", + "priority": "high" + }, + { + "id": "4", + "content": "实现成本关联计算逻辑", + "status": "completed", + "priority": "high" + }, + { + "id": "5", + "content": "验证数据一致性和流程闭环", + "status": "completed", + "priority": "medium" + } +] \ No newline at end of file diff --git a/.todo/c107664a-e3c5-46a4-ae97-398e96f6571c/todos.json b/.todo/c107664a-e3c5-46a4-ae97-398e96f6571c/todos.json new file mode 100644 index 0000000..0a1434f --- /dev/null +++ b/.todo/c107664a-e3c5-46a4-ae97-398e96f6571c/todos.json @@ -0,0 +1,32 @@ +[ + { + "id": "1", + "content": "读取并分析 OrderManagement.tsx 的当前UI实现", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "读取并分析 OrderEntry.tsx 的当前UI实现", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "读取并分析 OrderAllocation.tsx 的当前UI实现", + "status": "completed", + "priority": "high" + }, + { + "id": "4", + "content": "读取并分析 BidManagement.tsx 的当前UI实现", + "status": "completed", + "priority": "high" + }, + { + "id": "5", + "content": "统一优化四个文件的UI样式为Vercel Style", + "status": "in_progress", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/d647d6fd-2f32-4601-ab73-a2062904263c/todos.json b/.todo/d647d6fd-2f32-4601-ab73-a2062904263c/todos.json new file mode 100644 index 0000000..1ef557f --- /dev/null +++ b/.todo/d647d6fd-2f32-4601-ab73-a2062904263c/todos.json @@ -0,0 +1,62 @@ +[ + { + "id": "1", + "content": "完善订单分配功能(智能分配逻辑)", + "status": "in_progress", + "priority": "high" + }, + { + "id": "2", + "content": "完善竞价管理功能", + "status": "pending", + "priority": "high" + }, + { + "id": "3", + "content": "完善验收管理功能", + "status": "pending", + "priority": "high" + }, + { + "id": "4", + "content": "完善加工管理功能", + "status": "pending", + "priority": "high" + }, + { + "id": "5", + "content": "完善配送管理功能", + "status": "pending", + "priority": "high" + }, + { + "id": "6", + "content": "完善售后管理功能", + "status": "pending", + "priority": "medium" + }, + { + "id": "7", + "content": "完善异常管理功能", + "status": "pending", + "priority": "medium" + }, + { + "id": "8", + "content": "完善库存管理功能", + "status": "pending", + "priority": "medium" + }, + { + "id": "9", + "content": "完善仓库管理功能", + "status": "pending", + "priority": "medium" + }, + { + "id": "10", + "content": "完善财务结算功能", + "status": "pending", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/e332045d-648d-4fdb-9204-a89095d3ca8f/todos.json b/.todo/e332045d-648d-4fdb-9204-a89095d3ca8f/todos.json new file mode 100644 index 0000000..3d138a2 --- /dev/null +++ b/.todo/e332045d-648d-4fdb-9204-a89095d3ca8f/todos.json @@ -0,0 +1,50 @@ +[ + { + "id": "1", + "content": "核对登录认证流程", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "核对订单管理全流程", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "核对商品管理全流程", + "status": "completed", + "priority": "high" + }, + { + "id": "4", + "content": "核对客户供应商管理", + "status": "completed", + "priority": "high" + }, + { + "id": "5", + "content": "核对采购验收配送流程", + "status": "completed", + "priority": "high" + }, + { + "id": "6", + "content": "核对财务管理流程", + "status": "completed", + "priority": "high" + }, + { + "id": "7", + "content": "核对系统管理功能", + "status": "completed", + "priority": "high" + }, + { + "id": "8", + "content": "验证所有修复并运行完整测试", + "status": "completed", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/f1624c60-ae56-422a-8d24-0aa0c35d352c/todos.json b/.todo/f1624c60-ae56-422a-8d24-0aa0c35d352c/todos.json new file mode 100644 index 0000000..7a76daa --- /dev/null +++ b/.todo/f1624c60-ae56-422a-8d24-0aa0c35d352c/todos.json @@ -0,0 +1,62 @@ +[ + { + "id": "1", + "content": "优化Dashboard仪表盘UI", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "优化订单管理模块UI", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "优化采购管理模块UI", + "status": "in_progress", + "priority": "high" + }, + { + "id": "4", + "content": "优化验收管理模块UI", + "status": "pending", + "priority": "high" + }, + { + "id": "5", + "content": "优化配送管理模块UI", + "status": "pending", + "priority": "high" + }, + { + "id": "6", + "content": "优化库存管理模块UI", + "status": "pending", + "priority": "high" + }, + { + "id": "7", + "content": "优化财务管理模块UI", + "status": "pending", + "priority": "high" + }, + { + "id": "8", + "content": "优化系统管理模块UI", + "status": "pending", + "priority": "high" + }, + { + "id": "9", + "content": "优化Layout布局组件", + "status": "completed", + "priority": "high" + }, + { + "id": "10", + "content": "最终验证和测试", + "status": "pending", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/f390ada5-8df0-4454-a84c-2ca915614ee0/todos.json b/.todo/f390ada5-8df0-4454-a84c-2ca915614ee0/todos.json new file mode 100644 index 0000000..fc237c5 --- /dev/null +++ b/.todo/f390ada5-8df0-4454-a84c-2ca915614ee0/todos.json @@ -0,0 +1,32 @@ +[ + { + "id": "1", + "content": "简化 CustomerManagement.tsx - 删除副标题", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "简化 CustomerAliasLibrary.tsx - 删除副标题、统计卡片、简化OCR区域", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "简化 SupplierManagement.tsx - 删除副标题和统计卡片", + "status": "completed", + "priority": "high" + }, + { + "id": "4", + "content": "简化 OrderAllocation.tsx - 删除副标题、开发中提示、简化统计描述", + "status": "completed", + "priority": "high" + }, + { + "id": "5", + "content": "简化 BidManagement.tsx - 删除副标题、简化统计描述", + "status": "completed", + "priority": "high" + } +] \ No newline at end of file diff --git a/.todo/f908dfa8-2857-4beb-a23b-b3a348d894a8/todos.json b/.todo/f908dfa8-2857-4beb-a23b-b3a348d894a8/todos.json new file mode 100644 index 0000000..a13670d --- /dev/null +++ b/.todo/f908dfa8-2857-4beb-a23b-b3a348d894a8/todos.json @@ -0,0 +1,26 @@ +[ + { + "id": "1", + "content": "简化 Dashboard.tsx - 删除副标题和5个功能描述卡片", + "status": "completed", + "priority": "high" + }, + { + "id": "2", + "content": "简化 CategoryManagement.tsx - 删除副标题", + "status": "completed", + "priority": "high" + }, + { + "id": "3", + "content": "简化 SkuManagement.tsx - 删除副标题", + "status": "completed", + "priority": "high" + }, + { + "id": "4", + "content": "简化 AliasManagement.tsx - 删除副标题", + "status": "completed", + "priority": "high" + } +] \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..4f45d2b --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,299 @@ +# AGENTS.md — 交给本仓库 AI 助手的硬规则 + +> 本文件与 `.cursor/rules/` 下的规则共同生效。**冲突时以 `.cursor/rules/` 为准**(更完整)。 + +## 绝对禁止:未经直接命令部署上线 + +**未经人工在对话中直接下达的部署命令,严禁以任何方式把代码、构建产物、配置或数据库变更 +发布到生产环境。** + +- 「直接命令」= 用户本人当轮明确说要部署/上线/发布(如「部署上线」「发布到生产」); +- **不构成授权**:只让你改代码/修 bug;说「测试完毕」让你验收;更早轮次授权过一次;你自己 + 判断「改了好几处顺手发一下」。 +- 涉及即算部署:`scp`/`rsync` 上传产物、远端 `prod-apply-backend.sh`、重启线上服务、 + 执行生产迁移、改线上 Nginx、跑生产数据修复脚本。 +- 生产范围:test-api `146.56.223.139`、test-h5 `119.45.34.106`、 + `https://www.xdjchuanhui.com`、生产库 `1.13.62.2:20538/ai_fresh_delivery`。 + +### 允许直接做(无需额外授权) + +- 本地开发栈:`run-local.sh start|stop|status`、本地库迁移、本地构建与测试; +- **提交并推送代码到 git 仓库(推代码 ≠ 部署)**; +- 在本地库或只读快照库(`prod_*`)上查询分析。 + +### 需要部署时 + +先停下来讲清楚「做什么、影响哪个环境、回滚点」,**拿到明确命令再执行**;执行后报告验证结果 +与回滚方式。若已误发,立即停止后续动作并主动告知 + 给回滚路径。 + +完整条文见 [`.cursor/rules/deploy-authorization.mdc`](.cursor/rules/deploy-authorization.mdc)。 + +## 其他项目约定(摘要) + +- 入口规则:[`.cursor/rules/00-project.mdc`](.cursor/rules/00-project.mdc)(架构、文档权威、订单状态链)。 +- **设计先行**:功能/行为变更先写 `docs/design/`,再编码,收工对照验收标准验证。 +- 订单主状态链勿自造:`20→30→40→45→50→60→90`。 +- 禁止提交密钥类文件(`server/.env`、SSH 私钥、AppSecret 等)。 + +## 设计文档门禁(硬规则 · 2026-09-29 起常态化) + +**改 `docs/design/`、`docs/audit/`、`tools/design-consistency/` 之前先跑一次,汇报"改完了"之前必须再跑一次。** + +```bash +bash tools/design-consistency/run-all.sh --verify # 九道闸门,一个退出码 +``` + +- 已装 `pre-commit` 钩子:**快档每次提交**都跑;**事实档**仅在改动落到 + `docs/design|docs/audit|tools/*|功能全景图.html|AGENTS.md|.cursor/rules` 时跑。 +- **未通过就别提交**。未通过先判因:① 结论真没落到该展示面 → 改文档; + ② 检查器口径写错 → **改检查器**。**不许改文档措辞去迎合检查器**(那是把门禁变成形式主义)。 +- **`check-ai-cost.py` 目前是红的,且不许调绿**:解析/OCR/图像链路出口不记录 token usage + ⇒ 算不出每单成本。调绿只有两条路 —— 改产品代码(需批准)或填假数(禁止)。 +- **新增 AI 功能 = 在 [`docs/design/20260929-AI门槛与计量登记表.md`](docs/design/20260929-AI门槛与计量登记表.md) 加一行** + (门槛/分母/样本量/降级开关/计量点),否则闸门不放行。填不出真数时写「待补」+ 负责人。 +- **新增一个检查器,就要在 `check-self-test.py` 里给它加「正常 PASS + 注入缺陷 FAIL」两条用例** —— + 本项目的实测教训:旧版 `check-structure.py` 对「表头 4 格 vs 分隔行 3 格」两处判据全放过, + 坏文档照常提交成功。 +- 绕过:`GATE_BYPASS=1 git commit`(什么都不跑)、`GATE_SKIP_VERIFY=1`(只跳事实档)。 + **不要用 `git commit --no-verify`** —— 那样连快档都不跑,还不留提示。 +- 说明与九道门总表:[`tools/design-consistency/README.md`](tools/design-consistency/README.md)。 + +## 本地库禁止覆盖线上库(硬规则) + +**任何「本地/开发/测试库 → 线上库」的数据写入,一律禁止。** + +- **禁止**:整库恢复(本地 `pg_dump` 导入线上 / `DROP DATABASE` 重建)、 + 用本地数据 `UPDATE|INSERT` 线上 `system_configs`、AI 提示词表、 + 任何把本地数据"同步上去"的脚本或手工 SQL、新增 `dev → prod` 反向同步。 +- **唯一允许的线上库写入**:**迁移**(`migrations/*.sql`),且迁移不得内嵌"用某份本地数据覆盖线上数据"。 +- **重点保护对象**:`platform_llm_config`、`branch_llm_config`、 + `ai_prompt_templates` / `ai_prompt_revisions` / `ai_prompt_overrides`。 +- **提示词改动规范**:内置默认值只改 `server/src/prompts/defaults.ts`(走 git); + 线上生效文案**必须走发布流程升 `version`**——`version = 1` 的提示词 + **每次部署都会被代码默认值覆盖**,直接改库不升版会静默丢失。 +- **可以放心做**:`prod → dev` 单向同步、对线上**只读**查询、本地库随意改、 + 提交推送代码到 git。 + +完整条文见 [`.cursor/rules/local-db-must-not-overwrite-prod.mdc`](.cursor/rules/local-db-must-not-overwrite-prod.mdc)。 + +## 财务逻辑冻结(硬规则) + +**未经开发者明确批准,不得改动任何财务逻辑。** 2026-09-14 财务口径刚理顺,别又搞乱。 + +- **只读分析永远允许**:查数、对账、解释某个数字怎么算出来的、指出不一致——请照做。 +- **冻结范围**:`marginQueryService.ts`、`financeNetProfitFormula.ts`、`purchaseCostBucketSql.ts`、 + `financeRoutes.ts`、各类 `*Cost*` / `*cost*` / `*Finance*` / `*margin*` 服务、 + `src/pages/finance/**`、看板财务 KPI、`/cost/*` 与 `/finance/*` 接口。 +- **必须改时先告知**:说明「改什么 / 为什么非改不可(附改前改后实测数字)/ 影响面 / 回滚方式」, + **拿到明确批准再动**。不得先改后报,不得把"告知"当成"已获批准"。 +- **口径变更成对落地**:后端聚合 ↔ 前端展示同步;更新 `docs/design/` 与 + `docs/财务结算模块实现对照.md`;同步契约测试;提交信息写清改前/改后数字。 +- **已定稿口径(勿回退)**:采购成本/所有成本用**订单行口径**;净利与销售额**同口径**; + 仓内加工成品行**不计入合计**(材料成本已由独立自采入库或库存领用承担), + 但**排行展示层**仍显示加工后成本;毛利率=`(销售额−采购成本)/销售额`, + **禁止**写成 `采购/销售`;准时履约按「实际送达 ≤ 客户须送达时刻」,未设置按准时计。 +- **未决事项(改前必须先问)**:商品成本表「表头合计」与「订单采购成本」卡差 ¥42 + (前者含仓内加工行),待选定统一口径后再动。 + +完整条文见 [`.cursor/rules/finance-freeze.mdc`](.cursor/rules/finance-freeze.mdc)。 + +## 订单与分配冻结(硬规则) + +**未经开发者明确批准,不得改状态链常量、分配信号量、竞价事务写法与历史结案白名单。** + +- 主链固定 `20→30→40→45→50→60→90`,**不得自造状态**;`70/80` 已废弃。 +- `ORDER_STATUS_ALLOWED` 的 **`40: [45, 30]`** 是**合法的拒收回退异常边,勿删**(删了会把线上真实流转拒掉)。 +- 45/50 **没有**回退边,而线上真实回退走裸 SQL;**禁止**把它们接到 `advanceOrderWorkflow`。 +- `withAllocationSlot` 的 **`AsyncLocalStorage` 重入检测勿删**;`tryAutoAwardAndAllocate` 的 **SAVEPOINT 勿改回裸 `BEGIN/COMMIT`**(两个 P0 的修复)。 +- 请求级共享连接下开事务,只许用三套既有解药(`if (ownsClient)` 守卫 / `SAVEPOINT` / `getRawPoolConnect()`);全后端仍有约 97 处裸写法未甄别,**不得当已清干净**。 +- `historicalFinalizeAllowlist.json` 是**应急口子**(会把不合格改判合格、跳闸门、强推 90)——**禁止**擅自扩大;白名单内「不合格不得入库」不变量**有意不成立**。 +- `pickDisplayOrderStatus` / `computeEffectiveOrderStatus` 生产调用方为 0,定性待决——**禁止**擅自删除或恢复调用。 + +完整条文见 [`.cursor/rules/order-freeze.mdc`](.cursor/rules/order-freeze.mdc)。 + +## 采购与备货冻结(硬规则) + +**未经开发者明确批准,不得改 `purchase_status` 语义或把四处谓词「统一口径」。** + +- 完成自采写 **20**(待验收),**不是 30**;`30`/`32` 由验收模块写。 +- **禁止**把「有没有采购」统一成 `IN (10,32)`(会把已完成采购误判为缺口)。 +- 对照表标 ⛔ 的站点不要顺手补 `<> 40`;作废单复活回 10 是故意设计。 + +完整条文见 [`.cursor/rules/purchase-prep-freeze.mdc`](.cursor/rules/purchase-prep-freeze.mdc)。 + +## 验收与加工冻结(硬规则) + +**未经开发者明确批准,不得改入库门槛、验收损耗或拒收回退。** + +- 评级**合格**才能入库;禁止恢复「不合格打标仍入库」。 +- 点退回订单 **40→30**;仓内加工成品不允许这条退回。 +- **退回也必须拍照**(2026-09-20 起):分类须拍又无照 → `inspection_photo_required`,**退回与入库同门槛**,称台退回也不再跳过;**禁止**把 `!isRejected` 加回闸门。 +- 验收不计损耗;仓内加工成品不入可领库存。 + +完整条文见 [`.cursor/rules/inspection-processing-freeze.mdc`](.cursor/rules/inspection-processing-freeze.mdc)。 + +## 分拣出库冻结(硬规则) + +**未经开发者明确批准,不得让分拣完成改订单计划量或把出库加回主界面。** + +- `confirmPickingComplete` 不写 `order_items.quantity` / `amount`。 +- **禁止**再接 `customer` 拣货模式(现码为 `order` / `category` / `sku`)。 +- 界面无独立出库;发车兜底 `delivery_loading_out`。 + +完整条文见 [`.cursor/rules/picking-freeze.mdc`](.cursor/rules/picking-freeze.mdc)。 + +## 配送履约冻结(硬规则) + +**未经开发者明确批准,不得改发车门槛、免入库/加菜拍照闸门、结案顺序与结算单生成。** + +- 50→60 只拦「无核货明细」;**库存不足不拦发车**,直送免入库也须 `order_status >= 50`。 +- 核货改实配**只写** `picking_items.loaded_qty`;`applySkipInboundSettlementForOrder` 是空实现,别加回回写。 +- 须拍而未拍:免入库与加菜**恒拦发车**;加菜另拦「拍照送达」。 +- **结案会生成客户结算单 + 供应商结算单**——模块说明 §1/§5「不写结算单」是错的,别照它删。 +- 进圈首次时间只写一次(`IS NULL` 守卫勿删);卸货时长 = **同一任务** `end_time − geofence_entered_at`。 +- 定位上报的 `order_code` 取自**请求体**(小程序恒不传)→ 那条 `SET task_status = 20` 的 UPDATE 是热路径,其 **`task_status < 20` 守卫勿删**(2026-09-20 `98e1b775` 补,修 A4)。`/delivery/start` 的同名分支取自任务行 `order_code`(恒有值)= 死代码,别当同类问题。 +- `delivery_tasks.order_code` 唯一(一订单一任务);`task_status` 只有 10/20/30;`isDeliveryOnlineRequired()` 恒 `false`。 + +权威文另列 **14 项已知异常**(非斤结算/出库取值优先级相反、改绑覆盖在途任务、打印扇出翻倍等)——**修与不修由开发者裁决,不得当成正确现状冻结,也不得顺手一起改**。 + +完整条文见 [`.cursor/rules/delivery-freeze.mdc`](.cursor/rules/delivery-freeze.mdc)。 + +## 商品主数据冻结(硬规则) + +**未经开发者明确批准,不得改商品档案的价格面、批量导入硬参数、同步方向与共用范围口径。** + +- **商品档案不含销售价/成本价**(`skus` / `product_catalog` 无该两列),价格只在报价单条目;**禁止**加回。 +- 批量导入:**≤200/块、串行、单文件 20MB、无行数上限**(有契约测试);**禁止**改并发或加回行数上限。 +- `stock_mode` **只有过手/管库存**可达,「继承分类 `is_fresh`」不可达,别按它实现。 +- `product_catalog` 是分类+商品同表,**同步是单向的**(`skus`/`categories` 上零触发器);**禁止**加反向触发器。 +- **共用范围的权威在 `quality_reports.share_mode`/`share_key`**;分类的 `quality_report_share_scope` 是孤儿列,不得当权威。 +- `pricing_unit` 服务端**无写入点**;重量单位有**四套定义**(`isPickingWeightUnit` 仍不认 `jin`;**「两」已于 2026-09-20 `65e7c695` 对齐**)——改之前先裁决以哪套为准。 + +权威文另列 **14 项已知异常**(触发器被文档写成双向、`share_scope` 孤儿列、`safeDeleteBySku` 静默吞错、删商品遗留孤儿等)——**修与不修由开发者裁决**。 + +完整条文见 [`.cursor/rules/product-freeze.mdc`](.cursor/rules/product-freeze.mdc)。 + +## 客户管理冻结(硬规则) + +**未经开发者明确批准,不得改删客户守卫与级联面、`delivery_time` 空值口径、预算/信用口径。** + +- **有历史订单即拒绝删除**;级联清单 12 张 + 结算单 + 本体。新增含 `customer_code` 的表**必须并入清单**。 +- **禁止**用 `/api/data` 的 delete 直删 `customers`(通用执行器对任意表构造裸 `DELETE`,绕过拒删与级联)。 +- `delivery_time` **无默认值、可空**;空值必须写 `NULL`,**不得写空串**;读侧只用 `deliveryDeadlineSql.ts` 的短路版。 +- `cost_budget` ↔ `budget_amount` **成对写**;`sales_budget` **已参与销售预警**(对照 §9 与列注释的「只存档」已过期)。 +- **信用不拦单**(唯一 block 是「客户不存在」);**禁止**恢复按额度/冻结拦单。 +- ⛔ **`customer_portal_users` 表不得 DROP / 改名**(删表会让整个删号接口 500,进而波及客户档案停用)。 + +权威文另列 **11 项已知异常**(`/api/data` 直删旁路、改绑覆盖在途任务、收货人无分公司校验等)——**修与不修由开发者裁决**。 + +完整条文见 [`.cursor/rules/customer-freeze.mdc`](.cursor/rules/customer-freeze.mdc)。 + +## 供应商管理冻结(硬规则) + +**未经开发者明确批准,不得合并两种直送、改经营品类隔离方式或放宽供应商停用前提。** + +- **`skip_inbound`(供应商免入库)与 `skus.direct_delivery`(商品直送)是两种货**,禁止合并判定。 +- 免入库行三条同时成立:**必拍照** / **不进验收待办** / **发车扣库跳过**;读取点五处,改谓词要同看。 +- `supplier_categories` **没有 `branch_code`**(实测),分公司归属经 `suppliers` 主表关联——**禁止**加列并改写分配查询。 +- 综合分数的快照表实测 **0 行** → 列表页对**所有**供应商显示「—」;`GRADE_SCORE` 回退值只用于履约预测与分配降权,**不得当真实履约分**。 +- `sku_suppliers` 四租户 **0 行**(兜底路径空转)——**禁止**因数据为空就删掉查询分支。 +- 供应商**有删除入口但无守卫、无级联**(前端 → `/api/data` 动态 `DELETE`)。⚠️ 前端注释「主档删除亦有 CASCADE」在**租户内不成立**(外键只有 `legacy_public` 有)——那两行手动清品类**是承重的**,不得当冗余删掉。⛔ **`supplier_users` 表不得 DROP / 改名**(删号链路会 500)。 + +完整条文见 [`.cursor/rules/supplier-freeze.mdc`](.cursor/rules/supplier-freeze.mdc)。 + +## 库存管理冻结(硬规则) + +**未经开发者明确批准,不得改入库/出库写入方、FIFO 保护、预留语义与调整留痕。** + +- 入库唯一业务写入方是**验收**;无订单走独立入库(成本价必须 > 0)。 +- **发车扣库用 `softInventory`:库存不足不拦发车**——禁止改成硬拦。 +- FIFO 顺序(效期优先)+ 批次 **`FOR UPDATE`**;**禁止**去掉行锁或改成「先查后改」。库存**不足时先部分扣减再抛错**——不是原子语义,发车 `softInventory` 依赖它。 +- ⚠️ **`consumeReservationsForOrder` 只改状态、不扣库、不写流水**(8 个调用点,含分拣出库推进会在**发车之前**消费整单预留)——**禁止把「预留已消费」当成「库存已扣」的证据**(出库事实唯一以 `inventory_logs` 为准)。 +- `inventory_logs` **无 CHECK**:新增类型必须同提交同步前端三语文案;**禁止**按文档只列 6 种去删在用类型。 +- `stock_mode` 只有 `pass_through` / `inventory`;**商品级过手 UI 已废弃**,历史行只读兼容——不得把「过手」做成可选。 +- `POST /inventory/adjust` 的**备注必填 + 双日志 + 「已拣未出库允许调高」死锁例外**三条都不得移除。 +- **库存表写权限已收窄**(须 `inventory_manage` 或 `purchase_manage`)——禁止把库存表加进采购员整体放行。 + +权威文另列 **13 项已知异常**(`consumed_only` 出口致「预留已消费但库存未扣」、`/api/data` 可直改库存绕过审计、`inventory_logs`/`inventory_reservations` **零 RLS**、缺口修补整个是死代码、公开页泄露实际库存量等)——**修与不修由开发者裁决**。 + +完整条文见 [`.cursor/rules/inventory-freeze.mdc`](.cursor/rules/inventory-freeze.mdc)。 + +## 运营支撑冻结(硬规则) + +**未经开发者明确批准,不得改售后自动单的终态锁定、异常与订单状态的分离、或行情来源语义。** + +- ⚠️ **后端「有」`opsModule` 注册项,但它不挂路由**(`businessModules.ts` 的 `opsModule` 无 `workflowApiPrefix`/`mountWorkflowRoutes`)——能力分挂订单/商品/平台三套路由;**「后端没有注册项」是过期说法**,**不要新建第二个 ops 模块,也不要删这个注册项**。 +- 售后三类**自动单建单即终态**(`OIR_` 订单退货 / `SIV_` 独立入库作废 / `OIS_` 已入库改派):`status=30` + `handled_at` + `closed_at`;锁定**按类型**判、**三类错误码各不相同**(`order_return_locked` / `spi_void_locked` / `inbound_switch_locked`)。**禁止**改成可受理(意义就是**防二次冲账**)、**禁止**改单号前缀或锁定码。`handle_method` 实值为 `order_item_return`(「已红冲」只是 `reason` 文案)。 +- ⚠️ **该「不可再受理」只在服务层成立**:`after_sales` 不在 `DENY_WRITE_TABLES`,经 `/api/data` 可裸改绕过 409(已被 `routeLayerBoundary.test.ts` pin 住)。 +- 日期口径**两类**:客诉按配送日;**三类自动单按操作日 `created_at`**(否则当天操作当天看不到)。 +- 主表是 **`after_sales`**(不是 `after_sales_tickets`);`after_sale_returns` 仅 `handle_method='return'` 写入、**全租户 0 行**(可用但业务未走,**不得据此删表**)。 +- **异常工单状态 ≠ 订单状态**;「不问数/补货建议/AI 解析指标」小组件**已移除**,不得未获批准加回。 +- **市场监控:页面在运营、接口在商品模块**。行情**只有 `external`/`supplier_avg`/`ai` 且未过期才黄橙红**,`estimated` 不报警;`rebase_only` **不调 Ark**;刷新主路径不依赖 `MARKET_PRICE_API_URL`。 +- **售后的成本回冲 + 结算调整属财务冻结范围**——改前须走财务冻结流程。 + +完整条文见 [`.cursor/rules/ops-freeze.mdc`](.cursor/rules/ops-freeze.mdc)。 + +## 平台与系统冻结(硬规则) + +**本模块是分公司隔离与鉴权的配置中心——动它等于动所有模块。未经明确批准,不得改租户名单、鉴权、数据访问策略与落地路径。** + +- **新业务表必须写进 `public.tenant_business_tables()`**;迁移期**有断言守卫**(失败即中断迁移)。历史事故 **BR004 曾少 3 张表**。**禁止**删守卫或只对存量 schema 建表。 +- **客户门户已彻底下线**:**禁止**恢复「零角色可登录」例外。新增身份后缀/角色必须同时更新 `LOGIN_SUFFIXES` 与**落地路径**。 +- 四张名单:`ALLOWED_TABLES` / **`DENY_WRITE_TABLES`(禁写,即使有权限)** / `WRITE_PERMISSIONS` / 作用域名单。⚠️ **通用网关能写业务表(靠权限码)**:`customers`(绕过拒删与级联)、`inventory`/`inventory_logs`(绕过备注必填与双日志)、`suppliers` 都是实例——**禁止**未评估就放行新表,**禁止**把结算/成本表移出禁写。 +- LLM 顺序固定 **分公司覆盖 → 平台默认 → `.env`**;提示词顺序固定 **分公司覆盖 > 已发布 > 代码 DEFAULT**。**线上生效文案必须走发布流程升 `version`**(`version=1` 每次部署被代码默认值覆盖)。三组表属**重点保护对象**,禁止 dev → prod 数据写入。 +- **落地路径三处必须一致**,**不变量:落地路径必须是该角色真能访问的路由**;现取值 **`super_admin → /system/config`**、`admin → /dashboard`;改一处必须三处同改并跑 `homePathConsistency.test.ts`。 +- **平台分公司禁止维护商品主数据与录单**;**操作日志保留只删 `operation_logs`(默认一个月、分批),不得把 `inventory_logs` 纳入**;**字段级权限方案已移除,不得恢复**。 + +完整条文见 [`.cursor/rules/platform-freeze.mdc`](.cursor/rules/platform-freeze.mdc)。 + +## 数据看板冻结(硬规则) + +**未经开发者明确批准,不得改净利/成本口径、周期裁切、损耗取数来源与落地路径。** + +- **本模块纯只读**——不得新增写路径(不回写履约或结算)。 +- **净利润复用 `computeFinanceNetProfit`**(唯一实现 + `Object.freeze`);**禁止**另写一份。 +- 成本 KPI 账本窗口排除 `inventory_holding` 与重复占位行、**采购项用订单行口径**、`ledger_total = Σ构成`、**9 类与 `COST_CATEGORIES` 逐项一致**。 + ⚠️ **净利与成本口径属 [finance-freeze](.cursor/rules/finance-freeze.mdc) 范围**——改动必须走财务冻结流程。 +- **未结束的快捷周期止日裁到 `asOf`**,**自定义区间不裁切**;前后端**各有一份** `clipPeriodEndToAsOf`,改必须两份同改。 +- **损耗只认 `processing_tasks.loss_qty`**(完工中国日),**禁止**改成验收 `inspections.loss_qty`(会恒为 0)。 +- 需求预测**默认不自动请求**;下钻**必须携带区间**。 +- 看板菜单 **`roles: ['admin']` 不含超管**(后端放行集合是 `{admin, super_admin}`,比菜单宽);**禁止**把超管落地改回 `/dashboard`(会造成自环)。 + +⚠️ **一处待业务确认的口径差异(不是账错,别当 bug 修)**:净利要减的「期间费用」判定只看「该成本有没有挂订单号」,而「**库存持有**」(`inventory_holding`,盘盈/库存重估类)的行恰好都没订单号 → 被计入期间费用;可成本 KPI 一侧明确写了排除它(`excludeInventoryHoldingFromKpiSql`)。实测差额 BR002 cycle 202609 = **148 行 / 1,627.03 元**(占期间固定 3.6%)。**两种可能都保留**,需业务/财务确认该不该算本期成本;改动会同时影响看板净利、财务概览净利与客户预算预警,**属 [finance-freeze](.cursor/rules/finance-freeze.mdc) 流程**。 +⚠️ 另注:「**所有成本**」(成本构成)与「**净利润**」(损益)**本就是不同口径的聚合,不相等正常**——**不要**拿「两张卡对不上」当缺陷依据。 + +权威文另列 **9 项已知异常**(成本归类致非固定桶 **26.3%**、页头周期下拉已消失故裁切仅 API 可达、账本聚合**实测 1,681 ms / 542k shared hit** 且 `recentOrders` 无 LIMIT、9 类一致性无测试钉住等)——**修与不修由开发者裁决**;**禁止**把归类偏差当正确口径冻结。 + +完整条文见 [`.cursor/rules/dashboard-freeze.mdc`](.cursor/rules/dashboard-freeze.mdc)。 + +## 前端文案与小字:不得擅自增删(硬规则) + +**修改前端时,别未经许可擅自添加小字。** 界面文案属于产品决策,不属于实现细节。 + +- **必须先请示**:说明小字/提示语/tooltip/副标题/placeholder/按钮与标签文字的新增或修改。 +- **反面案例**:给供应商备货表加过「数据量过大,仅显示最近 N 条…」提示条(自行增添), + 阈值还设得不当导致正常业务也弹提示 —— 用户随后要求调整与删除。 +- **删除文案也要问清范围**:只删被指出的那一项;若与其它文案共用条件分支, + 删后必须保证其余分支仍正常显示(**不得出现"连提示都没有了"的退步**)。 +- **发现文案有误只报告不动手**:附位置与建议,由开发者决定。 +- **允许直接做**:用户明确要求的改动;把已确认的中文同步到 `en`/`id`;纯代码注释。 + +完整条文见 [`.cursor/rules/frontend-copy-changes.mdc`](.cursor/rules/frontend-copy-changes.mdc)。 + +## 前端界面纪律(硬规则) + +改 Web / 小程序界面时:**不擅自加小字**;**只改被点名的面**(共享组件会扩散,先问);**先复用现成组件**,不为对齐去改 B 面;保存/确认须**在途锁**,搜索须防抖或确认才请求;打开详情/切单必须用 **generation + 实体 id**,过期响不得写入(订单详情事故见 `docs/design/20260911-order-detail-stale-fetch.md`)。 + +完整条文见 [`.cursor/rules/frontend-ui-discipline.mdc`](.cursor/rules/frontend-ui-discipline.mdc)。 + +## 变更范围与变更清单(硬规则) + +- **只动被要求的地方**:不顺手修、不顺手清理、不顺手统一风格。范围外的问题只报告,不动手。 +- **越界先请示**:确需改范围外文件(如改签名要同步调用方),先说明「改什么、为什么非改不可、 + 影响面与回滚方式」,拿到明确许可再动。 +- **完工必须给变更清单**:列出「文件路径 / 新增·修改·删除 / 改动意图 / 是否在授权范围内」, + 范围外改动单独标注;同时给出用户可自行执行的核对命令(`git status --porcelain`、`git diff --stat`)。 +- **用客观基线代替自我报告**:任务开始记录 `git rev-parse HEAD` + `git status --porcelain`, + 结束用同命令重新采集并对比。 + +完整条文见 [`.cursor/rules/change-scope.mdc`](.cursor/rules/change-scope.mdc)。 diff --git a/ARCHITECTURE.html b/ARCHITECTURE.html new file mode 100644 index 0000000..d4bb591 --- /dev/null +++ b/ARCHITECTURE.html @@ -0,0 +1,13708 @@ + + + + + + + AI 生鲜配送系统 — 架构总览 Diagram + + + + + + + + + + + +
+ +
+
+
+

AI 生鲜配送系统 — 架构总览

+
+
+ + + + + + +
+ + AI 生鲜配送系统 — 架构总览 + A architecture diagram generated by Archify. + + + + + + + + + + + + + + + + + + + + + + + + + 腾讯云 CVM + + + 内网 + + + + + + + + + + + + + + + 微信平台 · 登录/支付/订阅 · Architecture component + + + + 微信平台 + 登录/支付/订阅 + + + + 火山引擎 Ark · AI 解析/识别/生图 · Architecture component + + + + 火山引擎 Ark + AI 解析/识别/生图 + + + + Web 管理端 · React SPA / 角色权限 · Architecture component + + + + Web 管理端 + React SPA / 角色权限 + + + + 微信小程序 · 供应商/采购/仓管/配送 · Architecture component + + + + 微信小程序 + 供应商/采购/仓管/配送 + + + + 供应商 H5 · 备货/报价/质检报告 · Architecture component + + + + 供应商 H5 + 备货/报价/质检报告 + + + + Nginx · HTTPS 路由分发 · 腾讯云 CVM + + + + Nginx + HTTPS 路由分发 + + + + Go 后端 · Gin :3002 / ~242 端点 · 腾讯云 CVM › 内网 · 主力业务 + + + + Go 后端 + Gin :3002 / ~242 端点 + 主力业务 + + + + Node.js 后端 · Express :3001 / AI 能力 · 腾讯云 CVM › 内网 · AI 兜底 + + + + Node.js 后端 + Express :3001 / AI 能力 + AI 兜底 + + + + PostgreSQL · 主库 / 16 业务域 · 腾讯云 CVM › 内网 + + + + PostgreSQL + 主库 / 16 业务域 + + + + OSS/S3 · 文件存储 / 5 个桶 · 腾讯云 CVM + + + + OSS/S3 + 文件存储 / 5 个桶 + + + + + + HTTPS + + + + + + /api/* (主力) + + + + AI / 订阅 / 地图 + + + + SQL + + + + SQL + + + + 文件读写 + + + + LLM API + + + + + Legend + + + Frontend + + + + Backend + + + + Database + + + + Cloud + + + + External + + + +

+ + + + + + + + +
+ + +
+
+
+
+

前端层

+
+
    +
  • • Web 管理端 (React SPA):订单管理、商品、财务、系统配置
  • +
  • • 微信小程序:供应商备货、采购员加单、仓管验收/分拣、配送签收
  • +
  • • 供应商 H5:备货接单、价格修改、质检报告上传、竞价报价
  • +
+
+ +
+
+
+

后端分工

+
+
    +
  • • Go (Gin) :3002 — 主力业务引擎,覆盖订单、分配、履约、配送、财务全链路
  • +
  • • Node.js (Express) :3001 — AI 能力专精:LLM 订单解析、语音转写、深度成本分析
  • +
+
+ +
+
+
+

数据与存储

+
+
    +
  • • PostgreSQL 主库:订单域、履约域、仓储域、配送域、财务域、基础域
  • +
  • • OSS/S3 文件存储:质检照片、签收照片、凭证照片、商品图片、质检报告
  • +
+
+
+ +
+ + + + diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..d06e3d9 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,1179 @@ +# 食堂配送系统 — 整体拓扑图 + +``` +┌─────────────────────────────────────────────────────────────────────────────────────────────┐ +│ 🖥️ 前端层 │ +│ │ +│ ┌──────────────────┐ ┌──────────────────────┐ ┌──────────────────┐ │ +│ │ 微信小程序 (MP) │ │ Web 管理端 (Admin) │ │ 供应商 H5/API │ │ +│ │ │ │ │ │ │ │ +│ │ • 客户下单 │ │ • 订单管理/推进 │ │ • 备货接单 │ │ +│ │ • 采购员加单/自采 │ │ • 分配/履约/财务 │ │ • 价格修改 │ │ +│ │ • 配送员装车/签收 │ │ • 供应商/客户管理 │ │ • 质检报告上传 │ │ +│ │ • 仓管验收/分拣 │ │ • 商品/分类/角色 │ │ • 竞价报价 │ │ +│ │ • 加工任务 │ │ • 仪表板/审计 │ │ • OAuth 集成 │ │ +│ └────────┬─────────┘ └──────────┬───────────┘ └────────┬─────────┘ │ +│ │ │ │ │ +│ │ /api/mobile/* │ /api/* /api/workflow/* │ /api/supplier/* │ +│ ▼ ▼ ▼ │ +├─────────────────────────────────────────────────────────────────────────────────────────────┤ +│ 🌐 API 网关层 │ +│ │ +│ ┌─────────────────────────────────────────────────────────────────────────────────────┐ │ +│ │ Nginx / 直连 (路由分发) │ │ +│ │ │ │ +│ │ /api/mobile/* ──────────▶ Go :3002 (主力) │ │ +│ │ /api/workflow/* ──────────▶ Go :3002 (主力) │ │ +│ │ /api/supplier/* ──────────▶ Go :3002 (主力) │ │ +│ │ /api/* ──────────▶ Go :3002 (主力) + Node :3001 (AI 兜底) │ │ +│ │ /api/storage/* ──────────▶ Go :3002 (文件上传/签名读取) │ │ +│ └─────────────────────────────────────────────────────────────────────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────────────────────────────┘ + │ + ┌───────────────────────────────┴───────────────────────────────┐ + ▼ ▼ +┌─────────────────────────────────────┐ ┌─────────────────────────────────────┐ +│ 🟢 Go 后端 :3002 │ │ 🔵 Node.js 后端 :3001 │ +│ Gin + pgx + ~242 端点 │ │ Express + pg + ~200 端点 │ +│ │ │ │ +│ ┌───────────────────────────────┐ │ │ 负责: │ +│ │ httpapi (路由层) │ │ │ • AI 订单解析 (LLM) │ +│ │ router.go (159 路由) │ │ │ • 语音转写 │ +│ │ workflow_*.go (58 路由) │ │ │ • 深度成本分析 (26 端点) │ +│ │ mobile_*.go (移动端处理) │ │ │ • 微信订阅通知 │ +│ │ admin_*.go (管理端处理) │ │ │ • 腾讯地图路线规划 │ +│ │ supplier_api*.go (供应商API) │ │ │ │ +│ └───────────────┬───────────────┘ │ └──────────────────┬──────────────────┘ +│ │ │ │ +│ ┌───────────────┼────────────────────────────────────────┼──────────────────┐ │ +│ │ ▼ 🏗️ 业务层 ▼ │ │ +│ │ │ │ +│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────┐ │ │ +│ │ │orderentry│ │orderadmin│ │ delivery │ │ purchase │ │ supplierbiz │ │ │ +│ │ │ 订单录入 │ │ 订单管理 │ │ 配送管理 │ │ 采购管理 │ │ 供应商业务 │ │ │ +│ │ │ submit │ │ manage │ │ tasks │ │ assign │ │ preps/quality│ │ │ +│ │ │ sync │ │ trace │ │ advance │ │ operation│ │ prepamend │ │ │ +│ │ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ └──────┬───────┘ │ │ +│ │ │ │ │ │ │ │ │ +│ │ ┌────┴────┐ ┌─────┴─────┐ ┌───┴────┐ ┌─────┴─────┐ │ │ +│ │ │allocation│ │orderfulfill│ │picking │ │inspection │ ┌──────────────┐ │ │ +│ │ │ 分配引擎 │ │ 履约管理 │ │ 分拣称重│ │ 质检验收 │ │ processing │ │ │ +│ │ │ engine │ │fulfillment│ │outbound│ │ advance │ │ ⚡ 独立模块 │ │ │ +│ │ │ rules │ │ │ │ weigh │ │compliance │ │ 加工/损耗 │ │ │ +│ │ └─────────┘ └───────────┘ └────────┘ └───────────┘ └──────────────┘ │ │ +│ │ │ │ +│ │ ┌──────────────────────────────────────────────────────────────────┐ │ │ +│ │ │ 💰 财务层 │ │ │ +│ │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────┐ │ │ │ +│ │ │ │ finance │ │ invcost │ │ pricing │ │ workflow │ │ │ │ +│ │ │ │ 对账结算 │ │ 库存成本 │ │ 报价定价 │ │ 工作流引擎 │ │ │ │ +│ │ │ │statement │ │ bid/cost │ │ │ │ customer │ │ │ │ +│ │ │ │ aging │ │ │ │ │ │ supplier │ │ │ │ +│ │ │ └──────────┘ └──────────┘ └──────────┘ │ delivery │ │ │ │ +│ │ │ │ finance │ │ │ │ +│ │ │ │ bid │ │ │ │ +│ │ │ │ import │ │ │ │ +│ │ │ │ units │ │ │ │ +│ │ │ └──────────────┘ │ │ │ +│ │ └──────────────────────────────────────────────────────────────────┘ │ │ +│ │ │ │ +│ │ ┌──────────────────────────────────────────────────────────────────┐ │ │ +│ │ │ 🔧 横向支撑层 │ │ │ +│ │ │ │ │ │ +│ │ │ ┌──────┐ ┌──────┐ ┌───────┐ ┌───────┐ ┌──────┐ ┌────────┐ │ │ │ +│ │ │ │ auth │ │tenant│ │storage│ │notify │ │ db │ │config │ │ │ │ +│ │ │ │ JWT │ │ 多租户│ │OSS/S3 │ │ 通知 │ │连接池│ │ 配置 │ │ │ │ +│ │ │ └──────┘ └──────┘ └───────┘ └───────┘ └──────┘ └────────┘ │ │ │ +│ │ │ │ │ │ +│ │ │ ┌────────┐ ┌──────────┐ ┌─────────┐ ┌────────┐ ┌──────────┐ │ │ │ +│ │ │ │bizerr │ │featurecfg│ │tenantscope│ │picking│ │queryexec │ │ │ │ +│ │ │ │ 业务错误 │ │ 功能开关 │ │ 租户上下文 │ │ 查询接口│ │ 查询执行 │ │ │ │ +│ │ │ └────────┘ └──────────┘ └─────────┘ └────────┘ └──────────┘ │ │ │ +│ │ └──────────────────────────────────────────────────────────────────┘ │ │ +│ └───────────────────────────────────────────────────────────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────────────────────────┐ +│ 🗄️ 数据层 │ +│ │ +│ ┌───────────────────────────────────────┐ ┌──────────────────────────────────┐ │ +│ │ PostgreSQL (主库) │ │ OSS/S3 (文件存储) │ │ +│ │ │ │ │ │ +│ │ ┌─────────────────────────────────┐ │ │ /inspection-photos/ (质检照片) │ │ +│ │ │ 订单域 │ │ │ /delivery-photos/ (签收照片) │ │ +│ │ │ orders, order_items │ │ │ /invoices/ (凭证照片) │ │ +│ │ │ order_item_fulfillments │ │ │ /sku-images/ (商品图片) │ │ +│ │ └─────────────────────────────────┘ │ │ /quality-reports/ (质检报告) │ │ +│ │ ┌─────────────────────────────────┐ │ │ /processing-inspection-photos/ │ │ +│ │ │ 履约域 │ │ └──────────────────────────────────┘ │ +│ │ │ supplier_preparations (备货) │ │ │ +│ │ │ purchase_orders (自采单) │ │ │ +│ │ └─────────────────────────────────┘ │ │ +│ │ ┌─────────────────────────────────┐ │ │ +│ │ │ 仓储域 │ │ │ +│ │ │ inspections (验收) │ │ │ +│ │ │ processing_tasks (加工) ⚡独立 │ │ │ +│ │ │ picking_tasks (分拣) │ │ │ +│ │ │ inventory (库存) │ │ │ +│ │ └─────────────────────────────────┘ │ │ +│ │ ┌─────────────────────────────────┐ │ │ +│ │ │ 配送域 │ │ │ +│ │ │ delivery_tasks (配送任务) │ │ │ +│ │ │ delivery_signatures (签收) │ │ │ +│ │ │ delivery_loading_items (装车) │ │ │ +│ │ └─────────────────────────────────┘ │ │ +│ │ ┌─────────────────────────────────┐ │ │ +│ │ │ 财务域 │ │ │ +│ │ │ customer_statements (客户对账) │ │ │ +│ │ │ supplier_statements (供应商对账) │ │ │ +│ │ │ cost_details (成本明细) │ │ │ +│ │ │ operation_logs (审计日志) │ │ │ +│ │ └─────────────────────────────────┘ │ │ +│ │ ┌─────────────────────────────────┐ │ │ +│ │ │ 基础域 │ │ │ +│ │ │ users, roles, suppliers │ │ │ +│ │ │ customers, purchasers, branches │ │ │ +│ │ │ skus, categories, system_configs │ │ │ +│ │ └─────────────────────────────────┘ │ │ +│ └───────────────────────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────────────────────────┐ +│ 🌍 外部集成层 │ +│ │ +│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ +│ │ 微信小程序 │ │ 腾讯地图 │ │ AI/LLM │ │ OSS/S3 │ │ +│ │ 登录/支付 │ │ 路线规划 │ │ 订单解析 │ │ 文件存储 │ │ +│ │ 订阅消息 │ │ (Node) │ │ 智能分类 │ │ │ │ +│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────────────────────┘ +``` + +--- + +## 订单主流程(核心数据流) + +``` + ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ + │ 01 下单 │ ──▶ │ 02 分配 │ ──▶ │ 03 验收 │ ──▶ │ 04 分拣 │ ──▶ │ 05 配送 │ ──▶ │ 06 结算 │ + │ │ │ │ │ │ │ │ │ │ │ │ + │ status 20│ │status 20→│ │status 30→│ │status 40→│ │status 50→│ │status 90 │ + │ 待分配 │ │ 30 │ │ 40 │ │ 50 │ │ 90 │ │ 完成 │ + └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ └──────────┘ + │ │ │ │ │ + ▼ ▼ ▼ ▼ ▼ + orderentry allocation inspection picking delivery + submit.go engine.go advance.go outbound.go advance.go + │ │ │ │ │ + ▼ ▼ ▼ ▼ ▼ + INSERT INSERT INSERT INSERT INSERT + orders supplier_ inspections picking_ delivery_ + order_items preparations (验收记录) tasks tasks + purchase_ (分拣任务) (配送任务) + orders + (自采单) + + ┌──────────────────────────────────────────────────────────────────────────────────┐ + │ ⚡ 独立模块(并行,不阻塞) │ + │ │ + │ 验收(40) ─────────────────────────▶ 分拣(45) ─────────▶ 配送(50) ← 主流程 │ + │ │ │ │ + │ └────────────┬───────────────────────┘ │ + │ │ 并行触发(不阻塞订单状态) │ + │ ▼ │ + │ ┌─────────────────────────────┐ │ + │ │ 加工模块 (processing) │ ← 独立路由 /api/mobile/processing/* │ + │ │ • 从验收单自动生成加工任务 │ │ + │ │ • 可手动创建独立加工单 │ ← /processing/standalone/create │ + │ │ • 完工记录损耗 + 人工成本 │ │ + │ │ • 加工验收拍照 │ │ + │ └─────────────────────────────┘ │ + └──────────────────────────────────────────────────────────────────────────────────┘ +``` + +--- + +## 模块间调用关系 + +``` + httpapi (路由入口) + │ + ├──▶ orderentry ──▶ allocation ──▶ orderfulfill + │ │ │ + │ ▼ ▼ + │ pricing purchase + │ invcost supplierbiz + │ + ├──▶ orderadmin ──▶ orderfulfill ──▶ picking + │ │ │ + │ ▼ ▼ + │ producttrace delivery + │ inspection + │ + ├──▶ delivery ──▶ delivery/advance ──▶ finance + │ + ├──▶ inspection ──▶ invcost + │ │ + │ ▼ + │ processing (独立) + │ + ├──▶ supplierbiz ──▶ finance + │ + └──▶ workflow/finance ──▶ finance + │ + ▼ + workflow/customer + workflow/supplier + workflow/delivery + workflow/bid +``` + +--- + +## 状态机 + +``` + ┌─────────────────────────────────┐ + │ 订单状态流转 (主流程) │ + └─────────────────────────────────┘ + + ┌──────┐ 分配引擎 ┌──────┐ 验收 ┌──────┐ 分拣 ┌──────┐ 发车 ┌──────┐ 签收 ┌──────┐ + │ 20 │ ────────▶ │ 30 │ ───────▶ │ 40 │ ──────▶ │ 50 │ ──────▶ │ 60 │ ──────▶ │ 90 │ + │待分配 │ │已分配 │ │待验收 │ │待配送 │ │配送中 │ │ 完成 │ + └──────┘ └──────┘ └──────┘ └──────┘ └──────┘ └──────┘ + │ │ │ + │ │ 验收不通过 │ 配送异常 + ▼ ▼ ▼ + ┌──────┐ ┌──────┐ ┌──────────┐ + │ 自采 │ │ 41 │ │ 异常工单 │ + │ 转供应商│ │ 退回 │ │ exception │ + └──────┘ └──────┘ └──────────┘ + + ═══════════════════════════════════════════════════════════════════════════════════════════ + ⚡ 加工模块独立状态机(不阻塞订单) + ═══════════════════════════════════════════════════════════════════════════════════════════ + + ┌──────┐ 开始 ┌──────┐ 完工 ┌──────┐ 验收 ┌──────┐ + │ 10 │ ───────▶ │ 20 │ ───────▶ │ 30 │ ───────▶ │ 40 │ + │ 待加工 │ │ 加工中 │ │ 待验收 │ │ 已完成 │ + └──────┘ └──────┘ └──────┘ └──────┘ +``` + +--- + +## Go 包依赖层次 + +``` +Layer 4 httpapi ───────────────────────────────────── (路由 + 处理器) + │ +Layer 3 orderentry orderadmin delivery supplierbiz purchase inspection + picking processing(⚡) allocation finance invcost workflow + │ +Layer 2 orderfulfill prepamend pricing producttrace stockin catalog + weighstation skuimage menugroupicon uipref userbinding + │ +Layer 1 auth tenant db storage notify config llm prompts + wechat bizerr featurecfg tenantscope queryexec chinadate + branchtax mobile purchaseradmin supplieradmin accountlogin + jwtutil password purchaserorder +``` + +--- + +## 数据表关系 (核心) + +``` + ┌─────────────────────────────────────┐ + │ orders (订单) │ + │ order_code PK │ customer_code │ + │ order_status │ total_amount │ + │ branch_code │ delivery_date │ + └───────────────┬─────────────────────┘ + ┌──────────────────────┼──────────────────────┐ + │ 1:N │ 1:N │ 1:N + ▼ ▼ ▼ + ┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐ + │ order_items │ │ inspections │ │ delivery_tasks │ + │ (订单明细) │ │ (验收记录) │ │ (配送任务) │ + │ id PK │ │ id PK │ │ task_code PK │ + │ sku_code │ │ inspection_ │ │ task_status │ + │ supplier_code │ │ status │ │ driver_id │ + │ quantity │ │ processing_ │ └────────┬────────┘ + │ price │ │ details │ │ + └────────┬─────────┘ └────────┬──────────┘ │ + │ │ │ + ┌───────────┼──────────┐ │ ┌────────┴────────┐ + ▼ ▼ ▼ ▼ ▼ ▼ +┌──────────┐ ┌────────┐ ┌────────┐ ┌──────────┐ ┌────────────┐ ┌────────────────┐ +│ order_ │ │supplier│ │purchase│ │processing│ │ picking │ │ delivery_ │ +│ item_ │ │_prepa- │ │_orders │ │_tasks │ │ _tasks │ │ signatures │ +│ fulfill- │ │rations │ │(自采单) │ │(加工⚡) │ │ (分拣) │ │ (签收) │ +│ ments │ │(备货) │ │ │ │ │ │ │ │ │ +└──────────┘ └────────┘ └────────┘ └──────────┘ └────────────┘ └────────────────┘ +``` + +--- + +## Go ↔ Node.js 分工 + +| 模块 | Go :3002 | Node :3001 | 说明 | +|------|:--------:|:----------:|------| +| 订单提交/改单 | ✅ | ✅ | Go 已完全替代 | +| 分配引擎 | ✅ | ✅ | Go Pipeline 实现 | +| 备货/自采 | ✅ | ✅ | Go 已完全替代 | +| 验收/分拣 | ✅ | ✅ | Go 已完全替代 | +| 配送管理 | ✅ | ✅ | Go 已完全替代 | +| 加工模块 | ✅ (独立) | ✅ | Go 独立实现 | +| 财务结算 | ✅ | ✅ | Go 已完全替代 | +| 供应商管理 | ✅ | ✅ | Go 已完全替代 | +| 深度成本分析 | 🟡 空返回 | ✅ | 26 端点 AI 依赖 | +| 微信订阅通知 | ❌ | ✅ | 需模板 ID 配置 | +| AI 订单解析 | ❌ | ✅ | LLM 依赖 | +| 语音转写 | ❌ | ✅ | LLM 依赖 | +| 腾讯地图路线 | ❌ | ✅ | 外部 API 依赖 | + + +--- + +# 全部系统数据流 + +## 1. 订单录入流 (Order Entry) + +``` +客户小程序 Go 后端 DB +───────── ──────── ── +│ 选品下单 │ +└────┬────┘ + │ POST /api/mobile/customer-order/orders + ▼ +┌─────────────┐ ┌──────────────────┐ ┌─────────────────────┐ +│ mobile_order │ ──▶ │ orderentry/ │ ──▶ │ 1. 商品智能分类 │ +│ .go │ │ submit.go │ │ 2. 报价定价 (pricing)│ +│ │ │ SubmitMobile │ │ 3. 预算校验 │ +│ │ │ CustomerOrder() │ │ 4. 零价拦截 │ +└─────────────┘ └────────┬─────────┘ └──────────┬──────────┘ + │ │ + ▼ ▼ + ┌──────────────┐ ┌──────────────┐ + │ 5. 生成订单号 │ │ 6. 商品建档 │ + │ allocateOrder │ │ upsert skus │ + │ Code() │ │ product_catalog│ + └──────┬───────┘ └──────────────┘ + │ + ▼ + ┌──────────────┐ + │ 7. INSERT │ + │ orders + │ + │ order_items │ + │ (status=20) │ + └──────┬───────┘ + │ + ▼ + ┌──────────────┐ ┌──────────────┐ + │ 8. 分配引擎 │ ──▶ │ allocation/ │ + │ ReprocessOrder│ │ engine.go │ + │ Allocation() │ │ 规则引擎分配 │ + └──────┬───────┘ └──────┬───────┘ + │ │ + ▼ ▼ + ┌──────────────┐ ┌──────────────┐ + │ 9. 库存成本 │ │ 10. INSERT │ + │ invcost 写回 │ │ supplier_ │ + │ │ │ preparations │ + └──────────────┘ │ purchase_ │ + │ orders │ + └──────────────┘ +``` + +## 2. 采购员加单/改单流 (Purchaser Order Management) + +``` +采购员小程序 Go 后端 DB +─────────── ──────── ── +│ 加单/改单 │ +└────┬─────┘ + │ POST /api/mobile/purchaser/order-items/orders/:code/items + │ PATCH /api/mobile/purchaser/order-items/orders/:code + ▼ +┌─────────────────┐ ┌──────────────────┐ ┌─────────────────────┐ +│ mobile_purchaser │ ──▶ │ orderentry/ │ ──▶ │ 1. 行锁订单 orders │ +│ _order.go │ │ sync_main.go │ │ FOR UPDATE │ +│ │ │ SyncOrderManage │ │ 2. 状态校验 │ +│ │ │ Items() │ │ 3. 零价加菜拦截 │ +└─────────────────┘ └────────┬──────────┘ └──────────┬──────────┘ + │ │ + ▼ ▼ + ┌──────────────┐ ┌──────────────┐ + │ 4. 删行+upsert│ │ 5. 重算金额/ │ + │ order_items │ │ 重量 │ + └──────┬───────┘ └──────────────┘ + │ + ┌────────────┴────────────┐ + ▼ ▼ + ┌────────────┐ ┌──────────────┐ + │ 订单未完成 │ │ 订单已完成 │ + │ status<90 │ │ status≥90 │ + └──────┬─────┘ └──────┬───────┘ + │ │ + ▼ ▼ + ┌────────────┐ ┌──────────────┐ + │ 分配引擎 │ │ 库存覆盖 │ + │ allocation │ │ + 财务结算 │ + │ engine.go │ │ + 成本回写 │ + └────────────┘ └──────────────┘ +``` + +## 3. 分配引擎流 (Allocation Engine) + +``` +触发: 订单提交 / 改单 / Web端手动分配 +───────────────────────────────────────────────── + +┌─────────────────────────────────────────────────────────────────────┐ +│ allocation/engine.go │ +│ │ +│ Phase 1: Validate & Lock │ +│ ┌──────────────────────────────────────────────────────────────┐ │ +│ │ SELECT ... FROM orders WHERE order_code = $1 FOR UPDATE │ │ +│ │ 校验: 订单存在 + 状态<90 │ │ +│ └──────────────────────────────────────────────────────────────┘ │ +│ │ │ +│ ▼ │ +│ Phase 2: Load Context (4 goroutines 并行) │ +│ ┌──────────┐ ┌──────────┐ ┌─────────────┐ ┌──────────────┐ │ +│ │ 加载规则 │ │ 加载供应商│ │ 加载分类绑定 │ │ 加载SKU供货 │ │ +│ │ system_ │ │ suppliers│ │ supplier_ │ │ sku_supplier_ │ │ +│ │ configs │ │ │ │ categories │ │ prices │ │ +│ └──────────┘ └──────────┘ └─────────────┘ └──────────────┘ │ +│ │ │ +│ ▼ │ +│ Phase 3: Load & Enrich Items │ +│ ┌──────────────────────────────────────────────────────────────┐ │ +│ │ SELECT ... FROM order_items WHERE order_code = $1 FOR UPDATE │ │ +│ └──────────────────────────────────────────────────────────────┘ │ +│ │ │ +│ ▼ │ +│ Phase 4: Allocate (规则引擎) │ +│ ┌──────────────────────────────────────────────────────────────┐ │ +│ │ 对每个未履约商品: │ │ +│ │ SKU供货目录匹配 → 供应商备货 │ │ +│ │ 分类绑定供应商 → 供应商备货 (优先 primary) │ │ +│ │ 无匹配 → 自采单 (purchase_orders) │ │ +│ └──────────────────────────────────────────────────────────────┘ │ +│ │ │ +│ ▼ │ +│ Phase 5: Finalize │ +│ ┌──────────────────────────────────────────────────────────────┐ │ +│ │ 覆盖未履约商品 → 强制自采兜底 │ │ +│ │ INSERT supplier_preparations + purchase_orders │ │ +│ │ INSERT order_item_fulfillments (履约关联) │ │ +│ │ UPDATE orders SET order_status = 30 │ │ +│ └──────────────────────────────────────────────────────────────┘ │ +│ │ │ +│ ▼ │ +│ Phase 6: PostProcess (异步 goroutine) │ +│ ┌──────────────────────────────────────────────────────────────┐ │ +│ │ ensureInspections (确保验收记录) │ │ +│ │ reconcileArtifacts (清理孤儿备货) │ │ +│ └──────────────────────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +## 4. 供应商备货流 (Supplier Preparation) + +``` +供应商 H5/小程序 Go 后端 DB +───────────── ──────── ── +│ 查看备货单 │ +└────┬──────┘ + │ GET /api/supplier/preparations + ▼ +┌─────────────────┐ ┌──────────────────┐ +│ supplier_api.go │ ──▶ │ supplierbiz/ │ +│ handleSupplier │ │ preps.go │ +│ ApiPreparations │ │ ListSupplier │ +│ │ │ Preparations() │ +└─────────────────┘ └────────┬─────────┘ + │ SELECT supplier_preparations + │ JOIN order_items, orders + │ WHERE supplier_code = ? + ▼ + ┌──────────────┐ + │ 返回备货列表 │ + │ + 订单信息 │ + │ + 商品信息 │ + └──────┬───────┘ + │ + ┌───────────────────────────┘ + │ 确认备货 + │ POST /api/mobile/supplier/preparations/status + ▼ +┌─────────────────┐ ┌──────────────────┐ ┌─────────────────────┐ +│ mobile_supplier │ ──▶ │ supplierbiz/ │ ──▶ │ UPDATE │ +│ .go │ │ prepstatus.go │ │ supplier_preparations│ +│ │ │ UpdatePreparation │ │ prepare_status │ +│ │ │ Status() │ │ 10→20(确认)→30(完成) │ +└─────────────────┘ └──────────────────┘ └─────────────────────┘ +``` + +## 5. 采购/自采流 (Purchase Order) + +``` +采购员小程序 Go 后端 DB +─────────── ──────── ── +│ 查看自采单 │ +└────┬─────┘ + │ GET /api/mobile/purchase/orders + ▼ +┌─────────────────┐ ┌──────────────────┐ +│ mobile_purchase │ ──▶ │ purchase/ │ +│ .go │ │ operation.go │ +│ │ │ ListPurchase │ +│ │ │ Orders() │ +└─────────────────┘ └────────┬─────────┘ + │ SELECT purchase_orders + │ WHERE purchaser_code = ? + ▼ + ┌──────────────┐ + │ 返回自采列表 │ + └──────┬───────┘ + │ + ┌───────────────────────────┘ + │ 转供应商 / 改状态 + │ POST /api/mobile/purchase/orders/assign-supplier + │ POST /api/mobile/purchase/orders/status + ▼ +┌─────────────────┐ ┌──────────────────┐ ┌─────────────────────┐ +│ mobile_purchase │ ──▶ │ purchase/ │ ──▶ │ UPDATE purchase_ │ +│ .go │ │ assign.go │ │ orders │ +│ │ │ AssignPurchase │ │ supplier_code │ +│ │ │ OrderToSupplier() │ │ purchase_status │ +└─────────────────┘ └──────────────────┘ └─────────────────────┘ +``` + +## 6. 验收流 (Inspection) + +``` +仓管小程序 Go 后端 DB +───────── ──────── ── +│ 验收任务列表 │ +└────┬───────┘ + │ GET /api/mobile/inspection/tasks + ▼ +┌─────────────────┐ ┌──────────────────┐ +│ mobile_inspection│ ──▶ │ inspection/ │ +│ .go │ │ compliance.go │ +│ │ │ ListInspection │ +│ │ │ Tasks() │ +└─────────────────┘ └────────┬─────────┘ + │ SELECT inspections + │ JOIN order_items, orders + ▼ + ┌──────────────┐ + │ 返回验收列表 │ + └──────┬───────┘ + │ + ┌───────────────────────────┘ + │ 提交验收 (拍照+称重) + │ POST /api/mobile/inspection/complete + │ POST /api/mobile/inspection/photo + ▼ +┌─────────────────┐ ┌──────────────────┐ ┌─────────────────────┐ +│ mobile_inspection│ ──▶ │ inspection/ │ ──▶ │ UPDATE inspections │ +│ .go │ │ advance.go │ │ inspection_status │ +│ │ │ CompleteInspection│ │ inspection_photos │ +│ │ │ () │ │ processing_details │ +└─────────────────┘ └────────┬─────────┘ └──────────┬──────────┘ + │ │ + ▼ ▼ + ┌──────────────┐ ┌──────────────┐ + │ 创建分拣任务 │ │ 创建加工任务 │ + │ picking_tasks │ │ processing_ │ + │ │ │ tasks (如需要) │ + └──────────────┘ └──────────────┘ +``` + +## 7. 加工流 (Processing) ⚡ 独立模块 + +``` +仓管 Web/小程序 Go 后端 DB +───────────── ──────── ── +│ 加工任务列表 │ +└────┬───────┘ + │ GET /api/mobile/processing/tasks + ▼ +┌─────────────────┐ ┌──────────────────┐ +│ mobile_processing│ ──▶ │ processing/ │ +│ .go │ │ tasks.go │ +│ │ │ ListTasks() │ +└─────────────────┘ └────────┬─────────┘ + │ SELECT processing_tasks + │ JOIN order_items, orders + ▼ + ┌──────────────┐ + │ 返回加工列表 │ + └──────┬───────┘ + │ + ┌───────────────────────────┼───────────────────────────┐ + │ 开始加工 │ 完工登记 │ 加工验收 + │ POST /processing/start │ POST /processing/complete │ POST /processing + ▼ ▼ │ /inspect/complete +┌──────────┐ ┌──────────────┐ ▼ +│ UPDATE │ │ UPDATE │ ┌──────────────┐ +│ status │ │ status │ │ 拍照上传 │ +│ 10→20 │ │ 20→30 │ │ 记录损耗 │ +│ (加工中) │ │ (待验收) │ │ 人工成本入账 │ +└──────────┘ └──────┬───────┘ │ processing_logs│ + │ └──────────────┘ + ▼ + ┌──────────────┐ + │ 记录损耗 │ + │ loss_qty │ + │ 出成率 │ + │ 人工成本入账 │ + │ cost_details │ + └──────────────┘ + + ★ 独立加工单 (不关联订单): + POST /api/mobile/processing/standalone/create + ──▶ processing/standalone ──▶ INSERT processing_tasks (order_code=NULL) +``` + +## 8. 分拣流 (Picking) + +``` +仓管小程序 Go 后端 DB +───────── ──────── ── +│ 分拣任务列表 │ +└────┬───────┘ + │ GET /api/mobile/picking/tasks + ▼ +┌─────────────────┐ ┌──────────────────┐ +│ mobile_picking │ ──▶ │ picking/ │ +│ .go │ │ outbound.go │ +│ │ │ ListPickingTasks() │ +└─────────────────┘ └────────┬─────────┘ + │ SELECT picking_tasks + ▼ + ┌──────────────┐ + │ 返回分拣列表 │ + └──────┬───────┘ + │ + ┌───────────────────────────┼───────────────────────────┐ + │ 称重站 │ 分拣确认 │ 出库 + │ POST /picking/weigh- │ POST /picking/confirm │ POST /picking + │ station/commit │ │ /outbound + ▼ ▼ ▼ +┌──────────┐ ┌──────────────┐ ┌──────────────┐ +│ 称重记录 │ │ 确认分拣 │ │ 出库扫描 │ +│ 毛重/净重 │ │ 更新状态 │ │ 生成配送任务 │ +│ 拍照 │ │ │ │ delivery_ │ +└──────────┘ └──────────────┘ │ tasks │ + └──────────────┘ +``` + +## 9. 配送流 (Delivery) + +``` +配送员小程序 Go 后端 DB +─────────── ──────── ── +│ 配送任务列表 │ +└────┬───────┘ + │ GET /api/mobile/delivery/tasks + ▼ +┌─────────────────┐ ┌──────────────────┐ +│ mobile_delivery │ ──▶ │ delivery/ │ +│ .go │ │ tasks.go │ +│ │ │ ListDriverTasks() │ +└─────────────────┘ └────────┬─────────┘ + │ SELECT delivery_tasks + │ WHERE driver_id = ? + ▼ + ┌──────────────┐ + │ 返回配送列表 │ + └──────┬───────┘ + │ + ┌───────────────────────────┼───────────────────────────┐ + │ 装车 │ 发车 │ 送达签收 + │ POST /delivery/loading │ POST /delivery/start │ POST /delivery + │ /confirm-item │ /start-batch │ /sign-photo + ▼ ▼ ▼ +┌──────────────┐ ┌──────────────┐ ┌──────────────┐ +│ 扫码装车 │ │ 发车出发 │ │ 拍照签收 │ +│ delivery_ │ │ 开始计费 │ │ 上传签名 │ +│ loading_items│ │ status 10→60 │ │ status 60→80 │ +│ │ │ orders 50→60 │ │ orders 60→90 │ +└──────────────┘ └──────────────┘ └──────┬───────┘ + │ + ▼ + ┌──────────────┐ + │ 触发财务结算 │ + │ customer_ │ + │ statements │ + │ supplier_ │ + │ statements │ + └──────────────┘ +``` + +## 10. 财务结算流 (Finance) + +``` +订单完成(status=90) / 手动触发 +───────────────────────────────── + +┌─────────────────────────────────────────────────────────────────────┐ +│ finance/statement.go │ +│ │ +│ ┌──────────────────────────────────────────────────────────────┐ │ +│ │ 1. 供应商对账单 │ │ +│ │ POST /api/workflow/finance/supplier-statements/generate │ │ +│ │ ──▶ 按供应商汇总 supplier_preparations │ │ +│ │ ──▶ INSERT supplier_statements │ │ +│ └──────────────────────────────────────────────────────────────┘ │ +│ │ │ +│ ┌──────────────────────────────────────────────────────────────┐ │ +│ │ 2. 客户对账单 │ │ +│ │ POST /api/workflow/finance/customer-statements/generate │ │ +│ │ ──▶ 按客户汇总 orders + order_items │ │ +│ │ ──▶ INSERT customer_statements │ │ +│ └──────────────────────────────────────────────────────────────┘ │ +│ │ │ +│ ┌──────────────────────────────────────────────────────────────┐ │ +│ │ 3. 对账确认/争议 │ │ +│ │ POST /api/workflow/finance/statement/confirm │ │ +│ │ POST /api/workflow/finance/statement/dispute │ │ +│ │ ──▶ 更新对账单状态 │ │ +│ └──────────────────────────────────────────────────────────────┘ │ +│ │ │ +│ ┌──────────────────────────────────────────────────────────────┐ │ +│ │ 4. 成本入账 │ │ +│ │ POST /api/workflow/finance/cost/post-orders │ │ +│ │ ──▶ 订单成本汇总 → cost_details │ │ +│ │ ──▶ 采购成本 → invcost/ReconcileOrderPurchase │ │ +│ └──────────────────────────────────────────────────────────────┘ │ +│ │ │ +│ ┌──────────────────────────────────────────────────────────────┐ │ +│ │ 5. 其他成本 (杂费) │ │ +│ │ POST /api/workflow/cost/free-cost │ │ +│ │ ──▶ 配送员/采购员录入其他费用 │ │ +│ │ ──▶ INSERT cost_details (cost_type='free_cost') │ │ +│ │ ──▶ 凭证照片上传 + HMAC 签名 │ │ +│ └──────────────────────────────────────────────────────────────┘ │ +│ │ │ +│ ┌──────────────────────────────────────────────────────────────┐ │ +│ │ 6. 账款催收 │ │ +│ │ POST /api/workflow/finance/aging/scan │ │ +│ │ GET /api/workflow/finance/collection-strategies │ │ +│ │ ──▶ 逾期账款分析 → 催收策略 │ │ +│ └──────────────────────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +## 11. 售后/退货流 (After-Sale) + +``` +客户小程序 Go 后端 DB +───────── ──────── ── +│ 申请售后 │ +└────┬────┘ + │ POST /api/mobile/customer-order/after-sales + ▼ +┌─────────────────┐ ┌──────────────────┐ ┌─────────────────────┐ +│ mobile_order.go │ ──▶ │ orderentry/ │ ──▶ │ INSERT │ +│ │ │ aftersale.go │ │ after_sale_orders │ +│ │ │ CreateAfterSale() │ │ 退货/换货/退款 │ +└─────────────────┘ └────────┬─────────┘ └──────────┬──────────┘ + │ │ + ▼ ▼ + ┌──────────────┐ ┌──────────────┐ + │ 库存退回 │ │ 退款处理 │ + │ inventory + │ │ finance │ + │ 重新入库 │ │ 退款单 │ + └──────────────┘ └──────────────┘ +``` + +## 12. 质检报告流 (Quality Report) + +``` +供应商 H5 Go 后端 DB +───────── ──────── ── +│ 上传质检报告 │ +└────┬──────┘ + │ POST /api/supplier/quality-reports/library + ▼ +┌─────────────────┐ ┌──────────────────┐ ┌─────────────────────┐ +│ supplier_api_ │ ──▶ │ supplierbiz/ │ ──▶ │ INSERT │ +│ quality.go │ │ quality.go │ │ quality_reports │ +│ │ │ UploadLibrary │ │ (报告类型+文件URL) │ +│ │ │ QualityReport() │ │ validity_status │ +└─────────────────┘ └──────────────────┘ └─────────────────────┘ + +│ 查看质检报告 +│ GET /api/supplier/quality-reports +▼ +┌─────────────────┐ ┌──────────────────┐ +│ supplier_api_ │ ──▶ │ supplierbiz/ │ +│ quality.go │ │ quality.go │ +│ │ │ ListQuality │ +│ │ │ Reports() │ +└─────────────────┘ └──────────────────┘ +``` + +## 13. 竞价流 (Bid) + +``` +供应商 H5 Go 后端 DB +───────── ──────── ── +│ 查看竞价邀约 │ +└────┬──────┘ + │ GET /api/supplier/bids + ▼ +┌─────────────────┐ ┌──────────────────┐ +│ supplier_api_ │ ──▶ │ workflow/ │ +│ bids.go │ │ bid.go │ +│ │ │ ListSupplierBid │ +│ │ │ Invitations() │ +└─────────────────┘ └────────┬─────────┘ + │ SELECT bid_rounds + │ JOIN bid_invitations + │ WHERE supplier_code = ? + ▼ + ┌──────────────┐ + │ 返回竞价列表 │ + └──────┬───────┘ + │ +│ 查看竞价详情 +│ GET /api/supplier/bids/:id +▼ +┌─────────────────┐ ┌──────────────────┐ +│ supplier_api_ │ ──▶ │ 查询 bid_rounds │ +│ bids.go │ │ + bid_items │ +│ │ │ + bid_quotes │ +└─────────────────┘ └──────────────────┘ + +│ 提交报价 +│ POST /api/supplier/bids/:id/quotes +▼ +┌─────────────────┐ ┌──────────────────┐ ┌─────────────────────┐ +│ supplier_api_ │ ──▶ │ workflow/ │ ──▶ │ INSERT/UPDATE │ +│ bids.go │ │ bid.go │ │ bid_quotes │ +│ │ │ SubmitBidQuotes() │ │ (报价价格+备注) │ +└─────────────────┘ └──────────────────┘ └─────────────────────┘ +``` + +## 14. 库存管理流 (Inventory) + +``` +仓管/采购员 Go 后端 DB +───────── ──────── ── +│ 入库登记 │ +└────┬────┘ + │ POST /api/mobile/inventory/stock-in + ▼ +┌─────────────────┐ ┌──────────────────┐ ┌─────────────────────┐ +│ mobile_inventory │ ──▶ │ stockin/ │ ──▶ │ INSERT inventory │ +│ .go │ │ inbound.go │ │ (批次号+数量+成本) │ +│ │ │ StockIn() │ │ 更新库存可用量 │ +└─────────────────┘ └──────────────────┘ └─────────────────────┘ + +│ 库存覆盖 (分配时) +│ 自动触发 +▼ +┌─────────────────┐ ┌──────────────────┐ +│ allocation/ │ ──▶ │ 查询 inventory │ +│ engine.go │ │ 可用库存覆盖 │ +│ │ │ 减少自采需求 │ +└─────────────────┘ └──────────────────┘ +``` + +## 15. 商品目录流 (Catalog) + +``` +Web 管理端 Go 后端 DB +───────── ──────── ── +│ 商品建档 │ +└────┬────┘ + │ POST /api/mobile/catalog/products + ▼ +┌─────────────────┐ ┌──────────────────┐ ┌─────────────────────┐ +│ mobile_inventory │ ──▶ │ catalog/ │ ──▶ │ UPSERT skus │ +│ .go │ │ product.go │ │ UPSERT product_ │ +│ │ │ CreateProduct() │ │ catalog │ +└─────────────────┘ └──────────────────┘ └─────────────────────┘ + +│ 税务编码查询 +│ GET /api/tax-code/search +│ GET /api/tax-code/suggest +▼ +┌─────────────────┐ ┌──────────────────┐ +│ catalog.go │ ──▶ │ 本地税收分类编码库 │ +│ │ │ 搜索/匹配 │ +└─────────────────┘ └──────────────────┘ +``` + +## 16. 用户认证流 (Auth) + +``` +所有客户端 Go 后端 DB +───────── ──────── ── +│ 登录 │ +│ POST /api/mobile/login │ POST /api/auth/token +│ POST /api/supplier/login │ POST /api/auth/unified-login +└────┬───┘ + ▼ +┌─────────────────┐ ┌──────────────────┐ ┌─────────────────────┐ +│ auth/ │ ──▶ │ auth/ │ ──▶ │ SELECT users │ +│ jwt.go │ │ login.go │ │ 验证密码/手机号 │ +│ Parse() │ │ 生成 JWT token │ │ 返回用户信息 │ +└─────────────────┘ └────────┬─────────┘ └─────────────────────┘ + │ + ▼ + ┌──────────────┐ + │ JWT 中间件 │ + │ authMiddleware│ + │ 解析 Bearer │ + │ 注入 Claims │ + └──────┬───────┘ + │ + ▼ + ┌──────────────┐ + │ 租户上下文 │ + │ tenant/ │ + │ 多租户隔离 │ + │ 分公司权限 │ + └──────────────┘ +``` + +## 17. 通知流 (Notification) + +``` +系统事件触发 Go 后端 外部 +───────── ──────── ── +│ 订单状态变更 │ +│ 备货通知 │ +│ 配送提醒 │ +└────┬───────┘ + ▼ +┌─────────────────┐ ┌──────────────────┐ +│ 各业务模块 │ ──▶ │ notify/ │ +│ delivery/ │ │ notify.go │ +│ advance.go │ │ 站内通知 │ +│ inspection/ │ │ 写入 notifications│ +│ advance.go │ │ 表 │ +└─────────────────┘ └────────┬─────────┘ + │ + ▼ + ┌──────────────┐ ┌──────────────┐ + │ 站内通知 │ │ 微信订阅通知 │ + │ GET /mobile/ │ │ (Node.js) │ + │ notifications │ │ 模板消息推送 │ + └──────────────┘ └──────────────┘ +``` + +## 18. 审计日志流 (Audit) + +``` +关键操作触发 Go 后端 DB +───────── ──────── ── +│ 订单编辑 │ +│ 分配完成 │ +│ 状态推进 │ +│ 财务操作 │ +└────┬───┘ + ▼ +┌─────────────────┐ ┌──────────────────┐ ┌─────────────────────┐ +│ 各业务模块 │ ──▶ │ httpapi/ │ ──▶ │ INSERT │ +│ (调用 AuditLog │ │ audit.go │ │ operation_logs │ +│ Quick) │ │ WriteAuditLog() │ │ operator_id │ +│ │ │ │ │ operation_type │ +│ │ │ │ │ old_value/new_value │ +└─────────────────┘ └──────────────────┘ └─────────────────────┘ +``` + +## 19. 文件存储流 (Storage) + +``` +所有客户端 Go 后端 OSS/S3 +───────── ──────── ────── +│ 上传图片 │ +└────┬────┘ + │ POST /api/storage/:bucket/upload + ▼ +┌─────────────────┐ ┌──────────────────┐ ┌─────────────────────┐ +│ storage_api.go │ ──▶ │ storage/ │ ──▶ │ 上传到 OSS/S3 │ +│ │ │ oss.go │ │ delivery-photos/ │ +│ │ │ SaveBase64Upload()│ │ inspection-photos/ │ +│ │ │ │ │ invoices/ │ +│ │ │ │ │ sku-images/ │ +│ │ │ │ │ quality-reports/ │ +└─────────────────┘ └──────────────────┘ └─────────────────────┘ + +│ 读取图片 +│ GET /api/storage/:bucket/public/:folder/:filename?exp=&sig= +▼ +┌─────────────────┐ ┌──────────────────┐ +│ storage_api.go │ ──▶ │ HMAC 签名校验 │ +│ │ │ verifyStorage │ +│ │ │ Signature() │ +│ │ │ 从 OSS 读取 │ +└─────────────────┘ └──────────────────┘ +``` + +## 20. 仪表板/统计流 (Dashboard) + +``` +Web 管理端 Go 后端 DB +───────── ──────── ── +│ 仪表板概览 │ +└────┬──────┘ + │ GET /api/dashboard + ▼ +┌─────────────────┐ ┌──────────────────┐ ┌─────────────────────┐ +│ admin_business │ ──▶ │ 聚合查询: │ │ COUNT orders │ +│ .go │ │ 待处理订单数 │ │ COUNT preparations │ +│ handleDashboard │ │ 待配送任务数 │ │ COUNT inspections │ +│ │ │ 待验收数 │ │ COUNT delivery_ │ +│ │ │ │ │ tasks │ +└─────────────────┘ └──────────────────┘ └─────────────────────┘ + +│ 操作队列 +│ GET /api/dashboard/action-queue +▼ +┌─────────────────┐ ┌──────────────────┐ +│ admin_business │ ──▶ │ 待分配订单 │ +│ .go │ │ 待配送任务 │ +│ │ │ 待验收记录 │ +└─────────────────┘ └──────────────────┘ +``` + +## 21. 客户管理流 (Customer) + +``` +Web 管理端 Go 后端 DB +───────── ──────── ── +│ 客户列表 │ +└────┬────┘ + │ GET /api/accounts (含客户) + ▼ +┌─────────────────┐ ┌──────────────────┐ +│ admin_business │ ──▶ │ SELECT customers │ +│ .go │ │ 预算/授信/状态 │ +└─────────────────┘ └──────────────────┘ + +│ 客户登录账号 +│ POST /api/accounts/customers/:code/login-account +▼ +┌─────────────────┐ ┌──────────────────┐ ┌─────────────────────┐ +│ accounts.go │ ──▶ │ ensureAccount() │ ──▶ │ INSERT users │ +│ │ │ 查找或创建用户 │ │ role_type='customer'│ +└─────────────────┘ └──────────────────┘ └─────────────────────┘ +``` + +## 22. 供应商管理流 (Supplier) + +``` +Web 管理端 Go 后端 DB +───────── ──────── ── +│ 供应商列表 │ +└────┬────┘ + │ GET /api/suppliers + ▼ +┌─────────────────┐ ┌──────────────────┐ +│ admin_business │ ──▶ │ SELECT suppliers │ +│ .go │ │ 评分/状态/联系人 │ +└─────────────────┘ └──────────────────┘ + +│ 供应商集成客户端 +│ POST /api/suppliers/integration-clients +▼ +┌─────────────────┐ ┌──────────────────┐ ┌─────────────────────┐ +│ admin_suppliers │ ──▶ │ INSERT supplier_ │ +│ .go │ │ integration_ │ +│ │ │ clients │ +│ │ │ (client_id+secret)│ +└─────────────────┘ └──────────────────┘ + +│ 供应商 OAuth +│ POST /api/supplier/oauth/token +▼ +┌─────────────────┐ ┌──────────────────┐ ┌─────────────────────┐ +│ supplier_api.go │ ──▶ │ 验证 client_id │ ──▶ │ 返回 JWT token │ +│ │ │ + client_secret │ │ scope=supplier_ │ +│ │ │ │ │ integration │ +└─────────────────┘ └──────────────────┘ └─────────────────────┘ +``` + +## 23. 数据查询/导出流 (Data API) + +``` +Web 管理端 Go 后端 DB +───────── ──────── ── +│ 数据查询 │ +└────┬────┘ + │ POST /api/data/query + ▼ +┌─────────────────┐ ┌──────────────────┐ ┌─────────────────────┐ +│ data_access.go │ ──▶ │ queryexec/ │ ──▶ │ 动态 SQL 查询 │ +│ │ │ 权限校验 │ │ 表级别权限控制 │ +│ │ │ 表白名单 │ │ 只读操作 │ +└─────────────────┘ └──────────────────┘ └─────────────────────┘ + +│ 批量操作 +│ POST /api/data/batch +▼ +┌─────────────────┐ ┌──────────────────┐ +│ data_access.go │ ──▶ │ 批量 INSERT/ │ +│ │ │ UPDATE/DELETE │ +│ │ │ 事务内执行 │ +└─────────────────┘ └──────────────────┘ +``` + +## 24. 完整数据流总览 + +``` + ┌─────────────────────────────────────────────────────────────┐ + │ 请求入口 (httpapi) │ + │ │ + │ /mobile/* /workflow/* /api/* /supplier/* │ + └──────────────────────────┬──────────────────────────────────┘ + │ + ┌────────────┬────────────┬──────────┬───────┼───────┬──────────┬────────────┬──┐ + ▼ ▼ ▼ ▼ │ ▼ ▼ ▼ │ + ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ ┌─────────┐ ┌─────────┐ ┌────────┐ + │ 订单录入 │ │ 订单管理 │ │ 配送管理 │ │ 采购管理 │ │ │ 验收管理 │ │ 分拣管理 │ │ 加工管理│ + │orderentry│ │orderadmin│ │ delivery │ │ purchase │ │ │inspection│ │ picking │ │processing│ + └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │ └────┬─────┘ └────┬─────┘ └────┬────┘ + │ │ │ │ │ │ │ │ + ▼ ▼ ▼ ▼ │ ▼ ▼ ▼ + ┌────────────────────────────────────────────────────┼────────────────────────────────────┐ + │ 共享数据层 │ │ + │ │ │ + │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ ┌──────────┐ ┌──────────┐ │ + │ │ 订单域 │ │ 履约域 │ │ 仓储域 │ │ │ 配送域 │ │ 财务域 │ │ + │ │ orders │ │ supplier │ │inspection│ │ │ delivery │ │ statements│ │ + │ │ order_ │ │ _prepa- │ │ picking │ │ │ _tasks │ │ cost_ │ │ + │ │ items │ │ rations │ │ _tasks │ │ │ loading │ │ details │ │ + │ │ fulfill │ │ purchase │ │ process │ │ │ sign │ │ operation │ │ + │ │ ments │ │ _orders │ │ _tasks │ │ │ │ │ _logs │ │ + │ └──────────┘ └──────────┘ └──────────┘ │ └──────────┘ └──────────┘ │ + │ │ │ + │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ ┌──────────┐ ┌──────────┐ │ + │ │ 供应商域 │ │ 客户域 │ │ 商品域 │ │ │ 用户域 │ │ 配置域 │ │ + │ │suppliers │ │customers │ │ skus │ │ │ users │ │ system_ │ │ + │ │ quality │ │ accounts │ │ catalog │ │ │ roles │ │ configs │ │ + │ │ bids │ │ │ │ tax │ │ │ profiles │ │ branches │ │ + │ └──────────┘ └──────────┘ └──────────┘ │ └──────────┘ └──────────┘ │ + └────────────────────────────────────────────────────┴────────────────────────────────────┘ + │ + ▼ + ┌──────────────────┐ + │ OSS/S3 文件存储 │ + │ 5 个桶 │ + └──────────────────┘ +``` \ No newline at end of file diff --git a/DESIGN_SYSTEM.md b/DESIGN_SYSTEM.md new file mode 100644 index 0000000..29de7d6 --- /dev/null +++ b/DESIGN_SYSTEM.md @@ -0,0 +1,525 @@ +# AI生鲜供应链管理系统 - 设计系统规范 + +## 1. 设计原则 + +### 核心目标 +- **极简**: 减少视觉噪音,每个元素都有明确目的 +- **高效**: 信息层级清晰,重要操作一目了然 +- **专业**: 体现供应链管理的严谨性和科技感 +- **清晰**: 功能状态明确,用户无需猜测 + +### 设计哲学 +基于Linear风格的精确性和Vercel风格的简洁性,适配生鲜供应链场景: +- 浅色主界面,确保在各种光线环境下可读 +- 精确的字距和行高,提升阅读效率 +- 明确的状态反馈,每个交互都有视觉响应 +- 数据密集型布局优化,高密度信息清晰呈现 + +--- + +## 2. 颜色系统 + +### 主色调 +``` +Primary: #0f172a /* 深蓝黑 - 主按钮、关键操作 */ +Primary Hover:#1e293b /* 悬停状态 */ +Accent: #6366f1 /* 靛紫 - 强调、激活状态 */ +Accent Hover: #818cf8 /* 强调色悬停 */ +``` + +### 背景色 +``` +Bg Primary: #ffffff /* 主背景 */ +Bg Secondary: #f8fafc /* 次级背景、卡片 */ +Bg Tertiary: #f1f5f9 /* 第三层背景、hover */ +Bg Dark: #0f172a /* 深色背景、反色 */ +``` + +### 文字色 +``` +Text Primary: #0f172a /* 主文字、标题 */ +Text Secondary: #475569 /* 次级文字、正文 */ +Text Muted: #94a3b8 /* 辅助文字、placeholder */ +Text Inverse: #ffffff /* 深色背景上的文字 */ +``` + +### 边框色 +``` +Border Light: #e2e8f0 /* 浅色边框 */ +Border Default: #cbd5e1 /* 默认边框 */ +Border Dark: #64748b /* 深色边框 */ +``` + +### 状态色 +``` +Success: #10b981 /* 成功、完成 */ +Success Light: #d1fae5 /* 成功背景 */ +Warning: #f59e0b /* 警告、注意 */ +Warning Light: #fef3c7 /* 警告背景 */ +Danger: #ef4444 /* 危险、错误 */ +Danger Light: #fee2e2 /* 危险背景 */ +Info: #3b82f6 /* 信息提示 */ +Info Light: #dbeafe /* 信息背景 */ +``` + +### 状态标签配色 +``` +待处理: bg-slate-100 text-slate-700 border-slate-200 +进行中: bg-indigo-50 text-indigo-700 border-indigo-200 +已完成: bg-emerald-50 text-emerald-700 border-emerald-200 +警告: bg-amber-50 text-amber-700 border-amber-200 +错误: bg-rose-50 text-rose-700 border-rose-200 +``` + +--- + +## 3. 字体系统 + +### 字体栈 +``` +Primary: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif +Mono: 'JetBrains Mono', 'Fira Code', monospace +``` + +### 字号规范 +``` +Display: 32px / font-weight: 600 / line-height: 1.2 / letter-spacing: -0.02em +H1: 24px / font-weight: 600 / line-height: 1.3 / letter-spacing: -0.01em +H2: 20px / font-weight: 600 / line-height: 1.4 +H3: 16px / font-weight: 600 / line-height: 1.5 +Body Large: 16px / font-weight: 400 / line-height: 1.6 +Body: 14px / font-weight: 400 / line-height: 1.6 +Small: 13px / font-weight: 400 / line-height: 1.5 +Caption: 12px / font-weight: 500 / line-height: 1.4 +``` + +### 字重规范 +``` +Regular: 400 +Medium: 500 +Semibold: 600 +Bold: 700 +``` + +--- + +## 4. 间距系统 + +### 基础单位: 4px +``` +space-1: 4px +space-2: 8px +space-3: 12px +space-4: 16px +space-5: 20px +space-6: 24px +space-8: 32px +space-10: 40px +space-12: 48px +``` + +### 组件间距 +``` +Card Padding: 20px - 24px +Section Gap: 24px +Element Gap: 12px - 16px +Form Field Gap: 16px +``` + +--- + +## 5. 圆角系统 +``` +Rounded None: 0px +Rounded Small: 4px /* 按钮、标签、输入框 */ +Rounded Medium: 6px /* 卡片、小容器 */ +Rounded Large: 8px /* 大卡片、模态框 */ +Rounded XL: 12px /* 特殊容器 */ +Rounded Full: 9999px /* 圆形、胶囊 */ +``` + +--- + +## 6. 阴影系统 +``` +Shadow SM: 0 1px 2px rgba(0,0,0,0.05) +Shadow: 0 1px 3px rgba(0,0,0,0.1), 0 1px 2px rgba(0,0,0,0.06) +Shadow MD: 0 4px 6px rgba(0,0,0,0.07), 0 2px 4px rgba(0,0,0,0.05) +Shadow LG: 0 10px 15px rgba(0,0,0,0.1), 0 4px 6px rgba(0,0,0,0.05) +Shadow XL: 0 20px 25px rgba(0,0,0,0.1), 0 10px 10px rgba(0,0,0,0.04) +``` + +--- + +## 7. 组件规范 + +### 按钮 + +#### 主按钮 (Primary) +``` +Background: #0f172a +Text: #ffffff +Border Radius: 6px +Padding: 8px 16px +Font Size: 13px +Font Weight: 500 +Hover: bg #1e293b, translateY(-1px) +Active: bg #0f172a, scale(0.98) +Disabled: bg #cbd5e1, text #94a3b8, cursor not-allowed +``` + +#### 次级按钮 (Secondary) +``` +Background: #ffffff +Border: 1px solid #e2e8f0 +Text: #475569 +Hover: bg #f8fafc, border #cbd5e1 +Active: bg #f1f5f9 +``` + +#### 幽灵按钮 (Ghost) +``` +Background: transparent +Text: #475569 +Hover: bg #f1f5f9 +Active: bg #e2e8f0 +``` + +#### 危险按钮 (Danger) +``` +Background: #ef4444 +Text: #ffffff +Hover: bg #dc2626 +``` + +### 输入框 + +#### 文本输入 +``` +Background: #ffffff +Border: 1px solid #e2e8f0 +Border Radius: 6px +Padding: 10px 14px +Font Size: 14px +Placeholder: #94a3b8 +Focus: border #6366f1, ring 2px #6366f1/20 +Error: border #ef4444, ring 2px #ef4444/20 +Disabled: bg #f1f5f9, text #94a3b8 +``` + +#### 选择框 +``` +同文本输入 +Height: 40px +``` + +### 卡片 + +#### 默认卡片 +``` +Background: #ffffff +Border: 1px solid #e2e8f0 +Border Radius: 8px +Padding: 20px +Shadow: 0 1px 3px rgba(0,0,0,0.1) +Hover: shadow 0 4px 6px rgba(0,0,0,0.07), border #cbd5e1 +``` + +#### 统计卡片 +``` +Background: #ffffff +Border: 1px solid #e2e8f0 +Border Radius: 8px +Padding: 20px +Header: 图标 + 标题 +Value: 24px, font-weight 600, text-primary +Label: 13px, text-muted +``` + +### 表格 + +#### 数据表格 +``` +Header Background: #f8fafc +Header Text: #475569, 12px, font-weight 500, uppercase +Row Border: 1px solid #e2e8f0 +Row Hover: bg #f8fafc +Cell Padding: 12px 16px +Striped: bg #f8fafc (even rows) +``` + +### 标签/徽章 + +#### 状态标签 +``` +Padding: 4px 10px +Border Radius: 9999px (pill) +Font Size: 12px +Font Weight: 500 +Border: 1px solid (varies by status) +``` + +### 导航 + +#### 侧边栏导航 +``` +Width: 240px +Background: #ffffff +Border Right: 1px solid #e2e8f0 +Item Padding: 10px 16px +Item Radius: 6px +Active: bg #f1f5f9, text #0f172a, font-weight 500 +Hover: bg #f8fafc +Inactive: text #64748b +``` + +#### 顶部导航 +``` +Height: 64px +Background: #ffffff +Border Bottom: 1px solid #e2e8f0 +``` + +### 模态框 + +#### 标准模态框 +``` +Overlay: bg rgba(0,0,0,0.5) +Background: #ffffff +Border Radius: 8px +Padding: 24px +Max Width: 560px (small), 720px (medium), 960px (large) +Shadow: 0 20px 25px rgba(0,0,0,0.1) +``` + +--- + +## 8. 布局规范 + +### 页面结构 +``` +Container: max-width 1440px, centered +Sidebar: 240px fixed +Main Content: flex-1, padding 24px +Header Height: 64px +``` + +### 网格系统 +``` +Grid: 12-column +Gap: 16px (default), 24px (large) +Breakpoints: + - sm: 640px + - md: 768px + - lg: 1024px + - xl: 1280px + - 2xl: 1536px +``` + +### 响应式断点 +``` +Mobile: < 768px +Tablet: 768px - 1024px +Desktop: > 1024px +``` + +--- + +## 9. 交互反馈 + +### 悬停状态 +- 按钮: 背景色变化 + 轻微上移 (translateY(-1px)) +- 卡片: 阴影增强 + 边框加深 +- 链接: 颜色变化 +- 表格行: 背景色变化 + +### 焦点状态 +- 输入框: 边框变为 accent 色 + 2px 浅色 ring +- 按钮: 2px 浅色 ring +- 所有可交互元素必须有可见的焦点指示 + +### 激活状态 +- 按钮: scale(0.98) + 背景色加深 +- 标签: 背景色变化 + +### 禁用状态 +- 透明度: 0.5 +- 光标: not-allowed +- 无悬停效果 + +### 加载状态 +- 按钮: spinner 图标 + 禁用状态 +- 页面: skeleton 骨架屏 +- 数据: 旋转 loading 图标 + +--- + +## 10. 动效规范 + +### 过渡时间 +``` +Fast: 100ms (hover, focus) +Normal: 150ms (state changes) +Slow: 200ms (modals, panels) +``` + +### 缓动函数 +``` +Default: cubic-bezier(0.4, 0, 0.2, 1) +Enter: cubic-bezier(0, 0, 0.2, 1) +Exit: cubic-bezier(0.4, 0, 1, 1) +``` + +### 常用动效 +``` +Fade In: opacity 0 → 1 +Slide Up: translateY(8px) → translateY(0) +Scale In: scale(0.95) → scale(1) +``` + +--- + +## 11. 图标规范 + +### 图标库 +- Lucide React (主要) +- 自定义 SVG (特殊需求) + +### 图标尺寸 +``` +Small: 14px +Default: 16px +Medium: 20px +Large: 24px +``` + +### 图标使用 +- 按钮内图标: 16px, 与文字间距 8px +- 导航图标: 20px +- 状态图标: 16px +- 标题图标: 20px + +--- + +## 12. 数据可视化 + +### 图表配色 +``` +Primary: #6366f1 +Secondary: #10b981 +Tertiary: #f59e0b +Quaternary: #ef4444 +Neutral: #64748b +``` + +### 统计数字展示 +``` +Large: 32px, font-weight 600, text-primary +Medium: 24px, font-weight 600 +Small: 18px, font-weight 500 +Label: 13px, text-muted +``` + +--- + +## 13. 特殊组件 + +### 状态时间线 +``` +Line: 2px solid #e2e8f0 +Active Dot: 10px, bg accent, border 2px white +Inactive Dot: 10px, bg #cbd5e1 +Label: 13px, text-secondary +Time: 12px, text-muted +``` + +### 进度条 +``` +Height: 8px +Background: #e2e8f0 +Fill: accent color +Radius: 9999px +``` + +### 搜索框 +``` +Height: 40px +Icon: 16px, text-muted, left 12px +Padding: 10px 14px 10px 40px +Placeholder: "搜索..." +``` + +--- + +## 14. 页面模板 + +### 列表页 +``` +Header: 标题 + 操作按钮 +Stats: 统计卡片行 (4-5个) +Filters: 搜索 + 筛选条件 +Table: 数据表格 +Pagination: 底部分页 +``` + +### 详情页 +``` +Header: 返回 + 标题 + 状态 + 操作 +Info Cards: 关键信息卡片 +Tabs: 多标签内容 +Content: 详细数据 +``` + +### 表单页 +``` +Header: 标题 + 保存/取消 +Form: 分组表单字段 +Actions: 底部操作栏 +``` + +--- + +## 15. 可访问性 + +### 对比度 +- 文字与背景对比度至少 4.5:1 +- 大文字 (18px+) 对比度至少 3:1 + +### 焦点可见 +- 所有可交互元素必须有焦点指示 +- 焦点指示必须清晰可见 + +### 触摸目标 +- 最小触摸目标: 44px × 44px +- 按钮最小高度: 36px + +--- + +## 16. Tailwind 配置速查 + +```javascript +// tailwind.config.js 扩展 +colors: { + primary: { + DEFAULT: '#0f172a', + hover: '#1e293b', + }, + accent: { + DEFAULT: '#6366f1', + hover: '#818cf8', + light: '#e0e7ff', + }, + success: { + DEFAULT: '#10b981', + light: '#d1fae5', + }, + warning: { + DEFAULT: '#f59e0b', + light: '#fef3c7', + }, + danger: { + DEFAULT: '#ef4444', + light: '#fee2e2', + }, +} +``` diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..4dbd881 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,39 @@ +# ========== 前端构建 ========== +FROM node:20-alpine AS frontend +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci +COPY index.html webpack.config.js tailwind.config.js postcss.config.js tsconfig.json ./ +COPY src ./src +RUN npm run build + +# ========== 后端构建 ========== +FROM node:20-alpine AS server-build +WORKDIR /app/server +COPY server/package.json server/package-lock.json ./ +RUN npm ci +COPY server/tsconfig.json ./ +COPY server/src ./src +RUN npm run build + +# ========== 生产运行 ========== +FROM node:20-alpine AS production +WORKDIR /app +ENV NODE_ENV=production + +RUN apk add --no-cache tini + +COPY --from=frontend /app/dist ./dist +COPY --from=server-build /app/server/dist ./server/dist +COPY --from=server-build /app/server/node_modules ./server/node_modules +COPY --from=server-build /app/server/package.json ./server/package.json +COPY migrations ./migrations +COPY server/scripts/docker-entrypoint.sh ./server/scripts/docker-entrypoint.sh + +RUN mkdir -p /app/uploads && chmod +x /app/server/scripts/docker-entrypoint.sh + +WORKDIR /app/server +EXPOSE 3001 + +ENTRYPOINT ["/sbin/tini", "--", "/app/server/scripts/docker-entrypoint.sh"] +CMD ["node", "dist/index.js"] diff --git a/Dockerfile.api b/Dockerfile.api new file mode 100644 index 0000000..4582c56 --- /dev/null +++ b/Dockerfile.api @@ -0,0 +1,27 @@ +FROM node:20-alpine AS server-build +WORKDIR /app/server +COPY server/package.json server/package-lock.json ./ +RUN npm ci +COPY server/tsconfig.json ./ +COPY server/src ./src +RUN npm run build + +FROM node:20-alpine +WORKDIR /app/server +ENV NODE_ENV=production +ENV SERVE_STATIC=false +ENV MIGRATIONS_DIR=/app/migrations + +RUN apk add --no-cache tini + +COPY --from=server-build /app/server/dist ./dist +COPY --from=server-build /app/server/node_modules ./node_modules +COPY --from=server-build /app/server/package.json ./package.json +COPY migrations /app/migrations +COPY server/scripts/docker-entrypoint.sh ./scripts/docker-entrypoint.sh + +RUN mkdir -p /app/uploads && chmod +x ./scripts/docker-entrypoint.sh + +EXPOSE 3001 +ENTRYPOINT ["/sbin/tini", "--", "./scripts/docker-entrypoint.sh"] +CMD ["node", "dist/index.js"] diff --git a/Dockerfile.web b/Dockerfile.web new file mode 100644 index 0000000..0a83978 --- /dev/null +++ b/Dockerfile.web @@ -0,0 +1,17 @@ +FROM node:20-alpine AS frontend-build +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci +COPY index.html webpack.config.js tailwind.config.js postcss.config.js tsconfig.json ./ +COPY public ./public +COPY src ./src +RUN npm run build + +FROM nginx:1.27-alpine +COPY deploy/nginx.frontend.conf /etc/nginx/conf.d/default.conf +COPY --from=frontend-build /app/dist /usr/share/nginx/html +COPY deploy/web-entrypoint.sh /web-entrypoint.sh +RUN chmod +x /web-entrypoint.sh + +EXPOSE 80 +ENTRYPOINT ["/web-entrypoint.sh"] diff --git a/FLOWCHART.html b/FLOWCHART.html new file mode 100644 index 0000000..f8863fc --- /dev/null +++ b/FLOWCHART.html @@ -0,0 +1,1327 @@ + + + + + +食堂配送系统 — 业务流程图 + + + + +
+

🏗️ 食堂配送系统 — 完整业务流程图

+ 订单流 + 财务流 + 决策点 + 结束节点 + 并行模块 + 异常 + AI / LLM + Android 称端 +
+
+ 开始 + 处理节点 + 决策分支 + 结束 + 并行模块 + 异常 + 数据写入 + 客户 采购员 仓管 供应商 配送员 管理员 +
+ +
+ + +
+
1 订单主流程 — 状态机总览
+
+
+
📥 下单
+
录单员代客下单
文字/语音/图片录入
+
order_status=20 待分配
+
order_items 写入
order_status=20 待分配
+
录单员
+
+
→
+
+
⚙️ 分配引擎
+
reprocessOrderAllocation()
分类绑采购员强制自采 → 分类供应商 → SKU → 自采兜底
+
order_status=30 待备货
+
系统自动
+
+
→
+
+
📦 备货
+
供应商备货常见 10→30(20可选;缺货40转自采)
自采完成=purchase_status 20(10/32 未齐;入库后常关到30)
+
订单 order_status=30 待备货
+
供应商 采购员
+
+
→
+
+
🔍 验收
+
多数在 40 待验收称重入库
(确认入库≠退回;实收少不挡升单)
+
order_status=40 待验收
+
仓管
+
+
→
+
+
📏 分拣出库
+
称重→确认→出库扫描
CompletePickingOutbound
+
order_status=45 待分拣
+
仓管
+
+
→
+
+
🚚 待配送
+
装车确认
准备发车
+
order_status=50 待配送
+
配送员
+
+
→
+
+
🚚 配送中
+
发车→位置实时上报
腾讯地图导航
+
order_status=60 配送中
+
配送员
+
+
→
+
+
✅ 签收完成
+
拍照签收
订单完结
+
order_status=90 已完成
+
配送员
+
+
+
+ + +
+
2 AI智能解析 — parseOrderThreeLayer 统一入口(文字/图片/语音三模态)
+ + +
+
📐 parseOrderThreeLayer 是统一入口;parseImageOrder / parseVoiceOrder 是薄包装(前者默认 customerCode='self',后者已传文本时可跳过 ASR)
+
+ + +
+
+
📝 文字输入
+
text 字段
用户输入自然语言
"菠菜10斤 西红柿5斤"
+
▼
+
extractItemsWithLLM
resolvePrompt('order.parse.text')
→ callArkWithText(历史别名,实走 llmService 多厂商层)
→ 文本 LLM 出 JSON
+
+
+
📷 图片输入
+
imageBase64 字段
拍照/选图上传
(无哈希缓存短路)
+
▼
+
extractItemsFromImage(Parallel)
resolvePrompt('order.parse.image')
→ callArkWithImage(历史别名,实走 llmService)
→ 多模态 LLM 直接出 JSON
→ 再进四层匹配
+
+
+
🎤 音频输入
+
audioBase64 / 录音
Web:停录→transcribe-audio 填文本
用户再点「智能解析」
小程序/API:可直接 audioBase64
+
▼
+
transcribeAudioBase64 (ASR)
语音识别 → 文本
speechService 转写
+
▼
+
extractItemsWithLLM
resolvePrompt('order.parse.text')
→ callArkWithText(历史别名,实走 llmService)
→ 文本 LLM 出 JSON
+
+
+ + +
▼ ▼ ▼ 三条路径汇聚到同一匹配引擎 ▼ ▼ ▼
+ + +
+
+
⚙️ matchSpokenRatioFromContext() — 生产 SKU 匹配引擎
+
LLM 一次拆出一批商品 → 逐条对 originalName 独立匹配(互不影响)
+ 客户库 / 别名 / 系统 SKU 上下文只加载一次;Layer 2(sku_aliases)已下线,层号不重编
+
+ +
+
① 精确匹配 — 短路:命中即停,不进下一层、也不进模糊(执行序:别名 → 客户库 → 系统库;层号仍标来源)
+
+
先试 · Layer 1
客户别名 exact
customer_sku_aliases
别名相等 → 0.95
命中则本行结束
+
→ 未中
+
再试 · Layer 0
客户商品库 exact
customer_skus
名相等 → confidence 0.98
命中则本行结束(含单位/加工)
+
→ 未中
+
Layer 3
系统 SKU exact
skus
库名相等 → 0.75
命中则本行结束
+
+
先别名精确,未中再客户库精确,再未中才系统库精确。三者都失败 → 进入模糊段。
+
+ +
▼ 精确全未中
+ +
+
② 模糊匹配 — 三源同时收候选,竞优取 1 条(不是「客户库模糊完再试系统库」)
+
+
源 A · L0
客户商品库窗口
spokenNameWindowScore
confidence 标 0.92
+
源 B · L1
客户别名窗口
同上 · 标 0.85
+
源 C · L3
系统 SKU 窗口
同上 · 标 0.70
+
+
+ 排序:leftover 更小优先 → usage_count 更大优先 → 推入顺序
+ 取 candidates[0];返回的 matchLayer 只表示赢家来自哪张表,不代表按层短路 +
+
+ +
▼ 仍无候选
+ +
未匹配
本行 skuCode='' · matchLayer=null
Web:未映射标红;已映射但录单名≠库名标黄
提交时可 ensureOrderProductsInCatalog 建档
+ +
+ 图片额外兜底:四层(精确+模糊)之后,仅对仍无 skuCode 的行再跑 findSkuByFuzzyName;文字/语音不做这一步 +
+
+
+
+ + +
+
📦 对外 API 层 — routes/functions.ts 暴露三个端点,底层都调用 parseOrderThreeLayer
+
+
+
POST /api/functions/
+
parse-order-three-layer
+
直接调用 parseOrderThreeLayer()
接受 text / imageBase64 / audioBase64
返回完整 ParseResult
+
+
+
POST /api/functions/
+
parse-image-order
+
parseImageOrder() 薄包装
→ 内部调用 parseOrderThreeLayer({imageBase64})
→ reshape 输出格式
+
+
+
POST /api/functions/
+
parse-voice-order
+
parseVoiceOrder() 薄包装
→ 内部调用 parseOrderThreeLayer({audioBase64})
→ ASR转写 → 文本LLM拆条 → 匹配
+
+
+
+ ⚠️ 语音:服务端路径 ASR→文本 LLM;Web 录单页为「先转写填框,再点智能解析」两步
+ ⚠️ 图片不经过 OCR 中转:直接多模态 LLM(order.parse.image),再进精确短路 + 模糊竞优匹配
+ ⚠️ 图片哈希缓存与成对归档已彻底拆除:order_image_vectors / customer_image_aliases 表已 drop(迁移 20260907),imageVectorService 已删,识别不落原图/会话 +
+
+ + +
+
📝 提示词注册表 — promptRegistryService.resolvePrompt(featureKey) 按模态取不同 system prompt(注册 3 套,实际在用 2 套:text + image;audio 注册了但代码走 ASR→text)
+
+
order.parse.text
文字解析提示词
NLP 提取: 品名/数量/单位
加工方式/备注/分类
六字段 JSON 输出
+
→
+
order.parse.image
图片解析提示词
多模态看图出 JSON
与文字解析共用字段规则
(ORDER_PARSE_SHARED_RULES)
+
→
+
order.parse.audio
⚠️ 已注册但代码未用
音频实际走 ASR → 文本
→ extractItemsWithLLM
→ 复用 order.parse.text
+
+
+ + +
+
🤖 多厂商 LLM 架构 — 分公司 → 平台 → 环境变量 三层配置 fallback
+
+
🔵 Layer 1: 分公司配置
system_configs key=branch_llm_config
超管在 AiModelManage 页面
按分公司配置 provider/API Keys/模型
+
→
+
🟡 Layer 2: 平台配置
system_configs key=platform_llm_config
全平台默认 LLM 配置
分公司未配置时 fallback
+
→
+
🟢 Layer 3: 环境变量
.env ARK_API_KEY / LLM_*
应急兜底配置
仅 ARK / OpenAI 兼容
+
+
+
多厂商
ark / openai / openai-compatible
llmProviderPresets 注册
超管界面可切换
+
→
+
模型分离
model: 文本/语音
visionModel: 录单识图
imageModel: 生图
+
→
+
用量预警(仅 Ark)
volcBillingService
余额查询+预警阈值
仅火山引擎可用
TokenHub 无余额查询
+
+
+ + +
+
🗂️ 商品映射表体系 — 支撑AI解析的核心数据
+
+
+
customer_sku_aliases
+
客户叫法 → 系统SKU
例: "大白菜"→SKU001
每个客户独立维护
提交订单后 learnAlias / syncCustomerMappings 写入
下次精确命中
+
+
+
customer_image_aliases
+
已 drop(迁移 20260907)
无运行时读写,连同 order_image_vectors 一并清理
+
+
+
customer_skus
+
客户商品库 Layer 0
显示名/单位/分类
提交后 syncCustomerMappings 更新
+
+
+
smart_classification_rules
+
智能分类规则
按关键词归类目录
+
+
+
+ + +
+
⚙️ AI提示词管理 — promptRegistryService + ai_params 表
+
+
+
提示词注册表
+
promptRegistryService
featureKey 标识功能
resolvePrompt 按分支解析
DB缺失时 fallback 到 defaults.ts
+
+
+
提示词模板
+
systemTemplate + userTemplate
变量注入(category_list等)
超管在 AiPromptManage 页面
可自定义编辑
+
+
+
功能矩阵
+
订单解析(文本/图片/语音)
市场自动配置
质检分析
SKU生图
成本分析 · 比价 · 税收编码
+
+
+
用量统计
+
aiParseMetricsService
记录每次AI调用
Token消耗/费用
成功/失败统计
+
+
+
+
+ + +
+
3 下单流程 — 12步骤详细分解
+
+
📥 客户提交订单 — 提交与分配共用一个事务(顺序对齐 customerOrderSubmitService)
+
+
步骤1
商品智能分类
enrichCustomerOrderItems
customer_skus 分类映射
smart_classification_rules 规则匹配
(分配内会再跑 enrichOrderItemsWithCategory)
+
→
+
步骤2
报价定价
orderPricingService
查询 customer_quote_sheets
匹配客户报价版本
+
→
+
步骤3
客户存在性校验
assertCustomerCredit
(customerBudgetService)
仅校验客户存在;额度/冻结只回显
Node 不再按 credit_limit 拦单
(零价拦截见步骤4)
+
→
+
步骤4
零价拦截(提交)
isBlockZeroSaleOnSubmitEnabled
键 block_zero_sale_on_submit
命中则拒绝提交
(分配内另有 assertNoZeroPriceItems)
+
+
+
步骤5
商品建档
ensureOrderProductsInCatalog
UPSERT skus 表
UPSERT product_catalog 表
(含 confirmNewProducts 门控)
+
→
+
步骤6
生成订单号
allocateOrderCode(事务内 advisory xact lock + 当日流水)
ORD_{WEB|MP|CP|API}_{YYYYMMDD}_{分公司}_{流水4位}
例 ORD_WEB_20260904_SH_0001
+
→
+
步骤7
写入订单+明细
INSERT orders order_status=20
→ 再 INSERT order_items
(含报价成本种子、remarks)
+
→
+
步骤8
触发分配引擎
reprocessOrderAllocation()
复用同一事务:规则匹配
+ 写备货/自采/履约
+ 全覆盖则 order_status=30
(步骤10-12 在此内部)
+
+
+
步骤9
同步加工需求
syncWarehouseProcessingDemandForOrder
processing_demand_items
(在分配之后,同事务)
+ post-commit 二次同步
+
→
+
步骤10-12
备货/自采/升30(分配内)
supplier_preparations prepare_status=10
purchase_orders purchase_status=10
全覆盖则 orders.order_status=30
文案:待备货
+
+
+
+ + +
+
4 分配引擎 — reprocessOrderAllocation() 单函数事务内执行
+
+
⚙️ orderAllocationService.ts — reprocessOrderAllocation() 一个事务内完成(6个步骤)
+
+
步骤1
行锁 + 竞价门控
SELECT orders FOR UPDATE
resolvePerOrderAutoBidGate
竞价进行中可 defer 分配
范围外商品立刻分配
+
→
+
步骤2
零价拦截
assertNoZeroPriceItems
零价商品拒绝分配
+
→
+
步骤3
加载上下文
loadAllocationContext
suppliers · supplier_categories
sku_suppliers · categoryRows
categoryPurchaserBindings
allocationRulesConfig
+
→
+
步骤4
明细增强
SELECT order_items FOR UPDATE
enrichOrderItemsWithCategory
enrichOrderItemsWithFuzzySku
applyStockCoverForOrder(在竞价门控内、零价之前)
+
→
+
步骤5
规则匹配 + 写入
allocateOrderItems()
①分类绑采购员→强制自采
②分类经营品类→备货(需 categoryMatchToSupplier 开)
③SKU供货目录→备货(②未命中才跑)
④自采兜底
→ INSERT 备货/自采/履约
(竞价中标在 allocate 之后 override)
+
→
+
步骤6
COMMIT + 后处理
事务提交
syncSkuCostFromPreparation
ensureInspectionsForOrder
notifyPreparationsAllocated
(孤儿清理在 COMMIT 之前)
竞价发标在 defer/外层调用方
+
+
+ + +
+
+
+
🔀 分配决策
+
对每个未履约商品
+
+
+
+
⚡ 优先:分类绑采购员
+
强制自采
purchase_category_purchaser_map
命中则跳过供应商备货
挂指定采购员
→ 采购员自采
+
+
+
✅ 分类供应商
+
分类经营品类
supplier_categories
categoryMatchToSupplier
支持父级分类链
→ 供应商备货
+
+
+
✅ SKU 目录
+
SKU供货目录
sku_suppliers
(仅当 categoryMatchToSupplier 开且分类未命中)
pickSkuSupplierFallback
→ 供应商备货
+
+
+
❌ 无匹配
+
自采兜底
purchase_orders
默认/规则配置采购员
→ 采购员自采
+
+
+
+
+
+ + +
+
5 备货与自采阶段 — 同一订单下按行挂履约,两条作业并行
+ +
+
+
订单已在 30 · 履约已挂齐
+
分配后:有的行→备货,有的行→自采
(还可库存覆盖);同单并行推进,不是先做完备货再自采
+
+
+
▼ 按行分叉(可混单)
+ +
+ +
+
Ⓐ 供应商备货轨 · supplier_preparations
+
+
10 待供
分配写入 · 挂 fulfillment
供应商
+
▼
+
20 确认(可选)
可跳过 · 非必经
+
▼
+
30 完成供货
可一并带价/量/单位
(完成前直改,不建申请)
本行备货齐
+
+ 旁路:缺货 40 → 转自采轨新建 PO
+ 完成后窗口内 amend-price → 管理员 confirm
+ 管理员亦可 update-purchase-price 直改 +
+
+
+ +
+ ∥ + 并
行
+ ∥ + 缺货↘
转供↗
+
+ + +
+
Ⓑ 自采轨 · purchase_orders
+
+
10 待采
分配写入 / 备货缺货转入
32=质检不合格待重采
采购员
+
▼
+
20 自采完成
POST …/purchase/complete
建待验;对升单已算「齐」
≠ purchase_status 30
本行自采齐
+
▼
+
常关到 30 / 作废 40
入库后关单;转供应商则
另建备货10、旧 PO→40
+
+ 旁路:仅 10/32 可 assign-supplier → 进备货轨
+ 与备货追加改价无关 +
+
+
+
+ +
▼ 整单状态何时离开 30(与页面「能不能看见备货/自采」无关)
+
+
+
订单状态门禁 · tryAdvanceOrderToInspection
+
+ 订单页随时可展示各行备货/自采进度(两轨作业互不挡展示)。
+ 仅当整单「未完成」清零才自动 30→40:
+ · 无未完成备货(prepare_status<30 且未转自采)
+ · 无待采自采(purchase_status 为 10 或 32;完成=20 即算齐)
+ · 库存抵扣行也已履约覆盖
+ 免入库 / 商品直送整单可直接 →50/90,不一定停 40。 +
+
+
+

+ 「并行」= 同单不同行可同时走备货或自采,供应商与采购员可同时作业;不是「先做完一轨再做另一轨」。
+ 「齐」只决定订单 order_status 能否升档,不是两轨合成一条展示链。完成前直改价 ≠ amend-price(键 supplier_prep_price_amend_enabled)。 +

+
+ + +
+
6 验收阶段 — 确认入库 vs 退回(现口径)
+
+
+
待验任务
+
GET /api/mobile/inspection/tasks
未提交:inspection_time 空
+ actual_qty=0 + 无质评
(已退回/已入库不在待验列表)
+
仓管
+
+
→
+
+
称重 · 拍照 · 质评
+
多数订单已在 40;仓内加工成品
待验可在订单仍 30 时出现
POST …/inspection/complete
+
+
→
+
+
确认入库 or 退回?
+
关键:reject_fulfillment
(≠ 质评合格/不合格二元)
+
+
+
+
+
✅ 确认入库(reject_fulfillment 未开)
+
写入入库
compliance_status=40
(验收入库 lossQty 恒 0;旧 20 损耗态不再新写)
可标质评不合格仍入库
可 upsert 供应商结算
本行覆盖
+
▼
+
部分入库?
未收满可建续验行
本行未完全覆盖则不升单
+
▼ 整单各行都入库覆盖
+
+
分拣
开分拣→建 picking
order 40→45
+
关分拣
order 40→50
+ 配送任务
+
加工
建验预推
入库再 upsert
+
+
+ maybeAdvanceOrderAfterFulfillment:实收<订货不挡整单离开待验收
+ (有成功入库行即视为该行覆盖) +
+
+
+
❌ 退回(reject_fulfillment=true)
+
不入库
compliance_status=30
不写批次账
供应商备货重置再供
或自采 → purchase_status=32
退回
+
▼
+
订单回落
仅当 order_status=40
才 UPDATE → 30
(已 >40 不因本行退回而降)
+
+
+
+
旁路(不经或不全经本图)
+
+
免入库 / 商品直送
可不建待验行
订单可 30→50/90
+
独立入库
order_code 可空
退回只回自采
不降销售单状态
+
库存全额抵扣行
可不经验收入库
仍计入履约覆盖
+
+
+
+ + +
+
7 ⚡ 加工模块 — 独立并行状态机
+
+
⚡ 不阻塞订单主流程。加工需求(processing_demand_items)在分配后 syncWarehouseProcessingDemandForOrder;验收通过后可据此生成 processing_tasks
+
+
+
待加工
+
从需求单/验收链路生成
或手动创建独立加工单
+
process_status=10
+
仓管
+
+
→
+
+
加工中
+
操作员开始加工操作
POST /processing/start
+
process_status=20
+
+
→
+
+
完工登记
+
记录损耗量 loss_qty
记录出成率 yield_rate
人工成本入账
+
process_status=30
+
+
→
+
+
加工验收
+
拍照验收
写入 processing_logs
成本入账 cost_details
+
process_status=40 完成
+
+
+
+ ★ 独立加工单: 小程序 POST /api/mobile/processing/standalone/create 或 Web /api/workflow/processing/standalone/create → order_code=NULL +
⚠️ 加工成品不入可领库存:加工产出的成品不进入分拣可领池,避免库存循环 +
⚠️ process_status 另有 50=不合格(rejected) +
+
+
+
✏️ 管理员改领料(已完工 XQG)
+
改领料总数
PATCH /api/workflow/processing/
demand/:taskId/material-qty
amendDemandSheetMaterialQty
新量 >0 且 ≥ net_weight
保持 process_status=40
管理员
+
▼
+
库存差额 + 重算摊价
增多 FIFO processing_out
减少 LIFO 退 PRT
settleDemandSheetCostOnCompletion
可覆盖入库批次 cost_price
(不入 cost_details 采购 KPI)
+
+
+
🗑️ 孤儿仓内需求单删除
+
删无活订单行需求单
DELETE /api/workflow/processing/
demand/:taskId
仅 source_type=demand
linked_order_count=0 才可删
任意 process_status(含40/50)
管理员
+
▼
+
退料或仅删记录
net_weight=0 且已领→先退料 PRT
net_weight>0→不退料只删任务
清 cost_details 脏引用
孤儿单隐藏领料/改领料
+
+
+
+
+ + +
+
8 分拣出库 → 装车 → 发车 → 配送签收
+
+
📏 订单已在 45 待分拣。CompletePickingOutbound 要求 pick_status≥30:扫码→确认→FIFO 扣库存→生成配送任务→order_status 45→50
+
+
+
📏 分拣称重
+
GET /picking/tasks
称重站称重/拍照
POST weigh-station/commit
+
仓管
+
+
→
+
+
分拣确认/完成
+
POST /picking/confirm → pick_status 20
POST /picking/complete → pick_status 30
(complete 后 post-commit 可升 50)
+
+
→
+
+
出库扫码+确认
+
POST /picking/outbound-scan
CompletePickingOutbound(需≥30)
FIFO扣库存·pick_status=40
自动生成配送任务
→ orders.order_status=50
+
pick_status 10→20→30→40
+
+
+
+
+
▼
+
+
+
+
🚚 装车确认
+
POST /delivery/loading/
confirm-item
扫码装车+拍照
delivery_loading_items
+
配送员
+
+
→
+
+
发车
+
POST start-batch
task_status=20
orders.order_status=60
+
order_status=60
+
+
→
+
+
配送中
+
位置实时上报
POST /delivery/location
delivery_locations
+
+
→
+
+
📸 配送员拍照
+
小程序 POST …/sign-photo
sign_type=delivery
写入 delivery_signatures
(本身不完结订单)
+
+
→
+
+
✅ 签收结案
+
Web: POST …/delivery/sign-off(需 order_status=60)
或 signature(sign_type=customer)
小程序: POST /delivery/stop→finalize
→ order_status=90
(残留下线代码已为 no-op)
+
order_status=90
+
+
+
+
+
⚠️ 配送异常
+
异常工单
人工处理
+
+
+
➕ 配送后加菜
+
≥50 加菜履约+成本
不走分配引擎;库存覆盖履约
自采→ensureCompletedExtraDishPurchase(PURX 已完成)
有供应商→补已完成备货+结算
无履约挂载→reconcileExtraDishPurchaseCosts
→ cost_details(extra_dish)
+
+
+
+ + +
+
9 财务结算流程 — 按周期走财务工作流(与订单履约状态解耦)
+
+
💰 入库/完结会 upsert 对账单(应用层 SELECT+UPDATE/INSERT);周期对账复核仍可手动/定时。客户对账单/批量采购入账与 order_status=90 耦合;采购/加工成本在入库/完工时入账;配送成本无自动入账路径(旧 postDeliveryCostForOrder 为死函数已删),仅作为 cost_details 标签展示
+
+
结算1
供应商对账单
验收入库后(order_status≥45)
ensureSupplierStatementAfterInbound
完结时 ensureSupplierStatementsForOrder
加菜补待确认·排除内部码
UPSERT supplier_statements
+
→
+
结算2
客户对账单
完结 finalize 时(≥90 才写)
upsertCustomerStatementForOrder
亦可按日批量复核
UPSERT customer_statements
+
→
+
结算3
对账确认/争议
确认或标记争议
更新对账单状态
+
→
+
结算4
成本入账
采购成本(验收写入 cost_details/purchase)
加工成本(完工写 labor_processing)
配送成本无自动入账路径
批量采购入账要求≥90
非订单完结自动触发
+
→
+
结算5
杂费/固定成本
杂费存 cost_details(cost_type='free_overhead')
fixed_costs 固定成本
凭证照片+签名存储URL
成本分摊到订单/客户/分公司
+
+
+
+ + +
+
10 售后与竞价管理
+
+
+
🔄 售后流程
+
+
客户自助售后
POST …/customer-order/after-sales
占位路由已删 · 404
(请走 Web/内部售后)
客户
+
▼
+
售后单(内部)
after_sales
退货/换货/退款
(自助入口已移除)
+
▼
+
+
库存退回
inventory 重新入库
+
退款处理
finance 退款单
+
+
+
+
+
📋 竞价流程
+
+
创建竞价轮次
bid_rounds
管理员
+
▼
+
发送邀约
bid_invitations
+
▼
+
供应商报价
bid_quotes
供应商
+
▼
+
比价定标
bidAwardScoringService
选择中标供应商
→ 写入 bid_awards
(不回写 sku_suppliers;下次分配从 bid_awards 读)
+
+
+
+
+ + +
+
11 系统架构总览 — 4层拓扑
+
+
+
🖥️ 前端展示层
+
+
微信小程序
26个页面
wx.request()
/api/mobile/*
+
Web管理端
React 18 SPA
~43个页面
localApiClient
+
供应商外部系统接口
OAuth client_credentials
/api/supplier/* 开放 API
备货/改价/质检/竞价
小程序 /api/mobile/supplier/*
+
Android 称端
android-weigh-terminal
验收 + 分拣 APK
串口秤 + 摄像头 + OTA
/api/mobile/weigh/*
+
+
+
▼
+
+
🌐 Nginx 网关
+
所有 /api/* 请求 → Node.js :3001
+
+
▼
+
+
+
🔵 Node.js 后端 :3001
+
Express + TypeScript · ~550+ 服务文件 · ~40 路由文件
订单/分配/备货/验收/分拣/配送/财务/供应商
Pipeline 6阶段分配引擎 · 多厂商 LLM 统一层
AI订单解析(文字/图片两套在用提示词,audio 注册未用)
称端识别:ONNX 本地视觉 + LLM 兜底 + 自动学习
提示词注册表 · 分公司LLM配置 · OAuth供应商集成
微信订阅通知(暂未接通)/腾讯地图/SKU AI生图/语音转写
称端 OTA(COS manifest + 静默安装)
Redis查询缓存 · 定时任务 · 分布式锁
+
+
+
▼
+
+
+
🗄️ PostgreSQL 16
+
canteen_delivery · 6大域
订单/履约/仓储/配送/财务/基础
RLS多租户行级安全 · 280+迁移
+
+
+
☁️ OSS/S3 文件存储
+
10个Bucket · HMAC签名URL
质检照片/签收照片/凭证/商品图片/质检报告
+
+
+
▼
+
+
🌍 外部集成
+
+
微信平台
登录
(订阅消息暂未接通)
+
腾讯地图
路线规划
+
多厂商 LLM
豆包/OpenAI
兼容API
+
豆包语音
语音转文字
+
ONNX 本地视觉
backbone.onnx
prototype 匹配
称端识别加速
+
Redis
查询缓存
+
+
+
+
+ + +
+
12 🤖 多厂商 LLM 架构详解
+
+
🔌 llmProviderPresets 注册厂商 → llmService 统一入口 → 各业务 Service 调用
+
+
ark (火山引擎)
豆包系列模型
doubao-seed-2-0-lite
doubao-seedream-4-0
语音识别 · 图片生成
+
→
+
openai
GPT 系列模型
chat/completions
images/generations
+
→
+
openai-compatible
TokenHub(腾讯)
hy-vision-2.0-instruct
glm-5v-turbo
称端视觉识别 + 质量
+
+
+
+
⚙️ 配置层级 — 分公司 > 平台 > 环境变量
+
+
branch_llm_config
system_configs 表
超管 AiModelManage 页面
按分公司选择厂商/模型/API Key
+
→
+
platform_llm_config
system_configs 表
全平台默认配置
分公司未启用时 fallback
+
→
+
环境变量
.env 文件
ARK_API_KEY / LLM_*
应急兜底
+
+
+
+
🎯 业务接入点
+
+
订单解析
orderParseService
文本/图片/语音
+
质检分析
inspectionAiService
图片质量评估
+
SKU生图
skuImageService
商品图片AI生成
+
市场比价
marketAiPriceQuoteService
AI辅助市场询价
+
成本分析
costAiService
成本根因分析
+
税收编码
taxCodeAiService
智能税收分类
+
全员助手
orderEntryAgentHost
会话索引 session_id
routeModules 1~2 模块
+
称端识别
weighStationService
ONNX 预筛 + LLM 识别
质量评估 + 自动学习
+
+
+
+ + +
+
13 核心数据表关系
+
+
+
📋 orders (订单主表)
+
order_code PK · order_status · customer_code · branch_code · total_amount · delivery_date
+
+
◢━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━━◣
+
+
order_items
订单明细
sku_code · qty · price
+
inspections
验收·compliance_status
inspection_photos · actual_qty
+
delivery_tasks
配送任务
task_status · person_code
+
+
◢━━━━━━╋━━━━━━◣
+
+
order_item_fulfillments
履约关联 (备货/自采二选一)
+
supplier_preparations
备货 10→30(20可选;40缺货)
+
purchase_orders
自采完成=20;10/32未齐
+
processing_tasks
加工⚡ 10→20→30→40(50不合格)
+
picking_tasks
pick_status 10→20→30→40
+
delivery_signatures
签收记录
+
+
◢━━━━━━━━━━━━━━ 称端相关 ━━━━━━━━━━━━━━◣
+
+
weigh_devices
称端设备注册
deviceCode + branch
+
prototypes.json
ONNX 原型向量
商品名 → 576维向量
自动学习更新
+
backbone.onnx
特征提取模型
常驻内存
非数据库文件
+
+
+
+ + +
+
14 完整数据流汇总
+
+ + + + + + + + + + + + + + + + + + + +
#流程触发端动作描述写入表状态变更
1下单录单员①enrichCustomerOrderItems 分类 ②报价定价 ③assertCustomerCredit(仅客户存在;额度不拦单) ④提交侧零价拦截(block_zero_sale_on_submit) ⑤ensureOrderProductsInCatalog 建档 ⑥allocateOrderCode(事务内advisory lock+当日流水,ORD_入口_日_分公司_流水) ⑦INSERT orders(20)再 order_items ⑧reprocessOrderAllocation(同事务,内含备货/自采/升30) ⑨syncWarehouseProcessingDemandForOrder→全覆盖 order_status=30orders, order_items, skus, customer_skus, processing_demand_items, supplier_preparations, purchase_ordersorder_status 20→30
2分配引擎自动reprocessOrderAllocation():锁定订单→竞价门控→applyStockCoverForOrder→assertNoZeroPriceItems→loadAllocationContext(含 categoryPurchaserBindings)→enrich→allocateOrderItems:①分类绑采购员强制自采 ②分类供应商(categoryMatchToSupplier开) ③SKU目录(②未命中) ④自采兜底→写备货/自采/履约→竞价中标override→全覆盖升30supplier_preparations, purchase_orders, order_item_fulfillments, purchase_category_purchaser_map, bid_awardsorder_status→30 待备货
3备货供应商备货10→(可选20)→完成30时可带价/量/单位;缺货40转自采。全单备货<30清零且自采无10/32→tryAdvance→订单30→40(免入/直送可50/90)。完成后窗口内 amend-price 写申请,管理员 confirm 才入账;管理员亦可 update-purchase-price 直改supplier_preparations, supplier_prep_amend_requestsprepare 10→30(可选20;40);订单→40
4自采采购采购员待采10(或质检驳回32)→complete→20 并建待验;可 assign-supplier 另建备货、PO作废40。入库后常关到30。与备货追加改价无关purchase_orders, supplier_preparationspurchase 10/32→20→30;转供40
5验收仓管待验=未提交(time空/无质评/qty0)。提交 POST …/inspection/complete:确认入库→compliance=40(lossQty=0;可不合格仍入库)/部分入库建续验;整单行覆盖后 maybeAdvance→45(开分拣+picking)或→50。退回 reject_fulfillment→compliance=30、备货重置或自采32;订单仅当前=40才回30。实收<订货不挡升单。免入/直送/独立入库旁路inspections, picking_tasks, processing_tasks, supplier_statements确认→40→45/50;退回可→30
6加工仓管/管理员需求单分配后同步;验收单创建时预推送。仓管领料加工 process_status 10→20→30→40(50不合格)。管理员可 PATCH …/demand/:taskId/material-qty 改已完工领料(保持40);DELETE …/demand/:taskId 删无活订单行孤儿需求单。成品不入可领库存;独立加工单 order_code=NULLprocessing_demand_items, processing_tasks, processing_demand_picks, processing_logsprocess_status 10→40(50);改领料保持40
7分拣出库仓管订单已在 45。/picking/confirm→20;/picking/complete→30(post-commit可升50);CompletePickingOutbound(需≥30):FIFO扣库存·pick_status=40·order_status 45→50·生成配送任务·装车确认picking_tasks, delivery_tasks, delivery_loading_items, picking_scan_logspick_status 10→40;order 45→50
8发车配送员装车确认→发车→task_status=20→order_status 50→60→位置上报→deliveryRoutingServicedelivery_tasks, delivery_person_locationstask_status 20;order 50→60
9签收配送员小程序 sign-photo(delivery) 存凭证→POST /delivery/stop→finalize;Web POST /delivery/sign-off(需order_status=60) 或 /delivery/signature(customer)→finalizeOrderFulfillment→order_status=90(会 upsert 客户/供应商结算)。下线代码已为 no-opdelivery_signatures, customer_statements, supplier_statementsorder_status 60→90
10财务结算入库/完结+手动定时入库 upsert 供应商结算(≥45);完结(≥90) upsert 客户/供应商结算(finalizeOrderFulfillment 不入账配送成本);批量采购成本入账要求≥90。周期对账确认/争议、加工成本(完工时入 labor_processing)、杂费(cost_details/free_overhead)、固定成本、分摊、发票仍可手动/定时customer_statements, supplier_statements, cost_details, fixed_costsstatement_status 变更
11售后客户客户申请售后→创建售后单(退货/换货/退款)→库存退回(重新入库)→退款处理→售后状态跟踪after_sales, inventory, order_item_returns售后状态变更
12竞价管理员管理员创建竞价轮次→添加竞价商品(bid_round_items)→发送邀约→供应商报价→比价定标→确认中标→写 bid_awards(不回写 sku_suppliers;下次分配从 bid_awards 读)bid_rounds, bid_round_items, bid_invitations, bid_quotes, bid_awards竞价状态变更
13质检报告供应商供应商选择报告类型(农残/重金属/检疫/产地)→上传质检报告到OSS→写入quality_reports→关联备货单→验收时自动校验报告是否齐全quality_reports上传
14入库仓管仓管扫码入库→登记批次号+数量+成本→写入inventory表→库存盘点→库存预警→批次管理inventory入库
15改单采购员采购员向已有订单添加/删除商品→更新order_items→修改order_item_fulfillments→重新触发分配引擎→重新分配新增商品→供应商重新备货order_items, order_item_fulfillments重新分配
16称端识别仓管Android 称端抓拍→POST recognize→ONNX 预筛 Top-K→置信度≥0.75 直返+补 LLM 质量→否则 LLM 全量识别→置信度≥0.85 自动学习 prototype→返回商品+质量→称重确认入库/分拣prototypes.json(异步更新)识别返回
17称端 OTA系统自动称端 30 分钟轮询 OTA 策略→比对 versionCode→下载 APK+SHA256 校验→日窗内静默安装(su 0 pm install)→非日窗弹窗安装→重启生效public.system_configs, COS manifestAPK 更新
+
+
+ + +
+
15 供应商管理全流程
+
+
+
📋 供应商注册
+
管理员创建供应商
前端 supabase.from('suppliers').insert()
经 /api/data(无独立 POST /api/suppliers)
supplier_code · company_name
管理员
+
▼
+
设置经营品类
supplier_categories
绑定供应商可经营的
商品分类 (支持多级)
+
▼
+
创建登录账号
POST /api/suppliers/
:supplierCode/login-account
supplier_users
+
▼
+
供应商评分
supplierRatingService
根据履约及时率/质量
自动计算评分
+
+
+
🔌 OAuth 集成
+
创建集成客户端
POST /api/suppliers/
integration-clients
supplier_integration_clients
生成 client_id + client_secret
+
▼
+
OAuth 获取令牌
POST /api/supplier/oauth/token
client_credentials 模式
返回 scope=supplier_integration
的 JWT Token
+
▼
+
API 调用
Bearer Token 调用
供应商开放 API
备货/改价/质检/竞价
+
+
+
📦 供货目录管理
+
SKU供货价设置
sku_suppliers
supplier_code + sku_code
supply_price · in_stock
竞价中标写 bid_awards(非目录)
+
▼
+
无货转自采
供应商标记无货(prepare_status=40)
→ transferPreparationStockoutToPurchase
→ 创建 purchase_orders(采购员自采)
非转给其他供应商
+
▼
+
缺货转单
POST /api/mobile/admin/
preparations/stockout-transfer
从缺货备货转采购员自采
(非转其他供应商)
+
+
+
+ + +
+
16 客户管理 — 档案/授信展示/别名/报价/代录
+
+
客户档案
customers
customer_code · company_name
contact_name · contact_phone
+
→
+
预算/授信(展示)
customers
credit_limit / credit_frozen / used_budget
下单只校验客户存在;额度不拦单
(budget_amount 已废弃)
+
→
+
商品别名
customer_sku_aliases
客户叫法→系统SKU
提交订单后 learnAlias 写入
+
→
+
客户商品库
customer_skus
显示名/单位/分类
提交后 syncCustomerMappings
+
→
+
报价单(主入口)
customer_quote_sheets
多商品 + 多/单客户
创建即生效(无需审批)
到期顺延 + 历史快照
+
→
+
报价版本(物化)
customer_quote_versions
由报价单 activate 时物化
旧 /quote/version* HTTP 已删
下单取价读此表
+
→
+
代录下单
Web CustomerOrder / 录单页
小程序客户自助下单占位已删(404)
(请联系录单员)
+
+
+ + +
+
17 商品与库存管理
+
+
+
📦 商品管理
+
分类管理
categories
树形结构 (parent_code)
支持多级分类
+
▼
+
SKU管理
skus
sku_code · sku_name
category_code · unit · price
AI生图(仅Node)
+
▼
+
商品目录
product_catalog
商品与分公司/分类关联
每个分公司独立目录
+
▼
+
+
单位管理
units + unit_conversions
+
税务编码
tax_codes
AI辅助税收分类
+
SKU图片
GET /api/sku-image/:skuCode
本地存储或OSS
+
+
+
+
🏪 库存管理
+
入库登记
POST /api/mobile/inventory/stock-in
INSERT inventory
batch_code · quantity · cost
仓管
+
▼
+
库存查询
GET /api/workflow/inventory/*
按SKU/批次/仓库查询
库存覆盖/库存预警
+
▼
+
库存调整
单条调整/独立入库
(无盘点会话闭环,见 §28)
+
▼
+
商品溯源
内部溯源: GET /api/workflow/trace/search
GET /api/workflow/trace/batch/:code
订单→验收→分拣→配送
公开溯源: GET /api/public/trace/:code
+
+
+
+ + +
+
18 通知系统 — 站内通知 + SSE推送(微信订阅暂未接通)
+
+
+
📬 站内通知
+
通知生成
notificationService
业务事件触发:
分配完成/备货确认/验收完成
配送发车/签收/改价审核
+
▼
+
通知存储
INSERT notifications
user_id · title · content
is_read=false
+
▼
+
通知列表
GET /api/mobile/notifications
按用户查询
未读/已读分类
+
+
+
📡 SSE 实时推送
+
建立SSE连接
GET /api/workflow/notifications/stream
fetch + ReadableStream 长连接
notificationStreamService
Redis Pub/Sub 桥接
+
▼
+
实时推送
新通知产生 →
Redis Publish →
SSE桥接 → 浏览器
useNotificationStream Hook
+
▼
+
角标更新
GET /api/mobile/badges
NotificationBell 组件
实时显示未读数
+
+
+
🔔 微信订阅通知(暂未接通)
+
微信绑定
POST /api/mobile/wechat/bind
user_wechat_subscriptions
关联微信 openid
+
▼
+
订阅授权
用户授权订阅消息模板
(暂未接通)
+
▼
+
模板消息推送
wechatMiniProgramService
验收提醒/配送通知
(暂未接通,暂不做)
+
+
+
+ + +
+
19 系统管理 — 用户/角色/权限/分公司/配置
+
+
用户管理
users
CRUD · 绑定角色
绑定业务身份
+
→
+
角色权限
roles + role_permissions
9个系统角色 · 46项权限
super_admin/admin/operator/finance
warehouse/picker/delivery
supplier/purchaser
+
→
+
分公司管理
branches
CRUD · 纳税等级
super_admin可切换
X-Operating-Branch header
+
→
+
系统配置
system_configs
config_key · config_value
按分公司持久化
分配规则/功能开关
+
→
+
操作日志
operation_logs
operationAuditMiddleware
自动记录所有变更操作
+
→
+
导航菜单
system_configs key=nav_menu_layout
分组/显示名/图标/排序
MenuLayoutConfig 拖拽配置
+
+
+
AI模型管理
AiModelManage.tsx
多厂商LLM配置
分公司→平台→环境变量
三层 fallback
+
→
+
AI提示词
AiPromptManage.tsx
promptRegistryService
可按分公司自定义
系统模板 + 用户模板
+
→
+
称端OTA
public.system_configs key=weigh_ota_policy
Android APK 远程更新
静默/手动 + 日窗
SHA256 校验
+
→
+
打印模板
system_configs JSON
配送单/标签模板
打印任务管理
+
→
+
导入映射
import_mapping_memories
Excel导入列映射配置
+
→
+
全员助手
POST /api/mcp/order-entry/chat
FAB session_id + 会话索引
assistantSessionStore
Redis/内存 TTL45min
(旧 /api/chatbot 未挂载)
+
+
+ + +
+
20 市场监控与数据分析
+
+
+
📊 市场价格监控
+
市场价格采集
marketPriceProvider
外部市场价格数据源
marketExternalBindingService
AI辅助市场自动配置
+
▼
+
价格对比分析
marketIndexService
系统采购价 vs 市场价
价格偏离度分析
+
▼
+
市场监控面板
MarketMonitor.tsx
AI辅助价格趋势
异常预警
+
+
+
📈 数据看板
+
仪表板概览
GET /api/dashboard/summary
待处理订单数
待配送任务数
待验收数
+
▼
+
操作队列
GET /api/dashboard/action-queue
待分配订单
待配送任务
待验收记录
+
▼
+
深度成本分析
CostRootCausePanel.tsx
成本根因分析
seasonalRecommendationService
季节性推荐
+
+
+
📋 批量导入
+
Excel导入
BulkImportModal组件
客户导入走 /api/data
导入映射 /import-mappings/:importType
客户/商品/订单批量导入
+
▼
+
文档导出
DocumentExportButton
ExportColumnModal
配送单打印:当前页注入
#canteen-delivery-print-host
→ window.print()(非 iframe)
+
+
+
+ + +
+
21 采购员专用工作流
+
+
+
📋 采购员工作台
+
PurchaserDashboard
待处理自采单
供应商备货状态
+
采购员
+
+
→
+
+
自采管理
+
查看自采单列表
确认自采完成
POST /purchase/orders/status
+
+
→
+
+
转供应商?
+
自采单可转给
有货供应商
+
+
→
+
+
供应商验收
+
POST /purchase/supplier-
inspection/complete-batch
批量完成供应商验收
+
+
+
+
加单
向已有订单添加商品
+
删单
从已有订单删除商品
+
修正实际量
PATCH /purchase/:code/amend-actual
+
关联销售价
PATCH /purchase/:code/linked-sale-price
+
修改采购员
PATCH /purchase/:code/purchaser
+
跳过仓需
POST /purchase/skip-warehouse-demand
+
直送拍照
POST /purchase/direct-delivery-photo
+
自采入库
POST /purchase/self-purchase-stock-inbound
+
自采加工
POST /purchase/self-process
+
+
+ + +
+
22 称重站详细流程 — Android 称端(验收 + 分拣)
+
+
⚖️ Android 称端(android-weigh-terminal)是独立 APK,走串口读秤 + 摄像头抓拍 + 服务端 AI 识别;验收和分拣共用同一套识别引擎
+
+
+
📸 识别流程(验收/分拣共用)
+
秤稳定 + 摄像头抓拍
串口读秤(kg/jin)
Camera1 API 预览帧 → takePicture
1600×1200 抓拍 → 裁剪 → JPEG
+
▼
+
POST 识别接口
验收: /mobile/inspection/weigh-station/recognize
分拣: /mobile/picking/weigh-station/recognize
image=base64 + 候选名单
+
▼
+
ONNX 本地视觉预处理
backbone.onnx 提取 576 维 embedding
与 prototypes.json 比较余弦相似度
Top-K 缩小候选名单(常驻内存)
+
▼
+
ONNX 置信度 ≥ 0.75?
WEIGH_ONNX_DIRECT_THRESHOLD
+
▼
+
+
+
✅ 是:ONNX 直返
+
跳过 LLM 识别
直接返回商品名
~0.2-0.3s
+
▼
+
补 LLM 质量评估
weigh.recognize.quality_only
只问质量,不传候选名单
~1-3s
+
▼
+
自动学习(≥0.85)
learnPrototype()
加权平均更新 prototype
异步持久化 prototypes.json
+
+
+
❌ 否:走 LLM
+
LLM 全量识别
weigh.recognize.catalog
缩小后的候选名单 + 图片
LLM 返回商品 + 质量
+
▼
+
LLM 兜底
ONNX 完全失败 → 全名单
LLM 未配置 → "请手选"
LLM 超时 → "请人工判定"
+
+
+
+
+
⚖️ 验收称重站
+
待验列表
GET /mobile/inspection/tasks
未提交的 inspections
含独立入库(order_code=null)
+
▼
+
称重 + 识别 + 质评
秤读数 + AI 识别商品
+ AI 质量评估(grade/score)
空秤 2s 后自动清空 + 刷新
+
▼
+
确认入库 / 退回
reject_fulfillment
入库 compliance=40
退回 compliance=30
+
▼
+
提交验收
POST /mobile/inspection/complete
打印标签(斤/瓶/个)
整单覆盖后升 40→45/50
+
+
+
📏 分拣称重站
+
待拣列表
GET /mobile/picking/tasks
未完成的 picking_items
按 SKU/客户分组
+
▼
+
称重 + 识别
秤读数 + AI 识别
计数单位(瓶/个)→ 数量
称重单位(斤)→ 秤读数
+
▼
+
确认装框
POST /mobile/picking/weigh-station/commit
pick_status 推进
打印分拣标签
+
▼
+
完成出库
CompletePickingOutbound
FIFO 扣库存
生成配送任务
order 45→50
+
+
+
+
+
🔧 称端 OTA 远程更新
+
+
OTA 策略
public.system_configs key=weigh_ota_policy
auto_update_enabled + 日窗 + schedule_at
manifest_url 平台统一
+
→
+
COS manifest
weigh-apk/manifest.json
versionCode + sha256 + apk_url
publish-weigh-apk.ts 发布
+
→
+
称端拉策略
GET /api/mobile/weigh/ota-policy
30 分钟轮询
策略 manifest_url 优先
+
→
+
下载 + 校验
下载 APK → SHA256 校验
自动窗内:静默安装
手动:弹窗安装
+
→
+
静默安装
SilentApkInstaller
su 0 pm install -r
A64 工控机已验证
+
+
+
+ + +
+
23 分拣模式详解 — 按订单 / 按分类
+
+
📏 分拣任务生成模式(picking_task_mode,按分公司配置,默认按订单)
+
+
+
📦 按订单(order · 默认)
+
一个订单 → 一个分拣任务
scope_type='order'
scope_key=order_code
scope_label=order_code
订单全部明细进同一任务
+
▼
+
适用场景
订单量小、客户单一
整单一次拣完
分拣员按单号领任务
+
+
+
🏷️ 按分类(category)
+
一个订单 → 多个分拣任务
scope_type='category'
scope_key=category_code
scope_label=分类名
按 category_code 分组
无分类归 UNCATEGORIZED
+
▼
+
适用场景
订单品类多、跨库区
不同分拣员按分类领
并行拣不同分类
+
+
+
+ 切换模式:PUT /api/workflow/picking/task-mode(可带 rebuild=true 重建未完成分拣任务)
+ 分拣员/配送员角色勾选分拣出库才启用分拣环节(仓管/管理员仅控菜单权限) +
+
+
+
⏳ 分拣阶段(pick_status)+ 自动分配分拣员
+
+
10
待分拣
创建任务时写入
tryAutoAssignPickerOnTask
按 scope 自动分配分拣员
+
→
+
20
分拣中
POST /picking/confirm
分拣员开始作业
称重站称重/计数
+
→
+
30
已完成(调单)
POST /picking/complete
或 /picking/audit(兼容旧路径)
reviewed_at 登记
不自动出库
+
→
+
40
已出库
CompletePickingOutbound(需≥30)
POST /picking/outbound 或 /outbound-scan
FIFO 扣库存 · 生成配送任务
order 45→50
+
+
+
+
⚖️ 称重站单位处理(不是分拣模式,是称重读数方式)
+
+
称重单位(斤/kg)
秤读数即数量
scaleKgToBusiness 换算
打印标签显示「斤」
+
→
+
计数单位(瓶/个/件)
秤读数不参与
默认取需求量
可手动改数量
打印标签显示「瓶/个」
+
→
+
混合单位
同一订单可含称重 + 计数
称重站按 SKU 单位自动判断
不作为分拣任务分组依据
+
+
+
+ + +
+
24 配送实时追踪 — 位置上报 + 轨迹查询
+
+
🚚 配送状态追踪 — 位置上报 + 轨迹查询(上下线已取消,仅校验在职状态)
+
+
位置上报
POST /api/mobile/delivery/location
delivery_person_locations
latitude · longitude
+
→
+
轨迹查询
GET /api/mobile/delivery/track/:taskCode
按时间排序的位置点
地图轨迹连线
+
→
+
路线规划
deliveryRoutingService.ts
腾讯地图API
多站点路径优化
+
→
+
配送排班
delivery_schedules
配送员排班管理
delivery_persons 在职状态
+
+
+
+ + +
+
25 异常管理详细流程
+
+
⚠️ 异常管理覆盖配送异常、验收异常、售后异常,exceptionPredictionService 规则引擎检测
+
+
+
配送异常
+
配送异常触发
超时未送达
配送员停车超时
签收异常
+
▼
+
异常工单创建
exception_tickets
ExceptionManagement.tsx
人工介入处理
+
+
+
验收异常
+
验收异常触发
验收不合规(compliance≈30)
质检不合格/数量短缺
现网拒收直接 40→30
(41 已从状态机移除,
仅 LABELS[41] 保留作历史展示)
+
▼
+
退回供应商
inspectionRejectNotificationService
通知供应商重新备货
记录退回原因
+
+
+
规则引擎异常检测
+
异常检测
exceptionPredictionService
规则引擎(非模型预测)
超时/停滞/积压检测
+
▼
+
预警通知
提前通知相关人员
采购员/仓管/配送员
降低异常发生率
+
+
+
+
+ + +
+
26 成本核算详细流程
+
+
采购成本(KPI)
权威:cost_details
cost_type=purchase
验收写入 / 加菜 extra_dish / unit_cost 同步
order_items.unit_cost 仅写缓存
非 KPI 读权威
+
→
+
加工成本
processing_tasks
人工/损耗 · yield_rate
需求单摊价写 unit_cost
(不入采购 KPI 账本)
+
→
+
配送成本
delivery_tasks
按配送任务分摊
距离/时间/油耗
+
→
+
固定成本
fixed_costs
仓库租金/设备折旧
FixedCostManagement.tsx
+
→
+
杂费录入
cost_details (cost_type='free_overhead')
停车费/过路费/其他
凭证照片+签名存储URL
+
→
+
成本分摊
costAllocationService
按订单/客户/分公司
多维度成本分摊
+
→
+
AI成本分析
costAiService
CostRootCausePanel.tsx
成本根因分析
+
→
+
发票管理
invoices
InvoiceManagement.tsx
开票辅助管理
+
+
+ + +
+
27 ⚙️ 控制开关与边界场景
+
+
🔔 定时强推+待补录
order_auto_advance(按分公司 HH:mm)
卡住单强推 → order_status=50
+ pending_backfill=true
scheduledJobs 日窗执行
+
→
+
➕ 完成单/≥50 加菜
不走分配;库存覆盖
自采 PURX / 供应备货(30)
+ reconcileExtraDishPurchaseCosts
→ cost_details extra_dish
+
→
+
↩️ 退货红冲
after_sales / is_returned
库存退回→成本回冲
结算调减
+
→
+
🎛️ 智能分配开关
smart_allocation_enabled
+ allocation_rules
categoryMatchToSupplier
直送/仓内强制自采
分类绑采购员 map
+
+
+
🕐 零价/下单时段
键 block_zero_sale_on_submit
零价商品拦截
order-submit-window-config
下单时间窗口限制
+
→
+
🚪 竞价门控
bid_rounds per_order
竞价进行中禁止分配
allocation_hold_until
中标后解除门控
+
→
+
📦 直送免仓
direct_delivery=true
跳过验收/分拣/加工
强制流转自采
直送拍照确认
+
→
+
🏭 过手vs管库存
供应商备货模式
过手(不管理库存)
管库存(FIFO扣减)
+
+
+ + +
+
28 ⚠️ 已知弱项与半成品
+
+ + + + + + + + +
模块现状弱项/缺口
财务核心概览/成本账/结算单可用AI根因默认接入 LLM(enrichRootCauseWithAi),未配 LLM 才回退规则引擎;仓储成本靠手动录入无自动派生
库存盘点有台账/调整/独立入库/缺口修补无盘点会话/锁定/差异报告/审批流闭环,仅单条调整
市场监控marketPriceAdapter 可插拔外部API外部价需配置MARKET_PRICE_API_URL才生效;未配置时兜底为 supplier_avg → estimated
发票验真API 框架已定义invoice-ocr 已接入 LLM scanInvoice(不再返回 501);进项验真仍非本期范围
称端识别ONNX 本地视觉常驻 + LLM 兜底 + 自动学习新商品需先录样图建 prototype;自动学习需 WEIGH_ONNX_AUTO_LEARN=1 且置信度≥0.85;ONNX 直返不识别质量需补 LLM
短信服务未实现(愿景已移除)系统无短信服务;通知走站内 + SSE(微信订阅暂未接通)
+
+
+ +
+ + + + \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..06d61ae --- /dev/null +++ b/README.md @@ -0,0 +1,456 @@ +# AI 生鲜配送系统 + +面向团膳、食堂、生鲜 B2B 配送场景的一体化供应链管理平台。覆盖 **订单录入(语音/图片/手工)→ 智能分配供应商 → 采购备货 → 验收分拣 → 配送签收 → 财务核算** 全链路,并提供 Web 管理端、移动端 H5 与微信小程序。 + +**生产访问(示例)** + +| 环境 | 地址 | +|------|------| +| 管理端 | https://www.xdjchuanhui.com | +| API 健康检查 | https://www.xdjchuanhui.com/api/health | + +默认超级管理员:本地开发见 `npm run seed:dev-passwords` 生成的账号(**勿在公开文档中写明文密码**)。 + +--- + +## 目录 + +- [功能概览](#功能概览) +- [技术栈](#技术栈) +- [系统架构](#系统架构) +- [项目结构](#项目结构) +- [环境要求](#环境要求) +- [本地开发](#本地开发) +- [环境变量](#环境变量) +- [数据库与迁移](#数据库与迁移) +- [构建与部署](#构建与部署) +- [微信小程序](#微信小程序) +- [AI 能力](#ai-能力) +- [供应商智能分配](#供应商智能分配) +- [代码仓库](#代码仓库) +- [常用脚本](#常用脚本) +- [测试](#测试) +- [安全说明](#安全说明) +- [相关文档](#相关文档) + +--- + +## 功能概览 + +### 订单中心 + +- **订单录入**:语音下单、图片识别下单、手工录入;支持加工方式、客户商品别名 +- **客户下单**:客户侧自助下单入口 +- **订单管理**:订单查询、详情、状态流转、明细编辑 +- **智能分配**:按规则将明细分配给供应商或采购员 +- **竞价管理**:供应商竞价相关流程 + +### 商品与客户 + +- **分类管理**:统一商品分类树(`product_catalog` 优先) +- **商品管理(SKU)**:规格、单位、成本价、图片上传 / AI 生成商品图 +- **客户管理**、**客户别名库**:客户商品名与系统 SKU 映射 + +### 供应商与采购 + +- **供应商管理**:档案、经营品类、等级、登录账号 +- **供应商供货管理**:供货目录、供货价、有货/无货、无货自动流转采购 +- **采购管理**、**供应商备货**、**采购员管理** + +### 仓储与配送 + +- **仓库管理**、**分拣管理** +- **配送管理**、**配送员管理**、**配送进度** +- **库存管理** + +### 质量与售后 + +- **验收管理**、**加工管理** +- **售后管理**、**异常管理** + +### 财务 + +- **财务概览**、**客户/供应商结算**、**发票** +- **成本管理**(Tab 聚合:成本核算、固定成本、成本调整) + +### 系统 + +- **系统配置**、**分公司管理**、**用户/角色/权限**、**操作日志**、**通知** +- **导航菜单配置**(分组、显示名、图标、拖拽排序,按分公司持久化) +- **市场监控**(AI 辅助) + +### 终端 + +| 终端 | 说明 | +|------|------| +| Web 管理端 | React SPA,角色权限控制 | +| 移动端 H5 | `/#/mobile/*`,浏览器 / WebView | +| 微信小程序 | 供应商、采购员、仓管、检验、录单、配送等角色 | + +--- + +## 技术栈 + +| 层级 | 技术 | +|------|------| +| 前端 | React 18、TypeScript、React Router 6、Tailwind CSS、Framer Motion、Webpack 5(图表为页面内自绘,未使用 Recharts) | +| 后端 | Node.js、Express、TypeScript、PostgreSQL、`pg` | +| 认证 | JWT、bcrypt 密码、`profiles` + 角色权限表 | +| 存储 | 本地文件存储(`/api/storage`),SKU 图片目录 | +| AI | 火山引擎 Ark(文本/图片/多模态)、豆包语音识别(可选) | +| 小程序 | 微信原生小程序 + `miniprogram-ci` 上传 | +| 部署 | Docker Compose、Nginx、腾讯云 CVM(前后端分离) | + +前端通过自研 **Local API Client** 对接后端 `/api/data`、`/api/auth` 等接口(兼容原 Supabase 调用风格,数据落在自建 PostgreSQL)。 + +--- + +## 系统架构 + +``` +浏览器 / 小程序 + │ + ▼ + Nginx(HTTPS,静态 + /api 反代) + │ + ▼ + Express API :3001 + │ + ├── PostgreSQL(订单、商品、供应商、权限等) + ├── 本地 uploads(图片、附件) + └── 火山引擎 Ark / 语音识别(可选) +``` + +**生产拓扑(腾讯云,详见 `deploy/PRODUCTION.md`)** + +- **test-h5**:Nginx + 前端静态资源,公网域名 `www.xdjchuanhui.com` +- **test-api**:Node API,内网 `10.206.16.9:3001` +- **数据库**:PostgreSQL 内网 `10.206.16.13` + +前端 `dist/config.js` 使用 `apiBase: '/api'`,由 Nginx 同源反代,无需跨域。 + +--- + +## 项目结构 + +``` +canteen-delivery2/ +├── src/ # Web 前端源码 +│ ├── pages/ # 业务页面(订单、商品、供应商、财务…) +│ ├── components/ # Layout、PermissionGuard、MenuLabel… +│ ├── config/ # menuCatalog、menuIcons +│ ├── hooks/ # useAuth、useMenuLayout、useMenuItemLabel +│ ├── utils/ # menuLayout、分配规则、分类工具 +│ ├── lib/ # API 客户端、认证会话 +│ └── styles/ # 全局样式与多主题 +├── server/ # 后端 API +│ ├── src/ +│ │ ├── routes/ # auth、data、workflow、mobile、functions… +│ │ ├── services/ # 业务服务(订单解析、财务、AI…) +│ │ └── migrate.ts # 数据库迁移入口 +│ └── uploads/ # 运行时上传目录 +├── miniprogram/ # 微信小程序 +├── migrations/ # SQL 迁移文件(76+) +├── docs/ # 项目文档(见 docs/README.md) +├── deploy/ # Nginx 配置、生产说明 +├── scripts/ # 部署、诊断、批量分配等脚本 +├── dist/ # 前端构建产物(gitignore) +├── docker-compose.yml # 本地 PostgreSQL +├── docker-compose.prod.yml # 一体式生产 Docker +└── docker-compose.split.yml# 前后端分离 Docker +``` + +--- + +## 环境要求 + +- **Node.js** 18+(推荐 20+) +- **npm** 9+ +- **PostgreSQL** 16(可用 Docker 拉起) +- **Windows**:PowerShell 5.1+(部署脚本) +- **可选**:Docker Desktop、微信开发者工具、火山引擎 Ark API Key + +--- + +## 本地开发 + +### 1. 克隆仓库 + +```bash +git clone https://git.xdjchuanhui.com/jxc/ai-fresh-delivery.git +cd ai-fresh-delivery +``` + +### 2. 安装依赖 + +```bash +npm install +npm --prefix server install +``` + +### 3. 启动数据库 + +```bash +npm run db:up # docker compose 启动 PostgreSQL +npm run setup # 初始化库与用户 +npm run db:migrate # 执行迁移 +``` + +### 4. 配置后端环境变量 + +```bash +copy server\.env.example server\.env +``` + +编辑 `server/.env`,至少配置 `DATABASE_URL`、`JWT_SECRET`;若使用语音/识图/AI 生图,配置 `ARK_API_KEY` 等(见 [环境变量](#环境变量))。 + +### 5. 启动开发服务 + +```bash +# 同时启动 API + 前端(推荐) +npm run dev:all + +# 或分别启动 +npm run dev:server # API http://localhost:3001 +npm run dev # 前端 http://localhost:3015 +``` + +### 6. 登录 + +浏览器打开 http://localhost:3015 ,使用本地 seed 账号登录(见 `npm run seed:dev-passwords`,勿在文档写明文密码)。 + +--- + +## 环境变量 + +### 后端 `server/.env` + +| 变量 | 说明 | 示例 | +|------|------|------| +| `PORT` | API 端口 | `3001` | +| `DATABASE_URL` | 应用数据库连接 | `postgresql://canteen:canteen123@127.0.0.1:5432/canteen_delivery` | +| `ADMIN_DATABASE_URL` | 建库用超级用户连接 | `postgresql://postgres@127.0.0.1:5432/postgres` | +| `JWT_SECRET` | JWT 签名密钥 | 生产环境务必更换 | +| `STORAGE_DIR` | 上传文件目录 | `./uploads` | +| `ARK_API_KEY` | 火山引擎 Ark API Key | 订单解析、识图、生图 | +| `ARK_MODEL` | 文本/多模态模型 | 可选 | +| `ARK_IMAGE_MODEL` / `ARK_IMAGE_SIZE` | 商品 AI 生图 | 推荐 `1024x1024` | +| `SPEECH_API_KEY` | 豆包语音识别 | 可选;未配置时可尝试 Ark 多模态音频 | + +完整示例见 `server/.env.example`。 + +### 生产 Docker `.env.production` + +参考 `.env.production.example`,配置强密码与 `JWT_SECRET`。 + +### 腾讯云部署 `.env.tencent` + +参考 `.env.tencent.example`,用于 CAM 子账号与自动化脚本(勿提交密钥文件)。 + +--- + +## 数据库与迁移 + +- 迁移文件:`migrations/*.sql` +- 执行迁移: + +```bash +npm run db:migrate +# 或 +npm --prefix server run migrate +``` + +- 本地数据库:`docker-compose.yml` 中默认用户 `canteen` / 密码 `canteen123`,库名 `canteen_delivery` +- 生产迁移问题排查见 `deploy/PRODUCTION.md` + +--- + +## 构建与部署 + +### 本地构建 + +```bash +npm run typecheck # TypeScript 检查 +npm run build:all # 前端 dist + 后端 server/dist +``` + +### Docker 一体部署 + +```bash +copy .env.production.example .env.production +# 编辑 .env.production +npm run deploy +``` + +### 前后端分离(局域网调试) + +```bash +copy .env.split.example .env.split +npm run deploy:split +# 或原生进程:npm run start:split +``` + +### 腾讯云生产(当前主流程) + +在项目根目录 PowerShell 执行: + +```powershell +.\scripts\deploy-prod-all.ps1 +``` + +流程:构建前端 + 后端 → 部署 test-h5 → 部署 test-api → 数据库迁移 → 重启 API。 + +仅更新前端: + +```powershell +.\scripts\deploy-frontend-prod.ps1 +``` + +详细拓扑、SSH 修复、已知问题见 **`deploy/PRODUCTION.md`**。 + +### 批量按分类重分配历史订单(运维) + +```powershell +$env:API_BASE_URL='https://www.xdjchuanhui.com/api' +npx --yes tsx scripts/reprocess-allocation-batch.ts +``` + +--- + +## 微信小程序 + +目录:`miniprogram/` + +```bash +npm run mp:config # 从 example 复制 config.js +npm run mp:upload # 使用 miniprogram-ci 上传(需配置 AppID 与上传密钥) +``` + +- 配置 API:`miniprogram/config.js` → `apiBase` 指向 HTTPS API +- AppID、上传密钥、AppSecret 等 **勿提交 Git**(已在 `.gitignore` 中忽略 `deploy/*AppSecret*`) +- 角色与页面说明见 **`miniprogram/README.md`** + +--- + +## AI 能力 + +| 能力 | 入口 | 依赖 | +|------|------|------| +| 语音下单 | 订单录入 | `SPEECH_API_KEY` 或 Ark 多模态音频 | +| 图片识别下单 | 订单录入 | `ARK_API_KEY` | +| 商品 AI 生图 | 商品管理 | `ARK_API_KEY` + 图片模型 | +| 智能分类规则 | 订单解析 | 数据库 `smart_classification_rules` | +| 市场监控 | AI 菜单 | Ark | + +健康检查:`GET /api/health` 返回 `arkConfigured`、`speechConfigured` 状态。 + +--- + +## 供应商智能分配 + +系统按 **商品分类优先** 将订单明细分配给供应商: + +1. 读取商品分类(SKU 分类、客户映射、智能分类规则) +2. 匹配 **供应商管理 → 经营品类** 绑定关系(支持父级分类链 + 分类名称桥接,如「猪类/鲜肉 → 猪肉供应商」) +3. 匹配成功 → 写入明细供应商、生成备货单 +4. 无绑定供应商 → 流转 **采购员**(不再用 SKU 供货目录兜底覆盖分类策略) + +**新订单**:在「订单录入 / 客户下单」提交成功后自动执行分配。 + +**历史订单**:在「订单管理」点击 **按分类重分配订单**,或运行 `scripts/reprocess-allocation-batch.ts`。 + +**配置建议**:在供应商管理中为各大类(尤其 **蔬菜 VEG001**)绑定经营品类与首选供应商。 + +分配规则可在「订单分配」页调整,并持久化到浏览器 `localStorage`(键:`canteen.allocation.rules`)。 + +--- + +## 代码仓库 + +Gitea 地址:[https://git.xdjchuanhui.com/](https://git.xdjchuanhui.com/) + +| 远程名 | 地址 | +|--------|------| +| `origin` | `https://git.xdjchuanhui.com/jxc/ai-fresh-delivery.git` | + +```bash +git pull origin main +git push origin main +``` + +--- + +## 常用脚本 + +| 脚本 | 说明 | +|------|------| +| `npm run dev:all` | 本地 API + 前端 | +| `npm run build:all` | 全量构建 | +| `scripts/deploy-prod-all.ps1` | 腾讯云生产全量部署 | +| `scripts/deploy-frontend-prod.ps1` | 仅部署前端 | +| `scripts/ssh-prod.ps1` | SSH 登录生产机 | +| `scripts/reprocess-allocation-batch.ts` | 批量按分类重分配 | +| `scripts/diagnose-allocation-prod.mjs` | 生产分配诊断 | +| `npm run test:all` | API + 页面流程冒烟测试 | + +--- + +## 测试 + +```bash +npm run typecheck +npm run test:api # 后端接口冒烟 +npm run test:pages # 页面流程测试 +npm run test:all +``` + +--- + +## 安全说明 + +- **切勿提交**:`.env`、`server/.env`、`SecretKey.csv`、`deploy/id_rsa_tencent`、`deploy/*AppSecret*`、私钥文件 +- 生产环境必须更换 `JWT_SECRET`、数据库密码 +- 管理端生产环境使用 **HTTPS**;小程序 request 域名需在公众平台配置 +- 登录接口已启用速率限制;敏感操作依赖角色权限 + +--- + +## 相关文档 + +| 文档 | 内容 | +|------|------| +| [docs/README.md](docs/README.md) | **文档索引(推荐入口)** | +| [docs/modules/README.md](docs/modules/README.md) | **分模块说明与跨模块关联** | +| [docs/PROJECT_OVERVIEW.md](docs/PROJECT_OVERVIEW.md) | 项目定位、业务全景、角色与终端 | +| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | 技术架构、数据模型、权限与 AI | +| [docs/WEB_MODULES.md](docs/WEB_MODULES.md) | Web 页面路由与权限对照 | +| [docs/API.md](docs/API.md) | 后端 API 概览 | +| [docs/财务结算模块实现对照.md](docs/财务结算模块实现对照.md) | 财务/成本已做未做与按钮审计 | +| [docs/数据隔离与共用关系图.md](docs/数据隔离与共用关系图.md) | 平台与分公司数据边界 | +| [docs/core-business-diagram.mmd](docs/core-business-diagram.mmd) | 核心业务 Mermaid 图 | +| [deploy/PRODUCTION.md](deploy/PRODUCTION.md) | 腾讯云生产拓扑与部署 | +| [miniprogram/README.md](miniprogram/README.md) | 微信小程序开发 | + +--- + +## 默认演示账号(本地/演示) + +本地演示账号由 `npm run seed:dev-passwords` 写入,**密码不在公开 README 中列出**。内部联调请查阅团队私密文档或本地 `.env` / seed 脚本输出。 + +登录时输入**用户名**即可(如 `superadmin`),无需输入 `@meoo.local`。 + +生产环境须强制改密;禁止将生产密钥、`deploy/*密码*`、小程序 AppSecret 提交到仓库。 + +--- + +## 安全审计清单(运维) + +- [ ] 生产默认口令已全部改密 +- [ ] `server/.env` / `.env.tencent` 仅在服务器,未入库 +- [ ] 数据库公网白名单最小化;口令轮换记录在运维侧 +- [ ] 演示账号仅限本地/演示库 +--- + +## 许可证 + +内部项目,版权归项目所有者所有。未经授权请勿对外分发。 diff --git a/android-weigh-terminal/.cursorrules b/android-weigh-terminal/.cursorrules new file mode 100644 index 0000000..7e0ee85 --- /dev/null +++ b/android-weigh-terminal/.cursorrules @@ -0,0 +1,24 @@ +# Cursor 智能称重终端项目规则 + +## 技术栈 +- Android 原生开发(Java) +- minSdk 19, compileSdk 28 +- Gradle 7.5.1 + Android Gradle Plugin 7.0.4 + +## 编码规范 +- 使用 Java 8 语法(Lambda 等) +- 网络请求在主线程回调(已封装在 ApiClient) +- 称重回调在主线程(WeighManager 已处理) + +## 项目结构 +- api/ → HTTP 接口封装 +- model/ → 数据模型 +- weigh/ → 京源衡业称重 SDK 封装 +- print/ → USB 热敏打印机(预留) +- ui/ → Activity 界面 + +## 重要API +- 登录: POST /mobile/login +- 验收任务: GET /mobile/inspection/tasks +- 提交验收: POST /mobile/inspection/complete +- 重量回调: WeighManager.WeighListener.onDataReceived() diff --git a/android-weigh-terminal/.gitignore b/android-weigh-terminal/.gitignore new file mode 100644 index 0000000..ea97185 --- /dev/null +++ b/android-weigh-terminal/.gitignore @@ -0,0 +1,15 @@ +# Local SDK path +local.properties + +# Gradle / build outputs +.gradle/ +**/build/ +dist/ +*.apk +*.ap_ +*.dex + +# IDE +.idea/ +*.iml +.vscode/ diff --git a/android-weigh-terminal/README.md b/android-weigh-terminal/README.md new file mode 100644 index 0000000..2b2f3a8 --- /dev/null +++ b/android-weigh-terminal/README.md @@ -0,0 +1,248 @@ +# 智能称重终端(Android) + +A64 / RK3288 平板上的智能称重 Android 应用,集成京源衡业称重 SDK,对接 AI 生鲜配送系统 API,支持**验收称重**和**分拣称重**。 +**同一 APK** 双机型并存:秤协议相同,差异在平板串口节点(见主界面「设备设置」)。 + +设计说明:`docs/design/20260813-android-weigh-dual-board.md` + +--- + +## 项目结构 + +``` +android-weigh-terminal/ +├── app/ +│ ├── build.gradle # 模块构建配置 +│ ├── libs/ +│ │ └── WeighSdk-release.aar # 京源衡业称重 SDK +│ └── src/main/ +│ ├── AndroidManifest.xml +│ ├── java/com/canteen/weigh/ +│ │ ├── CanteenApp.java # 全局状态 + SharedPreferences +│ │ ├── DeviceProfile.java # A64 / RK3288 / 自定义预设 +│ │ ├── api/ +│ │ ├── model/ +│ │ ├── weigh/ +│ │ │ └── WeighManager.java # 称重管理器(含 testOpen) +│ │ ├── print/ +│ │ │ └── PrintManager.java / CaysnUsbPrinter.java # USB 标签机(AutoReplyPrint) +│ │ └── ui/ +│ │ ├── LoginActivity.java +│ │ ├── MainActivity.java +│ │ ├── DeviceSettingsActivity.java # 机型 / 串口 / 测试连接 +│ │ ├── InspectionWeighActivity.java +│ │ └── PickingWeighActivity.java +│ └── res/layout/ +│ ├── activity_login.xml +│ ├── activity_main.xml +│ ├── activity_device_settings.xml +│ ├── activity_inspection_weigh.xml +│ └── activity_picking_weigh.xml +├── build.gradle +├── settings.gradle +└── gradle.properties +``` + +--- + +## 技术栈 + +| 组件 | 说明 | +|------|------| +| Android SDK | compileSdk 28, minSdk 19(兼容 Android 6.0.1 / 7.1.2) | +| 称重 SDK | 京源衡业 `WeighSdk-release.aar`(串口 9600) | +| HTTP | OkHttp 3.12.13 + Gson 2.8.9 | +| UI | AppCompat v7 + 原生布局(适配横屏触摸屏) | +| 打印 | Caysn AutoReplyPrint USB(`app/libs/autoreplyprint.aar`);现场 KC.EC VID `0x4B43` | + +--- + +## 双机型与外设 + +| 机型 | 秤串口(默认) | 波特率 | +|------|----------------|--------| +| A64 | `/dev/ttyS2` | 9600 | +| RK3288 | `/dev/ttyS1`(已现场确认) | 9600 | +| 自定义 | 手填 / SDK 列表 | 可改 | + +RK3288 外设分工: + +| 外设 | 通路 | +|------|------| +| 电子秤 | 板载 `/dev/ttyS1` | +| 标签打印机 | USB 串口 | +| 摄像头 | USB 串口 | + +首装未保存过配置时,按 `Build.HARDWARE` / `BOARD` 建议机型;用户在「设备设置」保存后以本地为准。 + +--- + +## 系统 API 对接点 + +| 功能 | 接口 | 说明 | +|------|------|------| +| 登录 | `POST /mobile/login` | 账号密码 + role_type | +| 验收任务 | `GET /mobile/inspection/tasks` | 获取待验收列表 | +| 提交验收 | `POST /mobile/inspection/complete` | id + actual_qty + quality_rating | + +无单库存入库请走 Web / 小程序,称端不再提供。 +| 分拣任务 | `GET /mobile/picking/tasks` | 获取待分拣列表(含客户名) | +| 分拣台待拣 | `GET /mobile/picking/weigh-station/pending` | 待拣明细 + 阈值配置 | +| 分拣台配置 | `GET /mobile/picking/weigh-station/config` | 称重阈值 | +| 分拣台识别 | `POST /mobile/picking/weigh-station/recognize` | 手填品名/SKU 或 `image_base64` 多模态(限待拣名单) | +| 分拣台提交 | `POST /mobile/picking/weigh-station/commit` | 实拣+装框+齐套完成 | +| 验收台待验 | `GET /mobile/inspection/weigh-station/pending` | 待验明细 + 阈值配置 | +| 验收台识别 | `POST /mobile/inspection/weigh-station/recognize` | 手填/图片,限待验名单 | +| Web 阈值 | `GET/PUT /api/workflow/picking/weigh-station-tolerance` | 绝对重量/百分比 | + +本期双机型:**无新接口**。 + +--- + +## 构建步骤 + +### 1. 环境准备 + +- Android Studio(推荐 2022.x 以上) +- JDK 1.8 +- Gradle 7.0+ + +### 2. 打开项目 + +```bash +cd android-weigh-terminal +``` + +用 Android Studio 打开 `android-weigh-terminal` 文件夹。 + +### 3. 配置服务器地址 + +默认生产地址可在登录页修改,会写入本地: + +`https://www.xdjchuanhui.com/api` + +### 4. 配置机型 / 串口 + +登录后主界面 → **设备设置**: + +1. 选择机型(A64 / RK3288 / 自定义) +2. 从 SDK 串口列表选择,或手填路径 +3. 波特率默认 9600 +4. 点 **测试连接**(打开后立即关闭) +5. **保存** 后进入验收/分拣 + +### 5. 构建 APK + +```bash +./gradlew assembleDebug +# 或 +./gradlew assembleRelease +``` + +APK:`app/build/outputs/apk/debug/app-debug.apk` + +### 6. 安装(A64 或 RK3288) + +```bash +adb install app/build/outputs/apk/debug/app-debug.apk +``` + +--- + +## 使用流程 + +### 验收台(对齐分拣台) + +设计:`docs/design/20260814-android-inbound-station.md`;下线库存入库见 `docs/design/20260907-weigh-android-drop-stock-in.md` + +1. 验收员登录 → 主界面「验收台」 +2. 刷新待验;**拍照识别**或手选商品 +3. 称重后按订单顺序 / 最小重量误差匹配待验行,可手改;超阈值不可提交 +4. 选合格/不合格 →「确认入库」(无损耗录入;损耗只在加工)→ 打标/可重打 +5. 提交仍走 `POST /mobile/inspection/complete` + +无单库存入库请走 Web / 小程序,称端不再提供。 + +### 分拣台(已对接) + +设计:`docs/design/20260814-android-picking-station.md` + +1. 分拣员登录 → 主界面「分拣台」 +2. 刷新待拣;**拍照识别**或手选商品 +3. 称重后按订单顺序 / 最小重量误差匹配订单行,可手改;超阈值不可提交 +4. 确认装框完成;打印标签(未接厂商 SDK 时可重打) +5. 与小程序并存:已实拣行不会再出现在待拣列表 + +Web「分拣出库」页顶栏可配置称重阈值(百分比或绝对量,与商品单位同口径多为斤)。 + +--- + +## 常见问题 + +### 串口打开失败 + +1. 确认平板有串口权限(需 root 或厂商已授权) +2. 主界面「设备设置」核对机型与路径(A64=`ttyS2`,RK=`ttyS1`) +3. 用「测试连接」验证;列表为空时手填 `/dev/ttyS1` 等 +4. 确认波特率 9600;勿把 USB 打印机/摄像头口配成秤口 + +### 网络请求失败 + +1. 确认平板已连接 WiFi/网线 +2. 检查服务器地址是否正确 +3. 确认系统 API 服务正常运行 + +### 重量不更新 + +1. 确认电子秤已开机 +2. 确认串口连接正确 +3. 查看 Logcat 中的 `WeighManager` 日志 + +--- + +### App 远程升级(COS OTA + Web 调度) + +设计: +- `docs/design/20260829-weigh-app-ota-cos.md`(COS manifest / 下载) +- `docs/design/20260830-weigh-ota-scheduled-silent.md`(Web 策略 + 真静默) + +流程:登录后拉 `GET /api/mobile/weigh/ota-policy` → 直拉 COS `manifest.json` → 有更高 `versionCode` 先下载并校验。 +- **自动更新开启且在日窗 / schedule_at**:`su 0 pm install -r` 真静默(A64 eng 已验证)。 +- **否则**:弹窗「立即安装」(兼容旧交互)。 + +Web:超级管理员 → 系统 → **称端 OTA**(`/system/weigh-ota`)配置开关、日窗、一次性时刻、统一 manifest URL。 + +### 发版上传 + +```bash +# 先打 release APK,再上传(需本机已配 S3/COS 环境变量) +cd server +npx tsx --env-file=.env scripts/publish-weigh-apk.ts --apk=../android-weigh-terminal/app/build/outputs/apk/release/app-release.apk --version-code=9 --version-name=1.1.7 +``` + +脚本会写入 `weigh-apk/releases/{versionCode}/…apk` 与 `weigh-apk/manifest.json`。 +**称端 / Web 策略填写的公网清单地址(生产)**: + +```text +https://www.xdjchuanhui.com/api/storage/weigh-apk/public/manifest.json +``` + +(COS 默认域名禁发 APK,必须走业务域名 `/api/storage` 反代。) + +### 称端配置 + +1. 优先在 Web「称端 OTA」填写上述 Manifest URL;设备设置本地 URL 为兜底。 +2. 设备设置可看 **当前版本**,并可点「检查更新」。 +3. 主界面约每 30 分钟轮询策略(受节流)。 + +每次发版须递增 `app/build.gradle` 的 `versionCode` / `versionName`(当前工程:`9` / `1.1.7`)。 + +--- + +## 扩展建议 + +1. ~~设置界面:机型/串口/波特率~~(已做设备设置) +2. **离线模式**:缓存任务,网络恢复后批量提交 +3. **语音播报**:称重后 TTS 播报重量 +4. **扫码枪**:集成 USB/蓝牙扫码枪,快速定位任务 +5. **打印联动**:验收提交成功后自动打印标签(USB) diff --git a/android-weigh-terminal/app/build.gradle b/android-weigh-terminal/app/build.gradle new file mode 100644 index 0000000..56d3f4b --- /dev/null +++ b/android-weigh-terminal/app/build.gradle @@ -0,0 +1,65 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 28 + buildToolsVersion "30.0.2" + + defaultConfig { + applicationId "com.canteen.weigh" + minSdkVersion 19 + targetSdkVersion 28 + versionCode 52 + versionName "1.1.52" + ndk { + // RK3288 / 多数工控板 + abiFilters "armeabi-v7a", "arm64-v8a", "x86", "x86_64" + } + } + + packagingOptions { + pickFirst 'lib/*/libjnidispatch.so' + pickFirst 'lib/*/libautoreplyprint.so' + pickFirst 'META-INF/DEPENDENCIES' + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + debug { + minifyEnabled false + } + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + encoding 'UTF-8' + } + + // 避免lint检查导致构建失败 + lintOptions { + abortOnError false + checkReleaseBuilds false + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar']) + + // Android Support + implementation 'com.android.support:appcompat-v7:28.0.0' + implementation 'com.android.support:support-compat:28.0.0' + implementation 'com.android.support:recyclerview-v7:28.0.0' + + // HTTP + implementation 'com.squareup.okhttp3:okhttp:3.12.13' + implementation 'com.squareup.okhttp3:logging-interceptor:3.12.13' + + // JSON + implementation 'com.google.code.gson:gson:2.8.9' + + // 标签二维码 + implementation 'com.google.zxing:core:3.3.3' +} diff --git a/android-weigh-terminal/app/libs/WeighSdk-release.aar b/android-weigh-terminal/app/libs/WeighSdk-release.aar new file mode 100644 index 0000000..aaee325 Binary files /dev/null and b/android-weigh-terminal/app/libs/WeighSdk-release.aar differ diff --git a/android-weigh-terminal/app/libs/autoreplyprint.aar b/android-weigh-terminal/app/libs/autoreplyprint.aar new file mode 100644 index 0000000..3413d2d Binary files /dev/null and b/android-weigh-terminal/app/libs/autoreplyprint.aar differ diff --git a/android-weigh-terminal/app/src/main/AndroidManifest.xml b/android-weigh-terminal/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..e8d3064 --- /dev/null +++ b/android-weigh-terminal/app/src/main/AndroidManifest.xml @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/BootReceiver.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/BootReceiver.java new file mode 100644 index 0000000..5df2e3a --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/BootReceiver.java @@ -0,0 +1,33 @@ +package com.canteen.weigh; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.util.Log; + +import com.canteen.weigh.ui.LoginActivity; + +/** + * 开机自启兜底:系统启动完成后拉起登录页。 + * 主路径是本应用注册为 HOME 桌面(禁用系统桌面后开机直进); + * 该 Receiver 用于系统桌面仍被占用时的兜底。 + */ +public class BootReceiver extends BroadcastReceiver { + + private static final String TAG = "BootReceiver"; + + @Override + public void onReceive(Context context, Intent intent) { + if (intent == null || !Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { + return; + } + Log.i(TAG, "BOOT_COMPLETED received, launch LoginActivity"); + try { + Intent launch = new Intent(context, LoginActivity.class); + launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); + context.startActivity(launch); + } catch (Exception e) { + Log.w(TAG, "launch on boot failed", e); + } + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/CanteenApp.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/CanteenApp.java new file mode 100644 index 0000000..895f135 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/CanteenApp.java @@ -0,0 +1,613 @@ +package com.canteen.weigh; + +import android.app.Application; +import android.content.SharedPreferences; +import android.text.TextUtils; + +import com.canteen.weigh.crash.CrashGuard; +import com.canteen.weigh.crash.CrashLocalStore; + +/** + * 全局应用状态(登录态 + 设备串口配置持久化) + */ +public class CanteenApp extends Application { + + /** 供 attachBaseContext 在 Application 未就绪时直读(与 PREFS_NAME 同值) */ + public static final String PREFS_NAME_PUBLIC = "weigh_terminal_prefs"; + public static final String KEY_UI_FONT_SIZE_PUBLIC = "ui_font_size"; + + private static final String PREFS_NAME = PREFS_NAME_PUBLIC; + private static final String KEY_DEVICE_PROFILE = "device_profile"; + private static final String KEY_UI_FONT_SIZE = KEY_UI_FONT_SIZE_PUBLIC; + private static final String KEY_SERIAL_PORT = "serial_port"; + private static final String KEY_BAUD_RATE = "baud_rate"; + private static final String KEY_API_BASE_URL = "api_base_url"; + private static final String KEY_CONFIG_SAVED = "config_saved"; + private static final String KEY_AUTO_SUBMIT = "auto_submit"; + private static final String KEY_RECOGNIZE_INTERVAL_MS = "recognize_interval_ms"; + /** 15 版:把现场已存的 500ms 连拍抬到 ≥3s */ + private static final String KEY_RECOGNIZE_TIMING_V15 = "recognize_timing_v15"; + private static final String KEY_CONTINUOUS_RECOGNIZE = "continuous_recognize_enabled"; + /** 静止画面闸门开关(无界面入口;现场 adb 改本机 prefs 即可关闭) */ + private static final String KEY_SCENE_GATE = "scene_gate_enabled"; + private static final String KEY_AUTH_TOKEN = "auth_token"; + private static final String KEY_AUTH_USER_ID = "auth_user_id"; + private static final String KEY_AUTH_USER_NAME = "auth_user_name"; + private static final String KEY_AUTH_ROLE_TYPE = "auth_role_type"; + private static final String KEY_LAST_STATION = "last_station"; + private static final String KEY_LABEL_PAPER_WIDTH_MM = "label_paper_width_mm"; + private static final String KEY_LABEL_PAPER_HEIGHT_MM = "label_paper_height_mm"; + /** 已把旧默认 50×50 迁到 50×30;为 true 后不再改用户自选的 50×50 */ + private static final String KEY_LABEL_PAPER_SIZE_V2 = "label_paper_size_v2"; + private static final String KEY_SCALE_UNIT = "scale_unit"; + private static final String KEY_DEVICE_ID = "print_device_id"; + private static final String KEY_DEVICE_DISPLAY_NAME = "print_device_display_name"; + private static final String KEY_WEIGHT_NOISE_IGNORE_JIN = "weight_noise_ignore_jin"; + private static final String KEY_CAPTURE_DISTANCE = "camera_capture_distance"; + private static final String KEY_OTA_MANIFEST_URL = "ota_manifest_url"; + private static final String KEY_OTA_LAST_CHECK_AT = "ota_last_check_at_ms"; + + /** OTA 检查最小间隔:6 小时 */ + /** 策略 + OTA 检查节流:30 分钟(自动窗依赖更频轮询) */ + public static final long OTA_CHECK_INTERVAL_MS = 30L * 60L * 1000L; + + public static final int DEFAULT_LABEL_PAPER_WIDTH_MM = 50; + public static final int DEFAULT_LABEL_PAPER_HEIGHT_MM = 30; + + public static final String STATION_INSPECTION = "inspection"; + public static final String STATION_PICKING = "picking"; + + /** 显示字体:大=顶格基准,中/小递减(Configuration.fontScale) */ + public static final String UI_FONT_LARGE = "large"; + public static final String UI_FONT_MEDIUM = "medium"; + public static final String UI_FONT_SMALL = "small"; + public static final float UI_FONT_SCALE_LARGE = 1.0f; + public static final float UI_FONT_SCALE_MEDIUM = 0.85f; + public static final float UI_FONT_SCALE_SMALL = 0.72f; + + public static final long DEFAULT_RECOGNIZE_INTERVAL_MS = 3000L; + public static final long MIN_RECOGNIZE_INTERVAL_MS = 500L; + public static final long MAX_RECOGNIZE_INTERVAL_MS = 10000L; + + /** + * 静止画面闸门默认值:画面指纹 + 重量都没变时跳过 AI 调用。 + * 设计 docs/design/20260924-weigh-scene-gate-and-adaptive-retry.md; + * 无界面入口(定稿决定不加设置项),现场可用 adb 改本机 SharedPreferences。 + */ + public static final boolean DEFAULT_SCENE_GATE_ENABLED = true; + + /** 重量跳变忽略阈值(斤):≤该值不触发换货重识,默认 0.2 */ + public static final double DEFAULT_WEIGHT_NOISE_IGNORE_JIN = 0.2; + public static final double MIN_WEIGHT_NOISE_IGNORE_JIN = 0.05; + public static final double MAX_WEIGHT_NOISE_IGNORE_JIN = 1.0; + + /** 摄像距离(识别中心裁切):远→更近 */ + public static final String CAPTURE_DISTANCE_FAR = "far"; + public static final String CAPTURE_DISTANCE_MID_FAR = "mid_far"; + public static final String CAPTURE_DISTANCE_STANDARD = "standard"; + public static final String CAPTURE_DISTANCE_NEAR = "near"; + public static final String CAPTURE_DISTANCE_CLOSER = "closer"; + + private static CanteenApp instance; + + private String apiBaseUrl = "https://www.xdjchuanhui.com/api"; + private String token; + private String userId; + private String userName; + private String roleType = "inspector"; // inspector | picker + private String lastStation; + + private DeviceProfile deviceProfile = DeviceProfile.A64; + private String serialPort = DeviceProfile.A64.getDefaultSerialPort(); + private int baudRate = DeviceProfile.A64.getDefaultBaudRate(); + /** 已废弃自动提交:始终 false(loadPrefs 忽略本地存储的 true) */ + private boolean autoSubmit = false; + private long recognizeIntervalMs = DEFAULT_RECOGNIZE_INTERVAL_MS; + /** false=仅手动拍照识别(默认);true=按间隔连续自动识别 */ + private boolean continuousRecognizeEnabled = false; + /** 静止画面闸门(画面 + 重量都没变则不调 AI);无界面入口,默认开 */ + private boolean sceneGateEnabled = DEFAULT_SCENE_GATE_ENABLED; + /** 标签纸张尺寸(mm),默认 50×30 */ + private int labelPaperWidthMm = DEFAULT_LABEL_PAPER_WIDTH_MM; + private int labelPaperHeightMm = DEFAULT_LABEL_PAPER_HEIGHT_MM; + /** 秤的实际输出单位("kg"/"jin"/"g"),默认 kg */ + private String scaleUnit = "kg"; + private String printDeviceId; + private String printDeviceDisplayName = ""; + /** 界面字体档位:large / medium / small,默认大(顶格) */ + private String uiFontSize = UI_FONT_LARGE; + /** 重量跳变忽略阈值(斤) */ + private double weightNoiseIgnoreJin = DEFAULT_WEIGHT_NOISE_IGNORE_JIN; + /** 摄像距离档位(识别中心裁切) */ + private String captureDistance = CAPTURE_DISTANCE_STANDARD; + /** COS manifest 公网 URL,如 https://xxx.cos.../weigh-apk/manifest.json */ + private String otaManifestUrl = ""; + + @Override + public void onCreate() { + super.onCreate(); + instance = this; + CrashGuard.install(this); + loadPrefs(); + try { + CrashLocalStore.tryImportLatestTombstone(this); + } catch (Throwable ignored) { + // 无 tombstone 读权限时静默跳过 + } + } + + public static CanteenApp get() { + return instance; + } + + private SharedPreferences prefs() { + return getSharedPreferences(PREFS_NAME, MODE_PRIVATE); + } + + private void loadPrefs() { + SharedPreferences sp = prefs(); + String savedUrl = sp.getString(KEY_API_BASE_URL, null); + if (savedUrl != null && !savedUrl.isEmpty()) { + apiBaseUrl = savedUrl; + } + + autoSubmit = false; + recognizeIntervalMs = clampRecognizeIntervalMs( + sp.getLong(KEY_RECOGNIZE_INTERVAL_MS, DEFAULT_RECOGNIZE_INTERVAL_MS)); + if (!sp.getBoolean(KEY_RECOGNIZE_TIMING_V15, false)) { + if (recognizeIntervalMs < DEFAULT_RECOGNIZE_INTERVAL_MS) { + recognizeIntervalMs = DEFAULT_RECOGNIZE_INTERVAL_MS; + } + sp.edit() + .putBoolean(KEY_RECOGNIZE_TIMING_V15, true) + .putLong(KEY_RECOGNIZE_INTERVAL_MS, recognizeIntervalMs) + .apply(); + } + continuousRecognizeEnabled = sp.getBoolean(KEY_CONTINUOUS_RECOGNIZE, false); + sceneGateEnabled = sp.getBoolean(KEY_SCENE_GATE, DEFAULT_SCENE_GATE_ENABLED); + + token = sp.getString(KEY_AUTH_TOKEN, null); + userId = sp.getString(KEY_AUTH_USER_ID, null); + userName = sp.getString(KEY_AUTH_USER_NAME, null); + String savedRole = sp.getString(KEY_AUTH_ROLE_TYPE, null); + if (!TextUtils.isEmpty(savedRole)) { + roleType = savedRole; + } + lastStation = normalizeStation(sp.getString(KEY_LAST_STATION, null)); + labelPaperWidthMm = clampPaperMm( + sp.getInt(KEY_LABEL_PAPER_WIDTH_MM, DEFAULT_LABEL_PAPER_WIDTH_MM)); + labelPaperHeightMm = clampPaperMm( + sp.getInt(KEY_LABEL_PAPER_HEIGHT_MM, DEFAULT_LABEL_PAPER_HEIGHT_MM)); + // 旧默认 50×50 一次性迁到现场 50×30;用户之后自选 50×50 不再改 + if (!sp.getBoolean(KEY_LABEL_PAPER_SIZE_V2, false)) { + SharedPreferences.Editor ed = sp.edit().putBoolean(KEY_LABEL_PAPER_SIZE_V2, true); + if (labelPaperWidthMm == 50 && labelPaperHeightMm == 50) { + labelPaperHeightMm = DEFAULT_LABEL_PAPER_HEIGHT_MM; + ed.putInt(KEY_LABEL_PAPER_HEIGHT_MM, labelPaperHeightMm); + } + ed.apply(); + } + scaleUnit = normalizeScaleUnit(sp.getString(KEY_SCALE_UNIT, "kg")); + ensurePrintDeviceId(sp); + uiFontSize = normalizeUiFontSize(sp.getString(KEY_UI_FONT_SIZE, UI_FONT_LARGE)); + weightNoiseIgnoreJin = clampWeightNoiseIgnoreJin( + (double) sp.getFloat(KEY_WEIGHT_NOISE_IGNORE_JIN, (float) DEFAULT_WEIGHT_NOISE_IGNORE_JIN)); + captureDistance = normalizeCaptureDistance( + sp.getString(KEY_CAPTURE_DISTANCE, CAPTURE_DISTANCE_STANDARD)); + String otaUrl = sp.getString(KEY_OTA_MANIFEST_URL, null); + otaManifestUrl = otaUrl != null ? otaUrl.trim() : ""; + + if (sp.getBoolean(KEY_CONFIG_SAVED, false)) { + deviceProfile = DeviceProfile.fromId(sp.getString(KEY_DEVICE_PROFILE, DeviceProfile.A64.getId())); + serialPort = sp.getString(KEY_SERIAL_PORT, deviceProfile.getDefaultSerialPort()); + baudRate = sp.getInt(KEY_BAUD_RATE, deviceProfile.getDefaultBaudRate()); + if (serialPort == null || serialPort.isEmpty()) { + serialPort = deviceProfile.getDefaultSerialPort(); + } + return; + } + + // 首装:按硬件建议机型与默认串口 + deviceProfile = DeviceProfile.suggestFromBuild(); + serialPort = deviceProfile.getDefaultSerialPort(); + baudRate = deviceProfile.getDefaultBaudRate(); + } + + public static long clampRecognizeIntervalMs(long ms) { + if (ms < MIN_RECOGNIZE_INTERVAL_MS) { + return MIN_RECOGNIZE_INTERVAL_MS; + } + if (ms > MAX_RECOGNIZE_INTERVAL_MS) { + return MAX_RECOGNIZE_INTERVAL_MS; + } + return ms; + } + + /** 标签纸单边合理范围 20~150mm */ + public static int clampPaperMm(int mm) { + if (mm < 20) return 20; + if (mm > 150) return 150; + return mm; + } + + public int getLabelPaperWidthMm() { + return labelPaperWidthMm; + } + + public int getLabelPaperHeightMm() { + return labelPaperHeightMm; + } + + /** 持久化标签纸张尺寸(mm) */ + public void saveLabelPaperSize(int widthMm, int heightMm) { + this.labelPaperWidthMm = clampPaperMm(widthMm); + this.labelPaperHeightMm = clampPaperMm(heightMm); + prefs().edit() + .putInt(KEY_LABEL_PAPER_WIDTH_MM, this.labelPaperWidthMm) + .putInt(KEY_LABEL_PAPER_HEIGHT_MM, this.labelPaperHeightMm) + .apply(); + } + + private static String normalizeStation(String station) { + if (STATION_INSPECTION.equals(station) + || STATION_PICKING.equals(station)) { + return station; + } + return null; + } + + /** + * 持久化设备机型 / 串口 / 波特率(设置页保存时调用) + */ + public void saveDeviceConfig(DeviceProfile profile, String port, int baud) { + if (profile == null) { + profile = DeviceProfile.CUSTOM; + } + if (port == null || port.trim().isEmpty()) { + port = profile.getDefaultSerialPort(); + } else { + port = port.trim(); + } + if (baud <= 0) { + baud = profile.getDefaultBaudRate(); + } + this.deviceProfile = profile; + this.serialPort = port; + this.baudRate = baud; + prefs().edit() + .putBoolean(KEY_CONFIG_SAVED, true) + .putString(KEY_DEVICE_PROFILE, profile.getId()) + .putString(KEY_SERIAL_PORT, port) + .putInt(KEY_BAUD_RATE, baud) + .apply(); + } + + public String getApiBaseUrl() { + return apiBaseUrl; + } + + public void setApiBaseUrl(String apiBaseUrl) { + if (apiBaseUrl == null || apiBaseUrl.trim().isEmpty()) { + return; + } + this.apiBaseUrl = apiBaseUrl.trim(); + prefs().edit().putString(KEY_API_BASE_URL, this.apiBaseUrl).apply(); + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getRoleType() { + return roleType; + } + + public void setRoleType(String roleType) { + this.roleType = roleType; + } + + /** 登录成功:内存 + prefs */ + public void saveSession(String token, String userId, String userName, String roleType) { + this.token = token; + this.userId = userId; + this.userName = userName; + if (!TextUtils.isEmpty(roleType)) { + this.roleType = roleType; + } + prefs().edit() + .putString(KEY_AUTH_TOKEN, this.token) + .putString(KEY_AUTH_USER_ID, this.userId) + .putString(KEY_AUTH_USER_NAME, this.userName) + .putString(KEY_AUTH_ROLE_TYPE, this.roleType) + .apply(); + } + + public boolean isLoggedIn() { + return token != null && !token.isEmpty(); + } + + /** 退出登录:清会话与上次工作台记忆 */ + public void logout() { + token = null; + userId = null; + userName = null; + lastStation = null; + prefs().edit() + .remove(KEY_AUTH_TOKEN) + .remove(KEY_AUTH_USER_ID) + .remove(KEY_AUTH_USER_NAME) + .remove(KEY_AUTH_ROLE_TYPE) + .remove(KEY_LAST_STATION) + .apply(); + } + + public String getLastStation() { + return lastStation; + } + + public void saveLastStation(String station) { + String normalized = normalizeStation(station); + if (normalized == null) { + return; + } + this.lastStation = normalized; + prefs().edit().putString(KEY_LAST_STATION, normalized).apply(); + } + + /** 返回主菜单选台时清除「开机直达」记忆,登录态保留 */ + public void clearLastStation() { + this.lastStation = null; + prefs().edit().remove(KEY_LAST_STATION).apply(); + } + + private void ensurePrintDeviceId(SharedPreferences sp) { + String saved = sp.getString(KEY_DEVICE_ID, null); + if (saved != null && saved.length() >= 8) { + printDeviceId = saved; + } else { + printDeviceId = java.util.UUID.randomUUID().toString(); + sp.edit().putString(KEY_DEVICE_ID, printDeviceId).apply(); + } + String name = sp.getString(KEY_DEVICE_DISPLAY_NAME, null); + printDeviceDisplayName = name != null ? name : ""; + } + + public String getPrintDeviceId() { + if (printDeviceId == null || printDeviceId.length() < 8) { + ensurePrintDeviceId(prefs()); + } + return printDeviceId; + } + + public String getPrintDeviceDisplayName() { + return printDeviceDisplayName != null ? printDeviceDisplayName : ""; + } + + public void savePrintDeviceDisplayName(String name) { + this.printDeviceDisplayName = name != null ? name.trim() : ""; + if (this.printDeviceDisplayName.length() > 100) { + this.printDeviceDisplayName = this.printDeviceDisplayName.substring(0, 100); + } + prefs().edit().putString(KEY_DEVICE_DISPLAY_NAME, this.printDeviceDisplayName).apply(); + } + + public DeviceProfile getDeviceProfile() { + return deviceProfile; + } + + public String getSerialPort() { + return serialPort; + } + + public void setSerialPort(String serialPort) { + this.serialPort = serialPort; + } + + public int getBaudRate() { + return baudRate; + } + + public void setBaudRate(int baudRate) { + this.baudRate = baudRate; + } + + /** 状态文案用:机型 + 端口 */ + public String describeSerialConfig() { + return deviceProfile.getDisplayName() + " " + serialPort + " @" + baudRate; + } + + /** 秤输出单位("kg"/"jin"/"g"),默认 kg */ + public String getScaleUnit() { + return scaleUnit != null ? scaleUnit : "kg"; + } + + /** 持久化秤输出单位 */ + public void saveScaleUnit(String unit) { + this.scaleUnit = normalizeScaleUnit(unit); + prefs().edit().putString(KEY_SCALE_UNIT, this.scaleUnit).apply(); + } + + private static String normalizeScaleUnit(String unit) { + if (unit == null) return "kg"; + String u = unit.trim().toLowerCase(); + if (u.equals("jin") || u.equals("斤") || u.equals("市斤")) return "jin"; + if (u.equals("g") || u.equals("克")) return "g"; + if (u.equals("kg") || u.equals("公斤") || u.equals("千克")) return "kg"; + return "kg"; + } + + public boolean isAutoSubmitEnabled() { + return autoSubmit; + } + + public void saveAutoSubmitEnabled(boolean enabled) { + this.autoSubmit = false; + prefs().edit().putBoolean(KEY_AUTO_SUBMIT, false).apply(); + } + + public boolean isContinuousRecognizeEnabled() { + return continuousRecognizeEnabled; + } + + public void saveContinuousRecognizeEnabled(boolean enabled) { + this.continuousRecognizeEnabled = enabled; + prefs().edit().putBoolean(KEY_CONTINUOUS_RECOGNIZE, enabled).apply(); + } + + public long getRecognizeIntervalMs() { + return recognizeIntervalMs; + } + + /** + * 静止画面闸门:画面指纹 + 重量都没变时跳过 AI 调用。 + * 设计 docs/design/20260924-weigh-scene-gate-and-adaptive-retry.md。无界面入口,默认开。 + */ + public boolean isSceneGateEnabled() { + return sceneGateEnabled; + } + + /** 仅供调试/回滚:无设置界面,现场用 adb 改本机 SharedPreferences 生效。 */ + public void setSceneGateEnabled(boolean enabled) { + this.sceneGateEnabled = enabled; + prefs().edit().putBoolean(KEY_SCENE_GATE, enabled).apply(); + } + + /** + * 保存称重台识别/提交偏好(与串口配置可分开保存)。 + */ + public void saveWeighStationPrefs(boolean autoSubmitEnabled, long intervalMs) { + this.autoSubmit = false; + this.recognizeIntervalMs = clampRecognizeIntervalMs(intervalMs); + prefs().edit() + .putBoolean(KEY_AUTO_SUBMIT, false) + .putLong(KEY_RECOGNIZE_INTERVAL_MS, this.recognizeIntervalMs) + .apply(); + } + + public String getUiFontSize() { + return uiFontSize; + } + + public float getUiFontScale() { + return scaleForUiFontSize(uiFontSize); + } + + public void saveUiFontSize(String level) { + this.uiFontSize = normalizeUiFontSize(level); + prefs().edit().putString(KEY_UI_FONT_SIZE, this.uiFontSize).apply(); + } + + public double getWeightNoiseIgnoreJin() { + return weightNoiseIgnoreJin; + } + + /** 内部 kg 阈值(1 斤 = 0.5 kg) */ + public double getWeightNoiseIgnoreKg() { + return weightNoiseIgnoreJin / 2.0; + } + + public void saveWeightNoiseIgnoreJin(double jin) { + this.weightNoiseIgnoreJin = clampWeightNoiseIgnoreJin(jin); + prefs().edit() + .putFloat(KEY_WEIGHT_NOISE_IGNORE_JIN, (float) this.weightNoiseIgnoreJin) + .apply(); + } + + public String getCaptureDistance() { + return captureDistance; + } + + /** + * 识别中心裁切比例:1=不裁;越小货物越大(数字变焦)。 + * 默认 0.90,与历史硬编码一致。 + */ + public float getCaptureCropRatio() { + if (CAPTURE_DISTANCE_FAR.equals(captureDistance)) return 1.00f; + if (CAPTURE_DISTANCE_MID_FAR.equals(captureDistance)) return 0.95f; + if (CAPTURE_DISTANCE_NEAR.equals(captureDistance)) return 0.75f; + if (CAPTURE_DISTANCE_CLOSER.equals(captureDistance)) return 0.60f; + return 0.90f; + } + + public void saveCaptureDistance(String distance) { + this.captureDistance = normalizeCaptureDistance(distance); + prefs().edit().putString(KEY_CAPTURE_DISTANCE, this.captureDistance).apply(); + } + + public static String normalizeCaptureDistance(String raw) { + if (CAPTURE_DISTANCE_FAR.equals(raw) + || CAPTURE_DISTANCE_MID_FAR.equals(raw) + || CAPTURE_DISTANCE_STANDARD.equals(raw) + || CAPTURE_DISTANCE_NEAR.equals(raw) + || CAPTURE_DISTANCE_CLOSER.equals(raw)) { + return raw; + } + return CAPTURE_DISTANCE_STANDARD; + } + + public String getOtaManifestUrl() { + return otaManifestUrl != null ? otaManifestUrl : ""; + } + + public void saveOtaManifestUrl(String url) { + this.otaManifestUrl = url != null ? url.trim() : ""; + prefs().edit().putString(KEY_OTA_MANIFEST_URL, this.otaManifestUrl).apply(); + } + + public boolean shouldCheckOtaNow() { + long last = prefs().getLong(KEY_OTA_LAST_CHECK_AT, 0L); + return System.currentTimeMillis() - last >= OTA_CHECK_INTERVAL_MS; + } + + public void markOtaCheckedNow() { + prefs().edit().putLong(KEY_OTA_LAST_CHECK_AT, System.currentTimeMillis()).apply(); + } + + public static double clampWeightNoiseIgnoreJin(double jin) { + if (Double.isNaN(jin) || jin < MIN_WEIGHT_NOISE_IGNORE_JIN) { + return DEFAULT_WEIGHT_NOISE_IGNORE_JIN; + } + if (jin > MAX_WEIGHT_NOISE_IGNORE_JIN) { + return MAX_WEIGHT_NOISE_IGNORE_JIN; + } + return jin; + } + + public static float scaleForUiFontSize(String level) { + String n = normalizeUiFontSizeStatic(level); + if (UI_FONT_SMALL.equals(n)) return UI_FONT_SCALE_SMALL; + if (UI_FONT_MEDIUM.equals(n)) return UI_FONT_SCALE_MEDIUM; + return UI_FONT_SCALE_LARGE; + } + + private String normalizeUiFontSize(String level) { + return normalizeUiFontSizeStatic(level); + } + + private static String normalizeUiFontSizeStatic(String level) { + if (UI_FONT_SMALL.equals(level) || UI_FONT_MEDIUM.equals(level) || UI_FONT_LARGE.equals(level)) { + return level; + } + return UI_FONT_LARGE; + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/DeviceProfile.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/DeviceProfile.java new file mode 100644 index 0000000..9331bcf --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/DeviceProfile.java @@ -0,0 +1,70 @@ +package com.canteen.weigh; + +import android.os.Build; + +/** + * 称重平板机型预设(同一京源 SDK,差异在串口节点) + */ +public enum DeviceProfile { + + A64("a64", "A64", "/dev/ttyS2", 9600), + RK3288("rk3288", "RK3288", "/dev/ttyS1", 9600), + CUSTOM("custom", "自定义", "/dev/ttyS2", 9600); + + private final String id; + private final String displayName; + private final String defaultSerialPort; + private final int defaultBaudRate; + + DeviceProfile(String id, String displayName, String defaultSerialPort, int defaultBaudRate) { + this.id = id; + this.displayName = displayName; + this.defaultSerialPort = defaultSerialPort; + this.defaultBaudRate = defaultBaudRate; + } + + public String getId() { + return id; + } + + public String getDisplayName() { + return displayName; + } + + public String getDefaultSerialPort() { + return defaultSerialPort; + } + + public int getDefaultBaudRate() { + return defaultBaudRate; + } + + public static DeviceProfile fromId(String id) { + if (id == null) { + return A64; + } + for (DeviceProfile p : values()) { + if (p.id.equalsIgnoreCase(id)) { + return p; + } + } + return A64; + } + + /** + * 按 Build 信息建议机型(仅首装无本地配置时使用) + */ + public static DeviceProfile suggestFromBuild() { + String hw = ((Build.HARDWARE != null ? Build.HARDWARE : "") + + " " + (Build.BOARD != null ? Build.BOARD : "") + + " " + (Build.MODEL != null ? Build.MODEL : "") + + " " + (Build.PRODUCT != null ? Build.PRODUCT : "")).toLowerCase(); + if (hw.contains("rk3288")) { + return RK3288; + } + if (hw.contains("a64") || hw.contains("sun50i")) { + return A64; + } + return A64; + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/api/ApiClient.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/api/ApiClient.java new file mode 100644 index 0000000..6a1b423 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/api/ApiClient.java @@ -0,0 +1,189 @@ +package com.canteen.weigh.api; + +import android.os.Handler; +import android.os.Looper; + +import com.canteen.weigh.CanteenApp; + +import org.json.JSONObject; + +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.logging.HttpLoggingInterceptor; + +/** + * HTTP 客户端封装 + */ +public class ApiClient { + + public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); + + private static ApiClient instance; + private final OkHttpClient client; + private final OkHttpClient longClient; + private final Handler mainHandler; + + private ApiClient() { + HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); + logging.setLevel(HttpLoggingInterceptor.Level.BODY); + + client = new OkHttpClient.Builder() + .connectTimeout(15, TimeUnit.SECONDS) + .readTimeout(20, TimeUnit.SECONDS) + .writeTimeout(20, TimeUnit.SECONDS) + .addInterceptor(logging) + .build(); + + // 识别图上传:更长超时,且不打 BODY(避免 base64 刷爆日志) + HttpLoggingInterceptor longLogging = new HttpLoggingInterceptor(); + longLogging.setLevel(HttpLoggingInterceptor.Level.BASIC); + longClient = new OkHttpClient.Builder() + .connectTimeout(20, TimeUnit.SECONDS) + .readTimeout(90, TimeUnit.SECONDS) + .writeTimeout(90, TimeUnit.SECONDS) + .addInterceptor(longLogging) + .build(); + + mainHandler = new Handler(Looper.getMainLooper()); + } + + public static synchronized ApiClient get() { + if (instance == null) { + instance = new ApiClient(); + } + return instance; + } + + /** 短超时客户端(API / manifest) */ + public OkHttpClient httpClient() { + return client; + } + + /** 长超时客户端(APK 下载) */ + public OkHttpClient downloadClient() { + return longClient; + } + + /** + * 构建基础请求 + */ + private Request.Builder baseBuilder(String path) { + String baseUrl = CanteenApp.get().getApiBaseUrl(); + if (baseUrl.endsWith("/")) { + baseUrl = baseUrl.substring(0, baseUrl.length() - 1); + } + if (!path.startsWith("/")) { + path = "/" + path; + } + + Request.Builder builder = new Request.Builder() + .url(baseUrl + path); + + String token = CanteenApp.get().getToken(); + if (token != null && !token.isEmpty()) { + builder.header("Authorization", "Bearer " + token); + } + return builder; + } + + /** + * GET 请求 + */ + public void get(String path, ApiCallback callback) { + Request request = baseBuilder(path) + .get() + .build(); + enqueue(client, request, callback); + } + + /** + * POST JSON 请求 + */ + public void post(String path, JSONObject body, ApiCallback callback) { + RequestBody requestBody = RequestBody.create(JSON, body != null ? body.toString() : "{}"); + Request request = baseBuilder(path) + .post(requestBody) + .build(); + enqueue(client, request, callback); + } + + /** + * POST JSON(长超时,用于图片识别等) + * 返回 Call 以便调用方在需要时 cancel(避免重试时旧请求堆积) + */ + public Call postLong(String path, JSONObject body, ApiCallback callback) { + RequestBody requestBody = RequestBody.create(JSON, body != null ? body.toString() : "{}"); + Request request = baseBuilder(path) + .post(requestBody) + .build(); + return enqueue(longClient, request, callback); + } + + /** + * POST 空请求 + */ + public void post(String path, ApiCallback callback) { + post(path, new JSONObject(), callback); + } + + private Call enqueue(OkHttpClient http, Request request, final ApiCallback callback) { + Call call = http.newCall(request); + call.enqueue(new Callback() { + @Override + public void onFailure(Call call, final IOException e) { + mainHandler.post(new Runnable() { + @Override + public void run() { + callback.onError(-1, "网络请求失败: " + e.getMessage()); + } + }); + } + + @Override + public void onResponse(Call call, final Response response) throws IOException { + final String bodyStr = response.body() != null ? response.body().string() : ""; + mainHandler.post(new Runnable() { + @Override + public void run() { + if (response.isSuccessful()) { + callback.onSuccess(response.code(), bodyStr); + } else { + callback.onError(response.code(), parseError(bodyStr)); + } + } + }); + } + }); + return call; + } + + private String parseError(String body) { + try { + JSONObject obj = new JSONObject(body); + if (obj.has("error_description")) { + return obj.getString("error_description"); + } + if (obj.has("error")) { + return obj.getString("error"); + } + } catch (Exception ignored) { + } + return body; + } + + /** + * 回调接口 + */ + public interface ApiCallback { + void onSuccess(int code, String body); + void onError(int code, String message); + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/api/AuthApi.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/api/AuthApi.java new file mode 100644 index 0000000..8ac2f50 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/api/AuthApi.java @@ -0,0 +1,52 @@ +package com.canteen.weigh.api; + +import org.json.JSONException; +import org.json.JSONObject; + +/** + * 认证相关 API + */ +public class AuthApi { + + /** + * 账号密码登录 + * + * @param username 用户名 + * @param password 密码 + * @param roleType 可选;null/空则不传,由服务端按账号解析角色 + * @param callback 回调 + */ + public static void login(String username, String password, String roleType, final ApiClient.ApiCallback callback) { + try { + JSONObject body = new JSONObject(); + body.put("username", username); + body.put("password", password); + if (roleType != null && !roleType.trim().isEmpty()) { + body.put("role_type", roleType.trim()); + } + ApiClient.get().post("/mobile/login", body, callback); + } catch (JSONException e) { + callback.onError(-1, "参数构造失败"); + } + } + + /** + * 获取当前用户信息 + */ + public static void me(ApiClient.ApiCallback callback) { + ApiClient.get().get("/mobile/me", callback); + } + + /** + * 切换角色 + */ + public static void switchRole(String roleType, ApiClient.ApiCallback callback) { + try { + JSONObject body = new JSONObject(); + body.put("role_type", roleType); + ApiClient.get().post("/mobile/switch-role", body, callback); + } catch (JSONException e) { + callback.onError(-1, "参数构造失败"); + } + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/api/InspectionApi.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/api/InspectionApi.java new file mode 100644 index 0000000..9c75666 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/api/InspectionApi.java @@ -0,0 +1,166 @@ +package com.canteen.weigh.api; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; + +import okhttp3.Call; + +/** + * 验收(验收台)相关 API + */ +public class InspectionApi { + + /** + * 获取待验收任务列表(兼容旧路径) + */ + public static void getTasks(ApiClient.ApiCallback callback) { + ApiClient.get().get("/mobile/inspection/tasks", callback); + } + + /** 验收台:默认只回 meta(件数)+ config;全量请用 mode=full(调试) */ + public static void getWeighStationPending(ApiClient.ApiCallback callback) { + ApiClient.get().get("/mobile/inspection/weigh-station/pending", callback); + } + + /** 待验商品模糊搜索(服务端,limit 默认 40) */ + public static void searchPending(String query, int limit, ApiClient.ApiCallback callback) { + String q = query == null ? "" : query.trim(); + int lim = limit > 0 ? limit : 40; + ApiClient.get().get("/mobile/inspection/weigh-station/search?q=" + enc(q) + "&limit=" + lim, callback); + } + + /** 按 SKU/品名拉取该品全部待验明细 */ + public static void getProduct(String skuCode, String itemName, ApiClient.ApiCallback callback) { + StringBuilder path = new StringBuilder("/mobile/inspection/weigh-station/product?"); + boolean has = false; + if (skuCode != null && !skuCode.trim().isEmpty()) { + path.append("sku=").append(enc(skuCode.trim())); + has = true; + } + if (itemName != null && !itemName.trim().isEmpty()) { + if (has) path.append('&'); + path.append("name=").append(enc(itemName.trim())); + has = true; + } + if (!has) { + callback.onError(-1, "缺少 sku 或 name"); + return; + } + ApiClient.get().get(path.toString(), callback); + } + + private static String enc(String raw) { + try { + return URLEncoder.encode(raw, "UTF-8"); + } catch (UnsupportedEncodingException e) { + return raw; + } + } + + /** 验收台:识别(手填或图片) */ + public static Call recognize(String itemName, String skuCode, String imageBase64, + ApiClient.ApiCallback callback) { + try { + JSONObject body = new JSONObject(); + if (itemName != null && !itemName.isEmpty()) { + body.put("item_name", itemName); + } + if (skuCode != null && !skuCode.isEmpty()) { + body.put("sku_code", skuCode); + } + if (imageBase64 != null && !imageBase64.isEmpty()) { + body.put("image_base64", imageBase64); + } + return ApiClient.get().postLong("/mobile/inspection/weigh-station/recognize", body, callback); + } catch (JSONException e) { + callback.onError(-1, "参数构造失败"); + return null; + } + } + + /** 验收台:对照片判断合格/不合格 */ + public static void assessQuality(String imageBase64, String itemName, + ApiClient.ApiCallback callback) { + try { + JSONObject body = new JSONObject(); + if (imageBase64 != null && !imageBase64.isEmpty()) { + body.put("image_base64", imageBase64); + } + if (itemName != null && !itemName.isEmpty()) { + body.put("item_name", itemName); + } + ApiClient.get().postLong("/mobile/inspection/weigh-station/assess-quality", body, callback); + } catch (JSONException e) { + callback.onError(-1, "参数构造失败"); + } + } + + /** + * 提交验收结果 + * actualWeight:可选,秤读数换算后的斤;>0 才发送。非斤计数单位时另存参考,actualQty 存件数。 + */ + public static void complete(String id, double actualQty, double actualWeight, String qualityRating, + ApiClient.ApiCallback callback) { + complete(id, actualQty, actualWeight, qualityRating, false, callback); + } + + public static void complete(String id, double actualQty, double actualWeight, String qualityRating, + boolean rejectFulfillment, ApiClient.ApiCallback callback) { + try { + JSONObject body = new JSONObject(); + body.put("id", id); + body.put("actual_qty", actualQty); + if (actualWeight > 0) { + body.put("actual_weight", actualWeight); + } + body.put("quality_rating", qualityRating != null ? qualityRating : "pass"); + body.put("loss_qty", 0); + if (rejectFulfillment) { + body.put("reject_fulfillment", true); + } + ApiClient.get().postLong("/mobile/inspection/complete", body, callback); + } catch (JSONException e) { + callback.onError(-1, "参数构造失败"); + } + } + + /** + * 同商品多待验合并入库:一次提交总重量;forceComplete=true 为偏差入库(短收也结案)。 + * 退供仍走 {@link #complete}。走长超时(合并/偏差多行串行写库,设计 20260910-weigh-submit-long-timeout)。 + */ + public static void completeMerge(String id, double actualQty, double actualWeight, String qualityRating, + boolean forceComplete, ApiClient.ApiCallback callback) { + try { + JSONObject body = new JSONObject(); + body.put("id", id); + body.put("actual_qty", actualQty); + if (actualWeight > 0) { + body.put("actual_weight", actualWeight); + } + body.put("quality_rating", qualityRating != null ? qualityRating : "pass"); + body.put("loss_qty", 0); + if (forceComplete) { + body.put("force_complete", true); + } + ApiClient.get().postLong("/mobile/inspection/complete-merge", body, callback); + } catch (JSONException e) { + callback.onError(-1, "参数构造失败"); + } + } + + /** 上传验收照片(写入 inspections.inspection_photos) */ + public static void uploadPhoto(String id, String imageBase64, ApiClient.ApiCallback callback) { + try { + JSONObject body = new JSONObject(); + body.put("id", id); + body.put("content", imageBase64); + body.put("ext", "jpg"); + ApiClient.get().postLong("/mobile/inspection/photo", body, callback); + } catch (JSONException e) { + callback.onError(-1, "参数构造失败"); + } + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/api/PrintJobApi.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/api/PrintJobApi.java new file mode 100644 index 0000000..580e84e --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/api/PrintJobApi.java @@ -0,0 +1,37 @@ +package com.canteen.weigh.api; + +import android.net.Uri; + +import com.canteen.weigh.CanteenApp; + +import org.json.JSONObject; + +/** + * Web 远程打印:轮询 pending + ack。 + */ +public class PrintJobApi { + + public static void fetchPending(ApiClient.ApiCallback callback) { + CanteenApp app = CanteenApp.get(); + String deviceId = app.getPrintDeviceId(); + String name = app.getPrintDeviceDisplayName(); + String path = "/mobile/print-jobs/pending?device_id=" + Uri.encode(deviceId); + if (name != null && !name.isEmpty()) { + path += "&display_name=" + Uri.encode(name); + } + ApiClient.get().get(path, callback); + } + + public static void ack(String jobId, String status, String error, ApiClient.ApiCallback callback) { + JSONObject body = new JSONObject(); + try { + body.put("device_id", CanteenApp.get().getPrintDeviceId()); + body.put("status", status); + if (error != null && !error.isEmpty()) { + body.put("error", error); + } + } catch (Exception ignored) { + } + ApiClient.get().post("/mobile/print-jobs/" + jobId + "/ack", body, callback); + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/api/WeighStationApi.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/api/WeighStationApi.java new file mode 100644 index 0000000..723ba54 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/api/WeighStationApi.java @@ -0,0 +1,103 @@ +package com.canteen.weigh.api; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; + +import okhttp3.Call; + +/** + * 分拣台 API(识别 / 配置 / 聚合提交) + */ +public class WeighStationApi { + + public static void getConfig(ApiClient.ApiCallback callback) { + ApiClient.get().get("/mobile/picking/weigh-station/config", callback); + } + + /** 默认只回 meta + config;全量调试用 ?mode=full */ + public static void getPending(ApiClient.ApiCallback callback) { + ApiClient.get().get("/mobile/picking/weigh-station/pending", callback); + } + + public static void searchPending(String query, int limit, ApiClient.ApiCallback callback) { + String q = query == null ? "" : query.trim(); + int lim = limit > 0 ? limit : 40; + ApiClient.get().get("/mobile/picking/weigh-station/search?q=" + enc(q) + "&limit=" + lim, callback); + } + + public static void getProduct(String skuCode, String itemName, ApiClient.ApiCallback callback) { + StringBuilder path = new StringBuilder("/mobile/picking/weigh-station/product?"); + boolean has = false; + if (skuCode != null && !skuCode.trim().isEmpty()) { + path.append("sku=").append(enc(skuCode.trim())); + has = true; + } + if (itemName != null && !itemName.trim().isEmpty()) { + if (has) path.append('&'); + path.append("name=").append(enc(itemName.trim())); + has = true; + } + if (!has) { + callback.onError(-1, "缺少 sku 或 name"); + return; + } + ApiClient.get().get(path.toString(), callback); + } + + private static String enc(String raw) { + try { + return URLEncoder.encode(raw, "UTF-8"); + } catch (UnsupportedEncodingException e) { + return raw; + } + } + + public static Call recognize(String itemName, String skuCode, String imageBase64, + ApiClient.ApiCallback callback) { + try { + JSONObject body = new JSONObject(); + if (itemName != null && !itemName.isEmpty()) { + body.put("item_name", itemName); + } + if (skuCode != null && !skuCode.isEmpty()) { + body.put("sku_code", skuCode); + } + if (imageBase64 != null && !imageBase64.isEmpty()) { + body.put("image_base64", imageBase64); + } + return ApiClient.get().postLong("/mobile/picking/weigh-station/recognize", body, callback); + } catch (JSONException e) { + callback.onError(-1, "参数构造失败"); + return null; + } + } + + public static Call recognize(String itemName, String skuCode, ApiClient.ApiCallback callback) { + return recognize(itemName, skuCode, null, callback); + } + + public static void commit(String pickItemId, String pickCode, + double pickedQty, double pickedWeight, + String unit, String diffReason, + ApiClient.ApiCallback callback) { + try { + JSONObject body = new JSONObject(); + body.put("pick_item_id", pickItemId); + body.put("pick_code", pickCode); + body.put("picked_qty", pickedQty); + body.put("picked_weight", pickedWeight); + if (unit != null) { + body.put("unit", unit); + } + if (diffReason != null && !diffReason.isEmpty()) { + body.put("diff_reason", diffReason); + } + ApiClient.get().postLong("/mobile/picking/weigh-station/commit", body, callback); + } catch (JSONException e) { + callback.onError(-1, "参数构造失败"); + } + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/BurstCaptureHelper.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/BurstCaptureHelper.java new file mode 100644 index 0000000..7e56cc3 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/BurstCaptureHelper.java @@ -0,0 +1,96 @@ +package com.canteen.weigh.camera; + +import android.os.Handler; +import android.os.Looper; +import android.text.TextUtils; + +import java.util.ArrayList; +import java.util.List; + +/** + * 有货时连拍固定张数,供识别与归档(替代无限间隔连续识别)。 + */ +public final class BurstCaptureHelper { + + public interface Callback { + void onProgress(int indexOneBased, int total); + + void onComplete(List photosBase64); + + void onAborted(); + } + + private final Handler handler = new Handler(Looper.getMainLooper()); + private boolean running = false; + private int session = 0; + + public void start(final SimpleCameraHelper camera, + final int count, + final long gapMs, + final int jpegQuality, + final Callback callback) { + cancel(); + if (camera == null || callback == null || count <= 0) { + if (callback != null) { + callback.onAborted(); + } + return; + } + running = true; + final int mySession = ++session; + final List photos = new ArrayList<>(); + captureNext(camera, count, gapMs, jpegQuality, 0, photos, mySession, callback); + } + + public void cancel() { + running = false; + session++; + handler.removeCallbacksAndMessages(null); + } + + public boolean isRunning() { + return running; + } + + private void captureNext(final SimpleCameraHelper camera, + final int count, + final long gapMs, + final int jpegQuality, + final int index, + final List photos, + final int mySession, + final Callback callback) { + if (!running || mySession != session) { + return; + } + if (index >= count) { + running = false; + callback.onComplete(photos); + return; + } + callback.onProgress(index + 1, count); + camera.captureJpegBase64Async(jpegQuality, new SimpleCameraHelper.CaptureCallback() { + @Override + public void onCaptured(String b64) { + if (!running || mySession != session) { + return; + } + if (!TextUtils.isEmpty(b64)) { + photos.add(b64); + } + final int next = index + 1; + if (next >= count) { + running = false; + callback.onComplete(photos); + return; + } + handler.postDelayed(new Runnable() { + @Override + public void run() { + captureNext(camera, count, gapMs, jpegQuality, next, photos, mySession, callback); + } + }, Math.max(80L, gapMs)); + } + }); + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/CaptureImageHelper.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/CaptureImageHelper.java new file mode 100644 index 0000000..2231758 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/CaptureImageHelper.java @@ -0,0 +1,81 @@ +package com.canteen.weigh.camera; + +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.os.Handler; +import android.os.Looper; +import android.util.Base64; +import android.widget.ImageView; + +/** + * Base64 JPEG → ImageView;解码在后台,避免卡主线程。 + */ +public final class CaptureImageHelper { + + public interface DecodeCallback { + void onDecoded(Bitmap bitmap); + } + + private CaptureImageHelper() { + } + + public static void decodeBase64JpegAsync(final String b64, final DecodeCallback callback) { + if (callback == null) { + return; + } + final Handler main = new Handler(Looper.getMainLooper()); + if (b64 == null || b64.length() == 0) { + main.post(new Runnable() { + @Override + public void run() { + callback.onDecoded(null); + } + }); + return; + } + new Thread(new Runnable() { + @Override + public void run() { + Bitmap bmp = null; + try { + byte[] raw = Base64.decode(b64, Base64.DEFAULT); + if (raw != null && raw.length > 0) { + BitmapFactory.Options opts = new BitmapFactory.Options(); + opts.inPreferredConfig = Bitmap.Config.RGB_565; + bmp = BitmapFactory.decodeByteArray(raw, 0, raw.length, opts); + } + } catch (Exception ignored) { + bmp = null; + } + final Bitmap result = bmp; + main.post(new Runnable() { + @Override + public void run() { + callback.onDecoded(result); + } + }); + } + }, "capture-decode").start(); + } + + public static void showOnImageView(final ImageView imageView, String b64) { + if (imageView == null) { + return; + } + decodeBase64JpegAsync(b64, new DecodeCallback() { + @Override + public void onDecoded(Bitmap bitmap) { + if (bitmap == null) { + return; + } + imageView.setImageBitmap(bitmap); + } + }); + } + + public static void clear(ImageView imageView) { + if (imageView != null) { + imageView.setImageDrawable(null); + } + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/ContinuousRecognizeScheduler.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/ContinuousRecognizeScheduler.java new file mode 100644 index 0000000..3d3626e --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/ContinuousRecognizeScheduler.java @@ -0,0 +1,67 @@ +package com.canteen.weigh.camera; + +import android.os.Handler; +import android.os.Looper; + +/** + * 入库/分拣台:按间隔触发一轮识别(由 Host 决定能否 tick / 实际抓帧)。 + */ +public final class ContinuousRecognizeScheduler { + + public interface Host { + /** 当前间隔(毫秒),每次 tick 前读取以便设置即时生效 */ + long intervalMs(); + + /** false 则跳过本轮(暂停、冷却、识别中、无列表等) */ + boolean canTick(); + + /** 执行一次抓帧识别(须自行处理 isRecognizing) */ + void onRecognizeTick(); + } + + private final Host host; + private final Handler handler = new Handler(Looper.getMainLooper()); + private boolean running = false; + + private final Runnable tickRunnable = new Runnable() { + @Override + public void run() { + if (!running) { + return; + } + long next = Math.max(1500L, host.intervalMs()); + try { + if (host.canTick()) { + host.onRecognizeTick(); + } + } finally { + if (running) { + handler.postDelayed(this, next); + } + } + } + }; + + public ContinuousRecognizeScheduler(Host host) { + this.host = host; + } + + public void start() { + if (running) { + return; + } + running = true; + handler.removeCallbacks(tickRunnable); + // 稍晚第一枪,等预览出帧 + handler.postDelayed(tickRunnable, 800L); + } + + public void stop() { + running = false; + handler.removeCallbacks(tickRunnable); + } + + public boolean isRunning() { + return running; + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/PreviewPinchZoomHelper.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/PreviewPinchZoomHelper.java new file mode 100644 index 0000000..51e726c --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/PreviewPinchZoomHelper.java @@ -0,0 +1,139 @@ +package com.canteen.weigh.camera; + +import android.graphics.Matrix; +import android.graphics.RectF; +import android.view.MotionEvent; +import android.view.ScaleGestureDetector; +import android.view.TextureView; +import android.view.View; +import android.widget.FrameLayout; + +/** + * 预览双指捏合缩放(1×~3×)。见 docs/design/20260911-weigh-preview-pinch-zoom.md + */ +public final class PreviewPinchZoomHelper implements SimpleCameraHelper.VisibleCropProvider { + + public static final float MIN_SCALE = 1f; + public static final float MAX_SCALE = 3f; + + private final TextureView textureView; + private final ScaleGestureDetector detector; + private final Matrix matrix = new Matrix(); + private float scale = MIN_SCALE; + private float transX; + private float transY; + + public PreviewPinchZoomHelper(FrameLayout container, TextureView textureView) { + this.textureView = textureView; + detector = new ScaleGestureDetector(container.getContext(), + new ScaleGestureDetector.SimpleOnScaleGestureListener() { + @Override + public boolean onScale(ScaleGestureDetector d) { + applyScale(d.getScaleFactor(), d.getFocusX(), d.getFocusY()); + return true; + } + }); + container.setClickable(true); + container.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + detector.onTouchEvent(event); + int action = event.getActionMasked(); + boolean pinch = event.getPointerCount() >= 2 || detector.isInProgress(); + if (pinch) { + v.getParent().requestDisallowInterceptTouchEvent(true); + } + if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { + v.getParent().requestDisallowInterceptTouchEvent(false); + } + return pinch; + } + }); + apply(); + container.post(new Runnable() { + @Override + public void run() { + apply(); + } + }); + } + + public void apply() { + clampTranslation(); + matrix.reset(); + matrix.setScale(scale, scale); + matrix.postTranslate(transX, transY); + textureView.setTransform(matrix); + textureView.invalidate(); + } + + @Override + public RectF getVisibleNormRect() { + if (scale <= 1.01f) { + return null; + } + int w = textureView.getWidth(); + int h = textureView.getHeight(); + if (w <= 0 || h <= 0) { + return null; + } + float left = (-transX) / (scale * w); + float top = (-transY) / (scale * h); + float rw = 1f / scale; + float rh = 1f / scale; + if (left < 0f) { + left = 0f; + } + if (top < 0f) { + top = 0f; + } + if (left + rw > 1f) { + left = 1f - rw; + } + if (top + rh > 1f) { + top = 1f - rh; + } + return new RectF(left, top, left + rw, top + rh); + } + + private void applyScale(float factor, float focusX, float focusY) { + float next = scale * factor; + if (next < MIN_SCALE) { + next = MIN_SCALE; + } else if (next > MAX_SCALE) { + next = MAX_SCALE; + } + if (Math.abs(next - scale) < 0.0001f) { + clampTranslation(); + apply(); + return; + } + transX = focusX - (focusX - transX) * (next / scale); + transY = focusY - (focusY - transY) * (next / scale); + scale = next; + apply(); + } + + private void clampTranslation() { + int w = textureView.getWidth(); + int h = textureView.getHeight(); + if (w <= 0 || h <= 0 || scale <= MIN_SCALE) { + scale = MIN_SCALE; + transX = 0f; + transY = 0f; + return; + } + float minTx = w * (1f - scale); + float minTy = h * (1f - scale); + if (transX > 0f) { + transX = 0f; + } else if (transX < minTx) { + transX = minTx; + } + if (transY > 0f) { + transY = 0f; + } else if (transY < minTy) { + transY = minTy; + } + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/SimpleCameraHelper.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/SimpleCameraHelper.java new file mode 100644 index 0000000..b6849df --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/SimpleCameraHelper.java @@ -0,0 +1,1191 @@ +package com.canteen.weigh.camera; + +import android.graphics.Bitmap; +import android.graphics.Rect; +import android.graphics.RectF; +import android.graphics.SurfaceTexture; +import android.hardware.Camera; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.Looper; +import android.os.SystemClock; +import android.util.Base64; +import android.util.Log; +import android.view.TextureView; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +/** + * Camera1 预览(兼容 Android 7 / USB UVC / 全志 A64 等)。 + *

+ * - 仅 {@link #requestOpen()} 打开;USB 热插拔冷却期内由业务禁止调用。 + * - TextureView 重建时只关 Camera;若仍 {@code wantPreview},会延迟重开,避免黑屏。 + * - 识别图只截 {@link TextureView#getBitmap()}(设计 20260911-weigh-delete-nv21); + * 不读 Camera 预览 NV21 缓冲。 + */ +@SuppressWarnings("deprecation") +public class SimpleCameraHelper implements TextureView.SurfaceTextureListener { + + public interface PreviewCallback { + void onCameraError(String msg); + + void onCameraReady(); + } + + /** 预览可见区域(归一化 0~1);null 表示整帧。捏合缩放用。 */ + public interface VisibleCropProvider { + RectF getVisibleNormRect(); + } + + private static final String TAG = "SimpleCameraHelper"; + private static final long SURFACE_RETRY_MS = 280L; + + private final TextureView textureView; + private final PreviewCallback callback; + private final Handler mainHandler = new Handler(Looper.getMainLooper()); + private final Object lock = new Object(); + private final AtomicInteger openGeneration = new AtomicInteger(0); + /** 有打开流程在 worker 上执行时为 true:避免连续开请求互相作废止(打开要 ~0.8s,期间新请求会把旧流程作废) */ + private volatile boolean openInFlight = false; + + private HandlerThread cameraThread; + private Handler cameraHandler; + private Camera camera; + private boolean previewing = false; + private volatile boolean disposed = false; + /** 业务仍希望预览(暂停/Surface 重建后可自动重开) */ + private volatile boolean wantPreview = false; + /** false:秤空等业务暂停,禁止自动/主动打开预览 */ + private volatile boolean allowPreview = true; + private int previewWidth; + private int previewHeight; + private volatile SurfaceTexture lastSurfaceTexture; + /** TextureView 最近一次 onSurfaceTextureUpdated */ + private volatile long lastTextureUpdatedAtMs = 0L; + + /** 画面内容变化监听(现为空实现,换货靠秤重) */ + public interface SceneChangeListener { + void onSceneChanged(); + } + + /** 当前生效的对焦模式;非 AF 模式(fixed/infinity/edof)时跳过单次对焦 */ + private volatile String activeFocusMode = null; + /** 单次对焦进行中(回调或超时后复位),避免重复 autoFocus 抛异常 */ + private volatile boolean focusInFlight = false; + private volatile VisibleCropProvider visibleCropProvider; + private int pictureWidth; + private int pictureHeight; + /** 识别图长边上限(像素),兼顾清晰度与 2MB body */ + private static final int MAX_STILL_LONG_EDGE = 1600; + /** 截图前等清晰总上限(对焦拉风箱常见 1~2s) */ + private static final long SHARPNESS_WAIT_MAX_MS = 2000L; + private static final long SHARPNESS_WAIT_STEP_MS = 80L; + /** 清晰门禁阈值:低于此值视为模糊,继续等 */ + private static final double SHARPNESS_MIN_FOR_AI = 4.0; + + public SimpleCameraHelper(TextureView textureView, PreviewCallback callback) { + this.textureView = textureView; + this.callback = callback; + ensureCameraThread(); + textureView.setSurfaceTextureListener(this); + if (textureView.isAvailable()) { + lastSurfaceTexture = textureView.getSurfaceTexture(); + } + } + + private void ensureCameraThread() { + if (cameraThread != null) { + return; + } + cameraThread = new HandlerThread("weigh-camera"); + cameraThread.start(); + cameraHandler = new Handler(cameraThread.getLooper()); + } + + public boolean isWantPreview() { + return wantPreview && !disposed; + } + + public boolean isPreviewing() { + return previewing && camera != null; + } + + /** 是否正在打开相机(请求已发、尚未就绪),用于上层去抖重复 open */ + public boolean isOpening() { + return openInFlight; + } + + public boolean isAllowPreview() { + return allowPreview && !disposed; + } + + /** + * 秤空时 false:关闭预览且禁止 surface/request 自动重开; + * 有货时 true:允许再次 {@link #requestOpen()}。 + */ + public void setAllowPreview(boolean allow) { + allowPreview = allow; + if (!allow) { + closeCameraKeepWant(); + } else if (wantPreview && !disposed) { + // 仅抬允许位时补开,避免秤空→有货后 wantPreview 仍为 true 却一直黑屏 + requestOpenInternal(false); + } + } + + /** 保留接口;识别间隔不再读 NV21,截图路径不节流预览。 */ + public void setPreviewFrameMinIntervalMs(long ms) { + // no-op:已删除预览帧回调 + } + + public void setVisibleCropProvider(VisibleCropProvider provider) { + visibleCropProvider = provider; + } + + /** 换货检测已改为秤重;保留空实现以免页面改动。 */ + public void armSceneChangeDetection(SceneChangeListener listener) { + // no-op + } + + public void disarmSceneChangeDetection() { + // no-op + } + + @Override + public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { + lastSurfaceTexture = surface; + Log.i(TAG, "surfaceTextureAvailable " + width + "x" + height + + " wantPreview=" + wantPreview + " allow=" + allowPreview); + if (wantPreview && allowPreview && !disposed) { + mainHandler.postDelayed(new Runnable() { + @Override + public void run() { + if (wantPreview && allowPreview && !disposed) { + requestOpenInternal(false); + } + } + }, SURFACE_RETRY_MS); + } + } + + @Override + public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { + lastSurfaceTexture = surface; + Log.i(TAG, "surfaceTextureSizeChanged " + width + "x" + height + " cam=" + (camera != null)); + if (cameraHandler == null || disposed) { + return; + } + if (!allowPreview) { + return; + } + if (camera == null && wantPreview) { + requestOpenInternal(false); + return; + } + final SurfaceTexture st = surface; + cameraHandler.post(new Runnable() { + @Override + public void run() { + synchronized (lock) { + if (disposed || camera == null || !allowPreview) { + return; + } + try { + camera.stopPreview(); + } catch (Exception ignored) { + } + startPreviewLocked(st); + } + } + }); + } + + @Override + public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { + Log.i(TAG, "surfaceTextureDestroyed wantPreview=" + wantPreview); + lastSurfaceTexture = null; + closeCameraKeepWant(); + return true; + } + + @Override + public void onSurfaceTextureUpdated(SurfaceTexture surface) { + lastTextureUpdatedAtMs = SystemClock.elapsedRealtime(); + } + + /** 业务请求打开预览 */ + public void requestOpen() { + wantPreview = true; + requestOpenInternal(true); + } + + private void requestOpenInternal(boolean notifyIfSurfaceMissing) { + if (disposed) { + return; + } + if (!allowPreview) { + Log.i(TAG, "requestOpen skipped: allowPreview=false (scale empty)"); + return; + } + ensureCameraThread(); + final SurfaceTexture texture = lastSurfaceTexture != null + ? lastSurfaceTexture + : (textureView.isAvailable() ? textureView.getSurfaceTexture() : null); + if (texture == null) { + Log.w(TAG, "surfaceTexture not ready yet, wait onSurfaceTextureAvailable"); + if (notifyIfSurfaceMissing) { + notifyError("预览区域准备中,请稍候或再点「连接摄像头」"); + } + return; + } + lastSurfaceTexture = texture; + synchronized (lock) { + if (camera == null && openInFlight) { + Log.i(TAG, "open already in flight, skip duplicate request"); + return; + } + openInFlight = true; + } + final int gen = openGeneration.incrementAndGet(); + cameraHandler.post(new Runnable() { + @Override + public void run() { + try { + openCameraOnWorker(texture, gen); + } finally { + synchronized (lock) { + openInFlight = false; + } + } + } + }); + } + + /** 热插拔:关 Camera 且不再自动重开,直到业务再次 requestOpen */ + public void closeCameraAndClearWant() { + wantPreview = false; + closeCameraKeepWant(); + } + + /** 仅释放 Camera(保留 wantPreview,Surface 重建 / onResume 可重开) */ + public void closeCameraKeepWant() { + openGeneration.incrementAndGet(); + final Handler handler = cameraHandler; + if (handler != null) { + handler.post(new Runnable() { + @Override + public void run() { + releaseCameraLocked(); + } + }); + } else { + releaseCameraLocked(); + } + } + + /** @deprecated 用 {@link #closeCameraKeepWant()} / {@link #closeCameraAndClearWant()} */ + public void closeCamera() { + closeCameraKeepWant(); + } + + private void openCameraOnWorker(SurfaceTexture texture, int gen) { + synchronized (lock) { + if (disposed || gen != openGeneration.get()) { + return; + } + if (camera != null) { + startPreviewLocked(texture); + if (previewing) { + notifyReady(); + } + return; + } + } + Camera opened = null; + try { + int count = Camera.getNumberOfCameras(); + Log.i(TAG, "getNumberOfCameras=" + count); + if (disposed || gen != openGeneration.get()) { + return; + } + if (count <= 0) { + notifyError("未检测到摄像头"); + return; + } + int index = 0; + if (count > 1) { + try { + Camera.CameraInfo info = new Camera.CameraInfo(); + for (int i = 0; i < count; i++) { + Camera.getCameraInfo(i, info); + if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) { + index = i; + break; + } + } + } catch (Exception e) { + Log.w(TAG, "getCameraInfo skipped, use index 0", e); + index = 0; + } + } + Log.i(TAG, "Camera.open(" + index + ")"); + opened = Camera.open(index); + if (disposed || gen != openGeneration.get()) { + opened.release(); + return; + } + Camera.Parameters params = opened.getParameters(); + try { + StringBuilder sb = new StringBuilder(); + for (Camera.Size s : params.getSupportedPreviewSizes()) { + if (sb.length() > 0) sb.append(','); + sb.append(s.width).append('x').append(s.height); + } + Log.i(TAG, "supported preview sizes: " + sb); + } catch (Exception ignored) { + } + // 预览:优先较高分辨率 + Camera.Size size = choosePreferredPreviewSize(params.getSupportedPreviewSizes()); + if (size != null) { + params.setPreviewSize(size.width, size.height); + previewWidth = size.width; + previewHeight = size.height; + } else { + Camera.Size cur = params.getPreviewSize(); + previewWidth = cur.width; + previewHeight = cur.height; + } + Camera.Size pic = choosePictureSize(params.getSupportedPictureSizes(), MAX_STILL_LONG_EDGE); + if (pic != null) { + try { + params.setPictureSize(pic.width, pic.height); + pictureWidth = pic.width; + pictureHeight = pic.height; + Log.i(TAG, "picture size " + pic.width + "x" + pic.height); + } catch (Exception e) { + Log.w(TAG, "setPictureSize failed", e); + pictureWidth = 0; + pictureHeight = 0; + } + } + try { + params.setJpegQuality(90); + } catch (Exception ignored) { + } + int[] fpsRange = choosePreviewFpsRange(params.getSupportedPreviewFpsRange(), 30000); + if (fpsRange != null) { + try { + params.setPreviewFpsRange(fpsRange[0], fpsRange[1]); + Log.i(TAG, "preview fps range " + fpsRange[0] + "-" + fpsRange[1] + + " (≈" + (fpsRange[1] / 1000) + "fps max)"); + } catch (Exception e) { + Log.w(TAG, "setPreviewFpsRange failed", e); + } + } else { + Log.w(TAG, "no supported preview fps range"); + } + opened.setParameters(params); + // 对焦:摄像头支持自动对焦,优先连续对焦;逐个尝试,单个失败不影响相机打开 + // 顺序:continuous-video(预览连续对焦)→ macro(近摄)→ fixed → infinity + List focuses = params.getSupportedFocusModes(); + Log.i(TAG, "supported focus modes: " + focuses); + String[] preferred = { + Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE, + Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO, + Camera.Parameters.FOCUS_MODE_AUTO, + Camera.Parameters.FOCUS_MODE_MACRO, + Camera.Parameters.FOCUS_MODE_FIXED, + Camera.Parameters.FOCUS_MODE_INFINITY, + }; + for (String mode : preferred) { + if (focuses == null || !focuses.contains(mode)) { + continue; + } + try { + Camera.Parameters p2 = opened.getParameters(); + p2.setFocusMode(mode); + // 中心对焦区域:与识别图的中心裁切一致,AF 对着秤垫中央的货物对焦而非背景 + if (p2.getMaxNumFocusAreas() > 0) { + try { + List areas = new ArrayList(); + areas.add(new Camera.Area(new Rect(-400, -400, 400, 400), 1000)); + p2.setFocusAreas(areas); + Log.i(TAG, "focus areas set: center, max=" + p2.getMaxNumFocusAreas()); + } catch (Exception e) { + Log.w(TAG, "setFocusAreas failed (ignored)", e); + } + } + opened.setParameters(p2); + activeFocusMode = mode; + Log.i(TAG, "focus mode set: " + mode); + break; + } catch (Exception e) { + Log.w(TAG, "set focus mode " + mode + " failed, try next", e); + } + } + // 先挂 Texture 再 start;回调放 start 之后,减少部分机型黑屏 + opened.setPreviewTexture(texture); + opened.startPreview(); + synchronized (lock) { + if (disposed || gen != openGeneration.get()) { + try { + opened.stopPreview(); + opened.release(); + } catch (Exception ignored) { + } + return; + } + camera = opened; + opened = null; + previewing = true; + } + Log.i(TAG, "preview started " + previewWidth + "x" + previewHeight + + (fpsRange != null ? (" @" + (fpsRange[1] / 1000) + "fps") : "")); + notifyReady(); + // 预览起流稳定后补一次单次对焦:相机到秤垫距离固定,一次合焦长期有效; + // 对「报告支持 continuous 但 UVC HAL 不干活」的机器是关键兜底 + scheduleOneShotFocus(600L); + } catch (Exception e) { + Log.e(TAG, "openCamera failed", e); + if (opened != null) { + try { + opened.release(); + } catch (Exception ignored) { + } + } + releaseCameraLocked(); + notifyError("打开摄像头失败: " + e.getMessage()); + } + } + + private void startPreviewLocked(SurfaceTexture texture) { + if (camera == null || disposed) { + return; + } + try { + camera.setPreviewTexture(texture); + camera.startPreview(); + previewing = true; + // 预览重启后焦点可能被 HAL 复位,补一次单次对焦 + // 预览重启后焦点可能被 HAL 复位,补一次单次对焦 + scheduleOneShotFocus(600L); + } catch (IOException e) { + previewing = false; + Log.e(TAG, "startPreview failed", e); + notifyError("摄像头预览失败"); + } + } + + /** + * 延迟触发一次单次对焦(预览必须已启动)。业务在「换货」「开始识别」前也可直接调 + * {@link #requestOneShotFocus()}。对焦成败只记日志,不阻塞抓帧。 + */ + private void scheduleOneShotFocus(long delayMs) { + final Handler handler = cameraHandler; + if (handler == null || disposed) { + return; + } + handler.postDelayed(new Runnable() { + @Override + public void run() { + doOneShotFocusLocked(); + } + }, delayMs); + } + + /** 业务入口:换货/识别前主动对焦一次(幂等,进行中自动跳过) */ + public void requestOneShotFocus() { + scheduleOneShotFocus(0L); + } + + private void doOneShotFocusLocked() { + final Camera cam; + synchronized (lock) { + cam = camera; + } + if (cam == null || !previewing || disposed) { + return; + } + final String mode = activeFocusMode; + // 即使 fixed/infinity 模式也尝试 autoFocus:很多 USB 摄像头报告 fixed 但实际支持自动对焦 + // 如果真正不支持,autoFocus() 会抛异常被 catch,不影响流程 + if (mode == null) { + Log.i(TAG, "skip one-shot focus: mode=null"); + return; + } + if (focusInFlight) { + Log.i(TAG, "skip one-shot focus: already in flight"); + return; + } + focusInFlight = true; + try { + cam.autoFocus(new Camera.AutoFocusCallback() { + @Override + public void onAutoFocus(boolean success, Camera camera) { + focusInFlight = false; + Log.i(TAG, "one-shot autoFocus done success=" + success + " mode=" + mode); + } + }); + // 部分 UVC HAL 对焦回调永远不来,1.5s 后强制复位避免永久挡后续对焦 + final Handler handler = cameraHandler; + if (handler != null) { + handler.postDelayed(new Runnable() { + @Override + public void run() { + if (focusInFlight) { + focusInFlight = false; + Log.w(TAG, "one-shot autoFocus callback timeout, reset"); + } + } + }, 1500L); + } + } catch (Exception e) { + focusInFlight = false; + Log.w(TAG, "autoFocus call failed (mode=" + mode + ")", e); + } + } + + /** TextureView Bitmap 中心锐度。 */ + private static double centerSharpnessBitmap(Bitmap bmp) { + if (bmp == null) { + return 0; + } + int w = bmp.getWidth(); + int h = bmp.getHeight(); + if (w < 8 || h < 8) { + return 0; + } + int x0 = w / 4; + int x1 = w - w / 4; + int y0 = h / 4; + int y1 = h - h / 4; + long sum = 0; + int n = 0; + for (int y = y0; y < y1 - 2; y += 2) { + for (int x = x0; x < x1 - 2; x += 2) { + int c0 = bmp.getPixel(x, y); + int c1 = bmp.getPixel(x + 2, y); + int c2 = bmp.getPixel(x, y + 2); + int yL = ((c0 >> 16) & 0xFF) * 3 + ((c0 >> 8) & 0xFF) * 6 + (c0 & 0xFF); + int yR = ((c1 >> 16) & 0xFF) * 3 + ((c1 >> 8) & 0xFF) * 6 + (c1 & 0xFF); + int yD = ((c2 >> 16) & 0xFF) * 3 + ((c2 >> 8) & 0xFF) * 6 + (c2 & 0xFF); + // 近似 luma*10,与字节差量级接近 + sum += Math.abs(yL - yR) + Math.abs(yL - yD); + n++; + } + } + return n > 0 ? (double) sum / (double) (n * 2 * 10) : 0; + } + + /** + * 选择预览 FPS range(单位:千分之一帧,如 30000=30fps)。 + * 优先 max==target;否则 max≤target 最接近;再否则 max 最接近 target。 + */ + private int[] choosePreviewFpsRange(List ranges, int targetMaxFps) { + if (ranges == null || ranges.isEmpty()) { + return null; + } + int[] exact = null; + int exactMin = -1; + int[] under = null; + int underDiff = Integer.MAX_VALUE; + int[] nearest = null; + int nearestDiff = Integer.MAX_VALUE; + for (int[] r : ranges) { + if (r == null || r.length < 2) { + continue; + } + int min = r[0]; + int max = r[1]; + if (max == targetMaxFps) { + if (exact == null || min > exactMin) { + exact = r; + exactMin = min; + } + continue; + } + int diff = Math.abs(max - targetMaxFps); + if (max <= targetMaxFps && (targetMaxFps - max) < underDiff) { + under = r; + underDiff = targetMaxFps - max; + } + if (diff < nearestDiff) { + nearest = r; + nearestDiff = diff; + } + } + if (exact != null) { + return exact; + } + if (under != null) { + return under; + } + return nearest; + } + + private static Camera.Size choosePreviewSize(List sizes, int preferW, int preferH) { + if (sizes == null || sizes.isEmpty()) { + return null; + } + Camera.Size best = sizes.get(0); + int bestScore = Integer.MAX_VALUE; + for (Camera.Size s : sizes) { + int score = Math.abs(s.width - preferW) + Math.abs(s.height - preferH); + if (score < bestScore) { + bestScore = score; + best = s; + } + } + return best; + } + + public interface CaptureCallback { + /** 主线程回调;失败时 base64 为 null */ + void onCaptured(String base64Jpeg); + } + + /** + * 识别图只截预览 TextureView。 + * 设计:docs/design/20260911-weigh-delete-nv21.md + * 清晰前提:截图 Bitmap 锐度达标,糊则等,最多约 2s。 + */ + public void captureJpegBase64Async(final int quality, final CaptureCallback callback) { + if (callback == null) { + return; + } + if (disposed) { + mainHandler.post(new Runnable() { + @Override + public void run() { + callback.onCaptured(null); + } + }); + return; + } + ensureCameraThread(); + final long deadlineAt = SystemClock.elapsedRealtime() + SHARPNESS_WAIT_MAX_MS; + mainHandler.post(new Runnable() { + @Override + public void run() { + capturePreviewScreenshot(quality, callback, deadlineAt, 0); + } + }); + } + + /** + * 预览截图;失败则重截。 + */ + private void capturePreviewScreenshot(final int quality, final CaptureCallback callback, + final long deadlineAt, final int bitmapRetry) { + if (disposed) { + callback.onCaptured(null); + return; + } + final TextureView tv = textureView; + long now = SystemClock.elapsedRealtime(); + if (tv == null || !tv.isAvailable()) { + retryScreenshotOrFail("texture unavailable", quality, callback, deadlineAt, bitmapRetry); + return; + } + synchronized (lock) { + if (!previewing) { + retryScreenshotOrFail("not previewing", quality, callback, deadlineAt, bitmapRetry); + return; + } + } + Bitmap bmp = null; + try { + int tw = previewWidth > 0 ? previewWidth : tv.getWidth(); + int th = previewHeight > 0 ? previewHeight : tv.getHeight(); + if (tw > 0 && th > 0) { + bmp = tv.getBitmap(tw, th); + } + if (bmp == null) { + bmp = tv.getBitmap(); + } + } catch (Exception e) { + Log.w(TAG, "textureview getBitmap failed", e); + retryScreenshotOrFail("getBitmap exception", quality, callback, deadlineAt, bitmapRetry); + return; + } + if (bmp == null || isBlankBitmap(bmp)) { + Log.w(TAG, "textureview blank/null"); + if (bmp != null) { + bmp.recycle(); + } + retryScreenshotOrFail("blank", quality, callback, deadlineAt, bitmapRetry); + return; + } + Bitmap cropped = cropBitmapToVisible(bmp); + if (cropped != bmp) { + bmp.recycle(); + bmp = cropped; + } + if (bmp == null) { + retryScreenshotOrFail("crop null", quality, callback, deadlineAt, bitmapRetry); + return; + } + if (isGreenBrokenBitmap(bmp)) { + Log.w(TAG, "textureview green junk " + bmp.getWidth() + "x" + bmp.getHeight() + + ", not uploading"); + bmp.recycle(); + retryScreenshotOrFail("green", quality, callback, deadlineAt, bitmapRetry); + return; + } + double bmpSharp = centerSharpnessBitmap(bmp); + boolean bmpOk = bmpSharp >= SHARPNESS_MIN_FOR_AI; + if (!bmpOk && now < deadlineAt) { + Log.i(TAG, "sharpness wait bitmap=" + String.format("%.2f", bmpSharp) + + " retry=" + bitmapRetry + " leftMs=" + (deadlineAt - now)); + bmp.recycle(); + scheduleScreenshotRetry(quality, callback, deadlineAt, bitmapRetry + 1); + return; + } + if (!bmpOk) { + Log.w(TAG, "sharpness wait timeout bitmap=" + String.format("%.2f", bmpSharp) + + ", screenshot anyway"); + } else { + Log.i(TAG, "sharpness bitmap ok=" + String.format("%.2f", bmpSharp)); + } + String b64 = bitmapToJpegBase64(bmp, quality); + Log.i(TAG, "textureview screenshot ok " + bmp.getWidth() + "x" + bmp.getHeight()); + bmp.recycle(); + callback.onCaptured(b64); + } + + private void retryScreenshotOrFail(String reason, final int quality, final CaptureCallback callback, + final long deadlineAt, final int bitmapRetry) { + if (SystemClock.elapsedRealtime() < deadlineAt) { + Log.i(TAG, "screenshot retry reason=" + reason + " retry=" + bitmapRetry); + scheduleScreenshotRetry(quality, callback, deadlineAt, bitmapRetry + 1); + return; + } + Log.w(TAG, "screenshot failed: " + reason); + callback.onCaptured(null); + } + + private void scheduleScreenshotRetry(final int quality, final CaptureCallback callback, + final long deadlineAt, final int next) { + cameraHandler.postDelayed(new Runnable() { + @Override + public void run() { + mainHandler.post(new Runnable() { + @Override + public void run() { + capturePreviewScreenshot(quality, callback, deadlineAt, next); + } + }); + } + }, SHARPNESS_WAIT_STEP_MS); + } + + /** Bitmap → 识别上传 JPEG → base64(缩放长边≤1280 + q≈82,设计 20260910-weigh-ai-upload-compress)。 */ + private static String bitmapToJpegBase64(Bitmap bmp, int quality) { + byte[] jpeg = bitmapToAiUploadJpeg(bmp, quality); + return jpeg == null ? null : Base64.encodeToString(jpeg, Base64.NO_WRAP); + } + + /** 空图判定:中心区域 RGB 三通道方差都低 → 全黑/单色空图。 */ + private static boolean isBlankBitmap(Bitmap bmp) { + if (bmp == null) { + return true; + } + int w = bmp.getWidth(); + int h = bmp.getHeight(); + if (w < 8 || h < 8) { + return true; + } + long sumR = 0, sumG = 0, sumB = 0; + long sumR2 = 0, sumG2 = 0, sumB2 = 0; + int n = 0; + for (int y = h / 4; y < h - h / 4; y += 4) { + for (int x = w / 4; x < w - w / 4; x += 4) { + int c = bmp.getPixel(x, y); + int r = (c >> 16) & 0xFF; + int g = (c >> 8) & 0xFF; + int b = c & 0xFF; + sumR += r; + sumG += g; + sumB += b; + sumR2 += (long) r * r; + sumG2 += (long) g * g; + sumB2 += (long) b * b; + n++; + } + } + if (n < 20) { + return true; + } + double mR = sumR / (double) n; + double mG = sumG / (double) n; + double mB = sumB / (double) n; + double vR = sumR2 / (double) n - mR * mR; + double vG = sumG2 / (double) n - mG * mG; + double vB = sumB2 / (double) n - mB * mB; + return vR < 20.0 && vG < 20.0 && vB < 20.0; + } + + /** TextureView 预览截图绿屏判定。 */ + private static boolean isGreenBrokenBitmap(Bitmap bmp) { + if (bmp == null) { + return false; + } + int w = bmp.getWidth(); + int h = bmp.getHeight(); + if (w < 8 || h < 8) { + return false; + } + long sumR = 0, sumG = 0, sumB = 0; + long sumR2 = 0, sumG2 = 0, sumB2 = 0; + int n = 0; + for (int y = h / 4; y < h - h / 4; y += 2) { + for (int x = w / 4; x < w - w / 4; x += 2) { + int c = bmp.getPixel(x, y); + int r = (c >> 16) & 0xFF; + int g = (c >> 8) & 0xFF; + int b = c & 0xFF; + sumR += r; + sumG += g; + sumB += b; + sumR2 += (long) r * r; + sumG2 += (long) g * g; + sumB2 += (long) b * b; + n++; + } + } + if (n < 40) { + return false; + } + double mR = sumR / (double) n; + double mG = sumG / (double) n; + double mB = sumB / (double) n; + double vR = sumR2 / (double) n - mR * mR; + double vG = sumG2 / (double) n - mG * mG; + double vB = sumB2 / (double) n - mB * mB; + return vR < 80.0 && vG < 80.0 && vB < 80.0 + && (mG - mR) > 40.0 && (mG - mB) > 40.0 + && mG > 40.0; + } + + /** + * 相机画面是否已稳定(供自动识别节拍门禁)。 + * TextureView 最近在刷即视为画面在动;清晰度在截图路径用 Bitmap 再判。 + */ + public boolean isPreviewFrameStable() { + if (disposed || !previewing) { + return false; + } + if (textureView == null || !textureView.isAvailable()) { + return false; + } + long now = SystemClock.elapsedRealtime(); + return (now - lastTextureUpdatedAtMs) <= 500L; + } + + /** + * 场景指纹探针:把预览缩成 {@link #PROBE_WIDTH}×{@link #PROBE_HEIGHT} 算 64 位 dHash。 + * 只用于判断「画面有没有变」,不压缩、不落盘、不发网络(约几毫秒)。 + * 设计:docs/design/20260924-weigh-scene-gate-and-adaptive-retry.md + * + * @return 64 位指纹;取不到帧(未预览 / 非主线程 / 异常)返回 0,调用方须按「未知 = 放行」处理 + */ + public long probeSceneHash() { + if (disposed || Looper.myLooper() != Looper.getMainLooper()) { + return 0L; + } + final TextureView tv = textureView; + if (tv == null || !tv.isAvailable() || !isPreviewing()) { + return 0L; + } + Bitmap small = null; + try { + small = tv.getBitmap(PROBE_WIDTH, PROBE_HEIGHT); + } catch (Exception e) { + Log.w(TAG, "probe getBitmap failed", e); + return 0L; + } + if (small == null) { + return 0L; + } + try { + return dHash64(small); + } finally { + small.recycle(); + } + } + + /** 9×8 灰度差分哈希(dHash):与右邻比较得 64 位指纹。纯像素计算。 */ + static long dHash64(Bitmap src) { + if (src == null) { + return 0L; + } + Bitmap grid = null; + try { + grid = Bitmap.createScaledBitmap(src, 9, 8, true); + long hash = 0L; + int bit = 0; + for (int y = 0; y < 8; y++) { + for (int x = 0; x < 8; x++) { + int left = lumaOf(grid.getPixel(x, y)); + int right = lumaOf(grid.getPixel(x + 1, y)); + if (left > right) { + hash |= (1L << bit); + } + bit++; + } + } + return hash; + } catch (Exception e) { + Log.w(TAG, "dHash64 failed", e); + return 0L; + } finally { + if (grid != null && grid != src && !grid.isRecycled()) { + grid.recycle(); + } + } + } + + /** 整数亮度(0.30R + 0.59G + 0.11B,放大 100 倍取整)。 */ + private static int lumaOf(int color) { + return ((color >> 16) & 0xFF) * 30 + ((color >> 8) & 0xFF) * 59 + (color & 0xFF) * 11; + } + + private static Camera.Size choosePreferredPreviewSize(List sizes) { + if (sizes == null || sizes.isEmpty()) { + return null; + } + // 优先:面积最大且长边<=1600(与静态拍照同分辨率,预览帧直取可省停预览耗时);若无则退回最接近 640x480 + Camera.Size bestMid = null; + int bestMidArea = -1; + for (Camera.Size s : sizes) { + if (s == null) continue; + int longEdge = Math.max(s.width, s.height); + if (longEdge > 1600) continue; + int area = s.width * s.height; + if (area > bestMidArea) { + bestMidArea = area; + bestMid = s; + } + } + if (bestMid != null) { + return bestMid; + } + // 无中档时尝试最大(含 1600),靠绿帧检测回退 + Camera.Size largest = null; + int largestArea = -1; + for (Camera.Size s : sizes) { + if (s == null) continue; + int area = s.width * s.height; + if (area > largestArea) { + largestArea = area; + largest = s; + } + } + return largest != null ? largest : choosePreviewSize(sizes, 640, 480); + } + + private static Camera.Size choosePictureSize(List sizes, int maxLongEdge) { + if (sizes == null || sizes.isEmpty()) { + return null; + } + List copy = new ArrayList(sizes); + Collections.sort(copy, new Comparator() { + @Override + public int compare(Camera.Size a, Camera.Size b) { + return Integer.compare(b.width * b.height, a.width * a.height); + } + }); + Camera.Size bestUnder = null; + for (Camera.Size s : copy) { + if (s == null) continue; + int longEdge = Math.max(s.width, s.height); + if (longEdge <= maxLongEdge) { + return s; + } + if (bestUnder == null) { + bestUnder = s; + } + } + return bestUnder != null ? bestUnder : copy.get(0); + } + + /** + * 识别上传压缩(设计 20260910-weigh-ai-upload-compress): + * 长边 ≤ 1280,JPEG 质量 82;不再使用旧的质量下限 92。 + */ + private static final int AI_UPLOAD_MAX_LONG_EDGE = 1024; + private static final int AI_UPLOAD_JPEG_QUALITY = 75; + + /** 场景指纹探针尺寸:只用于判断「画面有没有变」,与上传图无关(越小越省) */ + private static final int PROBE_WIDTH = 64; + private static final int PROBE_HEIGHT = 48; + + private static int resolveAiUploadJpegQuality(int quality) { + // 识别路径统一 82;忽略业务侧传入的 92,避免抵消压缩 + if (quality > 0 && quality < AI_UPLOAD_JPEG_QUALITY) { + return quality; + } + return AI_UPLOAD_JPEG_QUALITY; + } + + /** 等比缩放使长边 ≤ {@link #AI_UPLOAD_MAX_LONG_EDGE};无需缩放时返回原图。 */ + private static Bitmap scaleBitmapForAiUpload(Bitmap src) { + if (src == null) { + return null; + } + int w = src.getWidth(); + int h = src.getHeight(); + int longEdge = Math.max(w, h); + if (longEdge <= AI_UPLOAD_MAX_LONG_EDGE || w < 2 || h < 2) { + return src; + } + float scale = AI_UPLOAD_MAX_LONG_EDGE / (float) longEdge; + int nw = Math.max(1, Math.round(w * scale)); + int nh = Math.max(1, Math.round(h * scale)); + return Bitmap.createScaledBitmap(src, nw, nh, true); + } + + /** Bitmap → 识别上传 JPEG 字节(缩放 + q≈82)。 */ + private static byte[] bitmapToAiUploadJpeg(Bitmap bmp, int quality) { + if (bmp == null) { + return null; + } + Bitmap scaled = null; + try { + scaled = scaleBitmapForAiUpload(bmp); + if (scaled == null) { + return null; + } + int q = resolveAiUploadJpegQuality(quality); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + scaled.compress(Bitmap.CompressFormat.JPEG, q, out); + byte[] jpeg = out.toByteArray(); + Log.i(TAG, "ai jpeg " + bmp.getWidth() + "x" + bmp.getHeight() + + "→" + scaled.getWidth() + "x" + scaled.getHeight() + + " q=" + q + " bytes=" + jpeg.length); + return jpeg; + } catch (Exception e) { + Log.e(TAG, "bitmapToAiUploadJpeg failed", e); + return null; + } finally { + if (scaled != null && scaled != bmp && !scaled.isRecycled()) { + scaled.recycle(); + } + } + } + + private Bitmap cropBitmapToVisible(Bitmap bmp) { + Rect r = visiblePixelRect(bmp.getWidth(), bmp.getHeight()); + if (r == null) { + return bmp; + } + try { + Log.i(TAG, "pinch crop " + r.width() + "x" + r.height() + + " of " + bmp.getWidth() + "x" + bmp.getHeight()); + return Bitmap.createBitmap(bmp, r.left, r.top, r.width(), r.height()); + } catch (Exception e) { + Log.w(TAG, "cropBitmapToVisible failed", e); + return bmp; + } + } + + private Rect visiblePixelRect(int width, int height) { + VisibleCropProvider p = visibleCropProvider; + if (p == null || width < 4 || height < 4) { + return null; + } + RectF n = p.getVisibleNormRect(); + if (n == null || n.width() >= 0.99f || n.height() >= 0.99f) { + return null; + } + int x = Math.max(0, Math.round(n.left * width)); + int y = Math.max(0, Math.round(n.top * height)); + int cw = Math.min(width - x, Math.max(2, Math.round(n.width() * width))); + int ch = Math.min(height - y, Math.max(2, Math.round(n.height() * height))); + x &= ~1; + y &= ~1; + cw &= ~1; + ch &= ~1; + if (cw < 2 || ch < 2 || (cw >= width && ch >= height)) { + return null; + } + return new Rect(x, y, x + cw, y + ch); + } + + public void release() { + disposed = true; + wantPreview = false; + openGeneration.incrementAndGet(); + mainHandler.removeCallbacksAndMessages(null); + final HandlerThread thread = cameraThread; + final Handler handler = cameraHandler; + cameraThread = null; + cameraHandler = null; + if (handler != null) { + handler.post(new Runnable() { + @Override + public void run() { + releaseCameraLocked(); + if (thread != null) { + thread.quit(); + } + } + }); + } else { + releaseCameraLocked(); + } + try { + textureView.setSurfaceTextureListener(null); + } catch (Exception ignored) { + } + } + + private void releaseCameraLocked() { + synchronized (lock) { + previewing = false; + focusInFlight = false; + activeFocusMode = null; + if (camera != null) { + try { + camera.setPreviewCallback(null); + camera.stopPreview(); + } catch (Exception ignored) { + } + try { + camera.release(); + } catch (Exception ignored) { + } + camera = null; + } + } + } + + private void notifyError(final String msg) { + if (callback == null) { + return; + } + mainHandler.post(new Runnable() { + @Override + public void run() { + callback.onCameraError(msg); + } + }); + } + + private void notifyReady() { + if (callback == null) { + return; + } + mainHandler.post(new Runnable() { + @Override + public void run() { + callback.onCameraReady(); + } + }); + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/UsbCameraHotplugGuard.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/UsbCameraHotplugGuard.java new file mode 100644 index 0000000..6963075 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/UsbCameraHotplugGuard.java @@ -0,0 +1,97 @@ +package com.canteen.weigh.camera; + +import android.app.Activity; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.hardware.usb.UsbManager; +import android.os.SystemClock; + +/** + * USB 热插拔:立刻关 Camera,并进入冷却窗,避免枚举未完成时 Camera.open 整机假死。 + */ +public final class UsbCameraHotplugGuard { + + public static final long COOLDOWN_MS = 5000L; + + public interface Callback { + /** 关闭预览(不要在冷却窗内 requestOpen) */ + void onHotplugCloseCamera(); + + void onHotplugMessage(String message); + } + + private final Activity activity; + private final Callback callback; + private long openNotBeforeElapsed; + private BroadcastReceiver receiver; + private boolean registered; + + public UsbCameraHotplugGuard(Activity activity, Callback callback) { + this.activity = activity; + this.callback = callback; + } + + public void register() { + if (registered) { + return; + } + receiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + if (intent == null || intent.getAction() == null) { + return; + } + String action = intent.getAction(); + if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) { + beginCooldown(); + if (callback != null) { + callback.onHotplugCloseCamera(); + callback.onHotplugMessage( + "检测到 USB 接入。约 " + + (COOLDOWN_MS / 1000) + + " 秒后自动开预览(立刻打开易卡死)"); + } + } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) { + beginCooldown(); + if (callback != null) { + callback.onHotplugCloseCamera(); + callback.onHotplugMessage("USB 已拔出。可手选商品;重新插好后约数秒自动开预览"); + } + } + } + }; + IntentFilter filter = new IntentFilter(); + filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED); + filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED); + activity.registerReceiver(receiver, filter); + registered = true; + } + + public void unregister() { + if (!registered || receiver == null) { + return; + } + try { + activity.unregisterReceiver(receiver); + } catch (Exception ignored) { + } + registered = false; + receiver = null; + } + + public void beginCooldown() { + openNotBeforeElapsed = SystemClock.elapsedRealtime() + COOLDOWN_MS; + } + + /** @return 剩余冷却毫秒;0 表示可打开 */ + public long remainingCooldownMs() { + long left = openNotBeforeElapsed - SystemClock.elapsedRealtime(); + return left > 0 ? left : 0; + } + + public boolean canOpenNow() { + return remainingCooldownMs() == 0; + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/VideoStreamRecognizeHelper.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/VideoStreamRecognizeHelper.java new file mode 100644 index 0000000..e4af5eb --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/camera/VideoStreamRecognizeHelper.java @@ -0,0 +1,211 @@ +package com.canteen.weigh.camera; + +import android.os.Handler; +import android.os.Looper; +import android.util.Log; + +import com.canteen.weigh.CanteenApp; + +/** + * 秤上有重量时每 2 秒抽一帧识别;秤空停止。 + * 重量跳变或秤空时通知业务作废旧识别。 + */ +public final class VideoStreamRecognizeHelper { + + private static final String TAG = "WeighCycle"; + + public interface Host { + boolean canTick(); + + void onRecognizeTick(); + + /** scaleEmpty=true 秤已空;false 重量跳变(换货) */ + void onRescanNeeded(boolean scaleEmpty); + + /** 相机画面是否已稳定(设计 20260910-weigh-auto-capture-stable-gate)。无相机/不关心时返回 true 放行。 */ + boolean isCameraFrameStable(); + } + + public static final long TICK_MS = 2000L; + /** 兼容旧引用:默认忽略 0.2 斤(实际运行以 CanteenApp 配置为准) */ + public static final double NOISE_IGNORE_JIN = CanteenApp.DEFAULT_WEIGHT_NOISE_IGNORE_JIN; + public static final double NOISE_IGNORE_KG = NOISE_IGNORE_JIN / 2.0; + public static final double RESCAN_DELTA_KG = NOISE_IGNORE_KG; + public static final double STABLE_DELTA_KG = NOISE_IGNORE_KG; + /** 重量保持不动满该时长才算「稳定」,稳定前不抓拍(货在移动/换货中不识别)。400ms:放货动作落定即可,不等静置 */ + public static final long STABLE_MS = 250L; + /** 重量已稳但画面未稳时的短周期重试,避免干等下一个 2 秒周期 */ + public static final long FRAME_SETTLE_RECHECK_MS = 250L; + /** 有重量但长期达不到稳定(秤漂移大)时的兜底:超过该时长也放行一拍,避免节拍完全打不出 */ + private static final long UNSTABLE_FALLBACK_MS = 2500L; + + private final Host host; + private final Handler handler = new Handler(Looper.getMainLooper()); + private boolean running = false; + private double lastKg = Double.NaN; + private boolean lastHadWeight = false; + private double prevSampleKg = Double.NaN; + private long lastKgMoveAt = 0L; + private boolean wasStable = false; + + private final Runnable tickRunnable = new Runnable() { + @Override + public void run() { + if (!running) { + return; + } + try { + boolean canTick = host.canTick(); + boolean weightStable = isWeightStable(System.currentTimeMillis()); + boolean frameStable = host.isCameraFrameStable(); + if (canTick && weightStable && frameStable) { + host.onRecognizeTick(); + } else if (canTick && unstableFallbackDue()) { + // 秤漂移大导致长期不稳:兜底放行一拍,避免完全打不出节拍 + Log.i(TAG, "tick fallback: unstable for " + UNSTABLE_FALLBACK_MS + "ms, fire anyway"); + host.onRecognizeTick(); + } else if (canTick && weightStable && !frameStable) { + // 重量已稳、画面未稳:短周期重试,等画面收敛即拍 + Log.i(TAG, "tick recheck: weight stable but frame not stable, retry in " + FRAME_SETTLE_RECHECK_MS + "ms"); + handler.removeCallbacks(tickRunnable); + handler.postDelayed(this, FRAME_SETTLE_RECHECK_MS); + return; + } else { + Log.i(TAG, "tick skipped canTick=" + canTick + " weightStable=" + weightStable + " frameStable=" + frameStable); + } + } finally { + if (running) { + handler.removeCallbacks(tickRunnable); + handler.postDelayed(this, tickIntervalMs()); + } + } + } + }; + + private boolean isWeightStable(long now) { + return lastHadWeight && now - lastKgMoveAt >= STABLE_MS; + } + + /** 重量 + 画面双稳定(设计 20260910-weigh-auto-capture-stable-gate) */ + private boolean isStable(long now) { + return isWeightStable(now) && host.isCameraFrameStable(); + } + + /** 有重量但持续未稳定超过兜底时长 */ + private boolean unstableFallbackDue() { + return lastHadWeight + && lastKgMoveAt > 0 + && System.currentTimeMillis() - lastKgMoveAt >= UNSTABLE_FALLBACK_MS; + } + + /** 识别节奏跟随设备设置「识别间隔」(默认 2 秒),读取失败退回 2 秒 */ + private static long tickIntervalMs() { + try { + return CanteenApp.get().getRecognizeIntervalMs(); + } catch (Throwable t) { + return TICK_MS; + } + } + + /** 设备设置「重量跳变忽略(斤)」→ kg;失败退回默认 0.2 斤 */ + private static double noiseIgnoreKg() { + try { + if (CanteenApp.get() != null) { + return CanteenApp.get().getWeightNoiseIgnoreKg(); + } + } catch (Throwable ignored) { + } + return CanteenApp.DEFAULT_WEIGHT_NOISE_IGNORE_JIN / 2.0; + } + + public VideoStreamRecognizeHelper(Host host) { + this.host = host; + } + + public void onWeightSample(double kg, boolean hasWeight) { + long now = System.currentTimeMillis(); + if (!hasWeight) { + boolean had = lastHadWeight; + lastHadWeight = false; + lastKg = kg; + prevSampleKg = Double.NaN; + lastKgMoveAt = now; + wasStable = false; + stop(); + if (had) { + host.onRescanNeeded(true); + } + return; + } + // 稳定跟踪 / 换货跳变:阈值来自设备设置「重量跳变忽略(斤)」 + double noiseKg = noiseIgnoreKg(); + if (Double.isNaN(prevSampleKg) || Math.abs(kg - prevSampleKg) > noiseKg) { + lastKgMoveAt = now; + } + prevSampleKg = kg; + boolean jumped = lastHadWeight + && !Double.isNaN(lastKg) + && Math.abs(kg - lastKg) > noiseKg; + double prevJumpRefKg = lastKg; + lastKg = kg; + lastHadWeight = true; + if (jumped) { + wasStable = false; + Log.i(TAG, "weight jumped " + prevJumpRefKg + " -> " + kg); + host.onRescanNeeded(false); + return; + } + if (!running) { + start(); + } + // 从不稳定进入稳定:立即补一拍识别,不用等下一个 2 秒周期 + boolean stableNow = isStable(now); + if (stableNow && !wasStable && running) { + Log.i(TAG, "became stable kg=" + kg + " -> immediate tick"); + requestImmediateTick(); + } + wasStable = stableNow; + } + + public void start() { + if (running) { + return; + } + running = true; + handler.removeCallbacks(tickRunnable); + handler.post(tickRunnable); + } + + public void requestImmediateTick() { + handler.removeCallbacks(tickRunnable); + running = true; + handler.post(tickRunnable); + } + + public void stop() { + running = false; + handler.removeCallbacks(tickRunnable); + } + + public void reset() { + stop(); + lastKg = Double.NaN; + lastHadWeight = false; + prevSampleKg = Double.NaN; + lastKgMoveAt = 0L; + wasStable = false; + } + + public void nudgeIfHasWeight(double kg) { + if (kg <= 0) { + return; + } + if (!running) { + start(); + } + } + + public boolean isRunning() { + return running; + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/crash/CrashGuard.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/crash/CrashGuard.java new file mode 100644 index 0000000..dc36f0b --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/crash/CrashGuard.java @@ -0,0 +1,42 @@ +package com.canteen.weigh.crash; + +import android.app.Application; +import android.util.Log; + +/** + * 安装全局未捕获异常落盘;写完后交给系统默认 handler。 + */ +public final class CrashGuard { + + private static final String TAG = "CrashGuard"; + private static volatile boolean installed; + + private CrashGuard() { + } + + public static void install(final Application app) { + if (app == null || installed) { + return; + } + installed = true; + final Thread.UncaughtExceptionHandler previous = Thread.getDefaultUncaughtExceptionHandler(); + Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { + @Override + public void uncaughtException(Thread t, Throwable e) { + try { + CrashLocalStore.writeJavaCrash(app.getApplicationContext(), t, e); + } catch (Throwable writeErr) { + Log.e(TAG, "crash write failed", writeErr); + } + if (previous != null) { + previous.uncaughtException(t, e); + } else { + // 无默认 handler 时结束进程,避免卡死 + android.os.Process.killProcess(android.os.Process.myPid()); + System.exit(10); + } + } + }); + Log.i(TAG, "installed; dir=" + CrashLocalStore.crashDir(app).getAbsolutePath()); + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/crash/CrashLocalStore.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/crash/CrashLocalStore.java new file mode 100644 index 0000000..1504c06 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/crash/CrashLocalStore.java @@ -0,0 +1,200 @@ +package com.canteen.weigh.crash; + +import android.content.Context; +import android.content.pm.PackageInfo; +import android.os.Build; +import android.util.Log; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.charset.Charset; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +/** + * 崩溃/tombstone 摘要本地落盘(App 专属外置目录,无需额外存储权限)。 + */ +public final class CrashLocalStore { + + private static final String TAG = "CrashLocalStore"; + private static final String DIR_NAME = "crashes"; + private static final int MAX_FILES = 20; + private static final Charset UTF8 = Charset.forName("UTF-8"); + + private CrashLocalStore() { + } + + public static File crashDir(Context context) { + File base = context.getExternalFilesDir(null); + if (base == null) { + base = context.getFilesDir(); + } + File dir = new File(base, DIR_NAME); + if (!dir.exists() && !dir.mkdirs()) { + Log.w(TAG, "mkdir failed: " + dir.getAbsolutePath()); + } + return dir; + } + + public static File writeJavaCrash(Context context, Thread thread, Throwable throwable) { + String stamp = stampNow(); + File out = new File(crashDir(context), "crash_" + stamp + ".txt"); + StringBuilder sb = new StringBuilder(4096); + sb.append("type=java_uncaught\n"); + sb.append("time=").append(stamp).append('\n'); + appendDeviceHeader(context, sb); + sb.append("thread=").append(thread != null ? thread.getName() : "?").append('\n'); + sb.append("message=").append(throwable != null ? String.valueOf(throwable.getMessage()) : "null") + .append('\n'); + sb.append("--- stack ---\n"); + sb.append(stackTrace(throwable)); + return writeText(out, sb.toString()); + } + + /** + * 若进程可读 /data/tombstones,拷贝最近一份摘要(通常需 root;失败静默)。 + */ + public static void tryImportLatestTombstone(Context context) { + File tombs = new File("/data/tombstones"); + if (!tombs.isDirectory() || !tombs.canRead()) { + return; + } + File[] files = tombs.listFiles(); + if (files == null || files.length == 0) { + return; + } + Arrays.sort(files, new Comparator() { + @Override + public int compare(File a, File b) { + long d = b.lastModified() - a.lastModified(); + return d == 0 ? 0 : (d > 0 ? 1 : -1); + } + }); + File newest = files[0]; + if (!newest.isFile() || !newest.canRead()) { + return; + } + String stamp = stampNow(); + File out = new File(crashDir(context), "tombstone_" + stamp + ".txt"); + StringBuilder sb = new StringBuilder(8192); + sb.append("type=tombstone_import\n"); + sb.append("time=").append(stamp).append('\n'); + sb.append("source=").append(newest.getAbsolutePath()).append('\n'); + sb.append("source_mtime=").append(newest.lastModified()).append('\n'); + appendDeviceHeader(context, sb); + sb.append("--- tombstone head ---\n"); + sb.append(readHead(newest, 120)); + writeText(out, sb.toString()); + pruneOld(crashDir(context)); + } + + public static void pruneOld(File dir) { + if (dir == null || !dir.isDirectory()) { + return; + } + File[] files = dir.listFiles(); + if (files == null || files.length <= MAX_FILES) { + return; + } + Arrays.sort(files, new Comparator() { + @Override + public int compare(File a, File b) { + long d = a.lastModified() - b.lastModified(); + return d == 0 ? 0 : (d > 0 ? 1 : -1); + } + }); + int remove = files.length - MAX_FILES; + for (int i = 0; i < remove; i++) { + //noinspection ResultOfMethodCallIgnored + files[i].delete(); + } + } + + private static void appendDeviceHeader(Context context, StringBuilder sb) { + sb.append("package=").append(context.getPackageName()).append('\n'); + try { + PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); + sb.append("versionName=").append(pi.versionName).append('\n'); + sb.append("versionCode=").append(pi.versionCode).append('\n'); + } catch (Throwable ignored) { + sb.append("versionName=?\nversionCode=?\n"); + } + sb.append("sdk=").append(Build.VERSION.SDK_INT).append('\n'); + sb.append("model=").append(Build.MODEL).append('\n'); + sb.append("device=").append(Build.DEVICE).append('\n'); + sb.append("hardware=").append(Build.HARDWARE).append('\n'); + sb.append("fingerprint=").append(Build.FINGERPRINT).append('\n'); + } + + private static String stackTrace(Throwable t) { + if (t == null) { + return "null\n"; + } + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + t.printStackTrace(pw); + pw.flush(); + return sw.toString(); + } + + private static String readHead(File file, int maxLines) { + StringBuilder sb = new StringBuilder(); + BufferedReader br = null; + try { + br = new BufferedReader(new InputStreamReader(new FileInputStream(file), UTF8)); + String line; + int n = 0; + while ((line = br.readLine()) != null && n < maxLines) { + sb.append(line).append('\n'); + n++; + } + } catch (Throwable e) { + sb.append("read_error=").append(e.getMessage()).append('\n'); + } finally { + if (br != null) { + try { + br.close(); + } catch (Throwable ignored) { + } + } + } + return sb.toString(); + } + + private static File writeText(File out, String text) { + FileOutputStream fos = null; + try { + fos = new FileOutputStream(out); + fos.write(text.getBytes(UTF8)); + fos.flush(); + Log.i(TAG, "wrote " + out.getAbsolutePath()); + pruneOld(out.getParentFile()); + return out; + } catch (Throwable e) { + Log.e(TAG, "write failed: " + out, e); + return null; + } finally { + if (fos != null) { + try { + fos.close(); + } catch (Throwable ignored) { + } + } + } + } + + private static String stampNow() { + SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS", Locale.US); + fmt.setTimeZone(TimeZone.getDefault()); + return fmt.format(new Date()); + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/model/ApiResult.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/model/ApiResult.java new file mode 100644 index 0000000..c39c560 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/model/ApiResult.java @@ -0,0 +1,12 @@ +package com.canteen.weigh.model; + +/** + * 通用 API 响应包装 + */ +public class ApiResult { + + public boolean success; + public T data; + public String error; + public String errorDescription; +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/model/InspectionTask.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/model/InspectionTask.java new file mode 100644 index 0000000..39b1ec2 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/model/InspectionTask.java @@ -0,0 +1,31 @@ +package com.canteen.weigh.model; + +/** + * 验收 / 验收台待验任务 + */ +public class InspectionTask { + + public String id; + public String orderCode; + public String skuCode; + public String itemName; + public String supplierCode; + public String supplierName; + public double prepareQty; + /** 同订单 SKU 已累计入库量(分批入库) */ + public double receivedQty; + /** 净需求总量 = 已入 + 本次待入 */ + public double totalDemandQty; + public String unit; + public double purchasePrice; + public String sourceType; + public boolean isPrepackaged; + public String brand; + public int sortOrder; + + // 是否要求拍照(分类 requires_photo_inspection,默认 true) + public boolean photoRequired = true; + public int inspectionPhotoCount; + public boolean requiresPrepackagedCheck; + public Object prepackagedScan; +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/model/PickingItem.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/model/PickingItem.java new file mode 100644 index 0000000..1556a05 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/model/PickingItem.java @@ -0,0 +1,22 @@ +package com.canteen.weigh.model; + +/** + * 分拣台待拣明细 + */ +public class PickingItem { + + public String id; + public String pickCode; + public String orderCode; + public String itemName; + public String skuCode; + public double requiredQty; + public double pickedQty; + public double pickedWeight; + public String unit; + public int reviewStatus; + public int sortOrder; + public String companyName; + public String customerCode; + public String barcode; +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/model/PickingTask.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/model/PickingTask.java new file mode 100644 index 0000000..81ac954 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/model/PickingTask.java @@ -0,0 +1,12 @@ +package com.canteen.weigh.model; + +/** + * 分拣任务模型 + */ +public class PickingTask { + + public String pickCode; + public String orderCode; + public String status; + public String createdAt; +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/print/CaysnUsbPrinter.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/print/CaysnUsbPrinter.java new file mode 100644 index 0000000..85b77fd --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/print/CaysnUsbPrinter.java @@ -0,0 +1,250 @@ +package com.canteen.weigh.print; + +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.graphics.Bitmap; +import android.hardware.usb.UsbDevice; +import android.hardware.usb.UsbManager; +import android.os.Build; +import android.util.Log; + +import com.caysn.autoreplyprint.AutoReplyPrint; +import com.sun.jna.Pointer; + +import java.util.HashMap; +import java.util.Locale; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Caysn AutoReplyPrint · USB 标签机 + * 现场机型:KC.EC / KCEC-USB(VID 0x4B43) + */ +public final class CaysnUsbPrinter { + + private static final String TAG = "CaysnUsbPrinter"; + private static final String ACTION_USB_PERMISSION = "com.canteen.weigh.USB_PERMISSION"; + + /** Caysn / KC */ + private static final int VID_CAYSN = 0x4B43; + /** 常见兼容芯片 */ + private static final int VID_ALT = 0x0FE6; + + /** 打印锁:防止并发调用 native 打印导致 USB 冲突/系统崩溃 */ + private static final Object PRINT_LOCK = new Object(); + + private CaysnUsbPrinter() { + } + + public static String describeUsbPrinter(Context context) { + UsbDevice device = findUsbPrinterDevice(context); + if (device == null) { + return "未检测到 USB 标签机(VID 0x4B43/0x0FE6)"; + } + return String.format(Locale.US, "%s (%s) VID=0x%04X PID=0x%04X", + device.getProductName() != null ? device.getProductName() : "USBPrinter", + device.getDeviceName(), + device.getVendorId(), + device.getProductId()); + } + + public static boolean printBitmap(Context context, Bitmap bitmap) { + if (bitmap == null || bitmap.isRecycled()) { + Log.e(TAG, "bitmap null or recycled"); + return false; + } + synchronized (PRINT_LOCK) { + Context app = context.getApplicationContext(); + if (!hasUsbPermission(app)) { + Log.e(TAG, "USB permission not granted, skip print"); + return false; + } + + // 打印前短暂等待,让 USB 总线从秤的串口读取中释放,避免总线冲突导致平板重启 + try { + Thread.sleep(120); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + + Pointer handle = null; + try { + String address = pickUsbPortAddress(); + if (address == null || address.trim().isEmpty()) { + Log.e(TAG, "EnumUsb found no Caysn printer"); + return false; + } + Log.d(TAG, "Opening USB: " + address); + handle = AutoReplyPrint.INSTANCE.CP_Port_OpenUsb(address, 1); + if (handle == null) { + Log.e(TAG, "CP_Port_OpenUsb failed: " + address); + return false; + } + + // 降低打印浓度和速度,减少加热瞬时电流,避免 USB 总线供电不足导致平板重启 + // 浓度设为 5(范围 0-15,默认约 10),速度 60mm/s + AutoReplyPrint.INSTANCE.CP_Pos_SetPrintDensity(handle, 5); + AutoReplyPrint.INSTANCE.CP_Pos_SetPrintSpeed(handle, 60); + Log.d(TAG, "Print density=5 speed=60mm/s"); + + int pageW = PrintManager.paperWidthDots(); + int paperH = PrintManager.paperHeightDots(); + int dstW = Math.min(bitmap.getWidth(), pageW); + int dstH = Math.min(bitmap.getHeight(), paperH); + /* + * 页高跟位图,并留约 2mm 给间隙寻缝:打完当前张由固件送到缝, + * 不再用整张纸高 PageBegin(打满后再寻缝会空走下一张)。 + */ + int gapReserve = PrintManager.gapReserveDots(); + int pageH = Math.min(dstH, paperH - gapReserve); + if (pageH < 80) { + pageH = Math.min(dstH, paperH); + } + int drawH = Math.min(dstH, pageH); + Log.d(TAG, "printBitmap dst=" + dstW + "x" + drawH + + " page=" + pageW + "x" + pageH + " paperH=" + paperH); + + AutoReplyPrint.INSTANCE.CP_Label_EnableLabelMode(handle); + boolean ok = AutoReplyPrint.INSTANCE.CP_Label_PageBegin(handle, 0, 0, + pageW, pageH, 0); + ok = ok && AutoReplyPrint.CP_Label_DrawImageFromData_Helper.DrawImageFromBitmap( + handle, + 0, + 0, + dstW, + drawH, + bitmap, + AutoReplyPrint.CP_ImageBinarizationMethod_ErrorDiffusion, + AutoReplyPrint.CP_ImageCompressionMethod_None); + ok = ok && AutoReplyPrint.INSTANCE.CP_Label_PagePrint(handle, 1); + Log.d(TAG, "LabelPage " + dstW + "x" + drawH + " on " + pageW + "x" + pageH + " page: " + ok); + + Log.d(TAG, ok ? "PrintSuccess" : "PrintFailed"); + return ok; + } catch (OutOfMemoryError oom) { + Log.e(TAG, "printBitmap OOM", oom); + return false; + } catch (Throwable t) { + Log.e(TAG, "printBitmap failed", t); + return false; + } finally { + if (handle != null) { + try { + AutoReplyPrint.INSTANCE.CP_Port_Close(handle); + } catch (Throwable ignored) { + } + } + } + } + } + + /** 检查是否已有 USB 权限(不弹窗) */ + public static boolean hasUsbPermission(Context context) { + UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE); + UsbDevice device = findUsbPrinterDevice(context); + if (usbManager == null || device == null) { + return false; + } + return usbManager.hasPermission(device); + } + + private static String pickUsbPortAddress() { + String[] list = AutoReplyPrint.CP_Port_EnumUsb_Helper.EnumUsb(); + if (list == null || list.length == 0) { + return null; + } + String fallback = null; + for (String s : list) { + if (s == null) continue; + String u = s.toUpperCase(Locale.US); + Log.d(TAG, "EnumUsb: " + s); + if (u.contains("4B43") || u.contains("0X4B43") || u.contains("0FE6") || u.contains("0X0FE6")) { + return s; + } + if (fallback == null) { + fallback = s; + } + } + // 仅一台 USB 打印设备时直接用 + return list.length == 1 ? list[0] : fallback; + } + + static UsbDevice findUsbPrinterDevice(Context context) { + UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE); + if (usbManager == null) return null; + HashMap map = usbManager.getDeviceList(); + if (map == null) return null; + for (UsbDevice device : map.values()) { + int vid = device.getVendorId(); + if (vid == VID_CAYSN || vid == VID_ALT) { + return device; + } + } + return null; + } + + /** 主线程请求 USB 权限(弹系统框),子线程禁止调用 */ + public static boolean requestUsbPermissionOnUiThread(Context context) { + return ensureUsbPermission(context); + } + + /** 主线程专用:弹权限框并等待用户授权;子线程调用会直接返回 false */ + private static boolean ensureUsbPermission(Context context) { + if (android.os.Looper.myLooper() != android.os.Looper.getMainLooper()) { + Log.e(TAG, "ensureUsbPermission must be called on UI thread"); + return false; + } + UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE); + UsbDevice device = findUsbPrinterDevice(context); + if (usbManager == null || device == null) { + return false; + } + if (usbManager.hasPermission(device)) { + return true; + } + + final CountDownLatch latch = new CountDownLatch(1); + final AtomicBoolean granted = new AtomicBoolean(false); + BroadcastReceiver receiver = new BroadcastReceiver() { + @Override + public void onReceive(Context ctx, Intent intent) { + if (!ACTION_USB_PERMISSION.equals(intent.getAction())) { + return; + } + UsbDevice d = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); + boolean ok = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false); + if (ok && d != null) { + granted.set(true); + } + latch.countDown(); + } + }; + + IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION); + context.registerReceiver(receiver, filter); + + // FLAG_IMMUTABLE = 0x04000000,API 31+ + int flags = PendingIntent.FLAG_UPDATE_CURRENT; + if (Build.VERSION.SDK_INT >= 31) { + flags |= 0x04000000; + } + PendingIntent pi = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), flags); + usbManager.requestPermission(device, pi); + + try { + latch.await(20, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + try { + context.unregisterReceiver(receiver); + } catch (Exception ignored) { + } + return granted.get() || usbManager.hasPermission(device); + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/print/LabelQrEncoder.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/print/LabelQrEncoder.java new file mode 100644 index 0000000..6acc42e --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/print/LabelQrEncoder.java @@ -0,0 +1,55 @@ +package com.canteen.weigh.print; + +import android.graphics.Bitmap; +import android.graphics.Color; +import android.util.Log; + +import com.google.zxing.BarcodeFormat; +import com.google.zxing.EncodeHintType; +import com.google.zxing.common.BitMatrix; +import com.google.zxing.qrcode.QRCodeWriter; +import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; + +import java.util.EnumMap; +import java.util.Map; + +/** + * 标签二维码(内容一般为 container_code) + */ +public final class LabelQrEncoder { + + private static final String TAG = "LabelQrEncoder"; + + private LabelQrEncoder() { + } + + public static Bitmap encode(String content, int sizePx) { + String text = content == null ? "" : content.trim(); + if (text.isEmpty() || sizePx <= 0) { + return null; + } + try { + Map hints = new EnumMap<>(EncodeHintType.class); + hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); + hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); + hints.put(EncodeHintType.MARGIN, 1); + + BitMatrix matrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, sizePx, sizePx, hints); + int w = matrix.getWidth(); + int h = matrix.getHeight(); + int[] pixels = new int[w * h]; + for (int y = 0; y < h; y++) { + int offset = y * w; + for (int x = 0; x < w; x++) { + pixels[offset + x] = matrix.get(x, y) ? Color.BLACK : Color.WHITE; + } + } + Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); + bitmap.setPixels(pixels, 0, w, 0, 0, w, h); + return bitmap; + } catch (Exception e) { + Log.e(TAG, "QR encode failed: " + text, e); + return null; + } + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/print/PrintJobPoller.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/print/PrintJobPoller.java new file mode 100644 index 0000000..4afa800 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/print/PrintJobPoller.java @@ -0,0 +1,201 @@ +package com.canteen.weigh.print; + +import android.app.Activity; +import android.os.Handler; +import android.os.Looper; +import android.util.Log; + +import com.canteen.weigh.CanteenApp; +import com.canteen.weigh.api.ApiClient; +import com.canteen.weigh.api.PrintJobApi; + +import org.json.JSONObject; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * 仅在分拣工作台前台轮询 Web 远程打印任务。 + * 服务端 GET pending 即 claimed,拿到任务后必须打印并 ack,即使此时已离开页面。 + * USB 只打一遍;ack 失败可重试,不再调用 printPickingLabel。 + */ +public class PrintJobPoller { + + private static final String TAG = "PrintJobPoller"; + private static final long INTERVAL_MS = 4000L; + private static final int ACK_RETRY_MAX = 3; + private static final long ACK_RETRY_INTERVAL_MS = 1000L; + + private final Activity activity; + private final Handler handler = new Handler(Looper.getMainLooper()); + private boolean running; + private boolean busy; + + public PrintJobPoller(Activity activity) { + this.activity = activity; + } + + public void start() { + if (running) { + return; + } + running = true; + handler.post(tick); + } + + public void stop() { + running = false; + handler.removeCallbacks(tick); + } + + private final Runnable tick = new Runnable() { + @Override + public void run() { + if (!running) { + return; + } + pollOnce(); + handler.postDelayed(this, INTERVAL_MS); + } + }; + + private void pollOnce() { + if (busy || !CanteenApp.get().isLoggedIn()) { + return; + } + busy = true; + PrintJobApi.fetchPending(new ApiClient.ApiCallback() { + @Override + public void onSuccess(int code, String body) { + handlePendingBody(body); + } + + @Override + public void onError(int code, String message) { + Log.w(TAG, "poll pending failed: " + message); + busy = false; + } + }); + } + + private void handlePendingBody(String body) { + try { + JSONObject obj = new JSONObject(body); + if (obj.isNull("data")) { + busy = false; + return; + } + JSONObject data = obj.optJSONObject("data"); + if (data == null) { + busy = false; + return; + } + final String jobId = data.optString("id", ""); + JSONObject payload = data.optJSONObject("payload"); + if (jobId.isEmpty()) { + busy = false; + return; + } + if (payload == null) { + ackThenIdle(jobId, "failed", "打印内容缺失"); + return; + } + printAndAck(jobId, payload); + } catch (Exception e) { + Log.w(TAG, "parse pending", e); + busy = false; + } + } + + private void ackThenIdle(final String jobId, final String status, final String error) { + new Thread(new Runnable() { + @Override + public void run() { + ackWithRetriesBlocking(jobId, status, error); + busy = false; + } + }).start(); + } + + private void ackWithRetriesBlocking(String jobId, String status, String error) { + for (int attempt = 1; attempt <= ACK_RETRY_MAX; attempt += 1) { + final CountDownLatch latch = new CountDownLatch(1); + final boolean[] ok = new boolean[] { false }; + PrintJobApi.ack(jobId, status, error, new ApiClient.ApiCallback() { + @Override + public void onSuccess(int code, String body) { + ok[0] = true; + latch.countDown(); + } + + @Override + public void onError(int code, String message) { + Log.w(TAG, "ack failed: " + message); + latch.countDown(); + } + }); + try { + latch.await(25, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + if (ok[0]) { + return; + } + if (attempt < ACK_RETRY_MAX) { + try { + Thread.sleep(ACK_RETRY_INTERVAL_MS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + } + } + + private void printAndAck(final String jobId, final JSONObject payload) { + new Thread(new Runnable() { + @Override + public void run() { + boolean ok = false; + String err = null; + try { + String company = payload.optString("company_name", "客户"); + String orderCode = payload.optString("order_code", ""); + String itemName = payload.optString("item_name", "商品"); + double weight = payload.optDouble("weight", 0); + String unit = payload.optString("unit", "kg"); + String date = payload.optString("date", ""); + String barcode = payload.optString("barcode", ""); + if (barcode == null || barcode.isEmpty()) { + barcode = payload.optString("job_code", jobId); + } + int copies = payload.optInt("copies", 1); + if (copies < 1) { + copies = 1; + } + if (copies > 20) { + copies = 20; + } + ok = true; + for (int i = 0; i < copies; i += 1) { + boolean one = PrintManager.printPickingLabel( + activity, company, orderCode, itemName, weight, unit, date, barcode); + if (!one) { + ok = false; + err = "USB 标签机打印失败"; + break; + } + } + } catch (Throwable t) { + err = t.getMessage(); + ok = false; + } + final String status = ok ? "done" : "failed"; + ackWithRetriesBlocking(jobId, status, err); + busy = false; + } + }).start(); + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/print/PrintManager.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/print/PrintManager.java new file mode 100644 index 0000000..5f40793 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/print/PrintManager.java @@ -0,0 +1,346 @@ +package com.canteen.weigh.print; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.Typeface; +import android.util.Log; + +import com.canteen.weigh.weigh.WeighStationMatcher; + +import java.util.Locale; + +/** + * 打印管理器:封装 USB 标签机(Caysn AutoReplyPrint) + * + * 现场纸张默认 50×30mm @8dot/mm(见 docs/design/20260908-weigh-label-30mm-one-sheet.md) + */ +public class PrintManager { + + private static final String TAG = "PrintManager"; + + /** 203dpi 常见 8 点/mm */ + public static final int DOTS_PER_MM = 8; + /** 回落幅面:宽 50mm、高 30mm */ + private static final int LABEL_WIDTH_MM = 50; + private static final int LABEL_HEIGHT_MM = 30; + public static final int LABEL_WIDTH_DOTS = LABEL_WIDTH_MM * DOTS_PER_MM; // 400 + public static final int LABEL_HEIGHT_DOTS = LABEL_HEIGHT_MM * DOTS_PER_MM; // 240 + + /** 页高相对纸高预留,供间隙寻缝停在当前张(约 2mm) */ + public static int gapReserveDots() { + return 2 * DOTS_PER_MM; + } + + /** 设备设置里选择的纸张宽(点);未设置回落 50mm */ + public static int paperWidthDots() { + try { + return com.canteen.weigh.CanteenApp.get().getLabelPaperWidthMm() * DOTS_PER_MM; + } catch (Throwable t) { + return LABEL_WIDTH_DOTS; + } + } + + /** 设备设置里选择的纸张高(点);未设置回落 30mm */ + public static int paperHeightDots() { + try { + return com.canteen.weigh.CanteenApp.get().getLabelPaperHeightMm() * DOTS_PER_MM; + } catch (Throwable t) { + return LABEL_HEIGHT_DOTS; + } + } + + /** + * 设备设置页测试样张 + */ + public static boolean printTestLabel(Context context) { + return printPickingLabel( + context, + "测试食堂", + "TEST-ORDER", + "测试商品", + 1.234, + "kg", + new java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.CHINA) + .format(new java.util.Date()), + "TEST-BARCODE" + ); + } + + /** + * 打印分拣标签:客户/食堂、品名、重量、日期、条码(不含订单号) + * + * @param orderCode 保留入参兼容调用方,版式不绘制 + */ + public static boolean printPickingLabel(Context context, + String companyName, + String orderCode, + String itemName, + double weightKg, + String unit, + String date, + String barcode) { + try { + Bitmap bitmap = buildPickingLabelBitmap(companyName, itemName, weightKg, unit, date, barcode); + return doPrint(context, bitmap); + } catch (Exception e) { + Log.e(TAG, "打印分拣标签失败", e); + return false; + } + } + + private static Bitmap buildPickingLabelBitmap(String companyName, + String itemName, + double weightKg, + String unit, + String date, + String barcode) { + // 宽/高按设备设置的纸张尺寸;高度=内容+少量底边(满整页易多出一张) + int width = paperWidthDots(); + int maxHeight = paperHeightDots(); + /** 内容下方白边约 4mm;撕纸口由当前张寻缝送出 */ + int ejectMarginDots = 4 * DOTS_PER_MM; + int maxPrintHeight = Math.max(80, maxHeight - gapReserveDots()); + int padding = 8; + int qrSize = 110; + int gap = 8; + int textMaxW = width - padding * 2 - qrSize - gap; + int lineHeight = 28; + + // 先按内容高度排版,避免一次性创建大 Bitmap 导致 OOM + int contentHeight = padding + 24 + lineHeight * 4 + 4 + qrSize + padding + ejectMarginDots; + int bitmapHeight = Math.min(contentHeight, maxPrintHeight); + Bitmap full = Bitmap.createBitmap(width, bitmapHeight, Bitmap.Config.ARGB_8888); + Canvas canvas = new Canvas(full); + canvas.drawColor(Color.WHITE); + + Paint paint = new Paint(); + paint.setAntiAlias(true); + paint.setColor(Color.BLACK); + paint.setTextAlign(Paint.Align.LEFT); + + float y = padding + 24; + paint.setTextSize(24); + paint.setTypeface(Typeface.DEFAULT_BOLD); + canvas.drawText("分拣标签", padding, y, paint); + y += lineHeight; + + paint.setTextSize(20); + paint.setTypeface(Typeface.DEFAULT); + canvas.drawText(ellipsize(paint, "客户:" + safe(companyName), textMaxW), padding, y, paint); + y += lineHeight; + canvas.drawText(ellipsize(paint, "品名:" + safe(itemName), textMaxW), padding, y, paint); + y += lineHeight + 2; + + paint.setTextSize(26); + paint.setTypeface(Typeface.DEFAULT_BOLD); + String weightLine = formatLabelWeightLine(weightKg, unit); + canvas.drawText(ellipsize(paint, weightLine, textMaxW), padding, y, paint); + y += lineHeight; + + paint.setTextSize(18); + paint.setTypeface(Typeface.DEFAULT); + canvas.drawText(ellipsize(paint, "日期:" + safe(date), textMaxW), padding, y, paint); + Paint.FontMetrics dateFm = paint.getFontMetrics(); + float textBottom = y + dateFm.descent + 2; + + String code = safe(barcode); + int qrX = width - padding - qrSize; + int qrY = padding + 8; + Bitmap qr = LabelQrEncoder.encode(code, qrSize); + if (qr != null) { + canvas.drawBitmap(qr, qrX, qrY, null); + if (!qr.isRecycled()) { + qr.recycle(); + } + } + + paint.setTextSize(14); + String codeLine = code; + while (codeLine.length() > 4 && paint.measureText(codeLine) > qrSize) { + codeLine = codeLine.substring(0, codeLine.length() - 1); + } + if (!codeLine.equals(code) && codeLine.length() > 3) { + codeLine = codeLine.substring(0, Math.max(1, codeLine.length() - 1)) + "…"; + } + float codeX = qrX + Math.max(0, (qrSize - paint.measureText(codeLine)) / 2f); + float codeY = qrY + qrSize + 16; + canvas.drawText(codeLine, codeX, codeY, paint); + Paint.FontMetrics codeFm = paint.getFontMetrics(); + float codeBottom = codeY + codeFm.descent + 2; + + int contentBottom = (int) Math.ceil(Math.max(textBottom, codeBottom)) + padding; + contentBottom = Math.max(contentBottom, qrY + qrSize + padding); + int printHeight = Math.min(maxPrintHeight, contentBottom + ejectMarginDots); + printHeight = Math.max(printHeight, contentBottom); + printHeight = Math.min(printHeight, maxHeight); + // 裁剪到实际内容高度,避免多走空白标签纸(对齐 buildLabelBitmap 策略) + if (printHeight < bitmapHeight) { + Bitmap cropped = Bitmap.createBitmap(full, 0, 0, width, printHeight); + full.recycle(); + Log.d(TAG, "picking label " + width + "x" + printHeight + + " (content~" + contentBottom + ", eject+" + ejectMarginDots + ")"); + return cropped; + } + Log.d(TAG, "label bitmap " + width + "x" + bitmapHeight + + " (content~" + contentBottom + ", eject+" + ejectMarginDots + ")"); + return full; + } + + private static String ellipsize(Paint paint, String text, float maxWidth) { + if (text == null) return ""; + if (maxWidth <= 0 || paint.measureText(text) <= maxWidth) return text; + String ellipsis = "..."; + int end = text.length(); + while (end > 0 && paint.measureText(text.substring(0, end) + ellipsis) > maxWidth) { + end--; + } + return end <= 0 ? ellipsis : text.substring(0, end) + ellipsis; + } + + private static String safe(String v) { + return v == null ? "" : v; + } + + /** + * 打印验收标签 + * + * @param context Context + * @param orderCode 订单号 + * @param itemName 商品名称 + * @param weightKg 重量(kg) + * @param unit 单位 + * @param supplier 供应商 + */ + public static boolean printInspectionLabel(Context context, + String orderCode, + String itemName, + double weightKg, + String unit, + String supplier) { + try { + Bitmap bitmap = buildLabelBitmap(orderCode, itemName, weightKg, unit, supplier); + return doPrint(context, bitmap); + } catch (Exception e) { + Log.e(TAG, "打印标签失败", e); + return false; + } + } + + /** + * 构建验收标签位图(默认 50×30mm;底部少量白边,撕纸靠当前张寻缝) + */ + private static Bitmap buildLabelBitmap(String orderCode, + String itemName, + double weightKg, + String unit, + String supplier) { + int width = paperWidthDots(); + int maxHeight = paperHeightDots(); + /** 内容下方白边约 4mm;撕纸口由当前张寻缝送出 */ + int ejectMarginDots = 4 * DOTS_PER_MM; + int lineHeight = 26; + int padding = 8; + int maxPrintHeight = Math.max(80, maxHeight - gapReserveDots()); + + Bitmap full = Bitmap.createBitmap(width, maxHeight, Bitmap.Config.ARGB_8888); + Canvas canvas = new Canvas(full); + canvas.drawColor(Color.WHITE); + + Paint paint = new Paint(); + paint.setAntiAlias(true); + paint.setColor(Color.BLACK); + + float y = padding + 22; + + paint.setTextSize(22); + paint.setTypeface(Typeface.DEFAULT_BOLD); + canvas.drawText("验收标签", padding, y, paint); + y += lineHeight; + + paint.setTextSize(18); + paint.setTypeface(Typeface.DEFAULT); + canvas.drawText("订单:" + (orderCode != null ? orderCode : ""), padding, y, paint); + y += lineHeight; + + paint.setTextSize(18); + String displayName = itemName != null ? itemName : ""; + if (paint.measureText(displayName) > width - padding * 2) { + displayName = displayName.substring(0, Math.min(displayName.length(), 18)) + "..."; + } + canvas.drawText("商品:" + displayName, padding, y, paint); + y += lineHeight + 2; + + paint.setTextSize(26); + paint.setTypeface(Typeface.DEFAULT_BOLD); + canvas.drawText(formatLabelWeightLine(weightKg, unit), padding, y, paint); + y += lineHeight + 2; + + paint.setTextSize(16); + paint.setTypeface(Typeface.DEFAULT); + canvas.drawText("供应商:" + (supplier != null ? supplier : ""), padding, y, paint); + y += lineHeight; + + String timeStr = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm", java.util.Locale.CHINA) + .format(new java.util.Date()); + canvas.drawText("时间:" + timeStr, padding, y, paint); + Paint.FontMetrics fm = paint.getFontMetrics(); + int contentBottom = (int) Math.ceil(y + fm.descent) + padding; + + int printHeight = Math.min(maxPrintHeight, contentBottom + ejectMarginDots); + printHeight = Math.max(printHeight, contentBottom); + printHeight = Math.min(printHeight, maxHeight); + if (printHeight < maxHeight) { + Bitmap cropped = Bitmap.createBitmap(full, 0, 0, width, printHeight); + full.recycle(); + Log.d(TAG, "inspection label " + width + "x" + printHeight + + " (content~" + contentBottom + ", eject+" + ejectMarginDots + ")"); + return cropped; + } + return full; + } + + /** + * 标签重量/数量行:重量单位统一显示为「斤」,计数单位显示「数量:N 单位」。 + * 入参 weight 随 unit 同口径(unit=公斤则 weight 为 kg;unit=斤则 weight 为斤)。 + */ + private static String formatLabelWeightLine(double weight, String unit) { + String u = unit != null ? unit.trim() : ""; + if (!WeighStationMatcher.isWeightUnit(u)) { + // 计数单位(瓶/个/份等):显示数量 + return String.format(Locale.US, "数量:%.2f %s", weight, + WeighStationMatcher.displayUnit(u)); + } + // 重量单位 → 统一换算成斤展示 + double kg; + if (WeighStationMatcher.isJinUnit(u)) { + kg = weight / 2.0; // 斤 → kg + } else if (WeighStationMatcher.isGramUnit(u)) { + kg = weight / 1000.0; // 克 → kg + } else { + kg = weight; // kg/公斤/千克/空 → kg + } + double jin = kg * 2.0; + return String.format(Locale.US, "重量:%.2f 斤", jin); + } + + private static boolean doPrint(Context context, Bitmap bitmap) { + try { + boolean ok = CaysnUsbPrinter.printBitmap(context, bitmap); + if (!ok) { + Log.w(TAG, "打印失败:" + CaysnUsbPrinter.describeUsbPrinter(context)); + } + return ok; + } catch (Throwable t) { + Log.e(TAG, "调用打印 SDK 失败", t); + return false; + } finally { + // 打印完成后回收 bitmap,避免内存泄漏(native 打印后不再需要) + if (bitmap != null && !bitmap.isRecycled()) { + bitmap.recycle(); + } + } + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/ButtonClickEffect.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/ButtonClickEffect.java new file mode 100644 index 0000000..b1e119c --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/ButtonClickEffect.java @@ -0,0 +1,72 @@ +package com.canteen.weigh.ui; + +import android.graphics.drawable.Drawable; +import android.graphics.drawable.StateListDrawable; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; + +import com.canteen.weigh.R; + +/** + * 为界面内所有 Button 绑定按下缩放 + 缺省背景 selector。 + */ +public final class ButtonClickEffect { + + private ButtonClickEffect() { + } + + public static void apply(View root) { + if (root == null) { + return; + } + if (root instanceof ViewGroup) { + ViewGroup group = (ViewGroup) root; + for (int i = 0; i < group.getChildCount(); i++) { + apply(group.getChildAt(i)); + } + } + if (root instanceof Button) { + bind((Button) root); + } + } + + private static void bind(Button button) { + ensureSelectorBackground(button); + if (button.getTag(R.id.tag_button_click_effect) != null) { + return; + } + button.setTag(R.id.tag_button_click_effect, Boolean.TRUE); + button.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + if (!v.isEnabled()) { + return false; + } + switch (event.getActionMasked()) { + case MotionEvent.ACTION_DOWN: + v.animate().scaleX(0.96f).scaleY(0.96f).setDuration(80).start(); + break; + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: + v.animate().scaleX(1f).scaleY(1f).setDuration(100).start(); + break; + default: + break; + } + return false; + } + }); + } + + private static void ensureSelectorBackground(Button button) { + Drawable bg = button.getBackground(); + if (bg instanceof StateListDrawable) { + return; + } + if (bg == null) { + button.setBackgroundResource(R.drawable.btn_bg_default); + } + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/DeviceSettingsActivity.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/DeviceSettingsActivity.java new file mode 100644 index 0000000..d5bb2aa --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/DeviceSettingsActivity.java @@ -0,0 +1,660 @@ +package com.canteen.weigh.ui; + +import android.Manifest; +import android.content.pm.PackageManager; +import android.os.Build; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.v4.app.ActivityCompat; +import android.support.v4.content.ContextCompat; +import android.support.v7.app.AppCompatActivity; +import android.text.TextUtils; +import android.view.MotionEvent; +import android.view.TextureView; +import android.view.View; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.RadioGroup; +import android.widget.Spinner; +import android.widget.TextView; +import android.widget.Toast; + +import com.canteen.weigh.CanteenApp; +import com.canteen.weigh.DeviceProfile; +import com.canteen.weigh.R; +import com.canteen.weigh.camera.SimpleCameraHelper; +import com.canteen.weigh.camera.UsbCameraHotplugGuard; +import com.canteen.weigh.print.CaysnUsbPrinter; +import com.canteen.weigh.print.PrintManager; +import com.canteen.weigh.update.WeighAppUpdateHelper; +import com.canteen.weigh.weigh.WeighManager; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * 设备设置:机型预设 + 串口/波特率 + 摄像头预览调试 + 测试连接 + */ +public class DeviceSettingsActivity extends AppCompatActivity + implements SimpleCameraHelper.PreviewCallback, UsbCameraHotplugGuard.Callback { + + private static final int REQ_CAMERA = 2101; + + private RadioGroup rgProfile; + private Spinner spSerialPort; + private EditText etSerialPort; + private EditText etBaudRate; + private EditText etRecognizeInterval; + private EditText etWeightNoiseIgnore; + private Spinner spCaptureDistance; + private EditText etOtaManifestUrl; + private TextView tvAppVersion; + private Button btnCheckUpdate; + private Button btnTest; + private Button btnSave; + private Button btnBack; + private Button btnTestPrint; + private TextView tvPrinterStatus; + private TextureView svSettingsCamera; + private TextView tvSettingsCameraHint; + private Button btnSettingsOpenCamera; + private Button btnSettingsCloseCamera; + private Spinner spPaperSize; + private View llPaperCustom; + private EditText etPaperWidth; + private EditText etPaperHeight; + private Spinner spScaleUnit; + private TextView tvPrintDeviceId; + private EditText etPrintDeviceName; + + /** 常用标签纸(宽×高 mm),最后一项为自定义 */ + private static final String[] PAPER_LABELS = { + "50×30 mm(默认)", "50×50 mm", "40×30 mm", "60×40 mm", "70×50 mm", "80×60 mm", "自定义" + }; + private static final int[][] PAPER_DIMS = { + {50, 30}, {50, 50}, {40, 30}, {60, 40}, {70, 50}, {80, 60}, {0, 0} + }; + /** 秤输出单位选项 */ + private static final String[] SCALE_UNIT_LABELS = { "kg(公斤)", "斤(市斤)", "g(克)" }; + private static final String[] CAPTURE_DISTANCE_LABELS = { + "远(看全画面)", "较远", "标准(默认)", "近(放大货物)", "更近" + }; + private static final String[] CAPTURE_DISTANCE_VALUES = { + CanteenApp.CAPTURE_DISTANCE_FAR, + CanteenApp.CAPTURE_DISTANCE_MID_FAR, + CanteenApp.CAPTURE_DISTANCE_STANDARD, + CanteenApp.CAPTURE_DISTANCE_NEAR, + CanteenApp.CAPTURE_DISTANCE_CLOSER + }; + private static final String[] SCALE_UNIT_VALUES = { "kg", "jin", "g" }; + + private SimpleCameraHelper cameraHelper; + private UsbCameraHotplugGuard usbHotplugGuard; + + private final List portList = new ArrayList<>(); + private boolean suppressSpinnerCallback = false; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_device_settings); + ButtonClickEffect.apply(findViewById(android.R.id.content)); + SoftInputHelper.enableBlankFocus(findViewById(android.R.id.content)); + SoftInputHelper.keepFocusedAboveIme(this); + + rgProfile = findViewById(R.id.rg_profile); + spSerialPort = findViewById(R.id.sp_serial_port); + etSerialPort = findViewById(R.id.et_serial_port); + etBaudRate = findViewById(R.id.et_baud_rate); + etRecognizeInterval = findViewById(R.id.et_recognize_interval); + etWeightNoiseIgnore = findViewById(R.id.et_weight_noise_ignore); + spCaptureDistance = findViewById(R.id.sp_capture_distance); + etOtaManifestUrl = findViewById(R.id.et_ota_manifest_url); + tvAppVersion = findViewById(R.id.tv_app_version); + btnCheckUpdate = findViewById(R.id.btn_check_update); + btnTest = findViewById(R.id.btn_test); + btnSave = findViewById(R.id.btn_save); + btnBack = findViewById(R.id.btn_back); + btnTestPrint = findViewById(R.id.btn_test_print); + tvPrinterStatus = findViewById(R.id.tv_printer_status); + svSettingsCamera = findViewById(R.id.sv_settings_camera); + tvSettingsCameraHint = findViewById(R.id.tv_settings_camera_hint); + btnSettingsOpenCamera = findViewById(R.id.btn_settings_open_camera); + btnSettingsCloseCamera = findViewById(R.id.btn_settings_close_camera); + spPaperSize = findViewById(R.id.sp_paper_size); + llPaperCustom = findViewById(R.id.ll_paper_custom); + etPaperWidth = findViewById(R.id.et_paper_width); + etPaperHeight = findViewById(R.id.et_paper_height); + spScaleUnit = findViewById(R.id.sp_scale_unit); + tvPrintDeviceId = findViewById(R.id.tv_print_device_id); + etPrintDeviceName = findViewById(R.id.et_print_device_name); + + usbHotplugGuard = new UsbCameraHotplugGuard(this, this); + usbHotplugGuard.register(); + + // 提前申请 USB 打印机权限(主线程弹窗),避免打印时在子线程弹窗导致崩溃 + CaysnUsbPrinter.requestUsbPermissionOnUiThread(this); + + loadPortSpinner(); + bindPaperSizeSpinner(); + bindScaleUnitSpinner(); + bindCaptureDistanceSpinner(); + bindCurrentConfig(); + refreshPrinterStatus(); + + rgProfile.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(RadioGroup group, int checkedId) { + DeviceProfile profile = profileFromCheckedId(checkedId); + if (profile != DeviceProfile.CUSTOM) { + applyPortToUi(profile.getDefaultSerialPort()); + etBaudRate.setText(String.valueOf(profile.getDefaultBaudRate())); + } + } + }); + + spSerialPort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (suppressSpinnerCallback) { + return; + } + if (position >= 0 && position < portList.size()) { + String port = portList.get(position); + if (!"(手填)".equals(port)) { + etSerialPort.setText(port); + } + } + } + + @Override + public void onNothingSelected(AdapterView parent) { + } + }); + + btnTest.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + doTest(); + } + }); + btnSave.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + doSave(); + } + }); + btnCheckUpdate.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + String url = etOtaManifestUrl.getText().toString().trim(); + CanteenApp.get().saveOtaManifestUrl(url); + WeighAppUpdateHelper.checkAfterLogin(DeviceSettingsActivity.this, true); + } + }); + btnBack.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + finish(); + } + }); + btnTestPrint.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + doTestPrint(); + } + }); + btnSettingsOpenCamera.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ensureCameraPermissionThenOpen(); + } + }); + btnSettingsCloseCamera.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + closeSettingsCamera(); + } + }); + + if (getIntent() != null && getIntent().getBooleanExtra("auto_test_print", false)) { + btnTestPrint.post(new Runnable() { + @Override + public void run() { + doTestPrint(); + } + }); + } + } + + @Override + protected void onResume() { + super.onResume(); + refreshPrinterStatus(); + if (cameraHelper != null && cameraHelper.isWantPreview()) { + openSettingsCamera(); + } + } + + @Override + protected void onPause() { + if (cameraHelper != null) { + cameraHelper.closeCameraKeepWant(); + } + super.onPause(); + } + + @Override + protected void onDestroy() { + if (usbHotplugGuard != null) { + usbHotplugGuard.unregister(); + usbHotplugGuard = null; + } + if (cameraHelper != null) { + cameraHelper.release(); + cameraHelper = null; + } + super.onDestroy(); + } + + @Override + public void onHotplugCloseCamera() { + closeSettingsCamera(); + } + + @Override + public void onHotplugMessage(String message) { + if (tvSettingsCameraHint != null) { + tvSettingsCameraHint.setText(message); + } + } + + @Override + public void onCameraError(String msg) { + if (tvSettingsCameraHint != null) { + tvSettingsCameraHint.setText(msg != null ? msg : "摄像头不可用"); + } + } + + @Override + public void onCameraReady() { + if (tvSettingsCameraHint != null) { + tvSettingsCameraHint.setText("预览中(仅设备设置调试)"); + } + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, + @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + if (requestCode == REQ_CAMERA) { + if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + openSettingsCamera(); + } else if (tvSettingsCameraHint != null) { + tvSettingsCameraHint.setText("未授权摄像头"); + } + } + } + + private void ensureCameraPermissionThenOpen() { + if (Build.VERSION.SDK_INT >= 23) { + if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) + != PackageManager.PERMISSION_GRANTED) { + ActivityCompat.requestPermissions(this, + new String[]{Manifest.permission.CAMERA}, REQ_CAMERA); + if (tvSettingsCameraHint != null) { + tvSettingsCameraHint.setText("需要摄像头权限"); + } + return; + } + } + openSettingsCamera(); + } + + private void openSettingsCamera() { + if (usbHotplugGuard != null && !usbHotplugGuard.canOpenNow()) { + long sec = (usbHotplugGuard.remainingCooldownMs() + 999) / 1000; + if (tvSettingsCameraHint != null) { + tvSettingsCameraHint.setText("USB 冷却中(约 " + sec + " 秒)后再连接"); + } + return; + } + if (cameraHelper == null) { + cameraHelper = new SimpleCameraHelper(svSettingsCamera, this); + } + cameraHelper.setAllowPreview(true); + if (tvSettingsCameraHint != null) { + tvSettingsCameraHint.setText("正在连接摄像头…"); + } + cameraHelper.requestOpen(); + } + + private void closeSettingsCamera() { + if (cameraHelper != null) { + cameraHelper.closeCameraAndClearWant(); + } + if (tvSettingsCameraHint != null) { + tvSettingsCameraHint.setText("摄像头已关闭"); + } + } + + private void refreshPrinterStatus() { + tvPrinterStatus.setText("USB 标签机:" + CaysnUsbPrinter.describeUsbPrinter(this)); + } + + private void doTestPrint() { + refreshPrinterStatus(); + // 先确认 USB 权限(主线程),无权限直接提示 + if (!CaysnUsbPrinter.hasUsbPermission(this)) { + Toast.makeText(this, "USB 打印机未授权,请先连接打印机并允许权限", Toast.LENGTH_LONG).show(); + return; + } + btnTestPrint.setEnabled(false); + Toast.makeText(this, "正在打印测试标签…", Toast.LENGTH_SHORT).show(); + new Thread(new Runnable() { + @Override + public void run() { + final boolean ok = PrintManager.printTestLabel(DeviceSettingsActivity.this); + runOnUiThread(new Runnable() { + @Override + public void run() { + btnTestPrint.setEnabled(true); + refreshPrinterStatus(); + Toast.makeText(DeviceSettingsActivity.this, + ok ? "测试打印已发送" : ("测试打印失败:" + CaysnUsbPrinter.describeUsbPrinter(DeviceSettingsActivity.this)), + Toast.LENGTH_LONG).show(); + } + }); + } + }).start(); + } + + @Override + public boolean dispatchTouchEvent(MotionEvent ev) { + SoftInputHelper.hideOnTouchOutside(this, ev); + return super.dispatchTouchEvent(ev); + } + + private void bindPaperSizeSpinner() { + ArrayAdapter adapter = new ArrayAdapter<>( + this, android.R.layout.simple_spinner_item, PAPER_LABELS); + adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spPaperSize.setAdapter(adapter); + spPaperSize.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + boolean custom = position == PAPER_LABELS.length - 1; + llPaperCustom.setVisibility(custom ? View.VISIBLE : View.GONE); + } + + @Override + public void onNothingSelected(AdapterView parent) { + } + }); + } + + private void bindPaperSizeCurrent() { + int w = CanteenApp.get().getLabelPaperWidthMm(); + int h = CanteenApp.get().getLabelPaperHeightMm(); + int idx = PAPER_LABELS.length - 1; + for (int i = 0; i < PAPER_DIMS.length - 1; i++) { + if (PAPER_DIMS[i][0] == w && PAPER_DIMS[i][1] == h) { + idx = i; + break; + } + } + spPaperSize.setSelection(idx); + llPaperCustom.setVisibility(idx == PAPER_LABELS.length - 1 ? View.VISIBLE : View.GONE); + etPaperWidth.setText(String.valueOf(w)); + etPaperHeight.setText(String.valueOf(h)); + } + + private int readPaperMm(EditText et, int fallback) { + String raw = et.getText().toString().trim(); + if (TextUtils.isEmpty(raw)) { + return fallback; + } + try { + return CanteenApp.clampPaperMm(Integer.parseInt(raw)); + } catch (NumberFormatException e) { + return fallback; + } + } + + private void loadPortSpinner() { + portList.clear(); + String[] ports = WeighManager.get().getAvailablePorts(); + if (ports != null && ports.length > 0) { + portList.addAll(Arrays.asList(ports)); + } + portList.add("(手填)"); + + ArrayAdapter adapter = new ArrayAdapter<>( + this, android.R.layout.simple_spinner_item, portList); + adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spSerialPort.setAdapter(adapter); + } + + private void bindScaleUnitSpinner() { + ArrayAdapter adapter = new ArrayAdapter<>( + this, android.R.layout.simple_spinner_item, SCALE_UNIT_LABELS); + adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spScaleUnit.setAdapter(adapter); + } + + private void bindScaleUnitCurrent() { + String current = CanteenApp.get().getScaleUnit(); + int idx = 0; + for (int i = 0; i < SCALE_UNIT_VALUES.length; i++) { + if (SCALE_UNIT_VALUES[i].equals(current)) { + idx = i; + break; + } + } + spScaleUnit.setSelection(idx); + } + + private void bindCaptureDistanceSpinner() { + if (spCaptureDistance == null) { + return; + } + ArrayAdapter adapter = new ArrayAdapter<>( + this, android.R.layout.simple_spinner_item, CAPTURE_DISTANCE_LABELS); + adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spCaptureDistance.setAdapter(adapter); + } + + private void bindCaptureDistanceCurrent() { + if (spCaptureDistance == null) { + return; + } + String current = CanteenApp.get().getCaptureDistance(); + int idx = 2; // 标准 + for (int i = 0; i < CAPTURE_DISTANCE_VALUES.length; i++) { + if (CAPTURE_DISTANCE_VALUES[i].equals(current)) { + idx = i; + break; + } + } + spCaptureDistance.setSelection(idx); + } + + private void bindCurrentConfig() { + CanteenApp app = CanteenApp.get(); + DeviceProfile profile = app.getDeviceProfile(); + int radioId = R.id.rb_a64; + if (profile == DeviceProfile.RK3288) { + radioId = R.id.rb_rk3288; + } else if (profile == DeviceProfile.CUSTOM) { + radioId = R.id.rb_custom; + } + rgProfile.check(radioId); + applyPortToUi(app.getSerialPort()); + etBaudRate.setText(String.valueOf(app.getBaudRate())); + double sec = app.getRecognizeIntervalMs() / 1000.0; + etRecognizeInterval.setText(String.format(java.util.Locale.US, "%.1f", sec)); + etWeightNoiseIgnore.setText(String.format(java.util.Locale.US, "%.2f", + app.getWeightNoiseIgnoreJin())); + etOtaManifestUrl.setText(app.getOtaManifestUrl()); + if (tvAppVersion != null) { + tvAppVersion.setText( + "当前版本 " + + WeighAppUpdateHelper.currentVersionName(this) + + " (" + + WeighAppUpdateHelper.currentVersionCode(this) + + ")"); + } + bindPaperSizeCurrent(); + bindScaleUnitCurrent(); + bindCaptureDistanceCurrent(); + if (tvPrintDeviceId != null) { + tvPrintDeviceId.setText("device_id: " + CanteenApp.get().getPrintDeviceId()); + } + if (etPrintDeviceName != null) { + etPrintDeviceName.setText(CanteenApp.get().getPrintDeviceDisplayName()); + } + } + + private void applyPortToUi(String port) { + if (port == null) { + port = ""; + } + etSerialPort.setText(port); + suppressSpinnerCallback = true; + int idx = portList.indexOf(port); + if (idx >= 0) { + spSerialPort.setSelection(idx); + } else { + int hand = portList.indexOf("(手填)"); + if (hand >= 0) { + spSerialPort.setSelection(hand); + } + } + suppressSpinnerCallback = false; + } + + private DeviceProfile profileFromCheckedId(int checkedId) { + if (checkedId == R.id.rb_rk3288) { + return DeviceProfile.RK3288; + } + if (checkedId == R.id.rb_custom) { + return DeviceProfile.CUSTOM; + } + return DeviceProfile.A64; + } + + private String readPort() { + return etSerialPort.getText().toString().trim(); + } + + private int readBaud() { + String raw = etBaudRate.getText().toString().trim(); + if (TextUtils.isEmpty(raw)) { + return 9600; + } + try { + return Integer.parseInt(raw); + } catch (NumberFormatException e) { + return 9600; + } + } + + private void doTest() { + String port = readPort(); + int baud = readBaud(); + if (TextUtils.isEmpty(port)) { + Toast.makeText(this, "请填写串口路径", Toast.LENGTH_SHORT).show(); + return; + } + btnTest.setEnabled(false); + boolean ok = WeighManager.get().testOpen(port, baud); + btnTest.setEnabled(true); + if (ok) { + Toast.makeText(this, "测试连接成功: " + port + " @" + baud, Toast.LENGTH_LONG).show(); + } else { + Toast.makeText(this, "测试连接失败: " + port + " @" + baud + "(检查权限或路径)", Toast.LENGTH_LONG).show(); + } + } + + private void doSave() { + DeviceProfile profile = profileFromCheckedId(rgProfile.getCheckedRadioButtonId()); + String port = readPort(); + int baud = readBaud(); + if (TextUtils.isEmpty(port)) { + Toast.makeText(this, "请填写串口路径", Toast.LENGTH_SHORT).show(); + return; + } + CanteenApp.get().saveDeviceConfig(profile, port, baud); + long intervalMs = readRecognizeIntervalMs(); + CanteenApp.get().saveWeighStationPrefs(false, intervalMs); + double noiseJin = readWeightNoiseIgnoreJin(); + CanteenApp.get().saveWeightNoiseIgnoreJin(noiseJin); + if (spCaptureDistance != null) { + int distIdx = spCaptureDistance.getSelectedItemPosition(); + if (distIdx >= 0 && distIdx < CAPTURE_DISTANCE_VALUES.length) { + CanteenApp.get().saveCaptureDistance(CAPTURE_DISTANCE_VALUES[distIdx]); + } + } + CanteenApp.get().saveOtaManifestUrl(etOtaManifestUrl.getText().toString().trim()); + int paperIdx = spPaperSize.getSelectedItemPosition(); + int paperW; + int paperH; + if (paperIdx >= 0 && paperIdx < PAPER_DIMS.length - 1) { + paperW = PAPER_DIMS[paperIdx][0]; + paperH = PAPER_DIMS[paperIdx][1]; + } else { + paperW = readPaperMm(etPaperWidth, CanteenApp.DEFAULT_LABEL_PAPER_WIDTH_MM); + paperH = readPaperMm(etPaperHeight, CanteenApp.DEFAULT_LABEL_PAPER_HEIGHT_MM); + } + CanteenApp.get().saveLabelPaperSize(paperW, paperH); + int scaleIdx = spScaleUnit.getSelectedItemPosition(); + if (scaleIdx >= 0 && scaleIdx < SCALE_UNIT_VALUES.length) { + CanteenApp.get().saveScaleUnit(SCALE_UNIT_VALUES[scaleIdx]); + } + if (etPrintDeviceName != null) { + CanteenApp.get().savePrintDeviceDisplayName(etPrintDeviceName.getText().toString()); + } + Toast.makeText(this, "已保存: " + CanteenApp.get().describeSerialConfig() + + ";手动提交;识别间隔 " + + String.format(java.util.Locale.US, "%.1f", intervalMs / 1000.0) + "s" + + ";跳变忽略 " + + String.format(java.util.Locale.US, "%.2f", + CanteenApp.get().getWeightNoiseIgnoreJin()) + "斤" + + ";摄像距离 " + + CAPTURE_DISTANCE_LABELS[Math.max(0, + Math.min(CAPTURE_DISTANCE_LABELS.length - 1, + spCaptureDistance != null + ? spCaptureDistance.getSelectedItemPosition() : 2))] + + ";标签纸 " + paperW + "×" + paperH + "mm", + Toast.LENGTH_LONG).show(); + finish(); + } + + private long readRecognizeIntervalMs() { + String raw = etRecognizeInterval.getText().toString().trim(); + if (TextUtils.isEmpty(raw)) { + return CanteenApp.DEFAULT_RECOGNIZE_INTERVAL_MS; + } + try { + double sec = Double.parseDouble(raw); + return CanteenApp.clampRecognizeIntervalMs(Math.round(sec * 1000.0)); + } catch (NumberFormatException e) { + return CanteenApp.DEFAULT_RECOGNIZE_INTERVAL_MS; + } + } + + private double readWeightNoiseIgnoreJin() { + String raw = etWeightNoiseIgnore.getText().toString().trim(); + if (TextUtils.isEmpty(raw)) { + return CanteenApp.DEFAULT_WEIGHT_NOISE_IGNORE_JIN; + } + try { + return CanteenApp.clampWeightNoiseIgnoreJin(Double.parseDouble(raw)); + } catch (NumberFormatException e) { + return CanteenApp.DEFAULT_WEIGHT_NOISE_IGNORE_JIN; + } + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/InspectionWeighActivity.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/InspectionWeighActivity.java new file mode 100644 index 0000000..76c049e --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/InspectionWeighActivity.java @@ -0,0 +1,3417 @@ +package com.canteen.weigh.ui; + +import android.Manifest; +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.os.Handler; +import android.os.Looper; +import android.os.Build; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.v4.app.ActivityCompat; +import android.support.v4.content.ContextCompat; +import android.support.v7.app.AppCompatActivity; +import android.text.Editable; +import android.text.TextUtils; +import android.text.TextWatcher; +import android.util.Log; +import android.view.MotionEvent; +import android.view.TextureView; +import android.view.View; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.AutoCompleteTextView; +import android.widget.Button; +import android.widget.CompoundButton; +import android.widget.EditText; +import android.widget.FrameLayout; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ListView; +import android.widget.RadioGroup; +import android.widget.Spinner; +import android.widget.Switch; +import android.widget.TextView; +import android.widget.Toast; + +import com.canteen.weigh.CanteenApp; +import com.canteen.weigh.R; +import com.canteen.weigh.api.ApiClient; +import com.canteen.weigh.api.InspectionApi; +import com.canteen.weigh.api.WeighStationApi; +import com.canteen.weigh.camera.CaptureImageHelper; +import com.canteen.weigh.camera.PreviewPinchZoomHelper; +import com.canteen.weigh.camera.SimpleCameraHelper; +import com.canteen.weigh.camera.VideoStreamRecognizeHelper; +import com.canteen.weigh.camera.UsbCameraHotplugGuard; +import com.canteen.weigh.model.InspectionTask; +import com.canteen.weigh.print.PrintManager; +import com.canteen.weigh.weigh.SceneGate; +import com.canteen.weigh.weigh.WeighManager; +import com.canteen.weigh.weigh.WeighStationMatcher; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** + * 验收台:摄像头识别 / 列表点选 + 称重匹配 + 确认入库 + */ +public class InspectionWeighActivity extends AppCompatActivity + implements WeighManager.WeighListener, + SimpleCameraHelper.PreviewCallback, + UsbCameraHotplugGuard.Callback { + + private static final int REQ_CAMERA = 1002; + private static final String TAG_CYCLE = "WeighCycle"; + private static final long AUTO_SUBMIT_STABLE_MS = 650L; + /** 自动提交成功(或发起)后的最短间隔 */ + private static final long AUTO_SUBMIT_COOLDOWN_MS = 1000L; + private static final long TOAST_DEDUP_MS = 8000L; + /** 低于此公斤数视为称上无货,禁止识别/自动提交;并关预览 */ + private static final double MIN_SCALE_KG = 0.01; + /** 完成态:重量降到此值以下视为已拿下(残余重量可能 > MIN) */ + private static final double DONE_LIFT_OFF_KG = 0.20; + /** 有货稳定后恢复预览 */ + private static final long PREVIEW_RESUME_MS = 400L; + /** 识别命中后未确认就拿下:秤空满此时间后清空识别展示(不再一直卡住) */ + private static final long RECOGNIZE_LIFT_OFF_CLEAR_MS = 2000L; + /** 秤空自动刷新待验的最小间隔,避免频繁刷新 */ + private static final long AUTO_REFRESH_MIN_INTERVAL_MS = 4000L; + + /** 本轮称重流水线状态 */ + private enum CyclePhase { + IDLE, + ACTIVE, + DONE + } + + private CyclePhase cyclePhase = CyclePhase.IDLE; + /** 最近一次识别抓帧,入库时作验收照片(2B) */ + private String lastRecognizePhotoB64; + /** AI 识别返回的计数单位数量(件/包/瓶…),非斤单位时作为提交默认值;null 表示未识别出 */ + private Double lastSuggestedQty = null; + /** AI 识别返回的单位(仅参考;实际单位以匹配行为准) */ + private String lastSuggestedUnit = null; + + private final Handler uiHandler = new Handler(Looper.getMainLooper()); + private VideoStreamRecognizeHelper streamRecognize; + private boolean activityResumed = false; + private long lastWeightChangeAt = 0; + private long lastRematchAt = 0; + private double lastRematchKg = Double.NaN; + private String lastRecognizedToastKey = ""; + private long lastRecognizedToastAt = 0; + private long autoSubmitCooldownUntilMs = 0L; + /** true:上一单自动提交后须先归零才能再自动交 */ + private boolean requireLiftOffBeforeAutoSubmit = false; + private boolean submittingFromAutoSubmit = false; + /** 仅识别命中待办后武装;手选不武装 */ + private boolean autoSubmitArmedByRecognize = false; + /** 用户手动选择了商品(spProduct 选中 / 列表点选),或识别命中;用于 rematch() 与提交门禁 */ + private boolean productManuallySelected = false; + /** + * 相近商品待点选:候选展示在「识别商品」列表,不弹窗(设计 20260910-weigh-inspection-merge-similar-inline)。 + */ + private boolean similarPickMode = false; + private final List similarPickSkus = new ArrayList<>(); + private final List similarPickNames = new ArrayList<>(); + private final List similarPickLabels = new ArrayList<>(); + private final List similarPickConfs = new ArrayList<>(); + private int similarPickSelected = -1; + /** loadProduct 重建 spinner 时保留相近列表,便于默认最像后仍可改选 */ + private boolean preserveSimilarPickOnRebuild = false; + private JSONObject pendingSimilarQuality = null; + /** 仅当质量判定明确合格后才允许自动提交(兜底:判断中/待人工/不合格都挡) */ + private boolean qualityPassForAutoSubmit = false; + private boolean resumePreviewWhenLoadedScheduled = false; + /** 识别命中后未确认就拿下:秤空满 2 秒后清空识别展示的延时任务标记 */ + private boolean recognizeLiftOffClearScheduled = false; + /** 上次秤空自动刷新待验的时间,用于节流 */ + private long lastAutoRefreshAt = 0L; + + private static final long REMATCH_MIN_INTERVAL_MS = 300L; + private static final double REMATCH_MIN_DELTA_KG = 0.002; + + private final Runnable autoSubmitRunnable = new Runnable() { + @Override + public void run() { + maybeAutoSubmit(); + } + }; + + private final Runnable resumePreviewWhenLoadedRunnable = new Runnable() { + @Override + public void run() { + resumePreviewWhenLoadedScheduled = false; + resumePreviewBecauseScaleLoaded(); + } + }; + + /** 识别命中后未确认就拿下:秤空满 2 秒后清空识别展示,避免一直卡在已识别状态 */ + private final Runnable recognizeLiftOffClearRunnable = new Runnable() { + @Override + public void run() { + recognizeLiftOffClearScheduled = false; + if (cyclePhase == CyclePhase.DONE) return; + if (currentWeightKg > MIN_SCALE_KG) return; + long now = System.currentTimeMillis(); + if (now - lastAutoRefreshAt < AUTO_REFRESH_MIN_INTERVAL_MS) return; + lastAutoRefreshAt = now; + Log.i(TAG_CYCLE, "lift-off clear: scale empty " + RECOGNIZE_LIFT_OFF_CLEAR_MS + + "ms without confirm, auto refresh pending"); + // 刷新待验:会清空识别展示并重新拉取待验列表 + loadPending(); + } + }; + + private final Runnable retryPreviewAfterUsbCooldown = new Runnable() { + @Override + public void run() { + if (activityResumed && currentWeightKg > MIN_SCALE_KG) { + ensurePreviewOpenForWeight(); + } + } + }; + + private TextView tvWeight; + private TextView tvToleranceHint; + private TextView tvMatchInfo; + private TextView tvQualityReason; + private TextView tvRecognizedProduct; + private ListView lvPendingProducts; + private TextView tvCameraHint; + private TextView tvCaptureStage; + private TextureView svCamera; + private ImageView ivCapture; + private Spinner spProduct; + private Spinner spMatch; + private Button btnZero; + private Button btnTare; + private Button btnRefresh; + private Button btnSubmit; + private Button btnForceComplete; + private Button btnReturn; + private Button btnReprint; + private Button btnRecognize; + private Switch swContinuousRecognize; + private Button btnOpenCamera; + private RadioGroup rgQuality; + private TextView tvModeHint; + private TextView tvListTitle; + /** 识别不在待验名单时:输入搜索下拉选择验收列表商品 */ + private AutoCompleteTextView actvPendingSearch; + private boolean assessingQuality; + private int qualitySession = 0; + /** 本件货是否已发起过质量判断(换货/归零/手动重拍时复位) */ + private boolean qualityFiredForCycle = false; + /** 最近一次识别出的品名,用于质量结果回填展示 */ + private String lastRecognizedShowName = null; + /** 最近一次识别出的商品 key(sku|name),用于换货检测 */ + private String lastRecognizedItemKey = null; + /** 质量结论文案缓存:updateMatchInfo 重写匹配文案后重挂,避免被覆盖 */ + private String lastQualityLine = null; + + private WeighManager weighManager; + private SimpleCameraHelper cameraHelper; + private PreviewPinchZoomHelper previewPinchZoom; + private UsbCameraHotplugGuard usbHotplugGuard; + private final List pendingItems = new ArrayList<>(); + private final List productKeys = new ArrayList<>(); + private final List productLabels = new ArrayList<>(); + private final Map productRequiredQty = new LinkedHashMap<>(); + private final Map productAccumulated = new LinkedHashMap<>(); + /** 列表当前展示的商品(productKeys 下标);只展示识别到的商品 */ + private final List shownProductIndices = new ArrayList<>(); + /** 识别未命中时:验收列表商品搜索下拉(服务端搜索结果) */ + private final List pendingSearchLabels = new ArrayList<>(); + /** 本地索引(验收搜索改用 skus/names) */ + private final List pendingSearchIndices = new ArrayList<>(); + private final List pendingSearchSkus = new ArrayList<>(); + private final List pendingSearchNames = new ArrayList<>(); + private ArrayAdapter pendingSearchAdapter; + /** 隐藏搜索框清空文本时不触发过滤/下拉 */ + private boolean suppressPendingSearchWatcher = false; + /** pending 接口 meta:待验行数 / 品数(默认不灌全表) */ + private int pendingRowCount = 0; + private int pendingProductCount = 0; + private Runnable searchDebounceRunnable; + private int searchSession = 0; + private final List matchCandidates = new ArrayList<>(); + private final List matchLabels = new ArrayList<>(); + + private double currentWeightKg = 0; + private boolean isSubmitting = false; + private boolean isRecognizing = false; + /** 本次识别开始时刻,超时后允许作废再拍 */ + private long recognizeStartedAtMs = 0L; + /** 须覆盖 TokenHub 视觉常见 15~43s;低于 OkHttp longClient 90s */ + private static final long RECOGNIZE_STALE_MS = 60000L; + private okhttp3.Call currentRecognizeCall = null; + /** 递增以作废进行中的抓帧/识别回调 */ + private int recognizeSession = 0; + /** 本稳定周期是否已自动识别出结果:成功后不再每 2 秒重识,避免同一件货结果来回跳 */ + private boolean autoRecognizedForCycle = false; + /** 本周期是否已识别并选中商品:命中后停止自动重识;未命中/低置信/未识别出时继续按节拍重识 */ + private boolean recognizeMatched = false; + /** 识别进行中又检测到换货:等本轮结束后再扫,避免叠发 ARK */ + private boolean pendingRescanAfterRecognize = false; + /** 上一轮识别结束时刻;自动重试须间隔,避免 2s 节拍打爆豆包 */ + private long lastRecognizeFinishedAtMs = 0L; + private static final long RECOGNIZE_AUTO_RETRY_GAP_MS = 8000L; + /** + * 静止画面闸门:画面指纹 + 重量都没变时不调 AI(设计 docs/design/20260924-weigh-scene-gate-and-adaptive-retry.md)。 + * 只做「跳过本次 AI 调用」,不参与命中态/按钮/cyclePhase 判定。 + */ + private final SceneGate sceneGate = new SceneGate(); + /** 抓帧时刻的秤重:结果返回时若已偏离说明货已换,丢弃结果 */ + private double inFlightCaptureKg = Double.NaN; + private String toleranceMode = "percent"; + private double toleranceValue = 10; + /** Web 下发:入库标签打印,默认关 */ + private boolean inboundLabelPrintEnabled = false; + private InspectionTask lastPrintedTask; + private double lastPrintedWeight; + + private boolean suppressProductCb = false; + private boolean suppressMatchCb = false; + + @Override + protected void attachBaseContext(Context newBase) { + super.attachBaseContext(WeighUiFontHelper.wrap(newBase)); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + if (TextUtils.isEmpty(CanteenApp.get().getToken())) { + Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show(); + startActivity(new Intent(this, LoginActivity.class)); + finish(); + return; + } + CanteenApp.get().saveLastStation(CanteenApp.STATION_INSPECTION); + setContentView(R.layout.activity_inspection_weigh); + ButtonClickEffect.apply(findViewById(android.R.id.content)); + SoftInputHelper.enableBlankFocus(findViewById(R.id.inbound_root)); + View inboundRoot = findViewById(R.id.inbound_root); + if (inboundRoot != null) { + inboundRoot.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (actvPendingSearch != null && actvPendingSearch.hasFocus()) { + return; + } + SoftInputHelper.hide(InspectionWeighActivity.this); + } + }); + } + + tvWeight = findViewById(R.id.tv_weight); + tvToleranceHint = findViewById(R.id.tv_tolerance_hint); + tvMatchInfo = findViewById(R.id.tv_match_info); + tvRecognizedProduct = findViewById(R.id.tv_recognized_product); + lvPendingProducts = findViewById(R.id.lv_pending_products); + tvCameraHint = findViewById(R.id.tv_camera_hint); + tvCaptureStage = findViewById(R.id.tv_capture_stage); + svCamera = findViewById(R.id.sv_camera); + ivCapture = findViewById(R.id.iv_capture); + FrameLayout flCameraPreview = (FrameLayout) findViewById(R.id.fl_camera_preview); + if (flCameraPreview != null && svCamera != null) { + previewPinchZoom = new PreviewPinchZoomHelper(flCameraPreview, svCamera); + } + spProduct = findViewById(R.id.sp_product); + spMatch = findViewById(R.id.sp_match); + btnZero = findViewById(R.id.btn_zero); + btnTare = findViewById(R.id.btn_tare); + btnRefresh = findViewById(R.id.btn_refresh); + btnSubmit = findViewById(R.id.btn_submit); + btnForceComplete = findViewById(R.id.btn_force_complete); + btnReturn = findViewById(R.id.btn_return); + btnReprint = findViewById(R.id.btn_reprint); + btnRecognize = findViewById(R.id.btn_recognize); + btnOpenCamera = findViewById(R.id.btn_open_camera); + rgQuality = findViewById(R.id.rg_quality); + tvQualityReason = findViewById(R.id.tv_quality_reason); + tvModeHint = findViewById(R.id.tv_mode_hint); + tvListTitle = findViewById(R.id.tv_list_title); + actvPendingSearch = findViewById(R.id.actv_pending_search); + + btnZero.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (weighManager != null) { + weighManager.zeroing(); + Toast.makeText(InspectionWeighActivity.this, "已置零", Toast.LENGTH_SHORT).show(); + } + } + }); + btnTare.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (weighManager != null) { + weighManager.tare(); + Toast.makeText(InspectionWeighActivity.this, "已去皮", Toast.LENGTH_SHORT).show(); + } + } + }); + btnRefresh.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + // 手动刷新待验:允许在重量未变时重新识别 + prepareManualPendingRefreshForRerecognize(); + loadPending(); + } + }); + btnSubmit.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + SoftInputHelper.hide(InspectionWeighActivity.this); + confirmSubmit(false); + } + }); + if (btnForceComplete != null) { + btnForceComplete.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + SoftInputHelper.hide(InspectionWeighActivity.this); + confirmSubmit(true); + } + }); + } + if (btnReturn != null) { + btnReturn.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + SoftInputHelper.hide(InspectionWeighActivity.this); + confirmReturn(); + } + }); + } + btnReprint.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + reprintLast(); + } + }); + btnRecognize.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + recognizeFromCamera(); + } + }); + btnOpenCamera.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + connectCameraByUser(); + } + }); + Button btnLogout = findViewById(R.id.btn_logout); + if (btnLogout != null) { + btnLogout.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + performBackToMain(); + } + }); + } + bindContinuousRecognizeSwitch(); + + usbHotplugGuard = new UsbCameraHotplugGuard(this, this); + usbHotplugGuard.register(); + streamRecognize = new VideoStreamRecognizeHelper(new VideoStreamRecognizeHelper.Host() { + @Override + public boolean canTick() { + return canAutoRecognizeTick(); + } + + @Override + public void onRecognizeTick() { + recognizeFromCamera(true); + } + + @Override + public void onRescanNeeded(boolean scaleEmpty) { + Log.i(TAG_CYCLE, "onRescanNeeded scaleEmpty=" + scaleEmpty + + " kg=" + currentWeightKg + " matched=" + recognizeMatched); + // 换货跳变且当前是完成态:不拿空秤直接换下一件 → 退出 DONE 回 ACTIVE 重新识别 + if (!scaleEmpty && cyclePhase == CyclePhase.DONE) { + exitDoneForNewCycle(); + abandonInFlightRecognize(); + if (currentWeightKg > MIN_SCALE_KG) { + streamRecognize.start(); + } + return; + } + // 已命中且秤未空:重量微跳/抖动不重识别(设计 20260910-weigh-no-rerecognize-stable-weight) + if (!scaleEmpty && recognizeMatched) { + Log.i(TAG_CYCLE, "ignore weight-jump rescan while matched"); + return; + } + if (scaleEmpty) { + // 空秤 = 新一件:闸门复位,拿下来再放回去一定会重新识别 + sceneGate.reset(); + } + abandonInFlightRecognize(); + // 换货跳变(未命中时):helper 跳变分支不自行 start,主动重启节拍 + if (!scaleEmpty && currentWeightKg > MIN_SCALE_KG) { + streamRecognize.start(); + } + } + + @Override + public boolean isCameraFrameStable() { + return cameraHelper != null && cameraHelper.isPreviewFrameStable(); + } + }); + + lvPendingProducts.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + if (similarPickMode) { + onSimilarCandidatePicked(position); + return; + } + if (position < 0 || position >= shownProductIndices.size()) return; + applyProductIndex(shownProductIndices.get(position), true); + } + }); + + pendingSearchAdapter = new ArrayAdapter<>(this, + android.R.layout.simple_dropdown_item_1line, pendingSearchLabels); + if (actvPendingSearch != null) { + actvPendingSearch.setAdapter(pendingSearchAdapter); + actvPendingSearch.setThreshold(0); + actvPendingSearch.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + } + + @Override + public void afterTextChanged(Editable s) { + if (suppressPendingSearchWatcher) return; + rebuildPendingSearchOptions(s == null ? "" : s.toString()); + // 不在此处 showDropDown:每键弹下拉易把工控机软键盘收掉;等搜索回调再弹 + } + }); + actvPendingSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + if (position < 0 || position >= pendingSearchSkus.size()) return; + String sku = pendingSearchSkus.get(position); + String name = position < pendingSearchNames.size() + ? pendingSearchNames.get(position) : ""; + SoftInputHelper.hide(InspectionWeighActivity.this); + hidePendingSearchBox(); + loadProductThenApply(sku, name, true, null, null); + } + }); + } + + spProduct.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (suppressProductCb) return; + autoSubmitArmedByRecognize = false; + if (position >= 0 && position < productKeys.size()) { + showRecognizedProduct(position); + if (position < productLabels.size()) { + tvRecognizedProduct.setText(productLabels.get(position)); + tvRecognizedProduct.setTextColor(0xFF1565C0); + } + } + rematch(); + } + + @Override + public void onNothingSelected(AdapterView parent) { + } + }); + spMatch.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (suppressMatchCb) return; + updateMatchInfo(); + } + + @Override + public void onNothingSelected(AdapterView parent) { + } + }); + + // 先出界面,再异步连秤/摄像头/拉待验,避免 Camera.open / 串口堵死首帧 + tvCameraHint.setText("正在开启摄像头…"); + View root = findViewById(R.id.inbound_root); + root.post(new Runnable() { + @Override + public void run() { + startHardwareAndData(); + } + }); + } + + /** 首帧绘制后再做硬件与网络,保证点击验收台立刻可见 */ + private void startHardwareAndData() { + // 京源 WeighSdk.openSerialPort 内部会 new Handler,必须在主线程调用 + weighManager = WeighManager.get(); + weighManager.init(this); + if (currentWeightKg <= MIN_SCALE_KG) { + currentWeightKg = weighManager.getLastWeightKg(); + } + // 预览常开:进入工作台即打开,无需先放货 + ensureCameraPermissionThenOpen(); + loadPending(); + } + + @Override + protected void onResume() { + super.onResume(); + activityResumed = true; + // 预览常开:回到工作台确保预览开启 + if (cameraHelper == null || !cameraHelper.isPreviewing()) { + ensureCameraPermissionThenOpen(); + } + } + + @Override + protected void onPause() { + activityResumed = false; + cancelResumePreviewWhenLoaded(); + cancelRecognizeLiftOffClear(); + cancelRetryPreviewAfterUsbCooldown(); + cancelInFlightRecognize(); + if (cameraHelper != null) { + cameraHelper.closeCameraKeepWant(); + } + super.onPause(); + } + + @Override + public void onHotplugCloseCamera() { + cancelInFlightRecognize(); + if (cameraHelper != null) { + cameraHelper.closeCameraAndClearWant(); + } + schedulePreviewAfterUsbCooldown(); + } + + @Override + public void onHotplugMessage(String message) { + if (tvCameraHint != null) { + tvCameraHint.setText(message); + } + } + + private void bindContinuousRecognizeSwitch() { + if (swContinuousRecognize == null) { + return; + } + // 开关语义:自动入库(开=跳过确认自动提交;关=须手动确认) + swContinuousRecognize.setChecked(CanteenApp.get().isAutoSubmitEnabled()); + swContinuousRecognize.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + CanteenApp.get().saveAutoSubmitEnabled(isChecked); + if (isChecked) { + scheduleAutoSubmit(); + } else { + uiHandler.removeCallbacks(autoSubmitRunnable); + } + refreshPreviewHint(); + } + }); + } + + private boolean canAutoRecognizeTick() { + // 识别进行中绝不叠发;未命中时也要间隔 RECOGNIZE_AUTO_RETRY_GAP_MS 再自动重试 + long now = android.os.SystemClock.elapsedRealtime(); + boolean retryGapOk = lastRecognizeFinishedAtMs <= 0L + || now - lastRecognizeFinishedAtMs >= RECOGNIZE_AUTO_RETRY_GAP_MS; + return activityResumed + && cyclePhase == CyclePhase.ACTIVE + && !isRecognizing + && retryGapOk + && !isSubmitting + && !recognizeMatched + && cameraHelper != null + && cameraHelper.isPreviewing() + && hasStreamRecognizeTarget() + && currentWeightKg > MIN_SCALE_KG + && (usbHotplugGuard == null || usbHotplugGuard.canOpenNow()); + } + + /** 验收需待验名单(meta 件数或已加载明细) */ + private boolean hasStreamRecognizeTarget() { + return pendingRowCount > 0 || !pendingItems.isEmpty(); + } + + /** 是否仍有待验目录(meta 或本地明细) */ + private boolean hasPendingCatalog() { + return pendingRowCount > 0 || !pendingItems.isEmpty(); + } + + /** 相机就绪:拍照区已是实时预览,只更新阶段文案 */ + private void captureFrameForDisplay() { + if (tvCaptureStage != null && currentWeightKg > MIN_SCALE_KG) { + tvCaptureStage.setText("实时预览"); + } + } + + /** 作废进行中的识别结果,不停止 2 秒抽帧。 */ + private void abandonInFlightRecognize() { + // 取消旧 HTTP 请求,避免并发堆积导致 TokenHub 限速 + if (currentRecognizeCall != null && !currentRecognizeCall.isCanceled()) { + currentRecognizeCall.cancel(); + } + currentRecognizeCall = null; + recognizeSession++; + isRecognizing = false; + recognizeStartedAtMs = 0L; + qualitySession++; + assessingQuality = false; + qualityFiredForCycle = false; + lastRecognizedShowName = null; + lastRecognizedItemKey = null; + lastQualityLine = null; + autoRecognizedForCycle = false; + recognizeMatched = false; + pendingRescanAfterRecognize = false; + inFlightCaptureKg = Double.NaN; + if (tvQualityReason != null) { + tvQualityReason.setVisibility(View.GONE); + } + if (cameraHelper != null) { + cameraHelper.disarmSceneChangeDetection(); + } + if (btnRecognize != null) { + btnRecognize.setEnabled(true); + } + uiHandler.removeCallbacks(autoSubmitRunnable); + } + + /** + * 识别结果落地后:按设计不再用画面指纹自动重识别(易误判导致按钮灰、重复识别)。 + * 换货靠秤空→再放货,或手动刷新待验 / 点识别。 + * 设计 20260910-weigh-no-rerecognize-stable-weight + */ + private void armSceneChangeWatch() { + if (cameraHelper != null) { + cameraHelper.disarmSceneChangeDetection(); + } + } + + /** + * 换货检测:本次识别出的商品与上一件不同 → 作废旧质量结论与待发的自动入库, + * 本件重新判质。覆盖「两件重量相近、未触发秤重变化重扫」的场景。 + */ + private void onRecognizedItemMaybeChanged(String newKey) { + if (TextUtils.isEmpty(newKey) || "|".equals(newKey)) { + return; + } + String prev = lastRecognizedItemKey; + lastRecognizedItemKey = newKey; + if (prev == null || prev.equals(newKey)) { + return; + } + qualityFiredForCycle = false; + qualitySession++; + assessingQuality = false; + lastQualityLine = null; + autoSubmitArmedByRecognize = false; + qualityPassForAutoSubmit = false; + lastSuggestedQty = null; + lastSuggestedUnit = null; + uiHandler.removeCallbacks(autoSubmitRunnable); + } + + /** 停止连续识别,并作废进行中的抓帧/API,避免关开关后界面假死。 */ + private void cancelInFlightRecognize() { + abandonInFlightRecognize(); + if (streamRecognize != null) { + streamRecognize.stop(); + } + } + + private boolean isStaleRecognizeSession(int session) { + return session != recognizeSession; + } + + private void refreshPreviewHint() { + if (tvCameraHint == null) { + return; + } + if (cyclePhase == CyclePhase.DONE) { + tvCameraHint.setText("入库完成,请取下商品后再放下一件"); + return; + } + boolean previewing = cameraHelper != null && cameraHelper.isPreviewing(); + if (!previewing) { + if (currentWeightKg <= MIN_SCALE_KG) { + tvCameraHint.setText("秤空,相机已关,等待下一件"); + } else if (usbHotplugGuard != null && !usbHotplugGuard.canOpenNow()) { + long sec = (usbHotplugGuard.remainingCooldownMs() + 999) / 1000; + tvCameraHint.setText("USB 冷却中(约 " + sec + " 秒),结束后自动开预览"); + } else if (activityResumed) { + tvCameraHint.setText("正在连接相机(抓拍用)…"); + } else { + tvCameraHint.setText("相机未开启"); + } + return; + } + if (currentWeightKg <= MIN_SCALE_KG) { + tvCameraHint.setText("秤空,预览约 30 秒后关闭"); + return; + } + if (!hasPendingCatalog()) { + tvCameraHint.setText("相机就绪;暂无待验"); + return; + } + tvCameraHint.setText("相机就绪"); + } + + private void showCaptureImage(String b64, String stageLabel) { + if (tvCaptureStage != null && stageLabel != null) { + tvCaptureStage.setText(stageLabel); + } + // 拍照区为实时预览,不定格铺图 + } + + private void clearCaptureImage(String stageLabel) { + CaptureImageHelper.clear(ivCapture); + if (tvCaptureStage != null) { + tvCaptureStage.setText(stageLabel != null ? stageLabel : "等待识别…"); + } + } + + private void applyLabelPrintConfig(JSONObject cfg) { + if (cfg == null) { + return; + } + if (cfg.has("inbound_label_print_enabled")) { + inboundLabelPrintEnabled = cfg.optBoolean("inbound_label_print_enabled", false); + } + refreshReprintEnabled(); + } + + private void refreshReprintEnabled() { + if (btnReprint == null) { + return; + } + if (!inboundLabelPrintEnabled) { + btnReprint.setEnabled(false); + btnReprint.setVisibility(View.GONE); + return; + } + btnReprint.setVisibility(View.VISIBLE); + btnReprint.setEnabled(lastPrintedTask != null); + } + + private void connectCameraByUser() { + if (usbHotplugGuard != null && !usbHotplugGuard.canOpenNow()) { + long sec = (usbHotplugGuard.remainingCooldownMs() + 999) / 1000; + Toast.makeText(this, "USB 刚插拔,请再等 " + sec + " 秒后再连接", Toast.LENGTH_SHORT).show(); + if (tvCameraHint != null) { + tvCameraHint.setText("冷却中(约 " + sec + " 秒),勿立刻打开摄像头"); + } + return; + } + // 完成态仍压着货时,允许手动开预览进入下一轮 + if (cyclePhase == CyclePhase.DONE && currentWeightKg > DONE_LIFT_OFF_KG) { + cyclePhase = CyclePhase.ACTIVE; + autoSubmitArmedByRecognize = false; + autoRecognizedForCycle = false; + recognizeMatched = false; + } + ensureCameraPermissionThenOpen(); + } + + /** 有重量则自动开预览,不依赖「连接摄像头」按钮 */ + private void ensurePreviewOpenForWeight() { + if (!activityResumed || currentWeightKg <= MIN_SCALE_KG) { + return; + } + if (usbHotplugGuard != null && !usbHotplugGuard.canOpenNow()) { + schedulePreviewAfterUsbCooldown(); + return; + } + if (cyclePhase == CyclePhase.DONE && currentWeightKg > DONE_LIFT_OFF_KG) { + cyclePhase = CyclePhase.ACTIVE; + autoSubmitArmedByRecognize = false; + autoRecognizedForCycle = false; + recognizeMatched = false; + } + if (cameraHelper != null && cameraHelper.isPreviewing()) { + refreshPreviewHint(); + return; + } + if (cameraHelper != null && cameraHelper.isOpening()) { + return; + } + ensureCameraPermissionThenOpen(); + } + + private void schedulePreviewAfterUsbCooldown() { + if (usbHotplugGuard == null) { + return; + } + long left = usbHotplugGuard.remainingCooldownMs(); + uiHandler.removeCallbacks(retryPreviewAfterUsbCooldown); + if (left <= 0) { + ensurePreviewOpenForWeight(); + return; + } + if (tvCameraHint != null) { + tvCameraHint.setText("USB 冷却中(约 " + ((left + 999) / 1000) + " 秒),结束后自动开预览"); + } + uiHandler.postDelayed(retryPreviewAfterUsbCooldown, left + 80); + } + + private void cancelRetryPreviewAfterUsbCooldown() { + uiHandler.removeCallbacks(retryPreviewAfterUsbCooldown); + } + + @Override + public boolean dispatchTouchEvent(MotionEvent ev) { + // 入库搜索输入中:不点空白强收键盘,避免中文输入/误触把键盘弹没 + View focus = getCurrentFocus(); + if (focus != actvPendingSearch) { + SoftInputHelper.hideOnTouchOutside(this, ev); + } + return super.dispatchTouchEvent(ev); + } + + private void ensureCameraPermissionThenOpen() { + if (Build.VERSION.SDK_INT >= 23) { + if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) + != PackageManager.PERMISSION_GRANTED) { + ActivityCompat.requestPermissions(this, + new String[]{Manifest.permission.CAMERA}, REQ_CAMERA); + tvCameraHint.setText("需要摄像头权限后才能识别"); + return; + } + } + openCamera(); + } + + private void performBackToMain() { + CanteenApp.get().clearLastStation(); + Intent intent = new Intent(this, MainActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); + startActivity(intent); + finish(); + } + + /** 仅当未在预览且非打开中时才发起打开,避免多入口并发重复请求刷屏 */ + private void openCameraIfIdle() { + if (cameraHelper == null || !cameraHelper.isAllowPreview()) { + return; + } + if (cameraHelper.isPreviewing() || cameraHelper.isOpening()) { + return; + } + openCamera(); + } + + private void openCamera() { + if (usbHotplugGuard != null && !usbHotplugGuard.canOpenNow()) { + schedulePreviewAfterUsbCooldown(); + return; + } + if (cameraHelper == null) { + cameraHelper = new SimpleCameraHelper(svCamera, this); + if (previewPinchZoom != null) { + cameraHelper.setVisibleCropProvider(previewPinchZoom); + } + } + // 帧缓存最多 0.3 秒旧,保证拍到的是当前秤上的货(识别节奏由「识别间隔」设置控制) + cameraHelper.setPreviewFrameMinIntervalMs(300L); + // 预览常开:无论秤上有无货都打开;秤空仅停识别节拍 + cyclePhase = currentWeightKg > MIN_SCALE_KG ? CyclePhase.ACTIVE : CyclePhase.IDLE; + cameraHelper.setAllowPreview(true); + tvCameraHint.setText(currentWeightKg > MIN_SCALE_KG + ? "正在连接摄像头…(失败可手选)" + : "正在连接摄像头…(秤空,预览保持)"); + cameraHelper.requestOpen(); + } + + /** 秤空保持预览常开 / 有货确保预览开启;识别节拍由 VideoStreamRecognizeHelper 按秤重自控 */ + private void syncPreviewWithScaleWeight(double weightKg) { + if (!activityResumed) { + return; + } + if (cyclePhase == CyclePhase.DONE) { + if (weightKg <= DONE_LIFT_OFF_KG) { + exitDoneToIdleAfterLiftOff(); + } + return; + } + if (weightKg <= MIN_SCALE_KG) { + // 秤空:预览保持常开,不再安排关闭 + cancelResumePreviewWhenLoaded(); + if (cyclePhase == CyclePhase.ACTIVE) { + cyclePhase = CyclePhase.IDLE; + } + // 自动刷新在 onWeightChanged 的「有货→空」转换处一次性调度,此处不再循环调度 + refreshPreviewHint(); + } else { + // 有货:取消待清空 + cancelRecognizeLiftOffClear(); + if (cameraHelper != null && cameraHelper.isPreviewing()) { + return; + } + if (!resumePreviewWhenLoadedScheduled) { + resumePreviewWhenLoadedScheduled = true; + uiHandler.postDelayed(resumePreviewWhenLoadedRunnable, PREVIEW_RESUME_MS); + } + } + } + + private void cancelRecognizeLiftOffClear() { + if (recognizeLiftOffClearScheduled) { + recognizeLiftOffClearScheduled = false; + uiHandler.removeCallbacks(recognizeLiftOffClearRunnable); + } + } + + private void cancelResumePreviewWhenLoaded() { + uiHandler.removeCallbacks(resumePreviewWhenLoadedRunnable); + resumePreviewWhenLoadedScheduled = false; + } + + /** 完成态已拿下 → IDLE,预览先保持,空秤满 30 秒再关 */ + private void exitDoneToIdleAfterLiftOff() { + if (cyclePhase != CyclePhase.DONE) { + return; + } + cancelRecognizeLiftOffClear(); + if (streamRecognize != null) { + streamRecognize.reset(); + } + cyclePhase = CyclePhase.IDLE; + lastRecognizePhotoB64 = null; + autoSubmitArmedByRecognize = false; + recognizeMatched = false; + resetSubmitButton(); + clearCaptureImage("等待识别…"); + if (tvCameraHint != null) { + tvCameraHint.setText("秤空,预览保持,放上货物即可识别"); + } + } + + /** 完成态未拿空、直接换下一件 → 回 ACTIVE 重新识别 */ + private void exitDoneForNewCycle() { + if (cyclePhase != CyclePhase.DONE) { + return; + } + cyclePhase = CyclePhase.ACTIVE; + lastRecognizePhotoB64 = null; + autoSubmitArmedByRecognize = false; + autoRecognizedForCycle = false; + recognizeMatched = false; + qualityFiredForCycle = false; + resetSubmitButton(); + if (tvCameraHint != null) { + tvCameraHint.setText("检测到换货,重新识别…"); + } + } + + private void pausePreviewBecauseScaleEmpty() { + if (cyclePhase == CyclePhase.DONE) { + if (currentWeightKg > DONE_LIFT_OFF_KG) { + return; + } + exitDoneToIdleAfterLiftOff(); + return; + } else if (currentWeightKg > MIN_SCALE_KG) { + return; + } + if (streamRecognize != null) { + streamRecognize.stop(); + } + // 预览保持常开,不 setAllowPreview(false) + cyclePhase = CyclePhase.IDLE; + lastRecognizePhotoB64 = null; + autoSubmitArmedByRecognize = false; + clearCaptureImage("等待识别…"); + // 拿开即视为本轮结束(所有模式):复位识别态,放回新货可自动重识(不依赖场景指纹/重量跳变) + autoRecognizedForCycle = false; + recognizeMatched = false; + qualityFiredForCycle = false; + if (cameraHelper != null) { + cameraHelper.disarmSceneChangeDetection(); + } + clearProductSelection(); + if (tvCameraHint != null) { + tvCameraHint.setText("秤空,预览保持,放上货物即可识别"); + } + } + + private void resumePreviewBecauseScaleLoaded() { + if (currentWeightKg <= MIN_SCALE_KG || !activityResumed) { + return; + } + if (cyclePhase == CyclePhase.DONE) { + if (currentWeightKg > DONE_LIFT_OFF_KG) { + cyclePhase = CyclePhase.ACTIVE; + autoSubmitArmedByRecognize = false; + autoRecognizedForCycle = false; + recognizeMatched = false; + } else { + refreshPreviewHint(); + return; + } + } + if (usbHotplugGuard != null && !usbHotplugGuard.canOpenNow()) { + schedulePreviewAfterUsbCooldown(); + return; + } + cyclePhase = CyclePhase.ACTIVE; + if (cameraHelper == null) { + ensureCameraPermissionThenOpen(); + return; + } + cameraHelper.setAllowPreview(true); + if (!cameraHelper.isPreviewing() && !cameraHelper.isOpening()) { + openCamera(); + } else { + refreshPreviewHint(); + captureFrameForDisplay(); + nudgeAutoRecognize(); + } + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, + @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + if (requestCode == REQ_CAMERA) { + if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + openCamera(); + } else { + tvCameraHint.setText("未授权摄像头"); + } + } + } + + @Override + public void onCameraError(String msg) { + // 只提示,不 Toast,避免无摄像头时打断手选流程 + if (tvCameraHint != null) { + tvCameraHint.setText((msg != null ? msg : "摄像头不可用") + "(可手选)"); + } + } + + @Override + public void onCameraReady() { + if (previewPinchZoom != null) { + previewPinchZoom.apply(); + } + refreshPreviewHint(); + captureFrameForDisplay(); + nudgeAutoRecognize(); + } + + /** 有重量且预览就绪:自动抽一帧,不必点「拍照识别」 */ + private void nudgeAutoRecognize() { + if (streamRecognize == null || !hasScaleWeight()) { + return; + } + if (cyclePhase == CyclePhase.DONE) { + return; + } + // 相机就绪立即抽一帧,不等下一个识别周期 + streamRecognize.requestImmediateTick(); + } + + private boolean hasScaleWeight() { + return currentWeightKg > MIN_SCALE_KG; + } + + /** 识别一轮结束:记时间戳;若有延期换货重扫则触发 */ + private void onRecognizeAttemptFinished() { + lastRecognizeFinishedAtMs = android.os.SystemClock.elapsedRealtime(); + isRecognizing = false; + if (btnRecognize != null) { + btnRecognize.setEnabled(true); + } + if (pendingRescanAfterRecognize) { + pendingRescanAfterRecognize = false; + Log.i(TAG_CYCLE, "flush deferred scene-change rescan"); + abandonInFlightRecognize(); + if (streamRecognize != null && currentWeightKg > MIN_SCALE_KG) { + lastRecognizeFinishedAtMs = 0L; + streamRecognize.requestImmediateTick(); + } + } + } + + /** + * 「画面 + 重量都没变」→ 跳过本次 AI 调用(省钱、防夜班空转)。 + * 设计 docs/design/20260924-weigh-scene-gate-and-adaptive-retry.md + * + *

硬约束:本方法只回答「这一拍要不要调 AI」,不得触碰 {@code recognizeMatched}、 + * 按钮可用性、{@code cyclePhase}、{@code lastRecognizePhotoB64}。20260910 的「换货检测」就是因为 + * 误判换货清掉命中态、按钮置灰而被停用,不要再犯。 + * + *

只对自动节拍(silent)生效;手动点「识别」/刷新待验永不受闸门限制。 + */ + private boolean shouldSkipUnchangedScene() { + CanteenApp app = CanteenApp.get(); + if (cameraHelper == null || app == null || !app.isSceneGateEnabled()) { + return false; + } + // 取不到指纹时返回 0,SceneGate 按「未知 = 放行」处理 + long hash = cameraHelper.probeSceneHash(); + boolean skip = sceneGate.shouldSkip( + hash, currentWeightKg, android.os.SystemClock.elapsedRealtime(), true); + if (skip) { + Log.i(TAG_CYCLE, "scene unchanged, skip AI skipCount=" + sceneGate.skipCount() + + " kg=" + currentWeightKg + " hash=" + hash); + } + return skip; + } + + private void recognizeFromCamera() { + recognizeFromCamera(false); + } + + private void recognizeFromCamera(final boolean silent) { + if (isRecognizing) { + // 自动节拍绝不打断进行中的识别;仅手动且超时才作废重试 + if (!silent) { + long elapsed = android.os.SystemClock.elapsedRealtime() - recognizeStartedAtMs; + if (recognizeStartedAtMs > 0 && elapsed >= RECOGNIZE_STALE_MS) { + Log.i(TAG_CYCLE, "recognize stale " + elapsed + "ms, cancel old and retry"); + abandonInFlightRecognize(); + } else { + Toast.makeText(this, "正在识别中,请稍候", Toast.LENGTH_SHORT).show(); + return; + } + } else { + return; + } + } + if (!hasScaleWeight()) { + if (!silent) { + Toast.makeText(this, "请先将商品放上秤再识别", Toast.LENGTH_SHORT).show(); + } + return; + } + if (!hasPendingCatalog()) { + if (!silent) { + Toast.makeText(this, "暂无待验明细,请先刷新", Toast.LENGTH_SHORT).show(); + } + return; + } + if (cameraHelper == null) { + if (!silent) { + Toast.makeText(this, "摄像头未就绪,请授权后重试或手选", Toast.LENGTH_SHORT).show(); + } + ensureCameraPermissionThenOpen(); + return; + } + // 画面与重量都没变 → 不抓整图、不发 HTTP、不调 AI(只跳过 AI 调用,不动命中态)。 + // 设计 docs/design/20260924-weigh-scene-gate-and-adaptive-retry.md + if (silent && shouldSkipUnchangedScene()) { + return; + } + + isRecognizing = true; + recognizeStartedAtMs = android.os.SystemClock.elapsedRealtime(); + final int session = recognizeSession; + Log.i(TAG_CYCLE, "recognize start session=" + session + " silent=" + silent + + " kg=" + currentWeightKg + " phase=" + cyclePhase); + if (!silent) { + btnRecognize.setEnabled(false); + } + // 静默自动识别也显示"识别中…",让用户立刻看到反馈,不再感觉无响应 + if (tvCameraHint != null) { + tvCameraHint.setText("识别中…"); + } + cameraHelper.captureJpegBase64Async(92, new SimpleCameraHelper.CaptureCallback() { + @Override + public void onCaptured(String b64) { + if (isStaleRecognizeSession(session)) { + return; + } + if (isFinishing() || isDestroyed()) { + onRecognizeAttemptFinished(); + return; + } + if (TextUtils.isEmpty(b64)) { + onRecognizeAttemptFinished(); + if (!silent) { + Toast.makeText(InspectionWeighActivity.this, "抓帧失败,请稍候再试或手选", Toast.LENGTH_SHORT).show(); + } else if (tvCameraHint != null) { + tvCameraHint.setText("识别抓帧失败,预览保持,请重试或手选"); + } + return; + } + lastRecognizePhotoB64 = b64; + inFlightCaptureKg = currentWeightKg; + // 诊断:留存最近一张识别帧,便于核对 AI 实际看到的画面 + try { + byte[] jpg = android.util.Base64.decode(b64, android.util.Base64.NO_WRAP); + java.io.File f = new java.io.File(getExternalFilesDir(null), "last_capture.jpg"); + java.io.FileOutputStream fos = new java.io.FileOutputStream(f); + fos.write(jpg); + fos.close(); + } catch (Exception ignored) { + } + showCaptureImage(b64, "识别抓拍"); + if (!silent) { + // 手动重拍:允许对本件货重新判质 + qualityFiredForCycle = false; + } + // 质量判定已合并进识别接口:一张图一次调用同时出品名+质量(见 applyMergedQualityOrFallback) + ApiClient.ApiCallback cb = new ApiClient.ApiCallback() { + @Override + public void onSuccess(int code, String body) { + currentRecognizeCall = null; + if (isStaleRecognizeSession(session)) { + return; + } + onRecognizeAttemptFinished(); + // 识别在途期间货已换(重量偏离抓帧时)→ 丢弃旧货结果,按新重量立即重识 + if (!Double.isNaN(inFlightCaptureKg) + && Math.abs(currentWeightKg - inFlightCaptureKg) >= 0.03) { + Log.i(TAG_CYCLE, "drift discard: captureKg=" + inFlightCaptureKg + + " nowKg=" + currentWeightKg); + inFlightCaptureKg = Double.NaN; + if (tvCameraHint != null) { + tvCameraHint.setText("货物已更换,按当前货物重新识别…"); + } + lastRecognizeFinishedAtMs = 0L; + if (streamRecognize != null) { + streamRecognize.requestImmediateTick(); + } + return; + } + inFlightCaptureKg = Double.NaN; + if (!isFinishing() && !isDestroyed()) { + applyRecognizeResult(body, silent); + } + } + + @Override + public void onError(int code, String message) { + currentRecognizeCall = null; + if (isStaleRecognizeSession(session)) { + return; + } + inFlightCaptureKg = Double.NaN; + onRecognizeAttemptFinished(); + if (tvCameraHint != null) { + tvCameraHint.setText("识别失败:" + message + "(预览保持,可重试或手选)"); + } + if (!silent && !isFinishing() && !isDestroyed()) { + Toast.makeText(InspectionWeighActivity.this, "识别失败:" + message, Toast.LENGTH_LONG).show(); + } + } + }; + currentRecognizeCall = InspectionApi.recognize(null, null, b64, cb); + } + }); + } + + private void applyRecognizeResult(String body, boolean silent) { + try { + JSONObject root = new JSONObject(body); + JSONObject data = root.optJSONObject("data"); + if (data == null) data = root; + // 一件货只自动识别一次:本周期已有结果,停止每 2 秒重识(换货/重量跳变会复位) + autoRecognizedForCycle = true; + armSceneChangeWatch(); + + String message = data.optString("message", ""); + JSONObject recognized = data.optJSONObject("recognized"); + JSONArray candidates = data.optJSONArray("candidates"); + // 合并识别:新服务端随识别结果直接返回质量块;旧服务端为 null 时走兜底 + final JSONObject quality = data.optJSONObject("quality"); + // AI 识别数量(仅计数单位有值;旧服务端无该字段则为 null) + double sq = data.optDouble("suggested_qty", Double.NaN); + lastSuggestedQty = (Double.isNaN(sq) || sq <= 0) ? null : sq; + String su = data.optString("suggested_unit", null); + lastSuggestedUnit = ("null".equals(su) || TextUtils.isEmpty(su)) ? null : su; + + String sku = null; + String name = null; + double confidence = 0; + boolean catalogMatched = true; + if (recognized != null) { + sku = recognized.optString("sku_code", null); + if ("null".equals(sku) || TextUtils.isEmpty(sku)) sku = null; + name = recognized.optString("item_name", null); + if ("null".equals(name) || TextUtils.isEmpty(name)) name = null; + confidence = recognized.optDouble("confidence", 0); + // 缺省 true:兼容旧 API;未命中名单时服务端显式 false + catalogMatched = !recognized.has("catalog_matched") || recognized.optBoolean("catalog_matched", true); + } + if ((sku == null && name == null) && candidates != null && candidates.length() > 0) { + JSONObject top = candidates.getJSONObject(0); + double topConf = top.optDouble("confidence", 0); + // AI 未认出时候选第一名只是待验列表第一项(confidence=0),不能当识别结果套用 + if (topConf >= 0.5) { + sku = top.optString("sku_code", null); + if ("null".equals(sku) || TextUtils.isEmpty(sku)) sku = null; + name = top.optString("item_name", null); + if ("null".equals(name) || TextUtils.isEmpty(name)) name = null; + confidence = topConf; + } + } + onRecognizedItemMaybeChanged((sku != null ? sku : "") + "|" + (name != null ? name : "")); + + // A/C:模型有品名但未命中名单 — 展示品名 + 手选,不绑 SKU、不武装自动提交 + if (recognized != null && !catalogMatched && name != null) { + recognizeMatched = false; + autoSubmitArmedByRecognize = false; + clearProductSelection(); + lastRecognizedShowName = name; + String tip = !TextUtils.isEmpty(message) + ? message + : ("识别到「" + name + "」,但不在待验名单,请手选"); + if (tvRecognizedProduct != null) { + tvRecognizedProduct.setText(name + + String.format(Locale.US, " (%.0f%%)", confidence * 100)); + tvRecognizedProduct.setTextColor(0xFFC62828); + } + if (tvMatchInfo != null) { + tvMatchInfo.setText(tip + "\n可在下方搜索选择正确商品"); + tvMatchInfo.setTextColor(0xFFC62828); + tvMatchInfo.setVisibility(View.VISIBLE); + } + showPendingSearchBox(); + if (tvCameraHint != null) tvCameraHint.setText(tip); + setInboundActionEnabled(false); + if (!silent) { + Toast.makeText(this, tip, Toast.LENGTH_LONG).show(); + } + applyMergedQualityOrFallback(quality); + boolean needSelect = data.optBoolean("need_select", false) + || hasSimilarPickCandidates(candidates); + if (needSelect) { + showSimilarCandidatesInProductColumn(candidates, quality); + } + return; + } + + if (sku == null && name == null) { + recognizeMatched = false; + autoSubmitArmedByRecognize = false; + Log.i(TAG_CYCLE, "apply result: AI 未识别出商品, 不套用候选"); + if (tvCameraHint != null) { + String tip = !TextUtils.isEmpty(message) ? message : "未识别出商品,可搜索验收列表商品或重拍"; + tvCameraHint.setText(tip); + } + showPendingSearchBox(); + applyMergedQualityOrFallback(quality); + return; + } + if (recognized != null && confidence > 0 && confidence < 0.6) { + recognizeMatched = false; + autoSubmitArmedByRecognize = false; + if (tvCameraHint != null) { + String tip = !TextUtils.isEmpty(message) ? message : "识别不够确定,可搜索验收列表商品或重拍"; + tvCameraHint.setText(tip); + } + showPendingSearchBox(); + applyMergedQualityOrFallback(quality); + return; + } + + // 唯一命中但名单有多条相近:在识别商品列内选,不弹窗(设计 20260910-weigh-inspection-merge-similar-inline) + boolean needSelectOnMatch = data.optBoolean("need_select", false) + || hasSimilarPickCandidates(candidates); + if (needSelectOnMatch && candidates != null && candidates.length() > 1) { + recognizeMatched = false; + autoSubmitArmedByRecognize = false; + String tip = !TextUtils.isEmpty(message) + ? message + : ("识别到「" + (name != null ? name : "") + "」,请在下方点选相近商品"); + if (tvCameraHint != null) tvCameraHint.setText(tip); + if (tvRecognizedProduct != null && name != null) { + tvRecognizedProduct.setText(name + + String.format(Locale.US, " (%.0f%%)", confidence * 100)); + tvRecognizedProduct.setTextColor(0xFF1565C0); + } + if (!silent) { + Toast.makeText(this, tip, Toast.LENGTH_LONG).show(); + } + applyMergedQualityOrFallback(quality); + showSimilarCandidatesInProductColumn(candidates, quality); + return; + } + + final String fSku = sku; + final String fName = name; + final double fConfidence = confidence; + final boolean fSilent = silent; + final JSONObject fQuality = quality; + final String showName = name != null ? name : (sku != null ? sku : "未知"); + Log.i(TAG_CYCLE, "apply result name=" + name + " sku=" + sku + + " conf=" + confidence + " → loadProduct"); + loadProductThenApply(sku, name, false, new Runnable() { + @Override + public void run() { + recognizeMatched = true; + hidePendingSearchBox(); + String tip = showName + String.format(Locale.US, " (%.0f%%)", fConfidence * 100); + if (tvRecognizedProduct != null) { + tvRecognizedProduct.setText(tip); + tvRecognizedProduct.setTextColor(0xFF1565C0); + } + tvCameraHint.setText("已识别并匹配待验:" + tip); + String key = (fSku != null ? fSku : "") + "|" + (fName != null ? fName : ""); + long now = System.currentTimeMillis(); + if (!fSilent || !key.equals(lastRecognizedToastKey) || now - lastRecognizedToastAt > TOAST_DEDUP_MS) { + Toast.makeText(InspectionWeighActivity.this, "已识别:" + tip, Toast.LENGTH_SHORT).show(); + lastRecognizedToastKey = key; + lastRecognizedToastAt = now; + } + autoSubmitArmedByRecognize = true; + qualityPassForAutoSubmit = false; + lastRecognizedShowName = showName; + armSceneChangeWatch(); + applyMergedQualityOrFallback(fQuality); + } + }, new Runnable() { + @Override + public void run() { + recognizeMatched = false; + autoSubmitArmedByRecognize = false; + clearProductSelection(); + lastRecognizedShowName = showName; + String tip = "识别到「" + showName + "」,但不在待验名单,请人工检查"; + if (tvRecognizedProduct != null) { + tvRecognizedProduct.setText(showName + + String.format(Locale.US, " (%.0f%%)", fConfidence * 100)); + tvRecognizedProduct.setTextColor(0xFFC62828); + } + if (tvMatchInfo != null) { + tvMatchInfo.setText(tip + "\n可在下方搜索选择正确商品"); + tvMatchInfo.setTextColor(0xFFC62828); + tvMatchInfo.setVisibility(View.VISIBLE); + } + showPendingSearchBox(); + tvCameraHint.setText(tip); + setInboundActionEnabled(false); + if (!fSilent) { + Toast.makeText(InspectionWeighActivity.this, tip, Toast.LENGTH_LONG).show(); + } else { + String key = "miss|" + showName; + long now = System.currentTimeMillis(); + if (!key.equals(lastRecognizedToastKey) || now - lastRecognizedToastAt > TOAST_DEDUP_MS) { + Toast.makeText(InspectionWeighActivity.this, tip, Toast.LENGTH_LONG).show(); + lastRecognizedToastKey = key; + lastRecognizedToastAt = now; + } + } + applyMergedQualityOrFallback(fQuality); + } + }); + } catch (JSONException e) { + if (!silent) { + Toast.makeText(this, "识别结果解析失败", Toast.LENGTH_SHORT).show(); + } + } + } + + /** 相近候选:confidence≥0.6(设计 20260909-weigh-similar-candidates-pick) */ + private boolean hasSimilarPickCandidates(JSONArray candidates) { + if (candidates == null) return false; + for (int i = 0; i < candidates.length(); i++) { + JSONObject c = candidates.optJSONObject(i); + if (c != null && c.optDouble("confidence", 0) >= 0.6) return true; + } + return false; + } + + /** 相近商品写入「识别商品」列表;默认绑定最像(confidence 最高),仍可点选改绑 */ + private void showSimilarCandidatesInProductColumn(JSONArray candidates, final JSONObject quality) { + if (candidates == null || candidates.length() == 0) return; + final List skus = new ArrayList<>(); + final List names = new ArrayList<>(); + final List confs = new ArrayList<>(); + for (int i = 0; i < candidates.length(); i++) { + JSONObject c = candidates.optJSONObject(i); + if (c == null) continue; + double conf = c.optDouble("confidence", 0); + if (conf < 0.6) continue; + String itemName = c.optString("item_name", null); + if ("null".equals(itemName) || TextUtils.isEmpty(itemName)) itemName = null; + String sku = c.optString("sku_code", null); + if ("null".equals(sku) || TextUtils.isEmpty(sku)) sku = null; + if (itemName == null && sku == null) continue; + skus.add(sku); + names.add(itemName); + confs.add(conf); + } + if (names.isEmpty()) return; + + // 最像在前 + for (int i = 0; i < confs.size(); i++) { + for (int j = i + 1; j < confs.size(); j++) { + if (confs.get(j) > confs.get(i)) { + double tc = confs.get(i); confs.set(i, confs.get(j)); confs.set(j, tc); + String ts = skus.get(i); skus.set(i, skus.get(j)); skus.set(j, ts); + String tn = names.get(i); names.set(i, names.get(j)); names.set(j, tn); + } + } + } + + final List labels = new ArrayList<>(); + for (int i = 0; i < names.size(); i++) { + labels.add(formatSimilarCandidateLabel(names.get(i), skus.get(i), confs.get(i))); + } + + if (similarPickMode + && labels.size() == similarPickNames.size() + && namesEquals(similarPickNames, names) + && skusEquals(similarPickSkus, skus)) { + pendingSimilarQuality = quality; + // 待验明细可能刚刷新:补刷需求量文案 + rebuildSimilarPickLabelsFromDemand(); + renderSimilarCandidatesList(similarPickSelected); + return; + } + + similarPickMode = true; + pendingSimilarQuality = quality; + similarPickSkus.clear(); + similarPickNames.clear(); + similarPickLabels.clear(); + similarPickConfs.clear(); + similarPickSkus.addAll(skus); + similarPickNames.addAll(names); + similarPickConfs.addAll(confs); + similarPickLabels.addAll(labels); + similarPickSelected = -1; + + if (tvListTitle != null) { + tvListTitle.setText("相近商品(可改选)"); + } + if (tvMatchInfo != null) { + tvMatchInfo.setText("已默认最像,点选其它可改绑"); + tvMatchInfo.setTextColor(0xFF1565C0); + tvMatchInfo.setVisibility(View.VISIBLE); + } + renderSimilarCandidatesList(-1); + // 默认绑定置信度最高的一条 + applySimilarCandidate(0, false); + } + + private boolean namesEquals(List a, List b) { + if (a.size() != b.size()) return false; + for (int i = 0; i < a.size(); i++) { + String x = a.get(i); + String y = b.get(i); + if (x == null ? y != null : !x.equals(y)) return false; + } + return true; + } + + private boolean skusEquals(List a, List b) { + return namesEquals(a, b); + } + + /** 相近列表标签:品名 (置信度) · 需{合计}单位 */ + private String formatSimilarCandidateLabel(String itemName, String sku, double conf) { + String base = itemName != null ? itemName : (sku != null ? sku : "-"); + StringBuilder sb = new StringBuilder(base); + if (conf > 0) { + sb.append(String.format(Locale.US, " (%.0f%%)", conf * 100)); + } + double required = demandQtyForProduct(sku, itemName); + String unitLabel = demandUnitForProduct(sku, itemName); + if (required > 0) { + sb.append(" · 需").append(formatWeight(required)).append(unitLabel); + double accumulated = receivedQtyForProduct(sku, itemName); + if (accumulated > 0) { + sb.append(" · 已入库").append(formatWeight(accumulated)).append(unitLabel); + } + } + return sb.toString(); + } + + private String productKeyOf(String sku, String itemName) { + if (!TextUtils.isEmpty(sku)) return "sku:" + sku.trim(); + return "name:" + WeighStationMatcher.normalizeName(itemName); + } + + private double demandQtyForProduct(String sku, String itemName) { + String key = productKeyOf(sku, itemName); + if (productRequiredQty.containsKey(key)) { + return productRequiredQty.get(key); + } + double sum = 0; + for (InspectionTask it : pendingItems) { + if (productKey(it).equals(key)) { + sum += it.prepareQty > 0 ? it.prepareQty : 0; + } + } + if (sum > 0) return sum; + // sku 未对上时按品名兜底 + if (!TextUtils.isEmpty(itemName)) { + String norm = WeighStationMatcher.normalizeName(itemName); + for (InspectionTask it : pendingItems) { + if (norm.equals(WeighStationMatcher.normalizeName(it.itemName))) { + sum += it.prepareQty > 0 ? it.prepareQty : 0; + } + } + } + return sum; + } + + private double receivedQtyForProduct(String sku, String itemName) { + String key = productKeyOf(sku, itemName); + if (productAccumulated.containsKey(key)) { + return productAccumulated.get(key); + } + double sum = 0; + for (InspectionTask it : pendingItems) { + if (productKey(it).equals(key)) { + sum += it.receivedQty > 0 ? it.receivedQty : 0; + } + } + return sum; + } + + private String demandUnitForProduct(String sku, String itemName) { + String key = productKeyOf(sku, itemName); + for (InspectionTask it : pendingItems) { + if (productKey(it).equals(key) && !TextUtils.isEmpty(it.unit)) { + return WeighStationMatcher.displayUnit(it.unit); + } + } + if (!TextUtils.isEmpty(itemName)) { + String norm = WeighStationMatcher.normalizeName(itemName); + for (InspectionTask it : pendingItems) { + if (norm.equals(WeighStationMatcher.normalizeName(it.itemName)) + && !TextUtils.isEmpty(it.unit)) { + return WeighStationMatcher.displayUnit(it.unit); + } + } + } + return "斤"; + } + + private void rebuildSimilarPickLabelsFromDemand() { + similarPickLabels.clear(); + for (int i = 0; i < similarPickNames.size(); i++) { + double conf = i < similarPickConfs.size() ? similarPickConfs.get(i) : 0; + similarPickLabels.add(formatSimilarCandidateLabel( + similarPickNames.get(i), + i < similarPickSkus.size() ? similarPickSkus.get(i) : null, + conf)); + } + } + + private void renderSimilarCandidatesList(int checkedIndex) { + if (similarPickLabels.isEmpty()) return; + shownProductIndices.clear(); + for (int i = 0; i < similarPickLabels.size(); i++) { + shownProductIndices.add(i); + } + ArrayAdapter listAdapter = new ArrayAdapter<>(this, + R.layout.item_recognized_product, new ArrayList<>(similarPickLabels)); + lvPendingProducts.setAdapter(listAdapter); + lvPendingProducts.setVisibility(View.VISIBLE); + if (checkedIndex >= 0 && checkedIndex < similarPickLabels.size()) { + lvPendingProducts.setItemChecked(checkedIndex, true); + try { + lvPendingProducts.smoothScrollToPosition(checkedIndex); + } catch (Exception ignored) { + } + } else { + lvPendingProducts.clearChoices(); + } + suppressProductCb = true; + productKeys.clear(); + productLabels.clear(); + for (int i = 0; i < similarPickLabels.size(); i++) { + productKeys.add("similar:" + i); + productLabels.add(similarPickLabels.get(i)); + } + ArrayAdapter spinnerAdapter = new ArrayAdapter<>(this, + android.R.layout.simple_spinner_item, productLabels); + spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spProduct.setAdapter(spinnerAdapter); + suppressProductCb = false; + } + + private void clearSimilarPickMode() { + similarPickMode = false; + similarPickSkus.clear(); + similarPickNames.clear(); + similarPickLabels.clear(); + similarPickConfs.clear(); + similarPickSelected = -1; + preserveSimilarPickOnRebuild = false; + pendingSimilarQuality = null; + if (tvListTitle != null) { + tvListTitle.setText("识别商品"); + } + } + + private void onSimilarCandidatePicked(int which) { + applySimilarCandidate(which, true); + } + + /** + * 绑定相近候选;默认最像 fromUser=false;改选 fromUser=true。 + * 绑定后仍保留相近列表,便于改选。 + */ + private void applySimilarCandidate(final int which, final boolean fromUser) { + if (!similarPickMode || which < 0 || which >= similarPickNames.size()) return; + if (which == similarPickSelected && fromUser) return; + final String pickSku = similarPickSkus.get(which); + final String pickName = similarPickNames.get(which); + final JSONObject quality = pendingSimilarQuality; + SoftInputHelper.hide(InspectionWeighActivity.this); + hidePendingSearchBox(); + preserveSimilarPickOnRebuild = true; + loadProductThenApply(pickSku, pickName, fromUser, new Runnable() { + @Override + public void run() { + preserveSimilarPickOnRebuild = false; + similarPickMode = true; + similarPickSelected = which; + autoSubmitArmedByRecognize = false; + recognizeMatched = false; + productManuallySelected = true; + // pending 明细已拉齐:补上「需」量 + rebuildSimilarPickLabelsFromDemand(); + String tip = pickName != null ? pickName : pickSku; + if (tvListTitle != null) { + tvListTitle.setText("相近商品(可改选)"); + } + if (tvRecognizedProduct != null && tip != null) { + String withDemand = which < similarPickLabels.size() + ? similarPickLabels.get(which) : tip; + tvRecognizedProduct.setText(withDemand + (fromUser ? "" : " · 默认最像")); + tvRecognizedProduct.setTextColor(0xFF1565C0); + } + if (tvCameraHint != null) { + tvCameraHint.setText(fromUser + ? ("已改选:" + tip) + : ("已默认最像:" + tip + ",可点选其它")); + } + if (tvMatchInfo != null) { + tvMatchInfo.setText("已选「" + tip + "」,点选列表可改绑"); + tvMatchInfo.setTextColor(0xFF1565C0); + tvMatchInfo.setVisibility(View.VISIBLE); + } + renderSimilarCandidatesList(which); + applyMergedQualityOrFallback(quality); + } + }, new Runnable() { + @Override + public void run() { + preserveSimilarPickOnRebuild = false; + Toast.makeText(InspectionWeighActivity.this, + "未找到该商品待验明细", Toast.LENGTH_SHORT).show(); + renderSimilarCandidatesList(similarPickSelected); + showPendingSearchBox(); + } + }); + } + + /** + * 登记当前识别到的品名(用于质量结果展示)。 + * 质量判定已合并进识别响应(见 applyMergedQualityOrFallback),此处不再单独发请求。 + */ + private void requestQualityAssess(final String productName) { + if (!TextUtils.isEmpty(productName)) { + lastRecognizedShowName = productName.trim(); + } + } + + /** + * 识别+质量合并入口:识别响应带 quality 块(新服务端)→ 直接应用,一次出结果; + * quality 为 null(旧服务端)→ 兜底发独立 assess-quality。每件货只判一次。 + */ + private void applyMergedQualityOrFallback(JSONObject quality) { + Log.i(TAG_CYCLE, "quality apply: hasBlock=" + (quality != null) + + " fired=" + qualityFiredForCycle + " item=" + lastRecognizedShowName); + if (quality == null || qualityFiredForCycle) { + return; + } + qualityFiredForCycle = true; + qualitySession++; + assessingQuality = false; + applyQualityAssessData(quality, lastRecognizedShowName); + } + + /** 应用质量判定数据(识别合并块) */ + private void applyQualityAssessData(JSONObject data, String productName) { + boolean needsHuman = data.optBoolean("needs_human", false); + boolean pass = !needsHuman && !isStrictQualityFail(data); + Log.i(TAG_CYCLE, "quality verdict: item=" + productName + " pass=" + pass + + " needsHuman=" + needsHuman + " raw=" + data.toString()); + qualityPassForAutoSubmit = pass && !needsHuman; + String conclusion = data.optString("conclusion", ""); + String issues = joinQualityIssues(data); + if (rgQuality != null && !needsHuman) { + rgQuality.check(pass ? R.id.rb_pass : R.id.rb_reject); + } + String verdict = needsHuman ? "待人工严查" : (pass ? "合格" : "不合格"); + String line = "质量:" + verdict + + (TextUtils.isEmpty(conclusion) ? "" : (" · " + conclusion)) + + (TextUtils.isEmpty(issues) ? "" : (" · " + issues)); + lastQualityLine = line; + // 品质原因栏:紧挨品质行展示 AI 判定依据(结论+问题+建议),换货/作废时清空 + if (tvQualityReason != null) { + String suggestion = data.optString("suggestion", ""); + String reason = verdict + " · " + + (TextUtils.isEmpty(conclusion) ? "" : conclusion) + + (TextUtils.isEmpty(issues) ? "" : (";" + issues)) + + (TextUtils.isEmpty(suggestion) ? "" : (";建议:" + suggestion)); + tvQualityReason.setText(reason); + tvQualityReason.setTextColor(pass ? 0xFF2E7D32 : 0xFFC62828); + tvQualityReason.setVisibility(View.VISIBLE); + } + // 质量结论只在品质区展示,不再写入匹配明细区 + if (tvCameraHint != null) { + tvCameraHint.setText((productName != null ? productName : "已识别") + " · " + line); + } + if (pass && !needsHuman) { + scheduleAutoSubmit(); + } + } + + private static final java.util.regex.Pattern NEGATED_FAIL_TEXT = java.util.regex.Pattern.compile( + "(无|未见|没有|并无|不见|未发现|不存在)[^,。;,.;!!??]{0,12}?(腐烂|霉变|霉斑|霉点|发霉|霉|变质|发黑|软烂|坏死|病斑|不合格)"); + + /** + * 严格不合格判定:以结构化字段(等级/分数/损毁类型)+ 剔除否定语境后的文案为准。 + * 不信任服务端 pass/quality_rating 标志位——旧版门禁会把「无腐烂」误判为腐烂。 + */ + private static boolean isStrictQualityFail(JSONObject data) { + if (data.optBoolean("needs_human", false)) { + return false; + } + String grade = data.optString("grade", "").trim().toUpperCase(); + if ("C".equals(grade) || "D".equals(grade)) { + return true; + } + double score = data.optDouble("score", 100); + if (score > 0 && score < 85) { + return true; + } + StringBuilder damageCorpus = new StringBuilder(); + JSONArray damages = data.optJSONArray("damage_types"); + if (damages != null) { + for (int i = 0; i < damages.length(); i++) { + String d = damages.optString(i, ""); + damageCorpus.append(d); + if ("腐烂".equals(d) || "污染".equals(d)) { + return true; + } + } + } + String corpus = data.optString("conclusion", "") + data.optString("suggestion", "") + + joinQualityIssues(data) + damageCorpus; + String corpusClean = NEGATED_FAIL_TEXT.matcher(corpus).replaceAll(""); + return corpusClean.contains("不合格") || corpusClean.contains("腐烂") + || corpusClean.contains("霉") || corpusClean.contains("变质") + || corpusClean.contains("发黑") || corpusClean.contains("软烂"); + } + + private static String joinQualityIssues(JSONObject data) { + JSONArray arr = data.optJSONArray("issues"); + if (arr == null || arr.length() == 0) { + return ""; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < arr.length(); i++) { + String s = arr.optString(i, "").trim(); + if (s.isEmpty()) { + continue; + } + if (sb.length() > 0) { + sb.append(';'); + } + sb.append(s); + } + return sb.toString(); + } + + private void clearProductSelection() { + suppressProductCb = true; + suppressMatchCb = true; + matchCandidates.clear(); + matchLabels.clear(); + ArrayAdapter empty = new ArrayAdapter<>(this, + android.R.layout.simple_spinner_item, matchLabels); + spMatch.setAdapter(empty); + clearRecognizedDisplay(); + suppressProductCb = false; + suppressMatchCb = false; + } + + private void applyProductIndex(int idx, boolean fromUser) { + if (idx < 0 || idx >= productKeys.size()) return; + if (fromUser) { + autoSubmitArmedByRecognize = false; + } + productManuallySelected = true; // 手动点选或识别命中后视为已选定商品 + suppressProductCb = true; + spProduct.setSelection(idx); + showRecognizedProduct(idx); + suppressProductCb = false; + rematch(); + if (fromUser && idx < productLabels.size()) { + tvRecognizedProduct.setText(productLabels.get(idx)); + tvRecognizedProduct.setTextColor(0xFF1565C0); + } + } + + private boolean selectProduct(String sku, String name) { + if (productKeys.isEmpty()) return false; + int idx = -1; + if (!TextUtils.isEmpty(sku)) { + String want = "sku:" + sku.trim(); + for (int i = 0; i < productKeys.size(); i++) { + if (want.equals(productKeys.get(i))) { + idx = i; + break; + } + } + } + if (idx < 0 && !TextUtils.isEmpty(name)) { + String norm = WeighStationMatcher.normalizeName(name); + for (int i = 0; i < productKeys.size(); i++) { + String key = productKeys.get(i); + if (key.startsWith("name:") && key.substring(5).equals(norm)) { + idx = i; + break; + } + } + if (idx < 0) { + for (InspectionTask item : pendingItems) { + String nm = WeighStationMatcher.normalizeName(item.itemName); + if (nm.equals(norm)) { + String pk = productKey(item); + for (int j = 0; j < productKeys.size(); j++) { + if (pk.equals(productKeys.get(j))) { + idx = j; + break; + } + } + if (idx >= 0) break; + } + } + } + } + if (idx < 0) return false; + applyProductIndex(idx, false); + return true; + } + + /** + * 手动刷新待验:清掉「已命中」锁,允许重量未变时再自动识别一拍。 + * 设计 20260910-weigh-no-rerecognize-stable-weight + */ + private void prepareManualPendingRefreshForRerecognize() { + if (cameraHelper != null) { + cameraHelper.disarmSceneChangeDetection(); + } + pendingRescanAfterRecognize = false; + recognizeMatched = false; + autoRecognizedForCycle = false; + autoSubmitArmedByRecognize = false; + qualityPassForAutoSubmit = false; + qualityFiredForCycle = false; + lastRecognizeFinishedAtMs = 0L; + if (cyclePhase == CyclePhase.DONE) { + // 刷新待验时若仍停在完成态,回 ACTIVE 才能 canAutoRecognizeTick + cyclePhase = CyclePhase.ACTIVE; + resetSubmitButton(); + } + if (streamRecognize != null && currentWeightKg > MIN_SCALE_KG && activityResumed) { + streamRecognize.start(); + streamRecognize.requestImmediateTick(); + } + } + + private void loadPending() { + if (btnRefresh != null) { + btnRefresh.setEnabled(false); + } + if (tvCameraHint != null) { + tvCameraHint.setText("加载待验明细…"); + } + // 优先 weigh-station/pending(已排除垃圾桶订单);失败再回退 /inspection/tasks + InspectionApi.getWeighStationPending(new ApiClient.ApiCallback() { + @Override + public void onSuccess(int code, String body) { + if (btnRefresh != null) { + btnRefresh.setEnabled(true); + } + if (!applyPendingBody(body)) { + Toast.makeText(InspectionWeighActivity.this, "解析待验数据失败", Toast.LENGTH_SHORT).show(); + return; + } + if (pendingRowCount == 0) { + Toast.makeText(InspectionWeighActivity.this, "暂无待验明细", Toast.LENGTH_LONG).show(); + } + } + + @Override + public void onError(int code, String message) { + if (code == 401 || (message != null && message.contains("invalid_token"))) { + if (btnRefresh != null) { + btnRefresh.setEnabled(true); + } + Toast.makeText(InspectionWeighActivity.this, "登录已失效,请重新登录", Toast.LENGTH_LONG).show(); + CanteenApp.get().logout(); + Intent intent = new Intent(InspectionWeighActivity.this, LoginActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); + startActivity(intent); + finish(); + return; + } + tryInspectionTasksFallback(message); + } + }); + } + + private void tryInspectionTasksFallback(final String primaryError) { + if (tvCameraHint != null) { + tvCameraHint.setText("加载待验明细…"); + } + InspectionApi.getTasks(new ApiClient.ApiCallback() { + @Override + public void onSuccess(int code, String body) { + if (btnRefresh != null) { + btnRefresh.setEnabled(true); + } + if (!applyPendingBody(body)) { + Toast.makeText(InspectionWeighActivity.this, + "加载失败:" + primaryError, Toast.LENGTH_LONG).show(); + return; + } + loadToleranceConfigQuietly(); + if (pendingRowCount == 0) { + Toast.makeText(InspectionWeighActivity.this, "暂无待验明细", Toast.LENGTH_LONG).show(); + } + } + + @Override + public void onError(int code, String message) { + if (btnRefresh != null) { + btnRefresh.setEnabled(true); + } + Toast.makeText(InspectionWeighActivity.this, + "加载失败:" + (TextUtils.isEmpty(message) ? primaryError : message), + Toast.LENGTH_LONG).show(); + } + }); + } + + /** 解析 tasks 或 weigh-station/pending 的 data 数组 */ + private boolean applyPendingBody(String body) { + try { + JSONObject obj = new JSONObject(body); + JSONObject cfg = obj.optJSONObject("config"); + if (cfg != null) { + toleranceMode = cfg.optString("weigh_match_tolerance_mode", "percent"); + toleranceValue = cfg.optDouble("weigh_match_tolerance_value", 10); + applyLabelPrintConfig(cfg); + } + updateToleranceHint(); + + JSONObject meta = obj.optJSONObject("meta"); + if (meta != null) { + pendingRowCount = meta.optInt("pending_count", 0); + pendingProductCount = meta.optInt("product_count", 0); + } + JSONArray data = obj.optJSONArray("data"); + boolean hasRows = data != null && data.length() > 0; + if (!hasRows && meta != null) { + pendingItems.clear(); + rebuildProductSpinner(); + rematch(); + syncCameraWithPending(); + if (tvCameraHint != null) { + tvCameraHint.setText(pendingRowCount > 0 + ? ("待验 " + pendingRowCount + " 行 / " + pendingProductCount + " 品,放货识别或搜索") + : "暂无待验"); + } + return true; + } + parseInspectionRows(data); + rebuildProductSpinner(); + if (meta == null) { + pendingRowCount = pendingItems.size(); + pendingProductCount = productKeys.size(); + } + rematch(); + syncCameraWithPending(); + return true; + } catch (JSONException e) { + return false; + } + } + + /** 解析待验明细行写入 pendingItems(清空后填充) */ + private void parseInspectionRows(JSONArray data) throws JSONException { + pendingItems.clear(); + if (data == null) return; + for (int i = 0; i < data.length(); i++) { + JSONObject row = data.getJSONObject(i); + InspectionTask task = new InspectionTask(); + task.id = row.optString("id"); + task.orderCode = row.optString("order_code"); + task.skuCode = row.optString("sku_code"); + task.itemName = row.optString("item_name"); + if (TextUtils.isEmpty(task.itemName)) { + task.itemName = row.optString("sku_name"); + } + task.supplierCode = row.optString("supplier_code"); + task.supplierName = row.optString("supplier_name"); + task.prepareQty = row.optDouble("prepare_qty"); + if (!(task.prepareQty > 0)) { + task.prepareQty = row.optDouble("required_qty"); + } + if (!(task.prepareQty > 0)) { + task.prepareQty = row.optDouble("purchase_qty"); + } + if (!(task.prepareQty > 0)) { + task.prepareQty = row.optDouble("order_quantity"); + } + if (!(task.prepareQty > 0)) { + task.prepareQty = row.optDouble("quantity"); + } + if (!(task.prepareQty > 0)) { + task.prepareQty = row.optDouble("planned_qty"); + } + task.receivedQty = row.optDouble("received_qty"); + task.totalDemandQty = row.optDouble("total_demand_qty"); + if (!(task.totalDemandQty > 0)) { + task.totalDemandQty = task.receivedQty + task.prepareQty; + } + task.unit = row.optString("unit"); + task.purchasePrice = row.optDouble("purchase_price"); + task.sourceType = row.optString("source_type"); + task.isPrepackaged = row.optBoolean("is_prepackaged"); + task.brand = row.optString("brand"); + task.sortOrder = row.optInt("sort_order", i); + // 缺字段时默认需拍照,与服务端 isCategoryPhotoInspectionRequired 一致 + task.photoRequired = !row.has("requires_photo_inspection") + || row.optBoolean("requires_photo_inspection", true); + task.inspectionPhotoCount = row.optInt("inspection_photo_count", 0); + if (task.inspectionPhotoCount <= 0) { + org.json.JSONArray photos = row.optJSONArray("inspection_photos"); + if (photos != null) { + task.inspectionPhotoCount = photos.length(); + } + } + task.requiresPrepackagedCheck = row.optBoolean("requires_prepackaged_check"); + pendingItems.add(task); + } + } + + /** + * 按 SKU/品名拉取该品全部待验明细并选中。 + * @param onHit 选中成功后回调(可为 null) + * @param onMiss 无数据/失败回调(可为 null,默认 Toast) + */ + private void loadProductThenApply(final String sku, final String name, final boolean fromUser, + final Runnable onHit, final Runnable onMiss) { + InspectionApi.getProduct(sku, name, new ApiClient.ApiCallback() { + @Override + public void onSuccess(int code, String body) { + if (isFinishing() || isDestroyed()) return; + try { + JSONObject obj = new JSONObject(body); + JSONArray data = obj.optJSONArray("data"); + if (data == null || data.length() == 0) { + if (onMiss != null) { + onMiss.run(); + } else { + Toast.makeText(InspectionWeighActivity.this, + "未找到该商品待验明细", Toast.LENGTH_SHORT).show(); + } + return; + } + parseInspectionRows(data); + rebuildProductSpinner(); + boolean selected = selectProduct(sku, name); + if (!selected && !productKeys.isEmpty()) { + applyProductIndex(0, fromUser); + selected = true; + } else if (selected && fromUser) { + // selectProduct 已 apply;fromUser 时补文案 + int idx = spProduct.getSelectedItemPosition(); + if (idx >= 0 && idx < productLabels.size()) { + tvRecognizedProduct.setText(productLabels.get(idx)); + tvRecognizedProduct.setTextColor(0xFF1565C0); + } + } + if (!selected) { + if (onMiss != null) { + onMiss.run(); + } else { + Toast.makeText(InspectionWeighActivity.this, + "未找到该商品待验明细", Toast.LENGTH_SHORT).show(); + } + return; + } + if (onHit != null) { + onHit.run(); + } + } catch (JSONException e) { + if (onMiss != null) { + onMiss.run(); + } else { + Toast.makeText(InspectionWeighActivity.this, + "解析商品明细失败", Toast.LENGTH_SHORT).show(); + } + } + } + + @Override + public void onError(int code, String message) { + if (isFinishing() || isDestroyed()) return; + if (onMiss != null) { + onMiss.run(); + } else { + Toast.makeText(InspectionWeighActivity.this, + "加载商品失败:" + message, Toast.LENGTH_SHORT).show(); + } + } + }); + } + + /** 无待验则停连续识别但仍确保预览;有待验(meta 或明细)则确保预览并允许连续识别 */ + private void syncCameraWithPending() { + if (cyclePhase == CyclePhase.DONE) { + refreshPreviewHint(); + return; + } + if (!hasPendingCatalog()) { + ensurePreviewWhileOnStation("预览中;暂无待验"); + return; + } + boolean needOpen = cameraHelper == null + || !cameraHelper.isPreviewing(); + if (needOpen && activityResumed) { + if (usbHotplugGuard != null && !usbHotplugGuard.canOpenNow()) { + schedulePreviewAfterUsbCooldown(); + return; + } + ensureCameraPermissionThenOpen(); + } else if (activityResumed && cameraHelper != null && cameraHelper.isPreviewing()) { + } + } + + /** 停留本台时尽量保持预览画面(空名单也开;秤空则不开;仅真预览才写「预览中」) */ + private void ensurePreviewWhileOnStation(String emptyHint) { + if (!activityResumed) return; + if (cyclePhase == CyclePhase.DONE) { + refreshPreviewHint(); + return; + } + if (currentWeightKg <= MIN_SCALE_KG) { + refreshPreviewHint(); + return; + } + if (usbHotplugGuard != null && !usbHotplugGuard.canOpenNow()) { + schedulePreviewAfterUsbCooldown(); + return; + } + boolean needOpen = cameraHelper == null || !cameraHelper.isPreviewing(); + if (needOpen) { + ensureCameraPermissionThenOpen(); + } else if (tvCameraHint != null && emptyHint != null) { + tvCameraHint.setText(emptyHint); + } + } + + /** 阈值:优先新入库 pending;失败则尝试分拣 config;再失败用默认 10% */ + private void loadToleranceConfigQuietly() { + InspectionApi.getWeighStationPending(new ApiClient.ApiCallback() { + @Override + public void onSuccess(int code, String body) { + try { + JSONObject obj = new JSONObject(body); + JSONObject cfg = obj.optJSONObject("config"); + if (cfg != null) { + toleranceMode = cfg.optString("weigh_match_tolerance_mode", toleranceMode); + toleranceValue = cfg.optDouble("weigh_match_tolerance_value", toleranceValue); + applyLabelPrintConfig(cfg); + updateToleranceHint(); + updateMatchInfo(); + } + } catch (JSONException ignored) { + } + } + + @Override + public void onError(int code, String message) { + WeighStationApi.getConfig(new ApiClient.ApiCallback() { + @Override + public void onSuccess(int c, String body) { + try { + JSONObject obj = new JSONObject(body); + JSONObject cfg = obj.optJSONObject("data"); + if (cfg == null) cfg = obj; + toleranceMode = cfg.optString("weigh_match_tolerance_mode", "percent"); + toleranceValue = cfg.optDouble("weigh_match_tolerance_value", 10); + applyLabelPrintConfig(cfg); + updateToleranceHint(); + updateMatchInfo(); + } catch (JSONException ignored) { + } + } + + @Override + public void onError(int c, String m) { + // 保持默认 percent/10 + updateToleranceHint(); + } + }); + } + }); + } + + private void rebuildProductSpinner() { + if (!preserveSimilarPickOnRebuild) { + clearSimilarPickMode(); + } + productRequiredQty.clear(); + productAccumulated.clear(); + Map nameMap = new LinkedHashMap<>(); + Map lineCount = new HashMap<>(); + for (InspectionTask item : pendingItems) { + String key = productKey(item); + if (!nameMap.containsKey(key)) { + String base = (item.itemName != null ? item.itemName : "-") + + (TextUtils.isEmpty(item.skuCode) ? "" : (" (" + item.skuCode + ")")); + nameMap.put(key, base); + } + // 同商品合并:需 = 各行本次剩余 prepare 合计;已入 = received 合计(设计 20260910-weigh-inspection-merge-similar-inline) + double remain = item.prepareQty > 0 ? item.prepareQty : 0; + double prevReq = productRequiredQty.containsKey(key) ? productRequiredQty.get(key) : 0d; + productRequiredQty.put(key, prevReq + remain); + double prevAccum = productAccumulated.containsKey(key) ? productAccumulated.get(key) : 0d; + if (item.receivedQty > 0) { + productAccumulated.put(key, prevAccum + item.receivedQty); + } + Integer n = lineCount.get(key); + lineCount.put(key, n == null ? 1 : n + 1); + } + productKeys.clear(); + productLabels.clear(); + for (Map.Entry e : nameMap.entrySet()) { + productKeys.add(e.getKey()); + double required = productRequiredQty.containsKey(e.getKey()) ? productRequiredQty.get(e.getKey()) : 0; + double accumulated = productAccumulated.containsKey(e.getKey()) ? productAccumulated.get(e.getKey()) : 0; + String unitLabel = "斤"; + for (InspectionTask it : pendingItems) { + if (e.getKey().equals(productKey(it))) { + unitLabel = WeighStationMatcher.displayUnit(it.unit); + break; + } + } + StringBuilder label = new StringBuilder(e.getValue()); + Integer lines = lineCount.get(e.getKey()); + if (lines != null && lines > 1) { + label.append(" ×").append(lines); + } + label.append(" · 需").append(formatWeight(required)).append(unitLabel); + if (accumulated > 0) { + label.append(" · 已入库").append(formatWeight(accumulated)).append(unitLabel); + if (accumulated >= required && required > 0) { + label.append(" ✓"); + } + } + productLabels.add(label.toString()); + } + suppressProductCb = true; + ArrayAdapter spinnerAdapter = new ArrayAdapter<>(this, + android.R.layout.simple_spinner_item, productLabels); + spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spProduct.setAdapter(spinnerAdapter); + lvPendingProducts.clearChoices(); + suppressProductCb = false; + hidePendingSearchBox(); + if (!preserveSimilarPickOnRebuild) { + clearRecognizedDisplay(); + productManuallySelected = false; // 刷新待验数据后重置为未选定 + } + } + + private String productKey(InspectionTask item) { + String sku = item.skuCode == null ? "" : item.skuCode.trim(); + if (!sku.isEmpty()) return "sku:" + sku; + return "name:" + WeighStationMatcher.normalizeName(item.itemName); + } + + /** 只展示识别商品:空态提示「等待识别」;不绑全表 */ + private void clearRecognizedDisplay() { + if (similarPickMode && !preserveSimilarPickOnRebuild) { + clearSimilarPickMode(); + } + shownProductIndices.clear(); + hidePendingSearchBox(); + if (!preserveSimilarPickOnRebuild) { + productManuallySelected = false; + } + if (lvPendingProducts != null && !preserveSimilarPickOnRebuild) { + ArrayAdapter listAdapter = new ArrayAdapter<>(this, + R.layout.item_pending_product, + new ArrayList<>(java.util.Collections.singletonList("等待识别… 请将商品放上秤"))); + lvPendingProducts.setAdapter(listAdapter); + lvPendingProducts.clearChoices(); + lvPendingProducts.setVisibility(View.VISIBLE); + } + if (tvRecognizedProduct != null && !preserveSimilarPickOnRebuild) { + tvRecognizedProduct.setText("等待识别…"); + tvRecognizedProduct.setTextColor(0xFF1565C0); + } + } + + /** 识别未命中:保持列表为空态 */ + private void showPendingSearchBox() { + } + + private void hidePendingSearchBox() { + if (actvPendingSearch == null) return; + // 正在输入:只清下拉数据,保留已输入文字与焦点,避免识别/刷新把输入弹没 + if (actvPendingSearch.hasFocus()) { + pendingSearchLabels.clear(); + pendingSearchSkus.clear(); + pendingSearchNames.clear(); + pendingSearchIndices.clear(); + if (pendingSearchAdapter != null) { + pendingSearchAdapter.notifyDataSetChanged(); + } + return; + } + suppressPendingSearchWatcher = true; + try { + actvPendingSearch.setText(""); + } finally { + suppressPendingSearchWatcher = false; + } + pendingSearchLabels.clear(); + pendingSearchSkus.clear(); + pendingSearchNames.clear(); + pendingSearchIndices.clear(); + if (pendingSearchAdapter != null) { + pendingSearchAdapter.notifyDataSetChanged(); + } + } + + /** 防抖后服务端模糊搜索待验商品(禁止本地扫全量) */ + private void rebuildPendingSearchOptions(String query) { + final String q = query == null ? "" : query.trim(); + if (searchDebounceRunnable != null) { + uiHandler.removeCallbacks(searchDebounceRunnable); + searchDebounceRunnable = null; + } + if (q.isEmpty()) { + pendingSearchLabels.clear(); + pendingSearchSkus.clear(); + pendingSearchNames.clear(); + pendingSearchIndices.clear(); + if (pendingSearchAdapter != null) { + pendingSearchAdapter.notifyDataSetChanged(); + } + return; + } + searchDebounceRunnable = new Runnable() { + @Override + public void run() { + final int session = ++searchSession; + InspectionApi.searchPending(q, 40, new ApiClient.ApiCallback() { + @Override + public void onSuccess(int code, String body) { + if (session != searchSession || isFinishing() || isDestroyed()) return; + try { + JSONObject obj = new JSONObject(body); + JSONArray data = obj.optJSONArray("data"); + pendingSearchLabels.clear(); + pendingSearchSkus.clear(); + pendingSearchNames.clear(); + pendingSearchIndices.clear(); + if (data != null) { + for (int i = 0; i < data.length(); i++) { + JSONObject row = data.getJSONObject(i); + String sku = row.optString("sku_code", ""); + if ("null".equals(sku)) sku = ""; + String name = row.optString("item_name", ""); + if ("null".equals(name)) name = ""; + String label = name; + if (!TextUtils.isEmpty(sku)) { + label = (TextUtils.isEmpty(name) ? "-" : name) + " (" + sku + ")"; + } else if (TextUtils.isEmpty(label)) { + label = "-"; + } + pendingSearchLabels.add(label); + pendingSearchSkus.add(sku); + pendingSearchNames.add(name); + } + } + if (pendingSearchAdapter != null) { + pendingSearchAdapter.notifyDataSetChanged(); + } + if (actvPendingSearch != null && actvPendingSearch.hasFocus()) { + try { + actvPendingSearch.showDropDown(); + } catch (Exception ignored) { + } + } + } catch (JSONException e) { + Toast.makeText(InspectionWeighActivity.this, + "搜索结果解析失败", Toast.LENGTH_SHORT).show(); + } + } + + @Override + public void onError(int code, String message) { + if (session != searchSession || isFinishing() || isDestroyed()) return; + Toast.makeText(InspectionWeighActivity.this, + "搜索失败:" + message, Toast.LENGTH_SHORT).show(); + } + }); + } + }; + uiHandler.postDelayed(searchDebounceRunnable, 300); + } + + /** 只展示识别商品:列表只渲染识别到的这一行,大字号突出显示 */ + private void showRecognizedProduct(int idx) { + if (idx < 0 || idx >= productKeys.size()) return; + shownProductIndices.clear(); + shownProductIndices.add(idx); + String label = idx < productLabels.size() ? productLabels.get(idx) : ""; + ArrayAdapter listAdapter = new ArrayAdapter<>(this, + R.layout.item_recognized_product, + new ArrayList<>(java.util.Collections.singletonList(label))); + lvPendingProducts.setAdapter(listAdapter); + lvPendingProducts.setVisibility(View.VISIBLE); + lvPendingProducts.setItemChecked(0, true); + if (tvRecognizedProduct != null) { + tvRecognizedProduct.setText(label); + tvRecognizedProduct.setTextColor(0xFF1565C0); + } + } + + private void rematch() { + matchCandidates.clear(); + matchLabels.clear(); + // 只有识别命中或用户手动点选商品后才进行匹配, + // 防止 spProduct 默认选中第一项在重量变化时被误匹配导致未识别即可提交 + if (!recognizeMatched && !productManuallySelected) { + bindMatchSpinner(null); + updateMatchInfo(); + return; + } + int pPos = spProduct.getSelectedItemPosition(); + if (pPos < 0 || pPos >= productKeys.size()) { + bindMatchSpinner(null); + updateMatchInfo(); + return; + } + String key = productKeys.get(pPos); + String sku = key.startsWith("sku:") ? key.substring(4) : ""; + String name = ""; + for (InspectionTask item : pendingItems) { + if (productKey(item).equals(key)) { + name = item.itemName; + if (sku.isEmpty()) sku = item.skuCode; + break; + } + } + List same = WeighStationMatcher.filterSameInspectionProduct(pendingItems, sku, name); + double business = businessWeightFor(activeUnit()); + InspectionTask best = WeighStationMatcher.pickBestInspection(same, business); + matchCandidates.addAll(same); + for (InspectionTask item : same) { + matchLabels.add(formatMatchLabel(item)); + } + bindMatchSpinner(best); + updateMatchInfo(); + } + + private String formatMatchLabel(InspectionTask item) { + String order = TextUtils.isEmpty(item.orderCode) ? "" : (item.orderCode + " | "); + return order + "备货 " + formatWeight(item.prepareQty) + " " + + WeighStationMatcher.displayUnit(item.unit) + + (TextUtils.isEmpty(item.supplierName) ? "" : (" | " + item.supplierName)); + } + + private void bindMatchSpinner(InspectionTask preferred) { + suppressMatchCb = true; + ArrayAdapter adapter = new ArrayAdapter<>(this, + android.R.layout.simple_spinner_item, matchLabels); + adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spMatch.setAdapter(adapter); + if (preferred != null) { + for (int i = 0; i < matchCandidates.size(); i++) { + if (preferred.id != null && preferred.id.equals(matchCandidates.get(i).id)) { + spMatch.setSelection(i); + break; + } + } + } + suppressMatchCb = false; + } + + private InspectionTask selectedMatch() { + int pos = spMatch.getSelectedItemPosition(); + if (pos < 0 || pos >= matchCandidates.size()) return null; + return matchCandidates.get(pos); + } + + /** 当前业务单位:匹配行 > 所选商品 > 默认斤 */ + private String activeUnit() { + InspectionTask match = selectedMatch(); + if (match != null && !TextUtils.isEmpty(match.unit)) { + return match.unit; + } + int pPos = spProduct.getSelectedItemPosition(); + if (pPos >= 0 && pPos < productKeys.size()) { + String key = productKeys.get(pPos); + for (InspectionTask item : pendingItems) { + if (productKey(item).equals(key) && !TextUtils.isEmpty(item.unit)) { + return item.unit; + } + } + } + return "斤"; + } + + private double businessWeightFor(String unit) { + return WeighStationMatcher.scaleKgToBusiness(currentWeightKg, unit, CanteenApp.get().getScaleUnit()); + } + + private void refreshWeightDisplay() { + // 大屏秤读数恒以「斤」展示,不随商品档案单位切换 + double jin = WeighStationMatcher.scaleKgToBusiness(currentWeightKg, "斤", CanteenApp.get().getScaleUnit()); + tvWeight.setText(formatWeight(jin) + " 斤"); + } + + private void updateToleranceHint() { + if (tvToleranceHint == null) return; + tvToleranceHint.setText("阈值校验已关闭,称重即可入库"); + } + + private void setInboundActionEnabled(boolean enabled) { + if (btnSubmit != null) btnSubmit.setEnabled(enabled); + if (btnForceComplete != null) btnForceComplete.setEnabled(enabled); + } + + private void updateMatchInfo() { + InspectionTask item = selectedMatch(); + if (item == null) { + if (tvMatchInfo != null && (tvRecognizedProduct == null + || tvRecognizedProduct.getText() == null + || "等待识别…".contentEquals(tvRecognizedProduct.getText()) + || tvMatchInfo.getText() == null + || !tvMatchInfo.getText().toString().contains("请人工检查"))) { + tvMatchInfo.setText("放上秤后自动识别"); + tvMatchInfo.setTextColor(0xFF333333); + tvMatchInfo.setVisibility(View.VISIBLE); + } + setInboundActionEnabled(false); + refreshWeightDisplay(); + return; + } + // 供应商/品名/总量/已入/实重/误差等明细不再展示(上方识别行已有需入/已入) + double settlement = businessWeightFor(item.unit); + // 非斤系(计数)单位:无需秤重即可提交(弹窗确认件数);斤系仍需先称重 + final boolean countingUnit = !WeighStationMatcher.isWeightUnit(item.unit); + if (tvMatchInfo != null) { + if (!countingUnit && settlement <= 0) { + tvMatchInfo.setText("请先称重"); + tvMatchInfo.setTextColor(0xFFEF6C00); + tvMatchInfo.setVisibility(View.VISIBLE); + } else { + tvMatchInfo.setText(""); + tvMatchInfo.setVisibility(View.GONE); + } + } + setInboundActionEnabled((countingUnit || settlement > 0) && !isSubmitting); + refreshWeightDisplay(); + scheduleAutoSubmit(); + } + + private void scheduleAutoSubmit() { + uiHandler.removeCallbacks(autoSubmitRunnable); + if (!CanteenApp.get().isAutoSubmitEnabled()) { + return; + } + if (!autoSubmitArmedByRecognize) { + return; + } + uiHandler.postDelayed(autoSubmitRunnable, AUTO_SUBMIT_STABLE_MS); + } + + /** 自动提交:合格+阈值内+有秤重;跳过确认框 */ + + private void armAutoSubmitGate() { + requireLiftOffBeforeAutoSubmit = true; + autoSubmitCooldownUntilMs = System.currentTimeMillis() + AUTO_SUBMIT_COOLDOWN_MS; + } + + private void clearAutoSubmitLiftOffOnFailure() { + if (submittingFromAutoSubmit) { + requireLiftOffBeforeAutoSubmit = false; + } + submittingFromAutoSubmit = false; + } + + private void noteScaleMaybeEmptyForAutoSubmit(double weightKg) { + if (weightKg <= MIN_SCALE_KG) { + if (requireLiftOffBeforeAutoSubmit) { + requireLiftOffBeforeAutoSubmit = false; + } + // 归零后须重新识别才可再自动提交 + autoSubmitArmedByRecognize = false; + } + } + + private boolean canAutoSubmitAfterCooldownAndLiftOff() { + if (requireLiftOffBeforeAutoSubmit) { + return false; + } + return System.currentTimeMillis() >= autoSubmitCooldownUntilMs; + } + private void maybeAutoSubmit() { + if (!CanteenApp.get().isAutoSubmitEnabled()) return; + if (!activityResumed || isSubmitting || isRecognizing) return; + if (!autoSubmitArmedByRecognize) return; + // 质量判断未返回前绝不自动提交;等结果到达后再调度 + if (assessingQuality) { + scheduleAutoSubmit(); + return; + } + // 仅当质量明确判定合格才放行;待人工/不合格/未判都挡 + if (!qualityPassForAutoSubmit) return; + if (!canAutoSubmitAfterCooldownAndLiftOff()) return; + if (!hasScaleWeight()) return; + if (System.currentTimeMillis() - lastWeightChangeAt < AUTO_SUBMIT_STABLE_MS) { + scheduleAutoSubmit(); + return; + } + if (rgQuality != null && rgQuality.getCheckedRadioButtonId() == R.id.rb_reject) { + return; + } + final InspectionTask item = selectedMatch(); + if (item == null) return; + // 非斤系(计数)单位禁止自动提交:件数需人工/AI 确认,不能用秤读数 + if (!WeighStationMatcher.isWeightUnit(item.unit)) return; + final double settlement = businessWeightFor(item.unit); + if (settlement <= 0) return; + submittingFromAutoSubmit = true; + armAutoSubmitGate(); + Toast.makeText(this, "自动提交入库…", Toast.LENGTH_SHORT).show(); + // 斤系单位:actual_qty = actual_weight = 秤读数(斤);自动提交走确认入库(可分批) + doSubmit(item, "合格", settlement, settlement, false, false); + } + + /** @param forceComplete true=偏差入库(短收也结案);false=确认入库(可分批) */ + private void confirmSubmit(boolean forceComplete) { + final InspectionTask item = selectedMatch(); + if (item == null) return; + // 非斤系(计数)单位:件数来自 AI 识别/人工确认,重量仅作参考另存 + if (!WeighStationMatcher.isWeightUnit(item.unit)) { + confirmSubmitCounting(item, forceComplete); + return; + } + if (!hasScaleWeight()) { + Toast.makeText(this, "请先将商品放上秤", Toast.LENGTH_SHORT).show(); + return; + } + final double settlement = businessWeightFor(item.unit); + if (settlement <= 0) { + Toast.makeText(this, "请先称重", Toast.LENGTH_SHORT).show(); + return; + } + + // 点击确认直接入库,不再弹二次确认框 + int qualityId = rgQuality.getCheckedRadioButtonId(); + final String quality = (qualityId == R.id.rb_reject) ? "不合格" : "合格"; + // 斤系单位:actual_qty = actual_weight = 秤读数(斤) + doSubmit(item, quality, settlement, settlement, false, forceComplete); + } + + /** 非斤系计数单位:弹窗确认件数;重量作参考另存,不污染 actual_qty */ + private void confirmSubmitCounting(final InspectionTask item, final boolean forceComplete) { + final String unit = WeighStationMatcher.displayUnit(item.unit); + final double refWeightJin = hasScaleWeight() + ? WeighStationMatcher.scaleKgToBusiness(currentWeightKg, "斤", CanteenApp.get().getScaleUnit()) + : 0; + + LinearLayout box = new LinearLayout(this); + box.setOrientation(LinearLayout.VERTICAL); + int pad = (int) (16 * getResources().getDisplayMetrics().density); + box.setPadding(pad, pad / 2, pad, pad / 2); + + final EditText etQty = new EditText(this); + etQty.setHint("数量(" + unit + ")"); + etQty.setInputType(android.text.InputType.TYPE_CLASS_NUMBER + | android.text.InputType.TYPE_NUMBER_FLAG_DECIMAL); + if (lastSuggestedQty != null && lastSuggestedQty > 0) { + etQty.setText(formatWeight(lastSuggestedQty)); + } + box.addView(etQty); + + if (refWeightJin > 0) { + android.widget.TextView tvRef = new android.widget.TextView(this); + tvRef.setText("秤上参考重量 " + formatWeight(refWeightJin) + " 斤(仅记录,不作为数量)"); + tvRef.setTextColor(0xFF666666); + tvRef.setTextSize(13); + box.addView(tvRef); + } + + new AlertDialog.Builder(this) + .setTitle((forceComplete ? "偏差入库 · " : "确认数量 · ") + + (item.itemName != null ? item.itemName : "")) + .setView(box) + .setNegativeButton("取消", null) + .setPositiveButton(forceComplete ? "偏差入库" : "确认入库", (dialog, which) -> { + double qty; + try { + qty = Double.parseDouble(etQty.getText().toString().trim()); + } catch (Exception e) { + qty = 0; + } + if (!(qty > 0)) { + Toast.makeText(this, "请填写数量(" + unit + ")", Toast.LENGTH_SHORT).show(); + return; + } + int qualityId = rgQuality.getCheckedRadioButtonId(); + final String quality = (qualityId == R.id.rb_reject) ? "不合格" : "合格"; + doSubmit(item, quality, qty, refWeightJin, false, forceComplete); + }) + .show(); + } + + private void confirmReturn() { + final InspectionTask item = selectedMatch(); + if (item == null) { + Toast.makeText(this, "请先选择待验商品", Toast.LENGTH_SHORT).show(); + return; + } + new AlertDialog.Builder(this) + .setTitle("确认退回") + .setMessage("退回将走退供/重采,不会入库。独立入库请到自采列表撤销。") + .setNegativeButton("取消", null) + .setPositiveButton("退回", (dialog, which) -> { + double qty = 0; + double weight = 0; + if (hasScaleWeight() && WeighStationMatcher.isWeightUnit(item.unit)) { + qty = businessWeightFor(item.unit); + weight = qty; + } + doSubmit(item, "不合格", qty, weight, true, false); + }) + .show(); + } + + private void doSubmit(final InspectionTask task, String quality, final double actualQty, final double actualWeightJin, + final boolean rejectFulfillment, final boolean forceComplete) { + if (cyclePhase == CyclePhase.DONE) { + Toast.makeText(this, "本单已完成,请先取下商品", Toast.LENGTH_SHORT).show(); + return; + } + isSubmitting = true; + setInboundActionEnabled(false); + if (btnReturn != null) btnReturn.setEnabled(false); + if (tvCameraHint != null) { + tvCameraHint.setText(forceComplete ? "偏差入库提交中…" : "提交中…"); + } + + final Runnable afterPhoto = new Runnable() { + @Override + public void run() { + // 验收台不录损耗:损耗参数已在 InspectionApi.complete 内固定为 0 + // 合格入库走 complete-merge;forceComplete=偏差入库(设计 20260910-weigh-force-complete-inbound) + ApiClient.ApiCallback cb = new ApiClient.ApiCallback() { + @Override + public void onSuccess(int code, String body) { + finishInboundAfterSubmit(task, actualQty, forceComplete, body, false); + } + + @Override + public void onError(int code, String message) { + // 服务端已入库、称端超时/连点:按软成功收尾(设计 20260910-weigh-submit-long-timeout) + if (isAlreadySubmittedError(code, message)) { + Toast.makeText(InspectionWeighActivity.this, + "该单已入库,请勿重复提交", Toast.LENGTH_LONG).show(); + finishInboundAfterSubmit(task, actualQty, forceComplete, null, true); + return; + } + isSubmitting = false; + if (btnReturn != null) btnReturn.setEnabled(true); + clearAutoSubmitLiftOffOnFailure(); + updateMatchInfo(); + if (tvCameraHint != null) { + tvCameraHint.setText("提交失败:" + message + "(预览保持)"); + } + Toast.makeText(InspectionWeighActivity.this, "提交失败:" + message, Toast.LENGTH_LONG).show(); + } + }; + if (rejectFulfillment) { + InspectionApi.complete(task.id, actualQty, actualWeightJin, quality, true, cb); + } else { + InspectionApi.completeMerge(task.id, actualQty, actualWeightJin, quality, forceComplete, cb); + } + } + }; + + // 开启照片=硬闸(入库与退回相同);未开启时有拍照区仍尽量归档 + if (task.inspectionPhotoCount > 0) { + afterPhoto.run(); + return; + } + final boolean mustHavePhoto = task.photoRequired; + final boolean canTryCapture = !TextUtils.isEmpty(lastRecognizePhotoB64) + || (cameraHelper != null && cameraHelper.isPreviewing()); + if (!canTryCapture) { + if (mustHavePhoto) { + isSubmitting = false; + if (btnReturn != null) btnReturn.setEnabled(true); + clearAutoSubmitLiftOffOnFailure(); + updateMatchInfo(); + Toast.makeText(this, "需要验收照片,请确保摄像头预览中", Toast.LENGTH_LONG).show(); + return; + } + afterPhoto.run(); + return; + } + + final Runnable failOrContinue = new Runnable() { + @Override + public void run() { + if (mustHavePhoto) { + isSubmitting = false; + if (btnReturn != null) btnReturn.setEnabled(true); + clearAutoSubmitLiftOffOnFailure(); + updateMatchInfo(); + if (tvCameraHint != null) { + tvCameraHint.setText("需要验收照片,请重新识别(预览保持)"); + } + Toast.makeText(InspectionWeighActivity.this, + "需要验收照片,请重新识别或手选后再提交", Toast.LENGTH_LONG).show(); + return; + } + afterPhoto.run(); + } + }; + + final Runnable uploadThenComplete = new Runnable() { + @Override + public void run() { + final String photo = lastRecognizePhotoB64; + if (TextUtils.isEmpty(photo)) { + failOrContinue.run(); + return; + } + if (tvCameraHint != null) { + tvCameraHint.setText(mustHavePhoto ? "上传识别照片…" : "归档验收照片…"); + } + InspectionApi.uploadPhoto(task.id, photo, new ApiClient.ApiCallback() { + @Override + public void onSuccess(int code, String body) { + task.inspectionPhotoCount = Math.max(1, task.inspectionPhotoCount + 1); + afterPhoto.run(); + } + + @Override + public void onError(int code, String message) { + if (mustHavePhoto) { + isSubmitting = false; + clearAutoSubmitLiftOffOnFailure(); + updateMatchInfo(); + if (tvCameraHint != null) { + tvCameraHint.setText("上传照片失败:" + message + "(预览保持)"); + } + Toast.makeText(InspectionWeighActivity.this, + "上传照片失败:" + message, Toast.LENGTH_LONG).show(); + return; + } + Toast.makeText(InspectionWeighActivity.this, + "照片归档失败,继续入库:" + message, Toast.LENGTH_SHORT).show(); + afterPhoto.run(); + } + }); + } + }; + + if (!TextUtils.isEmpty(lastRecognizePhotoB64)) { + uploadThenComplete.run(); + return; + } + if (tvCameraHint != null) { + tvCameraHint.setText("抓取验收照片…"); + } + cameraHelper.captureJpegBase64Async(92, new SimpleCameraHelper.CaptureCallback() { + @Override + public void onCaptured(String b64) { + if (isFinishing() || isDestroyed()) { + isSubmitting = false; + return; + } + if (TextUtils.isEmpty(b64)) { + failOrContinue.run(); + return; + } + lastRecognizePhotoB64 = b64; + showCaptureImage(b64, "入库归档图"); + uploadThenComplete.run(); + } + }); + } + + /** 服务端已入库、称端超时后重试:按成功收尾,避免误报失败。 */ + private static boolean isAlreadySubmittedError(int code, String message) { + if (message == null) return false; + String m = message.toLowerCase(); + if (m.contains("already_submitted")) return true; + return message.contains("已提交") || message.contains("不能重复验收") || message.contains("已入库"); + } + + /** + * 入库 HTTP 成功,或「已提交」软成功共用收尾。 + * softAlreadySubmitted=true 时不解析 body(无合并/分批提示),仍进入完成态并刷新列表。 + */ + private void finishInboundAfterSubmit(final InspectionTask task, final double actualQty, + final boolean forceComplete, String body, + boolean softAlreadySubmitted) { + isSubmitting = false; + submittingFromAutoSubmit = false; + autoSubmitArmedByRecognize = false; + lastPrintedTask = task; + lastPrintedWeight = actualQty; + refreshReprintEnabled(); + if (!softAlreadySubmitted && body != null) { + try { + JSONObject root = new JSONObject(body); + JSONObject data = root.optJSONObject("data"); + if (data == null) data = root; + org.json.JSONArray warns = data.optJSONArray("warnings"); + if (warns != null && warns.length() > 0) { + JSONObject w0 = warns.optJSONObject(0); + String msg = w0 != null ? w0.optString("message", "") : ""; + if (!TextUtils.isEmpty(msg)) { + Toast.makeText(InspectionWeighActivity.this, msg, Toast.LENGTH_LONG).show(); + } + } + boolean forced = forceComplete || data.optBoolean("forceComplete"); + int mergedCount = data.optInt("mergedCount", 0); + boolean partial = !forced && data.optBoolean("partialInbound"); + double remain = data.optDouble("remainingQty"); + String unitLabel = WeighStationMatcher.displayUnit(task.unit); + if (forced) { + Toast.makeText(InspectionWeighActivity.this, + "已偏差入库(总重 " + formatWeight(actualQty) + unitLabel + ")", + Toast.LENGTH_SHORT).show(); + } else if (mergedCount > 1 && partial) { + String key = productKey(task); + double prev = productAccumulated.containsKey(key) + ? productAccumulated.get(key) : task.receivedQty; + productAccumulated.put(key, prev + actualQty); + Toast.makeText(InspectionWeighActivity.this, + "已分批抵扣 " + mergedCount + " 条,本次 " + + formatWeight(actualQty) + unitLabel + + ",剩余 " + formatWeight(remain) + unitLabel + + " 可下次继续入", + Toast.LENGTH_LONG).show(); + } else if (mergedCount > 1) { + Toast.makeText(InspectionWeighActivity.this, + "已合并入库 " + mergedCount + " 条(总重 " + + formatWeight(actualQty) + unitLabel + ")", + Toast.LENGTH_SHORT).show(); + } else if (partial) { + String key = productKey(task); + double prev = productAccumulated.containsKey(key) + ? productAccumulated.get(key) : task.receivedQty; + productAccumulated.put(key, prev + actualQty); + Toast.makeText(InspectionWeighActivity.this, + "部分入库成功,剩余 " + formatWeight(remain) + " " + + unitLabel + " 待继续入", + Toast.LENGTH_LONG).show(); + } + } catch (Exception ignored) { + } + } + if (!TextUtils.isEmpty(lastRecognizePhotoB64)) { + showCaptureImage(lastRecognizePhotoB64, "入库归档图"); + } + rgQuality.check(R.id.rb_pass); + if (inboundLabelPrintEnabled && !softAlreadySubmitted) { + if (tvCameraHint != null) { + tvCameraHint.setText("入库成功,正在打印标签…"); + } + tryPrint(task, actualQty, new Runnable() { + @Override + public void run() { + enterInboundDone(); + loadPending(); + } + }, new Runnable() { + @Override + public void run() { + if (tvCameraHint != null) { + tvCameraHint.setText("入库成功但打印失败,可点重打;取下商品后重来"); + } + Toast.makeText(InspectionWeighActivity.this, + "标签打印失败,可点重打", Toast.LENGTH_LONG).show(); + loadPending(); + } + }); + } else { + enterInboundDone( + softAlreadySubmitted + ? "该单已入库,请取下商品后再放下一件" + : "入库完成,请取下商品后再放下一件", + softAlreadySubmitted + ? "该单已入库\n请取下商品后再放下一件" + : (inboundLabelPrintEnabled + ? "入库完成\n请取下商品,标签已打印" + : "入库完成\n请取下商品(标签打印已关闭)"), + softAlreadySubmitted ? "该单已入库" : "入库完成"); + loadPending(); + } + } + + /** 完成态:关相机;文案保留到拿下 */ + private void enterInboundDone() { + enterInboundDone( + "入库完成,请取下商品后再放下一件", + inboundLabelPrintEnabled + ? "入库完成\n请取下商品,标签已打印" + : "入库完成\n请取下商品(标签打印已关闭)", + "入库完成"); + } + + private void enterInboundDone(String cameraHint, String matchInfo, String toastMsg) { + cyclePhase = CyclePhase.DONE; + autoSubmitArmedByRecognize = false; + lastSuggestedQty = null; + lastSuggestedUnit = null; + if (streamRecognize != null) { + streamRecognize.reset(); + } + if (!TextUtils.isEmpty(lastRecognizePhotoB64)) { + showCaptureImage(lastRecognizePhotoB64, "入库归档图"); + } + if (tvCameraHint != null && cameraHint != null) { + tvCameraHint.setText(cameraHint); + } + if (tvMatchInfo != null && matchInfo != null) { + tvMatchInfo.setText(matchInfo); + tvMatchInfo.setTextColor(0xFF2E7D32); + tvMatchInfo.setVisibility(View.VISIBLE); + } + // 入库完成:按钮文字放大,置灰不可点击,等秤归零后恢复 + if (btnSubmit != null) { + btnSubmit.setText("入库完成"); + btnSubmit.setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, 28); + btnSubmit.setEnabled(false); + btnSubmit.setBackgroundResource(R.drawable.btn_bg_green_dark); + } + if (btnForceComplete != null) { + btnForceComplete.setText("—"); + btnForceComplete.setEnabled(false); + btnForceComplete.setBackgroundResource(R.drawable.btn_bg_green_dark); + } + if (btnReturn != null) { + btnReturn.setEnabled(false); + } + if (!TextUtils.isEmpty(toastMsg)) { + Toast.makeText(this, toastMsg, Toast.LENGTH_SHORT).show(); + } + refreshReprintEnabled(); + } + + private void resetSubmitButton() { + if (btnSubmit != null) { + btnSubmit.setText("确认入库"); + btnSubmit.setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, 18); + btnSubmit.setEnabled(true); + btnSubmit.setBackgroundResource(R.drawable.btn_bg_green); + } + if (btnForceComplete != null) { + btnForceComplete.setText("偏差入库"); + btnForceComplete.setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, 18); + btnForceComplete.setEnabled(true); + btnForceComplete.setBackgroundResource(R.drawable.btn_bg_green); + } + if (btnReturn != null) { + btnReturn.setEnabled(true); + } + } + + private void tryPrint(final InspectionTask task, final double weightBusiness, + final Runnable onOk, final Runnable onFail) { + if (!inboundLabelPrintEnabled) { + if (onOk != null) { + onOk.run(); + } + return; + } + if (task == null) { + if (onFail != null) { + onFail.run(); + } + return; + } + new Thread(new Runnable() { + @Override + public void run() { + final boolean ok = PrintManager.printInspectionLabel( + InspectionWeighActivity.this, + task.orderCode, + task.itemName, + weightBusiness, + WeighStationMatcher.displayUnit(task.unit), + TextUtils.isEmpty(task.supplierName) ? task.supplierCode : task.supplierName + ); + runOnUiThread(new Runnable() { + @Override + public void run() { + if (ok) { + if (onOk != null) { + onOk.run(); + } + } else if (onFail != null) { + onFail.run(); + } + } + }); + } + }).start(); + } + + private void reprintLast() { + if (!inboundLabelPrintEnabled) { + Toast.makeText(this, "入库标签打印已关闭(可在 Web 入库管理开启)", Toast.LENGTH_SHORT).show(); + return; + } + if (lastPrintedTask == null) { + Toast.makeText(this, "没有可重打的标签", Toast.LENGTH_SHORT).show(); + return; + } + Toast.makeText(this, "正在重打标签…", Toast.LENGTH_SHORT).show(); + tryPrint(lastPrintedTask, lastPrintedWeight, new Runnable() { + @Override + public void run() { + Toast.makeText(InspectionWeighActivity.this, "重打已发送", Toast.LENGTH_SHORT).show(); + } + }, new Runnable() { + @Override + public void run() { + Toast.makeText(InspectionWeighActivity.this, "标签打印失败,可点重打", Toast.LENGTH_SHORT).show(); + } + }); + } + + @Override + public void onWeightChanged(String weight, double weightKg) { + boolean hadWeightBefore = currentWeightKg > MIN_SCALE_KG; + currentWeightKg = weightKg; + lastWeightChangeAt = System.currentTimeMillis(); + noteScaleMaybeEmptyForAutoSubmit(weightKg); + // 空→有货(放回新货)即开新周期,立即进入 1 秒自动识别节拍 + boolean nowHasWeight = weightKg > MIN_SCALE_KG; + if (nowHasWeight && !hadWeightBefore + && cyclePhase != CyclePhase.ACTIVE && activityResumed) { + cyclePhase = CyclePhase.ACTIVE; + autoRecognizedForCycle = false; + recognizeMatched = false; + qualityFiredForCycle = false; + if (streamRecognize != null) { + streamRecognize.requestImmediateTick(); + } + } + // 有货→空(拿下商品)转换:2 秒后自动刷新待验(仅一次,避免空闲循环刷新) + if (!nowHasWeight && hadWeightBefore && cyclePhase != CyclePhase.DONE) { + cancelRecognizeLiftOffClear(); + recognizeLiftOffClearScheduled = true; + uiHandler.postDelayed(recognizeLiftOffClearRunnable, RECOGNIZE_LIFT_OFF_CLEAR_MS); + } + if (streamRecognize != null) { + // DONE 态也喂秤重:换货跳变(不拿空)才能被检测到并退出 DONE 重新识别 + streamRecognize.onWeightSample(weightKg, nowHasWeight); + } + syncPreviewWithScaleWeight(weightKg); + refreshWeightDisplay(); + if (pendingItems.isEmpty()) { + return; + } + if (!Double.isNaN(lastRematchKg) + && Math.abs(weightKg - lastRematchKg) < REMATCH_MIN_DELTA_KG) { + return; + } + long now = System.currentTimeMillis(); + if ((now - lastRematchAt) < REMATCH_MIN_INTERVAL_MS) { + return; + } + lastRematchAt = now; + lastRematchKg = weightKg; + rematch(); + } + + @Override + public void onError(String msg) { + Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); + } + + @Override + public void onConnected(boolean connected) { + if (connected && activityResumed) { + syncPreviewWithScaleWeight(currentWeightKg); + } + } + + private String formatWeight(double w) { + if (w <= 0) return "0.00"; + return String.format(Locale.US, "%.2f", w); + } + + @Override + protected void onDestroy() { + activityResumed = false; + if (searchDebounceRunnable != null) { + uiHandler.removeCallbacks(searchDebounceRunnable); + searchDebounceRunnable = null; + } + cancelResumePreviewWhenLoaded(); + cancelRecognizeLiftOffClear(); + cancelRetryPreviewAfterUsbCooldown(); + cancelInFlightRecognize(); + if (usbHotplugGuard != null) { + usbHotplugGuard.unregister(); + usbHotplugGuard = null; + } + if (cameraHelper != null) { + cameraHelper.release(); + cameraHelper = null; + } + if (weighManager != null) { + weighManager.release(); + } + super.onDestroy(); + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/LoginActivity.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/LoginActivity.java new file mode 100644 index 0000000..a761b92 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/LoginActivity.java @@ -0,0 +1,177 @@ +package com.canteen.weigh.ui; + +import android.content.Intent; +import android.os.Bundle; +import android.support.v7.app.AppCompatActivity; +import android.text.TextUtils; +import android.view.MotionEvent; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ProgressBar; +import android.widget.Toast; + +import com.canteen.weigh.CanteenApp; +import com.canteen.weigh.R; +import com.canteen.weigh.api.ApiClient; +import com.canteen.weigh.api.AuthApi; + +import org.json.JSONException; +import org.json.JSONObject; + +/** + * 登录界面:账号密码即可,角色由服务端返回 + */ +public class LoginActivity extends AppCompatActivity { + + private EditText etUsername; + private EditText etPassword; + private EditText etApiBase; + private Button btnLogin; + private ProgressBar progressBar; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_login); + + ButtonClickEffect.apply(findViewById(android.R.id.content)); + SoftInputHelper.enableBlankFocus(findViewById(R.id.login_root)); + + // 已登录:直达上次工作台,或进主菜单选台 + if (CanteenApp.get().isLoggedIn()) { + if (resumeLastStationIfAny()) { + return; + } + startActivity(new Intent(this, MainActivity.class)); + finish(); + return; + } + + etUsername = findViewById(R.id.et_username); + etPassword = findViewById(R.id.et_password); + etApiBase = findViewById(R.id.et_api_base); + btnLogin = findViewById(R.id.btn_login); + progressBar = findViewById(R.id.progress_bar); + + // 预填上次的服务器地址 + etApiBase.setText(CanteenApp.get().getApiBaseUrl()); + + btnLogin.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + SoftInputHelper.hide(LoginActivity.this); + doLogin(); + } + }); + } + + @Override + public boolean dispatchTouchEvent(MotionEvent ev) { + SoftInputHelper.hideOnTouchOutside(this, ev); + return super.dispatchTouchEvent(ev); + } + + private void doLogin() { + final String username = etUsername.getText().toString().trim(); + final String password = etPassword.getText().toString().trim(); + String apiBase = etApiBase.getText().toString().trim(); + + if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) { + Toast.makeText(this, "请输入用户名和密码", Toast.LENGTH_SHORT).show(); + return; + } + + // 保存服务器地址 + if (!TextUtils.isEmpty(apiBase)) { + CanteenApp.get().setApiBaseUrl(apiBase); + } + + setLoading(true); + + // 不传 role_type:由服务端按账号可用角色解析 + AuthApi.login(username, password, null, new ApiClient.ApiCallback() { + @Override + public void onSuccess(int code, String body) { + setLoading(false); + try { + JSONObject obj = new JSONObject(body); + // 与小程序/服务端一致:access_token;兼容旧字段 token + String token = obj.optString("access_token"); + if (TextUtils.isEmpty(token)) { + token = obj.optString("token"); + } + + String userId = ""; + String userName = ""; + JSONObject profile = obj.optJSONObject("profile"); + if (profile != null) { + userId = profile.optString("id"); + userName = profile.optString("full_name"); + if (TextUtils.isEmpty(userName)) { + userName = profile.optString("username"); + } + } + if (TextUtils.isEmpty(userId)) { + userId = obj.optString("user_id"); + } + if (TextUtils.isEmpty(userName)) { + userName = obj.optString("user_name"); + } + + String resolvedRole = obj.optString("role_type"); + if (TextUtils.isEmpty(resolvedRole) || "null".equals(resolvedRole)) { + Toast.makeText(LoginActivity.this, "登录失败:账号无可用角色", Toast.LENGTH_LONG).show(); + return; + } + + if (TextUtils.isEmpty(token)) { + Toast.makeText(LoginActivity.this, "登录失败:服务器未返回token", Toast.LENGTH_SHORT).show(); + return; + } + + // 保存登录态(持久化,重启免登) + CanteenApp.get().saveSession(token, userId, userName, resolvedRole); + + Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show(); + + Intent intent = new Intent(LoginActivity.this, MainActivity.class); + startActivity(intent); + finish(); + + } catch (JSONException e) { + Toast.makeText(LoginActivity.this, "解析登录响应失败", Toast.LENGTH_SHORT).show(); + } + } + + @Override + public void onError(int code, String message) { + setLoading(false); + Toast.makeText(LoginActivity.this, "登录失败:" + message, Toast.LENGTH_LONG).show(); + } + }); + } + + /** @return true 已跳转工作台 */ + private boolean resumeLastStationIfAny() { + String station = CanteenApp.get().getLastStation(); + Intent intent = null; + if (CanteenApp.STATION_INSPECTION.equals(station)) { + intent = new Intent(this, InspectionWeighActivity.class); + } else if (CanteenApp.STATION_PICKING.equals(station)) { + intent = new Intent(this, PickingWeighActivity.class); + } + if (intent == null) { + return false; + } + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); + startActivity(intent); + finish(); + return true; + } + + private void setLoading(boolean loading) { + btnLogin.setEnabled(!loading); + progressBar.setVisibility(loading ? View.VISIBLE : View.GONE); + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/MainActivity.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/MainActivity.java new file mode 100644 index 0000000..27a9fb7 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/MainActivity.java @@ -0,0 +1,169 @@ +package com.canteen.weigh.ui; + +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.support.v7.app.AppCompatActivity; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; +import android.widget.Toast; + +import com.canteen.weigh.CanteenApp; +import com.canteen.weigh.R; +import com.canteen.weigh.update.WeighAppUpdateHelper; + +/** + * 主界面:选择工作模式 + 显示字体大/中/小 + */ +public class MainActivity extends AppCompatActivity { + + private TextView tvWelcome; + private TextView tvDeviceConfig; + private Button btnInspection; + private Button btnPicking; + private Button btnDeviceSettings; + private Button btnLogout; + private Button btnFontLarge; + private Button btnFontMedium; + private Button btnFontSmall; + + private final Handler otaHandler = new Handler(Looper.getMainLooper()); + private final Runnable otaPollRunnable = new Runnable() { + @Override + public void run() { + if (isFinishing()) return; + WeighAppUpdateHelper.checkAfterLogin(MainActivity.this, false); + otaHandler.postDelayed(this, CanteenApp.OTA_CHECK_INTERVAL_MS); + } + }; + + @Override + protected void attachBaseContext(Context newBase) { + super.attachBaseContext(WeighUiFontHelper.wrap(newBase)); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + ButtonClickEffect.apply(findViewById(android.R.id.content)); + + tvWelcome = findViewById(R.id.tv_welcome); + tvDeviceConfig = findViewById(R.id.tv_device_config); + btnInspection = findViewById(R.id.btn_inspection); + btnPicking = findViewById(R.id.btn_picking); + btnDeviceSettings = findViewById(R.id.btn_device_settings); + btnLogout = findViewById(R.id.btn_logout); + btnFontLarge = findViewById(R.id.btn_font_large); + btnFontMedium = findViewById(R.id.btn_font_medium); + btnFontSmall = findViewById(R.id.btn_font_small); + + String name = CanteenApp.get().getUserName(); + if (name == null || name.isEmpty()) { + name = CanteenApp.get().getUserId(); + } + tvWelcome.setText("欢迎," + name); + + String role = CanteenApp.get().getRoleType(); + if ("inspector".equals(role)) { + btnInspection.setVisibility(View.VISIBLE); + btnPicking.setVisibility(View.GONE); + } else if ("picker".equals(role)) { + btnInspection.setVisibility(View.GONE); + btnPicking.setVisibility(View.VISIBLE); + } else { + btnInspection.setVisibility(View.VISIBLE); + btnPicking.setVisibility(View.VISIBLE); + } + + refreshFontSizeButtons(); + btnFontLarge.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + applyFontSize(CanteenApp.UI_FONT_LARGE); + } + }); + btnFontMedium.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + applyFontSize(CanteenApp.UI_FONT_MEDIUM); + } + }); + btnFontSmall.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + applyFontSize(CanteenApp.UI_FONT_SMALL); + } + }); + + btnInspection.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + CanteenApp.get().saveLastStation(CanteenApp.STATION_INSPECTION); + startActivity(new Intent(MainActivity.this, InspectionWeighActivity.class)); + } + }); + btnPicking.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + CanteenApp.get().saveLastStation(CanteenApp.STATION_PICKING); + startActivity(new Intent(MainActivity.this, PickingWeighActivity.class)); + } + }); + + btnDeviceSettings.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + startActivity(new Intent(MainActivity.this, DeviceSettingsActivity.class)); + } + }); + + btnLogout.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + CanteenApp.get().logout(); + Toast.makeText(MainActivity.this, "已退出登录", Toast.LENGTH_SHORT).show(); + Intent intent = new Intent(MainActivity.this, LoginActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); + startActivity(intent); + } + }); + } + + private void applyFontSize(String level) { + String current = CanteenApp.get().getUiFontSize(); + if (level.equals(current)) { + refreshFontSizeButtons(); + return; + } + CanteenApp.get().saveUiFontSize(level); + recreate(); + } + + private void refreshFontSizeButtons() { + String level = CanteenApp.get().getUiFontSize(); + btnFontLarge.setSelected(CanteenApp.UI_FONT_LARGE.equals(level)); + btnFontMedium.setSelected(CanteenApp.UI_FONT_MEDIUM.equals(level)); + btnFontSmall.setSelected(CanteenApp.UI_FONT_SMALL.equals(level)); + } + + @Override + protected void onResume() { + super.onResume(); + tvDeviceConfig.setText("当前设备: " + CanteenApp.get().describeSerialConfig()); + refreshFontSizeButtons(); + // 登录后拉策略 + COS(30min 节流);未配置 URL 则静默跳过 + WeighAppUpdateHelper.checkAfterLogin(this, false); + otaHandler.removeCallbacks(otaPollRunnable); + otaHandler.postDelayed(otaPollRunnable, CanteenApp.OTA_CHECK_INTERVAL_MS); + } + + @Override + protected void onPause() { + otaHandler.removeCallbacks(otaPollRunnable); + super.onPause(); + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/PickingWeighActivity.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/PickingWeighActivity.java new file mode 100644 index 0000000..6faf140 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/PickingWeighActivity.java @@ -0,0 +1,2443 @@ +package com.canteen.weigh.ui; + +import android.Manifest; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.os.Handler; +import android.os.Looper; +import android.os.Build; +import android.os.Bundle; +import android.os.SystemClock; +import android.support.annotation.NonNull; +import android.support.v4.app.ActivityCompat; +import android.support.v4.content.ContextCompat; +import android.support.v7.app.AppCompatActivity; +import android.text.Editable; +import android.text.TextUtils; +import android.text.TextWatcher; +import android.util.Log; +import android.view.TextureView; +import android.view.View; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.FrameLayout; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ListView; +import android.widget.Spinner; +import android.widget.TextView; +import android.widget.Toast; + +import com.canteen.weigh.CanteenApp; +import com.canteen.weigh.R; +import com.canteen.weigh.api.ApiClient; +import com.canteen.weigh.api.WeighStationApi; +import com.canteen.weigh.camera.VideoStreamRecognizeHelper; +import com.canteen.weigh.camera.CaptureImageHelper; +import com.canteen.weigh.camera.PreviewPinchZoomHelper; +import com.canteen.weigh.camera.SimpleCameraHelper; +import com.canteen.weigh.camera.UsbCameraHotplugGuard; +import com.canteen.weigh.model.PickingItem; +import com.canteen.weigh.print.PrintJobPoller; +import com.canteen.weigh.print.PrintManager; +import com.canteen.weigh.weigh.SceneGate; +import com.canteen.weigh.weigh.WeighManager; +import com.canteen.weigh.weigh.WeighStationMatcher; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** + * 分拣台:摄像头识别 / 手选商品 + 称重匹配 + 装框完成 + 打标 + */ +public class PickingWeighActivity extends AppCompatActivity + implements WeighManager.WeighListener, + SimpleCameraHelper.PreviewCallback, + UsbCameraHotplugGuard.Callback { + + private static final int REQ_CAMERA = 1001; + private static final long TOAST_DEDUP_MS = 8000L; + /** 低于此公斤数视为称上无货,禁止识别;并关预览 */ + private static final double MIN_SCALE_KG = 0.01; + /** 完成态:重量降到此值以下视为已拿下(残余重量可能 > MIN) */ + private static final double DONE_LIFT_OFF_KG = 0.20; + /** 有货稳定后恢复预览 */ + private static final long PREVIEW_RESUME_MS = 400L; + /** 识别命中后未确认就拿下:秤空满此时间后清空识别展示(不再一直卡住) */ + private static final long RECOGNIZE_LIFT_OFF_CLEAR_MS = 2000L; + /** 秤空自动刷新待拣的最小间隔,避免频繁刷新 */ + private static final long AUTO_REFRESH_MIN_INTERVAL_MS = 4000L; + + /** 本轮称重流水线状态 */ + private enum CyclePhase { + IDLE, + ACTIVE, + DONE + } + + private CyclePhase cyclePhase = CyclePhase.IDLE; + /** 最近一次识别抓帧(分拣无验收照片上传;本轮缓存备用) */ + private String lastRecognizePhotoB64; + + private final Handler uiHandler = new Handler(Looper.getMainLooper()); + private VideoStreamRecognizeHelper streamRecognize; + private boolean activityResumed = false; + private PrintJobPoller printJobPoller; + private long lastWeightChangeAt = 0; + private long lastRematchAt = 0; + private double lastRematchKg = Double.NaN; + private String lastRecognizedToastKey = ""; + private long lastRecognizedToastAt = 0; + /** 识别命中后用于提示;重量再变仍可再识 */ + private boolean recognizeMatched = false; + /** 识别展示当前是否在显示已识别商品(用于拿下后延时清空) */ + private boolean recognizeDisplayActive = false; + private boolean resumePreviewWhenLoadedScheduled = false; + /** 识别命中后未确认就拿下:秤空满 2 秒后清空识别展示的延时任务标记 */ + private boolean recognizeLiftOffClearScheduled = false; + /** 上次秤空自动刷新待拣的时间,用于节流 */ + private long lastAutoRefreshAt = 0L; + + private static final long REMATCH_MIN_INTERVAL_MS = 300L; + private static final double REMATCH_MIN_DELTA_KG = 0.002; + + private final Runnable resumePreviewWhenLoadedRunnable = new Runnable() { + @Override + public void run() { + resumePreviewWhenLoadedScheduled = false; + resumePreviewBecauseScaleLoaded(); + } + }; + + /** 识别命中后未确认就拿下:秤空满 2 秒后清空识别展示,避免一直卡在已识别状态 */ + private final Runnable recognizeLiftOffClearRunnable = new Runnable() { + @Override + public void run() { + recognizeLiftOffClearScheduled = false; + if (cyclePhase == CyclePhase.DONE) return; + if (currentWeightKg > MIN_SCALE_KG) return; + long now = System.currentTimeMillis(); + if (now - lastAutoRefreshAt < AUTO_REFRESH_MIN_INTERVAL_MS) return; + lastAutoRefreshAt = now; + Log.i("WeighCycle", "lift-off clear: scale empty " + RECOGNIZE_LIFT_OFF_CLEAR_MS + + "ms without confirm, auto refresh pending"); + // 刷新待拣:会清空识别展示并重新拉取待拣列表 + loadPending(); + } + }; + + private void cancelRecognizeLiftOffClear() { + if (recognizeLiftOffClearScheduled) { + recognizeLiftOffClearScheduled = false; + uiHandler.removeCallbacks(recognizeLiftOffClearRunnable); + } + } + + private final Runnable retryPreviewAfterUsbCooldown = new Runnable() { + @Override + public void run() { + if (activityResumed && currentWeightKg > MIN_SCALE_KG) { + ensurePreviewOpenForWeight(); + } + } + }; + + private TextView tvWeight; + private TextView tvToleranceHint; + private TextView tvMatchInfo; + private TextView tvCameraHint; + private TextView tvCaptureStage; + private TextureView svCamera; + private ImageView ivCapture; + private ListView lvPendingProducts; + private TextView tvListTitle; + private ListView lvMatchItems; + private Spinner spProduct; + private Spinner spMatch; + private Button btnZero; + private Button btnTare; + private Button btnRefresh; + private Button btnSubmit; + private Button btnReprint; + private Button btnRecognize; + private Button btnOpenCamera; + private LinearLayout llRecognizeEdit; + private EditText etRecognizeName; + private EditText etRecognizeWeight; + private TextView tvRecognizeWeightUnit; + private Button btnRematchName; + + private WeighManager weighManager; + private SimpleCameraHelper cameraHelper; + private PreviewPinchZoomHelper previewPinchZoom; + private UsbCameraHotplugGuard usbHotplugGuard; + private final List pendingItems = new ArrayList<>(); + private final List productKeys = new ArrayList<>(); + private final List productLabels = new ArrayList<>(); + /** pending 接口 meta:待拣行数 / 品数(默认不灌全表) */ + private int pendingRowCount = 0; + private int pendingProductCount = 0; + /** 列表当前展示的商品(productKeys 下标);只展示识别到的商品 */ + private final List shownProductIndices = new ArrayList<>(); + /** + * 相近商品待点选:候选展示在「识别商品」列表,不弹窗 + * (设计 20260911-weigh-picking-similar-inline)。 + */ + private boolean similarPickMode = false; + private boolean preserveSimilarPickOnRebuild = false; + private final List similarPickSkus = new ArrayList<>(); + private final List similarPickNames = new ArrayList<>(); + private final List similarPickLabels = new ArrayList<>(); + private final List similarPickConfs = new ArrayList<>(); + private int similarPickSelected = -1; + private final List matchCandidates = new ArrayList<>(); + private final List matchLabels = new ArrayList<>(); + /** 用户手填数量/重量后,秤值不再覆盖输入框 */ + private boolean weightEditedByUser = false; + private boolean suppressWeightWatcher = false; + + private double currentWeightKg = 0; + private boolean isSubmitting = false; + private boolean isRecognizing = false; + /** 本次识别开始时刻,超时后允许作废再拍 */ + private long recognizeStartedAtMs = 0L; + /** 须覆盖 TokenHub 视觉常见 15~43s;低于 OkHttp longClient 90s */ + private static final long RECOGNIZE_STALE_MS = 60000L; + private static final long RECOGNIZE_AUTO_RETRY_GAP_MS = 8000L; + /** + * 静止画面闸门:画面指纹 + 重量都没变时不调 AI(设计 docs/design/20260924-weigh-scene-gate-and-adaptive-retry.md)。 + * 只做「跳过本次 AI 调用」,不参与命中态/按钮/cyclePhase 判定。 + */ + private final SceneGate sceneGate = new SceneGate(); + private okhttp3.Call currentRecognizeCall = null; + private long lastRecognizeFinishedAtMs = 0L; + /** 递增以作废进行中的抓帧/识别回调 */ + private int recognizeSession = 0; + private String toleranceMode = "percent"; + private double toleranceValue = 10; + private JSONObject lastLabelPayload; + /** Web 下发:分拣标签打印,默认开 */ + private boolean pickingLabelPrintEnabled = true; + + private boolean suppressProductCb = false; + private boolean suppressMatchCb = false; + + @Override + protected void attachBaseContext(Context newBase) { + super.attachBaseContext(WeighUiFontHelper.wrap(newBase)); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + CanteenApp.get().saveLastStation(CanteenApp.STATION_PICKING); + setContentView(R.layout.activity_picking_weigh); + ButtonClickEffect.apply(findViewById(android.R.id.content)); + + tvWeight = findViewById(R.id.tv_weight); + tvToleranceHint = findViewById(R.id.tv_tolerance_hint); + tvMatchInfo = findViewById(R.id.tv_match_info); + tvCameraHint = findViewById(R.id.tv_camera_hint); + tvCaptureStage = findViewById(R.id.tv_capture_stage); + svCamera = findViewById(R.id.sv_camera); + ivCapture = findViewById(R.id.iv_capture); + FrameLayout flCameraPreview = (FrameLayout) findViewById(R.id.fl_camera_preview); + if (flCameraPreview != null && svCamera != null) { + previewPinchZoom = new PreviewPinchZoomHelper(flCameraPreview, svCamera); + } + lvPendingProducts = findViewById(R.id.lv_pending_products); + tvListTitle = findViewById(R.id.tv_list_title); + lvMatchItems = findViewById(R.id.lv_match_items); + spProduct = findViewById(R.id.sp_product); + spMatch = findViewById(R.id.sp_match); + btnZero = findViewById(R.id.btn_zero); + btnTare = findViewById(R.id.btn_tare); + btnRefresh = findViewById(R.id.btn_refresh); + btnSubmit = findViewById(R.id.btn_submit); + btnReprint = findViewById(R.id.btn_reprint); + btnRecognize = findViewById(R.id.btn_recognize); + btnOpenCamera = findViewById(R.id.btn_open_camera); + llRecognizeEdit = findViewById(R.id.ll_recognize_edit); + etRecognizeName = findViewById(R.id.et_recognize_name); + etRecognizeWeight = findViewById(R.id.et_recognize_weight); + tvRecognizeWeightUnit = findViewById(R.id.tv_recognize_weight_unit); + btnRematchName = findViewById(R.id.btn_rematch_name); + + btnRematchName.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + rematchByName(); + } + }); + if (etRecognizeWeight != null) { + etRecognizeWeight.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + if (suppressWeightWatcher) return; + weightEditedByUser = true; + updateMatchInfo(); + } + + @Override + public void afterTextChanged(Editable s) { + } + }); + } + + btnZero.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (weighManager != null) { + weighManager.zeroing(); + Toast.makeText(PickingWeighActivity.this, "已置零", Toast.LENGTH_SHORT).show(); + } + } + }); + btnTare.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (weighManager != null) { + weighManager.tare(); + Toast.makeText(PickingWeighActivity.this, "已去皮", Toast.LENGTH_SHORT).show(); + } + } + }); + btnRefresh.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + prepareManualPendingRefreshForRerecognize(); + loadPending(); + } + }); + btnSubmit.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + confirmSubmit(); + } + }); + btnReprint.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + reprintLast(); + } + }); + btnRecognize.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + recognizeFromCamera(); + } + }); + btnOpenCamera.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + connectCameraByUser(); + } + }); + Button btnLogout = findViewById(R.id.btn_logout); + if (btnLogout != null) { + btnLogout.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + performBackToMain(); + } + }); + } + usbHotplugGuard = new UsbCameraHotplugGuard(this, this); + usbHotplugGuard.register(); + streamRecognize = new VideoStreamRecognizeHelper(new VideoStreamRecognizeHelper.Host() { + @Override + public boolean canTick() { + return canAutoRecognizeTick(); + } + + @Override + public void onRecognizeTick() { + recognizeOneFrame(true); + } + + @Override + public void onRescanNeeded(boolean scaleEmpty) { + Log.i("WeighCycle", "picking onRescanNeeded scaleEmpty=" + scaleEmpty + + " kg=" + currentWeightKg + " matched=" + recognizeMatched); + if (btnRecognize != null) { + btnRecognize.setEnabled(true); + } + if (cameraHelper != null) { + cameraHelper.disarmSceneChangeDetection(); + } + // 完成态换货:退出 DONE 再识别 + if (!scaleEmpty && cyclePhase == CyclePhase.DONE) { + exitDoneForNewCycle(); + recognizeSession++; + isRecognizing = false; + recognizeMatched = false; + if (currentWeightKg > MIN_SCALE_KG && streamRecognize != null) { + streamRecognize.start(); + } + return; + } + // 已命中且秤未空:忽略重量微跳,不重识别(对齐验收称) + if (!scaleEmpty && recognizeMatched) { + Log.i("WeighCycle", "picking ignore weight-jump rescan while matched"); + return; + } + recognizeSession++; + isRecognizing = false; + if (scaleEmpty) { + // 空秤 = 新一件:闸门复位,拿下来再放回去一定会重新识别 + sceneGate.reset(); + recognizeMatched = false; + } + if (!scaleEmpty && currentWeightKg > MIN_SCALE_KG && streamRecognize != null) { + streamRecognize.start(); + } + } + + @Override + public boolean isCameraFrameStable() { + return cameraHelper != null && cameraHelper.isPreviewFrameStable(); + } + }); + + lvPendingProducts.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + if (similarPickMode) { + onSimilarCandidatePicked(position); + return; + } + if (position < 0 || position >= shownProductIndices.size()) return; + applyProductIndex(shownProductIndices.get(position), true); + } + }); + + if (lvMatchItems != null) { + lvMatchItems.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + if (position < 0 || position >= pendingItems.size()) return; + PickingItem item = pendingItems.get(position); + // 通过隐藏 Spinner 联动到同品订单行 + int idx = matchCandidates.indexOf(item); + if (idx >= 0) { + suppressMatchCb = true; + if (spMatch != null) { + spMatch.setSelection(idx); + } + suppressMatchCb = false; + } + lvMatchItems.setItemChecked(position, true); + updateMatchInfo(); + } + }); + } + + spProduct.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (suppressProductCb) return; + recognizeMatched = false; + rematch(); + } + + @Override + public void onNothingSelected(AdapterView parent) { + } + }); + spMatch.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (suppressMatchCb) return; + updateMatchInfo(); + } + + @Override + public void onNothingSelected(AdapterView parent) { + } + }); + + View root = findViewById(android.R.id.content); + root.post(new Runnable() { + @Override + public void run() { + startHardwareAndData(); + } + }); + } + + private void startHardwareAndData() { + // 京源 WeighSdk.openSerialPort 内部会 new Handler,必须在主线程调用 + weighManager = WeighManager.get(); + weighManager.init(this); + if (currentWeightKg <= MIN_SCALE_KG) { + currentWeightKg = weighManager.getLastWeightKg(); + } + // 预览常开:进入工作台即打开,无需先放货 + ensureCameraPermissionThenOpen(); + loadPending(); + } + + @Override + protected void onResume() { + super.onResume(); + activityResumed = true; + if (printJobPoller == null) { + printJobPoller = new PrintJobPoller(this); + } + printJobPoller.start(); + // 预览常开:回到工作台确保预览开启 + if (cameraHelper == null || !cameraHelper.isPreviewing()) { + ensureCameraPermissionThenOpen(); + } + } + + @Override + protected void onPause() { + activityResumed = false; + if (printJobPoller != null) { + printJobPoller.stop(); + } + cancelResumePreviewWhenLoaded(); + cancelRecognizeLiftOffClear(); + cancelRetryPreviewAfterUsbCooldown(); + cancelInFlightRecognize(); + if (cameraHelper != null) { + cameraHelper.closeCameraKeepWant(); + } + super.onPause(); + } + + @Override + public void onHotplugCloseCamera() { + cancelInFlightRecognize(); + if (cameraHelper != null) { + cameraHelper.closeCameraAndClearWant(); + } + schedulePreviewAfterUsbCooldown(); + } + + @Override + public void onHotplugMessage(String message) { + if (tvCameraHint != null) { + tvCameraHint.setText(message); + } + } + + private boolean canAutoRecognizeTick() { + long now = SystemClock.elapsedRealtime(); + boolean retryGapOk = lastRecognizeFinishedAtMs <= 0L + || now - lastRecognizeFinishedAtMs >= RECOGNIZE_AUTO_RETRY_GAP_MS; + return activityResumed + && cyclePhase == CyclePhase.ACTIVE + && !isRecognizing + && retryGapOk + && !isSubmitting + && !recognizeMatched + && cameraHelper != null + && cameraHelper.isPreviewing() + && (pendingRowCount > 0 || !pendingItems.isEmpty()) + && currentWeightKg > MIN_SCALE_KG + && (usbHotplugGuard == null || usbHotplugGuard.canOpenNow()); + } + + /** + * 命中后不再用画面指纹自动重识别(对齐验收称)。 + * 换货靠秤空→再放,或手动刷新待拣 / 点识别。 + * 设计 20260910-weigh-no-rerecognize-stable-weight + */ + private void armSceneChangeWatch() { + if (cameraHelper != null) { + cameraHelper.disarmSceneChangeDetection(); + } + } + + private void cancelInFlightRecognize() { + recognizeSession++; + isRecognizing = false; + if (btnRecognize != null) { + btnRecognize.setEnabled(true); + } + if (streamRecognize != null) { + streamRecognize.stop(); + } + } + + private void resetStreamForNewCycle() { + if (streamRecognize != null) { + streamRecognize.reset(); + } + } + + private boolean isStaleRecognizeSession(int session) { + return session != recognizeSession; + } + + private void refreshPreviewHint() { + if (tvCameraHint == null) { + return; + } + if (cyclePhase == CyclePhase.DONE) { + tvCameraHint.setText("装框完成,请取下商品后再放下一件"); + return; + } + boolean previewing = cameraHelper != null && cameraHelper.isPreviewing(); + if (!previewing) { + if (currentWeightKg <= MIN_SCALE_KG) { + tvCameraHint.setText("秤空,相机已关,等待下一件"); + } else if (usbHotplugGuard != null && !usbHotplugGuard.canOpenNow()) { + long sec = (usbHotplugGuard.remainingCooldownMs() + 999) / 1000; + tvCameraHint.setText("USB 冷却中(约 " + sec + " 秒),结束后自动开预览"); + } else if (activityResumed) { + tvCameraHint.setText("正在连接相机(抓拍用)…"); + } else { + tvCameraHint.setText("相机未开启"); + } + return; + } + if (currentWeightKg <= MIN_SCALE_KG) { + tvCameraHint.setText("秤空,预览约 30 秒后关闭"); + return; + } + if (pendingRowCount <= 0 && pendingItems.isEmpty()) { + tvCameraHint.setText("相机就绪;暂无待拣"); + return; + } + tvCameraHint.setText("相机就绪"); + } + + private void showCaptureImage(String b64, String stageLabel) { + if (tvCaptureStage != null && stageLabel != null) { + tvCaptureStage.setText(stageLabel); + } + // 拍照区为实时预览,不定格铺图 + } + + private void clearCaptureImage(String stageLabel) { + CaptureImageHelper.clear(ivCapture); + if (tvCaptureStage != null) { + tvCaptureStage.setText(stageLabel != null ? stageLabel : "等待识别…"); + } + } + + private void applyLabelPrintConfig(JSONObject cfg) { + if (cfg == null) { + return; + } + if (cfg.has("picking_label_print_enabled")) { + pickingLabelPrintEnabled = cfg.optBoolean("picking_label_print_enabled", true); + } + refreshReprintEnabled(); + } + + private void refreshReprintEnabled() { + if (btnReprint == null) { + return; + } + boolean can = pickingLabelPrintEnabled && lastLabelPayload != null; + btnReprint.setEnabled(can); + btnReprint.setVisibility(pickingLabelPrintEnabled ? View.VISIBLE : View.GONE); + } + + private void connectCameraByUser() { + if (usbHotplugGuard != null && !usbHotplugGuard.canOpenNow()) { + long sec = (usbHotplugGuard.remainingCooldownMs() + 999) / 1000; + Toast.makeText(this, "USB 刚插拔,请再等 " + sec + " 秒后再连接", Toast.LENGTH_SHORT).show(); + if (tvCameraHint != null) { + tvCameraHint.setText("冷却中(约 " + sec + " 秒),勿立刻打开摄像头"); + } + return; + } + // 完成态仍压着货时,允许手动开预览进入下一轮 + if (cyclePhase == CyclePhase.DONE && currentWeightKg > DONE_LIFT_OFF_KG) { + cyclePhase = CyclePhase.ACTIVE; + recognizeMatched = false; + } + ensureCameraPermissionThenOpen(); + } + + /** 有重量则自动开预览,不依赖「连接摄像头」按钮 */ + private void ensurePreviewOpenForWeight() { + if (!activityResumed || currentWeightKg <= MIN_SCALE_KG) { + return; + } + if (usbHotplugGuard != null && !usbHotplugGuard.canOpenNow()) { + schedulePreviewAfterUsbCooldown(); + return; + } + if (cyclePhase == CyclePhase.DONE && currentWeightKg > DONE_LIFT_OFF_KG) { + cyclePhase = CyclePhase.ACTIVE; + recognizeMatched = false; + } + if (cameraHelper != null && cameraHelper.isPreviewing()) { + refreshPreviewHint(); + return; + } + ensureCameraPermissionThenOpen(); + } + + private void schedulePreviewAfterUsbCooldown() { + if (usbHotplugGuard == null) { + return; + } + long left = usbHotplugGuard.remainingCooldownMs(); + uiHandler.removeCallbacks(retryPreviewAfterUsbCooldown); + if (left <= 0) { + ensurePreviewOpenForWeight(); + return; + } + if (tvCameraHint != null) { + tvCameraHint.setText("USB 冷却中(约 " + ((left + 999) / 1000) + " 秒),结束后自动开预览"); + } + uiHandler.postDelayed(retryPreviewAfterUsbCooldown, left + 80); + } + + private void cancelRetryPreviewAfterUsbCooldown() { + uiHandler.removeCallbacks(retryPreviewAfterUsbCooldown); + } + + private void ensureCameraPermissionThenOpen() { + if (Build.VERSION.SDK_INT >= 23) { + if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) + != PackageManager.PERMISSION_GRANTED) { + ActivityCompat.requestPermissions(this, + new String[]{Manifest.permission.CAMERA}, REQ_CAMERA); + tvCameraHint.setText("需要摄像头权限后才能识别"); + return; + } + } + openCamera(); + } + + /** 返回主界面选台(保留登录;清 last_station) */ + private void performBackToMain() { + CanteenApp.get().clearLastStation(); + Intent intent = new Intent(this, MainActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); + startActivity(intent); + finish(); + } + + private void openCamera() { + if (usbHotplugGuard != null && !usbHotplugGuard.canOpenNow()) { + schedulePreviewAfterUsbCooldown(); + return; + } + if (cameraHelper == null) { + cameraHelper = new SimpleCameraHelper(svCamera, this); + if (previewPinchZoom != null) { + cameraHelper.setVisibleCropProvider(previewPinchZoom); + } + } + // 帧缓存最多 0.3 秒旧,保证拍到的是当前秤上的货(识别节奏由「识别间隔」设置控制) + cameraHelper.setPreviewFrameMinIntervalMs(300L); + // 预览常开:无论秤上有无货都打开;秤空仅停识别节拍 + cyclePhase = currentWeightKg > MIN_SCALE_KG ? CyclePhase.ACTIVE : CyclePhase.IDLE; + cameraHelper.setAllowPreview(true); + tvCameraHint.setText(currentWeightKg > MIN_SCALE_KG + ? "正在连接摄像头…(失败可手选)" + : "正在连接摄像头…(秤空,预览保持)"); + cameraHelper.requestOpen(); + } + + /** 秤空保持预览常开 / 有货确保预览开启;识别节拍由 VideoStreamRecognizeHelper 按秤重自控 */ + private void syncPreviewWithScaleWeight(double weightKg) { + if (!activityResumed) { + return; + } + if (cyclePhase == CyclePhase.DONE) { + if (weightKg <= DONE_LIFT_OFF_KG) { + exitDoneToIdleAfterLiftOff(); + } + return; + } + if (weightKg <= MIN_SCALE_KG) { + // 秤空:预览保持常开,不再安排关闭 + cancelResumePreviewWhenLoaded(); + if (cyclePhase == CyclePhase.ACTIVE) { + cyclePhase = CyclePhase.IDLE; + } + // 自动刷新在 onWeightChanged 的「有货→空」转换处一次性调度,此处不再循环调度 + refreshPreviewHint(); + } else { + // 有货:取消待清空 + cancelRecognizeLiftOffClear(); + if (cameraHelper != null && cameraHelper.isPreviewing()) { + return; + } + if (!resumePreviewWhenLoadedScheduled) { + resumePreviewWhenLoadedScheduled = true; + uiHandler.postDelayed(resumePreviewWhenLoadedRunnable, PREVIEW_RESUME_MS); + } + } + } + + private void cancelResumePreviewWhenLoaded() { + uiHandler.removeCallbacks(resumePreviewWhenLoadedRunnable); + resumePreviewWhenLoadedScheduled = false; + } + + /** 完成态未拿空、直接换下一件(重量跳变)→ 回 ACTIVE 重新识别 */ + private void exitDoneForNewCycle() { + if (cyclePhase != CyclePhase.DONE) { + return; + } + cyclePhase = CyclePhase.ACTIVE; + lastRecognizePhotoB64 = null; + recognizeMatched = false; + if (tvCameraHint != null) { + tvCameraHint.setText("检测到换货,重新识别…"); + } + } + + /** 完成态已拿下 → IDLE,预览先保持,空秤满 30 秒再关 */ + private void exitDoneToIdleAfterLiftOff() { + if (cyclePhase != CyclePhase.DONE) { + return; + } + cancelRecognizeLiftOffClear(); + cancelInFlightRecognize(); + resetStreamForNewCycle(); + cyclePhase = CyclePhase.IDLE; + lastRecognizePhotoB64 = null; + recognizeMatched = false; + clearRecognizedDisplay(); + clearCaptureImage("等待识别…"); + if (tvCameraHint != null) { + tvCameraHint.setText("秤空,预览保持,放上货物即可识别"); + } + } + + private void pausePreviewBecauseScaleEmpty() { + if (cyclePhase == CyclePhase.DONE) { + if (currentWeightKg > DONE_LIFT_OFF_KG) { + return; + } + exitDoneToIdleAfterLiftOff(); + return; + } else if (currentWeightKg > MIN_SCALE_KG) { + return; + } + cancelInFlightRecognize(); + resetStreamForNewCycle(); + // 预览保持常开,不 setAllowPreview(false) + cyclePhase = CyclePhase.IDLE; + lastRecognizePhotoB64 = null; + // 拿开即视为本轮结束:复位识别态,放回新货可自动重识(不依赖场景指纹/重量跳变) + recognizeMatched = false; + if (cameraHelper != null) { + cameraHelper.disarmSceneChangeDetection(); + } + clearRecognizedDisplay(); + clearCaptureImage("等待识别…"); + if (tvCameraHint != null) { + tvCameraHint.setText("秤空,预览保持,放上货物即可识别"); + } + } + + private void resumePreviewBecauseScaleLoaded() { + if (currentWeightKg <= MIN_SCALE_KG || !activityResumed) { + return; + } + if (cyclePhase == CyclePhase.DONE) { + refreshPreviewHint(); + return; + } + if (usbHotplugGuard != null && !usbHotplugGuard.canOpenNow()) { + schedulePreviewAfterUsbCooldown(); + return; + } + cyclePhase = CyclePhase.ACTIVE; + if (cameraHelper == null) { + ensureCameraPermissionThenOpen(); + return; + } + cameraHelper.setAllowPreview(true); + if (!cameraHelper.isPreviewing() && !cameraHelper.isOpening()) { + openCamera(); + } else { + refreshPreviewHint(); + captureFrameForDisplay(); + } + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, + @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + if (requestCode == REQ_CAMERA) { + if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + openCamera(); + } else { + tvCameraHint.setText("未授权摄像头,可手选商品"); + } + } + } + + @Override + public void onCameraError(String msg) { + if (tvCameraHint != null) { + tvCameraHint.setText((msg != null ? msg : "摄像头不可用") + "(可手选)"); + } + } + + @Override + public void onCameraReady() { + if (previewPinchZoom != null) { + previewPinchZoom.apply(); + } + refreshPreviewHint(); + captureFrameForDisplay(); + // 相机就绪立即抽一帧,不等下一个识别周期 + if (streamRecognize != null + && currentWeightKg > MIN_SCALE_KG + && cyclePhase != CyclePhase.DONE) { + streamRecognize.requestImmediateTick(); + } + } + + /** 相机就绪:拍照区已是实时预览,只更新阶段文案 */ + private void captureFrameForDisplay() { + if (tvCaptureStage != null && currentWeightKg > MIN_SCALE_KG) { + tvCaptureStage.setText("实时预览"); + } + } + + private boolean hasScaleWeight() { + return currentWeightKg > MIN_SCALE_KG; + } + + /** + * 「画面 + 重量都没变」→ 跳过本次 AI 调用(省钱、防夜班空转)。 + * 设计 docs/design/20260924-weigh-scene-gate-and-adaptive-retry.md + * + *

硬约束:本方法只回答「这一拍要不要调 AI」,不得触碰 {@code recognizeMatched}、 + * 按钮可用性、{@code cyclePhase}、{@code lastRecognizePhotoB64}。20260910 的「换货检测」就是因为 + * 误判换货清掉命中态、按钮置灰而被停用,不要再犯。 + * + *

只对自动节拍(silent)生效;手动点「识别」/刷新待拣永不受闸门限制。 + */ + private boolean shouldSkipUnchangedScene() { + CanteenApp app = CanteenApp.get(); + if (cameraHelper == null || app == null || !app.isSceneGateEnabled()) { + return false; + } + // 取不到指纹时返回 0,SceneGate 按「未知 = 放行」处理 + long hash = cameraHelper.probeSceneHash(); + boolean skip = sceneGate.shouldSkip( + hash, currentWeightKg, android.os.SystemClock.elapsedRealtime(), true); + if (skip) { + Log.i("WeighCycle", "picking scene unchanged, skip AI skipCount=" + sceneGate.skipCount() + + " kg=" + currentWeightKg + " hash=" + hash); + } + return skip; + } + + private void recognizeFromCamera() { + recognizeOneFrame(false); + } + + private void recognizeOneFrame(final boolean silent) { + if (isRecognizing) { + if (!silent) { + long elapsed = SystemClock.elapsedRealtime() - recognizeStartedAtMs; + if (recognizeStartedAtMs > 0 && elapsed >= RECOGNIZE_STALE_MS) { + Log.i("WeighCycle", "picking recognize stale " + elapsed + "ms, cancel old and retry"); + if (currentRecognizeCall != null && !currentRecognizeCall.isCanceled()) { + currentRecognizeCall.cancel(); + } + currentRecognizeCall = null; + recognizeSession++; + isRecognizing = false; + recognizeStartedAtMs = 0L; + if (btnRecognize != null) { + btnRecognize.setEnabled(true); + } + } else { + Toast.makeText(this, "正在识别中,请稍候", Toast.LENGTH_SHORT).show(); + return; + } + } else { + return; + } + } + if (!hasScaleWeight()) { + if (!silent) { + Toast.makeText(this, "请先将商品放上秤再识别", Toast.LENGTH_SHORT).show(); + } + return; + } + if (pendingRowCount <= 0 && pendingItems.isEmpty()) { + if (!silent) { + Toast.makeText(this, "暂无待拣明细,请先刷新", Toast.LENGTH_SHORT).show(); + } + return; + } + if (cameraHelper == null || !cameraHelper.isPreviewing()) { + if (!silent) { + Toast.makeText(this, "摄像头未就绪,请授权后重试或手选", Toast.LENGTH_SHORT).show(); + } + ensureCameraPermissionThenOpen(); + return; + } + // 画面与重量都没变 → 不抓整图、不发 HTTP、不调 AI(只跳过 AI 调用,不动命中态)。 + // 设计 docs/design/20260924-weigh-scene-gate-and-adaptive-retry.md + if (silent && shouldSkipUnchangedScene()) { + return; + } + if (!silent) { + recognizeMatched = false; + } + isRecognizing = true; + recognizeStartedAtMs = SystemClock.elapsedRealtime(); + final int session = recognizeSession; + if (!silent && btnRecognize != null) { + btnRecognize.setEnabled(false); + } + if (tvCameraHint != null) { + tvCameraHint.setText("识别中…"); + } + cameraHelper.captureJpegBase64Async(92, new SimpleCameraHelper.CaptureCallback() { + @Override + public void onCaptured(String b64) { + long captureMs = SystemClock.elapsedRealtime() - recognizeStartedAtMs; + Log.i("WeighCycle", "picking onCaptured: b64len=" + (b64 != null ? b64.length() : 0) + + " captureMs=" + captureMs); + if (isStaleRecognizeSession(session)) { + return; + } + if (isFinishing() || isDestroyed()) { + isRecognizing = false; + lastRecognizeFinishedAtMs = SystemClock.elapsedRealtime(); + return; + } + if (TextUtils.isEmpty(b64)) { + isRecognizing = false; + lastRecognizeFinishedAtMs = SystemClock.elapsedRealtime(); + if (btnRecognize != null) { + btnRecognize.setEnabled(true); + } + if (!silent) { + Toast.makeText(PickingWeighActivity.this, "抓帧失败,请稍候再试或手选", Toast.LENGTH_SHORT).show(); + } + return; + } + lastRecognizePhotoB64 = b64; + showCaptureImage(b64, "识别抓拍"); + final long httpStartMs = SystemClock.elapsedRealtime(); + currentRecognizeCall = WeighStationApi.recognize(null, null, b64, new ApiClient.ApiCallback() { + @Override + public void onSuccess(int code, String body) { + currentRecognizeCall = null; + long httpMs = SystemClock.elapsedRealtime() - httpStartMs; + long totalMs = SystemClock.elapsedRealtime() - recognizeStartedAtMs; + Log.i("WeighCycle", "picking recognize done: httpMs=" + httpMs + + " totalMs=" + totalMs + " code=" + code); + if (isStaleRecognizeSession(session)) { + return; + } + isRecognizing = false; + lastRecognizeFinishedAtMs = SystemClock.elapsedRealtime(); + if (btnRecognize != null) { + btnRecognize.setEnabled(true); + } + if (!isFinishing() && !isDestroyed()) { + applyRecognizeResult(body, silent); + } + } + + @Override + public void onError(int code, String message) { + currentRecognizeCall = null; + long httpMs = SystemClock.elapsedRealtime() - httpStartMs; + Log.i("WeighCycle", "picking recognize error: httpMs=" + httpMs + + " code=" + code + " msg=" + message); + if (isStaleRecognizeSession(session)) { + return; + } + isRecognizing = false; + lastRecognizeFinishedAtMs = SystemClock.elapsedRealtime(); + if (btnRecognize != null) { + btnRecognize.setEnabled(true); + } + if (tvCameraHint != null) { + tvCameraHint.setText("识别失败:" + message + "(预览保持,可重试或手选)"); + } + if (!silent && !isFinishing() && !isDestroyed()) { + Toast.makeText(PickingWeighActivity.this, + "识别失败:" + message, Toast.LENGTH_LONG).show(); + } + } + }); + } + }); + } + + private void applyRecognizeResult(String body, boolean silent) { + try { + JSONObject root = new JSONObject(body); + JSONObject data = root.optJSONObject("data"); + if (data == null) data = root; + + String message = data.optString("message", ""); + JSONObject recognized = data.optJSONObject("recognized"); + JSONArray candidates = data.optJSONArray("candidates"); + + String sku = null; + String name = null; + double confidence = 0; + boolean catalogMatched = true; + if (recognized != null) { + sku = recognized.optString("sku_code", null); + if ("null".equals(sku) || TextUtils.isEmpty(sku)) sku = null; + name = recognized.optString("item_name", null); + if ("null".equals(name) || TextUtils.isEmpty(name)) name = null; + confidence = recognized.optDouble("confidence", 0); + catalogMatched = !recognized.has("catalog_matched") || recognized.optBoolean("catalog_matched", true); + } + if ((sku == null && name == null) && candidates != null && candidates.length() > 0) { + JSONObject top = candidates.getJSONObject(0); + sku = top.optString("sku_code", null); + if ("null".equals(sku) || TextUtils.isEmpty(sku)) sku = null; + name = top.optString("item_name", null); + if ("null".equals(name) || TextUtils.isEmpty(name)) name = null; + confidence = top.optDouble("confidence", confidence); + } + if (recognized != null && !catalogMatched && name != null) { + recognizeMatched = false; + clearRecognizedDisplay(); + String tip = TextUtils.isEmpty(message) + ? ("识别到「" + name + "」,但不在待拣名单,请手选") + : message; + if (tvMatchInfo != null) { + tvMatchInfo.setText(name + + String.format(Locale.US, " (%.0f%%) · 未命中名单", confidence * 100)); + tvMatchInfo.setTextColor(0xFFC62828); + tvMatchInfo.setVisibility(View.VISIBLE); + } + tvCameraHint.setText(tip); + btnSubmit.setEnabled(false); + if (!silent) { + Toast.makeText(this, tip, Toast.LENGTH_LONG).show(); + } + boolean needSelect = data.optBoolean("need_select", false) + || hasSimilarPickCandidates(candidates); + if (needSelect) { + showSimilarCandidatesInProductColumn(candidates); + } + return; + } + if (recognized != null && confidence > 0 && confidence < 0.6) { + recognizeMatched = false; + tvCameraHint.setText(TextUtils.isEmpty(message) ? "识别不够确定,请手选或重拍" : message); + return; + } + if (sku == null && name == null) { + recognizeMatched = false; + clearRecognizedDisplay(); + String tip = TextUtils.isEmpty(message) ? "识别未命中待拣名单,请人工检查" : message; + tvCameraHint.setText(tip); + btnSubmit.setEnabled(false); + if (!silent) { + Toast.makeText(this, tip, Toast.LENGTH_LONG).show(); + } + return; + } + + // 唯一命中但名单有多条相近:识别商品列内选,不弹窗 + // 设计 20260911-weigh-picking-similar-inline + boolean needSelectOnMatch = data.optBoolean("need_select", false) + || hasSimilarPickCandidates(candidates); + if (needSelectOnMatch && candidates != null && candidates.length() > 1) { + recognizeMatched = false; + String tip = TextUtils.isEmpty(message) + ? ("识别到「" + (name != null ? name : "") + "」,请在下方点选相近商品") + : message; + tvCameraHint.setText(tip); + if (tvMatchInfo != null && name != null) { + tvMatchInfo.setText(name + + String.format(Locale.US, " (%.0f%%) · 请点选相近商品", confidence * 100)); + tvMatchInfo.setTextColor(0xFF1565C0); + tvMatchInfo.setVisibility(View.VISIBLE); + } + if (!silent) { + Toast.makeText(this, tip, Toast.LENGTH_LONG).show(); + } + showSimilarCandidatesInProductColumn(candidates); + return; + } + + final String fMessage = message; + final String fSku = sku; + final String fName = name; + final double fConfidence = confidence; + final boolean fSilent = silent; + final String tipBase = name != null ? name : sku; + loadProductThenApply(sku, name, false, new Runnable() { + @Override + public void run() { + String tip = "已识别:" + tipBase + + String.format(Locale.US, " (%.0f%%)", fConfidence * 100); + tvCameraHint.setText(tip); + String key = (fSku != null ? fSku : "") + "|" + (fName != null ? fName : ""); + long now = System.currentTimeMillis(); + if (!fSilent || !key.equals(lastRecognizedToastKey) || now - lastRecognizedToastAt > TOAST_DEDUP_MS) { + Toast.makeText(PickingWeighActivity.this, tip, Toast.LENGTH_SHORT).show(); + lastRecognizedToastKey = key; + lastRecognizedToastAt = now; + } + recognizeMatched = true; + armSceneChangeWatch(); + } + }, new Runnable() { + @Override + public void run() { + recognizeMatched = false; + clearRecognizedDisplay(); + String tip = TextUtils.isEmpty(fMessage) ? "识别未命中待拣名单,请人工检查" : fMessage; + tvCameraHint.setText(tip); + btnSubmit.setEnabled(false); + if (!fSilent) { + Toast.makeText(PickingWeighActivity.this, tip, Toast.LENGTH_LONG).show(); + } + } + }); + } catch (JSONException e) { + if (!silent) { + Toast.makeText(this, "识别结果解析失败", Toast.LENGTH_SHORT).show(); + } + } + } + + /** 相近候选:confidence≥0.6(设计 20260909-weigh-similar-candidates-pick) */ + private boolean hasSimilarPickCandidates(JSONArray candidates) { + if (candidates == null) return false; + for (int i = 0; i < candidates.length(); i++) { + JSONObject c = candidates.optJSONObject(i); + if (c != null && c.optDouble("confidence", 0) >= 0.6) return true; + } + return false; + } + + /** 相近商品写入「识别商品」列表;默认绑定最像,仍可点选改绑 */ + private void showSimilarCandidatesInProductColumn(JSONArray candidates) { + if (candidates == null || candidates.length() == 0) return; + final List skus = new ArrayList<>(); + final List names = new ArrayList<>(); + final List confs = new ArrayList<>(); + for (int i = 0; i < candidates.length(); i++) { + JSONObject c = candidates.optJSONObject(i); + if (c == null) continue; + double conf = c.optDouble("confidence", 0); + if (conf < 0.6) continue; + String itemName = c.optString("item_name", null); + if ("null".equals(itemName) || TextUtils.isEmpty(itemName)) itemName = null; + String sku = c.optString("sku_code", null); + if ("null".equals(sku) || TextUtils.isEmpty(sku)) sku = null; + if (itemName == null && sku == null) continue; + skus.add(sku); + names.add(itemName); + confs.add(conf); + } + if (names.isEmpty()) return; + + for (int i = 0; i < confs.size(); i++) { + for (int j = i + 1; j < confs.size(); j++) { + if (confs.get(j) > confs.get(i)) { + double tc = confs.get(i); confs.set(i, confs.get(j)); confs.set(j, tc); + String ts = skus.get(i); skus.set(i, skus.get(j)); skus.set(j, ts); + String tn = names.get(i); names.set(i, names.get(j)); names.set(j, tn); + } + } + } + + final List labels = new ArrayList<>(); + for (int i = 0; i < names.size(); i++) { + labels.add(formatSimilarCandidateLabel(names.get(i), skus.get(i), confs.get(i))); + } + + if (similarPickMode + && labels.size() == similarPickNames.size() + && namesEquals(similarPickNames, names) + && namesEquals(similarPickSkus, skus)) { + rebuildSimilarPickLabelsFromDemand(); + renderSimilarCandidatesList(similarPickSelected); + return; + } + + similarPickMode = true; + similarPickSkus.clear(); + similarPickNames.clear(); + similarPickLabels.clear(); + similarPickConfs.clear(); + similarPickSkus.addAll(skus); + similarPickNames.addAll(names); + similarPickConfs.addAll(confs); + similarPickLabels.addAll(labels); + similarPickSelected = -1; + + if (tvListTitle != null) { + tvListTitle.setText("相近商品(可改选)"); + } + if (tvMatchInfo != null) { + tvMatchInfo.setText("已默认最像,点选其它可改绑"); + tvMatchInfo.setTextColor(0xFF1565C0); + tvMatchInfo.setVisibility(View.VISIBLE); + } + renderSimilarCandidatesList(-1); + applySimilarCandidate(0, false); + } + + private boolean namesEquals(List a, List b) { + if (a.size() != b.size()) return false; + for (int i = 0; i < a.size(); i++) { + String x = a.get(i); + String y = b.get(i); + if (x == null ? y != null : !x.equals(y)) return false; + } + return true; + } + + private String formatSimilarCandidateLabel(String itemName, String sku, double conf) { + String base = itemName != null ? itemName : (sku != null ? sku : "-"); + StringBuilder sb = new StringBuilder(base); + if (conf > 0) { + sb.append(String.format(Locale.US, " (%.0f%%)", conf * 100)); + } + double required = demandQtyForProduct(sku, itemName); + String unitLabel = demandUnitForProduct(sku, itemName); + if (required > 0) { + sb.append(" · 需").append(formatWeight(required)).append(unitLabel); + } + return sb.toString(); + } + + private double demandQtyForProduct(String sku, String itemName) { + double sum = 0; + String skuTrim = sku == null ? "" : sku.trim(); + if (!skuTrim.isEmpty()) { + for (PickingItem it : pendingItems) { + if (skuTrim.equals(String.valueOf(it.skuCode == null ? "" : it.skuCode).trim())) { + sum += it.requiredQty > 0 ? it.requiredQty : 0; + } + } + if (sum > 0) return sum; + } + if (!TextUtils.isEmpty(itemName)) { + String norm = WeighStationMatcher.normalizeName(itemName); + for (PickingItem it : pendingItems) { + if (norm.equals(WeighStationMatcher.normalizeName(it.itemName))) { + sum += it.requiredQty > 0 ? it.requiredQty : 0; + } + } + } + return sum; + } + + private String demandUnitForProduct(String sku, String itemName) { + String skuTrim = sku == null ? "" : sku.trim(); + if (!skuTrim.isEmpty()) { + for (PickingItem it : pendingItems) { + if (skuTrim.equals(String.valueOf(it.skuCode == null ? "" : it.skuCode).trim()) + && !TextUtils.isEmpty(it.unit)) { + return WeighStationMatcher.displayUnit(it.unit); + } + } + } + if (!TextUtils.isEmpty(itemName)) { + String norm = WeighStationMatcher.normalizeName(itemName); + for (PickingItem it : pendingItems) { + if (norm.equals(WeighStationMatcher.normalizeName(it.itemName)) + && !TextUtils.isEmpty(it.unit)) { + return WeighStationMatcher.displayUnit(it.unit); + } + } + } + return "斤"; + } + + private void rebuildSimilarPickLabelsFromDemand() { + similarPickLabels.clear(); + for (int i = 0; i < similarPickNames.size(); i++) { + double conf = i < similarPickConfs.size() ? similarPickConfs.get(i) : 0; + similarPickLabels.add(formatSimilarCandidateLabel( + similarPickNames.get(i), + i < similarPickSkus.size() ? similarPickSkus.get(i) : null, + conf)); + } + } + + private void renderSimilarCandidatesList(int checkedIndex) { + if (similarPickLabels.isEmpty()) return; + ArrayAdapter listAdapter = new ArrayAdapter<>(this, + R.layout.item_recognized_product, new ArrayList<>(similarPickLabels)); + lvPendingProducts.setAdapter(listAdapter); + lvPendingProducts.setVisibility(View.VISIBLE); + if (checkedIndex >= 0 && checkedIndex < similarPickLabels.size()) { + lvPendingProducts.setItemChecked(checkedIndex, true); + try { + lvPendingProducts.smoothScrollToPosition(checkedIndex); + } catch (Exception ignored) { + } + } else { + lvPendingProducts.clearChoices(); + } + } + + private void clearSimilarPickMode() { + similarPickMode = false; + preserveSimilarPickOnRebuild = false; + similarPickSkus.clear(); + similarPickNames.clear(); + similarPickLabels.clear(); + similarPickConfs.clear(); + similarPickSelected = -1; + if (tvListTitle != null) { + tvListTitle.setText("识别商品"); + } + } + + private void onSimilarCandidatePicked(int which) { + applySimilarCandidate(which, true); + } + + /** + * 绑定相近候选;默认最像 fromUser=false;改选 fromUser=true。 + * 绑定后仍保留相近列表,便于改选。 + */ + private void applySimilarCandidate(final int which, final boolean fromUser) { + if (!similarPickMode || which < 0 || which >= similarPickNames.size()) return; + if (which == similarPickSelected && fromUser) return; + final String pickSku = similarPickSkus.get(which); + final String pickName = similarPickNames.get(which); + preserveSimilarPickOnRebuild = true; + loadProductThenApply(pickSku, pickName, fromUser, new Runnable() { + @Override + public void run() { + preserveSimilarPickOnRebuild = false; + similarPickMode = true; + similarPickSelected = which; + recognizeMatched = true; + rebuildSimilarPickLabelsFromDemand(); + String tip = pickName != null ? pickName : pickSku; + if (tvListTitle != null) { + tvListTitle.setText("相近商品(可改选)"); + } + if (tvCameraHint != null) { + tvCameraHint.setText(fromUser + ? ("已改选:" + tip) + : ("已默认最像:" + tip + ",可点选其它")); + } + if (tvMatchInfo != null) { + tvMatchInfo.setText("已选「" + tip + "」,点选列表可改绑"); + tvMatchInfo.setTextColor(0xFF1565C0); + tvMatchInfo.setVisibility(View.VISIBLE); + } + renderSimilarCandidatesList(which); + } + }, new Runnable() { + @Override + public void run() { + preserveSimilarPickOnRebuild = false; + Toast.makeText(PickingWeighActivity.this, + "该商品不在待拣名单", Toast.LENGTH_SHORT).show(); + renderSimilarCandidatesList(similarPickSelected); + } + }); + } + + /** 按识别结果选中商品;成功返回 true */ + private boolean selectProduct(String sku, String name) { + if (productKeys.isEmpty()) return false; + int idx = -1; + if (!TextUtils.isEmpty(sku)) { + String want = "sku:" + sku.trim(); + for (int i = 0; i < productKeys.size(); i++) { + if (productKeys.get(i).contains("|" + want)) { + idx = i; + break; + } + } + } + if (idx < 0 && !TextUtils.isEmpty(name)) { + String norm = WeighStationMatcher.normalizeName(name); + for (int i = 0; i < productKeys.size(); i++) { + String key = productKeys.get(i); + int nameIdx = key.lastIndexOf("name:"); + if (nameIdx >= 0 && key.substring(nameIdx + 5).equals(norm)) { + idx = i; + break; + } + } + if (idx < 0) { + for (int i = 0; i < pendingItems.size(); i++) { + PickingItem item = pendingItems.get(i); + String nm = WeighStationMatcher.normalizeName(item.itemName); + if (nm.equals(norm)) { + String pk = productKey(item); + for (int j = 0; j < productKeys.size(); j++) { + if (pk.equals(productKeys.get(j))) { + idx = j; + break; + } + } + if (idx >= 0) break; + } + } + } + } + if (idx < 0) return false; + applyProductIndex(idx, false); + return true; + } + + private void applyProductIndex(int idx, boolean fromUser) { + if (idx < 0 || idx >= productKeys.size()) return; + suppressProductCb = true; + spProduct.setSelection(idx); + suppressProductCb = false; + showRecognizedProduct(idx); + rematch(); + } + + /** + * 手动刷新待拣:清掉已命中锁,允许重量未变时再识别。 + * 设计 20260910-weigh-no-rerecognize-stable-weight + */ + private void prepareManualPendingRefreshForRerecognize() { + clearSimilarPickMode(); + if (cameraHelper != null) { + cameraHelper.disarmSceneChangeDetection(); + } + recognizeSession++; + isRecognizing = false; + recognizeMatched = false; + if (btnRecognize != null) { + btnRecognize.setEnabled(true); + } + if (cyclePhase == CyclePhase.DONE) { + cyclePhase = CyclePhase.ACTIVE; + if (btnSubmit != null) { + btnSubmit.setEnabled(true); + } + } + if (streamRecognize != null && currentWeightKg > MIN_SCALE_KG && activityResumed) { + streamRecognize.start(); + streamRecognize.requestImmediateTick(); + } + } + + private void loadPending() { + if (btnRefresh != null) { + btnRefresh.setEnabled(false); + } + if (tvCameraHint != null && cyclePhase != CyclePhase.DONE) { + tvCameraHint.setText("加载待拣明细…"); + } + WeighStationApi.getPending(new ApiClient.ApiCallback() { + @Override + public void onSuccess(int code, String body) { + if (btnRefresh != null) { + btnRefresh.setEnabled(true); + } + try { + JSONObject obj = new JSONObject(body); + JSONObject cfg = obj.optJSONObject("config"); + if (cfg != null) { + toleranceMode = cfg.optString("weigh_match_tolerance_mode", "percent"); + toleranceValue = cfg.optDouble("weigh_match_tolerance_value", 10); + applyLabelPrintConfig(cfg); + } + updateToleranceHint(); + + JSONObject meta = obj.optJSONObject("meta"); + if (meta != null) { + pendingRowCount = meta.optInt("pending_count", 0); + pendingProductCount = meta.optInt("product_count", 0); + } + JSONArray data = obj.optJSONArray("data"); + boolean hasRows = data != null && data.length() > 0; + if (!hasRows && meta != null) { + pendingItems.clear(); + rebuildProductSpinner(); + clearRecognizedDisplay(); + bindAllMatchItems(); + rematch(); + syncCameraWithPending(); + if (tvCameraHint != null && cyclePhase != CyclePhase.DONE) { + tvCameraHint.setText(pendingRowCount > 0 + ? ("待拣 " + pendingRowCount + " 行 / " + pendingProductCount + " 品,放货识别") + : "暂无待拣"); + } + if (pendingRowCount == 0) { + Toast.makeText(PickingWeighActivity.this, "暂无待拣明细", Toast.LENGTH_LONG).show(); + } + return; + } + parsePickingRows(data); + rebuildProductSpinner(); + if (meta == null) { + pendingRowCount = pendingItems.size(); + pendingProductCount = productKeys.size(); + } + rematch(); + bindAllMatchItems(); + syncCameraWithPending(); + if (pendingRowCount == 0) { + Toast.makeText(PickingWeighActivity.this, "暂无待拣明细", Toast.LENGTH_LONG).show(); + } + } catch (JSONException e) { + Toast.makeText(PickingWeighActivity.this, "解析待拣数据失败", Toast.LENGTH_SHORT).show(); + } + } + + @Override + public void onError(int code, String message) { + if (btnRefresh != null) { + btnRefresh.setEnabled(true); + } + Toast.makeText(PickingWeighActivity.this, "加载失败:" + message, Toast.LENGTH_LONG).show(); + } + }); + } + + /** 解析待拣明细行写入 pendingItems(清空后填充) */ + private void parsePickingRows(JSONArray data) throws JSONException { + pendingItems.clear(); + if (data == null) return; + for (int i = 0; i < data.length(); i++) { + JSONObject row = data.getJSONObject(i); + PickingItem item = new PickingItem(); + item.id = row.optString("id"); + item.pickCode = row.optString("pick_code"); + item.orderCode = row.optString("order_code"); + item.itemName = row.optString("item_name"); + item.skuCode = row.optString("sku_code"); + item.requiredQty = row.optDouble("required_qty"); + item.pickedQty = row.optDouble("picked_qty"); + item.pickedWeight = row.optDouble("picked_weight"); + item.unit = row.optString("unit"); + item.reviewStatus = row.optInt("review_status"); + item.sortOrder = row.optInt("sort_order"); + item.companyName = row.optString("company_name"); + item.customerCode = row.optString("customer_code"); + item.barcode = row.optString("barcode"); + pendingItems.add(item); + } + } + + /** + * 按 SKU/品名拉取该品全部待拣明细并选中。 + */ + private void loadProductThenApply(final String sku, final String name, final boolean fromUser, + final Runnable onHit, final Runnable onMiss) { + WeighStationApi.getProduct(sku, name, new ApiClient.ApiCallback() { + @Override + public void onSuccess(int code, String body) { + if (isFinishing() || isDestroyed()) return; + try { + JSONObject obj = new JSONObject(body); + JSONArray data = obj.optJSONArray("data"); + if (data == null || data.length() == 0) { + if (onMiss != null) { + onMiss.run(); + } else { + Toast.makeText(PickingWeighActivity.this, + "未找到该商品待拣明细", Toast.LENGTH_SHORT).show(); + } + return; + } + parsePickingRows(data); + rebuildProductSpinner(); + bindAllMatchItems(); + boolean selected = selectProduct(sku, name); + if (!selected && !productKeys.isEmpty()) { + applyProductIndex(0, fromUser); + selected = true; + } + if (!selected) { + if (onMiss != null) { + onMiss.run(); + } else { + Toast.makeText(PickingWeighActivity.this, + "未找到该商品待拣明细", Toast.LENGTH_SHORT).show(); + } + return; + } + if (onHit != null) { + onHit.run(); + } + } catch (JSONException e) { + if (onMiss != null) { + onMiss.run(); + } else { + Toast.makeText(PickingWeighActivity.this, + "解析商品明细失败", Toast.LENGTH_SHORT).show(); + } + } + } + + @Override + public void onError(int code, String message) { + if (isFinishing() || isDestroyed()) return; + if (onMiss != null) { + onMiss.run(); + } else { + Toast.makeText(PickingWeighActivity.this, + "加载商品失败:" + message, Toast.LENGTH_SHORT).show(); + } + } + }); + } + + /** 分拣台展示用客户名(按订单分拣时不展示订单号) */ + private String formatCustomer(PickingItem item) { + if (!TextUtils.isEmpty(item.companyName)) return item.companyName; + if (!TextUtils.isEmpty(item.customerCode)) return item.customerCode; + return "-"; + } + + private void rebuildProductSpinner() { + if (!preserveSimilarPickOnRebuild) { + clearSimilarPickMode(); + } + Map nameMap = new LinkedHashMap<>(); + Map countMap = new LinkedHashMap<>(); + for (PickingItem item : pendingItems) { + String key = productKey(item); + if (!nameMap.containsKey(key)) { + String base = formatCustomer(item) + + " | " + (item.itemName != null ? item.itemName : "-"); + nameMap.put(key, base); + countMap.put(key, 1); + } else { + countMap.put(key, countMap.get(key) + 1); + } + } + productKeys.clear(); + productLabels.clear(); + for (Map.Entry e : nameMap.entrySet()) { + productKeys.add(e.getKey()); + int n = countMap.get(e.getKey()); + productLabels.add(e.getValue() + " | " + n + "单"); + } + suppressProductCb = true; + ArrayAdapter spinnerAdapter = new ArrayAdapter<>(this, + android.R.layout.simple_spinner_item, productLabels); + spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spProduct.setAdapter(spinnerAdapter); + suppressProductCb = false; + if (!preserveSimilarPickOnRebuild) { + clearRecognizedDisplay(); + } + } + + /** 只展示识别商品:清空识别态,列表显示空态提示 */ + private void clearRecognizedDisplay() { + if (similarPickMode && !preserveSimilarPickOnRebuild) { + clearSimilarPickMode(); + } + shownProductIndices.clear(); + weightEditedByUser = false; + recognizeDisplayActive = false; + if (lvPendingProducts != null && !preserveSimilarPickOnRebuild) { + ArrayAdapter listAdapter = new ArrayAdapter<>(this, + R.layout.item_pending_product, + new ArrayList<>(java.util.Collections.singletonList("等待识别… 请将商品放上秤"))); + lvPendingProducts.setAdapter(listAdapter); + lvPendingProducts.clearChoices(); + } + if (llRecognizeEdit != null && !preserveSimilarPickOnRebuild) { + llRecognizeEdit.setVisibility(View.GONE); + } + if (preserveSimilarPickOnRebuild) { + return; + } + if (etRecognizeName != null) { + etRecognizeName.setText(""); + } + if (etRecognizeWeight != null) { + suppressWeightWatcher = true; + etRecognizeWeight.setText(""); + suppressWeightWatcher = false; + } + } + + /** 只展示识别商品:列表只渲染识别到的这一行,并展示可编辑卡片 */ + private void showRecognizedProduct(int idx) { + if (idx < 0 || idx >= productKeys.size()) return; + recognizeDisplayActive = true; + cancelRecognizeLiftOffClear(); + shownProductIndices.clear(); + shownProductIndices.add(idx); + String label = idx < productLabels.size() ? productLabels.get(idx) : ""; + // 与入库验收台一致:识别命中单行用大字号布局突出显示 + ArrayAdapter listAdapter = new ArrayAdapter<>(this, + R.layout.item_recognized_product, + new ArrayList<>(java.util.Collections.singletonList(label))); + lvPendingProducts.setAdapter(listAdapter); + lvPendingProducts.setItemChecked(0, true); + bindRecognizeEditCard(idx); + } + + /** 编辑卡片:品名(可改后重匹配)、数量/重量(可手填覆盖秤值) */ + private void bindRecognizeEditCard(int idx) { + if (llRecognizeEdit == null) return; + String key = productKeys.get(idx); + String baseName = ""; + String unit = null; + double requiredQty = 0; + for (PickingItem item : pendingItems) { + if (productKey(item).equals(key)) { + baseName = item.itemName != null ? item.itemName : ""; + unit = item.unit; + requiredQty = item.requiredQty; + break; + } + } + if (etRecognizeName != null) { + etRecognizeName.setText(baseName); + } + if (tvRecognizeWeightUnit != null) { + tvRecognizeWeightUnit.setText(WeighStationMatcher.displayUnit(unit)); + } + weightEditedByUser = false; + if (etRecognizeWeight != null) { + suppressWeightWatcher = true; + etRecognizeWeight.setText(""); + suppressWeightWatcher = false; + double scaleBiz = WeighStationMatcher.scaleKgToBusiness(currentWeightKg, unit, CanteenApp.get().getScaleUnit()); + if (scaleBiz > 0) { + etRecognizeWeight.setHint("秤值 " + formatWeight(scaleBiz) + ",可手填覆盖"); + } else if (!WeighStationMatcher.isWeightUnit(unit) && requiredQty > 0) { + // 计数单位(瓶/个/份等):秤值无法换算,默认按应拣数量 + etRecognizeWeight.setHint("应拣 " + formatWeight(requiredQty) + ",可手填覆盖"); + } else { + etRecognizeWeight.setHint("默认取秤值,可手填覆盖"); + } + } + llRecognizeEdit.setVisibility(View.VISIBLE); + } + + /** 结算量:手填优先(编辑后不随秤值变),否则取秤值换算;计数单位无秤值时按应拣数量兜底 */ + private double currentSettlementBusiness(String unit) { + return currentSettlementBusiness(unit, 0); + } + + private double currentSettlementBusiness(String unit, double fallbackQty) { + if (weightEditedByUser && etRecognizeWeight != null) { + String text = etRecognizeWeight.getText() == null + ? "" : etRecognizeWeight.getText().toString().trim(); + if (!TextUtils.isEmpty(text)) { + try { + double manual = Double.parseDouble(text); + if (manual > 0) return manual; + } catch (NumberFormatException ignored) { + } + } + } + double scaleBiz = WeighStationMatcher.scaleKgToBusiness(currentWeightKg, unit, CanteenApp.get().getScaleUnit()); + if (scaleBiz > 0) return scaleBiz; + // 计数单位秤值无法换算 → 用应拣数量兜底 + return fallbackQty > 0 ? fallbackQty : 0; + } + + /** 按手填品名在待拣名单内重新匹配(纠正图像识别错误) */ + private void rematchByName() { + SoftInputHelper.hide(this); + if (etRecognizeName == null) return; + String name = etRecognizeName.getText() == null + ? "" : etRecognizeName.getText().toString().trim(); + if (TextUtils.isEmpty(name)) { + Toast.makeText(this, "请先输入品名", Toast.LENGTH_SHORT).show(); + return; + } + boolean selected = selectProduct(null, name); + if (selected) { + recognizeMatched = true; + Toast.makeText(this, "已匹配:" + name, Toast.LENGTH_SHORT).show(); + return; + } + final String wantName = name; + loadProductThenApply(null, name, true, new Runnable() { + @Override + public void run() { + recognizeMatched = true; + Toast.makeText(PickingWeighActivity.this, "已匹配:" + wantName, Toast.LENGTH_SHORT).show(); + } + }, new Runnable() { + @Override + public void run() { + Toast.makeText(PickingWeighActivity.this, + "「" + wantName + "」不在待拣名单,请核对后重试", + Toast.LENGTH_LONG).show(); + } + }); + } + + /** 无待拣仍可预览;有待拣且秤有重则允许本轮识别 */ + private void syncCameraWithPending() { + if (cyclePhase == CyclePhase.DONE) { + refreshPreviewHint(); + return; + } + if (pendingRowCount <= 0 && pendingItems.isEmpty()) { + ensurePreviewWhileOnStation("预览中;暂无待拣"); + return; + } + boolean needOpen = cameraHelper == null + || !cameraHelper.isPreviewing(); + if (needOpen && activityResumed) { + if (usbHotplugGuard != null && !usbHotplugGuard.canOpenNow()) { + schedulePreviewAfterUsbCooldown(); + return; + } + ensureCameraPermissionThenOpen(); + } + } + + /** 停留本台时尽量保持预览画面(空名单也开;秤空则不开;仅真预览才写「预览中」) */ + private void ensurePreviewWhileOnStation(String emptyHint) { + if (!activityResumed) return; + if (cyclePhase == CyclePhase.DONE) { + refreshPreviewHint(); + return; + } + if (currentWeightKg <= MIN_SCALE_KG) { + refreshPreviewHint(); + return; + } + if (usbHotplugGuard != null && !usbHotplugGuard.canOpenNow()) { + schedulePreviewAfterUsbCooldown(); + return; + } + boolean needOpen = cameraHelper == null || !cameraHelper.isPreviewing(); + if (needOpen) { + ensureCameraPermissionThenOpen(); + } else if (tvCameraHint != null && emptyHint != null) { + tvCameraHint.setText(emptyHint); + } + } + + private String productKey(PickingItem item) { + String order = item.orderCode == null ? "" : item.orderCode.trim(); + String sku = item.skuCode == null ? "" : item.skuCode.trim(); + if (!sku.isEmpty()) return "order:" + order + "|sku:" + sku; + return "order:" + order + "|name:" + WeighStationMatcher.normalizeName(item.itemName); + } + + private void rematch() { + matchCandidates.clear(); + matchLabels.clear(); + int pPos = spProduct.getSelectedItemPosition(); + if (pPos < 0 || pPos >= productKeys.size()) { + bindMatchSpinner(null); + updateMatchInfo(); + return; + } + String key = productKeys.get(pPos); + String sku = ""; + int skuIdx = key.indexOf("|sku:"); + if (skuIdx >= 0) { + sku = key.substring(skuIdx + 5); + } + String name = ""; + for (PickingItem item : pendingItems) { + if (productKey(item).equals(key)) { + name = item.itemName; + if (sku.isEmpty()) sku = item.skuCode; + break; + } + } + List same = WeighStationMatcher.filterSameProduct(pendingItems, sku, name); + double business = currentSettlementBusiness(activeUnit()); + PickingItem best = WeighStationMatcher.pickBest(same, business); + matchCandidates.addAll(same); + for (PickingItem item : same) { + matchLabels.add(formatMatchLabel(item)); + } + bindMatchSpinner(best); + highlightMatchItems(same, best); + updateMatchInfo(); + } + + private String formatMatchLabel(PickingItem item) { + return formatAllMatchLabel(item); + } + + private void bindMatchSpinner(PickingItem preferred) { + suppressMatchCb = true; + ArrayAdapter adapter = new ArrayAdapter<>(this, + android.R.layout.simple_spinner_item, matchLabels); + adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spMatch.setAdapter(adapter); + suppressMatchCb = false; + } + + /** 待分拣商品列表:只显示品名、客户、应拣重量 */ + private void bindAllMatchItems() { + if (lvMatchItems == null) return; + List labels = new ArrayList<>(); + for (PickingItem item : pendingItems) { + labels.add(formatAllMatchLabel(item)); + } + ArrayAdapter listAdapter = new ArrayAdapter<>(this, + android.R.layout.simple_list_item_activated_1, + labels); + lvMatchItems.setAdapter(listAdapter); + lvMatchItems.clearChoices(); + } + + /** 识别命中后,把同品订单行高亮并滚动到第一条 */ + private void highlightMatchItems(List candidates, PickingItem preferred) { + if (lvMatchItems == null || candidates == null || candidates.isEmpty()) return; + int target = -1; + for (int i = 0; i < pendingItems.size(); i++) { + if (preferred != null && preferred.id != null && preferred.id.equals(pendingItems.get(i).id)) { + target = i; + break; + } + } + if (target >= 0) { + lvMatchItems.setItemChecked(target, true); + lvMatchItems.setSelection(target); + } + } + + private String formatAllMatchLabel(PickingItem item) { + String name = item.itemName != null ? item.itemName : "-"; + String qty = formatWeight(item.requiredQty) + " " + WeighStationMatcher.displayUnit(item.unit); + return name + " | " + formatCustomer(item) + " | " + qty; + } + + private PickingItem selectedMatch() { + int pos = spMatch.getSelectedItemPosition(); + if (pos < 0 || pos >= matchCandidates.size()) return null; + return matchCandidates.get(pos); + } + + private String activeUnit() { + PickingItem match = selectedMatch(); + if (match != null && !TextUtils.isEmpty(match.unit)) { + return match.unit; + } + int pPos = spProduct.getSelectedItemPosition(); + if (pPos >= 0 && pPos < productKeys.size()) { + String key = productKeys.get(pPos); + for (PickingItem item : pendingItems) { + if (productKey(item).equals(key) && !TextUtils.isEmpty(item.unit)) { + return item.unit; + } + } + } + return "斤"; + } + + private double businessWeightFor(String unit) { + return WeighStationMatcher.scaleKgToBusiness(currentWeightKg, unit, CanteenApp.get().getScaleUnit()); + } + + private void refreshWeightDisplay() { + String unit = activeUnit(); + double business = businessWeightFor(unit); + tvWeight.setText(formatWeight(business) + " " + WeighStationMatcher.displayUnit(unit)); + if (!weightEditedByUser && etRecognizeWeight != null + && llRecognizeEdit != null && llRecognizeEdit.getVisibility() == View.VISIBLE) { + if (business > 0) { + etRecognizeWeight.setHint("秤值 " + formatWeight(business) + ",可手填覆盖"); + } else if (!WeighStationMatcher.isWeightUnit(unit)) { + // 计数单位:取应拣数量做 hint + double req = requiredQtyOfActive(); + etRecognizeWeight.setHint(req > 0 + ? "应拣 " + formatWeight(req) + ",可手填覆盖" + : "可手填数量"); + } else { + etRecognizeWeight.setHint("默认取秤值,可手填覆盖"); + } + } + } + + /** 当前选中匹配行的应拣数量(计数单位兜底用) */ + private double requiredQtyOfActive() { + PickingItem item = selectedMatch(); + if (item != null && item.requiredQty > 0) return item.requiredQty; + int pPos = spProduct.getSelectedItemPosition(); + if (pPos >= 0 && pPos < productKeys.size()) { + String key = productKeys.get(pPos); + for (PickingItem it : pendingItems) { + if (productKey(it).equals(key) && it.requiredQty > 0) return it.requiredQty; + } + } + return 0; + } + + private void updateToleranceHint() { + if (tvToleranceHint == null) return; + tvToleranceHint.setText("阈值校验已关闭,称重即可分拣"); + } + + private void updateMatchInfo() { + PickingItem item = selectedMatch(); + if (item == null) { + tvMatchInfo.setText("点选商品或拍照识别"); + tvMatchInfo.setTextColor(0xFF333333); + tvMatchInfo.setVisibility(View.VISIBLE); + btnSubmit.setEnabled(false); + refreshWeightDisplay(); + return; + } + // 客户/拣货单/品名/应拣/实重/误差等明细不再展示 + boolean countUnit = !WeighStationMatcher.isWeightUnit(item.unit); + double settlement = currentSettlementBusiness(item.unit, item.requiredQty); + if ((!countUnit && !hasScaleWeight()) || settlement <= 0) { + tvMatchInfo.setText(!hasScaleWeight() ? "请先将商品放上秤" : "请先称重"); + tvMatchInfo.setTextColor(0xFFEF6C00); + tvMatchInfo.setVisibility(View.VISIBLE); + } else { + tvMatchInfo.setText(""); + tvMatchInfo.setVisibility(View.GONE); + } + btnSubmit.setEnabled(settlement > 0 && (countUnit || hasScaleWeight()) && !isSubmitting); + refreshWeightDisplay(); + } + + private void confirmSubmit() { + final PickingItem item = selectedMatch(); + if (item == null) return; + boolean countUnit = !WeighStationMatcher.isWeightUnit(item.unit); + if (!countUnit && !hasScaleWeight()) { + Toast.makeText(this, "请先将商品放上秤", Toast.LENGTH_SHORT).show(); + return; + } + final double settlement = currentSettlementBusiness(item.unit, item.requiredQty); + if (settlement <= 0) { + Toast.makeText(this, "请先称重", Toast.LENGTH_SHORT).show(); + return; + } + + doCommit(item, settlement); + } + + private void doCommit(final PickingItem item, double settlement) { + if (cyclePhase == CyclePhase.DONE) { + Toast.makeText(this, "本单已完成,请先取下商品", Toast.LENGTH_SHORT).show(); + return; + } + isSubmitting = true; + btnSubmit.setEnabled(false); + if (tvCameraHint != null) { + tvCameraHint.setText("提交中…"); + } + + double pickedQty; + double pickedWeight; + if (WeighStationMatcher.isWeightUnit(item.unit)) { + // 秤值只进实拣重量;数量保留应拣(避免 Web 把秤值显示在「实拣数量」) + pickedWeight = settlement; + double required = item.requiredQty > 0 ? item.requiredQty : 0; + double prevQty = item.pickedQty > 0 ? item.pickedQty : 0; + pickedQty = prevQty > 0 ? prevQty : (required > 0 ? required : settlement); + } else { + pickedQty = settlement; + pickedWeight = 0; + } + + WeighStationApi.commit(item.id, item.pickCode, pickedQty, pickedWeight, item.unit, null, + new ApiClient.ApiCallback() { + @Override + public void onSuccess(int code, String body) { + isSubmitting = false; + recognizeMatched = false; + try { + JSONObject root = new JSONObject(body); + JSONObject data = root.optJSONObject("data"); + if (data == null) data = root; + lastLabelPayload = data.optJSONObject("label_payload"); + refreshReprintEnabled(); + final boolean pickCompleted = data.optBoolean("pick_completed"); + if (pickingLabelPrintEnabled && lastLabelPayload != null) { + if (tvCameraHint != null) { + tvCameraHint.setText("装框成功,正在打印标签…"); + } + tryPrint(lastLabelPayload, new Runnable() { + @Override + public void run() { + enterPickingDone(pickCompleted); + } + }, new Runnable() { + @Override + public void run() { + if (tvCameraHint != null) { + tvCameraHint.setText("装框成功但打印失败,可点重打;取下商品后重来"); + } + Toast.makeText(PickingWeighActivity.this, + "标签打印失败,可点重打", Toast.LENGTH_LONG).show(); + loadPending(); + } + }); + } else { + enterPickingDone(pickCompleted); + } + } catch (JSONException e) { + if (tvCameraHint != null) { + tvCameraHint.setText("提交成功但解析返回失败(预览保持)"); + } + Toast.makeText(PickingWeighActivity.this, "提交成功但解析返回失败", Toast.LENGTH_SHORT).show(); + loadPending(); + } + } + + @Override + public void onError(int code, String message) { + // 服务端已提交、称端超时后重试:软成功(与验收台对齐) + if (message != null && (message.contains("已提交") || message.contains("已装框") + || message.toLowerCase().contains("already_submitted"))) { + Toast.makeText(PickingWeighActivity.this, + "该行已提交,请勿重复提交", Toast.LENGTH_LONG).show(); + isSubmitting = false; + recognizeMatched = false; + enterPickingDone(false); + loadPending(); + return; + } + isSubmitting = false; + updateMatchInfo(); + if (tvCameraHint != null) { + tvCameraHint.setText("提交失败:" + message + "(预览保持)"); + } + Toast.makeText(PickingWeighActivity.this, "提交失败:" + message, Toast.LENGTH_LONG).show(); + } + }); + } + + private void enterPickingDone(boolean pickCompleted) { + cyclePhase = CyclePhase.DONE; + recognizeMatched = false; + cancelInFlightRecognize(); + resetStreamForNewCycle(); + if (tvCameraHint != null) { + tvCameraHint.setText("装框完成,请取下商品后再放下一件"); + } + if (tvMatchInfo != null) { + StringBuilder sb = new StringBuilder("装框完成,请取下商品"); + if (pickCompleted) { + sb.append(";整单已待出库"); + } + if (lastLabelPayload != null) { + sb.append(pickingLabelPrintEnabled ? ",标签已打印" : "(标签打印已关闭)"); + } + tvMatchInfo.setText(sb.toString()); + tvMatchInfo.setTextColor(0xFF2E7D32); + tvMatchInfo.setVisibility(View.VISIBLE); + } + Toast.makeText(this, pickCompleted ? "装框完成,整单已待出库" : "装框完成", + Toast.LENGTH_SHORT).show(); + loadPending(); + } + + private void tryPrint(final JSONObject label, final Runnable onOk, final Runnable onFail) { + if (label == null) { + if (onFail != null) { + onFail.run(); + } + return; + } + + // 打印前释放 USB 资源:关闭摄像头和暂停秤的串口,避免打印时 USB 总线供电不足导致重启 + if (cameraHelper != null && cameraHelper.isPreviewing()) { + cameraHelper.closeCameraKeepWant(); + } + if (weighManager != null && weighManager.isConnected()) { + weighManager.pauseSerial(); + } + // 等待 USB 总线稳定 + try { + Thread.sleep(200); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + + new Thread(new Runnable() { + @Override + public void run() { + final boolean ok; + try { + ok = PrintManager.printPickingLabel( + PickingWeighActivity.this, + label.optString("company_name"), + label.optString("order_code"), + label.optString("item_name"), + label.optDouble("weight"), + label.optString("unit"), + label.optString("date"), + label.optString("barcode") + ); + } catch (Throwable t) { + android.util.Log.e("PickingWeighActivity", "printPickingLabel crashed", t); + runOnUiThread(new Runnable() { + @Override + public void run() { + restoreUsbDevices(); + if (onFail != null) { + onFail.run(); + } + } + }); + return; + } + runOnUiThread(new Runnable() { + @Override + public void run() { + restoreUsbDevices(); + if (ok) { + if (onOk != null) { + onOk.run(); + } + } else if (onFail != null) { + onFail.run(); + } + } + }); + } + }).start(); + } + + /** 打印完成后恢复 USB 设备:重新打开摄像头和秤的串口 */ + private void restoreUsbDevices() { + // 重新打开摄像头 + if (cameraHelper != null) { + cameraHelper.setAllowPreview(true); + cameraHelper.requestOpen(); + } + // 恢复秤的串口 + if (weighManager != null) { + weighManager.resumeSerial(); + } + } + + private void reprintLast() { + if (!pickingLabelPrintEnabled) { + Toast.makeText(this, "分拣标签打印已关闭(可在 Web 分拣出库开启)", Toast.LENGTH_SHORT).show(); + return; + } + if (lastLabelPayload == null) { + Toast.makeText(this, "没有可重打的标签", Toast.LENGTH_SHORT).show(); + return; + } + Toast.makeText(this, "正在重打标签…", Toast.LENGTH_SHORT).show(); + tryPrint(lastLabelPayload, new Runnable() { + @Override + public void run() { + Toast.makeText(PickingWeighActivity.this, "重打已发送", Toast.LENGTH_SHORT).show(); + } + }, new Runnable() { + @Override + public void run() { + Toast.makeText(PickingWeighActivity.this, "标签打印失败,可点重打", Toast.LENGTH_SHORT).show(); + } + }); + } + + @Override + public void onWeightChanged(String weight, double weightKg) { + boolean hadWeightBefore = currentWeightKg > MIN_SCALE_KG; + currentWeightKg = weightKg; + lastWeightChangeAt = System.currentTimeMillis(); + // 空→有货(放回新货)即开新周期,立即进入 1 秒自动识别节拍 + boolean nowHasWeight = weightKg > MIN_SCALE_KG; + if (nowHasWeight && !hadWeightBefore + && cyclePhase != CyclePhase.ACTIVE && activityResumed) { + cyclePhase = CyclePhase.ACTIVE; + recognizeMatched = false; + if (streamRecognize != null) { + streamRecognize.requestImmediateTick(); + } + } + // 有货→空(拿下商品)转换:2 秒后自动刷新待拣(仅一次,避免空闲循环刷新) + if (!nowHasWeight && hadWeightBefore + && cyclePhase != CyclePhase.DONE && recognizeDisplayActive) { + cancelRecognizeLiftOffClear(); + recognizeLiftOffClearScheduled = true; + uiHandler.postDelayed(recognizeLiftOffClearRunnable, RECOGNIZE_LIFT_OFF_CLEAR_MS); + } + if (weightKg <= MIN_SCALE_KG) { + recognizeMatched = false; + } + if (streamRecognize != null && cyclePhase != CyclePhase.IDLE) { + // DONE 态也喂秤重:换货跳变(不拿空)才能被检测到并退出 DONE 重新识别 + streamRecognize.onWeightSample(weightKg, weightKg > MIN_SCALE_KG); + } else if (streamRecognize != null && weightKg <= MIN_SCALE_KG) { + streamRecognize.onWeightSample(weightKg, false); + } + syncPreviewWithScaleWeight(weightKg); + refreshWeightDisplay(); + if (!hasScaleWeight()) { + updateMatchInfo(); + } + if (pendingItems.isEmpty()) { + return; + } + if (!Double.isNaN(lastRematchKg) + && Math.abs(weightKg - lastRematchKg) < REMATCH_MIN_DELTA_KG) { + return; + } + long now = System.currentTimeMillis(); + if ((now - lastRematchAt) < REMATCH_MIN_INTERVAL_MS) { + return; + } + lastRematchAt = now; + lastRematchKg = weightKg; + rematch(); + } + + @Override + public void onError(String msg) { + Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); + } + + @Override + public void onConnected(boolean connected) { + if (connected && activityResumed) { + syncPreviewWithScaleWeight(currentWeightKg); + } + } + + private String formatWeight(double w) { + if (w <= 0) return "0.00"; + return String.format(Locale.US, "%.2f", w); + } + + @Override + protected void onDestroy() { + activityResumed = false; + cancelResumePreviewWhenLoaded(); + cancelRecognizeLiftOffClear(); + cancelRetryPreviewAfterUsbCooldown(); + cancelInFlightRecognize(); + if (usbHotplugGuard != null) { + usbHotplugGuard.unregister(); + usbHotplugGuard = null; + } + if (cameraHelper != null) { + cameraHelper.release(); + cameraHelper = null; + } + if (weighManager != null) { + weighManager.release(); + } + super.onDestroy(); + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/SoftInputHelper.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/SoftInputHelper.java new file mode 100644 index 0000000..0753e14 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/SoftInputHelper.java @@ -0,0 +1,250 @@ +package com.canteen.weigh.ui; + +import android.app.Activity; +import android.content.Context; +import android.graphics.Rect; +import android.os.Handler; +import android.os.Looper; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewParent; +import android.view.ViewTreeObserver; +import android.view.inputmethod.InputMethodManager; +import android.widget.EditText; +import android.widget.ScrollView; + +import java.lang.reflect.Method; +import java.util.WeakHashMap; + +/** + * 软键盘:收起、点空白处关闭;当前输入框滚到键盘上方,不顶整窗/左栏。 + */ +public final class SoftInputHelper { + + /** 低于此高度视为键盘已收起或缩小,不是全高输入面板 */ + public static final int IME_FULL_MIN_PX = 160; + + private static final WeakHashMap LAST_PADDED = new WeakHashMap(); + private static final WeakHashMap ORIG_BOTTOM_PAD = new WeakHashMap(); + + private SoftInputHelper() { + } + + /** 当前输入法窗口高度;缩小/收起时接近 0。 */ + public static int imeVisibleHeight(Activity activity) { + if (activity == null) { + return 0; + } + InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); + if (imm != null) { + try { + Method m = InputMethodManager.class.getMethod("getInputMethodWindowVisibleHeight"); + Object v = m.invoke(imm); + if (v instanceof Integer) { + int h = (Integer) v; + if (h > 0) { + return h; + } + } + } catch (Exception ignored) { + } + } + if (activity.getWindow() == null) { + return 0; + } + View decor = activity.getWindow().getDecorView(); + Rect visible = new Rect(); + decor.getWindowVisibleDisplayFrame(visible); + return Math.max(0, decor.getHeight() - visible.bottom); + } + + public static boolean isFullImeVisible(Activity activity) { + return imeVisibleHeight(activity) >= IME_FULL_MIN_PX; + } + + public static void hide(Activity activity) { + if (activity == null) { + return; + } + View focus = activity.getCurrentFocus(); + if (focus == null) { + focus = activity.getWindow() != null ? activity.getWindow().getDecorView() : null; + } + if (focus == null) { + return; + } + InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); + if (imm != null) { + imm.hideSoftInputFromWindow(focus.getWindowToken(), 0); + } + focus.clearFocus(); + } + + /** + * 点在 EditText 外时收起键盘并清焦点。 + * 在 Activity#dispatchTouchEvent 开头调用;返回 true 表示已处理抬起。 + */ + public static boolean hideOnTouchOutside(Activity activity, MotionEvent ev) { + if (activity == null || ev == null || ev.getAction() != MotionEvent.ACTION_DOWN) { + return false; + } + View focus = activity.getCurrentFocus(); + if (!(focus instanceof EditText)) { + return false; + } + Rect r = new Rect(); + focus.getGlobalVisibleRect(r); + int x = (int) ev.getRawX(); + int y = (int) ev.getRawY(); + if (r.contains(x, y)) { + return false; + } + hide(activity); + return false; + } + + /** 根布局可点空白处拿焦点,便于收起键盘 */ + public static void enableBlankFocus(View root) { + if (root == null) { + return; + } + root.setFocusable(true); + root.setFocusableInTouchMode(true); + root.setClickable(true); + if (root instanceof ViewGroup) { + ((ViewGroup) root).setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); + } + root.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Context ctx = v.getContext(); + if (ctx instanceof Activity) { + hide((Activity) ctx); + } + } + }); + } + + /** + * 任意输入框获焦:把该框滚到系统键盘上方。只滚所在 ScrollView,不顶整窗。 + */ + public static void keepFocusedAboveIme(final Activity activity) { + if (activity == null || activity.getWindow() == null) { + return; + } + final Handler handler = new Handler(Looper.getMainLooper()); + final Runnable[] tick = new Runnable[1]; + tick[0] = new Runnable() { + @Override + public void run() { + if (activity.isFinishing()) { + return; + } + liftFocusedAboveIme(activity); + View focus = activity.getCurrentFocus(); + if (focus instanceof EditText || isFullImeVisible(activity)) { + handler.postDelayed(tick[0], 160); + } + } + }; + View decor = activity.getWindow().getDecorView(); + decor.getViewTreeObserver().addOnGlobalFocusChangeListener( + new ViewTreeObserver.OnGlobalFocusChangeListener() { + @Override + public void onGlobalFocusChanged(View oldFocus, View newFocus) { + handler.removeCallbacks(tick[0]); + handler.post(tick[0]); + } + }); + decor.getViewTreeObserver().addOnGlobalLayoutListener( + new ViewTreeObserver.OnGlobalLayoutListener() { + @Override + public void onGlobalLayout() { + handler.removeCallbacks(tick[0]); + handler.post(tick[0]); + } + }); + } + + /** + * @deprecated 改用 {@link #keepFocusedAboveIme(Activity)} + */ + public static void keepEditTextAboveKeyboard(final Activity activity, final View scrollView) { + keepFocusedAboveIme(activity); + } + + public static void applyBottomPadding(View scrollView, int bottom) { + if (scrollView == null) { + return; + } + if (!ORIG_BOTTOM_PAD.containsKey(scrollView)) { + ORIG_BOTTOM_PAD.put(scrollView, scrollView.getPaddingBottom()); + } + if (scrollView.getPaddingBottom() == bottom) { + return; + } + scrollView.setPadding( + scrollView.getPaddingLeft(), + scrollView.getPaddingTop(), + scrollView.getPaddingRight(), + bottom); + } + + public static void scrollFocusedIntoView(Activity activity) { + liftFocusedAboveIme(activity); + } + + private static void liftFocusedAboveIme(Activity activity) { + if (activity == null || activity.getWindow() == null) { + return; + } + View focus = activity.getCurrentFocus(); + int imeH = imeVisibleHeight(activity); + if (!(focus instanceof EditText) || imeH < IME_FULL_MIN_PX) { + restoreImePadding(activity); + return; + } + ScrollView sv = findAncestorScrollView(focus); + if (sv == null) { + return; + } + LAST_PADDED.put(activity, sv); + applyBottomPadding(sv, imeH); + final int extra = (int) (12 * focus.getResources().getDisplayMetrics().density); + final View field = focus; + final int imeTop = activity.getWindow().getDecorView().getHeight() - imeH; + sv.post(new Runnable() { + @Override + public void run() { + int[] loc = new int[2]; + field.getLocationOnScreen(loc); + int fieldBottom = loc[1] + field.getHeight(); + int need = fieldBottom + extra - imeTop; + if (need > 0) { + sv.smoothScrollBy(0, need); + } + } + }); + } + + private static void restoreImePadding(Activity activity) { + View padded = LAST_PADDED.remove(activity); + if (padded == null) { + return; + } + Integer orig = ORIG_BOTTOM_PAD.get(padded); + applyBottomPadding(padded, orig != null ? orig : 0); + } + + private static ScrollView findAncestorScrollView(View start) { + ViewParent p = start.getParent(); + while (p instanceof View) { + if (p instanceof ScrollView) { + return (ScrollView) p; + } + p = p.getParent(); + } + return null; + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/WeighUiFontHelper.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/WeighUiFontHelper.java new file mode 100644 index 0000000..60466a4 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/ui/WeighUiFontHelper.java @@ -0,0 +1,39 @@ +package com.canteen.weigh.ui; + +import android.content.Context; +import android.content.SharedPreferences; +import android.content.res.Configuration; + +import com.canteen.weigh.CanteenApp; + +/** + * 验收台/分拣台/主界面:按本地「显示字体」档位注入 Configuration.fontScale。 + * 见 docs/design/20260828-weigh-ui-font-size-levels.md + */ +public final class WeighUiFontHelper { + + private WeighUiFontHelper() {} + + public static Context wrap(Context base) { + if (base == null) return null; + float scale = CanteenApp.UI_FONT_SCALE_LARGE; + try { + if (CanteenApp.get() != null) { + scale = CanteenApp.get().getUiFontScale(); + } else { + SharedPreferences sp = base.getSharedPreferences( + CanteenApp.PREFS_NAME_PUBLIC, Context.MODE_PRIVATE); + scale = CanteenApp.scaleForUiFontSize( + sp.getString(CanteenApp.KEY_UI_FONT_SIZE_PUBLIC, CanteenApp.UI_FONT_LARGE)); + } + } catch (Throwable ignored) { + scale = CanteenApp.UI_FONT_SCALE_LARGE; + } + Configuration conf = new Configuration(base.getResources().getConfiguration()); + if (Math.abs(conf.fontScale - scale) < 0.001f) { + return base; + } + conf.fontScale = scale; + return base.createConfigurationContext(conf); + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/update/SilentApkInstaller.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/update/SilentApkInstaller.java new file mode 100644 index 0000000..ed44f34 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/update/SilentApkInstaller.java @@ -0,0 +1,112 @@ +package com.canteen.weigh.update; + +import android.util.Log; + +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStreamReader; + +/** + * 工控 eng 机(A64 已验证):App 内 su 0 → pm install -r 真静默。 + * 见 docs/design/20260830-weigh-ota-scheduled-silent.md + */ +public final class SilentApkInstaller { + + private static final String TAG = "SilentApkInstaller"; + + public static final class Result { + public final boolean ok; + public final String message; + + public Result(boolean ok, String message) { + this.ok = ok; + this.message = message != null ? message : ""; + } + } + + private SilentApkInstaller() {} + + /** 探测 App 能否 su 提权(不装包) */ + public static boolean canElevate() { + Result r = runSu(new String[]{"id"}); + return r.ok && r.message.contains("uid=0"); + } + + public static Result install(File apkFile) { + if (apkFile == null || !apkFile.isFile()) { + return new Result(false, "APK 不存在"); + } + String path = apkFile.getAbsolutePath(); + // 先 chmod,避免 pm 读不到应用私有目录 + runSu(new String[]{"chmod", "644", path}); + Result r = runSu(new String[]{"pm", "install", "-r", path}); + if (r.ok && (r.message.contains("Success") || r.message.trim().isEmpty())) { + return new Result(true, "Success"); + } + if (!r.ok && r.message.contains("su")) { + return new Result(false, "NEED_PRIVILEGE: " + r.message); + } + return new Result(false, r.message.isEmpty() ? "pm install 失败" : r.message); + } + + private static Result runSu(String[] cmdAfterSu0) { + Process process = null; + try { + String[] full = new String[cmdAfterSu0.length + 2]; + full[0] = "/system/bin/su"; + full[1] = "0"; + System.arraycopy(cmdAfterSu0, 0, full, 2, cmdAfterSu0.length); + process = Runtime.getRuntime().exec(full); + boolean finished = waitFor(process, 120); + String out = readFully(process.getInputStream()); + String err = readFully(process.getErrorStream()); + String combined = (out + "\n" + err).trim(); + if (!finished) { + process.destroy(); + return new Result(false, "命令超时: " + combined); + } + int code = process.exitValue(); + Log.i(TAG, "su0 exit=" + code + " out=" + combined); + return new Result(code == 0, combined); + } catch (Exception e) { + Log.w(TAG, "su failed", e); + return new Result(false, "su 不可用: " + e.getMessage()); + } finally { + if (process != null) { + try { + process.destroy(); + } catch (Exception ignored) { + } + } + } + } + + private static boolean waitFor(Process process, int seconds) throws InterruptedException { + // API 23 无 waitFor(timeout);轮询 + long deadline = System.currentTimeMillis() + seconds * 1000L; + while (System.currentTimeMillis() < deadline) { + try { + process.exitValue(); + return true; + } catch (IllegalThreadStateException e) { + Thread.sleep(200); + } + } + return false; + } + + private static String readFully(java.io.InputStream in) { + StringBuilder sb = new StringBuilder(); + try { + BufferedReader br = new BufferedReader(new InputStreamReader(in)); + String line; + while ((line = br.readLine()) != null) { + if (sb.length() > 0) sb.append('\n'); + sb.append(line); + } + br.close(); + } catch (Exception ignored) { + } + return sb.toString(); + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/update/WeighAppUpdateHelper.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/update/WeighAppUpdateHelper.java new file mode 100644 index 0000000..effd345 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/update/WeighAppUpdateHelper.java @@ -0,0 +1,432 @@ +package com.canteen.weigh.update; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.pm.PackageInfo; +import android.os.Handler; +import android.os.Looper; +import android.text.TextUtils; +import android.util.Log; +import android.widget.Toast; + +import com.canteen.weigh.CanteenApp; +import com.canteen.weigh.api.ApiClient; + +import org.json.JSONObject; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.MessageDigest; +import java.util.concurrent.atomic.AtomicBoolean; + +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; + +/** + * 称端 OTA:拉平台策略 → COS manifest → 下载校验 → 自动窗内真静默 / 否则弹窗安装。 + * 见 docs/design/20260830-weigh-ota-scheduled-silent.md + */ +public final class WeighAppUpdateHelper { + + private static final String TAG = "WeighAppUpdate"; + private static final AtomicBoolean checking = new AtomicBoolean(false); + private static final AtomicBoolean downloading = new AtomicBoolean(false); + private static final Handler MAIN = new Handler(Looper.getMainLooper()); + + private WeighAppUpdateHelper() {} + + /** 主界面静默检查;设置页传 force=true */ + public static void checkAfterLogin(final Activity activity, final boolean force) { + if (activity == null || activity.isFinishing()) return; + if (!CanteenApp.get().isLoggedIn()) return; + if (!force && !CanteenApp.get().shouldCheckOtaNow()) { + return; + } + if (!checking.compareAndSet(false, true)) { + if (force) toast(activity, "正在检查更新…"); + return; + } + if (force) toast(activity, "正在检查更新…"); + + // 先拉平台策略(失败则回退本地 URL + 旧弹窗逻辑) + ApiClient.get().get("/mobile/weigh/ota-policy", new ApiClient.ApiCallback() { + @Override + public void onSuccess(int code, String body) { + JSONObject data = null; + try { + JSONObject root = new JSONObject(body); + data = root.optJSONObject("data"); + } catch (Exception ignored) { + } + String policyManifest = data != null ? data.optString("manifest_url", "").trim() : ""; + boolean autoEnabled = data != null && data.optBoolean("auto_update_enabled", false); + boolean autoAllowedNow = data != null && data.optBoolean("auto_allowed_now", false); + int minIdle = data != null ? data.optInt("min_idle_seconds", 30) : 30; + if (minIdle < 0) minIdle = 0; + if (minIdle > 3600) minIdle = 3600; + + String manifestUrl = !TextUtils.isEmpty(policyManifest) + ? policyManifest + : CanteenApp.get().getOtaManifestUrl(); + if (TextUtils.isEmpty(manifestUrl)) { + checking.set(false); + if (force) toast(activity, "请先配置 OTA 清单 URL(Web 策略或设备设置)"); + return; + } + boolean silentAuto = autoEnabled && autoAllowedNow; + fetchManifestAndMaybeUpdate(activity, manifestUrl, force, silentAuto, minIdle); + } + + @Override + public void onError(int code, String message) { + Log.w(TAG, "ota-policy failed: " + message); + String manifestUrl = CanteenApp.get().getOtaManifestUrl(); + if (TextUtils.isEmpty(manifestUrl)) { + checking.set(false); + if (force) toast(activity, "策略拉取失败且未配置本地清单 URL"); + return; + } + fetchManifestAndMaybeUpdate(activity, manifestUrl, force, false, 30); + } + }); + } + + private static void fetchManifestAndMaybeUpdate( + final Activity activity, + final String manifestUrl, + final boolean force, + final boolean silentAuto, + final int minIdleSeconds + ) { + OkHttpClient client = ApiClient.get().httpClient(); + Request req = new Request.Builder().url(manifestUrl).get().build(); + client.newCall(req).enqueue(new Callback() { + @Override + public void onFailure(Call call, final IOException e) { + checking.set(false); + MAIN.post(new Runnable() { + @Override + public void run() { + if (force) toast(activity, "检查更新失败: " + e.getMessage()); + } + }); + } + + @Override + public void onResponse(Call call, Response response) throws IOException { + try { + if (!response.isSuccessful() || response.body() == null) { + throw new IOException("HTTP " + response.code()); + } + String body = response.body().string(); + final JSONObject man = new JSONObject(body); + final int remoteCode = man.optInt("versionCode", 0); + final int localCode = currentVersionCode(activity); + CanteenApp.get().markOtaCheckedNow(); + if (remoteCode <= localCode) { + MAIN.post(new Runnable() { + @Override + public void run() { + checking.set(false); + if (force) toast(activity, "已是最新版本(" + localCode + ")"); + } + }); + return; + } + final String apkUrl = resolveApkUrl(manifestUrl, man); + final String sha256 = man.optString("sha256", "").trim().toLowerCase(); + final String versionName = man.optString("versionName", String.valueOf(remoteCode)); + final String notes = man.optString("release_notes", ""); + final boolean forceUpdate = man.optBoolean("force_update", false); + if (TextUtils.isEmpty(apkUrl) || TextUtils.isEmpty(sha256) || sha256.length() != 64) { + throw new IOException("manifest 缺少有效 apk_url/sha256"); + } + MAIN.post(new Runnable() { + @Override + public void run() { + checking.set(false); + startDownload( + activity, apkUrl, sha256, versionName, remoteCode, notes, + forceUpdate, force, silentAuto, minIdleSeconds); + } + }); + } catch (Exception e) { + checking.set(false); + final String msg = e.getMessage(); + MAIN.post(new Runnable() { + @Override + public void run() { + if (force) toast(activity, "检查更新失败: " + msg); + } + }); + } finally { + response.close(); + } + } + }); + } + + private static void startDownload( + final Activity activity, + String apkUrl, + final String sha256, + final String versionName, + final int versionCode, + final String notes, + final boolean forceUpdate, + final boolean userTriggered, + final boolean silentAuto, + final int minIdleSeconds + ) { + if (!downloading.compareAndSet(false, true)) { + if (userTriggered) toast(activity, "正在下载更新…"); + return; + } + if (userTriggered) toast(activity, "发现新版本,正在下载…"); + final File dir = activity.getExternalFilesDir("ota"); + final File out = new File(dir != null ? dir : new File(activity.getFilesDir(), "ota"), "update.apk"); + //noinspection ResultOfMethodCallIgnored + out.getParentFile().mkdirs(); + + OkHttpClient client = ApiClient.get().downloadClient(); + Request req = new Request.Builder().url(apkUrl).get().build(); + client.newCall(req).enqueue(new Callback() { + @Override + public void onFailure(Call call, final IOException e) { + downloading.set(false); + MAIN.post(new Runnable() { + @Override + public void run() { + if (userTriggered) toast(activity, "下载失败: " + e.getMessage()); + } + }); + } + + @Override + public void onResponse(Call call, Response response) throws IOException { + ResponseBody body = response.body(); + try { + if (!response.isSuccessful() || body == null) { + throw new IOException("HTTP " + response.code()); + } + InputStream in = body.byteStream(); + FileOutputStream fos = new FileOutputStream(out); + byte[] buf = new byte[8192]; + int n; + while ((n = in.read(buf)) >= 0) { + fos.write(buf, 0, n); + } + fos.flush(); + fos.close(); + String actual = sha256Of(out); + if (!sha256.equalsIgnoreCase(actual)) { + //noinspection ResultOfMethodCallIgnored + out.delete(); + throw new IOException("文件校验失败(sha256 不匹配)"); + } + MAIN.post(new Runnable() { + @Override + public void run() { + downloading.set(false); + if (silentAuto) { + scheduleSilentInstall(activity, out, minIdleSeconds, userTriggered); + } else { + promptInstall(activity, out, versionName, versionCode, notes, forceUpdate); + } + } + }); + } catch (Exception e) { + downloading.set(false); + final String msg = e.getMessage(); + MAIN.post(new Runnable() { + @Override + public void run() { + if (userTriggered) toast(activity, "下载失败: " + msg); + } + }); + } finally { + if (body != null) body.close(); + response.close(); + } + } + }); + } + + private static void scheduleSilentInstall( + final Activity activity, + final File apkFile, + int minIdleSeconds, + final boolean userTriggered + ) { + if (userTriggered) toast(activity, "已下载,即将静默安装…"); + MAIN.postDelayed(new Runnable() { + @Override + public void run() { + if (activity.isFinishing()) return; + new Thread(new Runnable() { + @Override + public void run() { + final SilentApkInstaller.Result r = SilentApkInstaller.install(apkFile); + MAIN.post(new Runnable() { + @Override + public void run() { + if (r.ok) { + if (userTriggered) toast(activity, "静默安装成功,即将重启应用"); + // 给 PackageManager 一点时间,再拉起自身 + MAIN.postDelayed(new Runnable() { + @Override + public void run() { + try { + Intent launch = activity.getPackageManager() + .getLaunchIntentForPackage(activity.getPackageName()); + if (launch != null) { + launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK + | Intent.FLAG_ACTIVITY_CLEAR_TOP); + activity.startActivity(launch); + } + } catch (Exception ignored) { + } + Runtime.getRuntime().exit(0); + } + }, 800); + } else { + Log.w(TAG, "silent install failed: " + r.message); + if (userTriggered) { + toast(activity, "静默安装失败: " + r.message); + } + // 自动窗失败时不弹系统安装器,避免违背真静默产品选择 + } + } + }); + } + }, "silent-ota-install").start(); + } + }, Math.max(0, minIdleSeconds) * 1000L); + } + + private static void promptInstall( + final Activity activity, + final File apkFile, + String versionName, + int versionCode, + String notes, + boolean forceUpdate + ) { + if (activity.isFinishing()) return; + StringBuilder msg = new StringBuilder(); + msg.append("新版本 ").append(versionName).append(" (").append(versionCode).append(") 已下载完成。\n"); + if (!TextUtils.isEmpty(notes)) { + msg.append(notes).append('\n'); + } + msg.append("是否立即安装?"); + AlertDialog.Builder b = new AlertDialog.Builder(activity) + .setTitle("发现新版本") + .setMessage(msg.toString()) + .setCancelable(!forceUpdate) + .setPositiveButton("立即安装", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + toast(activity, "正在安装…"); + new Thread(new Runnable() { + @Override + public void run() { + final SilentApkInstaller.Result r = SilentApkInstaller.install(apkFile); + MAIN.post(new Runnable() { + @Override + public void run() { + if (r.ok) { + toast(activity, "安装成功,即将重启应用"); + MAIN.postDelayed(new Runnable() { + @Override + public void run() { + try { + Intent launch = activity.getPackageManager() + .getLaunchIntentForPackage(activity.getPackageName()); + if (launch != null) { + launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK + | Intent.FLAG_ACTIVITY_CLEAR_TOP); + activity.startActivity(launch); + } + } catch (Exception ignored) { + } + Runtime.getRuntime().exit(0); + } + }, 800); + } else { + toast(activity, "安装失败: " + r.message); + } + } + }); + } + }, "manual-ota-install").start(); + } + }); + if (!forceUpdate) { + b.setNegativeButton("稍后", null); + } + b.show(); + } + + static String resolveApkUrl(String manifestUrl, JSONObject man) { + String absolute = man.optString("apk_url", "").trim(); + if (!TextUtils.isEmpty(absolute) && (absolute.startsWith("http://") || absolute.startsWith("https://"))) { + return absolute; + } + String key = man.optString("apk_key", "").trim().replace('\\', '/'); + if (TextUtils.isEmpty(key)) return ""; + int slash = manifestUrl.lastIndexOf('/'); + if (slash <= 0) return ""; + String base = manifestUrl.substring(0, slash + 1); + while (key.startsWith("./")) key = key.substring(2); + return base + key; + } + + public static int currentVersionCode(Context context) { + try { + PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); + return pi.versionCode; + } catch (Exception e) { + return 0; + } + } + + public static String currentVersionName(Context context) { + try { + PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); + return pi.versionName != null ? pi.versionName : "?"; + } catch (Exception e) { + return "?"; + } + } + + private static String sha256Of(File file) throws Exception { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + FileInputStream in = new FileInputStream(file); + byte[] buf = new byte[8192]; + int n; + while ((n = in.read(buf)) >= 0) { + md.update(buf, 0, n); + } + in.close(); + byte[] dig = md.digest(); + StringBuilder sb = new StringBuilder(dig.length * 2); + for (byte b : dig) { + sb.append(String.format("%02x", b)); + } + return sb.toString(); + } + + private static void toast(Context ctx, String msg) { + Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show(); + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/weigh/SceneGate.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/weigh/SceneGate.java new file mode 100644 index 0000000..6f44947 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/weigh/SceneGate.java @@ -0,0 +1,95 @@ +package com.canteen.weigh.weigh; + +/** + * 静止画面闸门:画面指纹 + 重量都没变时,跳过本次 AI 调用(省钱、防夜班空转)。 + * + *

设计:docs/design/20260924-weigh-scene-gate-and-adaptive-retry.md + * + *

硬约束:本类只回答「这一拍要不要跳过 AI 调用」。它不得参与命中态 + * ({@code recognizeMatched})、按钮可用性、{@code cyclePhase} 的判定,也不得清识别结果。 + * 20260910 的「画面换货检测」就是因为会对焦/曝光抖动误判换货、清掉命中态导致按钮置灰而被停用 + * (见 docs/design/20260910-weigh-no-rerecognize-stable-weight.md),别再犯同一个错。 + * + *

纯 Java、无 Android 依赖,便于日后补单测(当前工程无单测设施)。 + */ +public final class SceneGate { + + /** 64 位 dHash 允许的差异位数;越小越敏感。4/64 为保守起点。 */ + public static final int HAMMING_MAX = 4; + + /** 重量视为「没变」的容差(kg)。比 0.1 斤(默认跳变阈值)更灵敏。 */ + public static final double WEIGHT_EPS_KG = 0.05; + + /** 连续跳过次数上限,达到后强制放行一次(防「永远跳过」)。与 {@link #MAX_SKIP_MS} 取先到者。 */ + public static final int MAX_SKIP_COUNT = 300; + + /** + * 距上次真正调 AI 的最长间隔(ms),超过后强制放行一次(防「永远跳过」的安全网)。 + * 15 分钟:静止画面下把调用压到 ≤4 次/时,同时不会让"真的出问题"隐藏太久; + * 换货(重量跳变)、空秤复位、手动识别都不受影响,随时能立刻调 AI。 + */ + public static final long MAX_SKIP_MS = 900000L; + + /** 上一次「已送去识别」的帧指纹;0 表示还没有基准。 */ + private long lastHash = 0L; + + /** 上一次「已送去识别」时的秤读数(kg)。 */ + private double lastKg = Double.NaN; + + /** 自上次真正调 AI 以来连续跳过的次数。 */ + private int skipCount = 0; + + /** 上一次真正调 AI 的时刻(elapsedRealtime)。 */ + private long lastAiAtMs = 0L; + + /** + * 判定这一拍是否跳过 AI 调用。 + * + * @param hash 当前帧指纹(0 = 取不到帧 → 失败开放,不跳过) + * @param kg 当前秤读数(kg;NaN → 失败开放,不跳过) + * @param nowMs {@code SystemClock.elapsedRealtime()} + * @param enabled 闸门开关 + * @return true = 画面与重量都没变,应跳过本次 AI 调用 + */ + public boolean shouldSkip(long hash, double kg, long nowMs, boolean enabled) { + if (!enabled || hash == 0L || Double.isNaN(kg)) { + return false; + } + boolean sameFrame = lastHash != 0L && Long.bitCount(hash ^ lastHash) <= HAMMING_MAX; + boolean sameWeight = !Double.isNaN(lastKg) && Math.abs(kg - lastKg) < WEIGHT_EPS_KG; + if (!(sameFrame && sameWeight)) { + // 有变化:把当前帧记为新的识别基准并放行(顺带实现「有变化免冷却」)。 + lastHash = hash; + lastKg = kg; + skipCount = 0; + lastAiAtMs = nowMs; + return false; + } + // 无变化:先看两条兜底,避免极端情况下「永远不调 AI」。 + if (skipCount >= MAX_SKIP_COUNT) { + skipCount = 0; + lastAiAtMs = nowMs; + return false; + } + if (lastAiAtMs > 0 && nowMs - lastAiAtMs >= MAX_SKIP_MS) { + skipCount = 0; + lastAiAtMs = nowMs; + return false; + } + skipCount++; + return true; + } + + /** 当前连续跳过次数(仅日志用)。 */ + public int skipCount() { + return skipCount; + } + + /** 空秤/新一件时复位,保证「拿下来再放回去」一定会重新识别。 */ + public void reset() { + lastHash = 0L; + lastKg = Double.NaN; + skipCount = 0; + lastAiAtMs = 0L; + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/weigh/WeighManager.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/weigh/WeighManager.java new file mode 100644 index 0000000..1137ec4 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/weigh/WeighManager.java @@ -0,0 +1,261 @@ +package com.canteen.weigh.weigh; + +import android.os.Handler; +import android.os.Looper; +import android.util.Log; + +import com.canteen.weigh.CanteenApp; +import com.keepempty.sph.library.ReceiveCallback; +import com.keepempty.sph.library.WeighSdk; + +/** + * 称重管理器:封装京源衡业 SDK,提供稳定的重量数据流 + */ +public class WeighManager implements ReceiveCallback { + + private static final String TAG = "WeighManager"; + private static WeighManager instance; + + private WeighListener listener; + private final Handler mainHandler; + + // 重量数据防抖:按解析后的数值去重,秤稳定时不重复回调 + private String lastWeight = ""; + private double lastWeightKg = Double.NaN; + private long lastCallbackAt = 0; + /** 低于该公斤差视为读数未变(5g,低于大屏 2 位小数的显示分辨率) */ + private static final double DEDUP_DELTA_KG = 0.005; + /** 读数长期不变时的纠正心跳:防止秤漂移后读数一直不被刷新 */ + private static final long HEARTBEAT_MS = 60_000L; + + public interface WeighListener { + /** + * 重量变化回调 + * @param weight 原始字符串(如 "1.235") + * @param weightKg 解析后的公斤数 + */ + void onWeightChanged(String weight, double weightKg); + + void onError(String msg); + + void onConnected(boolean connected); + } + + private WeighManager() { + mainHandler = new Handler(Looper.getMainLooper()); + } + + public static synchronized WeighManager get() { + if (instance == null) { + instance = new WeighManager(); + } + return instance; + } + + /** + * 初始化并打开串口 + */ + public void init(WeighListener listener) { + this.listener = listener; + + WeighSdk.getInstance().registerDataCallback(this); + + String port = CanteenApp.get().getSerialPort(); + int baud = CanteenApp.get().getBaudRate(); + String profile = CanteenApp.get().getDeviceProfile().getDisplayName(); + + Log.d(TAG, "尝试打开串口: " + profile + " " + port + " @ " + baud); + + boolean ok = WeighSdk.getInstance().openSerialPort(port, baud); + + if (ok) { + Log.d(TAG, "串口打开成功"); + notifyConnected(true); + // 进台时秤上可能已有货且读数未变,补推最近一次重量以便自动开预览 + if (listener != null && lastWeight != null && !lastWeight.isEmpty()) { + listener.onWeightChanged(lastWeight, parseWeight(lastWeight)); + } + } else { + Log.e(TAG, "串口打开失败: " + port); + notifyError("串口打开失败: " + profile + " " + port + " @" + baud); + notifyConnected(false); + } + } + + /** + * 设置页:按指定端口测试打开后立即关闭,不占用验收页 + */ + public boolean testOpen(String port, int baud) { + if (port == null || port.trim().isEmpty()) { + return false; + } + if (baud <= 0) { + baud = 9600; + } + try { + if (WeighSdk.getInstance().isOpen()) { + WeighSdk.getInstance().closeSerialPort(); + } + boolean ok = WeighSdk.getInstance().openSerialPort(port.trim(), baud); + WeighSdk.getInstance().closeSerialPort(); + Log.d(TAG, "测试连接 " + port + " @" + baud + " => " + ok); + return ok; + } catch (Exception e) { + Log.e(TAG, "测试连接异常: " + e.getMessage()); + try { + WeighSdk.getInstance().closeSerialPort(); + } catch (Exception ignored) { + } + return false; + } + } + + /** + * 关闭串口并释放资源 + */ + public void release() { + WeighSdk.getInstance().unregisterDataCallback(this); + WeighSdk.getInstance().closeSerialPort(); + listener = null; + Log.d(TAG, "称重管理器已释放"); + } + + /** + * 暂停串口读取(打印前释放 USB 总线),保留 listener 以便恢复 + */ + public void pauseSerial() { + if (WeighSdk.getInstance().isOpen()) { + WeighSdk.getInstance().closeSerialPort(); + Log.d(TAG, "串口已暂停(打印前释放 USB)"); + } + } + + /** + * 恢复串口读取(打印完成后) + */ + public void resumeSerial() { + if (WeighSdk.getInstance().isOpen()) { + return; // 已经打开 + } + String port = CanteenApp.get().getSerialPort(); + int baud = CanteenApp.get().getBaudRate(); + boolean ok = WeighSdk.getInstance().openSerialPort(port, baud); + Log.d(TAG, "串口恢复: " + port + " @" + baud + " => " + ok); + if (ok && listener != null && lastWeight != null && !lastWeight.isEmpty()) { + listener.onWeightChanged(lastWeight, parseWeight(lastWeight)); + } + } + + /** + * 置零(数字版) + */ + public boolean zeroing() { + if (!WeighSdk.getInstance().isOpen()) { + notifyError("串口未打开,无法置零"); + return false; + } + WeighSdk.getInstance().zeroingNum(); + return true; + } + + /** + * 去皮(数字版) + */ + public boolean tare() { + if (!WeighSdk.getInstance().isOpen()) { + notifyError("串口未打开,无法去皮"); + return false; + } + WeighSdk.getInstance().tareNum(); + return true; + } + + /** + * 获取可用串口列表 + */ + public String[] getAvailablePorts() { + try { + String[] ports = WeighSdk.getInstance().getSerialPorts(); + return ports != null ? ports : new String[0]; + } catch (Exception e) { + Log.w(TAG, "获取串口列表失败: " + e.getMessage()); + return new String[0]; + } + } + + /** + * 是否已连接 + */ + public boolean isConnected() { + return WeighSdk.getInstance().isOpen(); + } + + /** 最近一次解析到的公斤数;尚无读数则为 0 */ + public double getLastWeightKg() { + if (lastWeight == null || lastWeight.isEmpty()) { + return 0; + } + return parseWeight(lastWeight); + } + + // ========== ReceiveCallback 实现 ========== + + @Override + public void onDataReceived(final String ascii) { + mainHandler.post(new Runnable() { + @Override + public void run() { + if (ascii == null || ascii.isEmpty()) return; + + long now = System.currentTimeMillis(); + double kg = parseWeight(ascii); + boolean unchanged = !Double.isNaN(lastWeightKg) + && Math.abs(kg - lastWeightKg) < DEDUP_DELTA_KG; + if (unchanged && (now - lastCallbackAt) < HEARTBEAT_MS) { + lastWeight = ascii; + return; + } + lastWeight = ascii; + lastWeightKg = kg; + lastCallbackAt = now; + + if (listener != null) { + listener.onWeightChanged(ascii, kg); + } + } + }); + } + + private double parseWeight(String raw) { + try { + String cleaned = raw.replaceAll("[^0-9.\\-]", "").trim(); + if (cleaned.isEmpty()) return 0; + return Double.parseDouble(cleaned); + } catch (NumberFormatException e) { + Log.w(TAG, "重量解析失败: " + raw); + return 0; + } + } + + private void notifyConnected(final boolean connected) { + mainHandler.post(new Runnable() { + @Override + public void run() { + if (listener != null) { + listener.onConnected(connected); + } + } + }); + } + + private void notifyError(final String msg) { + mainHandler.post(new Runnable() { + @Override + public void run() { + if (listener != null) { + listener.onError(msg); + } + } + }); + } +} diff --git a/android-weigh-terminal/app/src/main/java/com/canteen/weigh/weigh/WeighStationMatcher.java b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/weigh/WeighStationMatcher.java new file mode 100644 index 0000000..2fceaf9 --- /dev/null +++ b/android-weigh-terminal/app/src/main/java/com/canteen/weigh/weigh/WeighStationMatcher.java @@ -0,0 +1,208 @@ +package com.canteen.weigh.weigh; + +import com.canteen.weigh.model.InspectionTask; +import com.canteen.weigh.model.PickingItem; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; + +/** + * 分拣台 / 验收台匹配与阈值校验 + */ +public final class WeighStationMatcher { + + private WeighStationMatcher() { + } + + public static String normalizeName(String name) { + if (name == null) return ""; + return name.trim().toLowerCase(Locale.ROOT).replaceAll("\\s+", ""); + } + + public static boolean isWeightUnit(String unit) { + if (unit == null) return false; + String u = unit.trim().toLowerCase(Locale.ROOT); + return u.contains("斤") || u.contains("公斤") || u.equals("kg") || u.equals("g") + || u.contains("千克") || u.equals("市斤") || u.equals("克") + || u.contains("两"); + } + + /** 市斤/斤(不含「公斤」) */ + public static boolean isJinUnit(String unit) { + if (unit == null) return false; + String u = unit.trim().toLowerCase(Locale.ROOT); + if (u.contains("公斤") || u.contains("千克") || u.equals("kg") || u.equals("g") || u.equals("克")) { + return false; + } + return u.contains("斤") || u.contains("市斤"); + } + + public static boolean isKgUnit(String unit) { + if (unit == null) return false; + String u = unit.trim().toLowerCase(Locale.ROOT); + return u.equals("kg") || u.contains("公斤") || u.contains("千克"); + } + + public static boolean isGramUnit(String unit) { + if (unit == null) return false; + String u = unit.trim().toLowerCase(Locale.ROOT); + return u.equals("g") || u.equals("克"); + } + + /** + * 电子秤读数 → 与商品备货/应拣同口径的业务量。 + * scaleUnit: 秤的实际输出单位("kg"/"jin"/"g"),默认 kg。 + * 斤/市斤 → kg(÷2) → 业务单位;g/克 → kg(÷1000) → 业务单位。 + */ + public static double scaleKgToBusiness(double weightRaw, String unit, String scaleUnit) { + if (!(weightRaw > 0)) { + return 0; + } + // Step 1: 秤读数 → kg + double kg; + String su = (scaleUnit != null) ? scaleUnit.trim().toLowerCase(Locale.ROOT) : ""; + if (su.equals("jin") || su.equals("斤") || su.equals("市斤")) { + kg = weightRaw / 2.0; // 斤 → kg + } else if (su.equals("g") || su.equals("克")) { + kg = weightRaw / 1000.0; // 克 → kg + } else { + kg = weightRaw; // 默认 kg + } + // Step 2: kg → 业务单位 + if (isJinUnit(unit)) { + return kg * 2.0; + } + if (isGramUnit(unit)) { + return kg * 1000.0; + } + // 1 两 = 0.1 斤,1 kg = 2 斤 → 1 kg = 20 两(与 unit_conversions 一致) + if (unit != null && unit.trim().contains("两")) { + return kg * 20.0; + } + if (isKgUnit(unit) || unit == null || unit.trim().isEmpty()) { + // kg / 公斤 / 千克 / 空单位:保持 kg(不再默认按斤,避免单位不明时误乘2) + return kg; + } + // 计数单位(瓶/个/份/件等):秤值无法换算成计数,返回 0 由调用方按应拣数量兜底 + return 0; + } + + /** 兼容旧调用:默认秤输出为 kg */ + public static double scaleKgToBusiness(double weightKg, String unit) { + return scaleKgToBusiness(weightKg, unit, "kg"); + } + + /** 展示用单位;空则默认斤 */ + public static String displayUnit(String unit) { + if (unit == null || unit.trim().isEmpty()) { + return "斤"; + } + return unit.trim(); + } + + public static List filterSameProduct(List all, String skuCode, String itemName) { + List out = new ArrayList<>(); + String sku = skuCode == null ? "" : skuCode.trim(); + String name = normalizeName(itemName); + for (PickingItem item : all) { + if (item == null) continue; + boolean sameSku = !sku.isEmpty() && sku.equals(String.valueOf(item.skuCode == null ? "" : item.skuCode).trim()); + boolean sameName = !name.isEmpty() && name.equals(normalizeName(item.itemName)); + if (sameSku || sameName) { + out.add(item); + } + } + return out; + } + + /** + * 优先按订单顺序分配(sortOrder → orderCode),同订单同量时才按重量误差匹配。 + * 这样同一商品跨多订单时,先到先拣,不会因重量相近而跳单。 + */ + public static PickingItem pickBest(List candidates, double actualWeight) { + if (candidates == null || candidates.isEmpty()) return null; + List list = new ArrayList<>(candidates); + Collections.sort(list, new Comparator() { + @Override + public int compare(PickingItem a, PickingItem b) { + // 1) 按订单号排序(先到先拣) + int byOrder = String.valueOf(a.orderCode).compareTo(String.valueOf(b.orderCode)); + if (byOrder != 0) return byOrder; + // 2) 同订单内按行号 + int bySort = Integer.compare(a.sortOrder, b.sortOrder); + if (bySort != 0) return bySort; + // 3) 同订单同行号:按重量误差(兜底) + double da = Math.abs(a.requiredQty - actualWeight); + double db = Math.abs(b.requiredQty - actualWeight); + return Double.compare(da, db); + } + }); + return list.get(0); + } + + public static List filterSameInspectionProduct( + List all, String skuCode, String itemName) { + List out = new ArrayList<>(); + String sku = skuCode == null ? "" : skuCode.trim(); + String name = normalizeName(itemName); + for (InspectionTask item : all) { + if (item == null) continue; + boolean sameSku = !sku.isEmpty() + && sku.equals(String.valueOf(item.skuCode == null ? "" : item.skuCode).trim()); + boolean sameName = !name.isEmpty() && name.equals(normalizeName(item.itemName)); + if (sameSku || sameName) { + out.add(item); + } + } + return out; + } + + /** 优先按订单顺序分配(sortOrder → orderCode),同订单同量时才按重量误差匹配 */ + public static InspectionTask pickBestInspection(List candidates, double actualWeight) { + if (candidates == null || candidates.isEmpty()) return null; + List list = new ArrayList<>(candidates); + Collections.sort(list, new Comparator() { + @Override + public int compare(InspectionTask a, InspectionTask b) { + // 1) 按订单号排序(先到先拣) + int byOrder = String.valueOf(a.orderCode).compareTo(String.valueOf(b.orderCode)); + if (byOrder != 0) return byOrder; + // 2) 同订单内按行号 + int bySort = Integer.compare(a.sortOrder, b.sortOrder); + if (bySort != 0) return bySort; + // 3) 同订单同行号:按重量误差(兜底) + double da = Math.abs(a.prepareQty - actualWeight); + double db = Math.abs(b.prepareQty - actualWeight); + return Double.compare(da, db); + } + }); + return list.get(0); + } + + public static double allowedDiff(String mode, double value, double requiredQty) { + if (!(value > 0)) { + return Double.POSITIVE_INFINITY; + } + if ("absolute".equals(mode)) { + return value; + } + return Math.abs(requiredQty) * (value / 100.0); + } + + /** value≤0 表示关闭误差校验 */ + public static boolean withinTolerance(double requiredQty, double actualQty, + String mode, double value) { + if (!(value > 0)) { + return true; + } + double diff = Math.abs(actualQty - requiredQty); + return diff <= allowedDiff(mode, value, requiredQty) + 1e-9; + } + + public static boolean isToleranceDisabled(double value) { + return !(value > 0); + } +} diff --git a/android-weigh-terminal/app/src/main/res/drawable/btn_bg_blue.xml b/android-weigh-terminal/app/src/main/res/drawable/btn_bg_blue.xml new file mode 100644 index 0000000..b323e39 --- /dev/null +++ b/android-weigh-terminal/app/src/main/res/drawable/btn_bg_blue.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/android-weigh-terminal/app/src/main/res/drawable/btn_bg_default.xml b/android-weigh-terminal/app/src/main/res/drawable/btn_bg_default.xml new file mode 100644 index 0000000..22b40f0 --- /dev/null +++ b/android-weigh-terminal/app/src/main/res/drawable/btn_bg_default.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/android-weigh-terminal/app/src/main/res/drawable/btn_bg_font_size.xml b/android-weigh-terminal/app/src/main/res/drawable/btn_bg_font_size.xml new file mode 100644 index 0000000..3780784 --- /dev/null +++ b/android-weigh-terminal/app/src/main/res/drawable/btn_bg_font_size.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/android-weigh-terminal/app/src/main/res/drawable/btn_bg_gray.xml b/android-weigh-terminal/app/src/main/res/drawable/btn_bg_gray.xml new file mode 100644 index 0000000..8687b18 --- /dev/null +++ b/android-weigh-terminal/app/src/main/res/drawable/btn_bg_gray.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/android-weigh-terminal/app/src/main/res/drawable/btn_bg_green.xml b/android-weigh-terminal/app/src/main/res/drawable/btn_bg_green.xml new file mode 100644 index 0000000..57e5a43 --- /dev/null +++ b/android-weigh-terminal/app/src/main/res/drawable/btn_bg_green.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/android-weigh-terminal/app/src/main/res/drawable/btn_bg_green_dark.xml b/android-weigh-terminal/app/src/main/res/drawable/btn_bg_green_dark.xml new file mode 100644 index 0000000..59e84e0 --- /dev/null +++ b/android-weigh-terminal/app/src/main/res/drawable/btn_bg_green_dark.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/android-weigh-terminal/app/src/main/res/drawable/btn_bg_orange.xml b/android-weigh-terminal/app/src/main/res/drawable/btn_bg_orange.xml new file mode 100644 index 0000000..f3accc8 --- /dev/null +++ b/android-weigh-terminal/app/src/main/res/drawable/btn_bg_orange.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/android-weigh-terminal/app/src/main/res/drawable/btn_bg_slate.xml b/android-weigh-terminal/app/src/main/res/drawable/btn_bg_slate.xml new file mode 100644 index 0000000..d30a32d --- /dev/null +++ b/android-weigh-terminal/app/src/main/res/drawable/btn_bg_slate.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/android-weigh-terminal/app/src/main/res/layout/activity_device_settings.xml b/android-weigh-terminal/app/src/main/res/layout/activity_device_settings.xml new file mode 100644 index 0000000..5b8ab4b --- /dev/null +++ b/android-weigh-terminal/app/src/main/res/layout/activity_device_settings.xml @@ -0,0 +1,464 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +