Commit c28f7802 by 张立顺

fix: guard vehicle picker async state

1 parent 8830480d
......@@ -74,6 +74,7 @@ Page({
childs: []
}))
this._restoredExpanded = false
this._canAutoRestoreSelection = true
this.setData(
{
brandInfo: res.brandInfo || {},
......@@ -151,13 +152,20 @@ Page({
restoreExpandedSelection(sectionIndex, seriesList) {
const selected = this.data.selectedCarInfo
if (this._restoredExpanded || !hasValue(selected?.vehicleShapeId)) return
if (
this._restoredExpanded ||
!this._canAutoRestoreSelection ||
!hasValue(selected?.vehicleShapeId)
) {
return
}
const seriesIndex = seriesList.findIndex(
series =>
String(carBrandApi.resolveCarSeriesId(series)) === String(selected.vehicleSeriesId)
)
if (seriesIndex < 0) return
this._restoredExpanded = true
this._canAutoRestoreSelection = false
const dataset = { sectionIndex, seriesIndex }
this.setData({ expandedSeriesKey: this.getSeriesKey(dataset) })
this.ensureShapeList(dataset)
......@@ -184,6 +192,7 @@ Page({
const { sectionIndex, seriesIndex } = e.currentTarget.dataset
const { section, series } = this.getSeriesNode(sectionIndex, seriesIndex)
if (!section || !series) return
this._canAutoRestoreSelection = false
const selectedCarInfo = buildSeriesSelection(this.data.brandInfo, section, series)
this.applySelection(selectedCarInfo)
},
......@@ -192,6 +201,7 @@ Page({
const dataset = e.currentTarget.dataset
const { section, series } = this.getSeriesNode(dataset.sectionIndex, dataset.seriesIndex)
if (!section || !series) return
this._canAutoRestoreSelection = false
const key = this.getSeriesKey(dataset)
if (this.data.expandedSeriesKey === key) {
this.setData({ expandedSeriesKey: '' })
......@@ -251,6 +261,7 @@ Page({
const { section, series } = this.getSeriesNode(sectionIndex, seriesIndex)
const shape = series?.shapeList?.[Number(shapeIndex)]
if (!section || !series || !shape) return
this._canAutoRestoreSelection = false
const selectedCarInfo = buildShapeSelection(this.data.brandInfo, section, series, shape)
this.applySelection(selectedCarInfo)
},
......
......@@ -787,7 +787,17 @@ Page({
/** 将车型对象回写顶层字段或 subform App 双 key,并只清除对应字段错误。 */
applyCarBrandResult({ childKey, groupKey, rowIndex, carInfo } = {}) {
if (!this.engine || !childKey || !carInfo) return
if (
this._savingDraft ||
this._pushing ||
this.data.writeInProgress ||
this.data.formDisabled ||
!this.engine ||
!childKey ||
!carInfo
) {
return
}
let viewState
const errors = { ...this.data.errors }
const extra = { errors, structureChanged: false }
......@@ -1293,6 +1303,11 @@ Page({
})
},
/** 页面卸载:清理车型选择 bridge pending,避免回调写入已销毁页面。 */
onUnload() {
carBrandPickerBridge.clearPending()
},
/** 返回上一页;汇总打开时先关闭汇总。 */
jump() {
if (this.data.showNegotiationSummary) {
......
......@@ -122,52 +122,3 @@
text-align: center;
color: #999;
}
@keyframes move {
from {
right: -60.5%;
}
to {
right: 0;
}
}
.car-type-box {
position: fixed;
left: 0;
top: 0;
width: 100vw;
height: 100vh;
font-size: 28rpx;
color: #333;
z-index: 9999;
}
.car-type-box .bg {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
}
.car-view {
position: absolute;
top: 0;
right: 0;
height: 100vh;
width: 75vw;
padding-bottom: constant(safe-area-inset-bottom) !important;
padding-bottom: env(safe-area-inset-bottom) !important;
background: #fff;
-webkit-overflow-scrolling: touch;
animation: move 0.4s;
box-sizing: border-box;
overflow-y: scroll;
}
.car-view .item {
padding: var(--fontSize20) var(--fontSize32);
border-bottom: var(--fontSize2) solid #e9e9e9;
}
......@@ -4,13 +4,15 @@ import { createRequire } from 'node:module'
import { readFileSync } from 'node:fs'
const require = createRequire(import.meta.url)
const carBrandApi = require('../api/carBrandApi.js')
const {
resolveBrandNodeId,
resolveChildBrandId,
resolveCarSeriesId,
buildCarSeriesListParams
} = require('../api/carBrandApi.js')
} = carBrandApi
const carBrandPickerBridge = require('../services/carBrandPickerBridge.js')
const selectionHelpers = require('../pages/carBrandSeries/carBrandSeries.helpers.js')
const {
getMockCarSeriesList,
getMockCarTypeList
......@@ -18,6 +20,86 @@ const {
const seriesPageRoot = new URL('../pages/carBrandSeries/', import.meta.url)
const seriesPageSource = readFileSync(new URL('carBrandSeries.js', seriesPageRoot), 'utf8')
const seriesPageWxml = readFileSync(new URL('carBrandSeries.wxml', seriesPageRoot), 'utf8')
const sharedPickerCss = readFileSync(new URL('../styles/car-brand-picker.wxss', import.meta.url), 'utf8')
function setDataPath(data, path, value) {
const parts = path.replace(/\[(\d+)\]/g, '.$1').split('.')
let cursor = data
for (let index = 0; index < parts.length - 1; index += 1) {
const part = parts[index]
if (cursor[part] == null) cursor[part] = /^\d+$/.test(parts[index + 1]) ? [] : {}
cursor = cursor[part]
}
cursor[parts.at(-1)] = value
}
function createPageInstance(definition) {
const page = { ...definition, data: structuredClone(definition.data) }
page.setData = function (patch, callback) {
Object.entries(patch).forEach(([path, value]) => setDataPath(this.data, path, value))
callback?.()
}
return page
}
function loadSeriesPage(apiOverrides = {}) {
let definition
const api = { ...carBrandApi, ...apiOverrides }
const requireForPage = specifier => {
if (specifier === '../../api/carBrandApi.js') return api
if (specifier === '../../services/carBrandPickerBridge.js') return carBrandPickerBridge
if (specifier === './carBrandSeries.helpers.js') return selectionHelpers
throw new Error(`Unexpected carBrandSeries dependency: ${specifier}`)
}
const wx = {
$util: {},
setNavigationBarTitle() {}
}
new Function('require', 'Page', 'wx', seriesPageSource)(
requireForPage,
config => {
definition = config
},
wx
)
return createPageInstance(definition)
}
function deferred() {
let resolve
let reject
const promise = new Promise((resolvePromise, rejectPromise) => {
resolve = resolvePromise
reject = rejectPromise
})
return { promise, resolve, reject }
}
function flushPromises() {
return new Promise(resolve => setImmediate(resolve))
}
function seedSeriesPage(page, selectedCarInfo = null) {
page.data.brandInfo = { vehicleBrandId: 1, vehicleBrandName: '鸿蒙智行' }
page.data.selectedCarInfo = selectedCarInfo
page.data.canConfirm = !!selectedCarInfo
page.data.list = [
{
id: 10,
name: 'AITO 问界',
childs: [
{
id: 100,
name: '问界M5',
shapeList: [],
shapeLoading: false,
shapeLoaded: false,
shapeError: ''
}
]
}
]
}
describe('car brand series flow', () => {
it('IT-CAR-001: buildCarSeriesListParams normalizes brandId and childBrandId', () => {
......@@ -74,14 +156,107 @@ describe('car brand series flow', () => {
assert.match(seriesPageWxml, /catchtap="selectShape"/)
assert.match(seriesPageWxml, /bindtap="confirmSelection"/)
assert.doesNotMatch(seriesPageWxml, /car-type-box/)
assert.doesNotMatch(sharedPickerCss, /\.car-type-box|\.car-view/)
})
it('IT-CAR-005: accordion page exposes lazy shape state and confirm guards', () => {
assert.match(seriesPageSource, /expandedSeriesKey/)
assert.match(seriesPageSource, /shapeLoading/)
assert.match(seriesPageSource, /shapeLoaded/)
assert.match(seriesPageSource, /shapeError/)
assert.match(seriesPageSource, /ensureShapeList/)
assert.match(seriesPageSource, /if \(!this\.data\.canConfirm\) return/)
it('IT-CAR-005: loading and successful empty shape results are requested once', async () => {
const response = deferred()
let requests = 0
const page = loadSeriesPage({
getCarTypeList() {
requests += 1
return response.promise
}
})
seedSeriesPage(page)
page.ensureShapeList({ sectionIndex: 0, seriesIndex: 0 })
page.ensureShapeList({ sectionIndex: 0, seriesIndex: 0 })
assert.equal(requests, 1)
assert.equal(page.data.list[0].childs[0].shapeLoading, true)
response.resolve({ code: 0, data: [] })
await flushPromises()
page.ensureShapeList({ sectionIndex: 0, seriesIndex: 0 })
assert.equal(requests, 1)
assert.equal(page.data.list[0].childs[0].shapeLoaded, true)
assert.deepEqual(page.data.list[0].childs[0].shapeList, [])
})
it('IT-CAR-006: a failed shape request stores an error and retry requests again', async () => {
let requests = 0
const page = loadSeriesPage({
getCarTypeList() {
requests += 1
return requests === 1
? Promise.reject(new Error('offline'))
: Promise.resolve({ code: 0, data: [{ id: 1, name: 'Max' }] })
}
})
seedSeriesPage(page)
page.ensureShapeList({ sectionIndex: 0, seriesIndex: 0 })
await flushPromises()
assert.equal(page.data.list[0].childs[0].shapeError, '获取车型失败')
assert.equal(page.data.list[0].childs[0].shapeLoaded, false)
page.retryShapeList({ currentTarget: { dataset: { sectionIndex: 0, seriesIndex: 0 } } })
await flushPromises()
assert.equal(requests, 2)
assert.equal(page.data.list[0].childs[0].shapeLoaded, true)
assert.equal(page.data.list[0].childs[0].shapeError, '')
})
it('IT-CAR-007: a missing restored shape preserves the old selection', async () => {
const selectedCarInfo = {
vehicleBrandId: 1,
vehicleSubBrandId: 10,
vehicleSeriesId: 100,
vehicleShapeId: 999,
displayText: '旧车型'
}
const page = loadSeriesPage({
getCarTypeList: () => Promise.resolve({ code: 0, data: [{ id: 1, name: 'Max' }] })
})
seedSeriesPage(page, selectedCarInfo)
page.ensureShapeList({ sectionIndex: 0, seriesIndex: 0 })
await flushPromises()
assert.equal(page.data.selectedCarInfo, selectedCarInfo)
assert.equal(page.data.selectedCarInfo.vehicleShapeId, 999)
assert.equal(page.data.canConfirm, true)
})
it('IT-CAR-008: a delayed restored series cannot override a manual expansion', async () => {
const selectedSection = deferred()
const otherSection = deferred()
const page = loadSeriesPage({
getCarSeriesList({ childBrandId }) {
return childBrandId === 10 ? selectedSection.promise : otherSection.promise
},
getCarTypeList: () => Promise.resolve({ code: 0, data: [] })
})
page.applySeriesNav({
brandInfo: { vehicleBrandId: 1, vehicleBrandName: '鸿蒙智行' },
currentValue: {
vehicleBrandId: 1,
vehicleSubBrandId: 10,
vehicleSeriesId: 100,
vehicleShapeId: 999
},
list: [
{ id: 10, name: 'AITO 问界' },
{ id: 20, name: 'LUXEED 智界' }
]
})
otherSection.resolve({ code: 0, data: [{ id: 200, name: '智界S7' }] })
await flushPromises()
page.toggleSeries({ currentTarget: { dataset: { sectionIndex: 1, seriesIndex: 0 } } })
assert.equal(page.data.expandedSeriesKey, '1-0')
selectedSection.resolve({ code: 0, data: [{ id: 100, name: '问界M5' }] })
await flushPromises()
assert.equal(page.data.expandedSeriesKey, '1-0')
})
})
......@@ -7,6 +7,49 @@ const js = readFileSync(new URL('storeDailyReport.js', pageRoot), 'utf8')
const wxml = readFileSync(new URL('storeDailyReport.wxml', pageRoot), 'utf8')
const calendarWxml = readFileSync(new URL('../components/weekCalendar/weekCalendar.wxml', import.meta.url), 'utf8')
function createFallbackModule(overrides = {}) {
return new Proxy(overrides, {
get(target, property) {
if (property in target) return target[property]
return () => ({})
}
})
}
function createStorePageHarness() {
let definition
let clearPendingCalls = 0
const carBrandPickerBridge = {
clearPending() {
clearPendingCalls += 1
},
openCarBrandPick() {},
resolveMerchantId: value => value
}
const modules = {
'../../services/carBrandPickerBridge.js': carBrandPickerBridge,
'../../form-engine/car-brand-value.js': {
resolveCarBrandValueForValidation: (field, childKey, value) => field?.[childKey] || value
},
'../../utils/user-merchant.js': { resolveSaveMerchantId: () => 10086 },
'../behaviors/dailyReportPage.js': {},
'../behaviors/dailyReportPageMethods.js': { applyEngineView() {} }
}
const requireForPage = specifier => modules[specifier] || createFallbackModule()
new Function('require', 'Page', 'wx', js)(
requireForPage,
config => {
definition = config
},
{ $util: {} }
)
const page = { ...definition, data: structuredClone(definition.data) }
page.setData = function (patch) {
Object.assign(this.data, patch)
}
return { page, getClearPendingCalls: () => clearPendingCalls }
}
describe('storeDailyReport page contract', () => {
it('IT-STORE-DAILY-PAGE-001: renders the state-machine actions and title', () => {
assert.match(wxml, /bindtap="editReport"/)
......@@ -102,12 +145,92 @@ describe('storeDailyReport page contract', () => {
)
})
it('IT-STORE-DAILY-PAGE-011: opens and applies the shared vehicle picker for dynamic fields', () => {
assert.match(js, /openCarBrandForField/)
assert.match(js, /applyCarBrandResult/)
assert.match(js, /carBrandPickerBridge\.openCarBrandPick/)
assert.match(js, /engine\.setFieldValue/)
assert.match(js, /engine\.mutateSubform/)
assert.match(js, /appDualKey:\s*true/)
it('IT-STORE-DAILY-PAGE-011: top-level picker result writes value and clears only its error', () => {
const { page } = createStorePageHarness()
const carInfo = { vehicleSeriesId: 3, displayText: '问界/M5' }
let writeArgs
page.data.errors = { vehicle: '请选择车型', untouched: '保留' }
page.engine = {
setFieldValue(...args) {
writeArgs = args
return { values: { vehicle: carInfo } }
}
}
page.applyEngineView = (viewState, extra) => {
page.lastApplied = { viewState, extra }
}
page.applyCarBrandResult({ childKey: 'vehicle', carInfo })
assert.deepEqual(writeArgs, ['vehicle', carInfo])
assert.deepEqual(page.lastApplied.extra.errors, { untouched: '保留' })
assert.equal(page.lastApplied.extra.structureChanged, false)
assert.equal(page.lastApplied.extra.changedGroupKey, undefined)
})
it('IT-STORE-DAILY-PAGE-012: subform picker result uses App dual key and refreshes its group', () => {
const { page } = createStorePageHarness()
const carInfo = { vehicleSeriesId: 3, vehicleShapeId: 4, displayText: '问界/M5/Max' }
let writeArgs
page.data.errors = {
'customers__1__vehicle': '请选择车型',
'customers__0__vehicle': '保留'
}
page.engine = {
mutateSubform(...args) {
writeArgs = args
return { values: { customers: [] } }
}
}
page.applyEngineView = (viewState, extra) => {
page.lastApplied = { viewState, extra }
}
page.applyCarBrandResult({
childKey: 'vehicle',
groupKey: 'customers',
rowIndex: 1,
carInfo
})
assert.deepEqual(writeArgs, [
'customers',
1,
'vehicle',
{ metaValue: carInfo },
{ appDualKey: true }
])
assert.deepEqual(page.lastApplied.extra.errors, {
'customers__0__vehicle': '保留'
})
assert.equal(page.lastApplied.extra.changedGroupKey, 'customers')
})
it('IT-STORE-DAILY-PAGE-013: stale picker results cannot write after the form locks', () => {
for (const lockedData of [{ formDisabled: true }, { writeInProgress: true }]) {
const { page } = createStorePageHarness()
let writes = 0
Object.assign(page.data, lockedData)
page.engine = {
setFieldValue() {
writes += 1
},
mutateSubform() {
writes += 1
}
}
page.applyCarBrandResult({
childKey: 'vehicle',
groupKey: 'customers',
rowIndex: 0,
carInfo: { vehicleSeriesId: 3 }
})
assert.equal(writes, 0)
}
})
it('IT-STORE-DAILY-PAGE-014: unloading clears the pending vehicle picker once', () => {
const { page, getClearPendingCalls } = createStorePageHarness()
page.onUnload()
assert.equal(getClearPendingCalls(), 1)
})
})
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!