优化预约表单并支持散客预约

This commit is contained in:
2026-10-20 13:29:55 +08:00
parent 4a7bd90088
commit c952a913e8
17 changed files with 1376 additions and 275 deletions
+403 -126
View File
@@ -192,6 +192,113 @@ function flattenTimeGroups(groups) {
return (groups || []).reduce((list, group) => list.concat(group.times || []), [])
}
function buildTimeValues(durationMinutes) {
const values = []
const open = dateUtil.minutesOfDay('10:00')
const close = dateUtil.minutesOfDay('22:00')
for (let minute = open; minute + durationMinutes <= close; minute += TIME_SLOT_MINUTES) {
values.push(dateUtil.timeFromMinutes(minute))
}
return values
}
function buildTimePickerSlots(calendar, form, durationMinutes) {
const schedules = calendar.schedules || []
const busyRanges = form.artistId ? buildBusyRanges(calendar.appointments || [], form) : []
return buildTimeValues(durationMinutes).map(value => {
const startMinute = dateUtil.minutesOfDay(value)
const endMinute = startMinute + durationMinutes
const occupied = hasBusyConflict(startMinute, endMinute, busyRanges)
const scheduled = !form.artistId || schedules.some(schedule =>
isScheduleCoveringTime(schedule, form, startMinute, endMinute)
)
const status = occupied ? 'occupied' : scheduled ? 'available' : 'off-shift'
return {
value,
hour: Number(value.slice(0, 2)),
minute: Number(value.slice(3, 5)),
rangeText: buildTimeRangeLabel(startMinute, durationMinutes),
status,
statusText: status === 'occupied' ? '已占用' : status === 'off-shift' ? '无排班' : ''
}
})
}
function buildTimePickerGroups(slots) {
const groupMap = {
morning: { key: 'morning', title: '上午', times: [] },
afternoon: { key: 'afternoon', title: '下午', times: [] },
evening: { key: 'evening', title: '晚上', times: [] }
}
;(slots || []).forEach(slot => groupMap[getTimePeriod(dateUtil.minutesOfDay(slot.value)).key].times.push(slot))
return Object.keys(groupMap).map(key => groupMap[key]).filter(group => group.times.length > 0)
}
function buildTimeWheelState(slots, preferredTime) {
if (!slots || slots.length === 0) {
return {
timePickerHours: [],
timePickerMinutes: [],
timePickerValue: [0, 0],
selectedTimeCandidate: '',
timePickerCandidateStatus: 'off-shift'
}
}
const preferredSlot = slots.find(slot => slot.value === preferredTime) || slots.find(slot => slot.value === '14:00')
const firstAvailableSlot = slots.find(slot => slot.status === 'available')
const selectedSlot = preferredSlot && preferredSlot.status === 'available'
? preferredSlot
: firstAvailableSlot || preferredSlot || slots[0]
const hours = Array.from(new Set(slots.map(slot => slot.hour)))
const selectedHourIndex = Math.max(0, hours.indexOf(selectedSlot.hour))
const minuteValues = [0, 15, 30, 45]
const minutes = minuteValues.map(minute => {
const slot = slots.find(item => item.hour === selectedSlot.hour && item.minute === minute)
return {
value: minute,
label: String(minute).padStart(2, '0'),
status: slot ? slot.status : 'off-shift',
disabled: !slot || slot.status !== 'available'
}
})
const selectedMinuteIndex = Math.max(0, minuteValues.indexOf(selectedSlot.minute))
return {
timePickerHours: hours.map(hour => ({
value: hour,
label: String(hour).padStart(2, '0'),
disabled: !slots.some(slot => slot.hour === hour && slot.status === 'available')
})),
timePickerMinutes: minutes,
timePickerValue: [selectedHourIndex, selectedMinuteIndex],
selectedTimeCandidate: selectedSlot.value,
timePickerCandidateStatus: selectedSlot.status
}
}
function timeWheelStateForHour(slots, hour, selectedMinute) {
const minuteValues = [0, 15, 30, 45]
const minutes = minuteValues.map(minute => {
const slot = slots.find(item => item.hour === hour && item.minute === minute)
return {
value: minute,
label: String(minute).padStart(2, '0'),
status: slot ? slot.status : 'off-shift',
disabled: !slot || slot.status !== 'available'
}
})
const selectedMinuteIndex = Math.max(0, minuteValues.indexOf(selectedMinute))
return { timePickerMinutes: minutes, selectedMinuteIndex }
}
function customerCreatedAt(customer) {
return customer.createTime || customer.createdAt || customer.addedAt || ''
}
function formatCustomerCreatedAt(value) {
if (!value) return '添加时间未知'
return `添加于 ${String(value).replace('T', ' ').slice(0, 16)}`
}
function parseProductTags(product) {
if (Array.isArray(product.tagList) && product.tagList.length > 0) {
return product.tagList
@@ -245,7 +352,8 @@ function normalizeCustomer(customer) {
name,
phone,
displayName: name || phone || '客户',
displayPhone: phone || '未填写手机号'
displayPhone: phone || '未填写手机号',
createdAt: customerCreatedAt(customer)
}
}
@@ -253,8 +361,8 @@ function buildCustomerSelectorItem(customer) {
return {
...customer,
title: customer.displayName,
subtitle: customer.displayPhone,
badge: '已有客户'
subtitle: formatCustomerCreatedAt(customer.createdAt),
rightText: customer.displayPhone
}
}
@@ -276,6 +384,7 @@ Page({
phone: '',
appointmentDate: dateUtil.formatDate(new Date()),
appointmentTime: '',
amount: '',
productId: '',
manualProductTitle: '',
manualProductPrice: '',
@@ -285,14 +394,18 @@ Page({
manualProductPrecautions: '',
manualProductImageFileIds: '',
manualProductImageUrl: '',
durationMinutes: '',
durationMinutes: '60',
artistId: '',
createCustomerRecord: false,
remark: ''
},
manualProductDraft: { title: '', price: '', description: '', tags: '', targetAudience: '', precautions: '', imageFileIds: '', imageUrl: '' },
customerOptions: [],
customerDirectory: [],
customerSheetVisible: false,
customerKeyword: '',
customerViewMode: 'list',
customerNewestFirst: true,
customerSuggestions: [],
customerLoading: false,
customerError: '',
products: [],
@@ -306,8 +419,6 @@ Page({
selectedProductPriceText: '',
selectedArtist: {},
productModalVisible: false,
productSelectorMode: 'list',
manualProductMoreExpanded: false,
productKeyword: '',
productError: '',
loadingProducts: false,
@@ -317,6 +428,14 @@ Page({
draftSavedAtText: '',
manualImageUploading: false,
timeSheetVisible: false,
timePickerMode: 'wheel',
timePickerValue: [0, 0],
timePickerHours: [],
timePickerMinutes: [],
timePickerSlots: [],
timePickerGroups: [],
timePickerCandidateStatus: 'off-shift',
selectedTimeCandidate: '',
timeLoading: false,
timeError: '',
timeSelectTip: '请先选择美甲师并填写时长',
@@ -330,16 +449,6 @@ Page({
const baseForm = draftForm || {}
this.setData({
canCreateAppointment: creatable,
manualProductDraft: {
title: baseForm.manualProductTitle || '',
price: baseForm.manualProductPrice || '',
description: baseForm.manualProductDescription || '',
tags: baseForm.manualProductTags || '',
targetAudience: baseForm.manualProductTargetAudience || '',
precautions: baseForm.manualProductPrecautions || '',
imageFileIds: baseForm.manualProductImageFileIds || '',
imageUrl: baseForm.manualProductImageUrl || ''
},
form: {
...this.data.form,
...baseForm,
@@ -375,10 +484,14 @@ Page({
await this.loadArtists()
this.refreshProductCards()
const selectedProduct = this.data.filteredProducts.find(item => String(item.id) === String(this.data.form.productId)) || {}
this.setData({
const selectedProductPatch = {
selectedProduct,
selectedProductPriceText: selectedProduct.priceText || ''
})
}
if (selectedProduct.id && (this.data.form.amount === '' || this.data.form.amount === undefined)) {
selectedProductPatch['form.amount'] = selectedProduct.price === undefined || selectedProduct.price === null ? '' : String(selectedProduct.price)
}
this.setData(selectedProductPatch)
await this.refreshAvailableTimes()
this.checkAvailability()
},
@@ -420,6 +533,47 @@ Page({
}
},
async loadCustomerDirectory() {
this.setData({ customerLoading: true })
try {
const size = 100
const rows = []
let page = 1
let total = Number.POSITIVE_INFINITY
while (rows.length < total) {
const result = await customersApi.list({ page, size })
const currentRows = Array.isArray(result) ? result : (result.list || [])
rows.push(...currentRows)
if (!Array.isArray(result) && Number.isFinite(Number(result.total))) {
total = Number(result.total)
} else if (currentRows.length < size) {
total = rows.length
}
if (currentRows.length === 0) break
page += 1
}
const directory = rows.map(normalizeCustomer)
this.setData({
customerDirectory: directory,
customerOptions: this.sortCustomerOptions(directory),
customerError: ''
})
this.refreshCustomerSuggestions(this.data.form.customerName, this.data.form.phone)
} catch (error) {
this.setData({ customerDirectory: [], customerOptions: [], customerError: error.message || '客户列表加载失败' })
} finally {
this.setData({ customerLoading: false })
}
},
sortCustomerOptions(customers, newestFirst = this.data.customerNewestFirst) {
return (customers || []).slice().sort((left, right) => {
const leftDate = String(left.createdAt || '')
const rightDate = String(right.createdAt || '')
return newestFirst ? rightDate.localeCompare(leftDate) : leftDate.localeCompare(rightDate)
}).map(buildCustomerSelectorItem)
},
onInput(event) {
const field = event.currentTarget.dataset.field
const patch = {
@@ -432,18 +586,81 @@ Page({
}
},
onStyleTitleInput(event) {
const patch = { 'form.manualProductTitle': event.detail.value }
if (this.data.form.productId) {
patch['form.productId'] = ''
patch.selectedProduct = {}
patch.selectedProductPriceText = ''
patch['form.manualProductImageFileIds'] = ''
patch['form.manualProductImageUrl'] = ''
}
this.setData(patch)
},
onCustomerInput(event) {
const field = event.currentTarget.dataset.field
const patch = {
[`form.${field}`]: event.detail.value,
'form.customerUserId': ''
}
if (field === 'customerName' && this.data.form.customerUserId) {
patch['form.phone'] = ''
'form.customerUserId': '',
'form.createCustomerRecord': false
}
this.setData({
...patch
})
const customerName = field === 'customerName' ? event.detail.value : this.data.form.customerName
const phone = field === 'phone' ? event.detail.value : this.data.form.phone
this.refreshCustomerSuggestions(customerName, phone)
},
refreshCustomerSuggestions(nameValue, phoneValue) {
const name = String(nameValue || '').trim().toLowerCase()
const phone = String(phoneValue || '').trim().toLowerCase()
if (!name && !phone) {
this._customerSuggestionSeq = (this._customerSuggestionSeq || 0) + 1
clearTimeout(this._suggestionTimer)
this.setData({ customerSuggestions: [] })
return
}
const suggestions = this.data.customerDirectory
.filter(customer => (!name || customer.name.toLowerCase().includes(name)) && (!phone || customer.phone.toLowerCase().includes(phone)))
.slice(0, 3)
.map(buildCustomerSelectorItem)
this.setData({ customerSuggestions: suggestions })
const requestSeq = (this._customerSuggestionSeq || 0) + 1
this._customerSuggestionSeq = requestSeq
clearTimeout(this._suggestionTimer)
this._suggestionTimer = setTimeout(async () => {
try {
const result = await customersApi.list({ page: 1, size: 50, keyword: name || phone })
if (requestSeq !== this._customerSuggestionSeq) return
const rows = Array.isArray(result) ? result : (result.list || [])
const remoteSuggestions = rows.map(normalizeCustomer)
.filter(customer => (!name || customer.name.toLowerCase().includes(name)) && (!phone || customer.phone.toLowerCase().includes(phone)))
.slice(0, 3)
.map(buildCustomerSelectorItem)
this.setData({ customerSuggestions: remoteSuggestions })
} catch (error) {
if (requestSeq === this._customerSuggestionSeq && suggestions.length === 0) {
this.setData({ customerSuggestions: [] })
}
}
}, 240)
},
selectCustomerSuggestion(event) {
const index = Number(event.currentTarget.dataset.index)
const customer = this.data.customerSuggestions[index]
if (!customer) return
this.setData({
'form.customerUserId': customer.id,
'form.customerName': customer.name,
'form.phone': customer.phone,
'form.createCustomerRecord': false,
customerSuggestions: [],
customerSheetVisible: false,
customerKeyword: ''
})
},
openCustomerSheet() {
@@ -467,22 +684,24 @@ Page({
return
}
const keyword = String(keywordValue === undefined ? this.data.customerKeyword : keywordValue || '').trim()
this.setData({ customerLoading: true })
try {
const data = await customersApi.list({ keyword, page: 1, size: 20 })
const list = data.list || data || []
this.setData({
customerOptions: list.map(normalizeCustomer).map(buildCustomerSelectorItem),
customerError: ''
})
} catch (error) {
this.setData({
customerOptions: [],
customerError: error.message || '客户列表加载失败'
})
} finally {
this.setData({ customerLoading: false })
}
if (this.data.customerDirectory.length === 0) await this.loadCustomerDirectory()
const matches = this.data.customerDirectory.filter(customer =>
!keyword || `${customer.name} ${customer.phone}`.toLowerCase().includes(keyword.toLowerCase())
)
this.setData({ customerOptions: this.sortCustomerOptions(matches), customerError: '' })
},
changeCustomerView(event) {
this.setData({ customerViewMode: event.detail.mode || 'list' })
},
toggleCustomerSort() {
const customerNewestFirst = !this.data.customerNewestFirst
const keyword = String(this.data.customerKeyword || '').trim().toLowerCase()
const matches = this.data.customerDirectory.filter(customer =>
!keyword || `${customer.name} ${customer.phone}`.toLowerCase().includes(keyword)
)
this.setData({ customerNewestFirst, customerOptions: this.sortCustomerOptions(matches, customerNewestFirst) })
},
retryCustomerSearch() {
@@ -498,8 +717,10 @@ Page({
'form.customerUserId': customer.id,
'form.customerName': customer.name,
'form.phone': customer.phone,
'form.createCustomerRecord': false,
customerSheetVisible: false,
customerKeyword: ''
customerKeyword: '',
customerSuggestions: []
})
},
@@ -507,6 +728,9 @@ Page({
if (this._customerTimer) {
clearTimeout(this._customerTimer)
}
if (this._suggestionTimer) {
clearTimeout(this._suggestionTimer)
}
},
async onDateChange(event) {
@@ -555,29 +779,20 @@ Page({
openProductModal() {
this.refreshProductCards()
this.setData({ productModalVisible: true, productSelectorMode: 'list' })
this.setData({ productModalVisible: true })
},
closeProductModal() {
this.setData({ productModalVisible: false, productSelectorMode: 'list' })
this.setData({ productModalVisible: false })
},
openManualProduct() {
this.setData({ productSelectorMode: 'manual', manualProductMoreExpanded: false })
},
backToProductList() {
this.setData({ productSelectorMode: 'list' })
this.refreshProductCards()
},
onManualProductInput(event) {
const field = event.detail.field
this.setData({ [`manualProductDraft.${field}`]: event.detail.value })
},
toggleManualProductMore() {
this.setData({ manualProductMoreExpanded: !this.data.manualProductMoreExpanded })
this.setData({
productModalVisible: false,
selectedProduct: {},
selectedProductPriceText: '',
'form.productId': ''
})
},
stopTap() {
@@ -597,16 +812,8 @@ Page({
this.setData({
selectedProduct,
selectedProductPriceText: selectedProduct.priceText || '',
manualProductDraft: { title: '', price: '', description: '', tags: '', targetAudience: '', precautions: '', imageFileIds: '', imageUrl: '' },
'form.productId': selectedProduct.id,
'form.manualProductTitle': '',
'form.manualProductPrice': '',
'form.manualProductDescription': '',
'form.manualProductTags': '',
'form.manualProductTargetAudience': '',
'form.manualProductPrecautions': '',
'form.manualProductImageFileIds': '',
'form.manualProductImageUrl': '',
'form.amount': selectedProduct.price === undefined || selectedProduct.price === null ? '' : String(selectedProduct.price),
'form.durationMinutes': String(selectedDuration || this.data.form.durationMinutes || '')
})
this.closeProductModal()
@@ -614,33 +821,6 @@ Page({
this.checkAvailability()
},
useManualProduct() {
const draft = this.data.manualProductDraft
const title = String(draft.title || '').trim()
const priceText = String(draft.price === undefined ? '' : draft.price).trim()
const price = Number(priceText)
if (!title || !priceText || !Number.isFinite(price) || price < 0) {
wx.showToast({ title: '请填写手动预约作品名称和价格', icon: 'none' })
return
}
this.setData({
selectedProduct: {},
selectedProductPriceText: `¥${price}`,
'form.productId': '',
'form.manualProductTitle': title,
'form.manualProductPrice': String(price),
'form.manualProductDescription': String(draft.description || '').trim(),
'form.manualProductTags': String(draft.tags || '').trim(),
'form.manualProductTargetAudience': String(draft.targetAudience || '').trim(),
'form.manualProductPrecautions': String(draft.precautions || '').trim(),
'form.manualProductImageFileIds': String(draft.imageFileIds || ''),
'form.manualProductImageUrl': String(draft.imageUrl || '')
})
this.closeProductModal()
this.refreshAvailableTimes()
this.checkAvailability()
},
async chooseManualProductImage() {
if (this.data.manualImageUploading) {
return
@@ -658,8 +838,11 @@ Page({
throw new Error('作品图片上传成功但未返回文件ID')
}
this.setData({
'manualProductDraft.imageFileIds': String(fileId),
'manualProductDraft.imageUrl': fileUrl
'form.productId': '',
selectedProduct: {},
selectedProductPriceText: '',
'form.manualProductImageFileIds': String(fileId),
'form.manualProductImageUrl': fileUrl
})
} catch (error) {
wx.showToast({ title: error.message || '图片上传失败', icon: 'none' })
@@ -670,8 +853,8 @@ Page({
removeManualProductImage() {
this.setData({
'manualProductDraft.imageFileIds': '',
'manualProductDraft.imageUrl': ''
'form.manualProductImageFileIds': '',
'form.manualProductImageUrl': ''
})
},
@@ -781,6 +964,13 @@ Page({
if (!form.appointmentDate || !durationMinutes) {
const patch = {
availableTimeGroups: [],
timePickerGroups: [],
timePickerSlots: [],
timePickerHours: [],
timePickerMinutes: [],
timePickerValue: [0, 0],
selectedTimeCandidate: '',
timePickerCandidateStatus: 'off-shift',
timeError: '',
timeSelectTip: '请先填写预约日期和时长'
}
@@ -792,8 +982,12 @@ Page({
}
if (!form.artistId) {
const availableTimeGroups = buildUnassignedTimeGroups(durationMinutes)
const timePickerSlots = buildTimePickerSlots({ schedules: [], appointments: [] }, form, durationMinutes)
this.setData({
availableTimeGroups,
timePickerSlots,
timePickerGroups: buildTimePickerGroups(timePickerSlots),
...buildTimeWheelState(timePickerSlots, form.appointmentTime),
timeError: '',
timeLoading: false,
timeSelectTip: '请选择预约时间,员工可稍后分配'
@@ -816,8 +1010,12 @@ Page({
}
const availableTimeGroups = buildAvailableTimeGroups(calendar, form, durationMinutes)
const availableTimes = flattenTimeGroups(availableTimeGroups).map(item => item.value)
const timePickerSlots = buildTimePickerSlots(calendar, form, durationMinutes)
const patch = {
availableTimeGroups,
timePickerSlots,
timePickerGroups: buildTimePickerGroups(timePickerSlots),
...buildTimeWheelState(timePickerSlots, form.appointmentTime),
timeSelectTip: availableTimes.length > 0 ? '请选择预约时间' : '当前美甲师当天暂无可约时间'
}
if (form.appointmentTime && !availableTimes.includes(form.appointmentTime)) {
@@ -845,7 +1043,7 @@ Page({
wx.showToast({ title: '请先填写预约日期和时长', icon: 'none' })
return
}
this.setData({ timeSheetVisible: true })
this.setData({ timeSheetVisible: true, timePickerMode: 'wheel' })
await this.refreshAvailableTimes()
},
@@ -855,16 +1053,61 @@ Page({
selectAvailableTime(event) {
const value = event.currentTarget.dataset.value
this.setData({
'form.appointmentTime': value,
timeSheetVisible: false
})
this.checkAvailability()
const slot = this.data.timePickerSlots.find(item => item.value === value)
if (!slot || slot.status !== 'available') {
wx.showToast({ title: slot && slot.status === 'occupied' ? '该时间已被占用' : '该时间不可预约', icon: 'none' })
return
}
this.setData({ selectedTimeCandidate: value, timePickerCandidateStatus: slot.status })
},
async checkAvailability() {
onTimePickerModeChange(event) {
this.setData({ timePickerMode: event.currentTarget.dataset.mode || 'wheel' })
},
onTimePickerChange(event) {
const values = event.detail.value || [0, 0]
const hourItem = this.data.timePickerHours[values[0]]
if (!hourItem) return
const hour = Number(hourItem.value)
const minuteIndex = Number(values[1] || 0)
const minuteItem = this.data.timePickerMinutes[minuteIndex]
const minute = minuteItem ? Number(minuteItem.value) : 0
const candidate = `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
const slot = this.data.timePickerSlots.find(item => item.value === candidate)
const nextMinutes = timeWheelStateForHour(this.data.timePickerSlots, hour, minute)
this.setData({
timePickerValue: [Number(values[0]), nextMinutes.selectedMinuteIndex],
timePickerMinutes: nextMinutes.timePickerMinutes,
selectedTimeCandidate: candidate,
timePickerCandidateStatus: slot ? slot.status : 'off-shift'
})
},
confirmTimeSelection() {
const candidate = this.data.selectedTimeCandidate
const slot = this.data.timePickerSlots.find(item => item.value === candidate)
if (!slot || slot.status !== 'available') {
wx.showToast({ title: slot && slot.status === 'occupied' ? '该时间已被占用' : '该时间不可预约', icon: 'none' })
return
}
this.checkAvailability(candidate).then(availability => {
if (!availability.ok) {
wx.showToast({
title: availability.tip && availability.tip.includes('已有预约') ? '该时间已被占用' : availability.tip || '该时间不可预约',
icon: 'none'
})
return
}
this.setData({ 'form.appointmentTime': candidate, timeSheetVisible: false })
this.checkAvailability()
})
},
async checkAvailability(candidateTime) {
const form = this.data.form
if (!form.appointmentDate || !form.appointmentTime) {
const appointmentTime = candidateTime || form.appointmentTime
if (!form.appointmentDate || !appointmentTime) {
this.setData({ conflictTip: '', conflictLevel: 'free' })
return { ok: true }
}
@@ -873,7 +1116,7 @@ Page({
this.setData({ conflictTip: '', conflictLevel: 'free' })
return { ok: true }
}
const startMinute = dateUtil.minutesOfDay(form.appointmentTime)
const startMinute = dateUtil.minutesOfDay(appointmentTime)
const endMinute = startMinute + durationMinutes
if (startMinute < dateUtil.minutesOfDay('10:00') || endMinute > dateUtil.minutesOfDay('22:00')) {
const tip = '该时间超出营业时间 10:00-22:00'
@@ -912,7 +1155,7 @@ Page({
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
return { ok: false, tip }
}
const tip = `${this.data.selectedArtist.name || '该美甲师'} ${form.appointmentTime}-${dateUtil.timeFromMinutes(endMinute)} 可预约`
const tip = `${this.data.selectedArtist.name || '该美甲师'} ${appointmentTime}-${dateUtil.timeFromMinutes(endMinute)} 可预约`
this.setData({ conflictTip: tip, conflictLevel: 'free' })
return { ok: true, tip }
} catch (error) {
@@ -925,8 +1168,12 @@ Page({
async ensureCustomerBeforeSubmit() {
const name = String(this.data.form.customerName || '').trim()
const phone = String(this.data.form.phone || '').trim()
if (!name && !phone) {
this.setData({ 'form.createCustomerRecord': false })
return true
}
if (!name) {
wx.showToast({ title: '请输入客户姓名', icon: 'none' })
wx.showToast({ title: '填写手机号时请同时填写客户姓名', icon: 'none' })
return false
}
if (phone && !/^1[3-9]\d{9}$/.test(phone)) {
@@ -934,6 +1181,7 @@ Page({
return false
}
if (this.data.form.customerUserId) {
this.setData({ 'form.createCustomerRecord': false })
return true
}
@@ -941,6 +1189,20 @@ Page({
try {
const matches = await customersApi.matchIdentity(name, phone || undefined)
if (matches.length > 1) {
const choice = await new Promise(resolve => {
wx.showModal({
title: '找到多个同名客户',
content: phone ? '无法确定唯一客户,请选择已有客户或按散客继续。' : '请先补充手机号或选择一个已有客户,也可以按散客继续。',
cancelText: '不关联提交',
confirmText: '选择客户',
success: resolve,
fail: () => resolve({ confirm: false })
})
})
if (!choice.confirm) {
this.setData({ 'form.createCustomerRecord': false })
return true
}
this.setData({
customerOptions: matches.map(normalizeCustomer).map(buildCustomerSelectorItem),
customerKeyword: name,
@@ -954,20 +1216,22 @@ Page({
wx.showModal({
title: '客户已存在',
content: `系统中已有“${name}”${phone ? `(${phone})` : ''},是否使用该客户?`,
cancelText: '取消',
cancelText: '不关联提交',
confirmText: '使用已有',
success: resolve,
fail: () => resolve({ confirm: false })
})
})
if (!choice.confirm) {
return false
if (choice.confirm) {
this.setData({
'form.customerUserId': customer.id,
'form.customerName': customer.name,
'form.phone': customer.phone,
'form.createCustomerRecord': false
})
} else {
this.setData({ 'form.createCustomerRecord': false })
}
this.setData({
'form.customerUserId': customer.id,
'form.customerName': customer.name,
'form.phone': customer.phone
})
return true
}
@@ -981,11 +1245,7 @@ Page({
fail: () => resolve({ confirm: false })
})
})
if (!createChoice.confirm) {
return false
}
const customerId = await customersApi.create({ nickname: name, phone: phone || undefined })
this.setData({ 'form.customerUserId': customerId })
this.setData({ 'form.createCustomerRecord': Boolean(createChoice.confirm) })
return true
} catch (error) {
wx.showToast({ title: error.message || '客户校验失败,请稍后重试', icon: 'none' })
@@ -1003,13 +1263,25 @@ Page({
wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' })
return
}
const form = this.data.form
const hasManualProduct = String(form.manualProductTitle || '').trim() && String(form.manualProductPrice || '').trim()
let form = this.data.form
const manualProductTitle = String(form.manualProductTitle || '').trim()
const manualProductImageFileIds = String(form.manualProductImageFileIds || '').trim()
const hasManualProduct = Boolean(manualProductTitle || manualProductImageFileIds || String(form.customerName || '').trim())
const amountText = String(form.amount === undefined || form.amount === null ? '' : form.amount).trim()
const amount = Number(amountText)
const durationMinutes = normalizeDuration(form.durationMinutes)
if (!form.customerName || (!form.productId && !hasManualProduct) || !form.appointmentDate || !form.appointmentTime) {
if ((!form.productId && !hasManualProduct) || !form.appointmentDate || !form.appointmentTime || !amountText) {
wx.showToast({ title: '请补全预约信息', icon: 'none' })
return
}
if (!Number.isFinite(amount) || amount < 0) {
wx.showToast({ title: '请输入不小于0的成交金额', icon: 'none' })
return
}
if (form.phone && !String(form.customerName || '').trim()) {
wx.showToast({ title: '填写手机号时请同时填写客户姓名', icon: 'none' })
return
}
if (form.phone && !/^1[3-9]\d{9}$/.test(String(form.phone).trim())) {
wx.showToast({ title: '请输入正确手机号', icon: 'none' })
return
@@ -1039,12 +1311,17 @@ Page({
if (!(await this.ensureCustomerBeforeSubmit())) {
return
}
form = this.data.form
this.setData({ loading: true })
try {
const payload = {
...form,
customerUserId: form.customerUserId ? String(form.customerUserId) : undefined,
artistId: form.artistId ? String(form.artistId) : undefined,
customerName: String(form.customerName || '').trim() || undefined,
phone: String(form.phone || '').trim() || undefined,
amount,
createCustomerRecord: Boolean(form.createCustomerRecord),
durationMinutes,
clientRequestId: buildClientRequestId('manager-appointment')
}
@@ -1054,8 +1331,8 @@ Page({
payload.manualProductPrice = undefined
} else {
payload.productId = undefined
payload.manualProductTitle = String(form.manualProductTitle || '').trim()
payload.manualProductPrice = Number(form.manualProductPrice)
payload.manualProductTitle = manualProductTitle || undefined
payload.manualProductPrice = amount
payload.manualProductDescription = String(form.manualProductDescription || '').trim() || undefined
payload.manualProductTags = String(form.manualProductTags || '').trim() || undefined
payload.manualProductTargetAudience = String(form.manualProductTargetAudience || '').trim() || undefined