diff --git a/docs/打印组件连接-持久化与自动重连方案.md b/docs/打印组件连接-持久化与自动重连方案.md new file mode 100644 index 00000000..cf1ce9be --- /dev/null +++ b/docs/打印组件连接-持久化与自动重连方案.md @@ -0,0 +1,312 @@ +# 打印组件连接:登录自动尝试 / 持久化防断连 / 增强失败自动重连 + +- 状态:**已废弃**(v1.0 草案,含“多入口自动尝试”设计) +- 日期:2026-09-04 +- **取代文档**:`docs/打印组件连接-登录一次连接与失败重连方案.md`(v1.1,按用户口径收敛为“登录一次连接 / 复用不断连 / 失败驱动自动重连”),本文档不再使用 +- 范围:`order/waveOrder` 及 `order/orderManagement`(pendingOrder / deliveryOrder / exceptionOrder)等提供「批量打印(平台数据)」的页面所用的**打印组件连接链路** +- 原则:**不改动打印协议与载荷**(print.ts 的 payload / 组件消息协议保持现状),只优化「连接生命周期、失败重连、配置持久化」三部分 +- 关联正式方案:`docs/用户偏好配置-浏览器本地保存方案.md`(v1.1,配置持久化的唯一依据,本文在此之上扩展“仓库”维度) + +--- + +## 1. 背景与目标 + +“批量打印(平台数据)”会把面单直接通过**浏览器 WebSocket 直发本机打印组件**(抖音 / 拼多多 / 快手 / 京东 / 菜鸟 / 视频号 / 小红书 / LODOP 等 8 个本地控件)。当前连接体验存在三类问题,对应本方案三个目标: + +| # | 目标 | 现状痛点 | +|---|------|----------| +| 1 | 登录后 / 进入打印页**自动尝试连接一次**打印组件 | 连接仅在登录成功的那个时间点尝试一次;若当时控件未启动,之后进入打印页/打开打印弹窗**不会自动再试**,需手动点“重连” | +| 2 | 组件连接**持久化**,切换页面后**不断连、不需重新连接** | 组件在后台可能被本地控件重启/断开;开关页回来后若失败自动重连关闭,就显示“未连接”需手动重连 | +| 3 | **增强失败自动重连**:可设置哪些组件“失败自动尝试 / 排除自动重连”;配置**分用户 + 分仓库持久化**(与表格字段排序等用户偏好同模式) | 现有“失败自动重连”是**浏览器全局布尔**,不分用户/仓库;只能整开整关,不能按组件排除 | + +> 说明:仓库(warehouse)维度取自当前登录上下文 `userStore.user?.warehouse_id ?? userStore.user?.store_id`(代码中已有同类取值先例)。控件安装在“本机/本仓”,不同仓库常用平台不同,因此“哪些组件参与自动重连”需要按 **用户 + 仓库** 分别记忆。 + +--- + +## 2. 现状梳理(关键代码位置) + +| 文件 | 角色 | 现状要点 | +|------|------|----------| +| `src/core/printerComponentCore.ts` | 连接引擎(模块级单例) | WebSocket 长连接 map;`autoReconnectEnabled` 全局布尔默认 `false`;失败重连固定间隔 `3000ms`、**无退避/无上限/无按组件排除**;`connectGeneration` 已防竞态;`initAll/setAutoReconnectEnabled/reconnectAll/disconnectAll` 遍历的是模块常量 `DEFAULT_PRINTER_COMPONENTS` 而非 `this.ports`(小瑕疵) | +| `src/core/printerRuntime.ts` | 生命周期门面 | `initPrinterRuntime()`(main 启动,仅挂消息);`startPrinterComponentConnections()`(`connectionsStarted` 置位,**会话内只一次**,登录成功调用);`ensurePrinterConnectionsForBrowserPrint()`(打印前调用,当前只是置位标记,**不实际建连**);`stopPrinterComponentConnections()`(登出断开) | +| `src/core/printerComponentConnection.ts` | loopback/HTTPS 环境检测 + preflight | 无需改(仅被复用) | +| `src/stores/modules/printerComponent.ts` | 连接状态 Pinia store | 全局布尔 key `printer_component_auto_reconnect`(localStorage,**不分用户/仓库**);`bindRuntimeEvents` 于 main.ts 挂一次 | +| `src/stores/modules/userPreference.ts` | 用户偏好 store(localStorage) | key=`user_prefs_{userId}`,按 scope 存 `{value,updated_at}`;**目前只有 user 维度,无仓库维度**;`load()` 挂在 permission 守卫 getInfo 成功后 | +| `src/stores/modules/user.ts` / `src/permission.ts` | 登录/登出接入 | login / getInfo 成功后 `startConnections()`;logout / resetToken 时 `stopConnections()` | +| `src/views/order/waveOrder/component/PrinterComponentConnectionPanel.vue` | 连接面板 UI(共享) | 含“失败自动重连”开关(全局)、连接概况、组件表格(名称/端口/状态/重连);**无逐组件配置** | +| `src/views/order/waveOrder/component/WavePlatformPrintPreviewDialog.vue` | 平台数据打印预览弹窗 | 打开时 `watch(modelValue)` 只 `refreshFromRuntime()`,**不自动尝试连接**;底部“打印组件连接”按钮内嵌连接面板;`allComponentsConnected` 未全连时“打印”禁用 | +| 打印流程 `src/views/order/waveOrder/config/print.ts` | 下发 | `sendWavePlatformBrowserPrint` 前调 `ensurePrinterConnectionsForBrowserPrint`(不实际连),随后校验未连接组件直接失败并提示去连接面板 | +| 页面(复用平台打印弹窗) | 入口 | `SandanWaveBatchListPanel.vue`、`GroupWaveBatchListPanel.vue`、orderManagement 的 `pendingOrder.vue / deliveryOrder.vue / exceptionOrder.vue`(经各自 `use-*.ts`);各面板含内嵌连接对话框;页面处于 `keep-alive`(index.vue / orderManagement index 用 KeepAlive + LRU) | + +**关键结论** +1. 路由切换本身**不会**断开 WebSocket(模块级单例、无 onUnmounted 断连),痛点是“断连后无自愈 + 未连组件无自动尝试 + 开关/排除配置不可按用户/仓库记忆”。 +2. “进入打印页/弹窗”与“打印前”都存在**可以且应该自动尝试一次**的时机,目前都未利用。 +3. 失败自动重连从“全局布尔”升级为“**用户+仓库级配置 + 逐组件参与开关 + 退避重试**”即可同时覆盖三目标。 + +--- + +## 3. 方案总览 + +```mermaid +flowchart TB + subgraph P[打印相关页面 order/waveOrder 等] + E[进入页面/打开平台打印弹窗
onMounted / onActivated / watch modelValue] + D[批量打印(平台数据) 下发前] + C[连接面板 / 设置弹窗] + end + + subgraph S[printerComponent store(用户+仓库配置作用域)] + L[loadReconnectConfig 登录后/换仓后加载] + A[applyConfig 应用引擎] + T[autoTryConnectOnce 节流自动尝试] + W[watch 状态变更刷新 UI] + end + + subgraph CORE[PrinterComponentCore 引擎] + R[失败自动重连
退避 + 上限 + 排除集合] + O[one-shot 自动尝试
连接代数防竞态] + H[健康检查/自愈
page focus / 页签回前台] + end + + subgraph STORE[localStorage 分用户+仓库] + PREFS[user_prefs_{userId}_{warehouseId}
scope: printer.autoReconnect] + end + + E -->|进入即自动尝试| T + D -->|下发前按配置自动尝试一次
未连才报错| T + C -->|修改配置即存即生效| L + L --> A --> CORE + T --> CORE + T -.读配置(排除集合).-> PREFS + L -.读写.-> PREFS + CORE -->|状态/重连事件| W + CORE -->|断连触发| R + CORE -->|页面回前台触发| H +``` + +--- + +## 4. 数据与存储设计(分用户 + 分仓库) + +### 4.1 身份与 key(userPreference 层扩展) + +沿用 `userPreference` store(与标签/字段排序等用户偏好**同源同模式**),在其上引入**仓库维度**,并做向后兼容迁移: + +```ts +// 新增:稳定取当前仓库标识(与订单页“仓库 ID 优先取行、其次登录上下文”一致) +function currentWarehouseId(): string { + const userStore = useUserStore() + const user = userStore.user || {} + const wh = user.warehouse_id ?? user.store_id + return wh != null && wh !== '' ? String(wh) : '' +} + +// 存储 key:有仓库上下文时 用户+仓库,否则退化为现状 user_prefs_{userId} +function currentStorageKey(): string { + const wh = currentWarehouseId() + return wh ? `user_prefs_${currentUserId()}_${wh}` : `user_prefs_${currentUserId()}` +} +``` + +- **load()**:先读 `user_prefs_{userId}_{warehouseId}`(新主 key);无数据则回退读旧 key `user_prefs_{userId}`,读到后**一次性迁移**(同内容写回新 key,仅当有仓库上下文时)。 +- **set / reset / persist**:一律写新 key;旧 key 保留不主动删(保守,避免回滚丢配置)。 +- 无仓库上下文的部署 key 不变,完全向后兼容;已有标签顺序等旧配置通过回退迁移无缝保留。 +- **身份变化时重载**:`changeRole` 成功(可能换仓)与 `userStore.getInfo` 成功后,若 `warehouse_id` 变化需重新 `load()`(可在 `userPreference` 内监听 user 或由调用方显式调用)。 +- localStorage 满/禁用仍沿用 try/catch 降级内存态。 + +### 4.2 新 scope 与配置结构 + +scope 命名沿用规范 `<模块>.<能力>.<页面标识>`,本方案注册: + +``` +printer.autoReconnect +``` + +value 结构: + +```ts +interface PrinterAutoReconnectConfig { + /** 主开关:是否开启“失败自动重连” */ + enabled: boolean + /** 参与失败自动重连的组件;默认全部组件都参与 */ + excluded: string[] // 排除名单(= 关闭逐组件开关的组件) + /** 基础重连间隔 ms,默认 3000 */ + intervalMs: number + /** 退避上限 ms,默认 30000(可选字段,UI 可不暴露) */ + maxIntervalMs: number + /** 连续失败达到该次数后暂停自动重连,默认 5(0=不限,可选字段) */ + maxConsecutiveFailures: number + /** 进入打印页/打开打印弹窗时对未连接且未排除组件自动尝试一次,默认 true */ + autoTryOnPageEntry: boolean + updated_at: number +} +``` + +> 术语对齐需求 3:“失败自动尝试”=组件参与 `enabled && !excluded` 的断线自动重连;“排除自动重连”=组件在 `excluded` 名单内(不自动尝试、不自动重连,仅可手动“重连”)。 + +### 4.3 旧全局开关迁移 + +- `printerComponent` store 启动读取时:若 `printer.autoReconnect` 尚无配置,则把旧 key `printer_component_auto_reconnect`(浏览器全局布尔)迁移为 `enabled`,然后写入新 scope;后续不再读写旧 key。 + +--- + +## 5. 连接引擎增强(`src/core/printerComponentCore.ts`) + +在保留现有 `connectGeneration` 防竞态机制基础上扩展: + +1. **配置化** + - 新增成员:`excluded = Set`、`reconnectIntervalMs`、`maxIntervalMs`、`maxConsecutiveFailures`、`autoTryOnPageEntry`、`attempts = Map`、`lastAutoTryAt`。 + - `applyConfig(cfg)`:合并配置;**不关闭已连 socket**,只影响后续失败处理与重连节奏;主开关由关→开时,对“未连接且未排除”的组件触发一次连接尝试(沿用现有 `setAutoReconnectEnabled` 行为并收敛到 `this.ports`)。 + - 辅助:`isExcluded(name)`、`shouldAutoReconnect(name) = enabled && !excluded`。 + - 修正 `initAll / setAutoReconnectEnabled / reconnectAll / disconnectAll` 遍历 `this.ports`(而非模块常量),为将来“按仓库组件集”留口。 + +2. **失败自动重连(需求 3)** + - `onclose / onerror`:手动关闭(`_manualClose`)不处理;否则若 `shouldAutoReconnect(name)` → 走退避重连;若被排除 → 仅置为 disconnected(记录一次 `attempts` 供 UI 显示“已排除”)。 + - `scheduleReconnect`:基础间隔 + 指数退避 `min(intervalMs * 2^attempts, maxIntervalMs)`;达到 `maxConsecutiveFailures` 后**暂停**(清 timer,标记 paused),等待手动重连 / 页面进入 auto-try / 页面回前台健康检查再重置。 + - `onopen`:重置该组件 `attempts`。 + +3. **one-shot 自动尝试(需求 1)** + - `autoTryConnectOnce(names?: string[])`:对 `names`(缺省=全部注册组件)中“未 OPEN 且未排除”的组件各尝试一次 `initComponent`;内置节流(`lastAutoTryAt`,如 ≥3s)避免在打印页/弹窗反复进出时抖动。 + - 手动 `reconnectComponent(name)` 不受排除限制,始终可用,并重置 `attempts`。 + +4. **健康检查 / 自愈(需求 2)** + - `healthCheck()`:遍历参与组件,对已断开者按节流自动尝试一次;由 store 在“打印页激活 / 弹窗打开 / tab 回前台(visibilitychange)”触发,使切换页面或控件重启后回来能自愈,无需手点。 + +5. **事件补充**:`printerComponentStatusChange` 之外增发 `printerReconnectStateChange`(含 attempts / paused / excluded 信息),供 UI 显示“连续失败 N 次/已暂停/已排除”。 + +> 边界:不做心跳保活(本地控件长连接本就稳定,多为控件进程重启导致断开);保持“断连→自愈”即可。 + +--- + +## 6. 运行时与生命周期接入 + +### 6.1 `src/core/printerRuntime.ts` +- `startPrinterComponentConnections()`:保持“登录成功后初始化并连接一次”;同时改为读取并应用当前(用户+仓库)重连配置(无 token/无仓库信息也安全)。 +- 新增导出:`loadAndApplyReconnectConfig()`、`autoTryConnectOnce(names?)`、`healthCheck()` 薄封装(内部调 core,并做节流)。 +- `ensurePrinterConnectionsForBrowserPrint(names?)`:从“仅置位”升级为“置位 + `autoTryConnectOnce(names)` 自动尝试一次”,使打印下发路径能自愈(见 §6.4)。 +- 登出 `stopPrinterComponentConnections()`:保持断开(登出后清空连接,符合预期);**文档化唯一断连点**。 + +### 6.2 登录/会话接入 +- `main.ts` `bindRuntimeEvents()` 后:`printerComponent` store 在 `bind` 时读取并应用持久化配置(先 `load` 用户偏好)。 +- `permission.ts` getInfo 成功后:现有 `startConnections()` 保留(登录自动尝试一次 → 需求 1 会话级);随后 `loadReconnectConfig()`。 +- `user.ts` `login()` / `changeRole()` 成功:同步 `loadReconnectConfig()`(换仓时配置随之切换)。 + +### 6.3 页面进入自动尝试(需求 1 + 2) +统一封装进 store action(避免各页重复写逻辑): + +```ts +// printerComponent store +autoTryForPage(names?: string[]) { + this.ensureConfigLoaded() // 已加载则跳过 + this.applyConfigToRuntime() + core.autoTryConnectOnce(names) // 节流内置 +} +``` + +接入点(“等提供打印功能的页面”): +- `WavePlatformPrintPreviewDialog.vue`:`watch(modelValue)` 为 true 时 `autoTryForPage(requiredComponents)`(本次弹窗涉及组件优先); +- `SandanWaveBatchListPanel.vue` / `GroupWaveBatchListPanel.vue` / orderManagement 三个订单页:`onMounted` 一次 + `onActivated`(keep-alive 返回页签时再次,覆盖 LRU 淘汰后重建)调用 `autoTryForPage()`(缺省=全部未排除组件)。 + +### 6.4 打印下发路径配合 +- `print.ts` `sendWavePlatformBrowserPrint` 调用 `ensurePrinterConnectionsForBrowserPrint(requiredComponents)` 后,若仍有未连接组件: + - 未连接且**被排除** → 直接失败并提示“该组件已设为排除自动重连,请在连接面板手动连接”; + - 未连接且未排除但本次尝试仍失败 → 失败并提示“自动尝试失败,可开启失败自动重连或手动连接”。 + - 错误文案带组件名与处置建议,沿用现有“未连接”报错结构(不改接口返回结构)。 + +### 6.5 切页/回前台自愈(需求 2) +- store `bindRuntimeEvents` 内注册 `document visibilitychange`:页面从后台回前台时 `healthCheck()`(节流)。 +- **约定固化**:任何页面/弹窗的 `onBeforeUnmount`、`destroy-on-close`、路由离开都**不得**调用 `disconnectAll / removeComponent / stopConnections`(登出除外),避免回归性断连。 + +--- + +## 7. 设置 UI(`PrinterComponentConnectionPanel.vue` 改造) + +在既有 el-form + el-table 结构内扩展,保持“配置表单”与表格样式/排序一致: + +1. **主开关区(form)** + - “失败自动重连”主开关(改存 `printer.autoReconnect.enabled`,不再写旧全局 key)。 + - 文案:开启后组件连接断开将按退避自动重连;下方“全部重连/刷新状态”保留。 + - 高级项(可折叠“高级设置”,可选一期不做):重连间隔(s)、连续失败上限、页面进入自动尝试开关。 + +2. **组件表格** + - 新增列 **“自动重连”**:逐组件 `el-switch`,关闭 = 加入 `excluded`(“排除自动重连”),该组件断开后不自动尝试/重连,仅手动。 + - 保留列:组件名称、本地端口、连接状态;状态列在“连续失败暂停”时显示辅助标签(如 `已暂停(3/5)`)。 + - 主开关关闭时逐组件开关置灰(提示“先开启失败自动重连”)。 + - 修改即存即生效:`store.updateComponentAutoReconnect(name, on)` → 写 scope → `core.applyConfig`;**不断开已连 socket**。 + +3. **入口收敛(可选优化,降低多页面重复)** + - 目前各页各自持有连接对话框(Sandan 内嵌 + 平台弹窗内嵌等)。可把 `printerComponentConnectionVisible` 收敛为 store 单例 `connectionPanelVisible`,所有“打印组件连接”按钮打开同一个弹窗(全局单一入口,天然“持久一致”)。若考虑影响面,也可保留现状仅复用面板组件。 + +4. 弹窗打开时先 `ensureConfigLoaded()`,保证展示的是当前用户+仓库配置。 + +--- + +## 8. 涉及文件改动清单(实施时参照) + +| 文件 | 改动 | +|------|------| +| `src/stores/modules/userPreference.ts` | 增加 `currentWarehouseId()`/`currentStorageKey()`;`load` 主 key + 旧 key 回退迁移;`persist/reset` 写新 key;暴露身份变化重载入口 | +| `src/core/printerComponentCore.ts` | 配置化成员 + `applyConfig`;逐组件 excluded;退避/上限/暂停计数;`autoTryConnectOnce`/`healthCheck`;`shouldAutoReconnect`;遍历统一走 `this.ports`;新事件 | +| `src/core/printerRuntime.ts` | 加载/应用配置封装;`autoTryConnectOnce`/`healthCheck` 导出;升级 `ensurePrinterConnectionsForBrowserPrint` 为真实自动尝试 | +| `src/stores/modules/printerComponent.ts` | 移除旧全局 key 逻辑;改为读写 `userPreference` scope `printer.autoReconnect`(含旧 key 迁移);状态加 excluded/attempts/paused;`autoTryForPage`、`updateComponentAutoReconnect`、`ensureConfigLoaded`、visibilitychange 自愈 | +| `src/main.ts` / `src/permission.ts` / `src/stores/modules/user.ts` | 登录/换仓后加载并应用配置;`startConnections` 保留 | +| `src/views/order/waveOrder/component/PrinterComponentConnectionPanel.vue` | 逐组件“自动重连”开关列 + 主开关/高级项 + 状态辅助展示 + 即存即生效 | +| `src/views/order/waveOrder/component/WavePlatformPrintPreviewDialog.vue` | 打开时 `autoTryForPage(requiredComponents)`;`allComponentsConnected` 文案优化 | +| `SandanWaveBatchListPanel.vue` / `GroupWaveBatchListPanel.vue` | `onMounted`/`onActivated` 调 `autoTryForPage`(平台打印相关页签) | +| `orderManagement`:`pendingOrder.vue` / `deliveryOrder.vue` / `exceptionOrder.vue`(及复用 `use-*.ts`) | 同上前置自动尝试;保持弹窗内连接面板不变 | +| `print.ts`(打印下发) | 未连接时按“排除/未排除”给出差异化提示(不改返回结构) | + +> 不改:`printerComponentConnection.ts`、打印协议/载荷、消息处理 handler。 + +--- + +## 9. 分阶段实施计划 + +| 阶段 | 内容 | 验收 | +|------|------|------| +| P0 数据层 | userPreference 仓库维度 + 回退迁移;新 scope 读写 | 旧用户标签顺序升级后仍保留;换仓 key 隔离 | +| P1 引擎 | core 配置化 + 排除集合 + 退避/上限 + one-shot + healthCheck | 单测/手测:断连→退避重连、排除组件不重连、手动重连恢复 | +| P2 运行时/store | runtime/store 封装、旧全局开关迁移、事件、visibilitychange | 登录/换仓自动加载应用配置;切页/回前台自愈 | +| P3 UI | 连接面板逐组件配置 + 高级项 | 开关即存即生效、显示暂停/排除态 | +| P4 页面接入 | 打印弹窗/各打印页 onMounted/onActivated 自动尝试;打印前自愈 + 提示 | 进入页面即自动尝试一次;打印路径未连提示准确 | +| P5 验证 | `npm run type-check` / `npm run build`;真机控件矩阵 | 见 §11 | + +--- + +## 10. 兼容、风险与注意事项 + +- **key 迁移风险**:写路径切到 `user_prefs_{userId}_{warehouseId}`,必须保留旧 key 回退读取 + 一次性迁移,避免升级后丢失已保存的标签顺序等配置;旧 key 不主动删除。 +- **“连接面板关/开”与切页**:面板/弹窗 `destroy-on-close` 只销毁 UI,不触碰单例连接;全流程 audit 确保无意外断连(登出除外)。 +- **keep-alive / LRU**:orderManagement 与 waveOrder 用 KeepAlive+LRU,组件可能被淘汰重建,`onActivated`/`onMounted` 都要兜底自动尝试(节流内置防抖)。 +- **重复 preflight / 端口扫描负担**:自动尝试节流(≥3s)+ 暂停机制,避免控件未安装时对 `ws://127.0.0.1:` 高频重试。 +- **竞态**:沿用 `connectGeneration` 丢弃过期建连结果;`applyConfig` 不改动已 OPEN 连接。 +- **loopback 限制**:HTTP 公网不可连(`accessBlockedHint`)时,自动尝试直接短路并展示既有提示,不做无意义重试。 +- **warehouse 缺失**:登录上下文取不到 `warehouse_id/store_id` 时退化为现状 `user_prefs_{userId}`(单仓部署零影响)。 +- **多实例/多标签**:本方案仍是“每浏览器实例一个 SPA 单例”;不同浏览器标签各自独立连接,符合控件按本机安装的语义。 +- **高级参数**(间隔/上限)默认值保守,避免误配导致刷屏;若 UI 一期不做则用默认值 + 预留字段。 + +--- + +## 11. 测试验证清单(真机/手测) + +1. 登录后:未开控件 → 状态未连接;启动控件后**进入任一打印页**,页面自动尝试成功(需求 1)。 +2. 切换页签(waveOrder↔orderManagement↔其他菜单)往返:已连接组件保持已连接,不需要手动重连(需求 2)。 +3. 打印过程中关闭控件再开启,回前台/回到打印页自动重连成功(需求 2/3)。 +4. 面板开启主开关:断开某组件(杀控件进程)→ 3s 起退避自动重连,控件重启后自动恢复。 +5. 面板关闭某组件“自动重连”(加入排除):该组件断开后不自动尝试/重连,仅手动可连;主开关开启不影响其他组件。 +6. 连续失败达上限后显示“已暂停”,不再高频尝试;手动“重连”立即恢复尝试。 +7. 配置持久化:A 仓库关闭抖音自动重连、B 仓库开启 → 切换用户/仓库后配置各自生效(分用户+仓库)。 +8. 升级兼容:已有标签顺序配置、旧 `printer_component_auto_reconnect` 开关在首次进入后迁移且行为不变。 +9. HTTP(非 HTTPS)环境:仍显示无法连接提示,不产生无意义重试。 +10. 批量打印(平台数据):全部所需组件已连接→正常打印;有组件排除未连→报“已排除需手动连接”提示,不改打印流程返回结构。 + +--- + +## 12. 待确认问题(评审时定) + +1. 需求 3“哪些组件是失败尝试 / 排除自动重连”是否即“**逐组件开关(默认全开,关闭=排除)**”这一实现口径?是否需要三态(自动重连 / 仅失败尝试一次 / 排除)? +2. “分用户和仓库”是否意味着**所有**用户偏好(含标签顺序/字段排序)都要升级为分仓库,还是仅本打印配置分仓库(本文推荐后者 + userPreference 预留仓库维度)? +3. 仓库上下文是否会在一次登录内动态切换(changeRole 换仓)?若是,身份变化重载触发点需确认到具体入口。 +4. 是否本期就把“打印组件连接”入口收敛为全局单例弹窗(含页面顶部入口),还是维持现状仅共享面板组件? +5. 高级参数(重连间隔/连续失败上限/页面进入自动尝试)是否需要 UI 暴露,还是先用默认值。 +6. 连接状态变化是否需要全局轻提示(如右上角角标/Toast),避免用户在非打印页感知不到控件离线。 diff --git a/docs/打印组件连接-登录一次连接与失败重连方案.md b/docs/打印组件连接-登录一次连接与失败重连方案.md new file mode 100644 index 00000000..cd81e899 --- /dev/null +++ b/docs/打印组件连接-登录一次连接与失败重连方案.md @@ -0,0 +1,314 @@ +# 打印组件连接:登录一次连接与失败自动重连方案 + +- 状态:**已实现(2026-09-04 落地,审计修订 v1.1,取代 `docs/打印组件连接-持久化与自动重连方案.md`)** +- 日期:2026-09-04 +- 范围:`order/waveOrder` 及 `order/orderManagement`(pendingOrder / deliveryOrder / exceptionOrder)等提供「批量打印(平台数据)」的页面所用的**打印组件连接链路** +- 原则:**不改动打印协议与载荷**(`print.ts` 的 payload / 组件消息协议保持现状),只优化「连接生命周期、失败重连、配置持久化」三部分 +- 关联正式方案:`docs/用户偏好配置-浏览器本地保存方案.md`(v1.1,配置持久化的唯一依据,本文在此之上扩展“仓库”维度) + +> **落地范围**(2026-09-04):`userPreference.ts`(仓库维度+旧 key 迁移)、`printerComponentCore.ts`(有界退避重连/排除/暂停/applyConfig)、`printerComponent.ts`(scope `printer.autoReconnect`+旧全局开关迁移)、`permission.ts`/`user.ts`(登录一次连接前先加载配置、changeRole 重载)、`PrinterComponentConnectionPanel.vue`(逐组件“自动重连”开关与状态提示)、`print.ts`(失败提示区分,不改发送/返回结构)。已通过 `npm run type-check` 与 `npm run build`。 + +--- + +## 0. 核心模型(用户口径,审计后收敛) + +> **一次连接**:登录成功后**只自动发起一次**连接;连上后**一直复用**,切任何页面都不断连;**任何打印页 / 打印动作都不再触发新的建连**,打印仅通过既有长连接发送,未连接则明确提示。 + +**不变式(实现必须守住)** +1. **建连自动入口(低频率、有界)**:登录成功后自动连接一次;**页面刷新也会各触发一次**——整页刷新(F5 / 顶部刷新)走登录守卫 getInfo 路径并由 `main.ts` 兜底一次,页签软刷新(经 `/redirect` 回到目标页)触发一次 `retryConnectionsOnce`。登录 / 刷新产生的“这一次连接”**对所有组件各尝试一次(不看逐组件“自动重连”开关/排除名单)**,与“失败自动重连”主开关无关;保留已连接、不无限重试。 +2. **断连唯一入口**:登出 / resetToken。路由切换、页面/弹窗 `onBeforeUnmount`、`destroy-on-close` 一律**不得**关闭 WebSocket。 +3. **发送唯一路径**:复用已 OPEN 的 socket;未 OPEN → 直接给出明确失败提示(含处置建议),**不新建、不静默重试**。 +4. **自动重连唯一触发(失败后)**:由“连接建立失败 / 连接断开”事件驱动(失败驱动的自愈);仅当 **“失败自动重连”主开关开启 + 该组件“自动重连”开启(未排除)+ 当前未连接** 时才会退避重试,带次数上限与暂停;与页面/路由/标签可见性**无关**。 +5. **手动重连**:连接面板“重连 / 全部重连”始终可用、不受排除限制。 + +**明确不做的(与 v1.0 草案的差异,逐条删除)** +- ❌ 页面 `onMounted / onActivated` 进入自动尝试 +- ❌ 打开打印弹窗(`WavePlatformPrintPreviewDialog`)时自动尝试 +- ❌ `document.visibilitychange` 回前台健康检查 +- ❌ 打印下发前自动尝试(`ensurePrinterConnectionsForBrowserPrint` 保持“不实际建连”) +- ❌ 配置字段 `autoTryOnPageEntry` + +> 例外(用户明确要求保留):**“页面刷新”是一次有界的主动触发**——整页刷新或页签软刷新后执行**一次**重连(`reconnectOnceAll`,对**所有组件**各尝试一次、保留已连接),与逐组件“自动重连”开关无关;不构成“每次进打印页都重连”。 + +> 之所以删掉这些:它们会造成“每进一个打印页/每打一次都重复尝试建连”,正是要减少的**无效连接请求**。一次连接 + 失败自愈已覆盖“登录后自动连、连上一直用”的全部诉求。 + +--- + +## 1. 背景与目标 + +“批量打印(平台数据)”会把面单通过**浏览器 WebSocket 直发本机打印组件**(抖音 / 拼多多 / 快手 / 京东 / 菜鸟 / 视频号 / 小红书 / LODOP 等 8 个本地控件)。按用户口径拆解为三条: + +| # | 需求(用户原话口径) | 实现策略 | +|---|------|----------| +| 1 | 登录成功后自动发起**一次**连接 | 保留并强化现有“登录一次性连接”;连接前先加载“用户+仓库”配置;对所有组件各尝试一次(排除名单仅约束“失败后的自动重连”) | +| 2 | 连接成功后**一直使用**;访问其他页面**不断连**;打印**无需多次重连** | 复用模块级单例长连接;固化“登出是唯一断连点”;打印路径只复用不建连 | +| 3 | 增强**失败自动重连**:可设置哪些组件“失败尝试 / 排除自动重连”,配置**分用户 + 分仓库持久化**(与表格字段排序等用户偏好同模式) | 主开关 + 逐组件参与开关(排除名单)+ 退避/上限/暂停;存入 `userPreference`(分用户+仓库 key) | + +> 仓库(warehouse)维度取自当前登录上下文 `userStore.user?.warehouse_id ?? userStore.user?.store_id`(代码中已有同类取值先例)。不同仓库常用平台/安装的控件不同,因此“哪些组件参与失败自动重连”按 **用户 + 仓库** 分别记忆;对本仓不用的组件做“排除”后,不会再对其进行失败后的持续重试,从而减少无效重试请求(登录/刷新仍会对它一次性尝试)。 + +--- + +## 2. 现状梳理与审计结论(代码事实) + +| 文件 | 角色 | 审计结论 | +|------|------|----------| +| `src/core/printerComponentCore.ts` | 连接引擎(模块级单例) | WebSocket 长连接 map 已存在;`autoReconnectEnabled` 全局布尔默认 `false`;失败重连**固定 3000ms、无限重试、无退避/无上限/无按组件排除**(→ 无效连接请求的源头之一);`connectGeneration` 已防竞态 | +| `src/core/printerRuntime.ts` | 生命周期门面 | `startPrinterComponentConnections()`:`connectionsStarted` 置位,**会话内一次**(→ 满足“登录一次”);`ensurePrinterConnectionsForBrowserPrint()`:目前只置位、**不实际建连**(→ 保持,勿“升级”成自动尝试);`stopPrinterComponentConnections()`:登出断开(唯一断连点) | +| `src/core/printerComponentCore.ts` → 打印发送 | `sendPayloadToComponentWs` / `sendWavePlatformBrowserPrint` / `queryComponentPrinterList` | **只复用已 OPEN socket**,未 OPEN 直接报错提示(→ 打印本就不建连,符合“一次连接”,无需改协议) | +| `src/stores/modules/printerComponent.ts` | 状态 Pinia store | 全局布尔 key `printer_component_auto_reconnect`(**不分用户/仓库**);`setAutoReconnect(true)` 会立即对所有未连组件再试一次 | +| `src/stores/modules/userPreference.ts` | 用户偏好 store | key=`user_prefs_{userId}`,**仅 user 维度,无仓库维度**;`load()` 挂在 permission 守卫 getInfo 成功后 | +| `src/stores/modules/user.ts` / `src/permission.ts` | 登录/登出接入 | login / getInfo 成功后 `startConnections()`;logout / resetToken 时 `stopConnections()`(→ 登录一次连接已具备) | +| 各打印页/弹窗 | 入口 | `WavePlatformPrintPreviewDialog` 打开时仅 `refreshFromRuntime()`,**不建连**(正确);各面板含内嵌连接对话框;页面在 `keep-alive`(LRU)内,但**均无 unmount 断连逻辑**(→ 切页本就不应断连) | + +**审计结论(为什么现在用户感觉“要反复重连/无效请求多”)** +1. 登录那次尝试若失败(控件后启动 / 中途重启),因默认关闭失败自动重连,之后**再无任何自动尝试** → 用户到打印页只能手动重连 → 表现为“要重新连接”。 +2. 一旦开启“失败自动重连”,未安装的控件端口会**每 3s 无限重试**;登录与开关键又会对**全部 8 个组件**无差别尝试 → “无效连接请求”多。 +3. 切换页面本身**不会**断连(单例 + 无 unmount 关闭);用户体感来自“断了没自愈 + 开关/排除无法按用户/仓库记忆”。 + +→ 据此:**不多加触发入口**,而是把登录那“一次连接”做可靠、把失败自愈做“有界 + 按组件可配 + 按用户/仓库持久化”,并让打印路径永远“只复用、不建连”。 + +--- + +## 3. 方案总览 + +```mermaid +flowchart LR + subgraph 登录[登录成功 getInfo 后] + L[加载 用户+仓库 配置
排除名单 excluded] + C[自动连接一次
所有组件各尝试一次
跳过已连接] + end + + subgraph 使用期[会话内长期复用] + S[(任意页面)打印/查打印机
只复用已 OPEN socket
不新建连接] + K[切页面 / 关弹窗
不断连] + end + + subgraph 失败自愈[失败驱动 自动重连] + F[连接失败/断开] + R[仅对 参与组件
退避重连 · 次数上限 · 暂停] + M[手动 重连/全部重连
不受排除限制] + end + + L --> C -->|成功 OPEN| S + S --> K + C -->|失败| F + F -->|enabled && !excluded| R + R -->|控件恢复| S + F -->|excluded| X[置未连接
等待手动] + X --> M + R -->|连续失败达上限| P[暂停
等待手动/重新启用] + P --> M + M --> S + M --> C +``` + +--- + +## 4. 数据与存储设计(分用户 + 分仓库) + +### 4.1 身份与 key(userPreference 层扩展) + +沿用 `userPreference` store(与标签/字段排序等用户偏好**同源同模式**),引入**仓库维度**,并向后兼容迁移: + +```ts +// 稳定取当前仓库标识(与订单页“仓库 ID 优先取行、其次登录上下文”一致) +function currentWarehouseId(): string { + const userStore = useUserStore() + const user = userStore.user || {} + const wh = user.warehouse_id ?? user.store_id + return wh != null && wh !== '' ? String(wh) : '' +} + +// 有仓库上下文:用户+仓库;否则退化为现状 user_prefs_{userId} +function currentStorageKey(): string { + const wh = currentWarehouseId() + return wh ? `user_prefs_${currentUserId()}_${wh}` : `user_prefs_${currentUserId()}` +} +``` + +- **load()**:先读 `user_prefs_{userId}_{warehouseId}`(新主 key);无则回退读旧 key `user_prefs_{userId}`,读到后**一次性迁移**写回新 key(仅当有仓库上下文时)。 +- **set / reset / persist**:一律写新 key;旧 key 不主动删(保守,避免回滚丢配置)。 +- 无仓库上下文的部署 key 不变,完全向后兼容;已有标签顺序等旧配置通过回退迁移无缝保留。 +- **身份变化重载**:`changeRole` 成功(可能换仓)后若 `warehouse_id` 变化需重新 `load()`。 +- localStorage 满/禁用仍沿用 try/catch 降级内存态。 + +### 4.2 新 scope 与配置结构 + +scope 沿用 `<模块>.<能力>.<页面标识>` 规范,注册: + +``` +printer.autoReconnect +``` + +```ts +interface PrinterAutoReconnectConfig { + /** 主开关:是否开启“失败自动重连”(连接建立失败/断开后对参与组件自动重试) */ + enabled: boolean + /** 排除“失败自动重连”的组件名单(= 逐组件“自动重连”开关关闭者);只影响失败后的自动重试,不影响登录/刷新对所有组件的一次尝试 */ + excluded: string[] + /** 基础重连间隔 ms,默认 3000 */ + intervalMs: number + /** 退避上限 ms,默认 30000(可选字段,UI 可不暴露) */ + maxIntervalMs: number + /** 连续失败达到该次数后暂停自动重连,默认 5(0=不限;可选字段) */ + maxConsecutiveFailures: number + updated_at: number +} +``` + +> 术语对齐:**“失败自动重连”触发条件**=“失败自动重连”主开关 `enabled=true` **且** 该组件“自动重连”开启(不在 `excluded`)**且** 当前未连接时,断线后才会退避重试;**排除自动重连**=组件在 `excluded` 名单内,断开后不做持续自动重试(仍会在登录/刷新的一次性连接中被尝试,也可手动“重连”)。**默认全关**:`enabled=false`(主开关关);`excluded` = 全部组件(各组件“自动重连”默认关闭)。 + +### 4.3 旧全局开关迁移 + +- `printerComponent` store 启动读取时:若 `printer.autoReconnect` 尚无配置,则把旧 key `printer_component_auto_reconnect`(浏览器全局布尔)迁移为 `enabled` 后写入新 scope;此后不再读写旧 key。 + +--- + +## 5. 引擎设计(`src/core/printerComponentCore.ts`) + +保留现有 `connectGeneration` 防竞态,改造如下: + +1. **配置化** + - 新增成员:`excluded: Set`、`intervalMs/maxIntervalMs/maxConsecutiveFailures`、`attempts: Map`、`paused: Map`。 + - `applyConfig(cfg)`:合并配置,**不关闭已 OPEN socket**;仅影响“失败后的自动重连”(参与范围与节奏)。 + - `shouldAutoReconnect(name) = enabled && !excluded.has(name)`(失败自动重连判定)。 + - 修正 `initAll / reconnectAll / disconnectAll` 遍历 `this.ports`(而非模块常量 `DEFAULT_PRINTER_COMPONENTS`)。 + +2. **登录 / 整页刷新“一次连接”(对全部组件)** + - `initAll()`:对**所有**注册组件各尝试一次(跳过已 OPEN/CONNECTING),不看逐组件“自动重连”开关;此后**不再有页面级/事件级自动建连**(页面刷新属例外,见 §0/§6)。 + - 一次连接失败/成功即定格:失败只进入 §5.3 的失败驱动重连(若主开关+组件“自动重连”都开),不会因为页面切换/打印而重试。 + +3. **失败驱动自动重连(需求 3,有界、按组件)** + - `onopen`:重置该组件 `attempts`、清 `paused`。 + - `onclose/onerror`:`_manualClose` 忽略;否则 + - `shouldAutoReconnect(name)` → `scheduleReconnect(name)`; + - 否则仅置 `disconnected`(被排除 / 未开主开关 → 不重试,等手动)。 + - `scheduleReconnect`:指数退避 `min(intervalMs * 2^attempts, maxIntervalMs)`;`attempts` 达 `maxConsecutiveFailures` → **暂停**(清 timer、`paused[name]=true`),不再高频轮询(消除对未安装端口的无限 3s 无效请求);手动重连或主开关重新启用时重置。 + - 主开关由关→开:对“未 OPEN 且参与”组件做**一次性**尝试(等同受限的“全部重连”),随后的节奏交给上表管理——不再无限轮询。 + +4. **手动重连** + - `reconnectComponent(name)` / `reconnectAll()`:不受 `excluded` 限制、重置 `attempts`,是唯一绕过排除的入口(连接面板按钮)。 + +5. **事件补充** + - 在 `printerComponentStatusChange` 外增发 `printerReconnectStateChange`(含 attempts / paused / excluded 信息),供 UI 显示“连续失败 N 次 / 已暂停 / 已排除”。 + +> 边界:不做心跳保活(本地控件长连接本就稳定,断开多为控件进程重启);不断言“回前台自愈”,避免引入页面级重连。 + +--- + +## 6. 运行时与生命周期接入 + +### 6.1 `src/core/printerRuntime.ts` +- `startPrinterComponentConnections()`:登录/整页刷新后调用一次(现状保留),行为 = `initAll()`(对所有组件各尝试一次)。 +- `ensurePrinterConnectionsForBrowserPrint(names?)`:**保持“只置位、不建连”**,不改造成自动尝试(否则打印就会重复建连,违背核心模型)。 +- `stopPrinterComponentConnections()`:登出断开(唯一断连点,文档固化)。 +- 可选清理:导出与 `print.ts` 打印路径无关,无需改动发送侧。 + +### 6.2 会话接入(登录一次连接 = 需求 1) +- `permission.ts` getInfo 成功后顺序调整:先 `useUserPreferenceStore().load()`(含 `printer.autoReconnect` 配置),**再** `usePrinterComponentStore().startConnections()` → 使登录那一次连接已加载“用户+仓库”配置(排除名单仅影响“失败后的自动重连”)。 +- `main.ts` `bindRuntimeEvents()` 保留(事件绑定 + 读一次旧开关做迁移)。 +- `user.ts` `login()` 现有 `startConnections()` 保留(幂等,配合 permission 守卫一起确保“登录/整页刷新都只连一次”);`changeRole()` 成功后重载偏好并 `applyConfig`(换仓配置切换,不断开已连 socket)。 + +### 6.3 打印路径(需求 2:只复用、不建连) +- `print.ts`:**不改**发送逻辑(`sendPayloadToComponentWs` / `sendWavePlatformBrowserPrint` 已做到“未 OPEN 即失败提示、不新建连接”)。 +- 仅在失败文案上可区分两类原因(可选优化,不改返回结构): + - 该组件在 `excluded` 内 → “已设为排除自动重连,请到连接面板手动连接”; + - 未排除但当前未连 → “组件未连接(登录后自动连接或失败自动重连中),请到连接面板查看/手动重连”。 + +### 6.4 页面/弹窗 +- **不新增**任何 onMounted/onActivated/watch/visibilitychange 建连钩子。 +- 各打印页与 `WavePlatformPrintPreviewDialog` 仅展示全局连接状态(store 已共享),打开面板时 `refreshFromRuntime()`(现已是如此)。 +- 固化约定:任何页面/弹窗 `onBeforeUnmount`、`destroy-on-close`、路由离开都不得调用 `disconnectAll / removeComponent / stopConnections`(登出除外)。 + +--- + +## 7. 设置 UI(`PrinterComponentConnectionPanel.vue` 改造) + +在既有 el-form + el-table 内扩展(样式与表格排序保持现有一致): + +1. **主开关区(form)** + - “失败自动重连”主开关 → 存 `printer.autoReconnect.enabled`。 + - 文案:开启后,仅对“自动重连”开启且当前未连接的组件,在断开后按退避自动重试(有限次数,避免无效请求);关闭则断开后不做持续自动重试。 + - 保留“全部重连 / 刷新状态”。 + - 高级项(可折叠,可选一期不做):重连间隔(s)、连续失败上限。 + +2. **组件表格** + - 新增列 **“自动重连”**:逐组件 `el-switch`(关闭 = 加入 `excluded`,即该组件不参与“失败自动重连”),提示:排除仅影响断开后的自动重试;登录 / 刷新的一次连接仍会对它尝试一次,也可手动“重连”。 + - 保留:组件名称、本地端口、连接状态;**连接状态列不显示“已排除”**(排除组件按“未连接”展示,排除状态由“自动重连”开关体现);连续失败暂停时显示辅助标签(如 `已暂停(连续失败 3 次)`)。 + - 逐组件“自动重连”开关不受主开关影响,可随时预先配置(即存即生效)。 + - 修改即存即生效:`store.updateComponentAutoReconnect(name, on)` → 写 scope → `core.applyConfig`;**不断开已连 socket**。 + +3. **入口(可选优化)**:把各页零散连接对话框收敛为 store 单例 `connectionPanelVisible`(全局同一面板),与“一次连接”体验一致;若求稳可保留现状仅共享面板组件。 + +4. 弹窗打开时先 `ensureConfigLoaded()`,保证展示当前“用户+仓库”配置。 + +--- + +## 8. 涉及文件改动清单 + +| 文件 | 改动 | +|------|------| +| `src/stores/modules/userPreference.ts` | 加 `currentWarehouseId()`/`currentStorageKey()`;`load` 主 key + 旧 key 回退迁移;`persist/reset` 写新 key;暴露身份变化重载入口 | +| `src/core/printerComponentCore.ts` | 配置化成员 + `applyConfig`;逐组件 `excluded`;失败重连退避/上限/暂停(有界,非无限 3s);`initAll`/`reconnectOnceAll` 对所有组件各尝试一次(不受排除约束);`reconnectAll/disconnectAll` 收敛到 `this.ports`;`printerReconnectStateChange` 事件 | +| `src/core/printerRuntime.ts` | `startPrinterComponentConnections` 保持一次性;`ensurePrinterConnectionsForBrowserPrint` **保持不建连**;新增 `retryPrintConnectionsOnce()`(刷新一次重连);文档化唯一断连点 | +| `src/stores/modules/printerComponent.ts` | 旧全局 key → 读写 `userPreference` scope `printer.autoReconnect`(含旧 key 迁移);状态加 excluded/attempts/paused;`ensureConfigLoaded/applyConfig/updateComponentAutoReconnect`;`retryConnectionsOnce`(刷新重连);visibilitychange 等页面级触发器**不新增** | +| `src/main.ts` | 整页刷新(F5 / 顶部刷新)后:`router.isReady()` 完成后对已登录用户 `startConnections()` 一次(与主开关无关、幂等兜底) | +| `src/permission.ts` / `src/stores/modules/user.ts` | 调整顺序:先 load 偏好配置再 `startConnections`(登录一次连接对所有组件各尝试一次);`changeRole` 换仓后重载配置;识别 `/redirect` 软刷新 → 回到目标页执行一次重连 | +| `src/views/order/waveOrder/component/PrinterComponentConnectionPanel.vue` | 逐组件“自动重连”开关列 + 主开关/高级项 + 状态辅助(已暂停);连接状态列不展示“已排除”+ 即存即生效 | +| `src/views/order/waveOrder/config/print.ts` | **发送逻辑不改**;仅失败文案区分“已排除/未连接”(可选,不改返回结构) | + +> 不改:`printerComponentConnection.ts`、打印协议/载荷、消息处理 handler、`WavePlatformPrintPreviewDialog` 及 `SandanWaveBatchListPanel/GroupWaveBatchListPanel/orderManagement 各页`(**不加任何自动尝试钩子**)。 + +--- + +## 9. 分阶段实施计划 + +| 阶段 | 内容 | 验收 | +|------|------|------| +| P0 数据层 | userPreference 仓库维度 + 回退迁移;`printer.autoReconnect` scope 读写 | 旧标签顺序升级后保留;换仓 key 隔离 | +| P1 引擎 | core 配置化 + 排除集合 + 有界退避/暂停 + 登录/刷新一次连接对所有组件尝试 | 断连→仅对 主开关开启 + 组件“自动重连”开启 的未连接组件有界重连;无无限轮询 | +| P2 运行时/store | 迁移旧全局开关、`ensureConfigLoaded/applyConfig`、事件 | 登录/换仓自动加载应用;行为与页面/路由无关 | +| P3 UI | 连接面板逐组件配置 + 高级项 | 开关即存即生效、显示已暂停/已排除 | +| P4 回归 | 登录只连一次;多打印页复用不重连;登出唯一断连 | 见 §11 | +| P5 验证 | `npm run type-check` / `npm run build`;真机控件矩阵 | 见 §11 | + +--- + +## 10. 兼容、风险与注意事项 + +- **登录后仍保持“会话内一次”**:连接在登录/刷新后只触发一次;失败是否继续由“失败自动重连”决定,与切页/打印无关。 +- **key 迁移**:写路径切到 `user_prefs_{userId}_{warehouseId}`,必须保留旧 key 回退读取 + 一次性迁移;旧 key 不删。 +- **无效连接请求收敛点**:① 登录/刷新的一次性连接对每个组件只尝试一次、不重复;② 失败自动重连有退避 + 次数上限 + 暂停,且可逐组件排除(对本仓不用的控件不做失败后的持续重试),杜绝未安装端口的无限 3s 轮询;③ 打印路径永远不建连。 +- **默认全关**:主开关“失败自动重连”默认关;各组件“自动重连”也默认关(`excluded` = 全部组件);两者都开启后才会有失败后的自动重试 + 有界重连,不会造成风暴。 +- **连接面板/弹窗生命周期**:`destroy-on-close` 只销毁 UI;全流程 audit 无意外断连(登出除外)。 +- **竞态**:沿用 `connectGeneration`;`applyConfig` 不动已 OPEN socket。 +- **loopback 限制**:HTTP 公网不可连时(`accessBlockedHint`)登录自动连接直接短路并展示既有提示,不做无意义重试。 +- **warehouse 缺失**:取不到 `warehouse_id/store_id` 时退化为 `user_prefs_{userId}`(单仓部署零影响)。 +- **多标签页**:每个浏览器标签独立 SPA 单例,各自登录时连接一次,符合控件按本机安装语义。 + +--- + +## 11. 测试验证清单(真机/手测) + +1. 登录成功 → **只发起一次连接**(Network/日志可见仅一次 ws 握手);成功组件显示已连接。 +2. 已连接后遍历各打印页(waveOrder ↔ orderManagement ↔ 其他菜单)往返:状态保持已连接,**无任何新建 ws**。 +3. 在任一打印页点击批量打印(平台数据):直接发送成功,日志中**无 init/preflight 建连动作**。 +4. 控件未启动时登录:该组件未连接;启动控件后打开连接面板点击“重连”成功;此后打印复用该连接。 +5. 开启主开关 + 某组件未安装(端口不通):按退避重试,连续失败达上限后**暂停**(不再每 3s 请求)。 +6. 关闭某组件“自动重连”(排除):登录/刷新仍会对它一次性尝试;断开后不做持续自动重试;手动“重连”仍可连;**连接状态列不显示“已排除”**。 +7. 已连接状态下登出再登录:旧连接关闭、新会话登录后自动连接一次。 +8. **页面刷新重连(与主开关、逐组件“自动重连”开关均无关)**:a) F5 / 顶部刷新整页重载后,对所有组件自动重连一次;b) 页签“刷新”(经 /redirect 软刷新)后回到目标页也对所有组件重连一次(保留已连接)。 +9. 配置持久化:A 仓库排除抖音、B 仓库不排除 → 换用户/仓库后各自生效(分用户+仓库)。 +10. 升级兼容:旧标签顺序、旧 `printer_component_auto_reconnect` 首次进入后迁移且行为不变。 +11. HTTP(非 HTTPS)环境:仅提示无法连接,无无效重试。 + +--- + +## 12. 待确认问题(评审时定) + +1. 需求 3 口径:逐组件开关两态(**默认关**;开启 = 参与“失败自动重连”)+ 主开关“失败自动重连”(默认关)即可,还是需要三态(持续自动重连 / 仅失败尝试一次 / 排除)?当前方案按**两态、默认全关**设计。 +2. “分用户和仓库”仅用于本打印配置,还是要推广到全部用户偏好(标签顺序/字段排序)?当前方案:仅打印配置分仓库 + userPreference 预留仓库维度。 +3. 登录“一次连接”的范围:全部未排除组件,还是可进一步限定为该仓库常用平台组件(若有仓库→组件映射可再减少无效请求)? +4. 失败自动重连主开关默认值:保持默认关,还是默认开? +5. “打印组件连接”入口是否本期收敛为全局单例弹窗(含页面顶部入口),还是维持现状仅共享面板组件? +6. 高级参数(重连间隔 / 连续失败上限)是否本期在 UI 暴露,还是先走默认值。 diff --git a/src/api/order/packing/index.ts b/src/api/order/packing/index.ts index cfb083df..99151217 100644 --- a/src/api/order/packing/index.ts +++ b/src/api/order/packing/index.ts @@ -43,7 +43,24 @@ export type PackingListSort = { sortOrder?: 'ASC' | 'DESC' | 'asc' | 'desc' } -/** 打包任务列表项 */ +/** 打包任务录像项 */ +export type PackingVideoItem = { + id?: number + video_url?: string + status?: string + [key: string]: any +} + +/** 打包任务运单关联项 */ +export type PackingExpressItem = { + id?: number + express_id?: number + waybill_code?: string + logistics_name?: string + [key: string]: any +} + +/** 打包任务列表项 / 详情对象(get/list 同构,字段以最新接口为准) */ export type PackingTaskItem = { id?: number order_id?: number | string @@ -52,13 +69,39 @@ export type PackingTaskItem = { wave_id?: number | string wave_no?: string waybill_code?: string + /** 打包数量 */ pack_quantity?: number + /** 商品数量 */ + item_quantity?: number + /** SKU 数 */ + sku_count?: number + /** 打包模式:1=散单 2=团购 */ pack_mode?: number | string + /** 任务状态:0=待处理 1=打包中 2=已完成 3=异常 */ status?: number | string start_time?: string end_time?: string + /** 打包员(展示文本) */ + operator_text?: string + /** 关联设备ID列表 */ + device_ids?: number[] + remark?: string + /** 扩展元信息 */ + meta?: Record | null create_time?: string update_time?: string + /** 工作台名称(关联展示) */ + workbench_name?: string + /** 工作台类型 */ + workbench_type?: string + /** 是否含录像 */ + has_video?: boolean | number + /** 录像是否可用 */ + video_enable?: boolean | number + /** 录像列表 */ + videos?: PackingVideoItem[] + /** 关联运单列表 */ + expresses?: PackingExpressItem[] [key: string]: any } diff --git a/src/api/stock.report/stock.report.ts b/src/api/stock.report/stock.report.ts index 93ab4ffc..b6e8d43c 100644 --- a/src/api/stock.report/stock.report.ts +++ b/src/api/stock.report/stock.report.ts @@ -35,15 +35,27 @@ export interface StockReportSearchBody { where?: { start_time?: string | Date end_time?: string | Date + /** 货主ID数组(仓库侧 search/export:store_ids;空或未传=不过滤) */ store_ids?: number[] + /** 是否按库位返回,默认 false */ by_space?: boolean + /** 仓库ID数组(货主侧 searchStore/exportStore;最新接口为数组写法) */ + warehouse_ids?: number[] + /** 旧单值写法兼容(货主侧已改为 warehouse_ids,不再推荐使用) */ warehouse_id?: number | string + /** 商品关键字:SKU ID/item_code/item_name/goods_code/barcode 模糊匹配 */ keyword?: string + /** 商品库存ID:单数兼容数组(数组=精确 in 匹配),与 stock_ids 二选一、与 keyword 互斥 */ + stock_id?: number | number[] + /** 商品库存ID数组,精确 in 匹配 */ + stock_ids?: number[] } sort?: { - sortField?: 'begin_total' | 'inbound_total' | 'outbound_total' | 'end_total' + /** 白名单:stock_id、item_code、item_name、begin_total、inbound_total、outbound_total、end_total */ + sortField?: 'stock_id' | 'item_code' | 'item_name' | 'begin_total' | 'inbound_total' | 'outbound_total' | 'end_total' sortOrder?: 'ASC' | 'DESC' | 'asc' | 'desc' } + /** 分页参数(最新接口支持服务端分页;未传默认 page=1、pageSize=20) */ pagination?: { page?: number pageSize?: number diff --git a/src/api/storage.entry/entry.ts b/src/api/storage.entry/entry.ts index 426e8f41..27c35ff0 100644 --- a/src/api/storage.entry/entry.ts +++ b/src/api/storage.entry/entry.ts @@ -379,6 +379,8 @@ export function addItem(data: AddItemParams): Promise { export type EntryCommitParams = { /** 入库单 ID */ entry_order_id: number + /** 是否跳过入库完成通知:0 通知(默认),1 不通知 */ + noNeedNotice?: number } export type EntryCommitResponse = { @@ -439,6 +441,8 @@ export function removeItem(data: RemoveItemParams): Promise export type QuickInboundParams = { /** 入库单ID */ id: number + /** 是否跳过入库完成通知:0 通知(默认),1 不通知 */ + noNeedNotice?: number } export type QuickInboundResponse = { diff --git a/src/api/workbench/workbench.ts b/src/api/workbench/workbench.ts index 0dc21e18..eaa74a72 100644 --- a/src/api/workbench/workbench.ts +++ b/src/api/workbench/workbench.ts @@ -2,11 +2,36 @@ import request from '@/utils/request' const v = '1.0' -/** 查询工作台列表(仓库隔离,支持分页与关键词筛选) */ +/** 工作台对象(最新接口:条码 barcode 字段已下线,列表/详情/信息接口均不再返回) */ +export interface WorkbenchItem { + /** 工作台ID */ + id: number + /** 仓库ID */ + warehouse_id: number + /** 工作台名称 */ + name: string + /** 状态:0-禁用 1-启用 */ + status?: number + /** 工作台类型:personal-个人工作台 group-团体工作台 */ + type?: string + /** 备注 */ + remark?: string + /** 绑定设备ID列表(摄像头等) */ + device_ids?: number[] | null + /** 登录码(list 返回;getWorkbenchInfo 不返回 token/login_code) */ + login_code?: string + /** 创建时间 */ + created_at?: string + /** 更新时间 */ + updated_at?: string + [key: string]: unknown +} + +/** 查询工作台列表(仓库隔离,支持分页与关键词筛选;条码 barcode 字段已下线,不再参与筛选) */ export function list(data?: { pagination?: { page?: number; pageSize?: number } - where?: { name?: string; barcode?: string; status?: number } -}) { + where?: { name?: string; status?: number } +}): Promise { return request({ url: '/system', method: 'post', @@ -35,13 +60,12 @@ export function detail(data: { id: number }) { } as any) } -/** 新增工作台(仓库隔离,条码仓库内唯一);创建时自动生成 login_code(前缀 wblc + 随机段共 64 位),不接受外部传入 login_code;响应 data 为新建的工作台对象(含自动生成的 login_code) */ +/** 新增工作台(仓库隔离);创建时自动生成 login_code(前缀 wblc + 随机段共 64 位),不接受外部传入 login_code;条码 barcode 字段已下线,不再接收;响应 data 为新建的工作台对象(含自动生成的 login_code) */ export function create(data: { name: string - barcode?: string status?: number remark?: string -}) { +}): Promise { return request({ url: '/system', method: 'post', @@ -55,14 +79,13 @@ export function create(data: { } as any) } -/** 更新工作台信息(仓库隔离) */ +/** 更新工作台信息(仓库隔离);条码 barcode 字段已下线,传入不予受理 */ export function update(data: { id: number name?: string - barcode?: string status?: number remark?: string -}) { +}): Promise { return request({ url: '/system', method: 'post', @@ -221,11 +244,11 @@ export function bind(data: { } as any) } -/** 使用 token 获取工作台信息(免登录、免鉴权):先查缓存 workbench:token:{token},未命中则按 token 查库并回填缓存后返回;token 不存在或无对应工作台返回失败(flag=failure、code=403);返回不含 token/login_code */ +/** 使用 token 获取工作台信息(免登录、免鉴权):先查缓存 workbench:token:{token},未命中则按 token 查库并回填缓存后返回;返回不含 token/login_code;条码 barcode 字段已下线;token 不存在或无对应工作台返回失败(flag=failure、code=403) */ export function getWorkbenchInfo(data: { /** 工作台 token(64 位) */ token: string -}) { +}): Promise { return request({ url: '/system', method: 'post', diff --git a/src/components/QR/QrCodeDisplay.vue b/src/components/QR/QrCodeDisplay.vue new file mode 100644 index 00000000..717ea69b --- /dev/null +++ b/src/components/QR/QrCodeDisplay.vue @@ -0,0 +1,78 @@ + + + + + diff --git a/src/core/printerComponentCore.ts b/src/core/printerComponentCore.ts index bbf4e173..baa87969 100644 --- a/src/core/printerComponentCore.ts +++ b/src/core/printerComponentCore.ts @@ -17,6 +17,20 @@ export type PrinterComponentStatusItem = { status: PrinterComponentStatus } +/** 失败自动重连配置(分用户+仓库持久化后由 store 下发) */ +export interface PrinterReconnectConfig { + /** 主开关:是否开启失败自动重连 */ + enabled?: boolean + /** 排除自动尝试/自动重连的组件名(仅可手动重连) */ + excluded?: string[] + /** 基础重连间隔(ms),默认 3000 */ + intervalMs?: number + /** 退避上限(ms),默认 30000 */ + maxIntervalMs?: number + /** 连续失败达到该次数后暂停自动重连,默认 5(0=不限) */ + maxConsecutiveFailures?: number +} + type PrinterWebSocket = WebSocket & { _manualClose?: boolean } @@ -51,8 +65,19 @@ export class PrinterComponentCore extends SimpleEmitter { private status = new Map() private reconnectTimers = new Map>() private connectGeneration = new Map() - private reconnectInterval = 3000 private autoReconnectEnabled = false + /** 排除自动尝试/自动重连的组件名(仅可手动重连) */ + private excludedComponents = new Set() + /** 失败自动重连基础间隔(ms) */ + private reconnectIntervalMs = 3000 + /** 失败自动重连退避上限(ms) */ + private maxReconnectIntervalMs = 30000 + /** 连续失败达到该次数后暂停(0=不限) */ + private maxConsecutiveFailures = 5 + /** 各组件连续失败次数(每成功一次/手动重连重置) */ + private attempts = new Map() + /** 各组件是否已暂停自动重连(连续失败达上限) */ + private paused = new Map() constructor(components: PrinterComponentPort[] = DEFAULT_PRINTER_COMPONENTS) { super() @@ -70,7 +95,11 @@ export class PrinterComponentCore extends SimpleEmitter { this.emit('loopbackAccessBlocked', { reason: 'insecure_context' }) return } - DEFAULT_PRINTER_COMPONENTS.forEach((item) => { + // 登录 / 整页刷新后的“一次连接”:对所有组件各尝试一次(保留已连接)。 + // 逐组件“自动重连”开关(excluded)只影响“失败后的自动重连”,不影响这里的一次性连接。 + this.forEachPort((item) => { + const existing = this.components.get(item.name) + if (existing?.readyState === WebSocket.OPEN || existing?.readyState === WebSocket.CONNECTING) return this.initComponent(item.name) }) } @@ -134,12 +163,15 @@ export class PrinterComponentCore extends SimpleEmitter { private attachWebSocket(name: string, ws: PrinterWebSocket, connect: () => void): void { ws.onopen = () => { + this.attempts.set(name, 0) + this.paused.delete(name) this.updateStatus(name, 'connected') + this.emitReconnectState(name) } ws.onclose = () => { this.updateStatus(name, 'disconnected') - if (!ws._manualClose && this.autoReconnectEnabled) { + if (!ws._manualClose && this.shouldAutoReconnect(name)) { this.scheduleReconnect(name, connect) } } @@ -156,7 +188,7 @@ export class PrinterComponentCore extends SimpleEmitter { ws.onerror = () => { this.updateStatus(name, 'disconnected') - if (!ws._manualClose && this.autoReconnectEnabled) { + if (!ws._manualClose && this.shouldAutoReconnect(name)) { this.scheduleReconnect(name, connect) } } @@ -165,15 +197,31 @@ export class PrinterComponentCore extends SimpleEmitter { } private scheduleReconnect(name: string, connectFn: () => void): void { - if (!this.autoReconnectEnabled) return + if (!this.shouldAutoReconnect(name)) return if (this.reconnectTimers.has(name)) return + if (this.paused.get(name)) return + + const attempts = this.attempts.get(name) ?? 0 + if (this.maxConsecutiveFailures > 0 && attempts >= this.maxConsecutiveFailures) { + // 连续失败达上限:暂停自动重连,避免对未安装控件高频无效请求(等待手动重连/重新启用) + this.paused.set(name, true) + this.emitReconnectState(name) + return + } + + this.attempts.set(name, attempts + 1) + const delay = Math.min( + this.reconnectIntervalMs * Math.pow(2, attempts), + this.maxReconnectIntervalMs + ) this.reconnectTimers.set( name, setTimeout(() => { - connectFn() this.reconnectTimers.delete(name) - }, this.reconnectInterval) + connectFn() + }, delay) ) + this.emitReconnectState(name) } addComponent(name: string, wsInstance: PrinterWebSocket): void { @@ -289,36 +337,146 @@ export class PrinterComponentCore extends SimpleEmitter { } setAutoReconnectEnabled(enabled: boolean): void { - if (this.autoReconnectEnabled === enabled) return - this.autoReconnectEnabled = enabled - if (!enabled) { - this.clearAllReconnectTimers() - } else { - DEFAULT_PRINTER_COMPONENTS.forEach((item) => { - if (this.status.get(item.name) !== 'connected') { - this.initComponent(item.name) + this.applyConfig({ enabled }) + } + + /** 组件是否被排除自动尝试/自动重连(仅可手动重连) */ + isComponentExcluded(name: string): boolean { + return this.excludedComponents.has(name) + } + + /** 当前排除名单(供 store/UI) */ + getExcludedNames(): string[] { + return Array.from(this.excludedComponents) + } + + /** 是否参与失败自动重连(未排除) */ + participatesAutoReconnect(name: string): boolean { + return !this.isComponentExcluded(name) + } + + /** 失败自动重连判定:主开关开 且 未排除 */ + shouldAutoReconnect(name: string): boolean { + return this.autoReconnectEnabled && !this.isComponentExcluded(name) + } + + /** + * 应用(用户+仓库)重连配置:不关闭已 OPEN socket,只影响失败重连的参与范围与节奏。 + * 注意:此处不做自动尝试——登录“一次连接”由 initAll 触发;开启后的即时尝试由 retryParticipatingOnce 显式触发。 + */ + applyConfig(cfg: PrinterReconnectConfig): void { + const prevEnabled = this.autoReconnectEnabled + + if (cfg.enabled !== undefined) this.autoReconnectEnabled = cfg.enabled + if (typeof cfg.intervalMs === 'number' && Number.isFinite(cfg.intervalMs) && cfg.intervalMs > 0) { + this.reconnectIntervalMs = cfg.intervalMs + } + if (typeof cfg.maxIntervalMs === 'number' && Number.isFinite(cfg.maxIntervalMs) && cfg.maxIntervalMs > 0) { + this.maxReconnectIntervalMs = cfg.maxIntervalMs + } + if ( + typeof cfg.maxConsecutiveFailures === 'number' && + Number.isInteger(cfg.maxConsecutiveFailures) && + cfg.maxConsecutiveFailures >= 0 + ) { + this.maxConsecutiveFailures = cfg.maxConsecutiveFailures + } + if (cfg.excluded !== undefined) { + const next = new Set(cfg.excluded) + // 新增排除:清掉其挂起重连计时与失败计数 + next.forEach((name) => { + if (!this.excludedComponents.has(name)) { + const timer = this.reconnectTimers.get(name) + if (timer) { + clearTimeout(timer) + this.reconnectTimers.delete(name) + } + this.attempts.delete(name) + this.paused.delete(name) } }) + // 移出排除:重置计数,允许其后续重新参与自动尝试 + this.excludedComponents.forEach((name) => { + if (!next.has(name)) { + this.attempts.delete(name) + this.paused.delete(name) + } + }) + this.excludedComponents = next } - this.emit('autoReconnectChange', { enabled }) + + if (this.autoReconnectEnabled && !prevEnabled) { + // 由关→开:重置失败计数,重新开始有界自动重连 + this.attempts.clear() + this.paused.clear() + } + if (!this.autoReconnectEnabled) { + this.clearAllReconnectTimers() + } + + this.emit('autoReconnectChange', { enabled: this.autoReconnectEnabled }) + } + + /** + * 对“参与自动重连且当前未连接/未暂停/无挂起重连”的组件做一次性尝试。 + * 用于:用户开启失败自动重连、组件从排除中恢复、换仓配置变更后。 + */ + retryParticipatingOnce(): void { + if (!this.autoReconnectEnabled) return + this.forEachPort((item) => { + const name = item.name + if (this.isComponentExcluded(name)) return + if (this.paused.get(name)) return + if (this.reconnectTimers.has(name)) return + const existing = this.components.get(name) + if (existing?.readyState === WebSocket.OPEN || existing?.readyState === WebSocket.CONNECTING) return + this.initComponent(name) + }) } reconnectComponent(name: string): void { + // 手动重连不受排除限制,并重置失败计数/暂停 + this.attempts.delete(name) + this.paused.delete(name) this.initComponent(name) } reconnectAll(): void { - DEFAULT_PRINTER_COMPONENTS.forEach((item) => { + // 手动“全部重连”:不受排除限制 + this.forEachPort((item) => { + this.attempts.delete(item.name) + this.paused.delete(item.name) this.initComponent(item.name) }) } + /** + * 页面刷新后的“一次重连”:对**所有**组件(不看逐组件“自动重连”开关/排除名单)重置失败计数并各尝试一次(保留已连接)。 + * 与“失败自动重连”主开关无关;排除名单只约束“失败后的自动重连”。已挂起的退避计时会先清除,避免重复链。 + */ + reconnectOnceAll(): void { + this.forEachPort((item) => { + const name = item.name + const timer = this.reconnectTimers.get(name) + if (timer) { + clearTimeout(timer) + this.reconnectTimers.delete(name) + } + this.attempts.delete(name) + this.paused.delete(name) + const existing = this.components.get(name) + if (existing?.readyState === WebSocket.OPEN || existing?.readyState === WebSocket.CONNECTING) return + this.initComponent(name) + }) + } + disconnectAll(): void { this.clearAllReconnectTimers() - DEFAULT_PRINTER_COMPONENTS.forEach((item) => { - const generation = (this.connectGeneration.get(item.name) ?? 0) + 1 - this.connectGeneration.set(item.name, generation) - const ws = this.components.get(item.name) + this.forEachPort((item) => { + const name = item.name + const generation = (this.connectGeneration.get(name) ?? 0) + 1 + this.connectGeneration.set(name, generation) + const ws = this.components.get(name) if (ws) { ws._manualClose = true try { @@ -326,12 +484,36 @@ export class PrinterComponentCore extends SimpleEmitter { } catch { // ignore } - this.components.delete(item.name) + this.components.delete(name) } - this.updateStatus(item.name, 'disconnected') + this.attempts.delete(name) + this.paused.delete(name) + this.updateStatus(name, 'disconnected') }) } + private forEachPort(fn: (item: PrinterComponentPort) => void): void { + this.ports.forEach((port, name) => fn({ name, port })) + } + + private emitReconnectState(name: string): void { + this.emit('printerReconnectStateChange', { + name, + attempts: this.attempts.get(name) ?? 0, + paused: this.paused.get(name) ?? false, + excluded: this.isComponentExcluded(name) + }) + } + + /** 各组件重连状态快照(供 UI/面板刷新) */ + getReconnectState(): Record { + const out: Record = {} + this.ports.forEach((_port, name) => { + out[name] = { attempts: this.attempts.get(name) ?? 0, paused: this.paused.get(name) ?? false } + }) + return out + } + private clearAllReconnectTimers(): void { this.reconnectTimers.forEach((timer) => clearTimeout(timer)) this.reconnectTimers.clear() diff --git a/src/core/printerRuntime.ts b/src/core/printerRuntime.ts index e11e31ad..d464b88e 100644 --- a/src/core/printerRuntime.ts +++ b/src/core/printerRuntime.ts @@ -42,7 +42,10 @@ export function initPrinterRuntime(): void { printerComponentMessageHandler.init() } -/** 登录成功后调用,与各本地打印组件建立 WebSocket 长连接 */ +/** + * 登录成功后 / 整页刷新(F5、顶部刷新)后调用:与各本地打印组件建立 WebSocket 长连接一次。 + * 该“一次自动连接”与“失败自动重连”主开关无关(主开关只控制断线后的持续重试)。 + */ export function startPrinterComponentConnections(): void { if (!initialized || connectionsStarted) return if (!getToken()) return @@ -69,3 +72,17 @@ export function stopPrinterComponentConnections(): void { connectionsStarted = false printerComponents.disconnectAll() } + +/** + * 页面刷新后的“一次重连”:未排除且未连接才尝试、保留已连接,与“失败自动重连”主开关无关。 + * - 软刷新(页签经 /redirect 中转,会话内已连过也可再发起一次)由 permission 守卫调用; + * - 整页刷新(F5 / 顶部刷新)主要由登录守卫 startPrinterComponentConnections 触发,main.ts 再兜底一次(幂等)。 + */ +export function retryPrintConnectionsOnce(): void { + if (!initialized) return + if (!getToken()) return + if (typeof WebSocket === 'undefined') return + + connectionsStarted = true + printerComponents.reconnectOnceAll() +} diff --git a/src/main.ts b/src/main.ts index e7ffafa4..388ad1ac 100644 --- a/src/main.ts +++ b/src/main.ts @@ -11,6 +11,7 @@ import SvgIcon from '@/components/SvgIcon/index.vue' import i18n, { loadServerMessages } from '@/lang/index' import '@/styles/index.scss' // global css +import { getToken } from '@/utils/auth' import { initPrinterRuntime } from '@/core/printerRuntime' import { usePrinterComponentStore } from '@/stores/modules/printerComponent' @@ -46,3 +47,14 @@ initPrinterRuntime() usePrinterComponentStore(pinia).bindRuntimeEvents() app.mount('#app') + +// 整页刷新(F5 / 顶部刷新)后的“一次自动连接”兜底: +// 等路由守卫初始化(getInfo)完成、拿到登录上下文后再执行一次; +// 与“失败自动重连”主开关无关(主开关只控制断线后的持续重试)。 +// 若守卫已发起连接,runtime 内 connectionsStarted 幂等跳过,不会重复建连。 +if (getToken()) { + router.isReady().then(() => { + if (!getToken()) return + usePrinterComponentStore(pinia).startConnections() + }) +} diff --git a/src/permission.ts b/src/permission.ts index 4f4fce5d..69aca2d2 100644 --- a/src/permission.ts +++ b/src/permission.ts @@ -51,11 +51,25 @@ function resolveRouteDocumentTitle(route: typeof router.currentRoute.value) { const whiteList = ['/login','/redirect','/admin/land'] // no redirect whitelist +/** 登录后“一次连接”:先加载用户偏好(含打印组件分用户+仓库配置),再自动连接一次 */ function ensurePrinterConnectionsAfterLogin() { if (!getToken()) return + const prefs = useUserPreferenceStore() + if (!prefs.isLoaded) prefs.load() usePrinterComponentStore().startConnections() } +/** 页签“刷新”经 /redirect 软刷新(非整页重载),标记为回到目标页后执行一次打印组件重连 */ +let pendingRefreshReconnect = false + +/** 软刷新回到目标路由后:执行一次打印组件重连(登录守卫路径外的补充触发点) */ +function maybeRetryPrintConnectionsAfterRefresh() { + if (!pendingRefreshReconnect) return + pendingRefreshReconnect = false + if (!getToken()) return + usePrinterComponentStore().retryConnectionsOnce() +} + router.beforeEach(async (to, from) => { NProgress.start() // console.log("路由表",router.getRoutes()); @@ -68,20 +82,26 @@ router.beforeEach(async (to, from) => { NProgress.done() return { path: '/' } } else { + // 页签“刷新”:先经 /redirect 中转(软刷新),回到目标页后执行一次打印组件重连 + if (to.path.startsWith('/redirect')) { + pendingRefreshReconnect = true + } const userStore = useUserStore() const hasGetUserInfo = userStore.user && userStore.user.employees_name if (hasGetUserInfo) { ensurePrinterConnectionsAfterLogin() + maybeRetryPrintConnectionsAfterRefresh() return true } else { try { // get user info const user = await userStore.getInfo() - ensurePrinterConnectionsAfterLogin() - // 加载用户偏好配置(浏览器本地保存:登录 + 整页刷新均在此触发) + // 加载用户偏好配置(浏览器本地保存:登录 + 整页刷新均在此触发),再触发登录后自动连接(按用户+仓库配置执行一次) useUserPreferenceStore().load() + ensurePrinterConnectionsAfterLogin() + maybeRetryPrintConnectionsAfterRefresh() const permissionStore = usePermissionStore() // generate accessible routes based on menus diff --git a/src/stores/modules/printerComponent.ts b/src/stores/modules/printerComponent.ts index f5b188f4..50e06739 100644 --- a/src/stores/modules/printerComponent.ts +++ b/src/stores/modules/printerComponent.ts @@ -1,45 +1,97 @@ import { defineStore } from 'pinia' +import { useUserPreferenceStore } from './userPreference' import { getLoopbackPrinterAccessHint, printerComponents, + retryPrintConnectionsOnce, startPrinterComponentConnections, stopPrinterComponentConnections } from '@/core/printerRuntime' import type { PrinterComponentPort, PrinterComponentStatus, - PrinterComponentStatusItem + PrinterComponentStatusItem, + PrinterReconnectConfig } from '@/core/printerComponentCore' -const AUTO_RECONNECT_STORAGE_KEY = 'printer_component_auto_reconnect' +/** userPreference scope:失败自动重连配置(分用户+仓库持久化) */ +export const PRINTER_AUTO_RECONNECT_SCOPE = 'printer.autoReconnect' -function readAutoReconnectFromStorage(): boolean { +/** 旧全局开关 key(浏览器级,仅迁移用) */ +const LEGACY_AUTO_RECONNECT_KEY = 'printer_component_auto_reconnect' + +/** 归一化后的完整配置 */ +export interface PrinterAutoReconnectConfig extends PrinterReconnectConfig { + enabled: boolean + excluded: string[] + intervalMs: number + maxIntervalMs: number + maxConsecutiveFailures: number +} + +const DEFAULT_RECONNECT_CONFIG: PrinterAutoReconnectConfig = { + enabled: false, + excluded: [], + intervalMs: 3000, + maxIntervalMs: 30000, + maxConsecutiveFailures: 5 +} + +/** 旧全局布尔 → 迁移(无记录返回 null) */ +function readLegacyAutoReconnect(): boolean | null { try { - const raw = localStorage.getItem(AUTO_RECONNECT_STORAGE_KEY) + const raw = localStorage.getItem(LEGACY_AUTO_RECONNECT_KEY) if (raw === '0' || raw === 'false') return false if (raw === '1' || raw === 'true') return true } catch { // ignore } - return false + return null } -function writeAutoReconnectToStorage(enabled: boolean): void { - try { - localStorage.setItem(AUTO_RECONNECT_STORAGE_KEY, enabled ? '1' : '0') - } catch { - // ignore +/** + * 归一化配置:合并默认值,容错非法字段。 + * 未存有 excluded(或配置不存在)时,按“组件‘自动重连’默认关闭”处理 → excluded = fallbackExcluded(全部组件)。 + */ +function normalizeConfig(raw: unknown, fallbackExcluded: string[]): PrinterAutoReconnectConfig { + const src = (raw && typeof raw === 'object' ? raw : {}) as Record + const cfg: PrinterAutoReconnectConfig = { ...DEFAULT_RECONNECT_CONFIG, excluded: [] } + if (src.enabled === true) cfg.enabled = true + if (Array.isArray(src.excluded)) { + cfg.excluded = src.excluded.filter((x): x is string => typeof x === 'string' && x !== '') + } else { + // 默认:全部组件都不参与“失败自动重连”(各组件“自动重连”开关默认关闭) + cfg.excluded = [...fallbackExcluded] } + const toNum = (v: unknown, fb: number) => { + const n = Number(v) + return Number.isFinite(n) ? n : fb + } + cfg.intervalMs = toNum(src.intervalMs, DEFAULT_RECONNECT_CONFIG.intervalMs) + cfg.maxIntervalMs = toNum(src.maxIntervalMs, DEFAULT_RECONNECT_CONFIG.maxIntervalMs) + const maxF = Number(src.maxConsecutiveFailures) + cfg.maxConsecutiveFailures = + Number.isInteger(maxF) && maxF >= 0 ? maxF : DEFAULT_RECONNECT_CONFIG.maxConsecutiveFailures + return cfg } export type PrinterComponentRow = PrinterComponentPort & { status: PrinterComponentStatus + /** 是否参与失败自动重连(= 未排除) */ + autoReconnect: boolean + excluded: boolean + paused: boolean + attempts: number } interface PrinterComponentState { statusList: PrinterComponentStatusItem[] components: PrinterComponentPort[] autoReconnectEnabled: boolean + /** 排除自动尝试/自动重连的组件名单 */ + excludedComponents: string[] + /** 各组件重连状态(连续失败次数 / 是否暂停),供 UI 展示 */ + reconnectState: Record /** 公网 HTTP 等场景下无法连接本机组件时的提示 */ accessBlockedHint: string | null } @@ -48,7 +100,9 @@ export const usePrinterComponentStore = defineStore('printerComponent', { state: (): PrinterComponentState => ({ statusList: printerComponents.getAllStatus(), components: printerComponents.getAllPorts(), - autoReconnectEnabled: readAutoReconnectFromStorage(), + autoReconnectEnabled: printerComponents.getAutoReconnectEnabled(), + excludedComponents: printerComponents.getExcludedNames(), + reconnectState: printerComponents.getReconnectState(), accessBlockedHint: getLoopbackPrinterAccessHint() }), getters: { @@ -64,10 +118,19 @@ export const usePrinterComponentStore = defineStore('printerComponent', { const item = state.statusList.find((s) => s.name === name) return item?.status === 'connected' }, + isComponentExcluded: + (state) => + (name: string): boolean => { + return state.excludedComponents.includes(name) + }, componentRows(state): PrinterComponentRow[] { return state.components.map((item) => ({ ...item, - status: state.statusList.find((s) => s.name === item.name)?.status ?? 'disconnected' + status: state.statusList.find((s) => s.name === item.name)?.status ?? 'disconnected', + excluded: state.excludedComponents.includes(item.name), + autoReconnect: !state.excludedComponents.includes(item.name), + paused: state.reconnectState[item.name]?.paused ?? false, + attempts: state.reconnectState[item.name]?.attempts ?? 0 })) }, connectedCount(state): number { @@ -78,11 +141,11 @@ export const usePrinterComponentStore = defineStore('printerComponent', { } }, actions: { + /** + * 绑定运行时事件(main 启动时调用一次)。 + * 注意:不在此时应用重连配置——配置需登录后按“用户+仓库”读取(见 ensureConfigLoaded)。 + */ bindRuntimeEvents() { - const saved = readAutoReconnectFromStorage() - printerComponents.setAutoReconnectEnabled(saved) - this.autoReconnectEnabled = saved - printerComponents.on('printerComponentStatusChange', (payload) => { const data = payload as { name: string; status: PrinterComponentStatus } const idx = this.statusList.findIndex((s) => s.name === data.name) @@ -98,34 +161,144 @@ export const usePrinterComponentStore = defineStore('printerComponent', { this.autoReconnectEnabled = data.enabled }) + printerComponents.on('printerReconnectStateChange', (payload) => { + const data = payload as { name: string; attempts: number; paused: boolean } + this.reconnectState[data.name] = { attempts: data.attempts, paused: data.paused } + }) + printerComponents.on('loopbackAccessBlocked', () => { this.accessBlockedHint = getLoopbackPrinterAccessHint() }) }, + + /** + * 读取 scope 配置(用户偏好未加载则先 load)。缺失时用默认值并迁移旧全局开关,首次写入持久化。 + * 返回归一化后的配置,并已应用(applyConfig)。 + */ + ensureConfigLoaded(): PrinterAutoReconnectConfig { + const prefs = useUserPreferenceStore() + if (!prefs.isLoaded) prefs.load() + + // 默认:主开关“失败自动重连”关;各组件“自动重连”也默认关(excluded = 全部组件,不参与失败自动重连) + const allComponentNames = printerComponents.getAllPorts().map((p) => p.name) + let raw = prefs.get(PRINTER_AUTO_RECONNECT_SCOPE) + let shouldPersist = false + if (!raw) { + const legacy = readLegacyAutoReconnect() + raw = { + ...DEFAULT_RECONNECT_CONFIG, + enabled: legacy === true, + excluded: [...allComponentNames] + } + if (legacy !== null) { + shouldPersist = true + } + } + const cfg = normalizeConfig(raw, allComponentNames) + if (shouldPersist) { + this.saveConfig(cfg) + } + this.applyConfig(cfg) + return cfg + }, + + /** 会话/换仓后重新读取并应用配置(登录“一次连接”由 startConnections 触发,此处不自动尝试) */ + loadReconnectConfig() { + this.ensureConfigLoaded() + }, + + /** 持久化到 userPreference(分用户+仓库) */ + saveConfig(cfg: PrinterAutoReconnectConfig) { + useUserPreferenceStore().set(PRINTER_AUTO_RECONNECT_SCOPE, { + enabled: cfg.enabled, + excluded: cfg.excluded, + intervalMs: cfg.intervalMs, + maxIntervalMs: cfg.maxIntervalMs, + maxConsecutiveFailures: cfg.maxConsecutiveFailures + }) + }, + + /** 应用配置到运行时引擎 + 同步 store 镜像 */ + applyConfig(cfg: PrinterAutoReconnectConfig) { + printerComponents.applyConfig({ + enabled: cfg.enabled, + excluded: cfg.excluded, + intervalMs: cfg.intervalMs, + maxIntervalMs: cfg.maxIntervalMs, + maxConsecutiveFailures: cfg.maxConsecutiveFailures + }) + this.autoReconnectEnabled = cfg.enabled + this.excludedComponents = [...cfg.excluded] + }, + refreshFromRuntime() { this.statusList = printerComponents.getAllStatus() this.components = printerComponents.getAllPorts() this.autoReconnectEnabled = printerComponents.getAutoReconnectEnabled() + this.excludedComponents = printerComponents.getExcludedNames() + this.reconnectState = printerComponents.getReconnectState() this.accessBlockedHint = getLoopbackPrinterAccessHint() }, - setAutoReconnect(enabled: boolean) { - writeAutoReconnectToStorage(enabled) - printerComponents.setAutoReconnectEnabled(enabled) - this.autoReconnectEnabled = enabled - }, - reconnectComponent(name: string) { - printerComponents.reconnectComponent(name) - }, - reconnectAll() { - printerComponents.reconnectAll() - }, + + /** + * 登录后 / 整页刷新后自动连接一次(低频率建连入口):先加载配置使排除名单生效。 + * 该“一次连接”与“失败自动重连”主开关无关(主开关仅控制断线后的持续重试);重复调用幂等跳过。 + */ startConnections() { + this.ensureConfigLoaded() startPrinterComponentConnections() this.refreshFromRuntime() }, + stopConnections() { stopPrinterComponentConnections() this.refreshFromRuntime() + }, + + /** 失败自动重连主开关:即存即生效(开启时对参与组件做一次性尝试) */ + setAutoReconnect(enabled: boolean) { + const cfg = this.ensureConfigLoaded() + cfg.enabled = enabled + this.saveConfig(cfg) + this.applyConfig(cfg) + if (enabled) { + printerComponents.retryParticipatingOnce() + } + this.refreshFromRuntime() + }, + + /** 逐组件“自动重连”开关:关闭=不参与“失败自动重连”(登录/刷新的一次连接仍会尝试它,也可手动重连),即存即生效 */ + updateComponentAutoReconnect(name: string, autoReconnect: boolean) { + const cfg = this.ensureConfigLoaded() + if (autoReconnect) { + cfg.excluded = cfg.excluded.filter((x) => x !== name) + } else if (!cfg.excluded.includes(name)) { + cfg.excluded = [...cfg.excluded, name] + } + this.saveConfig(cfg) + this.applyConfig(cfg) + // 移出排除后,若主开关开启则允许其重新参与自动尝试 + if (autoReconnect) { + printerComponents.retryParticipatingOnce() + } + this.refreshFromRuntime() + }, + + reconnectComponent(name: string) { + printerComponents.reconnectComponent(name) + this.refreshFromRuntime() + }, + + reconnectAll() { + printerComponents.reconnectAll() + this.refreshFromRuntime() + }, + + /** 页面刷新后的一次重连(软刷新经 /redirect 触发;整页刷新由登录守卫 getInfo 路径触发) */ + retryConnectionsOnce() { + this.ensureConfigLoaded() + retryPrintConnectionsOnce() + this.refreshFromRuntime() } } }) diff --git a/src/stores/modules/user.ts b/src/stores/modules/user.ts index eed307f7..b9deffd5 100644 --- a/src/stores/modules/user.ts +++ b/src/stores/modules/user.ts @@ -45,7 +45,7 @@ export const useUserStore = defineStore('user', { const data = resp.data this.token = data.token setToken(data.token) - usePrinterComponentStore().startConnections() + // 打印组件连接在路由守卫 getInfo 成功后统一触发一次(此时才可按“用户+仓库”配置决定尝试哪些组件) return true }, @@ -85,6 +85,11 @@ export const useUserStore = defineStore('user', { // Reset tags view after role change await tagsViewStore.delAllViews() + + // 切换角色/仓库后:重载用户偏好(含仓库维度)并应用打印组件重连配置(连接本身不断,仅配置随身份切换) + const { useUserPreferenceStore } = await import('./userPreference') + useUserPreferenceStore().load() + usePrinterComponentStore().loadReconnectConfig() return resp }, diff --git a/src/stores/modules/userPreference.ts b/src/stores/modules/userPreference.ts index 8f28c080..effceb9e 100644 --- a/src/stores/modules/userPreference.ts +++ b/src/stores/modules/userPreference.ts @@ -4,8 +4,10 @@ import { useUserStore } from './user' /** * 用户偏好配置(纯浏览器本地保存,正式方案) * - * - 存储:localStorage,key = `user_prefs_{userId}`,结构 `{ [scope]: { value, updated_at } }` - * - 按账号(user_id)隔离:key 含 user_id;登出不清除,登录按 user_id 读取 + * - 存储:localStorage,key = `user_prefs_{userId}`(无仓库上下文)或 `user_prefs_{userId}_{warehouseId}`(有仓库上下文) + * - 结构 `{ [scope]: { value, updated_at } }` + * - 按账号(user_id)隔离,并支持按仓库(warehouse_id/store_id)二次隔离(打印组件等“分用户+分仓库”配置用) + * - 登出不清除,登录按 identity 读取;旧 key(仅用户)无数据时回退读取并一次性迁移 * - 设计文档:docs/用户偏好配置-浏览器本地保存方案.md */ interface PreferenceEntry { @@ -34,6 +36,37 @@ function currentUserId(): string { return id != null && id !== '' ? String(id) : 'unknown' } +/** 稳定取当前仓库标识(与订单页“仓库 ID 优先取行、其次登录上下文”一致);无仓库上下文返回 '' */ +function currentWarehouseId(): string { + const userStore = useUserStore() + const user = userStore.user || {} + const wh = user.warehouse_id ?? user.store_id + return wh != null && wh !== '' ? String(wh) : '' +} + +/** 旧(仅用户)key:user_prefs_{userId} */ +function legacyStorageKey(): string { + return STORAGE_PREFIX + currentUserId() +} + +/** 当前 key:有仓库上下文时 user_prefs_{userId}_{warehouseId},否则退化为 user_prefs_{userId} */ +function currentStorageKey(): string { + const wh = currentWarehouseId() + return wh ? `${legacyStorageKey()}_${wh}` : legacyStorageKey() +} + +/** 读某 key 并解析为对象;缺失/非法返回 null */ +function readParsed(key: string): Record | null { + try { + const raw = localStorage.getItem(key) + if (!raw) return null + const parsed = JSON.parse(raw) + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null + } catch { + return null + } +} + export const useUserPreferenceStore = defineStore('userPreference', { state: (): State => ({ map: {}, @@ -42,13 +75,29 @@ export const useUserPreferenceStore = defineStore('userPreference', { }), actions: { - /** 按当前 user_id 从 localStorage 读取全部偏好;无缓存/解析失败置空,不抛异常 */ + /** + * 按当前 identity(user_id + 可选 warehouse_id)从 localStorage 读取全部偏好。 + * 新主 key(含仓库)无数据时回退读取旧 key(仅用户)并一次性迁移写回,保证升级不丢已有配置。 + * 无缓存/解析失败置空,不抛异常。 + */ load() { - const key = STORAGE_PREFIX + currentUserId() + const key = currentStorageKey() + const legacy = legacyStorageKey() try { - const raw = localStorage.getItem(key) - const parsed = raw ? JSON.parse(raw) : {} - this.map = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {} + let parsed = readParsed(key) + if (!parsed && key !== legacy) { + const fromLegacy = readParsed(legacy) + if (fromLegacy) { + parsed = fromLegacy + // 一次性迁移:写回新 key;旧 key 保留(保守,便于回滚) + try { + localStorage.setItem(key, JSON.stringify(fromLegacy)) + } catch { + // 忽略:降级为内存态 + } + } + } + this.map = parsed ?? {} } catch { this.map = {} } @@ -75,9 +124,9 @@ export const useUserPreferenceStore = defineStore('userPreference', { } }, - /** 写入 localStorage;禁用/超限等异常静默降级为内存态,不阻塞页面 */ + /** 写入 localStorage(按当前 identity key);禁用/超限等异常静默降级为内存态,不阻塞页面 */ persist() { - const key = STORAGE_PREFIX + currentUserId() + const key = currentStorageKey() try { localStorage.setItem(key, JSON.stringify(this.map)) } catch { diff --git a/src/views/Externalwarehouse/shipperSigning/index.vue b/src/views/Externalwarehouse/shipperSigning/index.vue index 20c96c9c..44bcb558 100644 --- a/src/views/Externalwarehouse/shipperSigning/index.vue +++ b/src/views/Externalwarehouse/shipperSigning/index.vue @@ -140,7 +140,7 @@ import { ref, reactive, onMounted } from 'vue' import { ElMessage } from 'element-plus' import { Search, Refresh } from '@element-plus/icons-vue' -import { storeWarehouseWarehouseList } from '@/api/storeWarehouse.warehouse/storeWarehouse' +import { storeWarehouseWarehouseList } from '@/api/storewarehouse.warehouse/storeWarehouse' import ScanBox from '@/components/ScanBox/index.vue' import UpperTable from '@/components/UpperTable/index.vue' diff --git a/src/views/data/packingflow/index.vue b/src/views/data/packingflow/index.vue index cc846ebe..8b8e4068 100644 --- a/src/views/data/packingflow/index.vue +++ b/src/views/data/packingflow/index.vue @@ -51,14 +51,14 @@ {{ row.id ?? '—' }}