Commit 06b86982 by 张立顺

refactor: simplify dynamic option visibility

1 parent 6b6a5060
# Simplify Multiple-Select Option Visibility Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Replace unpublished expression-based `optionShowRules` with declarative visibility metadata on each static option while preserving the confirmed F2-107-7 scene/brand matrix across rendering, stale-value cleanup, and save paths.
**Architecture:** `getVisibleFieldOptions` will evaluate option-level `baseSceneCode`, `brandId`, `filterBrandId`, and an AND-composed `hideWhen` object using normalized `pageContext` scene and brand IDs. Conditional options fail closed when required context is absent. The converter will emit the metadata directly into F2-107-7 options for both daily and production IDs, so the option-only `$hasNonFiveRealmBrand` resolver and expression engine integration can be removed.
**Tech Stack:** JavaScript ES modules, Node.js built-in test runner, Python 3 `unittest`, Excel-to-schema converter fixtures.
## Global Constraints
- Work on branch `SAAS+V5.8.5`.
- Do not retain compatibility for `optionShowRules`; it has not been published.
- Preserve the confirmed mixed-brand behavior: positive five-realm options remain visible, while `已交付引荐` is hidden in light scenes when any non-five-realm brand exists.
- Preserve unrelated working-tree changes in `packageDynamicForm/utils/daily-report-calendar.js` and its plan document.
- This is a local form-engine fix and does not require the repository migration manifest gate.
---
### Task 1: Define declarative option visibility behavior
**Files:**
- Modify: `packageDynamicForm/tests/option-visibility.test.mjs`
- Modify: `packageDynamicForm/tests/store-v230-context-visibility.test.mjs`
**Interfaces:**
- Consumes: `getVisibleFieldOptions(field, pageContext)` and `filterMultipleSelectValueByVisibleOptions(field, value, pageContext)`.
- Produces: executable expectations for option-level `baseSceneCode`, `brandId`, `filterBrandId`, `hideWhen`, missing-context fail-closed behavior, mixed brands, object selections, and stale-value cleanup.
- [ ] **Step 1: Replace expression-rule fixtures with option metadata**
Use literal options where `已拉群`, `首保维保客户`, and `事故车客户` carry light-scene `baseSceneCode` plus five-realm `brandId`, and `已交付引荐` carries `hideWhen.baseSceneCode` plus `hideWhen.filterBrandId`.
- [ ] **Step 2: Run the focused tests and verify RED**
Run: `node --test packageDynamicForm/tests/option-visibility.test.mjs packageDynamicForm/tests/store-v230-context-visibility.test.mjs`
Expected: FAIL because the current engine only reads `field.optionShowRules`.
### Task 2: Implement declarative option evaluation
**Files:**
- Modify: `packageDynamicForm/form-engine/option-visibility.js`
- Modify: `packageDynamicForm/form-engine/show-rule-context.js`
- Modify: `packageDynamicForm/form-engine/values.js`
**Interfaces:**
- Consumes: option metadata arrays and `pageContext.sceneList[].baseSceneCode`, fallback `pageContext.baseSceneCode`, and `pageContext.brandIds`.
- Produces: `hasOptionVisibilityConditions(option)`, option filtering, and value filtering without string expression evaluation.
- [ ] **Step 1: Implement normalized positive visibility checks**
An option with `baseSceneCode` requires a scene intersection; an option with `brandId` requires a brand intersection; an option with top-level `filterBrandId` requires at least one current brand outside the configured list.
- [ ] **Step 2: Implement `hideWhen` as an AND-composed negative condition**
Every configured property inside `hideWhen` must match before the option is hidden. Missing context required by either positive metadata or `hideWhen` hides the conditional option.
- [ ] **Step 3: Remove the option-only expression resolver and update stale-value guards**
Delete `resolveOptionShowRuleContextValue` and make cleanup conditional on option-level visibility metadata rather than `field.optionShowRules`.
- [ ] **Step 4: Run focused tests and verify GREEN**
Run: `node --test packageDynamicForm/tests/option-visibility.test.mjs packageDynamicForm/tests/store-v230-context-visibility.test.mjs packageDynamicForm/tests/form-field-multiple-select-option-visibility.test.mjs`
Expected: all tests pass.
### Task 3: Generate declarative F2-107-7 templates
**Files:**
- Modify: `packageDynamicForm/scripts/convert-excel-template-to-schema.py`
- Modify: `packageDynamicForm/tests/test_store_v230_converter.py`
- Modify: `packageDynamicForm/tests/store-v230-template-schema.test.mjs`
- Regenerate: `packageDynamicForm/fixtures/schema-store-daily-v2.3.0.js`
- Regenerate: `packageDynamicForm/fixtures/schema-store-daily-v2.3.0.json`
- Regenerate: `packageDynamicForm/fixtures/schema-store-daily-v2.3.0.prod.js`
- Regenerate: `packageDynamicForm/fixtures/schema-store-daily-v2.3.0.prod.json`
**Interfaces:**
- Consumes: `FIVE_REALM_IDS`, light-scene codes, parsed Excel option labels, and environment brand remapping.
- Produces: environment-correct metadata directly on the four conditional F2-107-7 options.
- [ ] **Step 1: Change converter and schema expectations first**
Assert that generated options contain the exact declarative metadata and that `optionShowRules`, `fiveRealmBrandIds`, and `$hasNonFiveRealmBrand` are absent.
- [ ] **Step 2: Run converter/schema tests and verify RED**
Run: `python -m unittest packageDynamicForm.tests.test_store_v230_converter && node --test packageDynamicForm/tests/store-v230-template-schema.test.mjs`
Expected: FAIL while the converter still emits expression rules.
- [ ] **Step 3: Implement the option metadata builder and validation**
Attach positive metadata to three five-realm options and `hideWhen` metadata to `已交付引荐`; validate supported option visibility properties as arrays/objects without expression dependency validation.
- [ ] **Step 4: Regenerate daily and production fixtures from the latest workbook**
Use the converter's existing CLI and environment mapping so only brand IDs differ between outputs.
- [ ] **Step 5: Run converter/schema tests and verify GREEN**
Run: `python -m unittest packageDynamicForm.tests.test_store_v230_converter && node --test packageDynamicForm/tests/store-v230-template-schema.test.mjs`
Expected: all tests pass.
### Task 4: Update documentation and verify the complete change
**Files:**
- Modify: `packageDynamicForm/docs/group-repeater.md`
**Interfaces:**
- Consumes: final option metadata contract.
- Produces: documentation for template authors and fresh verification evidence.
- [ ] **Step 1: Replace the `optionShowRules` documentation**
Document option-level positive properties, `hideWhen`, fail-closed context behavior, and shared filtering across UI/cleanup/save.
- [ ] **Step 2: Confirm obsolete symbols are gone**
Run: `rg -n "optionShowRules|hasNonFiveRealmBrand|fiveRealmBrandIds" packageDynamicForm`
Expected: no results outside historical plan text if retained for design history.
- [ ] **Step 3: Run complete dynamic-form verification**
Run: `npm run test:dynamicForm`
Expected: zero failures.
- [ ] **Step 4: Run converter verification**
Run: `python -m unittest packageDynamicForm.tests.test_store_v230_converter`
Expected: zero failures.
- [ ] **Step 5: Inspect scope and commit only related files**
Run: `git diff --check` and `git status --short`, then stage the files listed in this plan while leaving unrelated daily-report calendar changes untouched.
......@@ -2,7 +2,7 @@
## 2026-08-12 — 客户标签按业务场景和主营品牌动态显示
- **模板协议**:新增通用字段级 `optionShowRules`,复用安全显隐表达式;`$sceneCodes`、`$brandIds`、`$hasNonFiveRealmBrand` 提供页面上下文,五界 ID 由字段 `fiveRealmBrandIds` 按 daily/production 环境生成。
- **模板协议**:静态选项直接使用声明式 `baseSceneCode`、`brandId`、`filterBrandId`;需要反向隐藏时使用由这些属性组成的 `hideWhen`。五界 ID 直接按 daily/production 环境写入选项,不再生成选项表达式或额外上下文变量。
- **F2-107-7 规则**:`已触客`始终显示;轻改且含五界品牌时显示`已拉群/首保维保客户/事故车客户`;轻改且含任一非五界品牌时隐藏`已交付引荐`。混合品牌显示三类五界标签并隐藏交付引荐;缺少场景或品牌时条件选项 fail-closed。
- **运行时与保存**:多选组件的弹窗、回显、确认提交共用过滤结果;上下文变化会清除不可用旧值;App 的 `jsonContent`、`subformDataList` 保存前再次过滤,仍保持单文件零 import。
- **生成**:以最新版《门店工作汇报-V2.3.0输入输出模板 (1).xlsx》的`输入-门店日报`为来源,覆盖四份 V2.3 daily/production JS/JSON;保留纯文本 options,不生成 `sourceRule`。
......
......@@ -289,10 +289,10 @@ python packageDynamicForm/scripts/convert-excel-template-to-schema.py ^
### 8.1 V2.3 客户标签选项条件
最新版 `输入-门店日报` 的 `F2-107-7` 在选项括号中描述场景/品牌条件。转换器会保留纯文本 `options`,并将四个条件选项编译到字段级 `optionShowRules`;不会恢复旧的、运行时不支持的 `sourceRule`。
最新版 `输入-门店日报` 的 `F2-107-7` 在选项括号中描述场景/品牌条件。转换器会保留纯文本 `options`,并把条件直接编译成选项级 `baseSceneCode`、`brandId` 或 `hideWhen.filterBrandId`;不会生成表达式规则,也不会恢复旧的、运行时不支持的 `sourceRule`。
- daily 与 production 通过 `fiveRealmBrandIds` 和规则表达式写入各自环境的五界品牌 ID。
- 规则只使用 `$sceneCodes`、`$brandIds`、`$hasNonFiveRealmBrand` 三个保留键,未知保留键在转换校验阶段报错。
- daily 与 production 直接在各自选项的 `brandId` / `hideWhen.filterBrandId` 写入对应环境的五界品牌 ID。
- 转换器只允许选项使用 `baseSceneCode`、`brandId`、`filterBrandId`,以及由这些属性组成的 `hideWhen`;未知属性或非数组值在转换校验阶段报错。
- 条件上下文缺失时选项不显示;上下文变化后的不可用旧值会由运行时和保存序列化双重清理。
生成 V2.3 时需分别执行 daily/production 的 JS/JSON 四次转换,并运行 `test_store_v230_converter.py` 与 `store-v230-template-schema.test.mjs`。
......
......@@ -122,11 +122,11 @@ values['F2-9'] = [
- **编解码**:[`app-subform-json.js`](../form-engine/app-subform-json.js) — `buildAppDailyReportSubmitPayload` / `serializeFormListForAppJsonStorage` / `getSectionRowFieldsList`。
- `parseJsonContentDetailValues`:从 jsonContent 解析 values(支持 `childrenValue`)。
## multipleSelect 选项显隐(optionShowRules)
## multipleSelect 选项声明式显隐
- 字段可用 `optionShowRules[option.value] = { keys, result }` 为静态选项配置上下文显隐;没有规则的选项始终显示。表达式沿用 `childrenShowRules` 的安全解析语法。
- 保留键 `$sceneCodes`、`$brandIds` 分别读取 `pageContext.sceneList[].baseSceneCode`(回退 `baseSceneCode`)和 `pageContext.brandIds`;`$hasNonFiveRealmBrand` 根据字段的 `fiveRealmBrandIds` 判断经营品牌中是否存在非五界品牌。
- 条件选项在上下文缺失、规则非法或求值失败时 fail-closed;普通字段和未配置 `optionShowRules` 的字段行为不变。
- 静态选项可直接配置 `baseSceneCode`、`brandId`、`filterBrandId`,语义与字段显隐一致;多个属性为 AND,未配置条件的选项始终显示。
- 需要反向隐藏时使用 `hideWhen`,其内部仍使用以上三个属性,全部匹配时隐藏。例如 `{ hideWhen: { baseSceneCode: [...], filterBrandId: [...] } }` 表示指定场景且存在任一列表外经营品牌时隐藏。
- 场景取 `pageContext.sceneList[].baseSceneCode`(回退 `baseSceneCode`),品牌取 `pageContext.brandIds`。条件依赖的上下文缺失或配置结构非法时 fail-closed。
- `getVisibleFieldOptions` 统一供弹窗、回显和提交使用;`clearUnavailableOptionValues` 在上下文切换时删除已不可选的旧值。App 保存端在构建 `jsonContent`、`subformDataList` 前按同一规则再次过滤。
- 门店 V2.3 `F2-107-7`:`已触客`始终显示;轻改且包含五界品牌时显示`已拉群/首保维保客户/事故车客户`;轻改且包含任一非五界品牌时隐藏`已交付引荐`。混合品牌同时满足前两项,因此显示三类五界标签但隐藏`已交付引荐`。
......
......@@ -333,40 +333,31 @@
},
{
label: '已拉群',
value: '已拉群'
value: '已拉群',
baseSceneCode: [100101, 100102, 100103],
brandId: [3454, 3503, 3458, 3574, 3502]
},
{
label: '已交付引荐',
value: '已交付引荐'
value: '已交付引荐',
hideWhen: {
baseSceneCode: [100101, 100102, 100103],
filterBrandId: [3454, 3503, 3458, 3574, 3502],
}
},
{
label: '首保维保客户',
value: '首保维保客户'
value: '首保维保客户',
baseSceneCode: [100101, 100102, 100103],
brandId: [3454, 3503, 3458, 3574, 3502]
},
{
label: '事故车客户',
value: '事故车客户'
value: '事故车客户',
baseSceneCode: [100101, 100102, 100103],
brandId: [3454, 3503, 3458, 3574, 3502]
}
],
fiveRealmBrandIds: [3454, 3503, 3458, 3574, 3502],
optionShowRules: {
'已拉群': {
keys: ['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand'],
result: "val1 && Array.isArray(val1) && val2 && Array.isArray(val2) && val3 != null && (val1.includes('100101') || val1.includes('100102') || val1.includes('100103')) && (val2.includes('3454') || val2.includes('3503') || val2.includes('3458') || val2.includes('3574') || val2.includes('3502'))"
},
'已交付引荐': {
keys: ['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand'],
result: "val1 && Array.isArray(val1) && val2 && Array.isArray(val2) && val3 != null && !((val1.includes('100101') || val1.includes('100102') || val1.includes('100103')) && val3)"
},
'首保维保客户': {
keys: ['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand'],
result: "val1 && Array.isArray(val1) && val2 && Array.isArray(val2) && val3 != null && (val1.includes('100101') || val1.includes('100102') || val1.includes('100103')) && (val2.includes('3454') || val2.includes('3503') || val2.includes('3458') || val2.includes('3574') || val2.includes('3502'))"
},
'事故车客户': {
keys: ['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand'],
result: "val1 && Array.isArray(val1) && val2 && Array.isArray(val2) && val3 != null && (val1.includes('100101') || val1.includes('100102') || val1.includes('100103')) && (val2.includes('3454') || val2.includes('3503') || val2.includes('3458') || val2.includes('3574') || val2.includes('3502'))"
}
},
rules: {},
},
......
......@@ -268,62 +268,71 @@
},
{
"label": "已拉群",
"value": "已拉群"
"value": "已拉群",
"baseSceneCode": [
100101,
100102,
100103
],
"brandId": [
3454,
3503,
3458,
3574,
3502
]
},
{
"label": "已交付引荐",
"value": "已交付引荐"
"value": "已交付引荐",
"hideWhen": {
"baseSceneCode": [
100101,
100102,
100103
],
"filterBrandId": [
3454,
3503,
3458,
3574,
3502
]
}
},
{
"label": "首保维保客户",
"value": "首保维保客户"
"value": "首保维保客户",
"baseSceneCode": [
100101,
100102,
100103
],
"brandId": [
3454,
3503,
3458,
3574,
3502
]
},
{
"label": "事故车客户",
"value": "事故车客户"
}
],
"fiveRealmBrandIds": [
3454,
3503,
3458,
3574,
3502
],
"optionShowRules": {
"已拉群": {
"keys": [
"$sceneCodes",
"$brandIds",
"$hasNonFiveRealmBrand"
],
"result": "val1 && Array.isArray(val1) && val2 && Array.isArray(val2) && val3 != null && (val1.includes('100101') || val1.includes('100102') || val1.includes('100103')) && (val2.includes('3454') || val2.includes('3503') || val2.includes('3458') || val2.includes('3574') || val2.includes('3502'))"
},
"已交付引荐": {
"keys": [
"$sceneCodes",
"$brandIds",
"$hasNonFiveRealmBrand"
],
"result": "val1 && Array.isArray(val1) && val2 && Array.isArray(val2) && val3 != null && !((val1.includes('100101') || val1.includes('100102') || val1.includes('100103')) && val3)"
},
"首保维保客户": {
"keys": [
"$sceneCodes",
"$brandIds",
"$hasNonFiveRealmBrand"
"value": "事故车客户",
"baseSceneCode": [
100101,
100102,
100103
],
"result": "val1 && Array.isArray(val1) && val2 && Array.isArray(val2) && val3 != null && (val1.includes('100101') || val1.includes('100102') || val1.includes('100103')) && (val2.includes('3454') || val2.includes('3503') || val2.includes('3458') || val2.includes('3574') || val2.includes('3502'))"
},
"事故车客户": {
"keys": [
"$sceneCodes",
"$brandIds",
"$hasNonFiveRealmBrand"
],
"result": "val1 && Array.isArray(val1) && val2 && Array.isArray(val2) && val3 != null && (val1.includes('100101') || val1.includes('100102') || val1.includes('100103')) && (val2.includes('3454') || val2.includes('3503') || val2.includes('3458') || val2.includes('3574') || val2.includes('3502'))"
"brandId": [
3454,
3503,
3458,
3574,
3502
]
}
}
]
},
{
"label": "客户车型",
......
......@@ -333,40 +333,31 @@
},
{
label: '已拉群',
value: '已拉群'
value: '已拉群',
baseSceneCode: [100101, 100102, 100103],
brandId: [2695, 2741, 2698, 2797, 2740]
},
{
label: '已交付引荐',
value: '已交付引荐'
value: '已交付引荐',
hideWhen: {
baseSceneCode: [100101, 100102, 100103],
filterBrandId: [2695, 2741, 2698, 2797, 2740],
}
},
{
label: '首保维保客户',
value: '首保维保客户'
value: '首保维保客户',
baseSceneCode: [100101, 100102, 100103],
brandId: [2695, 2741, 2698, 2797, 2740]
},
{
label: '事故车客户',
value: '事故车客户'
value: '事故车客户',
baseSceneCode: [100101, 100102, 100103],
brandId: [2695, 2741, 2698, 2797, 2740]
}
],
fiveRealmBrandIds: [2695, 2741, 2698, 2797, 2740],
optionShowRules: {
'已拉群': {
keys: ['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand'],
result: "val1 && Array.isArray(val1) && val2 && Array.isArray(val2) && val3 != null && (val1.includes('100101') || val1.includes('100102') || val1.includes('100103')) && (val2.includes('2695') || val2.includes('2741') || val2.includes('2698') || val2.includes('2797') || val2.includes('2740'))"
},
'已交付引荐': {
keys: ['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand'],
result: "val1 && Array.isArray(val1) && val2 && Array.isArray(val2) && val3 != null && !((val1.includes('100101') || val1.includes('100102') || val1.includes('100103')) && val3)"
},
'首保维保客户': {
keys: ['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand'],
result: "val1 && Array.isArray(val1) && val2 && Array.isArray(val2) && val3 != null && (val1.includes('100101') || val1.includes('100102') || val1.includes('100103')) && (val2.includes('2695') || val2.includes('2741') || val2.includes('2698') || val2.includes('2797') || val2.includes('2740'))"
},
'事故车客户': {
keys: ['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand'],
result: "val1 && Array.isArray(val1) && val2 && Array.isArray(val2) && val3 != null && (val1.includes('100101') || val1.includes('100102') || val1.includes('100103')) && (val2.includes('2695') || val2.includes('2741') || val2.includes('2698') || val2.includes('2797') || val2.includes('2740'))"
}
},
rules: {},
},
......
......@@ -268,62 +268,71 @@
},
{
"label": "已拉群",
"value": "已拉群"
"value": "已拉群",
"baseSceneCode": [
100101,
100102,
100103
],
"brandId": [
2695,
2741,
2698,
2797,
2740
]
},
{
"label": "已交付引荐",
"value": "已交付引荐"
"value": "已交付引荐",
"hideWhen": {
"baseSceneCode": [
100101,
100102,
100103
],
"filterBrandId": [
2695,
2741,
2698,
2797,
2740
]
}
},
{
"label": "首保维保客户",
"value": "首保维保客户"
"value": "首保维保客户",
"baseSceneCode": [
100101,
100102,
100103
],
"brandId": [
2695,
2741,
2698,
2797,
2740
]
},
{
"label": "事故车客户",
"value": "事故车客户"
}
],
"fiveRealmBrandIds": [
2695,
2741,
2698,
2797,
2740
],
"optionShowRules": {
"已拉群": {
"keys": [
"$sceneCodes",
"$brandIds",
"$hasNonFiveRealmBrand"
],
"result": "val1 && Array.isArray(val1) && val2 && Array.isArray(val2) && val3 != null && (val1.includes('100101') || val1.includes('100102') || val1.includes('100103')) && (val2.includes('2695') || val2.includes('2741') || val2.includes('2698') || val2.includes('2797') || val2.includes('2740'))"
},
"已交付引荐": {
"keys": [
"$sceneCodes",
"$brandIds",
"$hasNonFiveRealmBrand"
],
"result": "val1 && Array.isArray(val1) && val2 && Array.isArray(val2) && val3 != null && !((val1.includes('100101') || val1.includes('100102') || val1.includes('100103')) && val3)"
},
"首保维保客户": {
"keys": [
"$sceneCodes",
"$brandIds",
"$hasNonFiveRealmBrand"
"value": "事故车客户",
"baseSceneCode": [
100101,
100102,
100103
],
"result": "val1 && Array.isArray(val1) && val2 && Array.isArray(val2) && val3 != null && (val1.includes('100101') || val1.includes('100102') || val1.includes('100103')) && (val2.includes('2695') || val2.includes('2741') || val2.includes('2698') || val2.includes('2797') || val2.includes('2740'))"
},
"事故车客户": {
"keys": [
"$sceneCodes",
"$brandIds",
"$hasNonFiveRealmBrand"
],
"result": "val1 && Array.isArray(val1) && val2 && Array.isArray(val2) && val3 != null && (val1.includes('100101') || val1.includes('100102') || val1.includes('100103')) && (val2.includes('2695') || val2.includes('2741') || val2.includes('2698') || val2.includes('2797') || val2.includes('2740'))"
"brandId": [
2695,
2741,
2698,
2797,
2740
]
}
}
]
},
{
"label": "客户车型",
......
......@@ -1710,43 +1710,103 @@ function resolveAppOptionForSelection(options = [], selection) {
) || null
}
function resolveAppOptionShowRuleContextValue(
key = '',
pageContext = {},
field = {}
) {
const sharedValue = resolveAppShowRuleContextValue(key, pageContext)
if (sharedValue !== undefined) return sharedValue
if (key !== '$hasNonFiveRealmBrand') return undefined
const APP_OPTION_VISIBILITY_KEYS = ['baseSceneCode', 'brandId', 'filterBrandId']
function hasAppOptionVisibilityMetadata(config = {}) {
if (!config || typeof config !== 'object' || Array.isArray(config)) return false
return APP_OPTION_VISIBILITY_KEYS.some(key =>
Object.hasOwn(config, key) && (!Array.isArray(config[key]) || config[key].length > 0)
)
}
function hasAppOptionVisibilityConditions(option = {}) {
return Boolean(
option &&
typeof option === 'object' &&
(hasAppOptionVisibilityMetadata(option) || Object.hasOwn(option, 'hideWhen'))
)
}
function isValidAppOptionVisibilityMetadata(config = {}) {
return Boolean(
config &&
typeof config === 'object' &&
!Array.isArray(config) &&
APP_OPTION_VISIBILITY_KEYS.every(key =>
!Object.hasOwn(config, key) || Array.isArray(config[key])
)
)
}
function getAppOptionVisibilityContextRequirements(config = {}) {
return {
scene: Array.isArray(config.baseSceneCode) && config.baseSceneCode.length > 0,
brand:
(Array.isArray(config.brandId) && config.brandId.length > 0) ||
(Array.isArray(config.filterBrandId) && config.filterBrandId.length > 0)
}
}
function matchesAppOptionVisibilityMetadata(config = {}, sceneCodes = [], brandIds = []) {
const configuredSceneCodes = new Set((config.baseSceneCode || []).map(String))
if (configuredSceneCodes.size && !sceneCodes.some(code => configuredSceneCodes.has(code))) {
return false
}
const configuredBrandIds = new Set((config.brandId || []).map(String))
if (configuredBrandIds.size && !brandIds.some(id => configuredBrandIds.has(id))) {
return false
}
const filteredBrandIds = new Set((config.filterBrandId || []).map(String))
if (filteredBrandIds.size && !brandIds.some(id => !filteredBrandIds.has(id))) {
return false
}
return true
}
function isAppOptionVisible(option = {}, pageContext = {}) {
if (!hasAppOptionVisibilityConditions(option)) return true
if (!isValidAppOptionVisibilityMetadata(option)) return false
const hideWhen = Object.hasOwn(option, 'hideWhen') ? option.hideWhen : null
if (Object.hasOwn(option, 'hideWhen')) {
if (
!isValidAppOptionVisibilityMetadata(hideWhen) ||
!hasAppOptionVisibilityMetadata(hideWhen)
) {
return false
}
}
const sceneCodes = normalizeAppShowRuleContextArray(
(pageContext.sceneList || []).map(item => item?.baseSceneCode)
)
const effectiveSceneCodes = sceneCodes.length
? sceneCodes
: normalizeAppShowRuleContextArray(pageContext.baseSceneCode)
const brandIds = normalizeAppShowRuleContextArray(pageContext.brandIds || [])
const fiveRealmBrandIds = normalizeAppShowRuleContextArray(field.fiveRealmBrandIds || [])
if (!brandIds.length || !fiveRealmBrandIds.length) return null
const fiveRealmBrandIdSet = new Set(fiveRealmBrandIds)
return brandIds.some(brandId => !fiveRealmBrandIdSet.has(brandId))
const positiveContext = getAppOptionVisibilityContextRequirements(option)
const hideContext = getAppOptionVisibilityContextRequirements(hideWhen || {})
if ((positiveContext.scene || hideContext.scene) && !effectiveSceneCodes.length) return false
if ((positiveContext.brand || hideContext.brand) && !brandIds.length) return false
if (!matchesAppOptionVisibilityMetadata(option, effectiveSceneCodes, brandIds)) return false
if (hideWhen && matchesAppOptionVisibilityMetadata(hideWhen, effectiveSceneCodes, brandIds)) {
return false
}
return true
}
function filterAppFieldValueByOptionShowRules(field = {}, pageContext = {}) {
if (
field.type !== 'multipleSelect' ||
!field.optionShowRules ||
typeof field.optionShowRules !== 'object'
) {
function filterAppFieldValueByOptionVisibility(field = {}, pageContext = {}) {
const hasConditionalOptions = (field.options || []).some(hasAppOptionVisibilityConditions)
if (field.type !== 'multipleSelect' || !hasConditionalOptions) {
return field
}
const rawValue = resolveAppRowFieldEngineValue(field)
if (!Array.isArray(rawValue)) return field
const visibleOptionKeys = new Set(
(field.options || []).filter(option => {
const rule = field.optionShowRules[getAppOptionRuleKey(option)]
if (!rule) return true
const keys = Array.isArray(rule.keys) ? rule.keys : []
if (!keys.length || !rule.result) return false
return evaluateShowRuleForJson(keys, rule.result, [], (_rowFields, key) =>
resolveAppOptionShowRuleContextValue(key, pageContext, field)
)
}).map(getAppOptionRuleKey).filter(Boolean)
(field.options || [])
.filter(option => isAppOptionVisible(option, pageContext))
.map(getAppOptionRuleKey)
.filter(Boolean)
)
const filteredValue = rawValue.filter(item => {
const matchedOption = resolveAppOptionForSelection(field.options || [], item)
......@@ -1821,7 +1881,7 @@ export function buildAppJsonContent(visibleList = [], groupRowsCache = {}, pageC
const children = cloneRowFieldsList(rowFieldsList).map(row => {
const optionFilteredRow = row.map(cell =>
filterAppFieldValueByOptionShowRules(cell, pageContext)
filterAppFieldValueByOptionVisibility(cell, pageContext)
)
const rowMap = rowFieldsToStorageValueMap(optionFilteredRow)
const visibleRow = filterVisibleRowFieldsForJson(
......
/** multipleSelect 静态选项的上下文显隐与不可用值清理。 */
import { evaluateShowRule } from './group-show-rule-eval.js'
import { resolveOptionShowRuleContextValue } from './show-rule-context.js'
/** multipleSelect 静态选项的声明式上下文显隐与不可用值清理。 */
import {
resolveShowRuleBrandIds,
resolveShowRuleSceneCodes
} from './show-rule-context.js'
const OPTION_VISIBILITY_KEYS = ['baseSceneCode', 'brandId', 'filterBrandId']
export function getCanonicalOptionKey(option) {
if (option == null) return ''
......@@ -35,27 +39,93 @@ export function resolveOptionForSelection(options = [], selection) {
) || null
}
function isOptionVisible(field = {}, option = {}, pageContext = {}) {
const optionKey = getCanonicalOptionKey(option)
const rule = field.optionShowRules?.[optionKey]
if (!rule) {
return true
function hasOwn(object, key) {
if (!object || typeof object !== 'object') return false
return Object.prototype.hasOwnProperty.call(object, key)
}
function hasConfiguredArray(object, key) {
return hasOwn(object, key) && (!Array.isArray(object[key]) || object[key].length > 0)
}
function hasVisibilityMetadata(object = {}) {
return OPTION_VISIBILITY_KEYS.some(key => hasConfiguredArray(object, key))
}
export function hasOptionVisibilityConditions(option = {}) {
if (!option || typeof option !== 'object') return false
return hasVisibilityMetadata(option) || hasOwn(option, 'hideWhen')
}
export function hasFieldOptionVisibilityConditions(field = {}) {
return Array.isArray(field.options) && field.options.some(hasOptionVisibilityConditions)
}
function validateVisibilityMetadata(config = {}) {
if (!config || typeof config !== 'object' || Array.isArray(config)) return false
for (const key of OPTION_VISIBILITY_KEYS) {
if (hasOwn(config, key) && !Array.isArray(config[key])) return false
}
return true
}
function getRequiredContext(config = {}) {
return {
scene: Array.isArray(config.baseSceneCode) && config.baseSceneCode.length > 0,
brand:
(Array.isArray(config.brandId) && config.brandId.length > 0) ||
(Array.isArray(config.filterBrandId) && config.filterBrandId.length > 0)
}
}
function matchesVisibilityMetadata(config = {}, sceneCodes = [], brandIds = []) {
const configuredSceneCodes = new Set((config.baseSceneCode || []).map(String))
if (configuredSceneCodes.size && !sceneCodes.some(code => configuredSceneCodes.has(code))) {
return false
}
const configuredBrandIds = new Set((config.brandId || []).map(String))
if (configuredBrandIds.size && !brandIds.some(id => configuredBrandIds.has(id))) {
return false
}
const keys = Array.isArray(rule.keys) ? rule.keys : []
if (!keys.length || !rule.result) {
const filteredBrandIds = new Set((config.filterBrandId || []).map(String))
if (filteredBrandIds.size && !brandIds.some(id => !filteredBrandIds.has(id))) {
return false
}
return evaluateShowRule(keys, rule.result, [], (_rowFields, key) =>
resolveOptionShowRuleContextValue(key, pageContext, field)
)
return true
}
function isOptionVisible(option = {}, pageContext = {}) {
if (!hasOptionVisibilityConditions(option)) return true
if (!validateVisibilityMetadata(option)) return false
const hideWhen = hasOwn(option, 'hideWhen') ? option.hideWhen : null
if (hasOwn(option, 'hideWhen')) {
if (!validateVisibilityMetadata(hideWhen) || !hasVisibilityMetadata(hideWhen)) {
return false
}
}
const sceneCodes = resolveShowRuleSceneCodes(pageContext)
const brandIds = resolveShowRuleBrandIds(pageContext)
const positiveContext = getRequiredContext(option)
const hideContext = getRequiredContext(hideWhen || {})
if ((positiveContext.scene || hideContext.scene) && !sceneCodes.length) return false
if ((positiveContext.brand || hideContext.brand) && !brandIds.length) return false
if (!matchesVisibilityMetadata(option, sceneCodes, brandIds)) return false
if (hideWhen && matchesVisibilityMetadata(hideWhen, sceneCodes, brandIds)) return false
return true
}
export function getVisibleFieldOptions(field = {}, pageContext = {}) {
const options = Array.isArray(field.options) ? field.options : []
if (!field.optionShowRules || typeof field.optionShowRules !== 'object') {
if (!hasFieldOptionVisibilityConditions(field)) {
return options
}
return options.filter(option => isOptionVisible(field, option, pageContext))
return options.filter(option => isOptionVisible(option, pageContext))
}
export function filterMultipleSelectValueByVisibleOptions(
......@@ -69,7 +139,7 @@ export function filterMultipleSelectValueByVisibleOptions(
const visibleOptionKeys = new Set(
getVisibleFieldOptions(field, pageContext).map(getCanonicalOptionKey).filter(Boolean)
)
if (!field.optionShowRules || typeof field.optionShowRules !== 'object') {
if (!hasFieldOptionVisibilityConditions(field)) {
return value
}
return value.filter(item => {
......@@ -82,6 +152,8 @@ if (typeof module !== 'undefined' && module.exports) {
module.exports = {
getCanonicalOptionKey,
resolveOptionForSelection,
hasOptionVisibilityConditions,
hasFieldOptionVisibilityConditions,
getVisibleFieldOptions,
filterMultipleSelectValueByVisibleOptions
}
......
......@@ -34,22 +34,3 @@ export function resolveShowRuleContextValue(key = '', pageContext = {}) {
}
return undefined
}
/** optionShowRules 专用上下文;五界品牌集合由字段模板按环境提供。 */
export function resolveOptionShowRuleContextValue(key = '', pageContext = {}, field = {}) {
const sharedValue = resolveShowRuleContextValue(key, pageContext)
if (sharedValue !== undefined) {
return sharedValue
}
if (key !== '$hasNonFiveRealmBrand') {
return undefined
}
const brandIds = resolveShowRuleBrandIds(pageContext)
const fiveRealmBrandIds = normalizeContextArray(field.fiveRealmBrandIds || [])
if (!brandIds.length || !fiveRealmBrandIds.length) {
return null
}
const fiveRealmBrandIdSet = new Set(fiveRealmBrandIds)
return brandIds.some(brandId => !fiveRealmBrandIdSet.has(brandId))
}
......@@ -17,7 +17,10 @@ import { normalizeFieldValueByType } from './field-types/registry.js'
import { normalizeSelectValuesInMap } from './select-value.js'
import { coerceMultipleSelectValue } from './multiple-select-value.js'
import { extractSubformValuesFromField } from './group-row-adapter.js'
import { filterMultipleSelectValueByVisibleOptions } from './option-visibility.js'
import {
filterMultipleSelectValueByVisibleOptions,
hasFieldOptionVisibilityConditions
} from './option-visibility.js'
function isMeaningfulValue(field, value) {
if (value === undefined || value === null || value === '') {
return false
......@@ -163,7 +166,7 @@ export function clearHiddenFieldValues(list, ctx, values) {
function filterConditionalMultipleSelectValue(field, value, ctx) {
if (
field?.type !== 'multipleSelect' ||
!field.optionShowRules ||
!hasFieldOptionVisibilityConditions(field) ||
!Array.isArray(value)
) {
return value
......@@ -171,7 +174,7 @@ function filterConditionalMultipleSelectValue(field, value, ctx) {
return filterMultipleSelectValueByVisibleOptions(field, value, ctx)
}
/** 清除因 optionShowRules 上下文变化而不可再选择的 multipleSelect 值。 */
/** 清除因选项声明式显隐上下文变化而不可再选择的 multipleSelect 值。 */
export function clearUnavailableOptionValues(list, ctx, values) {
const nextValues = { ...values }
let changed = false
......
......@@ -690,9 +690,7 @@ V230_STORE_CHILD_SHOW_RULES = {
}
V230_SHOW_RULE_CONTEXT_KEYS = {'$sceneCodes', '$brandIds'}
V230_OPTION_SHOW_RULE_CONTEXT_KEYS = {
'$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand',
}
OPTION_VISIBILITY_KEYS = {'baseSceneCode', 'brandId', 'filterBrandId'}
def _includes_any(value_name: str, values: list[int]) -> str:
......@@ -731,37 +729,20 @@ def build_v230_store_child_show_rules() -> dict:
}
def build_v230_customer_tag_option_show_rules() -> dict:
"""生成 F2-107-7 客户标签的场景×主营品牌选项显隐规则。"""
def apply_v230_customer_tag_option_visibility(options: list[dict]) -> None:
"""给 F2-107-7 选项写入声明式场景×主营品牌显隐配置。"""
light_scenes = [100101, 100102, 100103]
light_expr = f"({_includes_any('val1', light_scenes)})"
five_realm_expr = f"({_includes_any('val2', FIVE_REALM_IDS)})"
context_guard = (
'val1 && Array.isArray(val1) && '
'val2 && Array.isArray(val2) && val3 != null'
)
five_realm_only_result = (
f'{context_guard} && {light_expr} && {five_realm_expr}'
)
keys = ['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand']
return {
'已拉群': {
'keys': keys.copy(),
'result': five_realm_only_result,
},
'已交付引荐': {
'keys': keys.copy(),
'result': f'{context_guard} && !({light_expr} && val3)',
},
'首保维保客户': {
'keys': keys.copy(),
'result': five_realm_only_result,
},
'事故车客户': {
'keys': keys.copy(),
'result': five_realm_only_result,
},
}
five_realm_values = {'已拉群', '首保维保客户', '事故车客户'}
for option in options:
value = option.get('value')
if value in five_realm_values:
option['baseSceneCode'] = light_scenes.copy()
option['brandId'] = FIVE_REALM_IDS.copy()
elif value == '已交付引荐':
option['hideWhen'] = {
'baseSceneCode': light_scenes.copy(),
'filterBrandId': FIVE_REALM_IDS.copy(),
}
def build_v230_children_rules(children: list[dict]) -> dict:
......@@ -849,10 +830,7 @@ def assemble_v230_list(records: list[dict], sheet_cfg: dict) -> list[dict]:
None,
)
if customer_tags is not None:
customer_tags['fiveRealmBrandIds'] = FIVE_REALM_IDS.copy()
customer_tags['optionShowRules'] = (
build_v230_customer_tag_option_show_rules()
)
apply_v230_customer_tag_option_visibility(customer_tags.get('options') or [])
parent['children'] = [children]
parent['childrenRules'] = build_v230_children_rules(children)
child_keys = {child['key'] for child in children}
......@@ -919,21 +897,30 @@ def validate_v230_shape(records: list[dict], fields: list[dict], sheet_cfg: dict
if isinstance(row, list)
for child in row
):
option_values = {
option.get('value')
for option in child.get('options') or []
if isinstance(option, dict)
}
for target, rule in (child.get('optionShowRules') or {}).items():
if target not in option_values:
for option in child.get('options') or []:
if not isinstance(option, dict):
continue
for prop in OPTION_VISIBILITY_KEYS:
if prop in option and not isinstance(option[prop], list):
raise ValueError(
f'option visibility {prop} must be a list for {child.get("key")}'
)
if 'hideWhen' not in option:
continue
hide_when = option['hideWhen']
if (
not isinstance(hide_when, dict)
or not hide_when
or set(hide_when) - OPTION_VISIBILITY_KEYS
):
raise ValueError(
f'optionShowRules target missing from {child.get("key")}: {target}'
f'option visibility hideWhen unsupported for {child.get("key")}'
)
for dependency in rule.get('keys') or []:
if dependency not in V230_OPTION_SHOW_RULE_CONTEXT_KEYS:
for prop, values in hide_when.items():
if not isinstance(values, list):
raise ValueError(
f'optionShowRules dependency unsupported for '
f'{child.get("key")}: {dependency}'
f'option visibility hideWhen {prop} must be a list '
f'for {child.get("key")}'
)
......@@ -1065,7 +1052,7 @@ COMMENTS_JSON = PKG_ROOT / 'fixtures/template-field-comments.json'
# 字段属性输出顺序(对齐 V2.0 业务配置粘贴格式)
FIELD_PROP_ORDER = [
'label', 'sortNum', 'key', 'type', 'required', 'sceneType', 'brandId',
'baseSceneCode', 'options', 'fiveRealmBrandIds', 'optionShowRules',
'baseSceneCode', 'options',
'optionsKey', 'value', 'prefixComponent',
'unit', 'rules',
'filterBrandId', 'completeFun', 'disabledFun', 'isYB', 'isQY',
......@@ -1206,12 +1193,6 @@ def _js_object(
f'{_js_children_show_rules(val, indent + 4)},'
)
continue
if prop == 'optionShowRules':
lines.append(
f'{inner_pad}optionShowRules: '
f'{_js_children_show_rules(val, indent + 4)},'
)
continue
if prop in ('completeFun', 'disabledFun') and isinstance(val, dict):
lines.append(f'{inner_pad}{prop}: {_js_fun_obj(val, indent + 4)},')
continue
......@@ -1282,10 +1263,11 @@ def _js_options(options: list, indent: int) -> str:
inner = ' ' * (indent + 4)
items = []
for opt in options:
props = [
f'{inner} label: {_js_str(opt["label"])}',
f'{inner} value: {_js_str(opt["value"])}',
]
props = []
for key in ('label', 'value', 'baseSceneCode', 'brandId', 'filterBrandId', 'hideWhen'):
if key not in opt:
continue
props.append(f'{inner} {key}: {_js_value(opt[key], indent + 8)}')
items.append(f'{inner}{{\n' + ',\n'.join(props) + f'\n{inner}}}')
return '[\n' + ',\n'.join(items) + f'\n{pad}]'
......
......@@ -265,23 +265,27 @@ describe('App save lists from jsonContent', () => {
})
it('IT-APP-LISTS-F2107-003: App save filters customer tags by mixed-brand context', () => {
const keys = ['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand']
const customerTagField = {
key: 'F2-107-7',
label: '客户标签',
type: 'multipleSelect',
fiveRealmBrandIds: ['3454'],
options: ['已触客', '已拉群', '已交付引荐'].map(value => ({ label: value, value })),
optionShowRules: {
已拉群: {
keys,
result: "val1 && val2 && val3 != null && val1.includes('100101') && val2.includes('3454')"
options: [
{ label: '已触客', value: '已触客' },
{
label: '已拉群',
value: '已拉群',
baseSceneCode: ['100101'],
brandId: ['3454']
},
已交付引荐: {
keys,
result: "val1 && val2 && val3 != null && !(val1.includes('100101') && val3)"
{
label: '已交付引荐',
value: '已交付引荐',
hideWhen: {
baseSceneCode: ['100101'],
filterBrandId: ['3454']
}
}
}
]
}
const customerSection = {
key: 'F2-107',
......@@ -321,17 +325,19 @@ describe('App save lists from jsonContent', () => {
key: 'F2-107-7',
label: '客户标签',
type: 'multipleSelect',
fiveRealmBrandIds: ['3454'],
options: [
{ id: 'tag-contacted', label: '已触客', value: '已触客' },
{ id: 'tag-referral', label: '已交付引荐', value: '已交付引荐' }
],
optionShowRules: {
已交付引荐: {
keys: ['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand'],
result: "val1 && val2 && val3 != null && !(val1.includes('100101') && val3)"
}
}
{
id: 'tag-referral',
label: '已交付引荐',
value: '已交付引荐',
hideWhen: {
baseSceneCode: ['100101'],
filterBrandId: ['3454']
}
},
{ id: 'tag-invalid', label: '非法标签', value: '非法标签', hideWhen: null }
]
}
const customerSection = {
key: 'F2-107',
......@@ -347,6 +353,7 @@ describe('App save lists from jsonContent', () => {
value: [
{ id: 'tag-contacted', name: '已触客' },
{ id: 'tag-referral', name: '已交付引荐' },
{ id: 'tag-invalid', name: '非法标签' },
{ id: 'obsolete', name: '旧标签' }
]
}]]
......
......@@ -62,24 +62,4 @@ describe('App show-rule parity', () => {
assert.equal(evaluateAppShowRuleExpression('val1 >>> 1', { val1: 2 }), false)
})
it('IT-APP-SHOW-RULE-004: option expressions keep parser parity', () => {
const optionExpressions = [
"val1 && val2 && val3 != null && val1.includes('100101') && val2.includes('3454')",
"val1 && val2 && val3 != null && !(val1.includes('100101') && val3)"
]
const optionContexts = [
{ val1: ['100101'], val2: ['3454'], val3: false },
{ val1: ['100101'], val2: ['3454', '9999'], val3: true },
{ val1: ['110201'], val2: ['9999'], val3: true },
{ val1: null, val2: null, val3: null }
]
for (const expression of optionExpressions) {
for (const context of optionContexts) {
assert.equal(
evaluateAppShowRuleExpression(expression, context),
fallbackEvaluate(expression, context)
)
}
}
})
})
......@@ -56,18 +56,23 @@ function createField() {
return {
key: 'F2-107-7',
type: 'multipleSelect',
fiveRealmBrandIds: ['3454'],
options: ['已触客', '已拉群', '已交付引荐'].map(value => ({ label: value, value })),
optionShowRules: {
已拉群: {
keys: ['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand'],
result: "val1 && val2 && val3 != null && val1.includes('100101') && val2.includes('3454')"
options: [
{ label: '已触客', value: '已触客' },
{
label: '已拉群',
value: '已拉群',
baseSceneCode: ['100101'],
brandId: ['3454']
},
已交付引荐: {
keys: ['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand'],
result: "val1 && val2 && val3 != null && !(val1.includes('100101') && val3)"
{
label: '已交付引荐',
value: '已交付引荐',
hideWhen: {
baseSceneCode: ['100101'],
filterBrandId: ['3454']
}
}
}
]
}
}
......
......@@ -13,38 +13,29 @@ const FIVE_REALM_BRAND = '3454'
const OTHER_BRAND = '9999'
function createCustomerTagField() {
const lightSceneExpr = "val1.includes('100101')"
const fiveRealmExpr = "val2.includes('3454')"
const contextGuard = 'val1 && val2 && val3 != null'
const fiveRealmLightOption = label => ({
label,
value: label,
baseSceneCode: [LIGHT_SCENE],
brandId: [FIVE_REALM_BRAND]
})
return {
key: 'F2-107-7',
type: 'multipleSelect',
fiveRealmBrandIds: [FIVE_REALM_BRAND],
options: [
{ label: '已触客', value: '已触客' },
{ label: '已拉群', value: '已拉群' },
{ label: '已交付引荐', value: '已交付引荐' },
{ label: '首保维保客户', value: '首保维保客户' },
{ label: '事故车客户', value: '事故车客户' }
],
optionShowRules: {
已拉群: {
keys: ['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand'],
result: `${contextGuard} && ${lightSceneExpr} && ${fiveRealmExpr}`
},
已交付引荐: {
keys: ['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand'],
result: `${contextGuard} && !(${lightSceneExpr} && val3)`
},
首保维保客户: {
keys: ['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand'],
result: `${contextGuard} && ${lightSceneExpr} && ${fiveRealmExpr}`
fiveRealmLightOption('已拉群'),
{
label: '已交付引荐',
value: '已交付引荐',
hideWhen: {
baseSceneCode: [LIGHT_SCENE],
filterBrandId: [FIVE_REALM_BRAND]
}
},
事故车客户: {
keys: ['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand'],
result: `${contextGuard} && ${lightSceneExpr} && ${fiveRealmExpr}`
}
}
fiveRealmLightOption('首保维保客户'),
fiveRealmLightOption('事故车客户')
]
}
}
......@@ -52,7 +43,7 @@ function optionValues(field, pageContext) {
return getVisibleFieldOptions(field, pageContext).map(option => option.value)
}
describe('optionShowRules', () => {
describe('declarative option visibility', () => {
it('IT-OPTION-VIS-001: filters customer tags by scene and merchant brand matrix', () => {
const field = createCustomerTagField()
assert.deepEqual(
......@@ -85,17 +76,14 @@ describe('optionShowRules', () => {
)
})
it('IT-OPTION-VIS-002: missing context and invalid rules fail closed', () => {
it('IT-OPTION-VIS-002: missing context and malformed metadata fail closed', () => {
const field = createCustomerTagField()
field.options.push({ label: '非法规则', value: '非法规则' })
field.optionShowRules.非法规则 = {
keys: ['$unknownContext'],
result: 'val1.some(() => true)'
}
field.options.push({ label: '非法规则', value: '非法规则', baseSceneCode: '100101' })
field.options.push({ label: '空隐藏条件', value: '空隐藏条件', hideWhen: null })
assert.deepEqual(optionValues(field, {}), ['已触客'])
})
it('IT-OPTION-VIS-003: fields without optionShowRules keep all options', () => {
it('IT-OPTION-VIS-003: options without declarative conditions remain visible', () => {
const field = {
type: 'multipleSelect',
options: [
......@@ -106,6 +94,23 @@ describe('optionShowRules', () => {
assert.deepEqual(getVisibleFieldOptions(field, {}), field.options)
})
it('IT-OPTION-VIS-003b: top-level filterBrandId shows an option for any other brand', () => {
const field = {
type: 'multipleSelect',
options: [
{ label: '常规', value: '常规' },
{ label: '其他品牌', value: '其他品牌', filterBrandId: [FIVE_REALM_BRAND] }
]
}
assert.deepEqual(optionValues(field, { brandIds: [FIVE_REALM_BRAND] }), ['常规'])
assert.deepEqual(optionValues(field, { brandIds: [OTHER_BRAND] }), ['常规', '其他品牌'])
assert.deepEqual(
optionValues(field, { brandIds: [FIVE_REALM_BRAND, OTHER_BRAND] }),
['常规', '其他品牌']
)
assert.deepEqual(optionValues(field, {}), ['常规'])
})
it('IT-OPTION-VIS-004: removes invisible selections and preserves visible objects', () => {
const field = createCustomerTagField()
const objectSelection = { id: '已交付引荐', name: '已交付引荐' }
......@@ -128,17 +133,18 @@ describe('optionShowRules', () => {
it('IT-OPTION-VIS-004b: matches object selections by option id and removes unknown values', () => {
const field = {
type: 'multipleSelect',
fiveRealmBrandIds: [FIVE_REALM_BRAND],
options: [
{ id: 'tag-contacted', label: '已触客', value: '已触客' },
{ id: 'tag-referral', label: '已交付引荐', value: '已交付引荐' }
],
optionShowRules: {
已交付引荐: {
keys: ['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand'],
result: "val1 && val2 && val3 != null && !(val1.includes('100101') && val3)"
{
id: 'tag-referral',
label: '已交付引荐',
value: '已交付引荐',
hideWhen: {
baseSceneCode: [LIGHT_SCENE],
filterBrandId: [FIVE_REALM_BRAND]
}
}
}
]
}
const contacted = { id: 'tag-contacted', name: '已触客' }
const referral = { id: 'tag-referral', name: '已交付引荐' }
......
......@@ -93,32 +93,38 @@ describe('store daily template V2.3.0 schema', () => {
assert.ok(tags?.options?.every(option => !Object.hasOwn(option, 'sourceRule')))
})
it('IT-V230-003b: customer tags carry environment-aware option visibility rules', () => {
it('IT-V230-003b: customer tags carry declarative environment-aware option visibility', () => {
const dailyTags = findDeep(daily.list, 'F2-107-7')
const productionTags = findDeep(production.list, 'F2-107-7')
assert.deepEqual(dailyTags?.fiveRealmBrandIds, [3454, 3503, 3458, 3574, 3502])
assert.deepEqual(productionTags?.fiveRealmBrandIds, [2695, 2741, 2698, 2797, 2740])
assert.deepEqual(Object.keys(dailyTags?.optionShowRules || {}), [
'已拉群', '已交付引荐', '首保维保客户', '事故车客户'
])
for (const rule of Object.values(dailyTags.optionShowRules)) {
assert.deepEqual(rule.keys, [
'$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand'
])
assert.match(rule.result, /val1 && Array\.isArray\(val1\)/)
assert.match(rule.result, /val2 && Array\.isArray\(val2\)/)
assert.match(rule.result, /val3 != null/)
const findOption = (field, value) => field.options.find(option => option.value === value)
const lightScenes = [100101, 100102, 100103]
const dailyBrands = [3454, 3503, 3458, 3574, 3502]
const productionBrands = [2695, 2741, 2698, 2797, 2740]
assert.deepEqual(findOption(dailyTags, '已触客'), { label: '已触客', value: '已触客' })
for (const value of ['已拉群', '首保维保客户', '事故车客户']) {
assert.deepEqual(findOption(dailyTags, value), {
label: value,
value,
baseSceneCode: lightScenes,
brandId: dailyBrands
})
assert.deepEqual(findOption(productionTags, value)?.brandId, productionBrands)
}
for (const option of ['已拉群', '首保维保客户', '事故车客户']) {
for (const brandId of dailyTags.fiveRealmBrandIds) {
assert.match(
dailyTags.optionShowRules[option].result,
new RegExp(`val2\\.includes\\('${brandId}'\\)`)
)
assert.deepEqual(findOption(dailyTags, '已交付引荐'), {
label: '已交付引荐',
value: '已交付引荐',
hideWhen: {
baseSceneCode: lightScenes,
filterBrandId: dailyBrands
}
}
assert.match(dailyTags.optionShowRules['已交付引荐'].result, /!\(/)
assert.match(dailyTags.optionShowRules['已交付引荐'].result, /&& val3\)/)
})
assert.deepEqual(
findOption(productionTags, '已交付引荐')?.hideWhen?.filterBrandId,
productionBrands
)
assert.equal(Object.hasOwn(dailyTags, 'fiveRealmBrandIds'), false)
assert.equal(Object.hasOwn(dailyTags, 'optionShowRules'), false)
})
it('IT-V230-004: subform childrenShowRules retain every Excel dependency', () => {
......@@ -179,13 +185,6 @@ describe('store daily template V2.3.0 schema', () => {
if (subform?.childrenShowRules?.['F2-107-4']) {
subform.childrenShowRules['F2-107-4'].result = '<environment-specific>'
}
const tags = findDeep(copy.list, 'F2-107-7')
if (tags) {
tags.fiveRealmBrandIds = '<environment-specific>'
for (const rule of Object.values(tags.optionShowRules || {})) {
rule.result = '<environment-specific>'
}
}
return withoutBrandIds(copy)
}
assert.deepEqual(withoutEnvRule(production), withoutEnvRule(daily))
......@@ -204,7 +203,7 @@ describe('store daily template V2.3.0 schema', () => {
const resultLines = dailyJsSource
.split(/\r?\n/)
.filter(line => line.trimStart().startsWith('result:'))
assert.equal(resultLines.length, 12)
assert.equal(resultLines.length, 8)
assert.ok(resultLines.every(line => /^\s*result: "/.test(line)))
assert.ok(resultLines.every(line => !line.includes("\\'")))
})
......
......@@ -332,29 +332,7 @@ class StoreV230ConverterTest(unittest.TestCase):
['F2-107-7'],
)
def test_builds_customer_tag_option_visibility_rules(self):
rules = converter.build_v230_customer_tag_option_show_rules()
self.assertEqual(
list(rules),
['已拉群', '已交付引荐', '首保维保客户', '事故车客户'],
)
for rule in rules.values():
self.assertEqual(
rule['keys'],
['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand'],
)
self.assertIn('val1 && Array.isArray(val1)', rule['result'])
self.assertIn('val2 && Array.isArray(val2)', rule['result'])
self.assertIn('val3 != null', rule['result'])
for option in ['已拉群', '首保维保客户', '事故车客户']:
for brand_id in converter.FIVE_REALM_IDS:
self.assertIn(
f"val2.includes('{brand_id}')",
rules[option]['result'],
)
self.assertIn("!(", rules['已交付引荐']['result'])
self.assertIn('&& val3)', rules['已交付引荐']['result'])
def test_builds_declarative_customer_tag_option_visibility(self):
rows = [
record('F2-107', '今日非成交客户', '子表单', 142),
record(
......@@ -371,8 +349,31 @@ class StoreV230ConverterTest(unittest.TestCase):
converter.resolve_sheet_config('store', '2.3.0'),
)
tags = fields[0]['children'][0][0]
self.assertEqual(tags['fiveRealmBrandIds'], converter.FIVE_REALM_IDS)
self.assertEqual(tags['optionShowRules'], rules)
options = {option['value']: option for option in tags['options']}
self.assertEqual(options['已触客'], {'label': '已触客', 'value': '已触客'})
for value in ['已拉群', '首保维保客户', '事故车客户']:
self.assertEqual(
options[value],
{
'label': value,
'value': value,
'baseSceneCode': [100101, 100102, 100103],
'brandId': converter.FIVE_REALM_IDS,
},
)
self.assertEqual(
options['已交付引荐'],
{
'label': '已交付引荐',
'value': '已交付引荐',
'hideWhen': {
'baseSceneCode': [100101, 100102, 100103],
'filterBrandId': converter.FIVE_REALM_IDS,
},
},
)
self.assertNotIn('fiveRealmBrandIds', tags)
self.assertNotIn('optionShowRules', tags)
self.assertTrue(all('sourceRule' not in item for item in tags['options']))
def test_multiline_visibility_comment_emits_parseable_js(self):
......@@ -457,24 +458,40 @@ class StoreV230ConverterTest(unittest.TestCase):
}]
converter.validate_v230_shape([], context_dependencies, validation_cfg)
option_context_dependencies = copy.deepcopy(context_dependencies)
option_context_dependencies[0]['children'][0][0].update({
declarative_options = copy.deepcopy(context_dependencies)
declarative_options[0]['children'][0][0].update({
'type': 'multipleSelect',
'options': [{'label': 'A', 'value': 'A'}],
'optionShowRules': {
'A': {
'keys': ['$sceneCodes', '$brandIds', '$hasNonFiveRealmBrand'],
'result': 'val1 && val2 && val3 != null',
'options': [
{
'label': 'A',
'value': 'A',
'baseSceneCode': [100101],
'brandId': [3454],
},
},
{
'label': 'B',
'value': 'B',
'hideWhen': {
'baseSceneCode': [100101],
'filterBrandId': [3454],
},
},
],
})
converter.validate_v230_shape([], option_context_dependencies, validation_cfg)
converter.validate_v230_shape([], declarative_options, validation_cfg)
bad_option_context = copy.deepcopy(option_context_dependencies)
bad_option_context[0]['children'][0][0]['optionShowRules']['A']['keys'][2] = '$unknown'
with self.assertRaisesRegex(ValueError, r'optionShowRules dependency.*\$unknown'):
bad_option_context = copy.deepcopy(declarative_options)
bad_option_context[0]['children'][0][0]['options'][0]['brandId'] = 3454
with self.assertRaisesRegex(ValueError, r'option visibility brandId.*F2-107-1'):
converter.validate_v230_shape([], bad_option_context, validation_cfg)
bad_hide_context = copy.deepcopy(declarative_options)
bad_hide_context[0]['children'][0][0]['options'][1]['hideWhen'] = {
'unknownBrandRule': [3454],
}
with self.assertRaisesRegex(ValueError, r'option visibility hideWhen.*F2-107-1'):
converter.validate_v230_shape([], bad_hide_context, validation_cfg)
bad_context_dependency = copy.deepcopy(context_dependencies)
bad_context_dependency[0]['childrenShowRules']['F2-107-2']['keys'][0] = '$unknown'
with self.assertRaisesRegex(ValueError, r'dependency.*\$unknown'):
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!