Commit c513c02c by 张立顺

feat 洽谈bug修复

1 parent e33f7c5d
# DEVLOG — packageDynamicForm
## 2026-06-04 — 洽谈明细 (轻改) 提交卡住修复
- **现象**:F3-4 填完后点击提交,仅 Toast「校验成功/通过」(车架号 API),无 Loading、未调 `dynamic.save`。
- **根因**:`flushAllVinApiValidation` 走 `validateVin` 防抖,并发时旧 Promise 悬挂;`vinApiValidMap` 依赖 `setData` 异步;提交前 `validate`/`applyEngineView` 无 try/catch。
- **修复**:`validateVinImmediate`(静默、无防抖)+ `buildVinApiValidMapFromEntries`;`flush` 返回内存 map;`submit` 提前 Loading + try/catch;`engine.prepareForSubmit`;防抖取消时 reject `cancelled`。
- **单测**:`IT-VIN-FLUSH-001`~`003`、`IT-NEG-016`。
## 2026-06-04 — 洽谈明细多 subform 提交校验误报修复
- **现象**:仅填岚图 (F3-1) 可提交;再填问界鸿蒙 (F3-2) 时 Toast「必填不能为空」且不调用 `dynamic.save`,界面无红字(尤其「是否成交=否」)。
......
......@@ -141,7 +141,7 @@ schema 子字段 `type: input` + `prefixComponent: 'scan'` 时,`form-field-inp
| 识别页 | [`tabWorkOrder/pages/ocr/ocr`](../../tabWorkOrder/pages/ocr/ocr.js)(不修改) |
| 回写 | 上一页 `reWrite` → `applyVinOcrResult` → `engine.setGroupFieldValue`(与车型选择同路径);`wx.nextTick` + `onShow` 延迟刷视图 |
| 上下文 | [`resolveVinFieldContext`](../services/vin-ocr-context.js) 推断 `groupKey`(如 `F3-1-7`→`F3-1`)、补全 `rowIndex`(含第 0 行);模块 `pending` + page `_vinOcrCtx` |
| 校验 | `validateVin` / `dj.pad.api.vin.validate` **仅校验与 toast,不写表单**;回显必须在 OCR 回写阶段完成 |
| 校验 | 失焦/OCR:`validateVin`(防抖 + 可 toast);**提交前**:`validateVinImmediate`(静默、无防抖)+ `flushAllVinApiValidation` 返回内存 `vinApiValidMap` 再 `engine.validate`;`validateVin` 防抖被取消时会 `reject({ cancelled: true })`,避免 `Promise.all` 悬挂 |
洽谈页:[`negotiationDetail.js`](../pages/negotiationDetail/negotiationDetail.js) 提供 `openVinOcrForField` / `reWrite`。
......
......@@ -327,10 +327,15 @@ export function createFormEngine(schemaRoot = {}) {
getViewState() {
return getViewState()
},
/** @returns {{ ok: boolean, errors: Array, errorMap: object }} 校验结果 */
validate(options = {}) {
/** 提交/校验前:repair cache 并写回 values */
prepareForSubmit() {
groupRowsCache = repairGroupRowsCacheFromValues(list, values, groupRowsCache)
values = syncSubformValuesFromCache(values, groupRowsCache, list, pageContext)
values = clearHiddenFieldValues(list, pageContext, values)
},
/** @returns {{ ok: boolean, errors: Array, errorMap: object }} 校验结果 */
validate(options = {}) {
this.prepareForSubmit()
return validateForm(list, pageContext, values, groupRowsCache, options)
},
/** @returns {object} schema 元信息(version、formCode、title) */
......
......@@ -14,6 +14,11 @@ export function shouldRunVinApiValidate(vin) {
return str.length === 17
}
function resolveVinApiValid(result) {
const valid = result?.data?.data?.valid
return { ok: true, valid: valid !== false }
}
/**
* @param {string} vin
* @param {Function} validateVinFn - utils/vinVaildate.validateVin
......@@ -28,17 +33,103 @@ export async function runVinApiValidate(vin, validateVinFn) {
}
try {
const result = await validateVinFn(vin)
const valid = result?.data?.data?.valid
return { ok: true, valid: valid !== false }
return resolveVinApiValid(result)
} catch (err) {
if (err?.cancelled) {
return { ok: false, valid: false, cancelled: true }
}
return { ok: false, valid: false }
}
}
/**
* 提交前批量校验:无防抖,默认 silent
* @param {string} vin
* @param {Function} validateVinImmediateFn - utils/vinVaildate.validateVinImmediate
* @param {{ silent?: boolean }} [options]
* @returns {Promise<{ ok: boolean, valid: boolean }>}
*/
export async function runVinApiValidateImmediate(
vin,
validateVinImmediateFn,
options = {}
) {
if (!shouldRunVinApiValidate(vin)) {
return { ok: true, valid: true }
}
if (typeof validateVinImmediateFn !== 'function') {
return { ok: false, valid: false }
}
const silent = options.silent !== false
try {
const result = await validateVinImmediateFn(vin, { silent })
return resolveVinApiValid(result)
} catch {
return { ok: false, valid: false }
}
}
/**
* 从 groupRowsCache 收集需 API 校验的 VIN 单元格
* @returns {Array<{ errorKey: string, vin: string }>}
*/
export function listVinScanCellsFromCache(groupRowsCache = {}, buildKey = buildVinErrorKey) {
const entries = []
Object.keys(groupRowsCache || {}).forEach(groupKey => {
;(groupRowsCache[groupKey] || []).forEach((rowFields, rowIndex) => {
;(rowFields || []).forEach(child => {
if (child?.type !== 'input' || child.prefixComponent !== 'scan') {
return
}
const vin = child.value
if (!shouldRunVinApiValidate(vin)) {
return
}
entries.push({
errorKey: buildKey({ groupKey, rowIndex, childKey: child.key }),
vin
})
})
})
})
return entries
}
/**
* 批量跑 VIN API 校验并返回 errorKey → 是否通过
* @param {Array<{ errorKey: string, vin: string }>} entries
* @param {Function} runOne - (vin) => Promise<{ ok, valid }>
* @returns {Promise<Record<string, boolean>>}
*/
export async function buildVinApiValidMapFromEntries(entries = [], runOne) {
const map = {}
if (!entries.length || typeof runOne !== 'function') {
return map
}
const results = await Promise.all(
entries.map(async entry => {
const { ok, valid, cancelled } = await runOne(entry.vin)
return {
errorKey: entry.errorKey,
passed: !cancelled && ok && valid
}
})
)
results.forEach(({ errorKey, passed }) => {
if (errorKey) {
map[errorKey] = passed
}
})
return map
}
export default {
buildVinErrorKey,
shouldRunVinApiValidate,
runVinApiValidate
runVinApiValidate,
runVinApiValidateImmediate,
listVinScanCellsFromCache,
buildVinApiValidMapFromEntries
}
if (typeof module !== 'undefined' && module.exports) {
......@@ -46,10 +137,16 @@ if (typeof module !== 'undefined' && module.exports) {
buildVinErrorKey,
shouldRunVinApiValidate,
runVinApiValidate,
runVinApiValidateImmediate,
listVinScanCellsFromCache,
buildVinApiValidMapFromEntries,
default: {
buildVinErrorKey,
shouldRunVinApiValidate,
runVinApiValidate
runVinApiValidate,
runVinApiValidateImmediate,
listVinScanCellsFromCache,
buildVinApiValidMapFromEntries
}
}
}
......@@ -24,7 +24,11 @@ const {
isNegotiationDealDateFieldKey
} = require('../../form-engine/select-complete-fun.js')
const { isOrderListField } = require('../../utils/order-list-params.js')
import { validateVin } from '~/utils/vinVaildate.js'
import {
validateVin,
validateVinImmediate,
cancelPendingVinDebounce
} from '~/utils/vinVaildate.js'
const {
isVinScanField,
validateVinSyncFormat,
......@@ -34,7 +38,10 @@ const {
const {
buildVinErrorKey,
shouldRunVinApiValidate,
runVinApiValidate
runVinApiValidate,
runVinApiValidateImmediate,
listVinScanCellsFromCache,
buildVinApiValidMapFromEntries
} = require('../../form-engine/vin-api-valid-tracker.js')
const dailyReportPage = require('../behaviors/dailyReportPage.js')
......@@ -495,28 +502,35 @@ Page({
if (!this.data.isTodayReport) {
return wx.$util.showToast('仅支持填写当天日报')
}
await this.flushAllVinApiValidation()
const validation = this.engine.validate({
vinApiValidMap: this.data.vinApiValidMap
})
if (!validation.ok) {
const firstErr = validation.errors[0]
this.applyEngineView(this.engine.getViewState(), {
errors: validation.errorMap,
structureChanged: false,
groupActiveIndex: this.buildGroupActiveIndexFromErrors(validation.errorMap)
})
return wx.$util.showToast(
firstErr?.message || firstErr?.label || '必填不能为空'
)
}
this.applyEngineView(this.engine.getViewState(), { errors: {}, structureChanged: false })
if (!this.reportTemplateId) {
return wx.$util.showToast('缺少报表模板,请联系运营配置')
}
this._submitting = true
wx.$util.showLoading()
try {
cancelPendingVinDebounce()
if (typeof this.engine.prepareForSubmit === 'function') {
this.engine.prepareForSubmit()
}
const { vinApiValidMap, vinApiFailures } = await this.flushAllVinApiValidation()
const validation = this.engine.validate({ vinApiValidMap })
if (!validation.ok) {
this.logSubmitValidationFailures({
vinApiFailures,
errors: validation.errors,
errorMap: validation.errorMap
})
const firstErr = validation.errors[0]
this.applyEngineView(this.engine.getViewState(), {
errors: validation.errorMap,
structureChanged: false,
groupActiveIndex: this.buildGroupActiveIndexFromErrors(validation.errorMap)
})
return wx.$util.showToast(
firstErr?.message || firstErr?.label || '必填不能为空'
)
}
this.applyEngineView(this.engine.getViewState(), { errors: {}, structureChanged: false })
if (!this.reportTemplateId) {
return wx.$util.showToast('缺少报表模板,请联系运营配置')
}
this._submitting = true
const res = await negotiationApi.submitForm({
engine: this.engine,
reportTemplateId: this.reportTemplateId,
......@@ -532,8 +546,8 @@ Page({
wx.$util.showToast('提交成功')
await this.refreshAfterSubmit()
} catch (error) {
console.error(error)
wx.$util.showToast('提交失败')
console.error('[negotiationDetail] submit', error)
wx.$util.showToast('提交失败,请重试')
} finally {
this._submitting = false
wx.$util.hideLoading()
......@@ -663,31 +677,55 @@ Page({
this.applyEngineView(viewState, extra)
},
/** 提交前补跑可见行内 17 位车架号的 API 校验 */
/** 提交校验未通过时输出失败项(控制台),供联调定位 */
logSubmitValidationFailures({ vinApiFailures = [], errors = [], errorMap = {} } = {}) {
const items = (errors || []).map(err => ({
key: err.key,
label: err.label,
message: err.message,
groupKey: err.groupKey,
rowIndex: err.rowIndex
}))
if (vinApiFailures.length) {
console.warn('[negotiationDetail] submit vin api failed', vinApiFailures)
}
if (items.length) {
console.warn('[negotiationDetail] submit validation failed', { items, errorMap })
}
},
/**
* 提交前补跑可见行内 17 位车架号的 API 校验(无防抖、静默,成功不 Toast)
* @returns {Promise<{ vinApiValidMap: Record<string, boolean>, vinApiFailures: Array }>}
*/
async flushAllVinApiValidation() {
if (!this.engine) return
const baseMap = { ...(this.data.vinApiValidMap || {}) }
if (!this.engine) {
return { vinApiValidMap: baseMap, vinApiFailures: [] }
}
const { groupRowsCache } = this.engine.getViewState()
const tasks = []
Object.keys(groupRowsCache || {}).forEach(groupKey => {
;(groupRowsCache[groupKey] || []).forEach((rowFields, rowIndex) => {
;(rowFields || []).forEach(child => {
if (child.type === 'input' && isVinScanField(child)) {
const vin = child.value
if (shouldRunVinApiValidate(vin)) {
tasks.push(
this.scheduleVinApiValidate({
childKey: child.key,
groupKey,
rowIndex,
vin
})
)
}
}
})
})
const entries = listVinScanCellsFromCache(groupRowsCache)
const built = await buildVinApiValidMapFromEntries(entries, vin =>
runVinApiValidateImmediate(vin, validateVinImmediate, { silent: true })
)
const vinApiValidMap = { ...baseMap, ...built }
const vinApiFailures = entries
.filter(entry => built[entry.errorKey] !== true)
.map(entry => ({
errorKey: entry.errorKey,
vin: entry.vin,
message: VIN_API_FAIL_MSG
}))
const errors = { ...(this.data.errors || {}) }
Object.keys(built).forEach(errorKey => {
if (built[errorKey] === true) {
delete errors[errorKey]
} else {
errors[errorKey] = VIN_API_FAIL_MSG
}
})
await Promise.all(tasks)
this.setData({ vinApiValidMap, errors })
return { vinApiValidMap, vinApiFailures }
},
/** 异步 API 校验车架号并更新 vinApiValidMap / errors */
......@@ -719,7 +757,10 @@ Page({
return
}
const { ok, valid } = await runVinApiValidate(vin, validateVin)
const { ok, valid, cancelled } = await runVinApiValidate(vin, validateVin)
if (cancelled) {
return
}
vinApiValidMap[errorKey] = ok && valid
if (!ok || !valid) {
errors[errorKey] = VIN_API_FAIL_MSG
......
......@@ -1887,6 +1887,67 @@ describe('negotiation schema (F3)', async () => {
assert.equal(result.ok, true, JSON.stringify(result.errorMap))
})
it('IT-NEG-016: F3-4 boutique row validate and save payload include subform', async () => {
const { createFormEngine } = await import('../packageDynamicForm/form-engine/core.js')
const { buildAppDailySavePayload } = await import(
'../packageDynamicForm/form-engine/app-daily-save.js'
)
const engine = createFormEngine(negotiationSchema)
const boutiqueCtx = {
baseSceneCode: 100101,
brandIds: [3454],
sceneType: 1,
sceneList: [{ baseSceneCode: 100101 }]
}
const carInfo = {
vehicleBrandId: 1,
vehicleBrandName: '岚图',
vehicleSubBrandId: 2,
vehicleSubBrandName: '岚图汽车',
vehicleSeriesId: 3,
vehicleSeriesName: 'FREE',
vehicleShapeId: 4,
vehicleShapeName: '2024款'
}
const vin = 'LHGCV1650MH000001'
engine.init(negotiationSchema, boutiqueCtx)
const group = negotiationSchema.list.find(item => item.key === 'F3-4')
engine.addGroupRow(group)
const gk = 'F3-4'
engine.setGroupFieldValue(gk, 0, 'F3-4-1', '2026-06-01 10:00')
engine.setAppGroupFieldValue(gk, 0, 'F3-4-2', { id: 'staff-1', displayLabel: '驻店甲' })
engine.setGroupFieldValue(gk, 0, 'F3-4-3', '销售部')
engine.setAppGroupFieldValue(gk, 0, 'F3-4-4', { id: '4s-1', displayLabel: '销售乙' })
engine.setGroupFieldValue(gk, 0, 'F3-4-5', '客户')
engine.setGroupFieldValue(gk, 0, 'F3-4-6', '13800138000')
engine.mutateSubform(gk, 0, 'F3-4-7', { metaValue: carInfo }, { appDualKey: true })
engine.setGroupFieldValue(gk, 0, 'F3-4-8', vin)
engine.setGroupFieldValue(gk, 0, 'F3-4-9', 0)
engine.setGroupFieldValue(gk, 0, 'F3-4-10', '商超')
engine.setGroupFieldValue(gk, 0, 'F3-4-11', '是')
engine.setGroupFieldValue(gk, 0, 'F3-4-12', '是')
engine.setGroupFieldValue(gk, 0, 'F3-4-13', 100)
engine.setGroupFieldValue(gk, 0, 'F3-4-14', 200)
engine.setGroupFieldValue(gk, 0, 'F3-4-15', 300)
engine.setGroupFieldValue(gk, 0, 'F3-4-16', 400)
engine.prepareForSubmit()
const result = engine.validate({
vinApiValidMap: { [`${gk}__0__F3-4-8`]: true }
})
assert.equal(result.ok, true, JSON.stringify(result.errorMap))
const payload = buildAppDailySavePayload({
reportTemplateId: 1,
engine
})
const json = JSON.parse(payload.jsonContent)
const f34 = json.find(item => item.key === 'F3-4')
assert.ok(f34)
assert.ok(
(f34.childrenValue && f34.childrenValue.length) ||
(f34.children && f34.children.length)
)
})
it('IT-NEG-009: F3-4 row validates with dual-key select and carBrand', async () => {
const { validateForm } = await import('../packageDynamicForm/form-engine/validator.js')
const carInfo = {
......
/** Minimal api stub for vinVaildate node tests */
export default {
checkVinValidate() {
return Promise.resolve({
code: 0,
data: { message: '校验成功', data: { valid: true } }
})
}
}
import path from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const projectRoot = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'../..'
)
const mockApiUrl = pathToFileURL(
path.join(path.dirname(fileURLToPath(import.meta.url)), 'mock-api.mjs')
).href
/** Node test runner: map mini-program `~/` imports to project root */
export async function resolve(specifier, context, nextResolve) {
if (specifier === '~/api/api') {
return nextResolve(mockApiUrl, context)
}
if (specifier.startsWith('~/')) {
let mapped = path.join(projectRoot, specifier.slice(2))
if (!path.extname(mapped)) {
mapped += '.js'
}
return nextResolve(pathToFileURL(mapped).href, context)
}
return nextResolve(specifier, context)
}
import { register } from 'node:module'
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
register('./shims/resolve-tilde-loader.mjs', import.meta.url)
describe('vin submit flush', async () => {
it('IT-VIN-FLUSH-001: superseded debounced validateVin rejects cancelled without hanging', async () => {
globalThis.wx = globalThis.wx || {
showToast() {}
}
const { validateVin } = await import('../utils/vinVaildate.js')
const vin = 'LHGCV1650MH000001'
const first = validateVin(vin).catch(err => err)
await new Promise(resolve => setTimeout(resolve, 20))
validateVin(vin).catch(() => {})
const firstResult = await Promise.race([
first,
new Promise((_, reject) =>
setTimeout(() => reject(new Error('first validateVin hung')), 2000)
)
])
assert.equal(firstResult.cancelled, true)
})
it('IT-VIN-FLUSH-002: buildVinApiValidMapFromEntries merges API results', async () => {
const {
buildVinApiValidMapFromEntries,
listVinScanCellsFromCache
} = await import('../packageDynamicForm/form-engine/vin-api-valid-tracker.js')
const cache = {
'F3-4': [
[
{
key: 'F3-4-8',
type: 'input',
prefixComponent: 'scan',
value: 'LHGCV1650MH000001'
}
]
]
}
const entries = listVinScanCellsFromCache(cache)
assert.equal(entries.length, 1)
const map = await buildVinApiValidMapFromEntries(entries, async () => ({
ok: true,
valid: true
}))
assert.equal(map['F3-4__0__F3-4-8'], true)
})
it('IT-VIN-FLUSH-003: runVinApiValidateImmediate skips debounce', async () => {
const { runVinApiValidateImmediate } = await import(
'../packageDynamicForm/form-engine/vin-api-valid-tracker.js'
)
const result = await runVinApiValidateImmediate(
'SHORT',
async () => ({ success: true }),
{ silent: true }
)
assert.equal(result.ok, true)
assert.equal(result.valid, true)
})
})
......@@ -11,8 +11,97 @@ let pendingReject = null;
let pendingVin = null;
const DEBOUNCE_DELAY = 500; // 防抖延迟时间(毫秒)
/** 提交前取消失焦防抖,避免与批量静默校验叠加弹出「校验成功」 */
export function cancelPendingVinDebounce() {
if (debounceTimer) {
clearTimeout(debounceTimer);
debounceTimer = null;
}
if (pendingReject) {
const prevReject = pendingReject;
pendingResolve = null;
pendingReject = null;
pendingVin = null;
prevReject({
success: false,
message: "cancelled",
cancelled: true,
});
}
}
function showVinToast(title, silent) {
if (silent || !title || typeof wx === "undefined") {
return;
}
wx.showToast({
title,
icon: "none",
});
}
function requestVinApi(upperVin) {
return api.checkVinValidate({ vin: upperVin }).then((res) => {
const { code, data } = res;
if (code == 0) {
return {
success: true,
message: data?.message || "校验成功",
data: res,
vin: upperVin,
};
}
const errorMsg = data?.message || res.message || "车架号校验失败";
const err = {
success: false,
message: errorMsg,
data: res,
};
return Promise.reject(err);
});
}
/**
* 车架号校验(统一处理版本)
* 提交前批量校验:无防抖、默认不弹 Toast
* @param {string} vin
* @param {{ silent?: boolean }} [options]
*/
export function validateVinImmediate(vin, options = {}) {
const silent = options.silent !== false;
const upperVin = vin ? vin.toUpperCase() : "";
if (!upperVin || upperVin.length !== 17 || !VALID_VIN_REG.test(upperVin)) {
if (!silent) {
showVinToast(ERROR_MSG, false);
}
return Promise.reject({
success: false,
message: ERROR_MSG,
});
}
return requestVinApi(upperVin)
.then((result) => {
if (!silent && result.message) {
showVinToast(result.message, false);
}
return result;
})
.catch((err) => {
const errorMsg = err?.message || "车架号校验异常";
if (!silent) {
showVinToast(errorMsg, false);
}
return Promise.reject({
success: false,
message: errorMsg,
data: err?.data,
});
});
}
/**
* 车架号校验(统一处理版本,失焦/OCR 用,带防抖)
* @param {string} vin - 车架号
* @returns {Promise<Object>} 返回校验结果 { success: boolean, message: string, data?: any, vin?: string }
*/
......@@ -33,16 +122,28 @@ export function validateVin(vin) {
return;
}
// 清除之前的定时器,并 reject 上一次 Promise,避免 Promise.all 悬挂
if (debounceTimer) {
clearTimeout(debounceTimer);
debounceTimer = null;
if (pendingReject) {
const prevReject = pendingReject;
pendingResolve = null;
pendingReject = null;
pendingVin = null;
prevReject({
success: false,
message: "cancelled",
cancelled: true,
});
}
}
// 保存当前调用的 resolve 和 reject
pendingResolve = resolve;
pendingReject = reject;
pendingVin = upperVin;
// 清除之前的定时器
if (debounceTimer) {
clearTimeout(debounceTimer);
}
// 设置防抖定时器
debounceTimer = setTimeout(() => {
// 执行接口调用
......@@ -56,49 +157,19 @@ export function validateVin(vin) {
pendingReject = null;
debounceTimer = null;
// 调用后端接口校验
api
.checkVinValidate({ vin: currentVin })
.then((res) => {
let { code, data } = res;
if (code == 0) {
// 校验成功但有提示信息
if (data?.message) {
wx.showToast({
title: data.message,
icon: "none",
});
}
currentResolve({
success: true,
message: data?.message || "校验成功",
data: res,
vin: currentVin,
});
} else {
// 接口返回失败
const errorMsg = data?.message || res.message || "车架号校验失败";
wx.showToast({
title: errorMsg,
icon: "none",
});
currentReject({
success: false,
message: errorMsg,
data: res,
});
requestVinApi(currentVin)
.then((result) => {
if (result.message) {
showVinToast(result.message, false);
}
currentResolve(result);
})
.catch((err) => {
const errorMsg = err.message || "车架号校验异常";
wx.showToast({
title: errorMsg,
icon: "none",
});
currentReject({
success: false,
message: errorMsg,
});
const errorMsg = err?.message || "车架号校验异常";
if (!err?.cancelled) {
showVinToast(errorMsg, false);
}
currentReject(err);
});
}, DEBOUNCE_DELAY);
});
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!