diff --git a/docs/自定义过滤条件-设计与实施.md b/docs/自定义过滤条件-设计与实施.md new file mode 100644 index 00000000..9af20a89 --- /dev/null +++ b/docs/自定义过滤条件-设计与实施.md @@ -0,0 +1,216 @@ +# 自定义过滤条件:设计与实施 + +- 日期:2026-11-09 +- 状态:**已实现(P1–P3)** +- 定位:给 ScanBox「过滤」页签增加**用户自定义条件**,与后端下发的系统预设并存 +- 相关文档:`docs/设置中心-设计与实施.md`、`docs/统一配置文件-tbyc-config.md`、`docs/用户偏好配置-浏览器本地保存方案.md` + +--- + +## 1. 目标 + +| 目标 | 说明 | +|---|---| +| 任意列表页可自定义常用过滤条件 | 不依赖后端新增配置 | +| 一键使用 | 点「过滤」页签里的条目即查询,与系统预设体验一致 | +| 可管理 | 「设置 → 筛选与查询 → 自定义过滤条件」查看 / 新增 / 编辑 / 启停 / 排序 / 复制 / 删除 / 恢复默认 | +| 可备份 | 随 `tbyc-config.json` 导入导出 | +| 本地优先 | 条件只存本机浏览器,按账号隔离,不经过服务端 | + +非目标:跨设备同步(需后端接口)、OR / 嵌套条件组、按角色差异化。 + +--- + +## 2. 数据分层 + +``` +第 1 层:系统预设(只读) + 后端 index.fastWhereTree(type) → presetTree prop → 「系统」分组 +第 2 层:我的预设(本地,可增删改) + user_prefs_{userId} → scope "scanFilterPresets" +第 3 层:导出文件 + tbyc-config.json → sections.scanFilterPresets(只导出第 2 层) +第 4 层:页面元数据(本机,不导出) + localStorage "scan_box_pages_{userId}"(页面 → 可筛选字段快照) +``` + +--- + +## 3. 存储与作用域 + +| 数据 | 位置 | 作用域 | 是否导出 | +|---|---|---|---| +| 自定义条件 | `user_prefs_{userId}` → scope `scanFilterPresets` | 账号(`setGlobal`,不分仓库/角色) | ✅ | +| 页面元数据(可筛选字段) | `localStorage.scan_box_pages_{userId}` | 账号 + 本机 | ❌ | + +- `scanFilterPresets` 已加入 `USER_GLOBAL_SCOPES`(`src/stores/modules/userPreference.ts`), + 避免仓库级 key 迁移时产生副本。 +- 读取/写入统一走 `useUserPreferenceStore().getGlobal / setGlobal`,localStorage 不可用时静默降级。 + +### 文档结构 + +```jsonc +// user_prefs_{userId} → "scanFilterPresets".value +{ + "version": 1, + "presets": [ + { + "id": "sp_1760000000000_ab12", + "pageKey": "stock-management-warehouse", // ScanBox cache-key + "name": "零库存商品", + "enabled": true, + "order": 0, + "conditions": { + "quantity": { "operator": "le", "value": 0, "type": "number" }, + "is_images": { "operator": "eq", "value": "N", "type": "boolean" } + }, + "createdAt": 1760000000000, + "updatedAt": 1760000000000 + } + ] +} +``` + +**条件必须是扁平结构** `{ 字段: { operator, value, type } }`: + +- 与「筛选」页签的产出一致,页面侧 `buildXxxQuery` / `normalizeToWhere` 不需要区分来源; +- `stock/stock` 的 `buildStockQuery` 只认扁平结构(已顺带兼容 `{ conditions: {...} }` 信封,见 §7)。 + +--- + +## 4. 页面标识与页面登记 + +### 4.1 pageKey + +取 `ScanBox` 的 **`cache-key`**(全项目基本都有且唯一),缺省回退 `route.path`。 + +- 同一页面多块 ScanBox(如波次面板、订单管理各页签)天然分开; +- 与 ScanBox 筛选快照的隔离键一致,符合既有习惯。 + +### 4.2 自动登记(设置中心需要“页面 → 字段”映射) + +`ScanBox` 挂载时把 `availableFields` 精简后写入 `scan_box_pages_{userId}`: + +```ts +{ pageKey, title, path, fields: [{ value, label, type, operators, defaultOperator, group, options }], updatedAt } +``` + +- 字段来源是 `props.availableFields`,**跳过 ScanBox 自动合并的时间伪字段**(`autoMergedTimeRange`), + 保留页面原始时间字段(如 `create_at` / `update_at`); +- `select / multiple` 的选项做快照(上限 200 条),供设置中心渲染下拉; + 异步选项(货主、违禁品、库存单位)加载后通过轻量签名 watch 补登记(800ms 防抖); +- 与「所有表格字段」一致:**页面打开一次后才会出现在设置中心**。 + +--- + +## 5. ScanBox 交互 + +| 场景 | 行为 | +|---|---| +| 只有系统条件 | 平铺展示(与改造前一致) | +| 只有自定义条件 | 平铺展示 | +| 两者都有 | 分组:`系统` / `我的`(默认展开) | +| 点击叶子 | `activeCondition = data.value` → `emit('condition-change')`,页面立即查询 | +| 选中后继续追加 | 预设置条件**回填到「筛选」表单**;切到「筛选」可继续增删条件,点「确定」按「预设 + 追加」合并提交 | +| 存为过滤条件 | 底部按钮打开 task-panel 表单弹窗(名称 + 条件预览),保存后立即应用并切到「过滤」页签 | +| 更新预设 | 选中的是**本地自定义条件**时,底部按钮变为「更新过滤条件」:点一下就把当前条件写回该预设并重新查询(系统预设只读,仍为「存为过滤条件」) | +| 筛选页签底部 | 显示「过滤条件:xxx」+「存为过滤条件」;表单无法表达的条件(如预设里的特殊字段)在提交时按基线自动补回 | +| 取消应用 | 过滤面板**底部**显示「已应用:<条件名>」+「取消应用」(与「筛选」底部条同一位置与样式),点一下清除条件并重查(预设本身保留) | +| 搜索 | 仍然按 `label` 过滤;数据变化后自动重放关键字 | +| 停用的条件 | 不进入过滤树(设置里保留) | +| 紧凑模式 | 上一轮修复后,切「过滤」复用同一棵预设树 | +| 存为过滤条件 | 「筛选」页签有值时,底部出现入口:命名 → 保存 → 自动切到「过滤」并应用 | + +系统节点结构保持后端原样(`{ id, label, icon, count, value, children }`); +自定义节点为 `{ id: 'custom:', label: name, value: 扁平conditions }`。 + +> ⚠️ 不要把 `type: 'preset'` 等标记塞进 `value`:`stock/stock` 的 `buildStockQuery` +> 会把未知键当字段。选中态由 el-tree 的 `highlight-current` 维护,无需写进条件。 + +--- + +## 6. 设置中心分区 + +路径:**设置 → 筛选与查询 → 自定义过滤条件**(`components/settings/registry.ts`) + +``` +┌────────────────┬────────────────────────────────────────────┐ +│ 页面(自动登记)│ 页面标题 / pageKey [恢复默认] │ +│ ▸ 商品明细 3 │ ┌ 零库存商品 [开关] ↑ ↓ 编辑 复制 删除 │ +│ ▸ 待处理订单 │ │ 库存数量 小于等于 0 且 无图 │ +│ ▸ … │ └ … │ +└────────────────┴────────────────────────────────────────────┘ +``` + +- 保存即时生效(无全局保存/取消),与设置中心其它分区一致; +- 删除 / 恢复默认使用 **task-panel 确认弹窗**(标题 + 说明 + 条件/范围预览 + 警示提示 + 取消/确认),确认按钮按危险等级显示为 `danger`; +- 条件编辑器:字段(按 group 分组、已选字段禁选)→ 操作符(按字段 `operators` / 类型默认)→ 值控件; +- 支持的字段类型:`text / number / select / multiple / boolean / date / daterange / datetimerange`; +- 值控件:文本、数字、数字区间、日期、日期区间、单选、多选、是/否;`isnull / isnotnull` 无需填值; +- 校验:名称(必填 / ≤20 字 / 同页唯一)、至少 1 个条件、必填值、区间上下限; +- `type` 归一:`boolean→boolean`、`number→number`、`date→date`、`daterange→daterange`、其它 → `text` + (避免 `multiple` 被部分页面误判成 `daterange`)。 + +--- + +## 7. 与页面查询的兼容 + +- 自定义条件输出扁平结构,页面原有 `buildXxxQuery` 直接可用; +- `buildStockQuery` 增加兜底:`{ conditions: {...} }` 信封先展开,并跳过 `type` / `preset` 元数据键—— + 顺带修好了「系统过滤条件点了没反应」的隐患; +- 导出:`buildExportPayload()` 使用 `currentConditions`,自定义条件自动带入导出。 + +--- + +## 8. 导入 / 导出(tbyc-config) + +`src/config/tbyc-config-sections.ts` 新增分区: + +| 项 | 值 | +|---|---| +| key | `scanFilterPresets` | +| title | 自定义过滤条件 | +| collect | 有数据时输出 `{ version, presets }` | +| apply | 同 `id` 覆盖;同页面同名覆盖(保留本地 id/顺序);其余追加 | + +导入结果提示形如:`自定义过滤条件 3 项`。未知分区仍只忽略并提示。 + +--- + +## 9. 容错与边界 + +| 场景 | 处理 | +|---|---| +| 页面从未打开 | 设置中心提示“打开任意列表页后再回来”,不报错 | +| 字段被删除/改名 | 预设保留;编辑时字段选项不可选,摘要显示原字段名 | +| 下拉选项已变化 | 摘要按保存时的选项快照显示,查询以实际值为准 | +| 名称重复 | 编辑/复制时拦下并提示 | +| localStorage 不可用 | 内存态运行,不阻塞页面 | +| 导入异常数据 | `normalizePresetsDoc` 丢弃非法项(缺 pageKey/name/conditions 等) | +| 故障修复 | 一并清除自定义条件与页面登记,提示中列出条数 | + +--- + +## 10. 已落地文件 + +| 文件 | 说明 | +|---|---| +| `src/utils/scan-filter-presets.ts` | 类型 / 归一化 / 页面登记 / 摘要 / 校验 | +| `src/stores/modules/scanFilterPresets.ts` | Pinia store(条件 + 页面元数据,ScanBox 与设置共用) | +| `src/components/ScanBox/index.vue` | 过滤树合并、页面登记、「存为过滤条件」 | +| `src/components/settings/sections/FilterPresetsSection.vue` | 设置分区 UI + 条件编辑器 | +| `src/components/settings/registry.ts` | 新增分组「筛选与查询」与分区条目 | +| `src/config/tbyc-config-sections.ts` | 新增 `scanFilterPresets` 分区 | +| `src/stores/modules/userPreference.ts` | `scanFilterPresets` 加入用户级 scope | +| `src/utils/stockQueryBuilder.ts` | 兼容 `{ conditions }` 信封 | +| `src/components/settings/sections/DataSection.vue` | 故障修复一并清理 | + +--- + +## 11. 后续可扩展 + +1. **跨设备同步**:需要后端保存接口,本地结构可直接作为 payload; +2. **内置默认条件**:新增 `src/config/scan-filter-presets.default.ts`,作为只读第三分组「内置」; +3. **OR / 条件组**:`conditions` 升级为 `{ logic: 'and'|'or', groups: [...] }`,读取时做版本迁移; +4. **上次使用高亮**:记录 `pageKey → presetId`,页面重进时恢复高亮(不自动应用); +5. **从 URL 分享条件**:序列化预设为链接参数(注意敏感字段)。 diff --git a/docs/设置中心-设计与实施.md b/docs/设置中心-设计与实施.md index 93ced5f5..f15a2847 100644 --- a/docs/设置中心-设计与实施.md +++ b/docs/设置中心-设计与实施.md @@ -19,23 +19,25 @@ ``` 设置(左导航 + 右内容,1280px) -├─ 表格 +├─ 字段与列 │ ├─ 列表字段 当前表格列显隐 / 顺序 / 固定(由 UpperTable 通过插槽注入) -│ └─ 所有表格字段 跨页面管理全部已登记表格(搜索 / 显隐 / 顺序 / 固定 / 恢复默认) -├─ 显示与交互 +│ ├─ 所有表格字段 跨页面管理全部已登记表格(搜索 / 显隐 / 顺序 / 固定 / 恢复默认) +│ └─ 导出字段 订单管理各页「导出(不含明细)」的导出字段勾选(账号 + 角色) +├─ 系统设置 │ ├─ 界面显示 布局模式 / 固定头部 / 侧栏 Logo / Scan-box / 工具栏 / 快捷键区域 +│ └─ 基础设置 表格工作模式 + 页面缓存 + 标签缓存(原「性能」两项合并) +├─ 设备与打印 │ └─ 设备与打印 打印组件连接状态、失败自动重连、逐组件开关(账号 + 仓库) -├─ 性能 -│ ├─ 表格与性能 表格工作模式(低占用 / 高性能) -│ └─ 页面与标签缓存 页面缓存、tab 缓存(开关 + 上限) -├─ 导航 +├─ 导航与入口 │ ├─ 标签排序 全项目页面标签顺序 + 默认页签 │ └─ 快捷入口 侧边栏收藏的快捷入口集中管理 └─ 数据与维护 - ├─ 导出字段 订单管理各页「导出全部(不含明细)」的导出字段勾选(账号 + 角色) └─ 导入 / 导出与维护 导出/导入 tbyc-config.json、恢复全部默认、故障修复、诊断信息 ``` +分类原则:按**配置对象**分组(字段与列 / 系统设置 / 设备与打印 / 导航 / 数据),不再按“功能模块”拆散。 +单条目且条目名与分组名相同时(如「设备与打印」)左导航省略分组标题,避免重复。 + 作用域提示直接显示在导航项右侧:`当前表格 / 账号 + 角色 / 账号 / 本机`,避免用户误以为会同步到服务端。 --- @@ -49,8 +51,7 @@ components/settings/ sections/ DisplaySection.vue 界面显示(含布局 / 固定头部 / 侧栏 Logo) DeviceSection.vue 设备与打印(复用 PrinterComponentConnectionPanel) - PerformanceSection.vue - CacheSection.vue + BasicSettingsSection.vue 基础设置(表格工作模式 + 页面/标签缓存,resetToDefaults 统一恢复) TabOrderSection.vue → 复用 components/TabOrderPanel.vue ShortcutsSection.vue 快捷入口集中管理 AllTablesSection.vue 所有表格字段(跨页面列配置管理) @@ -129,8 +130,17 @@ DataSection ──▶ TBYC_CONFIG_SECTIONS(fieldColumns / tabOrder / display / | 文件 | 替代 | |---|---| -| `components/UpperTable/MoreSettingsDialog.vue` | 「界面显示」「表格与性能」「页面与标签缓存」分区 | +| `components/UpperTable/MoreSettingsDialog.vue` | 「界面显示」「基础设置」分区 | | `components/TabOrderSettingsDialog.vue` | 「标签排序」分区(`TabOrderPanel`) | +| `sections/PerformanceSection.vue` + `sections/CacheSection.vue` | 合并为 `sections/BasicSettingsSection.vue`(「基础设置」) | + +--- + +## 9. 后续计划(未实现) + +统一「列表字段」入口:像列表页「字段设置」一样,设置中心里点「列表字段」直接打开**目标表格**的字段表单(先选表 / 带入当前表), +届时删除「所有表格字段」这个独立分区(`AllTablesSection.vue`),避免两套列表字段编辑 UI。 +当前保留两者共存,待改造完成后再移除。 --- @@ -139,10 +149,11 @@ DataSection ──▶ TBYC_CONFIG_SECTIONS(fieldColumns / tabOrder / display / 1. 列表页「字段设置」→ 停在「列表字段」,列显隐/排序/固定/恢复默认均正常 2. Navbar「设置」→ 无「列表字段」,默认停在「所有表格字段」 3. 「所有表格字段」:搜索、仅看已自定义、修改后当前页面表格即时刷新、恢复默认生效 -4. 界面显示:布局模式/固定头部/侧栏 Logo/Scan-box/工具栏/快捷键区域 即时生效,刷新后保持 -5. 设备与打印:连接状态、主开关、逐组件开关、全部重连 -6. 快捷入口:列表与侧边栏星标一致,移除/清空生效 -4. 标签排序:只列多标签页面;默认标签展示与保存正常;保存后当前页即时生效 -5. 导出 → 重置 → 导入:字段、标签、显示、缓存、快捷键全部恢复 -6. 故障修复:二次确认后清除并给出恢复项摘要 -7. 诊断信息:账号/角色/仓库、配置版本、占用体积、存储 key 正确 +4. 基础设置:表格工作模式 / 页面缓存 / 标签缓存即时生效,单「恢复默认」一次性回滚三项 +5. 界面显示:布局模式/固定头部/侧栏 Logo/Scan-box/工具栏/快捷键区域 即时生效,刷新后保持 +6. 设备与打印:连接状态、主开关、逐组件开关、全部重连 +7. 快捷入口:列表与侧边栏星标一致,移除/清空生效 +8. 标签排序:只列多标签页面;默认标签展示与保存正常;保存后当前页即时生效 +9. 导出 → 重置 → 导入:字段、标签、显示、缓存、快捷键全部恢复 +10. 故障修复:二次确认后清除并给出恢复项摘要 +11. 诊断信息:账号/角色/仓库、配置版本、占用体积、存储 key 正确 diff --git a/src/components/ScanBox/index.vue b/src/components/ScanBox/index.vue index e84499d5..41b0c56c 100644 --- a/src/components/ScanBox/index.vue +++ b/src/components/ScanBox/index.vue @@ -29,8 +29,8 @@ - -
+ +
@@ -387,6 +387,24 @@
+ +
+
+ 过滤条件: + {{ activePresetName }} +
+ + {{ presetSaveActionLabel }} + +
+
@@ -413,7 +431,7 @@
- + + +
+ + 已应用:{{ appliedPresetLabel }} + + + 取消应用 + +
- -
+ +
+ +
+
+ 过滤条件: + {{ activePresetName }} +
+ + {{ presetSaveActionLabel }} + +
+ + + +
+
+
+

存为过滤条件

+

保存后可在「过滤」页签一键使用,后续可在「设置 → 自定义过滤条件」中修改

+
+ +
+ +
+
+
+ 名称 +
+ + + + + +
+
+ +
+ 条件预览 + + {{ savePresetSummary || '—' }} + +
+
+ +

+ 条件与当前「筛选」保持一致;保存后会立即应用并切到「过滤」页签。 +

+
+ +
+ 名称最多 20 个字,同页面不可重名 +
+ 取消 + 保存 +
+
+
+
diff --git a/src/components/settings/sections/DataSection.vue b/src/components/settings/sections/DataSection.vue index 14fb4519..a8f11277 100644 --- a/src/components/settings/sections/DataSection.vue +++ b/src/components/settings/sections/DataSection.vue @@ -94,6 +94,8 @@ import { isTbycConfig } from '@/utils/tbyc-config' import { TBYC_CONFIG_SECTIONS, getTbycConfigSection } from '@/config/tbyc-config-sections' +import { useScanFilterPresetsStore } from '@/stores/modules/scanFilterPresets' +import { clearScanBoxPages } from '@/utils/scan-filter-presets' defineOptions({ name: 'SettingsDataSection' }) @@ -311,7 +313,7 @@ async function handleResetAll() { async function handleRepair() { try { await ElMessageBox.confirm( - '故障修复会清除当前电脑中此账号的全部字段配置、标签排序、显示设置、表格与缓存设置及快捷键,并恢复所有默认配置。是否继续?', + '故障修复会清除当前电脑中此账号的全部字段配置、标签排序、显示设置、表格与缓存设置、自定义过滤条件及快捷键,并恢复所有默认配置。是否继续?', '确认故障修复', { type: 'warning', buttonSize: 'small', confirmButtonText: '确认清除', cancelButtonText: '取消' } ) @@ -352,6 +354,13 @@ async function handleRepair() { const hadTabOrder = !!preferenceStore.getGlobal(TAB_ORDER_SCOPE) if (hadTabOrder) preferenceStore.resetGlobal(TAB_ORDER_SCOPE) + // 6. 自定义过滤条件(用户级)+ 页面字段登记(本机元数据) + const filterPresetStore = useScanFilterPresetsStore() + filterPresetStore.ensureLoaded() + const presetCount = filterPresetStore.presets.length + if (presetCount) filterPresetStore.clearAll() + clearScanBoxPages() + emit('columns-changed') const parts: string[] = [] @@ -360,6 +369,7 @@ async function handleRepair() { if (hadExperimental) parts.push('表格与缓存') if (hadShortcuts) parts.push('快捷键') if (hadTabOrder) parts.push('标签排序') + if (presetCount > 0) parts.push(`${presetCount} 条自定义过滤条件`) ElMessage.success(`故障修复完成${parts.length ? ',已恢复 ' + parts.join('、') : ''}`) } diff --git a/src/components/settings/sections/FilterPresetsSection.vue b/src/components/settings/sections/FilterPresetsSection.vue new file mode 100644 index 00000000..7111f2f2 --- /dev/null +++ b/src/components/settings/sections/FilterPresetsSection.vue @@ -0,0 +1,1397 @@ + + + + + + + + diff --git a/src/components/settings/sections/PerformanceSection.vue b/src/components/settings/sections/PerformanceSection.vue deleted file mode 100644 index b40f73f9..00000000 --- a/src/components/settings/sections/PerformanceSection.vue +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - diff --git a/src/components/settings/sections/shared.scss b/src/components/settings/sections/shared.scss index f2a6713e..20cd2e6c 100644 --- a/src/components/settings/sections/shared.scss +++ b/src/components/settings/sections/shared.scss @@ -78,6 +78,14 @@ padding-left: 2px; } +.block-desc { + margin-top: 2px; + font-size: 12px; + line-height: 18px; + color: #909399; + padding-left: 2px; +} + .block-desc { margin: 4px 0 8px; padding-left: 2px; diff --git a/src/config/tbyc-config-sections.ts b/src/config/tbyc-config-sections.ts index cffc30a8..679cb3d0 100644 --- a/src/config/tbyc-config-sections.ts +++ b/src/config/tbyc-config-sections.ts @@ -12,6 +12,7 @@ import { useSettingsStore } from '@/stores/modules/settings' import { useShortcutsStore } from '@/stores/modules/shortcuts' import { useExperimentalStore } from '@/stores/modules/experimental' import { useUserPreferenceStore } from '@/stores/modules/userPreference' +import { useScanFilterPresetsStore } from '@/stores/modules/scanFilterPresets' import { PRINTER_AUTO_RECONNECT_SCOPE } from '@/stores/modules/printerComponent' import { getTabOrderPageKeys } from '@/config/tab-order-registry' import { ORDER_INDEX_EXPORT_SCOPES } from '@/views/order/shared/orderListExport' @@ -348,6 +349,23 @@ const orderExportColumnsSection: TbycConfigSection = { } } +/** ============ 分区 8:自定义过滤条件(ScanBox「过滤」页签) ============ */ +const scanFilterPresetsSection: TbycConfigSection = { + key: 'scanFilterPresets', + title: '自定义过滤条件', + collect: () => { + const store = useScanFilterPresetsStore() + store.ensureLoaded() + return store.presets.length ? { version: 1, presets: store.presets } : undefined + }, + apply: (data) => { + if (!data || typeof data !== 'object') return 0 + const store = useScanFilterPresetsStore() + store.ensureLoaded() + return store.importPresets(data) + } +} + export const TBYC_CONFIG_SECTIONS: TbycConfigSection[] = [ fieldColumnsSection, tabOrderSection, @@ -355,7 +373,8 @@ export const TBYC_CONFIG_SECTIONS: TbycConfigSection[] = [ experimentalSection, printerSection, shortcutsSection, - orderExportColumnsSection + orderExportColumnsSection, + scanFilterPresetsSection ] /** 按 key 取分区 */ diff --git a/src/stores/modules/scanFilterPresets.ts b/src/stores/modules/scanFilterPresets.ts new file mode 100644 index 00000000..fef95788 --- /dev/null +++ b/src/stores/modules/scanFilterPresets.ts @@ -0,0 +1,252 @@ +/** + * 自定义过滤条件 store + * + * - 预设条件:本地(userPreference 用户级 scope `scanFilterPresets`),按账号隔离 + * - 页面元数据:本地 localStorage(`scan_box_pages_{userId}`),由 ScanBox 自动登记 + * - ScanBox 与设置中心共用此 store,任一处修改都会即时反映到另一方(同一 Pinia 实例) + */ +import { defineStore } from 'pinia' +import { + createPresetId, + normalizeConditions, + normalizePageMeta, + normalizePresetsDoc, + readScanBoxPages, + readScanFilterPresets, + writeScanBoxPages, + writeScanFilterPresets, + type ScanFilterPageMeta, + type ScanFilterPreset +} from '@/utils/scan-filter-presets' + +interface ScanFilterPresetState { + presets: ScanFilterPreset[] + pages: Record + loaded: boolean +} + +/** 页面元数据是否等价(避免每次进入页面都写 localStorage) */ +function isSamePageMeta(a: ScanFilterPageMeta, b: ScanFilterPageMeta): boolean { + return ( + a.title === b.title && + a.path === b.path && + JSON.stringify(a.fields) === JSON.stringify(b.fields) + ) +} + +export const useScanFilterPresetsStore = defineStore('scanFilterPresets', { + state: (): ScanFilterPresetState => ({ + presets: [], + pages: {}, + loaded: false + }), + + getters: { + /** 设置中心左侧页面列表(按页面标题排序) */ + pageList(state): ScanFilterPageMeta[] { + return Object.values(state.pages).sort((a, b) => + a.title.localeCompare(b.title, 'zh-Hans-CN') + ) + } + }, + + actions: { + /** 首次使用 / 登录后加载 */ + ensureLoaded() { + if (this.loaded) return + this.presets = readScanFilterPresets() + const pages = readScanBoxPages() + this.pages = pages.reduce>((acc, page) => { + acc[page.pageKey] = page + return acc + }, {}) + this.loaded = true + }, + + /** 强制从本地重新读取(导入配置后使用) */ + reload() { + this.loaded = false + this.ensureLoaded() + }, + + /** 某页面的预设(按 order 升序) */ + presetsForPage(pageKey: string): ScanFilterPreset[] { + return this.presets + .filter((preset) => preset.pageKey === pageKey) + .sort((a, b) => a.order - b.order) + }, + + persistPresets() { + writeScanFilterPresets(this.presets) + }, + + persistPages() { + writeScanBoxPages(Object.values(this.pages)) + }, + + /** ScanBox 挂载时登记页面与可筛选字段(供设置中心选择页面) */ + registerPage(meta: ScanFilterPageMeta) { + const normalized = normalizePageMeta(meta) + if (!normalized || !normalized.fields.length) return + const existing = this.pages[normalized.pageKey] + if (existing && isSamePageMeta(existing, normalized)) return + this.pages = { + ...this.pages, + [normalized.pageKey]: { ...normalized, updatedAt: Date.now() } + } + this.persistPages() + }, + + /** 新增一条自定义过滤条件 */ + addPreset(input: { + pageKey: string + name: string + conditions: unknown + enabled?: boolean + }): ScanFilterPreset | null { + const conditions = normalizeConditions(input.conditions) + if (!input.pageKey || !Object.keys(conditions).length) return null + const siblings = this.presetsForPage(input.pageKey) + const lastOrder = siblings.length ? (siblings[siblings.length - 1]?.order ?? -1) : -1 + const preset: ScanFilterPreset = { + id: createPresetId(), + pageKey: input.pageKey, + name: String(input.name || '').trim(), + enabled: input.enabled !== false, + order: lastOrder + 1, + conditions, + createdAt: Date.now(), + updatedAt: Date.now() + } + this.presets = [...this.presets, preset] + this.persistPresets() + return preset + }, + + /** 更新名称 / 条件 / 启用状态 */ + updatePreset( + id: string, + patch: Partial> + ): boolean { + const index = this.presets.findIndex((preset) => preset.id === id) + if (index < 0) return false + const current = this.presets[index] + if (!current) return false + const next: ScanFilterPreset = { + ...current, + ...(patch.name !== undefined ? { name: String(patch.name).trim() } : {}), + ...(patch.conditions !== undefined + ? { conditions: normalizeConditions(patch.conditions) } + : {}), + ...(patch.enabled !== undefined ? { enabled: patch.enabled } : {}), + updatedAt: Date.now() + } + this.presets = this.presets.map((preset) => (preset.id === id ? next : preset)) + this.persistPresets() + return true + }, + + removePreset(id: string): boolean { + const next = this.presets.filter((preset) => preset.id !== id) + if (next.length === this.presets.length) return false + this.presets = next + this.persistPresets() + return true + }, + + setEnabled(id: string, enabled: boolean) { + this.updatePreset(id, { enabled }) + }, + + /** 同页内上移 / 下移(direction: -1 上移,1 下移) */ + movePreset(id: string, direction: -1 | 1) { + const target = this.presets.find((preset) => preset.id === id) + if (!target) return + const siblings = this.presetsForPage(target.pageKey) + const index = siblings.findIndex((preset) => preset.id === id) + const swapIndex = index + direction + if (index < 0 || swapIndex < 0 || swapIndex >= siblings.length) return + + const reordered = [...siblings] + const [moved] = reordered.splice(index, 1) + if (!moved) return + reordered.splice(swapIndex, 0, moved) + const orderMap = new Map(reordered.map((preset, idx) => [preset.id, idx])) + this.presets = this.presets.map((preset) => + orderMap.has(preset.id) + ? { ...preset, order: orderMap.get(preset.id) as number } + : preset + ) + this.persistPresets() + }, + + /** 清空某页面的全部自定义条件(恢复默认) */ + clearPage(pageKey: string): number { + const next = this.presets.filter((preset) => preset.pageKey !== pageKey) + const count = this.presets.length - next.length + if (!count) return 0 + this.presets = next + this.persistPresets() + return count + }, + + /** 清空全部自定义条件(故障修复用) */ + clearAll(): number { + const count = this.presets.length + if (!count) return 0 + this.presets = [] + this.persistPresets() + return count + }, + + /** + * 导入预设(tbyc-config): + * - 同 id 覆盖 + * - 同页面同名覆盖(保留本地 id / 顺序) + * - 其余追加 + * 返回应用条数。 + */ + importPresets(raw: unknown): number { + const incoming = normalizePresetsDoc(raw) + if (!incoming.length) return 0 + + let presets = [...this.presets] + let count = 0 + + incoming.forEach((item) => { + const byId = presets.findIndex((preset) => preset.id === item.id) + if (byId >= 0) { + const existing = presets[byId] + if (existing) presets[byId] = { ...item, order: existing.order } + count += 1 + return + } + const byName = presets.findIndex( + (preset) => + preset.pageKey === item.pageKey && + preset.name.trim().toLowerCase() === item.name.trim().toLowerCase() + ) + if (byName >= 0) { + const existing = presets[byName] + if (existing) { + presets[byName] = { + ...existing, + name: item.name, + conditions: item.conditions, + enabled: item.enabled, + updatedAt: Date.now() + } + } + count += 1 + return + } + presets = [...presets, { ...item, id: presets.some((p) => p.id === item.id) ? createPresetId() : item.id }] + count += 1 + }) + + this.presets = presets + this.persistPresets() + return count + } + } +}) diff --git a/src/stores/modules/userPreference.ts b/src/stores/modules/userPreference.ts index 5ca9638e..54952f73 100644 --- a/src/stores/modules/userPreference.ts +++ b/src/stores/modules/userPreference.ts @@ -35,7 +35,7 @@ const STORAGE_PREFIX = 'user_prefs_' * - 读取:getGlobal 优先 globalMap,其次回退 map(兼容历史上写进仓库 key 的旧数据) * - 迁移:旧 key → 仓库 key 时**排除**这些 scope,避免在仓库 key 里留下会被回滚读到的陈旧副本 */ -export const USER_GLOBAL_SCOPES = ['tabOrder'] +export const USER_GLOBAL_SCOPES = ['tabOrder', 'scanFilterPresets'] /** 稳定取当前用户标识:employees_id > id > roleId,取不到用 'unknown' */ function currentUserId(): string { diff --git a/src/utils/scan-filter-presets.ts b/src/utils/scan-filter-presets.ts new file mode 100644 index 00000000..91583a76 --- /dev/null +++ b/src/utils/scan-filter-presets.ts @@ -0,0 +1,518 @@ +/** + * 自定义过滤条件(ScanBox「过滤」页签) + * + * 设计文档:docs/自定义过滤条件-设计与实施.md + * + * - 条件本身按账号保存在本地:`userPreference` 用户级 scope `scanFilterPresets` + * (存储结构 `{ version, presets: ScanFilterPreset[] }`,可用 tbyc-config.json 导入导出) + * - 页面元数据(pageKey → 页面标题 / 可筛选字段)保存在 `localStorage.scan_box_pages_{userId}`, + * 由 ScanBox 挂载时自动登记(与「所有表格字段」同一套路),**不参与** tbyc-config 导出 + * - 自定义条件固定输出「扁平结构」 `{ [字段]: { operator, value, type } }`, + * 与「筛选」页签的产出一致,页面侧 `buildXxxQuery` / `normalizeToWhere` 无需区分来源 + */ +import { useUserPreferenceStore } from '@/stores/modules/userPreference' +import { useUserStore } from '@/stores/modules/user' + +/** 用户级 scope(写进 user_prefs_{userId},不随仓库变化) */ +export const SCAN_FILTER_PRESET_SCOPE = 'scanFilterPresets' + +/** 存储文档版本(结构变化时递增,读取时兜底归一化) */ +export const SCAN_FILTER_PRESET_VERSION = 1 + +/** 页面元数据本地存储前缀(仅本机,不随 tbyc-config 导入导出) */ +const PAGE_STORAGE_PREFIX = 'scan_box_pages_' + +/** 单条预设最多条件数(防御异常数据) */ +export const SCAN_FILTER_MAX_CONDITIONS = 10 + +/** 预设名称最大长度 */ +export const SCAN_FILTER_NAME_MAX_LENGTH = 20 + +/** 单个字段保存的选项快照上限(如货主 / 违禁品类型等异步下拉;控制 localStorage 体积) */ +const MAX_FIELD_OPTIONS = 80 + +/** 单个条件对象 */ +export interface ScanFilterCondition { + operator: string + value: any + type?: string +} + +/** 条件集合:字段名 → 条件(扁平结构) */ +export type ScanFilterConditions = Record + +/** 一条自定义过滤条件 */ +export interface ScanFilterPreset { + /** 稳定唯一 id(导入导出按 id 覆盖) */ + id: string + /** 页面标识(ScanBox 的 cache-key,缺省为 route.path) */ + pageKey: string + /** 用户命名,同页内唯一 */ + name: string + /** 是否在「过滤」页签展示 */ + enabled: boolean + /** 同页内排序(升序) */ + order: number + /** 条件(扁平结构) */ + conditions: ScanFilterConditions + createdAt: number + updatedAt: number +} + +/** 页面字段的下拉选项快照 */ +export interface ScanFilterFieldOption { + value: any + label: string +} + +/** 页面可筛选字段(由 ScanBox 的 availableFields 精简而来) */ +export interface ScanFilterPageField { + value: string + label: string + type: string + operators?: string[] + defaultOperator?: string + group?: string + /** 仅 select / multiple 保存,供设置中心渲染下拉;异步加载的选项可能过期 */ + options?: ScanFilterFieldOption[] +} + +/** 页面元数据(设置中心按它列出页面 + 渲染条件编辑器) */ +export interface ScanFilterPageMeta { + pageKey: string + title: string + path: string + fields: ScanFilterPageField[] + updatedAt: number +} + +/** 操作符中文名(与 ScanBox 默认操作符文案保持一致) */ +export const SCAN_FILTER_OPERATOR_LABELS: Record = { + eq: '等于', + ne: '不等于', + like: '模糊匹配', + notlike: '模糊排除', + contains: '包含', + startswith: '开头为', + endswith: '结尾为', + in: 'IN', + notin: 'NOT IN', + isnull: '为空', + isnotnull: '不为空', + regexp: '正则匹配', + notregexp: '正则不匹配', + gt: '大于', + lt: '小于', + ge: '大于等于', + le: '小于等于', + between: '介于', + notbetween: '不在区间' +} + +/** 各字段类型默认支持的操作符(与 ScanBox 的 defaultOperators 对齐) */ +export const SCAN_FILTER_DEFAULT_OPERATORS: Record = { + text: ['eq', 'ne', 'contains', 'startswith', 'endswith', 'in', 'notin', 'isnull', 'isnotnull'], + number: ['eq', 'ne', 'gt', 'lt', 'ge', 'le', 'between', 'notbetween', 'in', 'notin', 'isnull', 'isnotnull'], + select: ['eq', 'ne', 'in', 'notin', 'isnull', 'isnotnull'], + multiple: ['in', 'notin', 'isnull', 'isnotnull'], + boolean: ['eq'], + date: ['eq', 'ne', 'gt', 'lt', 'ge', 'le', 'isnull', 'isnotnull'], + daterange: ['between'], + datetimerange: ['between'] +} + +/** 设置中心条件编辑器支持编辑的字段类型 */ +const EDITABLE_FIELD_TYPES = ['text', 'number', 'select', 'multiple', 'boolean', 'date', 'daterange', 'datetimerange'] + +/** 生成预设 id(时间戳 + 随机串,导入导出稳定) */ +export function createPresetId(): string { + return `sp_${Date.now()}_${Math.random().toString(36).slice(2, 8)}` +} + +/** 判断值是否为空(空字符串 / null / undefined / 空数组) */ +export function isEmptyConditionValue(value: unknown): boolean { + if (value === null || value === undefined) return true + if (typeof value === 'string' && value.trim() === '') return true + if (Array.isArray(value) && value.length === 0) return true + return false +} + +/** + * 取条件集合本体: + * - `{ conditions: {...} }` 信封(后端预设 / 部分页面传入)→ 取 conditions + * - 普通对象 → 原样返回 + */ +export function unwrapConditions(raw: unknown): Record | null { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null + const source = raw as Record + if (source.conditions && typeof source.conditions === 'object' && !Array.isArray(source.conditions)) { + return source.conditions as Record + } + return source +} + +/** + * 归一化为扁平条件结构;非法 / 空值 / 元数据键(type、preset 等)会被丢弃。 + * 已是 `{ operator, value, type }` 的原样保留(缺 operator 时默认 eq)。 + */ +export function normalizeConditions(raw: unknown): ScanFilterConditions { + const source = unwrapConditions(raw) + const result: ScanFilterConditions = {} + if (!source) return result + + Object.keys(source).forEach((key) => { + if (key === 'type' || key === 'preset' || key === 'conditions') return + const entryRaw = source[key] + if (entryRaw === null || entryRaw === undefined) return + + let condition: ScanFilterCondition + if (typeof entryRaw === 'object' && !Array.isArray(entryRaw)) { + const entry = entryRaw as Record + if (!('value' in entry)) return + condition = { + operator: typeof entry.operator === 'string' && entry.operator ? entry.operator : 'eq', + value: entry.value, + ...(typeof entry.type === 'string' && entry.type ? { type: entry.type } : {}) + } + } else { + condition = { operator: 'eq', value: entryRaw } + } + + if (isEmptyConditionValue(condition.value)) return + result[key] = condition + }) + + return result +} + +/** 读取预设文档(任意来源)→ 合法预设数组 */ +export function normalizePresetsDoc(raw: unknown): ScanFilterPreset[] { + const list = Array.isArray(raw) + ? raw + : raw && typeof raw === 'object' && Array.isArray((raw as any).presets) + ? (raw as any).presets + : [] + + const seenIds = new Set() + const result: ScanFilterPreset[] = [] + + list.forEach((item: any, index: number) => { + if (!item || typeof item !== 'object') return + const pageKey = typeof item.pageKey === 'string' ? item.pageKey.trim() : '' + const name = typeof item.name === 'string' ? item.name.trim() : '' + if (!pageKey || !name) return + + const conditions = normalizeConditions(item.conditions) + if (!Object.keys(conditions).length) return + + let id = typeof item.id === 'string' && item.id ? item.id : createPresetId() + if (seenIds.has(id)) id = createPresetId() + seenIds.add(id) + + const order = Number.isFinite(Number(item.order)) ? Number(item.order) : index + const createdAt = Number(item.createdAt) || Date.now() + const updatedAt = Number(item.updatedAt) || createdAt + + result.push({ + id, + pageKey, + name: name.slice(0, SCAN_FILTER_NAME_MAX_LENGTH), + enabled: item.enabled !== false, + order, + conditions, + createdAt, + updatedAt + }) + }) + + return result +} + +/** 构造持久化文档 */ +export function buildPresetsDoc(presets: ScanFilterPreset[]) { + return { + version: SCAN_FILTER_PRESET_VERSION, + presets: presets.map((preset) => ({ + ...preset, + conditions: { ...preset.conditions } + })) + } +} + +/** 读取当前账号的自定义过滤条件 */ +export function readScanFilterPresets(): ScanFilterPreset[] { + const preferenceStore = useUserPreferenceStore() + if (!preferenceStore.isLoaded) preferenceStore.load() + return normalizePresetsDoc(preferenceStore.getGlobal(SCAN_FILTER_PRESET_SCOPE)) +} + +/** 写回当前账号的自定义过滤条件 */ +export function writeScanFilterPresets(presets: ScanFilterPreset[]): void { + useUserPreferenceStore().setGlobal(SCAN_FILTER_PRESET_SCOPE, buildPresetsDoc(presets)) +} + +/** 字段可用的操作符列表 */ +export function getFieldOperators(field?: ScanFilterPageField | null): string[] { + if (!field) return ['eq'] + if (Array.isArray(field.operators) && field.operators.length) return field.operators + return SCAN_FILTER_DEFAULT_OPERATORS[field.type] || ['eq'] +} + +/** 字段是否可在设置中心编辑 */ +export function isEditableFilterField(field?: ScanFilterPageField | null): boolean { + if (!field) return false + return EDITABLE_FIELD_TYPES.includes(field.type) +} + +/** 区间操作符 */ +export function isRangeFilterOperator(operator?: string): boolean { + return operator === 'between' || operator === 'notbetween' +} + +/** 无需填值的操作符 */ +export function isNullishFilterOperator(operator?: string): boolean { + return operator === 'isnull' || operator === 'isnotnull' +} + +/** 单值字段是否强制使用某个操作符(多选 → in,日期区间 → between,布尔 → eq) */ +export function resolveForcedOperator(field: ScanFilterPageField): string { + if (field.type === 'multiple') return 'in' + if (field.type === 'daterange' || field.type === 'datetimerange') return 'between' + if (field.type === 'boolean') return 'eq' + return '' +} + +/** 归一化单个页面字段(来自页面 availableFields) */ +export function normalizePageField(raw: any): ScanFilterPageField | null { + if (!raw || typeof raw !== 'object') return null + const value = typeof raw.value === 'string' ? raw.value.trim() : '' + if (!value) return null + const type = typeof raw.type === 'string' && raw.type ? raw.type : 'text' + + const field: ScanFilterPageField = { + value, + label: typeof raw.label === 'string' && raw.label ? raw.label : value, + type, + ...(Array.isArray(raw.operators) && raw.operators.length + ? { operators: raw.operators.filter((op: unknown): op is string => typeof op === 'string') } + : {}), + ...(typeof raw.defaultOperator === 'string' && raw.defaultOperator + ? { defaultOperator: raw.defaultOperator } + : {}), + ...(typeof raw.group === 'string' && raw.group ? { group: raw.group } : {}) + } + + if ((type === 'select' || type === 'multiple') && Array.isArray(raw.options)) { + const options = raw.options + .filter((option: any) => option && typeof option === 'object' && option.value !== undefined) + .slice(0, MAX_FIELD_OPTIONS) + .map((option: any) => ({ + value: option.value, + label: + option.label != null + ? String(option.label) + : option.name != null + ? String(option.name) + : String(option.value) + })) + if (options.length) field.options = options + } + + return field +} + +/** 归一化页面元数据 */ +export function normalizePageMeta(raw: any): ScanFilterPageMeta | null { + if (!raw || typeof raw !== 'object') return null + const pageKey = typeof raw.pageKey === 'string' ? raw.pageKey.trim() : '' + if (!pageKey) return null + const fields = Array.isArray(raw.fields) + ? raw.fields.map(normalizePageField).filter((field: ScanFilterPageField | null): field is ScanFilterPageField => !!field) + : [] + + return { + pageKey, + title: typeof raw.title === 'string' && raw.title ? raw.title : pageKey, + path: typeof raw.path === 'string' ? raw.path : '', + fields, + updatedAt: Number(raw.updatedAt) || Date.now() + } +} + +/** 稳定取当前账号标识(与 userPreference 的取法保持一致) */ +function currentUserId(): string { + try { + const userStore = useUserStore() + const user = userStore.user || {} + const id = user.employees_id ?? user.id ?? userStore.roleId + return id != null && id !== '' ? String(id) : 'unknown' + } catch { + return 'unknown' + } +} + +function pageStorageKey(): string { + return `${PAGE_STORAGE_PREFIX}${currentUserId()}` +} + +/** 读取本机已登记的页面元数据 */ +export function readScanBoxPages(): ScanFilterPageMeta[] { + try { + const raw = localStorage.getItem(pageStorageKey()) + if (!raw) return [] + const parsed = JSON.parse(raw) + const list = Array.isArray(parsed) ? parsed : [] + return list.map(normalizePageMeta).filter((item: ScanFilterPageMeta | null): item is ScanFilterPageMeta => !!item) + } catch { + return [] + } +} + +/** 写回本机页面元数据(localStorage 不可用时静默忽略) */ +export function writeScanBoxPages(pages: ScanFilterPageMeta[]): void { + try { + localStorage.setItem(pageStorageKey(), JSON.stringify(pages)) + } catch { + // 忽略:localStorage 不可用时仅影响设置中心的页面列表 + } +} + +/** 清空本机页面登记(故障修复用;页面下次打开会自动重建) */ +export function clearScanBoxPages(): void { + try { + localStorage.removeItem(pageStorageKey()) + } catch { + // 忽略 + } +} + +/** 格式化单个条件的值(用于摘要展示) */ +export function formatConditionValue(field: ScanFilterPageField | undefined, condition: ScanFilterCondition): string { + const value = condition.value + if (Array.isArray(value)) { + if (isRangeFilterOperator(condition.operator)) { + const [start, end] = value + return `${start ?? ''} ~ ${end ?? ''}` + } + return value + .map((item) => formatScalarValue(field, item)) + .filter((item) => item !== '') + .join('、') + } + return formatScalarValue(field, value) +} + +function formatScalarValue(field: ScanFilterPageField | undefined, value: any): string { + if (value === null || value === undefined) return '' + if (typeof value === 'boolean') return value ? '是' : '否' + if (field?.options?.length) { + const hit = field.options.find((option) => String(option.value) === String(value)) + if (hit) return hit.label + } + return String(value) +} + +/** 生成单条条件的可读描述,如「库存数量 小于等于 0」 */ +export function describeCondition( + field: ScanFilterPageField | undefined, + condition: ScanFilterCondition +): string { + const label = field?.label || condition.operator + const opLabel = SCAN_FILTER_OPERATOR_LABELS[condition.operator] || condition.operator + if (isNullishFilterOperator(condition.operator)) { + return `${label} ${opLabel}` + } + const valueText = formatConditionValue(field, condition) + if (isRangeFilterOperator(condition.operator)) { + return `${label} ${valueText}` + } + return `${label} ${opLabel} ${valueText}` +} + +/** 生成整条预设的可读描述,多个条件用「且」连接 */ +export function describeConditions( + conditions: ScanFilterConditions, + fields: ScanFilterPageField[] +): string { + const fieldMap = new Map(fields.map((field) => [field.value, field])) + return Object.keys(conditions) + .map((key) => { + const condition = conditions[key] + return condition ? describeCondition(fieldMap.get(key), condition) : '' + }) + .filter(Boolean) + .join(' 且 ') +} + +/** 校验名称(返回错误文案,null 表示通过) */ +export function validatePresetName( + name: string, + presets: ScanFilterPreset[], + options: { pageKey: string; excludeId?: string } +): string | null { + const trimmed = String(name || '').trim() + if (!trimmed) return '请输入过滤条件名称' + if (trimmed.length > SCAN_FILTER_NAME_MAX_LENGTH) { + return `名称最多 ${SCAN_FILTER_NAME_MAX_LENGTH} 个字` + } + const duplicated = presets.some( + (preset) => + preset.pageKey === options.pageKey && + preset.id !== options.excludeId && + preset.name.trim().toLowerCase() === trimmed.toLowerCase() + ) + return duplicated ? '该页面已存在同名过滤条件' : null +} + +/** 校验条件集合(返回错误文案数组) */ +export function validatePresetConditions( + conditions: ScanFilterConditions, + fields: ScanFilterPageField[] +): string[] { + const errors: string[] = [] + const keys = Object.keys(conditions) + if (!keys.length) { + errors.push('请至少添加一个筛选条件') + return errors + } + if (keys.length > SCAN_FILTER_MAX_CONDITIONS) { + errors.push(`最多支持 ${SCAN_FILTER_MAX_CONDITIONS} 个筛选条件`) + } + + const fieldMap = new Map(fields.map((field) => [field.value, field])) + keys.forEach((key) => { + const field = fieldMap.get(key) + const condition = conditions[key] + if (!condition) return + if (!field) { + errors.push(`字段 ${key} 不在当前页面的可筛选字段中`) + return + } + if (!isEditableFilterField(field)) { + errors.push(`字段 ${field.label} 的类型暂不支持自定义过滤`) + return + } + const allowed = getFieldOperators(field) + if (!allowed.includes(condition.operator)) { + errors.push(`${field.label} 不支持操作符 ${condition.operator}`) + return + } + if (isNullishFilterOperator(condition.operator)) return + if (isEmptyConditionValue(condition.value)) { + errors.push(`请填写 ${field.label} 的值`) + return + } + if (isRangeFilterOperator(condition.operator)) { + if (!Array.isArray(condition.value) || condition.value.length < 2) { + errors.push(`${field.label} 需要填写区间上下限`) + return + } + const [start, end] = condition.value + if (isEmptyConditionValue(start) || isEmptyConditionValue(end)) { + errors.push(`${field.label} 需要填写区间上下限`) + } + } + }) + + return errors +} diff --git a/src/utils/stockQueryBuilder.ts b/src/utils/stockQueryBuilder.ts index 7367e720..c0b43174 100644 --- a/src/utils/stockQueryBuilder.ts +++ b/src/utils/stockQueryBuilder.ts @@ -14,7 +14,17 @@ export function buildStockQuery(params: Record) { if (!params) return where; - for (const [key, val] of Object.entries(params)) { + // 兼容预设条件信封结构 { conditions: {...}, type, preset }(后端 index.fastWhereTree 节点 / 历史调用) + const source = + (params as any).conditions && + typeof (params as any).conditions === 'object' && + !Array.isArray((params as any).conditions) + ? ((params as any).conditions as Record) + : params; + + for (const [key, val] of Object.entries(source)) { + // 元数据键(预设类型 / 预设标识)不是查询字段 + if (key === 'type' || key === 'preset') continue; // 1. 基础空值检查 if (val === null || val === undefined || val === '') continue; if (Array.isArray(val) && val.length === 0) continue;