小程序预约详情支持图片预览、编辑预约与完成收款拆分
自动发布开发环境 Nacos 配置 / publish (push) Successful in 34s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 11s

This commit is contained in:
2026-11-09 15:18:27 +08:00
parent 6f6625bc0d
commit 69ea01eaa4
18 changed files with 801 additions and 61 deletions
@@ -0,0 +1,155 @@
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const planningApi = require('../../api/planning')
let appGlobalData = { userInfo: { type: 2 } }
global.wx = {
getAccountInfoSync: () => ({ miniProgram: { envVersion: 'develop' } }),
getDeviceInfo: () => ({ platform: 'devtools' }),
removeStorageSync: () => {},
setStorageSync: () => {},
showToast: () => {},
showModal: options => { if (options.success) options.success({ confirm: true }) },
navigateTo: () => {},
navigateBack: () => {},
setNavigationBarTitle: () => {},
redirectTo: () => {}
}
global.getApp = () => ({ globalData: appGlobalData })
global.getCurrentPages = () => []
let definition
global.Page = value => { definition = value }
require('./index')
function createPage() {
return {
...definition,
data: JSON.parse(JSON.stringify(definition.data)),
setData(values) {
Object.entries(values).forEach(([key, value]) => {
const parts = key.split('.')
let target = this.data
for (let index = 0; index < parts.length - 1; index += 1) target = target[parts[index]]
target[parts[parts.length - 1]] = value
})
}
}
}
async function run() {
const appointmentWxml = fs.readFileSync(path.join(__dirname, 'index.wxml'), 'utf8')
const artistIndex = appointmentWxml.indexOf('bindtap="openArtistSheet"')
const timeIndex = appointmentWxml.indexOf('bindtap="openTimeSheet"')
assert.ok(artistIndex > -1 && timeIndex > -1)
assert.ok(artistIndex < timeIndex, '美甲师字段应位于预约时间之前')
assert.match(appointmentWxml, /editMode \? '保存修改' : '提交预约'/)
planningApi.appointment = async () => ({
orderItemId: 88,
orderId: 77,
orderNo: 'SALON-088',
customerUserId: 31,
customerName: '测试客户',
customerPhone: '138****8000',
customerPhoneAvailable: false,
artistId: 9,
artistName: '小李',
startTime: '2027-05-01T10:30:00',
endTime: '2027-05-01T11:30:00',
durationMinutes: 60,
amount: 268,
productId: 41,
productTitle: '猫眼甲',
productSourceType: 'LIBRARY',
remark: '加急',
status: 1,
canEdit: true
})
planningApi.calendar = async () => ({
businessStartTime: '09:00',
businessEndTime: '20:00',
artists: [{ id: 9, name: '小李' }],
schedules: [{ artistId: 9, date: '2027-05-01', status: 1, capacity: 1, startTime: '09:00', endTime: '20:00' }],
appointments: [{ orderItemId: 88, artistId: 9, startTime: '2027-05-01T10:30:00', endTime: '2027-05-01T11:30:00' }]
})
planningApi.products = async () => ({ list: [{ id: 41, title: '猫眼甲', price: 268, approximateDuration: '60分钟' }] })
const page = createPage()
page.data.form.durationMinutes = '60'
await page.loadEditAppointment(88)
assert.strictEqual(page.data.editMode, true)
assert.strictEqual(page._editMode, true)
assert.strictEqual(page.data.form.customerName, '测试客户')
assert.strictEqual(page.data.form.phone, '')
assert.strictEqual(page.data.form.appointmentDate, '2027-05-01')
assert.strictEqual(page.data.form.appointmentTime, '10:30')
assert.strictEqual(String(page.data.form.artistId), '9')
assert.strictEqual(String(page.data.form.productId), '41')
assert.strictEqual(page.data.form.amount, '268')
assert.ok(Object.keys(page.data.availableTimeGroups).length > -1 || page._editOriginalSchedule)
const availability = await page.checkAvailability()
assert.strictEqual(availability.ok, true)
let updatedPayload = null
let updatedId = ''
let creatorCalled = false
planningApi.updateAppointment = async (id, payload) => {
updatedId = id
updatedPayload = payload
return { orderItemId: 88 }
}
planningApi.createAppointment = async () => {
creatorCalled = true
return {}
}
page.cancelDraftSave = () => {}
await page.submit()
assert.strictEqual(creatorCalled, false)
assert.strictEqual(updatedId, '88')
assert.strictEqual(updatedPayload.customerName, '测试客户')
assert.strictEqual(updatedPayload.amount, 268)
assert.strictEqual(updatedPayload.appointmentTime, '10:30')
const original = page.isEditOriginalSchedule('2027-05-01', '10:30')
assert.strictEqual(original, true)
assert.strictEqual(page.isEditOriginalSchedule('2027-05-01', '11:00'), false)
const manualPage = createPage()
planningApi.appointment = async () => ({
orderItemId: 89,
customerName: '散客',
customerPhoneAvailable: false,
artistId: null,
startTime: '2027-05-02T09:00:00',
durationMinutes: 90,
amount: 150,
productId: 55,
productSourceType: 'MANAGER_APPOINTMENT',
productTitle: '手绘款',
productDescription: '渐变',
productImageFileIds: 'f1,f2',
coverImages: ['https://cdn/f1.png'],
status: 1,
canEdit: true
})
planningApi.products = async () => ({ list: [] })
planningApi.calendar = async () => ({ businessStartTime: '09:00', businessEndTime: '20:00', artists: [], schedules: [], appointments: [] })
await manualPage.loadEditAppointment(89)
assert.strictEqual(manualPage.data.form.productId, '')
assert.strictEqual(manualPage.data.form.manualProductTitle, '手绘款')
assert.strictEqual(manualPage.data.form.manualProductDescription, '渐变')
assert.strictEqual(manualPage.data.form.manualProductImages.length, 2)
assert.strictEqual(manualPage.data.form.artistId, '')
assert.strictEqual(manualPage.data.selectedArtist.id, '__unassigned__')
}
run().catch(error => {
console.error(error)
process.exitCode = 1
})
+143 -17
View File
@@ -236,8 +236,9 @@ function isCancelledAppointment(item) {
return item.status === 3 || item.statusText === '已取消'
}
function buildBusyRanges(appointments, form) {
function buildBusyRanges(appointments, form, excludeOrderItemId) {
return (appointments || [])
.filter(item => !excludeOrderItemId || String(item.orderItemId) !== String(excludeOrderItemId))
.filter(item => String(item.artistId) === String(form.artistId))
.filter(item => normalizeAppointmentDate(item) === form.appointmentDate)
.filter(item => !isCancelledAppointment(item))
@@ -278,12 +279,12 @@ function resolveBusinessHours(calendar, targetDate) {
return { start, end }
}
function buildAvailableTimeGroups(calendar, form, durationMinutes) {
function buildAvailableTimeGroups(calendar, form, durationMinutes, excludeOrderItemId) {
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 busyRanges = buildBusyRanges(calendar.appointments || [], form, excludeOrderItemId)
const today = dateUtil.formatDate(new Date())
const now = new Date()
const currentMinute = now.getHours() * 60 + now.getMinutes()
@@ -366,9 +367,9 @@ function buildTimeValues(durationMinutes, businessStart, businessEnd, appointmen
return values
}
function buildTimePickerSlots(calendar, form, durationMinutes) {
function buildTimePickerSlots(calendar, form, durationMinutes, excludeOrderItemId) {
const schedules = calendar.schedules || []
const busyRanges = form.artistId ? buildBusyRanges(calendar.appointments || [], form) : []
const busyRanges = form.artistId ? buildBusyRanges(calendar.appointments || [], form, excludeOrderItemId) : []
const businessHours = resolveBusinessHours(calendar, form.appointmentDate)
if (!businessHours.start) return []
const businessStart = businessHours.start
@@ -648,10 +649,33 @@ Page({
appointmentDateBadge: '',
appointmentDateLong: '',
availableTimeGroups: [],
loading: false
loading: false,
editMode: false
},
onLoad(options = {}) {
const editId = options && options.mode === 'edit' ? String(options.id || '') : ''
if (editId) {
if (!canCreateAppointment()) {
wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' })
wx.navigateBack()
return
}
this._editMode = true
this._editAppointmentId = editId
this._draftReady = false
this._draftPersistenceDisabled = true
this.setData({
editMode: true,
canCreateAppointment: canCreateAppointment(),
canManageShopSettings: isShopManager(),
'form.durationMinutes': '60',
draftSavedAtText: ''
})
wx.setNavigationBarTitle({ title: '编辑预约' })
this.loadEditAppointment(editId)
return
}
const manualDateMode = options && options.dateMode === 'manual'
const today = dateUtil.formatDate(new Date())
if (options && options.date && options.date < today) {
@@ -748,6 +772,88 @@ Page({
wx.navigateTo({ url: '/pages/shop-settings/index' })
},
async loadEditAppointment(id) {
this._editMode = true
this._editAppointmentId = String(id || '')
this._draftPersistenceDisabled = true
this.setData({ loading: true, editMode: true })
try {
const appointment = await planningApi.appointment(id)
const startTime = String(appointment.startTime || '')
const appointmentDate = startTime ? startTime.slice(0, 10) : String(appointment.date || '')
const appointmentTime = startTime ? startTime.slice(11, 16) : ''
const manualProduct = String(appointment.productSourceType || '') === 'MANAGER_APPOINTMENT'
const manualImages = String(appointment.productImageFileIds || '')
.split(',')
.map(fileId => fileId.trim())
.filter(Boolean)
.slice(0, 9)
.map((fileId, index) => ({
fileId,
fileUrl: index === 0 && appointment.coverImages && appointment.coverImages[0] ? String(appointment.coverImages[0]) : '',
previewUrl: index === 0 && appointment.coverImages && appointment.coverImages[0] ? String(appointment.coverImages[0]) : ''
}))
const form = {
...this.data.form,
customerUserId: appointment.customerUserId ? String(appointment.customerUserId) : '',
customerName: appointment.customerName || '',
phone: appointment.customerPhoneAvailable ? String(appointment.customerPhone || '') : '',
wechatId: '',
appointmentDate,
appointmentTime,
amount: appointment.amount === null || appointment.amount === undefined ? '' : String(appointment.amount),
productId: manualProduct ? '' : (appointment.productId ? String(appointment.productId) : ''),
manualProductTitle: manualProduct ? String(appointment.productTitle || '') : '',
manualProductPrice: manualProduct ? (appointment.amount === null || appointment.amount === undefined ? '' : String(appointment.amount)) : '',
manualProductDescription: manualProduct ? String(appointment.productDescription || '') : '',
manualProductTags: manualProduct ? String(appointment.productTags || '') : '',
manualProductTargetAudience: manualProduct ? String(appointment.productTargetAudience || '') : '',
manualProductPrecautions: manualProduct ? String(appointment.productPrecautions || '') : '',
manualProductImageFileIds: manualImages.map(image => image.fileId).join(','),
manualProductImageUrl: manualImages[0] ? manualImages[0].previewUrl || manualImages[0].fileUrl : '',
manualProductImages: manualImages,
durationMinutes: appointment.durationMinutes ? String(appointment.durationMinutes) : '60',
artistId: appointment.artistId ? String(appointment.artistId) : '',
createCustomerRecord: false,
remark: appointment.remark || ''
}
this._editOriginalSchedule = {
appointmentDate,
appointmentTime,
artistId: form.artistId,
durationMinutes: form.durationMinutes
}
const dateLabels = buildAppointmentDateLabels(appointmentDate)
this.setData({
form,
unifiedStyleDescription: String(appointment.remark || appointment.productDescription || ''),
manualProductTitleLength: String(form.manualProductTitle).length,
selectedArtist: appointment.artistId
? { id: String(appointment.artistId), name: appointment.artistName || '' }
: { id: '__unassigned__', name: '暂不分配美甲师' },
draftSavedAtText: '',
appointmentDayLabel: dateLabels.day,
appointmentDateBadge: dateLabels.badge,
appointmentDateLong: dateLabels.long,
durationManuallyChanged: true,
canCreateAppointment: canCreateAppointment()
})
await this.loadOptions()
} catch (error) {
this.setData({ loading: false })
wx.showToast({ title: toUserMessage(error, '预约加载失败'), icon: 'none' })
return
}
this.setData({ loading: false })
},
isEditOriginalSchedule(date, time) {
const origin = this._editOriginalSchedule
return Boolean(this._editMode && origin
&& String(date || '') === String(origin.appointmentDate || '')
&& String(time || '') === String(origin.appointmentTime || ''))
},
async loadOptions() {
this.setData({ loadingProducts: true })
try {
@@ -1099,6 +1205,7 @@ Page({
},
persistDraft(showToast) {
if (this._editMode) return
try {
if (!hasDraftContent(
this.data.form,
@@ -1595,7 +1702,7 @@ Page({
timePickerHours: [],
timePickerMinutes: [],
selectedTimeCandidate: '',
'form.appointmentTime': '',
'form.appointmentTime': this.isEditOriginalSchedule(form.appointmentDate, form.appointmentTime) ? form.appointmentTime : '',
timeError: message,
businessHoursMissing: !closed,
timeLoading: false,
@@ -1665,7 +1772,7 @@ Page({
timePickerHours: [],
timePickerMinutes: [],
selectedTimeCandidate: '',
'form.appointmentTime': '',
'form.appointmentTime': this.isEditOriginalSchedule(form.appointmentDate, form.appointmentTime) ? form.appointmentTime : '',
timeError: message,
businessHoursMissing: !closed,
timeLoading: false,
@@ -1673,9 +1780,9 @@ Page({
})
return
}
const availableTimeGroups = buildAvailableTimeGroups(calendar, form, durationMinutes)
const availableTimeGroups = buildAvailableTimeGroups(calendar, form, durationMinutes, this._editAppointmentId)
const availableTimes = flattenTimeGroups(availableTimeGroups).map(item => item.value)
const timePickerSlots = buildTimePickerSlots(calendar, form, durationMinutes)
const timePickerSlots = buildTimePickerSlots(calendar, form, durationMinutes, this._editAppointmentId)
const patch = {
availableTimeGroups,
timePickerSlots,
@@ -1685,7 +1792,8 @@ Page({
businessHoursMissing: false,
timeSelectTip: availableTimes.length > 0 ? '请选择预约时间' : '当前美甲师当天暂无可约时间'
}
if (form.appointmentTime && !availableTimes.includes(form.appointmentTime)) {
if (form.appointmentTime && !availableTimes.includes(form.appointmentTime)
&& !this.isEditOriginalSchedule(form.appointmentDate, form.appointmentTime)) {
patch['form.appointmentTime'] = ''
}
this.setData(patch)
@@ -1816,21 +1924,28 @@ Page({
}
const startMinute = dateUtil.minutesOfDay(appointmentTime)
const endMinute = startMinute + durationMinutes
const editOriginalSchedule = this.isEditOriginalSchedule(form.appointmentDate, appointmentTime)
if (!this.data.businessStartTime || !this.data.businessEndTime) {
if (editOriginalSchedule) {
this.setData({ conflictTip: '沿用当前预约时间', conflictLevel: 'free' })
return { ok: true }
}
const tip = this.data.businessHoursMissing
? '门店营业时间尚未设置,请先完成设置'
: '营业时间暂不可用,请稍后重试'
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
return { ok: false, tip }
}
if (startMinute < dateUtil.minutesOfDay(this.data.businessStartTime) || endMinute > dateUtil.minutesOfDay(this.data.businessEndTime)) {
if (!editOriginalSchedule
&& (startMinute < dateUtil.minutesOfDay(this.data.businessStartTime) || endMinute > dateUtil.minutesOfDay(this.data.businessEndTime))) {
const tip = `该时间超出营业时间 ${this.data.businessStartTime}-${this.data.businessEndTime}`
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
return { ok: false, tip }
}
const now = new Date()
const today = dateUtil.formatDate(now)
if (form.appointmentDate < today || (form.appointmentDate === today && startMinute <= now.getHours() * 60 + now.getMinutes())) {
if (!editOriginalSchedule && (form.appointmentDate < today
|| (form.appointmentDate === today && startMinute <= now.getHours() * 60 + now.getMinutes()))) {
const tip = '该时间已过,请改选未来时段或使用历史补单'
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
return { ok: false, tip }
@@ -1853,6 +1968,7 @@ Page({
return { ok: false, tip }
}
const conflicts = (calendar.appointments || []).filter(item => {
if (this._editMode && String(item.orderItemId) === String(this._editAppointmentId)) return false
if (String(item.artistId) !== String(form.artistId) || normalizeAppointmentDate(item) !== form.appointmentDate) return false
if (isCancelledAppointment(item)) return false
const itemStart = resolveAppointmentStartMinute(item)
@@ -1968,7 +2084,7 @@ Page({
wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' })
return
}
if (isShopBusinessExpired()) {
if (!this._editMode && isShopBusinessExpired()) {
await showBusinessExpiryNotice(this)
return
}
@@ -1976,7 +2092,9 @@ Page({
const today = dateUtil.formatDate(new Date())
const now = new Date()
const selectedMinute = form.appointmentTime ? dateUtil.minutesOfDay(form.appointmentTime) : -1
if (form.appointmentDate < today || (form.appointmentDate === today && selectedMinute <= now.getHours() * 60 + now.getMinutes())) {
const editOriginalSchedule = this.isEditOriginalSchedule(form.appointmentDate, form.appointmentTime)
if (!editOriginalSchedule && (form.appointmentDate < today
|| (form.appointmentDate === today && selectedMinute <= now.getHours() * 60 + now.getMinutes()))) {
await this.showBackfillPrompt(form.appointmentDate, form.appointmentDate < today ? '所选日期已经过去' : '所选时段已经过去')
return
}
@@ -2059,7 +2177,15 @@ Page({
payload.manualProductPrecautions = String(form.manualProductPrecautions || '').trim() || undefined
payload.manualProductImageFileIds = String(form.manualProductImageFileIds || '').trim() || undefined
}
const result = await planningApi.createAppointment(payload)
const result = this._editMode
? await planningApi.updateAppointment(this._editAppointmentId, payload)
: await planningApi.createAppointment(payload)
if (this._editMode) {
markPlanningRefresh()
wx.showToast({ title: '已保存修改', icon: 'success' })
wx.navigateBack()
return
}
this.cancelDraftSave()
this._draftReady = false
this._draftPersistenceDisabled = true
@@ -2074,7 +2200,7 @@ Page({
if ((error.message || '').includes('有效期') || (error.message || '').includes('到期')) {
await showBusinessExpiryNotice(this)
} else {
showErrorToast(error, '提交失败')
showErrorToast(error, this._editMode ? '保存失败' : '提交失败')
}
} finally {
this.setData({ loading: false })
@@ -1,8 +1,8 @@
<view class="page no-tab appointment-page">
<view class="appointment-hero">
<view class="appointment-hero-copy">
<text class="appointment-eyebrow">NEW APPOINTMENT</text>
<text class="appointment-title">安排一场美甲</text>
<text class="appointment-eyebrow">{{editMode ? 'EDIT APPOINTMENT' : 'NEW APPOINTMENT'}}</text>
<text class="appointment-title">{{editMode ? '调整这场预约' : '安排一场美甲'}}</text>
</view>
<view class="appointment-date-pill"><text class="date-pill-icon">◷</text><text>{{appointmentDateBadge}}</text></view>
</view>
@@ -47,16 +47,16 @@
<text class="chevron">›</text>
</view>
</picker>
<view class="field-card appointment-field-card" bindtap="openTimeSheet">
<view class="field-icon">◷</view>
<view class="field-text"><text class="field-label"><text class="required-mark required-mark-before">*</text>预约时间</text><text wx:if="{{form.appointmentTime}}" class="field-value">{{appointmentDayLabel}} {{form.appointmentTime}} · {{form.durationMinutes}}分钟</text><text wx:else class="field-value placeholder">{{timeSelectTip}}</text><text wx:if="{{form.appointmentTime}}" class="field-meta">{{selectedArtist.name || '暂不分配美甲师'}}</text></view>
<text class="chevron">›</text>
</view>
<view class="field-card appointment-field-card" bindtap="openArtistSheet">
<view class="field-icon">♙</view>
<view class="field-text"><text class="field-label">服务美甲师(选填)</text><text wx:if="{{selectedArtist.id === '__unassigned__'}}" class="field-value">已选择暂不分配美甲师</text><text wx:else class="field-value {{selectedArtist.name ? '' : 'placeholder'}}">{{selectedArtist.name || '请选择美甲师或暂不分配'}}</text></view>
<text class="chevron">›</text>
</view>
<view class="field-card appointment-field-card" bindtap="openTimeSheet">
<view class="field-icon">◷</view>
<view class="field-text"><text class="field-label"><text class="required-mark required-mark-before">*</text>预约时间</text><text wx:if="{{form.appointmentTime}}" class="field-value">{{appointmentDayLabel}} {{form.appointmentTime}} · {{form.durationMinutes}}分钟</text><text wx:else class="field-value placeholder">{{timeSelectTip}}</text><text wx:if="{{form.appointmentTime}}" class="field-meta">{{selectedArtist.name || '暂不分配美甲师'}}</text></view>
<text class="chevron">›</text>
</view>
</view>
<view class="card form-card customer-section">
@@ -75,7 +75,7 @@
<view wx:if="{{form.customerUserId}}" class="customer-selected-tip">已选择系统客户</view>
</view>
<view class="draft-tip card"><text>{{draftSavedAtText}}</text><button class="text-btn draft-clear" bindtap="resetForm">恢复默认值</button></view>
<view wx:if="{{!editMode}}" 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" />
@@ -148,6 +148,6 @@
</view>
</view>
<view class="fixed-bottom"><view wx:if="{{canCreateAppointment}}" class="action-row"><button class="secondary-btn draft-btn" bindtap="saveDraft">保存草稿</button><button class="primary-btn submit-btn" loading="{{loading}}" bindtap="submit">提交预约</button></view></view>
<view class="fixed-bottom"><view wx:if="{{canCreateAppointment}}" class="action-row"><button wx:if="{{!editMode}}" class="secondary-btn draft-btn" bindtap="saveDraft">保存草稿</button><button class="primary-btn submit-btn" loading="{{loading}}" bindtap="submit">{{editMode ? '保存修改' : '提交预约'}}</button></view></view>
<action-modal id="actionModal" />
</view>