Commit 072ecfe0 by 张立顺

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

1 parent 251b3ce0
......@@ -21,6 +21,7 @@ import {
} from './values.js'
import { assertEngineSubformsAligned } from './subform-invariants.js'
import { validateForm } from './validator.js'
import { validateSubformDuplicates } from './subform-duplicate-validation.js'
import {
getGroupRows,
setGroupFieldValue,
......@@ -395,6 +396,11 @@ export function createFormEngine(schemaRoot = {}) {
values = syncSubformValuesFromCache(values, groupRowsCache, list, pageContext)
applyVisibilityClearing()
},
/** @returns {{ ok: boolean, errors: Array, errorMap: object }} 仅执行模板重复校验 */
validateDuplicates() {
this.prepareForSubmit()
return validateSubformDuplicates(list, pageContext, values, groupRowsCache)
},
/** @returns {{ ok: boolean, errors: Array, errorMap: object }} 校验结果 */
validate(options = {}) {
this.prepareForSubmit()
......
......@@ -31,6 +31,7 @@ import {
} from './field-format-rules.js'
import { resolveSubformMaxRows } from './subform-limits.js'
import { resolveSubformChildValue } from './subform-child-validation-value.js'
import { validateSubformDuplicates } from './subform-duplicate-validation.js'
function isEmptyValue(value) {
if (value === undefined || value === null) {
......@@ -197,8 +198,14 @@ function validateField(field, value, options = {}) {
/** 校验可见固定字段与 subform 行内字段
* @returns {{ ok: boolean, errors: Array, errorMap: object }} */
export function validateForm(list = [], ctx, values, groupRowsCache = {}, options = {}) {
const errors = []
const errorMap = {}
const duplicateValidation = validateSubformDuplicates(
list,
ctx,
values,
groupRowsCache
)
const errors = [...duplicateValidation.errors]
const errorMap = { ...duplicateValidation.errorMap }
const visibleList = getVisibleList(list, ctx, values)
getVisibleLeafFields(list, ctx, values).forEach(field => {
......@@ -207,7 +214,9 @@ export function validateForm(list = [], ctx, values, groupRowsCache = {}, option
errorKey: field.key
})
if (fieldErrors.length) {
errorMap[field.key] = fieldErrors[0]
if (!(field.key in errorMap)) {
errorMap[field.key] = fieldErrors[0]
}
errors.push({
key: field.key,
label: field.label,
......@@ -262,7 +271,9 @@ export function validateForm(list = [], ctx, values, groupRowsCache = {}, option
errorKey
})
if (fieldErrors.length) {
errorMap[errorKey] = fieldErrors[0]
if (!(errorKey in errorMap)) {
errorMap[errorKey] = fieldErrors[0]
}
errors.push({
key: errorKey,
label: `${group.label} 第${rowIndex + 1}行 ${child.label}`,
......
......@@ -64,7 +64,6 @@ const {
decorateStoreDailyWeekDays
} = require('../../utils/store-daily-report-state.js')
const {
findDuplicateStoreDailyPhoneRows,
buildStoreDailySaveThrottleKey,
isStoreDailySaveThrottled,
normalizeStoreDailyRecordId,
......@@ -368,10 +367,12 @@ Page({
/** 校验失败时定位到首个出错 subform 行 */
buildGroupActiveIndexFromErrors(errorMap = {}) {
const map = this.getGroupActiveIndexMap()
const locatedGroups = new Set()
Object.keys(errorMap).forEach(errorKey => {
const parsed = parseGroupErrorKey(errorKey)
if (parsed) {
if (parsed && !locatedGroups.has(parsed.groupKey)) {
map[parsed.groupKey] = parsed.rowIndex
locatedGroups.add(parsed.groupKey)
}
})
return map
......@@ -988,6 +989,22 @@ Page({
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 行上下文。 */
openVinOcrForField({ childKey, groupKey, rowIndex } = {}) {
if (this.data.formDisabled || this.data.writeInProgress || !childKey) return
......@@ -1231,13 +1248,7 @@ Page({
wx.$util.showToast('操作过于频繁,请稍后再试')
return
}
const duplicateRows = findDuplicateStoreDailyPhoneRows(
writeContext.engine.getViewState().values
)
if (duplicateRows.length) {
wx.$util.showToast(`第${duplicateRows.join(',')}行客户手机号重复`)
return
}
if (!this.validateFormDuplicates()) return
this._savingDraft = true
this.data.writeInProgress = true
this.setData({ writeInProgress: true })
......
......@@ -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 () => {
const { createFormEngine } = await import('../form-engine/core.js')
const schema = loadSchemaFixture('staff')
......
......@@ -4,7 +4,6 @@ import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)
const {
findDuplicateStoreDailyPhoneRows,
buildStoreDailySaveThrottleKey,
isStoreDailySaveThrottled,
resolveStoreDailyRecordId,
......@@ -15,20 +14,6 @@ const {
} = require('../utils/store-daily-save-guards.js')
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', () => {
assert.equal(isStoreDailySaveThrottled(1_000, 60_999), true)
assert.equal(isStoreDailySaveThrottled(1_000, 61_000), false)
......
......@@ -31,6 +31,14 @@ function createStorePageHarness(overrides = {}) {
resolveMerchantId: value => value
}
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/vinOcrBridge.js': {
clearPending() {
......@@ -188,6 +196,53 @@ describe('storeDailyReport page contract', () => {
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', () => {
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))
......
......@@ -18,20 +18,6 @@ function hasStoreDailyRecordIdConflict(baseId, 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 } = {}) {
return `store-daily-save:${merchantId ?? ''}:${reportDate ?? ''}:${staffUuid ?? ''}`
}
......@@ -53,7 +39,6 @@ function mergeStoreDailySubmissionState(captured = {}, latest = {}) {
}
module.exports = {
findDuplicateStoreDailyPhoneRows,
buildStoreDailySaveThrottleKey,
isStoreDailySaveThrottled,
resolveStoreDailyRecordId,
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!