Commit 251b3ce0 by 张立顺

feat: 增加模板驱动子表单重复校验

1 parent a26bb95e
......@@ -23,8 +23,9 @@
## File Structure
- Create `packageDynamicForm/form-engine/subform-child-validation-value.js`: 承接现有子表单单元格校验取值解析,供普通校验与重复校验共同复用,避免循环依赖。
- Create `packageDynamicForm/form-engine/subform-duplicate-validation.js`: 唯一负责解析配置、归一化值、聚合重复行并生成标准错误结果。
- Modify `packageDynamicForm/form-engine/validator.js`: 导出已有子表单取值函数,并把重复错误合并到完整校验结果最前方。
- Modify `packageDynamicForm/form-engine/validator.js`: 改用共享子表单取值函数,并把重复错误合并到完整校验结果最前方。
- Modify `packageDynamicForm/form-engine/core.js`: 暴露 `validateDuplicates()`,在同步 cache 后调用通用重复校验器。
- Modify `packageDynamicForm/pages/storeDailyReport/storeDailyReport.js`: 用引擎预检替换固定手机号 helper,失败时应用错误状态并终止 VIN 请求。
- Modify `packageDynamicForm/utils/store-daily-save-guards.js`: 移除已被模板能力替代的固定字段 helper。
......@@ -35,12 +36,13 @@
### Task 1: 通用重复校验器
**Files:**
- Create: `packageDynamicForm/form-engine/subform-child-validation-value.js`
- Create: `packageDynamicForm/form-engine/subform-duplicate-validation.js`
- Modify: `packageDynamicForm/form-engine/validator.js`
- Test: `packageDynamicForm/tests/subform-duplicate-validation.test.mjs`
**Interfaces:**
- Consumes: `getVisibleList(list, ctx, values)`、`getVisibleGroupChildFields(...)`、`resolveEffectiveRowFields(...)`、`getGroupRows(values, groupKey)`、`buildGroupErrorKey(groupKey, rowIndex, childKey)`、`resolveSubformChildValue(child, row, rowField)`。
- Consumes: `getVisibleList(list, ctx, values)`、`getVisibleGroupChildFields(...)`、`resolveEffectiveRowFields(...)`、`getGroupRows(values, groupKey)`、`buildGroupErrorKey(groupKey, rowIndex, childKey)`、共享的 `resolveSubformChildValue(child, row, rowField)`。
- Produces: `validateSubformDuplicates(list, ctx, values, groupRowsCache) -> { ok, errors, errorMap }`。
- [ ] **Step 1: 写失败测试,覆盖空值、trim、全部重复行、配置优先级和错误定位**
......@@ -72,7 +74,7 @@ Run: `node --test packageDynamicForm/tests/subform-duplicate-validation.test.mjs
Expected: FAIL,错误包含 `ERR_MODULE_NOT_FOUND` 或缺少 `validateSubformDuplicates`。
- [ ] **Step 3: 导出统一子表单取值函数并实现最小重复校验器**
- [ ] **Step 3: 提取统一子表单取值函数并实现最小重复校验器**
```js
export function normalizeDuplicateValue(value) {
......@@ -100,7 +102,7 @@ Expected: PASS,至少覆盖:隐藏目标不校验、空/无效配置忽略
- [ ] **Step 5: 提交通用校验器**
```powershell
git add packageDynamicForm/form-engine/subform-duplicate-validation.js packageDynamicForm/form-engine/validator.js packageDynamicForm/tests/subform-duplicate-validation.test.mjs
git add packageDynamicForm/form-engine/subform-child-validation-value.js packageDynamicForm/form-engine/subform-duplicate-validation.js packageDynamicForm/form-engine/validator.js packageDynamicForm/tests/subform-duplicate-validation.test.mjs
git commit -m "feat: 增加模板驱动子表单重复校验"
```
......@@ -313,4 +315,3 @@ git diff --stat HEAD~3
git add packageDynamicForm/docs/PAGES.md packageDynamicForm/docs/store-template-features.md packageDynamicForm/docs/DEVLOG.md docs/superpowers/plans/2026-08-14-subform-duplicate-validation.md
git commit -m "docs: 记录子表单重复校验能力"
```
/** subform 单元格校验取值(App 双 key / carBrand 优先 meta) */
import { resolveCarBrandValueForValidation } from './car-brand-value.js'
import {
getFieldTypeStrategy,
resolveSubformChildValidationValue
} from './field-types/registry.js'
import {
hasPlanImportDateMarker
} from './plan-import-date-value.js'
function hasMeaningfulRowValue(value) {
return value !== undefined && value !== null && value !== ''
}
export function resolveSubformChildValue(child, row, rowField) {
if (child?.type === 'carBrandSelect') {
return resolveCarBrandValueForValidation(rowField, child.key, row?.[child.key])
}
if (getFieldTypeStrategy(child?.type)?.resolveValidationValue) {
return resolveSubformChildValidationValue(child, rowField, row?.[child.key])
}
const isDateField = child?.type === 'date' || child?.type === 'datetime'
if (isDateField) {
if (rowField && hasPlanImportDateMarker(rowField.value)) {
return rowField.value
}
const rowMapVal = row?.[child.key]
if (hasPlanImportDateMarker(rowMapVal)) {
return rowMapVal
}
const metaVal = rowField?.[child.key]
if (hasPlanImportDateMarker(metaVal)) {
return metaVal
}
}
if (rowField && hasMeaningfulRowValue(rowField.value)) {
return rowField.value
}
return row?.[child.key]
}
/** 模板驱动的 subform 重复值校验。 */
import {
getVisibleList,
getVisibleGroupChildFields,
resolveEffectiveRowFields
} from './visibility.js'
import { getSubformRowTemplate } from './field-types.js'
import { buildGroupErrorKey, getGroupRows } from './group-values.js'
import { resolveSubformChildValue } from './subform-child-validation-value.js'
export function normalizeDuplicateValue(value) {
if (value === undefined || value === null) return null
if (typeof value === 'string') {
const normalized = value.trim()
return normalized === '' ? null : normalized
}
if (Array.isArray(value)) {
return value.length ? JSON.stringify(value) : null
}
if (typeof value === 'object') {
return JSON.stringify(value)
}
return String(value)
}
function resolveDuplicateKeys(group = {}) {
if (!Array.isArray(group.validateDuplicates)) return []
const childKeys = new Set(getSubformRowTemplate(group).map(child => child.key))
return group.validateDuplicates.filter(
key => typeof key === 'string' && key !== '' && childKeys.has(key)
)
}
function findDuplicateRowIndexes(group, child, list, ctx, values, groupRowsCache) {
const rows = getGroupRows(values, group.key)
const rowFieldsList = groupRowsCache[group.key] || []
const rowCount = Math.max(rows.length, rowFieldsList.length)
const indexesByValue = new Map()
for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {
const row = rows[rowIndex] || {}
const rowFields = rowFieldsList[rowIndex] || []
const effectiveRowFields = resolveEffectiveRowFields(group, rowFields, row)
const visibleKeys = new Set(
getVisibleGroupChildFields(
group,
ctx,
values,
list,
effectiveRowFields,
row
).map(field => field.key)
)
if (!visibleKeys.has(child.key)) continue
const rowField = effectiveRowFields.find(field => field.key === child.key)
const normalized = normalizeDuplicateValue(
resolveSubformChildValue(child, row, rowField)
)
if (normalized === null) continue
const indexes = indexesByValue.get(normalized) || []
indexes.push(rowIndex)
indexesByValue.set(normalized, indexes)
}
return [...indexesByValue.values()]
.filter(indexes => indexes.length > 1)
.flat()
.sort((left, right) => left - right)
}
/**
* @returns {{ ok: boolean, errors: Array, errorMap: object }}
*/
export function validateSubformDuplicates(
list = [],
ctx = {},
values = {},
groupRowsCache = {}
) {
const visibleGroups = getVisibleList(list, ctx, values).filter(
field => field.type === 'subform'
)
for (const group of visibleGroups) {
const children = getSubformRowTemplate(group)
for (const childKey of resolveDuplicateKeys(group)) {
const child = children.find(field => field.key === childKey)
if (!child) continue
const rowIndexes = findDuplicateRowIndexes(
group,
child,
list,
ctx,
values,
groupRowsCache
)
if (!rowIndexes.length) continue
const rowNumbers = rowIndexes.map(index => index + 1)
const message = `第${rowNumbers.join(',')}行${child.label}重复`
const errorMap = {}
rowIndexes.forEach(rowIndex => {
errorMap[buildGroupErrorKey(group.key, rowIndex, child.key)] = message
})
const firstRowIndex = rowIndexes[0]
return {
ok: false,
errors: [{
key: buildGroupErrorKey(group.key, firstRowIndex, child.key),
label: `${group.label} 第${firstRowIndex + 1}行 ${child.label}`,
message,
groupKey: group.key,
rowIndex: firstRowIndex,
childKey: child.key
}],
errorMap
}
}
}
return { ok: true, errors: [], errorMap: {} }
}
......@@ -6,7 +6,7 @@ import {
resolveEffectiveRowFields
} from './visibility.js'
import { buildGroupErrorKey, getGroupRows } from './group-values.js'
import { isCarBrandComplete, resolveCarBrandValueForValidation } from './car-brand-value.js'
import { isCarBrandComplete } from './car-brand-value.js'
import {
resolveNumberInputMaxLength,
isNonNegativeIntegerInput,
......@@ -14,9 +14,7 @@ import {
} from './field-input-limits.js'
import { coerceSelectValue } from './select-value.js'
import {
getFieldTypeStrategy,
validateFieldByTypeStrategy,
resolveSubformChildValidationValue
validateFieldByTypeStrategy
} from './field-types/registry.js'
import { parseDateTimeLocal, resolveNotAfterNow } from './datetime-picker-mode.js'
import {
......@@ -32,6 +30,7 @@ import {
VIN_API_FAIL_MSG
} from './field-format-rules.js'
import { resolveSubformMaxRows } from './subform-limits.js'
import { resolveSubformChildValue } from './subform-child-validation-value.js'
function isEmptyValue(value) {
if (value === undefined || value === null) {
......@@ -56,38 +55,6 @@ function parseFieldDate(value) {
return Number.isNaN(date.getTime()) ? null : date
}
function hasMeaningfulRowValue(value) {
return value !== undefined && value !== null && value !== ''
}
/** subform 单元格校验取值(App 双 key / carBrand 优先 meta) */
function resolveSubformChildValue(child, row, rowField) {
if (child?.type === 'carBrandSelect') {
return resolveCarBrandValueForValidation(rowField, child.key, row?.[child.key])
}
if (getFieldTypeStrategy(child?.type)?.resolveValidationValue) {
return resolveSubformChildValidationValue(child, rowField, row?.[child.key])
}
const isDateField = child?.type === 'date' || child?.type === 'datetime'
if (isDateField) {
if (rowField && hasPlanImportDateMarker(rowField.value)) {
return rowField.value
}
const rowMapVal = row?.[child.key]
if (hasPlanImportDateMarker(rowMapVal)) {
return rowMapVal
}
const metaVal = rowField?.[child.key]
if (hasPlanImportDateMarker(metaVal)) {
return metaVal
}
}
if (rowField && hasMeaningfulRowValue(rowField.value)) {
return rowField.value
}
return row?.[child.key]
}
function appendVinApiError(field, value, errors, vinApiValidMap, errorKey) {
if (!isVinScanField(field) || !shouldCheckVinApi(value)) {
return
......
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { validateSubformDuplicates } from '../form-engine/subform-duplicate-validation.js'
function buildGroup(overrides = {}) {
return {
key: 'G1',
type: 'subform',
label: '客户',
validateDuplicates: ['name', 'phone'],
children: [[
{ key: 'name', type: 'input', label: '姓名', sortNum: '1' },
{ key: 'phone', type: 'phoneInput', label: '客户手机号', sortNum: '2' }
]],
...overrides
}
}
describe('subform template duplicate validation', () => {
it('IT-SUBFORM-DUP-001: reports only the first configured duplicate field and trims strings', () => {
const group = buildGroup()
const result = validateSubformDuplicates([group], {}, {
G1: [
{ name: '张三', phone: '13800138000' },
{ name: '', phone: '13900139000' },
{ name: ' 张三 ', phone: '13800138000' },
{ name: '李四', phone: '13900139000' }
]
})
assert.equal(result.ok, false)
assert.equal(result.errors.length, 1)
assert.deepEqual(result.errors[0], {
key: 'G1__0__name',
label: '客户 第1行 姓名',
message: '第1,3行姓名重复',
groupKey: 'G1',
rowIndex: 0,
childKey: 'name'
})
assert.deepEqual(result.errorMap, {
G1__0__name: '第1,3行姓名重复',
G1__2__name: '第1,3行姓名重复'
})
})
it('IT-SUBFORM-DUP-002: aggregates every row involved in any duplicate value', () => {
const group = buildGroup({ validateDuplicates: ['phone'] })
const result = validateSubformDuplicates([group], {}, {
G1: [
{ phone: '13800138000' },
{ phone: '13900139000' },
{ phone: '13800138000' },
{ phone: '13900139000' },
{ phone: null },
{ phone: ' ' }
]
})
assert.equal(result.errors[0].message, '第1,2,3,4行客户手机号重复')
assert.deepEqual(Object.keys(result.errorMap), [
'G1__0__phone',
'G1__1__phone',
'G1__2__phone',
'G1__3__phone'
])
})
it('IT-SUBFORM-DUP-003: ignores empty, malformed and missing child configurations', () => {
const rows = { G1: [{ phone: '1' }, { phone: '1' }] }
for (const validateDuplicates of [undefined, [], [null, 7, 'missing']]) {
const result = validateSubformDuplicates(
[buildGroup({ validateDuplicates })],
{},
rows
)
assert.deepEqual(result, { ok: true, errors: [], errorMap: {} })
}
})
it('IT-SUBFORM-DUP-004: uses App row field display values when value maps contain ids', () => {
const group = buildGroup({ validateDuplicates: ['phone'] })
const values = {
G1: [{ phone: 'phone-id-a' }, { phone: 'phone-id-b' }]
}
const groupRowsCache = {
G1: [
[{ key: 'phone', type: 'phoneInput', label: '客户手机号', value: '13800138000', phone: 'phone-id-a' }],
[{ key: 'phone', type: 'phoneInput', label: '客户手机号', value: '13800138000', phone: 'phone-id-b' }]
]
}
const result = validateSubformDuplicates([group], {}, values, groupRowsCache)
assert.equal(result.errors[0].message, '第1,2行客户手机号重复')
})
it('IT-SUBFORM-DUP-005: ignores a duplicate target hidden by template visibility', () => {
const group = buildGroup({
validateDuplicates: ['phone'],
children: [[
{ key: 'phone', type: 'phoneInput', label: '客户手机号', baseSceneCode: [100101] }
]]
})
const result = validateSubformDuplicates(
[group],
{ sceneList: [{ baseSceneCode: 110101 }] },
{ G1: [{ phone: '13800138000' }, { phone: '13800138000' }] }
)
assert.deepEqual(result, { ok: true, errors: [], errorMap: {} })
})
})
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!