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
+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() {