fix(salon): 完善预约草稿与表单重置

This commit is contained in:
2026-10-31 23:03:13 +08:00
parent 5426df3ef2
commit e52e04685d
8 changed files with 619 additions and 46 deletions
@@ -0,0 +1,279 @@
const assert = require('assert')
const fs = require('fs')
const path = require('path')
let appointmentDefinition
let backfillDefinition
const storage = new Map()
let modalConfirm = true
let modalCalls = 0
const app = { globalData: { userInfo: { id: 'manager-1', shopId: 'shop-1', type: 2 } } }
global.Page = value => { appointmentDefinition = value }
global.getApp = () => app
global.wx = {
getStorageSync(key) { return storage.get(key) },
setStorageSync(key, value) { storage.set(key, JSON.parse(JSON.stringify(value))) },
removeStorageSync(key) { storage.delete(key) },
showModal(options) { modalCalls += 1; options.success({ confirm: modalConfirm }) },
showToast() {},
redirectTo() {},
navigateTo() {}
}
require('./index')
global.Page = value => { backfillDefinition = value }
require('../backfill-order/index')
function clone(value) {
return JSON.parse(JSON.stringify(value))
}
function createPage(definition) {
const page = {
...definition,
data: clone(definition.data),
setData(patch, callback) {
Object.entries(patch || {}).forEach(([key, value]) => {
const parts = key.split('.')
let target = this.data
for (let index = 0; index < parts.length - 1; index += 1) {
if (!target[parts[index]]) target[parts[index]] = {}
target = target[parts[index]]
}
target[parts[parts.length - 1]] = value
})
if (callback) callback()
}
}
return page
}
function draftKey(userId = 'manager-1', shopId = 'shop-1') {
return `managerAppointmentDraft:${userId}:${shopId}`
}
async function testDraftRestoreAndEntryOverrides() {
storage.clear()
modalConfirm = true
storage.set(draftKey(), {
form: {
...appointmentDefinition.data.form,
customerName: '草稿客户',
phone: '13800000000',
productId: 'product-1',
appointmentDate: '2099-10-10',
appointmentTime: '14:00',
artistId: 'artist-1',
durationMinutes: '90'
},
durationManuallyChanged: true,
savedAt: Date.now()
})
const page = createPage(appointmentDefinition)
page.loadOptions = () => {}
page.onLoad({ date: '2099-10-11', artistId: 'artist-2', customerName: encodeURIComponent('入口客户') })
assert.strictEqual(page.data.form.customerName, '入口客户')
assert.strictEqual(page.data.form.phone, '')
assert.strictEqual(page.data.form.productId, 'product-1')
assert.strictEqual(page.data.form.appointmentDate, '2099-10-11')
assert.strictEqual(page.data.form.appointmentTime, '')
assert.strictEqual(page.data.form.artistId, 'artist-2')
assert.strictEqual(page.data.form.durationMinutes, '90')
assert.strictEqual(page.data.durationManuallyChanged, true)
assert.ok(page.data.draftSavedAtText.includes('已恢复草稿'))
const manualPage = createPage(appointmentDefinition)
manualPage.loadOptions = () => {}
manualPage.onLoad({ dateMode: 'manual', artistId: 'artist-2' })
assert.strictEqual(manualPage.data.form.appointmentDate, '2099-10-10')
assert.strictEqual(manualPage.data.form.appointmentTime, '14:00')
assert.strictEqual(manualPage.data.form.customerName, '草稿客户')
assert.strictEqual(manualPage.data.form.artistId, 'artist-2')
}
async function testDraftAutosaveExpiryAndIsolation() {
storage.clear()
modalConfirm = true
const page = createPage(appointmentDefinition)
page.loadOptions = () => {}
page.onLoad({ dateMode: 'manual' })
page.setData({ 'form.customerName': '自动保存客户' })
await new Promise(resolve => setTimeout(resolve, 450))
assert.strictEqual(storage.get(draftKey()).form.customerName, '自动保存客户')
page.setData({ 'form.phone': '13800000000' })
page.setData({ 'form.durationMinutes': '90', durationManuallyChanged: true })
page.saveDraft()
assert.strictEqual(storage.get(draftKey()).form.phone, '13800000000')
assert.strictEqual(storage.get(draftKey()).durationManuallyChanged, true)
app.globalData.userInfo.id = 'manager-2'
const otherUserPage = createPage(appointmentDefinition)
otherUserPage.loadOptions = () => {}
otherUserPage.onLoad({ dateMode: 'manual' })
otherUserPage.setData({ 'form.customerName': '另一位店长' })
await new Promise(resolve => setTimeout(resolve, 450))
assert.strictEqual(storage.get(draftKey('manager-2')).form.customerName, '另一位店长')
assert.strictEqual(storage.get(draftKey('manager-1')).form.customerName, '自动保存客户')
app.globalData.userInfo.id = 'manager-1'
app.globalData.userInfo.shopId = 'shop-2'
const otherShopPage = createPage(appointmentDefinition)
otherShopPage.loadOptions = () => {}
otherShopPage.onLoad({ dateMode: 'manual' })
assert.strictEqual(otherShopPage.data.form.customerName, '')
otherShopPage.setData({ 'form.customerName': '另一家门店' })
await new Promise(resolve => setTimeout(resolve, 450))
assert.strictEqual(storage.get(draftKey('manager-1', 'shop-2')).form.customerName, '另一家门店')
app.globalData.userInfo.shopId = 'shop-1'
storage.set(draftKey(), {
form: { ...appointmentDefinition.data.form, customerName: '过期草稿' },
savedAt: Date.now() - 8 * 24 * 60 * 60 * 1000
})
const expiredPage = createPage(appointmentDefinition)
expiredPage.loadOptions = () => {}
expiredPage.onLoad({ dateMode: 'manual' })
assert.strictEqual(expiredPage.data.form.customerName, '')
assert.strictEqual(storage.has(draftKey()), false)
}
async function testResetAndSuccessfulSubmitClearDraft() {
storage.clear()
modalConfirm = true
const page = createPage(appointmentDefinition)
page.data.defaultAppointmentDurationMinutes = 75
page.loadOptions = () => {}
page.refreshAvailableTimes = async () => {}
page.onLoad({ date: '2099-10-12', artistId: 'artist-3' })
page.setData({
'form.customerName': '需要清空',
'form.amount': '268',
'form.appointmentTime': '15:00',
'form.remark': '备注'
})
page.saveDraft()
modalConfirm = false
await page.resetForm()
assert.strictEqual(page.data.form.customerName, '需要清空')
assert.strictEqual(storage.has(draftKey()), true)
const modalCallCount = modalCalls
page.setData({ loading: true })
await page.resetForm()
assert.strictEqual(modalCalls, modalCallCount)
assert.strictEqual(page.data.form.customerName, '需要清空')
page.setData({ loading: false })
page.setData({ manualImageUploading: true })
await page.resetForm()
assert.strictEqual(modalCalls, modalCallCount)
assert.strictEqual(page.data.form.customerName, '需要清空')
page.setData({ manualImageUploading: false })
modalConfirm = true
await page.resetForm()
assert.strictEqual(page.data.form.customerName, '')
assert.strictEqual(page.data.form.amount, '')
assert.strictEqual(page.data.form.appointmentTime, '')
assert.strictEqual(page.data.form.remark, '')
assert.strictEqual(page.data.form.appointmentDate, '2099-10-12')
assert.strictEqual(page.data.form.artistId, 'artist-3')
assert.strictEqual(page.data.form.durationMinutes, '75')
assert.strictEqual(storage.has(draftKey()), false)
assert.strictEqual(page.data.manualProductMoreVisible, false)
assert.strictEqual(page.data.timeSheetVisible, false)
page.setData({ 'form.customerName': '重置后继续填写' })
await new Promise(resolve => setTimeout(resolve, 450))
assert.strictEqual(storage.get(draftKey()).form.customerName, '重置后继续填写')
const planningApi = require('../../api/planning')
const originalCreateAppointment = planningApi.createAppointment
planningApi.createAppointment = async () => ({ orderItemId: 'order-item-1' })
page.data.form = {
...page.data.form,
productId: 'product-1',
amount: '120',
appointmentDate: '2099-10-12',
appointmentTime: '15:00',
artistId: 'artist-3',
durationMinutes: '60'
}
page.checkAvailability = async () => ({ ok: true })
page.ensureCustomerBeforeSubmit = async () => true
storage.set(draftKey(), { form: page.data.form, savedAt: Date.now() })
await page.submit()
assert.strictEqual(storage.has(draftKey()), false)
planningApi.createAppointment = originalCreateAppointment
}
async function testBackfillResetAndLibraryGuidance() {
modalConfirm = true
const page = createPage(backfillDefinition)
page.loadArtists = () => {}
page.loadProducts = () => {}
page.loadCustomers = () => {}
page.onLoad({ serviceDate: '2020-01-02', artistId: 'artist-9' })
page.data.artists = [{ id: 'artist-9', name: '美甲师九' }]
page.setData({ 'form.customerName': '需要清空', 'form.amount': '99', 'form.serviceTime': '12:30' })
const modalCallCount = modalCalls
page.setData({ manualImageUploading: true })
await page.resetForm()
assert.strictEqual(modalCalls, modalCallCount)
assert.strictEqual(page.data.form.customerName, '需要清空')
page.setData({ manualImageUploading: false })
modalConfirm = false
await page.resetForm()
assert.strictEqual(page.data.form.customerName, '需要清空')
modalConfirm = true
await page.resetForm()
assert.strictEqual(page.data.form.serviceDate, '2020-01-02')
assert.strictEqual(page.data.form.artistId, 'artist-9')
assert.strictEqual(page.data.selectedArtistName, '美甲师九')
assert.strictEqual(page.data.form.customerName, '')
assert.strictEqual(page.data.form.amount, '')
assert.strictEqual(page.data.form.serviceTime, '')
assert.strictEqual(page.data.form.status, 4)
const unassignedPage = createPage(appointmentDefinition)
unassignedPage.loadOptions = () => {}
unassignedPage.refreshAvailableTimes = async () => {}
unassignedPage.onLoad({ date: '2099-10-15', artistId: '__unassigned__' })
assert.strictEqual(unassignedPage.data.form.artistId, '')
assert.strictEqual(unassignedPage.data.selectedArtist.id, '__unassigned__')
await unassignedPage.resetForm()
assert.strictEqual(unassignedPage.data.form.appointmentDate, '2099-10-15')
assert.strictEqual(unassignedPage.data.form.artistId, '')
assert.strictEqual(unassignedPage.data.selectedArtist.id, '__unassigned__')
unassignedPage.setData({ 'form.appointmentTime': '' })
await new Promise(resolve => setTimeout(resolve, 450))
assert.strictEqual(storage.has(draftKey()), false)
const manualEntryPage = createPage(appointmentDefinition)
manualEntryPage.loadOptions = () => {}
manualEntryPage.onLoad({ dateMode: 'manual' })
assert.strictEqual(manualEntryPage.data.form.appointmentDate, '')
manualEntryPage.setData({ 'form.appointmentDate': '2099-10-20' })
await manualEntryPage.resetForm()
assert.strictEqual(manualEntryPage.data.form.appointmentDate, '')
const appointmentMarkup = fs.readFileSync(path.join(__dirname, 'index.wxml'), 'utf8')
const backfillMarkup = fs.readFileSync(path.join(__dirname, '..', 'backfill-order', 'index.wxml'), 'utf8')
const guidance = '仅门店可见,不会公开展示'
assert.ok(appointmentMarkup.includes(guidance))
assert.ok(backfillMarkup.includes(guidance))
}
async function run() {
await testDraftRestoreAndEntryOverrides()
await testDraftAutosaveExpiryAndIsolation()
await testResetAndSuccessfulSubmitClearDraft()
await testBackfillResetAndLibraryGuidance()
console.log('预约草稿与重置测试通过')
}
run().catch(error => {
console.error(error)
process.exitCode = 1
})
@@ -74,7 +74,7 @@ async function run() {
assert.strictEqual(draftPage.data.form.appointmentTime, '14:00')
assert.strictEqual(draftPage.data.form.customerName, '草稿客户')
assert.strictEqual(draftPage.data.form.artistId, '88')
assert.strictEqual(draftPage.data.draftSavedAtText, '已恢复本机草稿')
assert.ok(draftPage.data.draftSavedAtText.startsWith('已恢复草稿'))
storedDraft = null
const page = createPage()
+263 -39
View File
@@ -6,6 +6,8 @@ const { markPlanningRefresh } = require('../../utils/planning-refresh')
const { uploadObjectFile } = require('../../utils/upload')
const DRAFT_STORAGE_PREFIX = 'managerAppointmentDraft'
const DRAFT_TTL_MS = 7 * 24 * 60 * 60 * 1000
const DRAFT_SAVE_DELAY_MS = 400
const TIME_SLOT_MINUTES = 15
function buildClientRequestId(prefix) {
@@ -53,25 +55,31 @@ function buildDraftKey() {
return `${DRAFT_STORAGE_PREFIX}:${userInfo.id || 'guest'}:${userInfo.shopId || 'default'}`
}
function hasPresetOptions(options) {
return Boolean(options.customerName || options.phone || options.date || options.artistId)
}
function readDraftForm() {
function readDraft() {
try {
const draft = wx.getStorageSync(buildDraftKey())
return draft && draft.form ? draft.form : null
if (!draft || !draft.form) return null
const savedAt = Number(draft.savedAt)
if (!Number.isFinite(savedAt) || savedAt <= 0 || savedAt > Date.now() || Date.now() - savedAt > DRAFT_TTL_MS) {
wx.removeStorageSync(buildDraftKey())
return null
}
return draft
} catch (error) {
throw new Error(`读取预约草稿失败:${error.message || error}`)
}
}
function writeDraftForm(form) {
function writeDraftForm(form, artistSelectionId, durationManuallyChanged) {
try {
const savedAt = Date.now()
wx.setStorageSync(buildDraftKey(), {
form,
savedAt: Date.now()
artistSelectionId: artistSelectionId === '__unassigned__' ? artistSelectionId : '',
durationManuallyChanged: Boolean(durationManuallyChanged),
savedAt
})
return savedAt
} catch (error) {
throw new Error(`保存预约草稿失败:${error.message || error}`)
}
@@ -85,6 +93,42 @@ function removeDraftForm() {
}
}
function formatDraftStatus(status, savedAt) {
if (!savedAt) return status
const date = new Date(Number(savedAt))
if (Number.isNaN(date.getTime())) return status
const pad = value => String(value).padStart(2, '0')
return `${status} · ${date.getMonth() + 1}月${date.getDate()}日 ${pad(date.getHours())}:${pad(date.getMinutes())}`
}
function decodeOptionValue(value) {
if (value === undefined || value === null) return ''
try {
return decodeURIComponent(String(value))
} catch (error) {
return String(value)
}
}
function hasDraftContent(form, entryDefaults, selectedArtist, defaultDuration) {
if (!form) return false
const changedDate = String(form.appointmentDate || '') !== String(entryDefaults.appointmentDate || '')
const currentArtistSelectionId = selectedArtist && selectedArtist.id === '__unassigned__'
? '__unassigned__'
: String(form.artistId || '')
const defaultArtistSelectionId = String(entryDefaults.artistSelectionId || entryDefaults.artistId || '')
const changedArtist = currentArtistSelectionId !== defaultArtistSelectionId
return Boolean(
form.customerUserId || form.customerName || form.phone || form.wechatId ||
form.productId || form.manualProductTitle || form.manualProductDescription ||
form.manualProductTags || form.manualProductTargetAudience || form.manualProductPrecautions ||
form.manualProductImageFileIds || (Array.isArray(form.manualProductImages) && form.manualProductImages.length) ||
String(form.amount || '').trim() || form.appointmentTime || form.createCustomerRecord || form.remark ||
changedDate || changedArtist ||
(Number(form.durationMinutes) > 0 && Number(form.durationMinutes) !== Number(defaultDuration || 60))
)
}
function normalizeManualProductImages(form) {
const savedImages = form && Array.isArray(form.manualProductImages) ? form.manualProductImages : null
if (savedImages) {
@@ -598,7 +642,7 @@ Page({
loading: false
},
onLoad(options) {
onLoad(options = {}) {
const manualDateMode = options && options.dateMode === 'manual'
const today = dateUtil.formatDate(new Date())
if (options && options.date && options.date < today) {
@@ -607,29 +651,62 @@ Page({
return
}
const creatable = canCreateAppointment()
const draftForm = creatable && (manualDateMode || !hasPresetOptions(options)) ? readDraftForm() : null
const baseForm = draftForm || {}
const manualProductImages = normalizeManualProductImages(baseForm)
const appointmentDate = options.date || baseForm.appointmentDate || (manualDateMode ? '' : today)
let draft = null
if (creatable) {
try {
draft = readDraft()
} catch (error) {
wx.showToast({ title: error.message || '预约草稿读取失败', icon: 'none' })
}
}
const draftForm = draft && draft.form ? draft.form : {}
const routeDate = options && options.date ? String(options.date) : ''
const routeArtistSelectionId = options && options.artistId ? String(options.artistId) : ''
const routeArtistId = routeArtistSelectionId === '__unassigned__' ? '' : routeArtistSelectionId
const hasRouteCustomer = ['customerUserId', 'customerName', 'wechatId', 'phone']
.some(key => options && options[key] !== undefined)
const routeDateChanged = Boolean(routeDate && draftForm.appointmentDate && routeDate !== draftForm.appointmentDate)
const draftArtistSelectionId = draft && draft.artistSelectionId === '__unassigned__'
? '__unassigned__'
: String(draftForm.artistId || '')
const manualProductImages = normalizeManualProductImages(draftForm)
const appointmentDate = routeDate || draftForm.appointmentDate || (manualDateMode ? '' : today)
const appointmentTime = routeDateChanged ? '' : (draftForm.appointmentTime || '')
const dateLabels = buildAppointmentDateLabels(appointmentDate)
this._entryDefaults = {
appointmentDate: routeDate || (manualDateMode ? '' : today),
artistId: routeArtistId,
artistSelectionId: routeArtistSelectionId
}
this._draftReady = false
this._draftPersistenceDisabled = false
this._draftTimer = null
this.setData({
canCreateAppointment: creatable,
canManageShopSettings: isShopManager(),
form: {
...this.data.form,
...baseForm,
...draftForm,
manualProductImages,
manualProductImageFileIds: manualProductImages.map(image => image.fileId).join(','),
manualProductImageUrl: manualProductImages[0] ? manualProductImages[0].previewUrl || manualProductImages[0].fileUrl : '',
customerName: options.customerName ? decodeURIComponent(options.customerName) : (baseForm.customerName || ''),
phone: options.phone ? decodeURIComponent(options.phone) : (baseForm.phone || ''),
customerUserId: hasRouteCustomer ? String(options.customerUserId || '') : (draftForm.customerUserId || ''),
customerName: hasRouteCustomer ? decodeOptionValue(options.customerName) : (draftForm.customerName || ''),
wechatId: hasRouteCustomer ? decodeOptionValue(options.wechatId) : (draftForm.wechatId || ''),
phone: hasRouteCustomer ? decodeOptionValue(options.phone) : (draftForm.phone || ''),
appointmentDate,
artistId: options.artistId || baseForm.artistId || ''
appointmentTime,
artistId: routeArtistId || draftForm.artistId || ''
},
durationManuallyChanged: Boolean(baseForm.durationMinutes && !baseForm.productId),
manualProductTitleLength: String(baseForm.manualProductTitle || '').length,
unifiedStyleDescription: String(baseForm.remark || baseForm.manualProductDescription || ''),
draftSavedAtText: draftForm ? '已恢复本机草稿' : '',
selectedArtist: routeArtistSelectionId === '__unassigned__' || (!routeArtistId && draftArtistSelectionId === '__unassigned__')
? { id: '__unassigned__', name: '暂不分配美甲师' }
: {},
durationManuallyChanged: draft && draft.durationManuallyChanged !== undefined
? Boolean(draft.durationManuallyChanged)
: Boolean(draftForm.durationMinutes && !draftForm.productId && Number(draftForm.durationMinutes) !== 60),
manualProductTitleLength: String(draftForm.manualProductTitle || '').length,
unifiedStyleDescription: String(draftForm.remark || draftForm.manualProductDescription || ''),
draftSavedAtText: draft ? formatDraftStatus('已恢复草稿', draft.savedAt) : '内容变更后自动保存到本机,保留7天',
appointmentDayLabel: dateLabels.day,
appointmentDateBadge: dateLabels.badge,
appointmentDateLong: dateLabels.long
@@ -638,9 +715,15 @@ Page({
wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' })
return
}
this.installDraftAutoSave()
this._draftReady = true
this.loadOptions()
},
onHide() {
this.flushDraftSave()
},
onShow() {
if (!this._refreshTimesAfterSettings) return
this._refreshTimesAfterSettings = false
@@ -950,6 +1033,7 @@ Page({
},
onUnload() {
this.flushDraftSave()
if (this._customerTimer) {
clearTimeout(this._customerTimer)
}
@@ -958,6 +1042,154 @@ Page({
}
},
installDraftAutoSave() {
if (this._draftSetDataInstalled) return
const setData = this.setData.bind(this)
this.setData = (patch, callback) => {
const formChanged = patch && Object.keys(patch).some(key => key === 'form' || key.startsWith('form.'))
const result = setData(patch, callback)
if (formChanged) this.scheduleDraftSave()
return result
}
this._draftSetDataInstalled = true
},
scheduleDraftSave() {
if (!this._draftReady || this._draftPersistenceDisabled) return
if (this._draftTimer) clearTimeout(this._draftTimer)
this._draftTimer = setTimeout(() => {
this._draftTimer = null
this.persistDraft(false)
}, DRAFT_SAVE_DELAY_MS)
},
cancelDraftSave() {
if (this._draftTimer) clearTimeout(this._draftTimer)
this._draftTimer = null
},
flushDraftSave() {
if (!this._draftTimer) return
this.cancelDraftSave()
this.persistDraft(false)
},
persistDraft(showToast) {
try {
if (!hasDraftContent(
this.data.form,
this._entryDefaults || {},
this.data.selectedArtist,
this.data.defaultAppointmentDurationMinutes
)) {
removeDraftForm()
this.setData({ draftSavedAtText: '内容变更后自动保存到本机,保留7天' })
if (showToast) wx.showToast({ title: '当前没有需要保存的内容', icon: 'none' })
return false
}
const savedAt = writeDraftForm(
this.data.form,
this.data.selectedArtist && this.data.selectedArtist.id,
this.data.durationManuallyChanged
)
this.setData({ draftSavedAtText: formatDraftStatus(showToast ? '草稿已手动保存' : '草稿已自动保存', savedAt) })
if (showToast) wx.showToast({ title: '草稿已保存', icon: 'success' })
return true
} catch (error) {
this.setData({ draftSavedAtText: '草稿保存失败,请点击保存草稿重试' })
if (showToast) wx.showToast({ title: error.message || '草稿保存失败', icon: 'none' })
return false
}
},
async resetForm() {
if (this.data.loading) {
wx.showToast({ title: '预约正在提交,请稍后再恢复默认值', icon: 'none' })
return
}
if (this.data.manualImageUploading) {
wx.showToast({ title: '图片上传中,请稍后再恢复默认值', icon: 'none' })
return
}
const result = await new Promise(resolve => wx.showModal({
title: '恢复默认值',
content: '将清除本表单内容和本机草稿,但不会删除已上传图片文件。保留日历带入的日期和美甲师,确定继续吗?',
cancelText: '继续填写',
confirmText: '恢复默认',
success: resolve,
fail: () => resolve({ confirm: false })
}))
if (!result.confirm) return
this.cancelDraftSave()
try {
removeDraftForm()
} catch (error) {
wx.showToast({ title: error.message || '草稿清理失败,请稍后重试', icon: 'none' })
return
}
const defaults = this._entryDefaults || {}
const appointmentDate = defaults.appointmentDate || ''
const artistId = defaults.artistId || ''
const artistSelectionId = defaults.artistSelectionId || artistId
const durationMinutes = String(this.data.defaultAppointmentDurationMinutes || 60)
const selectedArtist = artistSelectionId === '__unassigned__'
? { id: '__unassigned__', name: '暂不分配美甲师' }
: artistId ? findArtist(this.data.artists, artistId) : {}
const dateLabels = buildAppointmentDateLabels(appointmentDate)
this._draftPersistenceDisabled = true
this.setData({
form: {
...this.data.form,
customerUserId: '',
customerName: '',
phone: '',
wechatId: '',
appointmentDate,
appointmentTime: '',
amount: '',
productId: '',
manualProductTitle: '',
manualProductPrice: '',
manualProductDescription: '',
manualProductTags: '',
manualProductTargetAudience: '',
manualProductPrecautions: '',
manualProductImageFileIds: '',
manualProductImageUrl: '',
manualProductImages: [],
durationMinutes,
artistId: artistSelectionId === '__unassigned__' ? '' : artistId,
createCustomerRecord: false,
remark: ''
},
selectedProduct: {},
selectedProductPriceText: '',
selectedArtist,
customerSuggestions: [],
customerKeyword: '',
durationManuallyChanged: false,
manualProductTitleLength: 0,
unifiedStyleDescription: '',
draftSavedAtText: '已恢复默认值;后续修改会自动保存到本机',
appointmentDayLabel: dateLabels.day,
appointmentDateBadge: dateLabels.badge,
appointmentDateLong: dateLabels.long,
conflictTip: '',
conflictLevel: 'free',
timeError: '',
selectedTimeCandidate: '',
timeSheetVisible: false,
timePickerMode: 'wheel',
manualProductSheetVisible: false,
manualProductMoreVisible: false,
productModalVisible: false,
customerSheetVisible: false,
artistSheetVisible: false
})
this._draftPersistenceDisabled = false
await this.refreshAvailableTimes()
},
async onDateChange(event) {
const nextDate = event.detail.value
const today = dateUtil.formatDate(new Date())
@@ -1807,7 +2039,14 @@ Page({
payload.manualProductImageFileIds = String(form.manualProductImageFileIds || '').trim() || undefined
}
const result = await planningApi.createAppointment(payload)
removeDraftForm()
this.cancelDraftSave()
this._draftReady = false
this._draftPersistenceDisabled = true
try {
removeDraftForm()
} catch (error) {
console.warn('预约已创建,但草稿清理失败', error)
}
markPlanningRefresh()
wx.redirectTo({ url: `/pages/appointment-detail/index?id=${result.orderItemId}` })
} catch (error) {
@@ -1822,23 +2061,8 @@ Page({
},
saveDraft() {
try {
writeDraftForm(this.data.form)
this.setData({ draftSavedAtText: '草稿已保存到本机' })
wx.showToast({ title: '草稿已保存', icon: 'success' })
} catch (error) {
wx.showToast({ title: error.message || '草稿保存失败', icon: 'none' })
}
},
clearDraft() {
try {
removeDraftForm()
this.setData({ draftSavedAtText: '' })
wx.showToast({ title: '草稿已清空', icon: 'success' })
} catch (error) {
wx.showToast({ title: error.message || '草稿清空失败', icon: 'none' })
}
this.cancelDraftSave()
this.persistDraft(true)
},
back() {
@@ -22,7 +22,7 @@
<text wx:elif="{{form.manualProductImages.length}}" class="field-value">已添加 {{form.manualProductImages.length}} 张款式图片</text>
<text wx:else class="field-value placeholder">填写款式名称或添加图片</text>
<text wx:if="{{form.amount || form.durationMinutes}}" class="field-meta">{{form.amount || '待填'}} 元 · 预计 {{form.durationMinutes || '60'}} 分钟</text>
<text class="field-label">{{form.manualProductImages.length ? '已添加 ' + form.manualProductImages.length + ' 张图片 · 点击可编辑' : '点击可手动录入,提交预约后自动加入款式库'}}</text>
<text class="field-label">{{form.manualProductImages.length ? '已添加 ' + form.manualProductImages.length + ' 张图片 · 点击可编辑' : '点击可手动录入,提交后自动保存到本店款式库'}}</text>
</view>
<text class="chevron">›</text>
</button>
@@ -33,6 +33,7 @@
<button class="switch-manual-action" catchtap="openManualProduct">调整</button>
</view>
<text class="style-hint">名称和图片至少填写一项;名称为空时会使用客户姓名或“散客款式”。</text>
<text class="style-hint">手动录入款式在预约提交成功后自动保存到本店款式库,仅门店可见,不会公开展示。</text>
</view>
<view class="card form-card appointment-info-section">
@@ -74,7 +75,7 @@
<view wx:if="{{form.customerUserId}}" class="customer-selected-tip">已选择系统客户</view>
</view>
<view wx:if="{{draftSavedAtText}}" class="draft-tip card"><text>{{draftSavedAtText}}</text><button class="text-btn draft-clear" bindtap="clearDraft">清空</button></view>
<view class="draft-tip card"><text>{{draftSavedAtText}}</text><button class="text-btn draft-clear" bindtap="resetForm">恢复默认值</button></view>
<view wx:if="{{conflictTip}}" class="availability-tip card {{conflictLevel}}"><text class="tip-title">时段检查</text><text class="tip-text">{{conflictTip}}</text></view>
<entity-selector-sheet visible="{{customerSheetVisible}}" title="选择客户" keyword="{{customerKeyword}}" placeholder="搜索客户姓名或手机号" items="{{customerOptions}}" selected-id="{{form.customerUserId}}" loading="{{customerLoading}}" error-text="{{customerError}}" empty-text="暂无匹配客户" show-view-switch="{{true}}" view-mode="{{customerViewMode}}" sort-label="{{customerNewestFirst ? '最新添加' : '最早添加'}}" bind:search="onCustomerSearch" bind:select="selectCustomer" bind:retry="retryCustomerSearch" bind:changeview="changeCustomerView" bind:sort="toggleCustomerSort" bind:close="closeCustomerSheet" />
@@ -217,7 +217,7 @@ async function testManualProductImages() {
appointmentDate: '2026-10-21',
manualProductImageFileIds: '44',
manualProductImageUrl: 'https://img.example/legacy.jpg'
} })
}, savedAt: Date.now() })
const legacyDraftPage = createPage()
legacyDraftPage.loadOptions = () => {}
legacyDraftPage.onLoad({})
@@ -233,7 +233,7 @@ async function testManualProductImages() {
fileUrl: 'https://img.example/restored.jpg',
previewUrl: '/tmp/stale-style.jpg'
}]
} })
}, savedAt: Date.now() })
const restoredDraftPage = createPage()
restoredDraftPage.loadOptions = () => {}
restoredDraftPage.onLoad({})
+58 -1
View File
@@ -34,7 +34,64 @@ Page({
manualProductDraft: { title: '', price: '', durationMinutes: '60', description: '' },
artists: [], artistOptions: [], products: [], productOptions: [], allCustomerOptions: [], customerOptions: [], productSelectorVisible: false, manualProductSheetVisible: false, artistSelectorVisible: false, customerSelectorVisible: false, loadingProducts: false, loadingArtists: false, loadingCustomers: false, manualImageUploading: false, submitting: false, productKeyword: '', artistKeyword: '', customerKeyword: '', productError: '', artistError: '', customerError: '', selectedArtistName: '', selectedProduct: {}, selectedProductTitle: '', selectedProductPriceText: '', manualProductTitleLength: 0, manualProductMoreVisible: false
},
onLoad(options = {}) { this.setData({ 'form.serviceDate': options.serviceDate || this.data.form.serviceDate, 'form.artistId': options.artistId || '' }); this.loadArtists(options.artistId); this.loadProducts(); this.loadCustomers() },
onLoad(options = {}) { const serviceDate = options.serviceDate || this.data.form.serviceDate; const artistId = options.artistId || ''; this._entryDefaults = { serviceDate, artistId }; this.setData({ 'form.serviceDate': serviceDate, 'form.artistId': artistId }); this.loadArtists(options.artistId); this.loadProducts(); this.loadCustomers() },
async resetForm() {
if (this.data.submitting) return
if (this.data.manualImageUploading) {
wx.showToast({ title: '图片上传中,请稍后再恢复默认值', icon: 'none' })
return
}
const result = await new Promise(resolve => wx.showModal({
title: '恢复默认值',
content: '将清除本次补录内容,但不会删除已上传图片文件。保留入口带入的日期和美甲师,确定继续吗?',
cancelText: '继续填写',
confirmText: '恢复默认',
success: resolve,
fail: () => resolve({ confirm: false })
}))
if (!result.confirm) return
const defaults = this._entryDefaults || {}
const artistId = defaults.artistId || ''
const artist = this.data.artists.find(item => String(item.id) === String(artistId))
this.setData({
form: {
serviceDate: defaults.serviceDate || dateUtil.formatDate(new Date()),
serviceTime: '',
artistId,
productId: '',
manualProductTitle: '',
manualProductDescription: '',
manualProductTags: '',
manualProductTargetAudience: '',
manualProductPrecautions: '',
manualProductImageFileIds: '',
manualProductImageUrl: '',
manualProductImages: [],
customerUserId: '',
customerName: '',
wechatId: '',
phone: '',
amount: '',
durationMinutes: '60',
status: 4,
remark: ''
},
manualProductDraft: { title: '', price: '', durationMinutes: '60', description: '' },
selectedArtistName: artist ? artist.name : '',
selectedProduct: {},
selectedProductTitle: '',
selectedProductPriceText: '',
manualProductTitleLength: 0,
manualProductMoreVisible: false,
productKeyword: '',
artistKeyword: '',
customerKeyword: '',
customerSelectorVisible: false,
artistSelectorVisible: false,
productSelectorVisible: false,
manualProductSheetVisible: false
})
},
async loadArtists(preferredArtistId) { this.setData({ loadingArtists: true }); try { const result = await employeesApi.list({ page: 1, size: 100 }); const list = result.list || result || []; const artists = list.map(item => ({ ...item, name: item.name || item.nickname || item.account || `美甲师${item.id}` })); const selected = artists.find(item => String(item.id) === String(preferredArtistId || this.data.form.artistId)); this.setData({ artists, artistOptions: artists.map(item => ({ id: item.id, title: item.name, subtitle: item.phone || '' })), selectedArtistName: selected ? selected.name : '', 'form.artistId': selected ? selected.id : '', artistError: '' }); this.refreshProductOptions() } catch (error) { this.setData({ artists: [], artistOptions: [], artistError: error.message || '美甲师加载失败' }) } finally { this.setData({ loadingArtists: false }) } },
async loadProducts() { this.setData({ loadingProducts: true }); try { const result = await productsApi.list({ page: 1, size: 100 }); this.setData({ products: result.list || result || [], productError: '' }); this.refreshProductOptions() } catch (error) { this.setData({ products: [], productOptions: [], productError: error.message || '款式加载失败' }) } finally { this.setData({ loadingProducts: false }) } },
refreshProductOptions() { const keyword = String(this.data.productKeyword || '').trim().toLowerCase(); const all = (this.data.products || []).map(product => normalizeProduct(product, this.data.artists)); this.setData({ productOptions: all.filter(item => !keyword || `${item.title} ${item.artistText} ${item.durationText} ${item.tagList.join(' ')}`.toLowerCase().includes(keyword)) }) },
@@ -20,7 +20,7 @@
<text wx:elif="{{form.manualProductImages.length}}" class="field-value">已添加 {{form.manualProductImages.length}} 张款式图片</text>
<text wx:else class="field-value placeholder">填写款式名称或添加图片</text>
<text wx:if="{{form.amount || form.durationMinutes}}" class="field-meta">{{form.amount || '待填'}} 元 · 预计 {{form.durationMinutes || '60'}} 分钟</text>
<text class="field-label">{{form.manualProductImages.length ? '已添加图片 · 点击可编辑' : '点击手动录入,提交后自动加入款式库'}}</text>
<text class="field-label">{{form.manualProductImages.length ? '已添加图片 · 点击可编辑' : '点击手动录入,提交后自动保存到本店款式库'}}</text>
</view>
<text class="chevron">›</text>
</button>
@@ -31,6 +31,7 @@
<button class="switch-manual-action" catchtap="openManualProduct">调整</button>
</view>
<text class="style-hint">名称和图片至少填写一项;名称未填时会使用客户姓名,未选择客户则使用“散客款式”。</text>
<text class="style-hint">手动录入款式在补录提交成功后自动保存到本店款式库,仅门店可见,不会公开展示。</text>
</view>
<view class="card form-card appointment-info-section">
@@ -66,6 +67,8 @@
<text class="style-hint">历史补单不校验美甲师排班,也不会占用预约时段。</text>
</view>
<view class="draft-tip card"><text>恢复默认值会清空本次填写,并保留入口日期和美甲师。</text><button class="text-btn draft-clear" bindtap="resetForm">恢复默认值</button></view>
<view class="fixed-bottom"><button class="primary-btn submit-btn" loading="{{submitting}}" disabled="{{submitting}}" bindtap="submit">保存历史补单</button></view>
<product-selector-sheet visible="{{productSelectorVisible}}" mode="list" title="选择已有款式" keyword="{{productKeyword}}" placeholder="搜索款式、标签、美甲师" items="{{productOptions}}" selected-id="{{form.productId}}" loading="{{loadingProducts}}" error-text="{{productError}}" empty-text="暂无匹配款式" show-manual-action="{{true}}" bind:search="searchProducts" bind:select="selectProduct" bind:openmanual="openManualProduct" bind:close="closeProductSelector" bind:retry="loadProducts" />
+9
View File
@@ -459,3 +459,12 @@
- 预约款式图片横向滚动内容明确从左侧开始排列,保持图片和添加入口为正方形。
- 美甲师选择器中的“暂不分配”可选中;选择后表单显示“已选择暂不分配美甲师”,但提交仍不携带美甲师 ID,并保留不校验排班占用的行为。
- 日期切换重新加载美甲师列表或列表加载失败时,保留已选择的“暂不分配”展示状态;其业务 ID 仍为空。
## 2026-10-31 Salon 预约草稿与表单重置
- 新建预约草稿改为内容变化后自动保存,同时保留手动保存;草稿按用户和门店隔离,7 天后过期,页面隐藏或退出时及时写入,提交成功后清除。
- 草稿恢复不再因入口参数而跳过;入口明确带入的客户、日期和美甲师优先,日期变化时清除不再适用的预约时间,并保留手动时长选择状态。
- 新建预约和历史补录增加确认后的恢复默认操作,清除表单和草稿图片引用,保留入口日期与美甲师、恢复默认时长;上传进行中时暂不重置,防止异步上传完成后图片引用重新出现。
- 两类表单均说明手动录入款式提交成功后会保存到本店款式库且仅门店可见;没有新增“关闭入库”选项,因为现有订单创建流程会建立对应款式记录。
- 原因:原草稿只支持手动保存,带入日期、客户或美甲师时会跳过恢复;“清空草稿”仅删除本机数据,不重置当前页面。改为统一的自动保存、入口优先合并和页面级重置。
- 不新增 API、数据库字段或迁移;小程序全量测试通过,`git diff --check` 通过。