Files
JayuCloud/JC-Salon-WeChat/pages/appointment-form/index.js
T

1100 lines
37 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const planningApi = require('../../api/planning')
const productsApi = require('../../api/products')
const customersApi = require('../../api/customers')
const dateUtil = require('../../utils/date')
const { markPlanningRefresh } = require('../../utils/planning-refresh')
const { chooseImageFilePath, uploadObjectFile } = require('../../utils/upload')
const DRAFT_STORAGE_PREFIX = 'managerAppointmentDraft'
const TIME_SLOT_MINUTES = 15
function buildClientRequestId(prefix) {
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
}
function getCalendarArtists(calendar) {
return calendar && Array.isArray(calendar.artists) ? calendar.artists : []
}
function findArtist(artists, artistId) {
return artists.find(item => String(item.id) === String(artistId)) || {}
}
function canCreateAppointment() {
const app = getApp()
const userInfo = app.globalData.userInfo || {}
return Number(userInfo.type) !== 3
}
function buildDraftKey() {
const app = getApp()
const userInfo = app.globalData.userInfo || {}
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() {
try {
const draft = wx.getStorageSync(buildDraftKey())
return draft && draft.form ? draft.form : null
} catch (error) {
throw new Error(`读取预约草稿失败:${error.message || error}`)
}
}
function writeDraftForm(form) {
try {
wx.setStorageSync(buildDraftKey(), {
form,
savedAt: Date.now()
})
} catch (error) {
throw new Error(`保存预约草稿失败:${error.message || error}`)
}
}
function removeDraftForm() {
try {
wx.removeStorageSync(buildDraftKey())
} catch (error) {
throw new Error(`清空预约草稿失败:${error.message || error}`)
}
}
function normalizeDuration(value) {
const duration = Number(value)
return Number.isFinite(duration) && duration > 0 ? Math.floor(duration) : 0
}
function buildTimeRangeLabel(startMinute, durationMinutes) {
return `${dateUtil.timeFromMinutes(startMinute)}-${dateUtil.timeFromMinutes(startMinute + durationMinutes)}`
}
function getTimePeriod(minute) {
if (minute < 12 * 60) {
return { key: 'morning', title: '上午' }
}
if (minute < 18 * 60) {
return { key: 'afternoon', title: '下午' }
}
return { key: 'evening', title: '晚上' }
}
function normalizeAppointmentDate(item) {
return item.date || String(item.startTime || '').slice(0, 10)
}
function extractTimeText(value) {
const target = String(value || '')
if (target.includes('T')) {
return target.slice(11, 16)
}
if (target.includes(' ')) {
return target.slice(11, 16)
}
return target.slice(0, 5)
}
function resolveAppointmentStartMinute(item) {
if (item.startMinute !== undefined && item.startMinute !== null) {
return Number(item.startMinute)
}
return dateUtil.minutesOfDay(extractTimeText(item.startTime))
}
function resolveAppointmentEndMinute(item, startMinute) {
if (item.endMinute !== undefined && item.endMinute !== null) {
return Number(item.endMinute)
}
if (item.endTime) {
return dateUtil.minutesOfDay(extractTimeText(item.endTime))
}
return startMinute + Number(item.durationMinutes || 60)
}
function isCancelledAppointment(item) {
return item.status === 3 || item.statusText === '已取消'
}
function buildBusyRanges(appointments, form) {
return (appointments || [])
.filter(item => String(item.artistId) === String(form.artistId))
.filter(item => normalizeAppointmentDate(item) === form.appointmentDate)
.filter(item => !isCancelledAppointment(item))
.map(item => {
const startMinute = resolveAppointmentStartMinute(item)
return {
startMinute,
endMinute: resolveAppointmentEndMinute(item, startMinute)
}
})
}
function hasBusyConflict(startMinute, endMinute, ranges) {
return ranges.some(range => startMinute < range.endMinute && endMinute > range.startMinute)
}
function buildAvailableTimeGroups(calendar, form, durationMinutes) {
const schedules = (calendar.schedules || [])
.filter(item => String(item.artistId) === String(form.artistId))
.filter(item => item.date === form.appointmentDate)
.filter(item => item.status === 1 && Number(item.capacity === undefined ? 1 : item.capacity) >= 1)
const busyRanges = buildBusyRanges(calendar.appointments || [], form)
const groupMap = {
morning: { key: 'morning', title: '上午', times: [] },
afternoon: { key: 'afternoon', title: '下午', times: [] },
evening: { key: 'evening', title: '晚上', times: [] }
}
schedules.forEach(schedule => {
const scheduleStart = dateUtil.minutesOfDay(extractTimeText(schedule.startTime))
const scheduleEnd = dateUtil.minutesOfDay(extractTimeText(schedule.endTime))
for (let minute = scheduleStart; minute + durationMinutes <= scheduleEnd; minute += TIME_SLOT_MINUTES) {
const endMinute = minute + durationMinutes
if (!hasBusyConflict(minute, endMinute, busyRanges)) {
const period = getTimePeriod(minute)
groupMap[period.key].times.push({
value: dateUtil.timeFromMinutes(minute),
rangeText: buildTimeRangeLabel(minute, durationMinutes)
})
}
}
})
return Object.keys(groupMap)
.map(key => ({
...groupMap[key],
times: groupMap[key].times.filter((item, index, array) => array.findIndex(candidate => candidate.value === item.value) === index)
}))
.filter(group => group.times.length > 0)
}
function buildUnassignedTimeGroups(durationMinutes) {
const groupMap = {
morning: { key: 'morning', title: '上午', times: [] },
afternoon: { key: 'afternoon', title: '下午', times: [] },
evening: { key: 'evening', title: '晚上', times: [] }
}
const businessStart = dateUtil.minutesOfDay('10:00')
const businessEnd = dateUtil.minutesOfDay('22:00')
for (let minute = businessStart; minute + durationMinutes <= businessEnd; minute += TIME_SLOT_MINUTES) {
const period = getTimePeriod(minute)
groupMap[period.key].times.push({
value: dateUtil.timeFromMinutes(minute),
rangeText: buildTimeRangeLabel(minute, durationMinutes)
})
}
return Object.keys(groupMap).map(key => groupMap[key]).filter(group => group.times.length > 0)
}
function flattenTimeGroups(groups) {
return (groups || []).reduce((list, group) => list.concat(group.times || []), [])
}
function parseProductTags(product) {
if (Array.isArray(product.tagList) && product.tagList.length > 0) {
return product.tagList
}
if (Array.isArray(product.tagInfos) && product.tagInfos.length > 0) {
return product.tagInfos.map(item => item.tagName).filter(Boolean)
}
return String(product.tags || '')
.split(/[;,,、]/)
.map(item => item.trim())
.filter(Boolean)
}
function normalizeProduct(product, artists) {
const imageUrls = Array.isArray(product.imageUrls) ? product.imageUrls : []
const bookableArtists = String(product.bookableArtists || '')
.split(',')
.map(item => item.trim())
.filter(Boolean)
const artistNames = bookableArtists
.map(id => findArtist(artists, id).name)
.filter(Boolean)
const durationText = product.approximateDuration || (product.serviceDurationMinutes ? `${product.serviceDurationMinutes}分钟` : '')
return {
...product,
coverImage: imageUrls[0] || '',
tagList: parseProductTags(product).slice(0, 4),
artistText: artistNames.length > 0 ? artistNames.join('、') : '全部美甲师',
priceText: product.price || product.price === 0 ? `¥${product.price}` : '价格待定',
durationText
}
}
function isScheduleCoveringTime(schedule, form, startMinute, endMinute) {
if (!schedule || String(schedule.artistId) !== String(form.artistId) || schedule.date !== form.appointmentDate) {
return false
}
if (schedule.status !== 1 || Number(schedule.capacity === undefined ? 1 : schedule.capacity) < 1) {
return false
}
const scheduleStartMinute = dateUtil.minutesOfDay(extractTimeText(schedule.startTime))
const scheduleEndMinute = dateUtil.minutesOfDay(extractTimeText(schedule.endTime))
return scheduleStartMinute <= startMinute && scheduleEndMinute >= endMinute
}
function normalizeCustomer(customer) {
const name = customer.nickname || customer.name || customer.account || ''
const phone = customer.contactPhone || customer.phone || ''
return {
id: customer.id,
name,
phone,
displayName: name || phone || '客户',
displayPhone: phone || '未填写手机号'
}
}
function buildCustomerSelectorItem(customer) {
return {
...customer,
title: customer.displayName,
subtitle: customer.displayPhone,
badge: '已有客户'
}
}
function buildArtistSelectorItem(artist) {
return {
...artist,
title: artist.name || '未命名员工',
subtitle: artist.statusText || '可用于指定预约',
meta: artist.workStartTime && artist.workEndTime ? `${artist.workStartTime.slice(0, 5)}-${artist.workEndTime.slice(0, 5)}` : '',
avatar: artist.avatar || artist.avatarUrl || '/assets/images/default-user-avatar.png'
}
}
Page({
data: {
form: {
customerUserId: '',
customerName: '',
phone: '',
appointmentDate: dateUtil.formatDate(new Date()),
appointmentTime: '',
productId: '',
manualProductTitle: '',
manualProductPrice: '',
manualProductDescription: '',
manualProductTags: '',
manualProductTargetAudience: '',
manualProductPrecautions: '',
manualProductImageFileIds: '',
manualProductImageUrl: '',
durationMinutes: '',
artistId: '',
remark: ''
},
manualProductDraft: { title: '', price: '', description: '', tags: '', targetAudience: '', precautions: '', imageFileIds: '', imageUrl: '' },
customerOptions: [],
customerSheetVisible: false,
customerKeyword: '',
customerLoading: false,
customerError: '',
products: [],
filteredProducts: [],
artists: [],
artistSelectorItems: [],
artistSheetVisible: false,
artistKeyword: '',
artistError: '',
selectedProduct: {},
selectedProductPriceText: '',
selectedArtist: {},
productModalVisible: false,
productSelectorMode: 'list',
manualProductMoreExpanded: false,
productKeyword: '',
productError: '',
loadingProducts: false,
conflictTip: '',
conflictLevel: 'free',
canCreateAppointment: true,
draftSavedAtText: '',
manualImageUploading: false,
timeSheetVisible: false,
timeLoading: false,
timeError: '',
timeSelectTip: '请先选择美甲师并填写时长',
availableTimeGroups: [],
loading: false
},
onLoad(options) {
const creatable = canCreateAppointment()
const draftForm = creatable && !hasPresetOptions(options) ? readDraftForm() : null
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,
customerName: options.customerName ? decodeURIComponent(options.customerName) : (baseForm.customerName || ''),
phone: options.phone ? decodeURIComponent(options.phone) : (baseForm.phone || ''),
appointmentDate: options.date || baseForm.appointmentDate || dateUtil.formatDate(new Date()),
artistId: options.artistId || baseForm.artistId || ''
},
draftSavedAtText: draftForm ? '已恢复本机草稿' : ''
})
if (!creatable) {
wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' })
return
}
this.loadOptions()
},
async loadOptions() {
this.setData({ loadingProducts: true })
try {
const productsData = await productsApi.list({ page: 1, size: 100 })
const products = productsData.list || productsData || []
this.setData({ products, productError: '' })
} catch (error) {
this.setData({
products: [],
filteredProducts: [],
productError: error.message || '作品列表加载失败'
})
} finally {
this.setData({ loadingProducts: false })
}
await this.loadArtists()
this.refreshProductCards()
const selectedProduct = this.data.filteredProducts.find(item => String(item.id) === String(this.data.form.productId)) || {}
this.setData({
selectedProduct,
selectedProductPriceText: selectedProduct.priceText || ''
})
await this.refreshAvailableTimes()
this.checkAvailability()
},
async loadArtists(preferredArtistId, fallbackEmployee) {
try {
const calendar = await planningApi.calendar({
startDate: this.data.form.appointmentDate,
endDate: this.data.form.appointmentDate
})
let artists = getCalendarArtists(calendar)
const requestedId = preferredArtistId || this.data.form.artistId
if (fallbackEmployee && requestedId && !findArtist(artists, requestedId).id) {
artists = artists.concat({
id: requestedId,
name: fallbackEmployee.name || fallbackEmployee.title,
avatar: fallbackEmployee.avatar || ''
})
}
const selectedArtist = requestedId ? findArtist(artists, requestedId) : {}
this.setData({
artists,
artistSelectorItems: this.filterArtistItems(artists, this.data.artistKeyword),
selectedArtist,
artistError: '',
'form.artistId': selectedArtist.id || ''
})
this.refreshProductCards()
} catch (error) {
this.setData({
artists: [],
artistSelectorItems: [],
selectedArtist: {},
'form.artistId': '',
artistError: error.message || '员工列表加载失败',
conflictTip: error.message || '美甲师列表加载失败',
conflictLevel: 'danger'
})
}
},
onInput(event) {
const field = event.currentTarget.dataset.field
const patch = {
[`form.${field}`]: event.detail.value
}
this.setData(patch)
if (field === 'durationMinutes') {
this.refreshAvailableTimes()
this.checkAvailability()
}
},
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'] = ''
}
this.setData({
...patch
})
},
openCustomerSheet() {
this.setData({ customerSheetVisible: true })
this.searchCustomers(this.data.customerKeyword)
},
closeCustomerSheet() {
this.setData({ customerSheetVisible: false })
},
onCustomerSearch(event) {
const keyword = event.detail.value
this.setData({ customerKeyword: keyword })
clearTimeout(this._customerTimer)
this._customerTimer = setTimeout(() => this.searchCustomers(keyword), 250)
},
async searchCustomers(keywordValue) {
if (!this.data.canCreateAppointment) {
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 })
}
},
retryCustomerSearch() {
this.searchCustomers(this.data.customerKeyword)
},
selectCustomer(event) {
const customer = event.detail.item
if (!customer) {
return
}
this.setData({
'form.customerUserId': customer.id,
'form.customerName': customer.name,
'form.phone': customer.phone,
customerSheetVisible: false,
customerKeyword: ''
})
},
onUnload() {
if (this._customerTimer) {
clearTimeout(this._customerTimer)
}
},
async onDateChange(event) {
const nextDate = event.detail.value
const today = dateUtil.formatDate(new Date())
if (nextDate < today) {
const result = await new Promise(resolve => {
wx.showModal({
title: '历史日期不能新建预约',
content: '之前的日期只能作为历史补单记录,不会校验员工排班,也不会占用预约时段。',
cancelText: '取消',
confirmText: '去补单',
success: resolve,
fail: () => resolve({ confirm: false })
})
})
if (result.confirm) {
const query = [`serviceDate=${encodeURIComponent(nextDate)}`]
if (this.data.form.artistId) {
query.push(`artistId=${encodeURIComponent(this.data.form.artistId)}`)
}
wx.navigateTo({ url: `/pages/backfill-order/index?${query.join('&')}` })
}
return
}
this.setData({
'form.appointmentDate': nextDate,
'form.appointmentTime': ''
})
await this.loadArtists()
await this.refreshAvailableTimes()
this.checkAvailability()
},
refreshProductCards() {
const keyword = this.data.productKeyword.trim().toLowerCase()
const products = this.data.products
.map(product => normalizeProduct(product, this.data.artists))
.filter(product => {
if (!keyword) return true
return [product.title, product.artistText, product.priceText, product.durationText, ...(product.tagList || [])]
.some(value => String(value || '').toLowerCase().includes(keyword))
})
this.setData({ filteredProducts: products })
},
openProductModal() {
this.refreshProductCards()
this.setData({ productModalVisible: true, productSelectorMode: 'list' })
},
closeProductModal() {
this.setData({ productModalVisible: false, productSelectorMode: 'list' })
},
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 })
},
stopTap() {
},
stopTouchMove() {
},
onProductSearch(event) {
this.setData({ productKeyword: event.detail.value })
this.refreshProductCards()
},
selectProduct(event) {
const selectedProduct = event.detail.item || this.data.filteredProducts.find(item => String(item.id) === String(event.currentTarget.dataset.id)) || {}
const selectedDuration = parseInt(selectedProduct.serviceDurationMinutes || selectedProduct.approximateDuration, 10)
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.durationMinutes': String(selectedDuration || this.data.form.durationMinutes || '')
})
this.closeProductModal()
this.refreshAvailableTimes()
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
}
try {
const filePath = await chooseImageFilePath()
if (!filePath) {
return
}
this.setData({ manualImageUploading: true })
const uploadResult = await uploadObjectFile(filePath)
const fileId = uploadResult.id || uploadResult.fileId
const fileUrl = uploadResult.fileUrl || uploadResult.primaryUrl || filePath
if (!fileId) {
throw new Error('作品图片上传成功但未返回文件ID')
}
this.setData({
'manualProductDraft.imageFileIds': String(fileId),
'manualProductDraft.imageUrl': fileUrl
})
} catch (error) {
wx.showToast({ title: error.message || '图片上传失败', icon: 'none' })
} finally {
this.setData({ manualImageUploading: false })
}
},
removeManualProductImage() {
this.setData({
'manualProductDraft.imageFileIds': '',
'manualProductDraft.imageUrl': ''
})
},
filterArtistItems(artists, keywordValue) {
const keyword = String(keywordValue || '').trim().toLowerCase()
const items = (artists || [])
.filter(item => !keyword || String(item.name || '').toLowerCase().includes(keyword))
.map(buildArtistSelectorItem)
if (!keyword || '暂不分配'.includes(keyword)) {
items.unshift({ id: '__unassigned__', title: '暂不分配', subtitle: '先记录预约,后续再分配员工', badge: '待分配' })
}
return items
},
openArtistSheet() {
this.setData({
artistSheetVisible: true,
artistSelectorItems: this.filterArtistItems(this.data.artists, this.data.artistKeyword)
})
},
closeArtistSheet() {
this.setData({ artistSheetVisible: false })
},
retryArtists() {
this.loadArtists()
},
onArtistSearch(event) {
const artistKeyword = event.detail.value
this.setData({
artistKeyword,
artistSelectorItems: this.filterArtistItems(this.data.artists, artistKeyword)
})
},
selectArtist(event) {
const selectedArtist = event.detail.item || {}
if (selectedArtist.id === '__unassigned__') {
this.setData({
selectedArtist: {},
'form.artistId': '',
artistSheetVisible: false,
conflictTip: '',
conflictLevel: 'free'
})
this.refreshAvailableTimes()
return
}
this.setData({
selectedArtist,
'form.artistId': selectedArtist.id,
'form.appointmentTime': '',
artistSheetVisible: false
})
this.refreshAvailableTimes()
this.checkAvailability()
},
addEmployeeFromSelector() {
this.setData({ artistSheetVisible: false })
wx.navigateTo({
url: `/pages/employee-create/index?picker=1&date=${encodeURIComponent(this.data.form.appointmentDate || '')}&time=${encodeURIComponent(this.data.form.appointmentTime || '')}&durationMinutes=${encodeURIComponent(this.data.form.durationMinutes || '')}`,
success: result => {
result.eventChannel.on('employeeCreated', employee => this.handleEmployeeCreated(employee))
}
})
},
async handleEmployeeCreated(employee) {
const originalTime = this.data.form.appointmentTime
await this.loadArtists(employee.autoSelect === false ? '' : employee.id, employee)
if (employee.autoSelect === false) {
this.setData({ selectedArtist: {}, 'form.artistId': '' })
await this.refreshAvailableTimes()
return
}
if (employee.scheduleSaved && originalTime) {
const availability = await this.checkAvailability()
if (!availability.ok) {
this.setData({
selectedArtist: {},
'form.artistId': '',
'form.appointmentTime': originalTime,
conflictTip: `${availability.tip || '新员工当前排班无法承接'},预约已保持待分配`,
conflictLevel: 'danger'
})
}
} else {
this.setData({ 'form.appointmentTime': '' })
}
await this.refreshAvailableTimes()
if (this.data.form.artistId) this.checkAvailability()
},
canOpenTimeSheet() {
const form = this.data.form
return Boolean(form.appointmentDate && normalizeDuration(form.durationMinutes))
},
async refreshAvailableTimes() {
const form = this.data.form
const durationMinutes = normalizeDuration(form.durationMinutes)
const requestSeq = (this._availableTimeRequestSeq || 0) + 1
this._availableTimeRequestSeq = requestSeq
if (!form.appointmentDate || !durationMinutes) {
const patch = {
availableTimeGroups: [],
timeError: '',
timeSelectTip: '请先填写预约日期和时长'
}
if (form.appointmentTime) {
patch['form.appointmentTime'] = ''
}
this.setData(patch)
return
}
if (!form.artistId) {
const availableTimeGroups = buildUnassignedTimeGroups(durationMinutes)
this.setData({
availableTimeGroups,
timeError: '',
timeLoading: false,
timeSelectTip: '请选择预约时间,员工可稍后分配'
})
return
}
this.setData({
timeLoading: true,
timeError: '',
timeSelectTip: '正在计算可约时间...'
})
try {
const calendar = await planningApi.calendar({
startDate: form.appointmentDate,
endDate: form.appointmentDate,
artistId: form.artistId
})
if (requestSeq !== this._availableTimeRequestSeq) {
return
}
const availableTimeGroups = buildAvailableTimeGroups(calendar, form, durationMinutes)
const availableTimes = flattenTimeGroups(availableTimeGroups).map(item => item.value)
const patch = {
availableTimeGroups,
timeSelectTip: availableTimes.length > 0 ? '请选择预约时间' : '当前美甲师当天暂无可约时间'
}
if (form.appointmentTime && !availableTimes.includes(form.appointmentTime)) {
patch['form.appointmentTime'] = ''
}
this.setData(patch)
} catch (error) {
if (requestSeq !== this._availableTimeRequestSeq) {
return
}
this.setData({
availableTimeGroups: [],
timeError: error.message || '可约时间加载失败',
timeSelectTip: '可约时间加载失败'
})
} finally {
if (requestSeq === this._availableTimeRequestSeq) {
this.setData({ timeLoading: false })
}
}
},
async openTimeSheet() {
if (!this.canOpenTimeSheet()) {
wx.showToast({ title: '请先填写预约日期和时长', icon: 'none' })
return
}
this.setData({ timeSheetVisible: true })
await this.refreshAvailableTimes()
},
closeTimeSheet() {
this.setData({ timeSheetVisible: false })
},
selectAvailableTime(event) {
const value = event.currentTarget.dataset.value
this.setData({
'form.appointmentTime': value,
timeSheetVisible: false
})
this.checkAvailability()
},
async checkAvailability() {
const form = this.data.form
if (!form.appointmentDate || !form.appointmentTime) {
this.setData({ conflictTip: '', conflictLevel: 'free' })
return { ok: true }
}
const durationMinutes = normalizeDuration(form.durationMinutes)
if (!durationMinutes) {
this.setData({ conflictTip: '', conflictLevel: 'free' })
return { ok: true }
}
const startMinute = dateUtil.minutesOfDay(form.appointmentTime)
const endMinute = startMinute + durationMinutes
if (startMinute < dateUtil.minutesOfDay('10:00') || endMinute > dateUtil.minutesOfDay('22:00')) {
const tip = '该时间超出营业时间 10:00-22:00'
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
return { ok: false, tip }
}
if (!form.artistId) {
const tip = '预约将保存为待分配,当前不会占用员工时间'
this.setData({ conflictTip: tip, conflictLevel: 'free' })
return { ok: true, tip }
}
try {
const calendar = await planningApi.calendar({
startDate: form.appointmentDate,
endDate: form.appointmentDate,
artistId: form.artistId
})
const schedule = (calendar.schedules || []).find(item => isScheduleCoveringTime(item, form, startMinute, endMinute))
if (!schedule) {
const tip = `${this.data.selectedArtist.name || '该美甲师'} 当前时段无可预约排班`
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
return { ok: false, tip }
}
const conflicts = (calendar.appointments || []).filter(item => {
if (String(item.artistId) !== String(form.artistId) || normalizeAppointmentDate(item) !== form.appointmentDate) return false
if (isCancelledAppointment(item)) return false
const itemStart = resolveAppointmentStartMinute(item)
const itemEnd = resolveAppointmentEndMinute(item, itemStart)
return startMinute < itemEnd && endMinute > itemStart
})
if (conflicts.length > 0) {
const first = conflicts[0]
const itemStart = resolveAppointmentStartMinute(first)
const itemEnd = resolveAppointmentEndMinute(first, itemStart)
const tip = `${this.data.selectedArtist.name || '该美甲师'} ${dateUtil.timeFromMinutes(itemStart)}-${dateUtil.timeFromMinutes(itemEnd)} 已有预约`
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
return { ok: false, tip }
}
const tip = `${this.data.selectedArtist.name || '该美甲师'} ${form.appointmentTime}-${dateUtil.timeFromMinutes(endMinute)} 可预约`
this.setData({ conflictTip: tip, conflictLevel: 'free' })
return { ok: true, tip }
} catch (error) {
const tip = error.message || '排班校验失败,请稍后重试'
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
return { ok: false, tip }
}
},
async ensureCustomerBeforeSubmit() {
const name = String(this.data.form.customerName || '').trim()
const phone = String(this.data.form.phone || '').trim()
if (!name) {
wx.showToast({ title: '请输入客户姓名', icon: 'none' })
return false
}
if (phone && !/^1[3-9]\d{9}$/.test(phone)) {
wx.showToast({ title: '请输入正确手机号', icon: 'none' })
return false
}
if (this.data.form.customerUserId) {
return true
}
this.setData({ loading: true })
try {
const matches = await customersApi.matchIdentity(name, phone || undefined)
if (matches.length > 1) {
this.setData({
customerOptions: matches.map(normalizeCustomer).map(buildCustomerSelectorItem),
customerKeyword: name,
customerSheetVisible: true
})
return false
}
if (matches.length > 0) {
const customer = normalizeCustomer(matches[0])
const choice = await new Promise(resolve => {
wx.showModal({
title: '客户已存在',
content: `系统中已有“${name}”${phone ? `(${phone})` : ''},是否使用该客户?`,
cancelText: '取消',
confirmText: '使用已有',
success: resolve,
fail: () => resolve({ confirm: false })
})
})
if (!choice.confirm) {
return false
}
this.setData({
'form.customerUserId': customer.id,
'form.customerName': customer.name,
'form.phone': customer.phone
})
return true
}
const createChoice = await new Promise(resolve => {
wx.showModal({
title: '新建客户',
content: '系统中没有匹配客户,是否新建到客户档案?',
cancelText: '不新建',
confirmText: '确认',
success: resolve,
fail: () => resolve({ confirm: false })
})
})
if (!createChoice.confirm) {
return false
}
const customerId = await customersApi.create({ nickname: name, phone: phone || undefined })
this.setData({ 'form.customerUserId': customerId })
return true
} catch (error) {
wx.showToast({ title: error.message || '客户校验失败,请稍后重试', icon: 'none' })
return false
} finally {
this.setData({ loading: false })
}
},
async submit() {
if (this.data.loading) {
return
}
if (!this.data.canCreateAppointment) {
wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' })
return
}
const form = this.data.form
const hasManualProduct = String(form.manualProductTitle || '').trim() && String(form.manualProductPrice || '').trim()
const durationMinutes = normalizeDuration(form.durationMinutes)
if (!form.customerName || (!form.productId && !hasManualProduct) || !form.appointmentDate || !form.appointmentTime) {
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
}
if (!durationMinutes) {
wx.showToast({ title: '请填写预约时长', icon: 'none' })
return
}
const availability = await this.checkAvailability()
if (!availability.ok) {
wx.showToast({ title: availability.tip || '该时段已被预约', icon: 'none' })
return
}
if (!form.artistId) {
const result = await new Promise(resolve => {
wx.showModal({
title: '保存为待分配预约',
content: '当前未指定员工,预约会正常保存,但不会占用员工时间。可以稍后在预约详情中分配。',
cancelText: '返回选择',
confirmText: '继续保存',
success: resolve,
fail: () => resolve({ confirm: false })
})
})
if (!result.confirm) return
}
if (!(await this.ensureCustomerBeforeSubmit())) {
return
}
this.setData({ loading: true })
try {
const payload = {
...form,
customerUserId: form.customerUserId ? String(form.customerUserId) : undefined,
artistId: form.artistId ? String(form.artistId) : undefined,
durationMinutes,
clientRequestId: buildClientRequestId('manager-appointment')
}
if (form.productId) {
payload.productId = String(form.productId)
payload.manualProductTitle = undefined
payload.manualProductPrice = undefined
} else {
payload.productId = undefined
payload.manualProductTitle = String(form.manualProductTitle || '').trim()
payload.manualProductPrice = Number(form.manualProductPrice)
payload.manualProductDescription = String(form.manualProductDescription || '').trim() || undefined
payload.manualProductTags = String(form.manualProductTags || '').trim() || undefined
payload.manualProductTargetAudience = String(form.manualProductTargetAudience || '').trim() || undefined
payload.manualProductPrecautions = String(form.manualProductPrecautions || '').trim() || undefined
payload.manualProductImageFileIds = String(form.manualProductImageFileIds || '').trim() || undefined
}
const result = await planningApi.createAppointment(payload)
removeDraftForm()
markPlanningRefresh()
wx.redirectTo({ url: `/pages/appointment-detail/index?id=${result.orderItemId}` })
} catch (error) {
wx.showToast({ title: error.message || '提交失败', icon: 'none' })
} finally {
this.setData({ loading: false })
}
},
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' })
}
},
back() {
wx.navigateBack()
}
})