Commit 072ecfe0 by 张立顺

feat: 门店日报按模板拦截重复手机号

1 parent 251b3ce0
...@@ -21,6 +21,7 @@ import { ...@@ -21,6 +21,7 @@ import {
} from './values.js' } from './values.js'
import { assertEngineSubformsAligned } from './subform-invariants.js' import { assertEngineSubformsAligned } from './subform-invariants.js'
import { validateForm } from './validator.js' import { validateForm } from './validator.js'
import { validateSubformDuplicates } from './subform-duplicate-validation.js'
import { import {
getGroupRows, getGroupRows,
setGroupFieldValue, setGroupFieldValue,
...@@ -395,6 +396,11 @@ export function createFormEngine(schemaRoot = {}) { ...@@ -395,6 +396,11 @@ export function createFormEngine(schemaRoot = {}) {
values = syncSubformValuesFromCache(values, groupRowsCache, list, pageContext) values = syncSubformValuesFromCache(values, groupRowsCache, list, pageContext)
applyVisibilityClearing() applyVisibilityClearing()
}, },
/** @returns {{ ok: boolean, errors: Array, errorMap: object }} 仅执行模板重复校验 */
validateDuplicates() {
this.prepareForSubmit()
return validateSubformDuplicates(list, pageContext, values, groupRowsCache)
},
/** @returns {{ ok: boolean, errors: Array, errorMap: object }} 校验结果 */ /** @returns {{ ok: boolean, errors: Array, errorMap: object }} 校验结果 */
validate(options = {}) { validate(options = {}) {
this.prepareForSubmit() this.prepareForSubmit()
......
...@@ -31,6 +31,7 @@ import { ...@@ -31,6 +31,7 @@ import {
} from './field-format-rules.js' } from './field-format-rules.js'
import { resolveSubformMaxRows } from './subform-limits.js' import { resolveSubformMaxRows } from './subform-limits.js'
import { resolveSubformChildValue } from './subform-child-validation-value.js' import { resolveSubformChildValue } from './subform-child-validation-value.js'
import { validateSubformDuplicates } from './subform-duplicate-validation.js'
function isEmptyValue(value) { function isEmptyValue(value) {
if (value === undefined || value === null) { if (value === undefined || value === null) {
...@@ -197,8 +198,14 @@ function validateField(field, value, options = {}) { ...@@ -197,8 +198,14 @@ function validateField(field, value, options = {}) {
/** 校验可见固定字段与 subform 行内字段 /** 校验可见固定字段与 subform 行内字段
* @returns {{ ok: boolean, errors: Array, errorMap: object }} */ * @returns {{ ok: boolean, errors: Array, errorMap: object }} */
export function validateForm(list = [], ctx, values, groupRowsCache = {}, options = {}) { export function validateForm(list = [], ctx, values, groupRowsCache = {}, options = {}) {
const errors = [] const duplicateValidation = validateSubformDuplicates(
const errorMap = {} list,
ctx,
values,
groupRowsCache
)
const errors = [...duplicateValidation.errors]
const errorMap = { ...duplicateValidation.errorMap }
const visibleList = getVisibleList(list, ctx, values) const visibleList = getVisibleList(list, ctx, values)
getVisibleLeafFields(list, ctx, values).forEach(field => { getVisibleLeafFields(list, ctx, values).forEach(field => {
...@@ -207,7 +214,9 @@ export function validateForm(list = [], ctx, values, groupRowsCache = {}, option ...@@ -207,7 +214,9 @@ export function validateForm(list = [], ctx, values, groupRowsCache = {}, option
errorKey: field.key errorKey: field.key
}) })
if (fieldErrors.length) { if (fieldErrors.length) {
errorMap[field.key] = fieldErrors[0] if (!(field.key in errorMap)) {
errorMap[field.key] = fieldErrors[0]
}
errors.push({ errors.push({
key: field.key, key: field.key,
label: field.label, label: field.label,
...@@ -262,7 +271,9 @@ export function validateForm(list = [], ctx, values, groupRowsCache = {}, option ...@@ -262,7 +271,9 @@ export function validateForm(list = [], ctx, values, groupRowsCache = {}, option
errorKey errorKey
}) })
if (fieldErrors.length) { if (fieldErrors.length) {
errorMap[errorKey] = fieldErrors[0] if (!(errorKey in errorMap)) {
errorMap[errorKey] = fieldErrors[0]
}
errors.push({ errors.push({
key: errorKey, key: errorKey,
label: `${group.label} 第${rowIndex + 1}行 ${child.label}`, label: `${group.label} 第${rowIndex + 1}行 ${child.label}`,
......
...@@ -64,7 +64,6 @@ const { ...@@ -64,7 +64,6 @@ const {
decorateStoreDailyWeekDays decorateStoreDailyWeekDays
} = require('../../utils/store-daily-report-state.js') } = require('../../utils/store-daily-report-state.js')
const { const {
findDuplicateStoreDailyPhoneRows,
buildStoreDailySaveThrottleKey, buildStoreDailySaveThrottleKey,
isStoreDailySaveThrottled, isStoreDailySaveThrottled,
normalizeStoreDailyRecordId, normalizeStoreDailyRecordId,
...@@ -368,10 +367,12 @@ Page({ ...@@ -368,10 +367,12 @@ Page({
/** 校验失败时定位到首个出错 subform 行 */ /** 校验失败时定位到首个出错 subform 行 */
buildGroupActiveIndexFromErrors(errorMap = {}) { buildGroupActiveIndexFromErrors(errorMap = {}) {
const map = this.getGroupActiveIndexMap() const map = this.getGroupActiveIndexMap()
const locatedGroups = new Set()
Object.keys(errorMap).forEach(errorKey => { Object.keys(errorMap).forEach(errorKey => {
const parsed = parseGroupErrorKey(errorKey) const parsed = parseGroupErrorKey(errorKey)
if (parsed) { if (parsed && !locatedGroups.has(parsed.groupKey)) {
map[parsed.groupKey] = parsed.rowIndex map[parsed.groupKey] = parsed.rowIndex
locatedGroups.add(parsed.groupKey)
} }
}) })
return map return map
...@@ -988,6 +989,22 @@ Page({ ...@@ -988,6 +989,22 @@ Page({
return true return true
}, },
/** 模板声明的 subform 重复值预检;失败时标红、定位并 Toast。 */
validateFormDuplicates() {
if (!this.engine) return false
if (typeof this.engine.validateDuplicates !== 'function') return true
const validation = this.engine.validateDuplicates()
if (validation.ok) return true
this.applyEngineView(this.engine.getViewState(), {
errors: validation.errorMap,
structureChanged: true,
groupActiveIndex: this.buildGroupActiveIndexFromErrors(validation.errorMap)
})
const firstError = Array.isArray(validation.errors) ? validation.errors[0] : null
wx.$util.showToast(firstError?.message || '子表单存在重复数据')
return false
},
/** 打开 VIN OCR,并保留 subform 行上下文。 */ /** 打开 VIN OCR,并保留 subform 行上下文。 */
openVinOcrForField({ childKey, groupKey, rowIndex } = {}) { openVinOcrForField({ childKey, groupKey, rowIndex } = {}) {
if (this.data.formDisabled || this.data.writeInProgress || !childKey) return if (this.data.formDisabled || this.data.writeInProgress || !childKey) return
...@@ -1231,13 +1248,7 @@ Page({ ...@@ -1231,13 +1248,7 @@ Page({
wx.$util.showToast('操作过于频繁,请稍后再试') wx.$util.showToast('操作过于频繁,请稍后再试')
return return
} }
const duplicateRows = findDuplicateStoreDailyPhoneRows( if (!this.validateFormDuplicates()) return
writeContext.engine.getViewState().values
)
if (duplicateRows.length) {
wx.$util.showToast(`第${duplicateRows.join(',')}行客户手机号重复`)
return
}
this._savingDraft = true this._savingDraft = true
this.data.writeInProgress = true this.data.writeInProgress = true
this.setData({ writeInProgress: true }) this.setData({ writeInProgress: true })
......
...@@ -130,6 +130,58 @@ describe('form-engine visibility', async () => { ...@@ -130,6 +130,58 @@ describe('form-engine visibility', async () => {
}) })
}) })
describe('form-engine template duplicate validation', async () => {
const { createFormEngine } = await import('../form-engine/core.js')
const schema = {
version: 'test',
list: [{
key: 'G1',
type: 'subform',
label: '客户',
validateDuplicates: ['phone'],
children: [[{
key: 'phone',
type: 'phoneInput',
label: '客户手机号',
required: true
}]]
}]
}
it('IT-GROUP-DUP-001: exposes duplicate-only preflight after synchronizing subform rows', () => {
const engine = createFormEngine()
engine.init(schema, {
initialValues: {
G1: [
{ phone: '13800138000' },
{ phone: '13800138000' }
]
}
})
const result = engine.validateDuplicates()
assert.equal(result.ok, false)
assert.equal(result.errors[0].message, '第1,2行客户手机号重复')
})
it('IT-GROUP-DUP-002: full validation reports template duplicate error before field errors', () => {
const engine = createFormEngine()
engine.init(schema, {
initialValues: {
G1: [
{ phone: '123' },
{ phone: '123' }
]
}
})
const result = engine.validate()
assert.equal(result.ok, false)
assert.equal(result.errors[0].message, '第1,2行客户手机号重复')
assert.equal(result.errorMap.G1__0__phone, '第1,2行客户手机号重复')
})
})
describe('form-engine validator', async () => { describe('form-engine validator', async () => {
const { createFormEngine } = await import('../form-engine/core.js') const { createFormEngine } = await import('../form-engine/core.js')
const schema = loadSchemaFixture('staff') const schema = loadSchemaFixture('staff')
......
...@@ -4,7 +4,6 @@ import { createRequire } from 'node:module' ...@@ -4,7 +4,6 @@ import { createRequire } from 'node:module'
const require = createRequire(import.meta.url) const require = createRequire(import.meta.url)
const { const {
findDuplicateStoreDailyPhoneRows,
buildStoreDailySaveThrottleKey, buildStoreDailySaveThrottleKey,
isStoreDailySaveThrottled, isStoreDailySaveThrottled,
resolveStoreDailyRecordId, resolveStoreDailyRecordId,
...@@ -15,20 +14,6 @@ const { ...@@ -15,20 +14,6 @@ const {
} = require('../utils/store-daily-save-guards.js') } = require('../utils/store-daily-save-guards.js')
describe('store-daily-save-guards', () => { describe('store-daily-save-guards', () => {
it('IT-STORE-SAVE-GUARD-001: returns every row number that shares a non-empty customer phone', () => {
assert.deepEqual(
findDuplicateStoreDailyPhoneRows({
'F2-107': [
{ 'F2-107-2': '13800138000' },
{ 'F2-107-2': '' },
{ 'F2-107-2': ' 13800138000 ' },
{ 'F2-107-2': '13900139000' }
]
}),
[1, 3]
)
})
it('IT-STORE-SAVE-GUARD-002: blocks saves for the first minute after a prior save', () => { it('IT-STORE-SAVE-GUARD-002: blocks saves for the first minute after a prior save', () => {
assert.equal(isStoreDailySaveThrottled(1_000, 60_999), true) assert.equal(isStoreDailySaveThrottled(1_000, 60_999), true)
assert.equal(isStoreDailySaveThrottled(1_000, 61_000), false) assert.equal(isStoreDailySaveThrottled(1_000, 61_000), false)
......
...@@ -31,6 +31,14 @@ function createStorePageHarness(overrides = {}) { ...@@ -31,6 +31,14 @@ function createStorePageHarness(overrides = {}) {
resolveMerchantId: value => value resolveMerchantId: value => value
} }
const modules = { const modules = {
'../../form-engine/group-values.js': {
parseGroupErrorKey(errorKey = '') {
const match = String(errorKey).match(/^(.+)__(\d+)__(.+)$/)
return match
? { groupKey: match[1], rowIndex: Number(match[2]), childKey: match[3] }
: null
}
},
'../../services/carBrandPickerBridge.js': carBrandPickerBridge, '../../services/carBrandPickerBridge.js': carBrandPickerBridge,
'../../services/vinOcrBridge.js': { '../../services/vinOcrBridge.js': {
clearPending() { clearPending() {
...@@ -188,6 +196,53 @@ describe('storeDailyReport page contract', () => { ...@@ -188,6 +196,53 @@ describe('storeDailyReport page contract', () => {
assert.match(js, /if \(this\._savingDraft \|\| this\._pushing\) return/) assert.match(js, /if \(this\._savingDraft \|\| this\._pushing\) return/)
}) })
it('IT-STORE-DAILY-PAGE-DUP-001: duplicate template preflight runs before VIN and replaces the fixed phone helper', () => {
const saveSource = js.slice(js.indexOf('async onSave()'), js.indexOf('\n\t/** @deprecated', js.indexOf('async onSave()')))
assert.match(saveSource, /validateFormDuplicates\(\)/)
assert.ok(
saveSource.indexOf('validateFormDuplicates()') <
saveSource.indexOf('flushAllVinApiValidation()')
)
assert.doesNotMatch(js, /findDuplicateStoreDailyPhoneRows/)
})
it('IT-STORE-DAILY-PAGE-DUP-002: duplicate preflight applies every row error and focuses the first duplicate row', () => {
let toastMessage = ''
let appliedExtra
const { page } = createStorePageHarness({
wx: {
$util: {
showToast(message) {
toastMessage = message
}
}
}
})
page.data.groupActiveIndex = { G1: 4 }
page.engine = {
validateDuplicates: () => ({
ok: false,
errors: [{ message: '第1,3行客户手机号重复' }],
errorMap: {
G1__0__phone: '第1,3行客户手机号重复',
G1__2__phone: '第1,3行客户手机号重复'
}
}),
getViewState: () => ({ values: {}, groupRowsCache: {} })
}
page.applyEngineView = (_viewState, extra) => {
appliedExtra = extra
}
assert.equal(page.validateFormDuplicates(), false)
assert.equal(toastMessage, '第1,3行客户手机号重复')
assert.deepEqual(appliedExtra.errors, {
G1__0__phone: '第1,3行客户手机号重复',
G1__2__phone: '第1,3行客户手机号重复'
})
assert.equal(appliedExtra.groupActiveIndex.G1, 0)
})
it('IT-STORE-DAILY-PAGE-006: synchronizes field-level disabled state after edit changes', () => { it('IT-STORE-DAILY-PAGE-006: synchronizes field-level disabled state after edit changes', () => {
const editSource = js.slice(js.indexOf('\n\teditReport()'), js.indexOf('\n\t/**', js.indexOf('\n\teditReport()') + 1)) const editSource = js.slice(js.indexOf('\n\teditReport()'), js.indexOf('\n\t/**', js.indexOf('\n\teditReport()') + 1))
const exitSource = js.slice(js.indexOf('\n\texitEditMode()'), js.indexOf('\n\t/**', js.indexOf('\n\texitEditMode()') + 1)) const exitSource = js.slice(js.indexOf('\n\texitEditMode()'), js.indexOf('\n\t/**', js.indexOf('\n\texitEditMode()') + 1))
......
...@@ -18,20 +18,6 @@ function hasStoreDailyRecordIdConflict(baseId, latestId) { ...@@ -18,20 +18,6 @@ function hasStoreDailyRecordIdConflict(baseId, latestId) {
return normalizeStoreDailyRecordId(baseId) !== normalizeStoreDailyRecordId(latestId) return normalizeStoreDailyRecordId(baseId) !== normalizeStoreDailyRecordId(latestId)
} }
function findDuplicateStoreDailyPhoneRows(values = {}) {
const rows = Array.isArray(values['F2-107']) ? values['F2-107'] : []
const indexesByPhone = new Map()
rows.forEach((row, index) => {
const phone = String(row?.['F2-107-2'] ?? '').trim()
if (!phone) return
indexesByPhone.set(phone, [...(indexesByPhone.get(phone) || []), index + 1])
})
return [...indexesByPhone.values()]
.filter(indexes => indexes.length > 1)
.flat()
.sort((left, right) => left - right)
}
function buildStoreDailySaveThrottleKey({ merchantId, reportDate, staffUuid } = {}) { function buildStoreDailySaveThrottleKey({ merchantId, reportDate, staffUuid } = {}) {
return `store-daily-save:${merchantId ?? ''}:${reportDate ?? ''}:${staffUuid ?? ''}` return `store-daily-save:${merchantId ?? ''}:${reportDate ?? ''}:${staffUuid ?? ''}`
} }
...@@ -53,7 +39,6 @@ function mergeStoreDailySubmissionState(captured = {}, latest = {}) { ...@@ -53,7 +39,6 @@ function mergeStoreDailySubmissionState(captured = {}, latest = {}) {
} }
module.exports = { module.exports = {
findDuplicateStoreDailyPhoneRows,
buildStoreDailySaveThrottleKey, buildStoreDailySaveThrottleKey,
isStoreDailySaveThrottled, isStoreDailySaveThrottled,
resolveStoreDailyRecordId, resolveStoreDailyRecordId,
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!