小程序预约详情支持图片预览、编辑预约与完成收款拆分
自动发布开发环境 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
+16
View File
@@ -51,6 +51,22 @@ module.exports = {
})
},
updateAppointment(orderItemId, data) {
return request({
url: `/manager/planning/appointments/${orderItemId}`,
method: 'PUT',
data
})
},
registerOfflinePayment(orderId, data) {
return request({
url: `/manager/orders/${orderId}/offline-payment`,
method: 'POST',
data
})
},
updateStatus(orderId, status, cancelReason) {
return request({
url: `/manager/planning/appointments/${orderId}/status`,
@@ -10,7 +10,8 @@ Component({
layout: 'column',
editable: false,
placeholderText: '',
inputValue: ''
inputValue: '',
inputType: 'text'
},
methods: {
@@ -27,7 +28,8 @@ Component({
layout: options.layout || (options.cancelText ? 'row' : 'column'),
editable: options.editable === true,
placeholderText: options.placeholderText || '',
inputValue: ''
inputValue: options.inputValue === undefined || options.inputValue === null ? '' : String(options.inputValue),
inputType: options.inputType || 'text'
})
},
@@ -3,7 +3,7 @@
<view wx:if="{{icon}}" class="action-modal-icon {{icon}}">{{icon === 'warning' ? '!' : 'i'}}</view>
<text class="action-modal-title">{{title}}</text>
<text wx:if="{{content}}" class="action-modal-content">{{content}}</text>
<input wx:if="{{editable}}" class="action-modal-input" value="{{inputValue}}" maxlength="60" placeholder="{{placeholderText}}" bindinput="onInput" />
<input wx:if="{{editable}}" class="action-modal-input" type="{{inputType}}" value="{{inputValue}}" maxlength="60" placeholder="{{placeholderText}}" bindinput="onInput" />
<view class="action-modal-actions {{layout === 'row' ? 'row' : ''}}">
<button wx:if="{{cancelText}}" class="action-modal-btn secondary" bindtap="onCancel">{{cancelText}}</button>
<button class="action-modal-btn {{confirmType === 'danger' ? 'danger' : 'primary'}}" bindtap="onConfirm">{{confirmText}}</button>
@@ -15,6 +15,17 @@ function formatAmount(value) {
return amount ? `¥${amount}` : '未记录'
}
function isPaid(appointment) {
return String((appointment && appointment.paymentStatus) || '').toUpperCase() === 'PAID'
}
const PAY_METHODS = [
{ label: '现金', value: 'CASH' },
{ label: '微信', value: 'WECHAT' },
{ label: '支付宝', value: 'ALIPAY' },
{ label: '线下其他', value: 'OFFLINE' }
]
Page({
data: {
id: '',
@@ -25,10 +36,13 @@ Page({
timeText: '',
isUnassigned: false,
showTransfer: false,
showEdit: false,
showConfirm: false,
showCollect: false,
showComplete: false,
showCancel: false,
updating: false,
paying: false,
dialing: false,
loadError: ''
},
@@ -38,6 +52,13 @@ Page({
this.loadDetail()
},
onShow() {
if (this._needReload && this.data.id) {
this._needReload = false
this.loadDetail()
}
},
async loadDetail() {
try {
const appointment = await planningApi.appointment(this.data.id)
@@ -75,11 +96,16 @@ Page({
amountText: formatAmount(safeAppointment.amount),
statusText: displayValue(safeAppointment.statusText, '状态未知'),
remarkText: displayValue(safeAppointment.remark, '暂无备注'),
cancelReasonText: displayValue(safeAppointment.cancelReason, '')
cancelReasonText: displayValue(safeAppointment.cancelReason, ''),
paymentStatusText: isPaid(safeAppointment)
? `已收款${safeAppointment.paidAmount !== null && safeAppointment.paidAmount !== undefined ? ` ¥${safeAppointment.paidAmount}` : ''}`
: '未收款'
}
const coverImages = Array.isArray(safeAppointment.coverImages)
? safeAppointment.coverImages.filter(item => Boolean(item))
: []
const paid = isPaid(safeAppointment)
const canOperateService = !isUnassigned && (status === 1 || status === 4)
this.setData({
appointment: normalizedAppointment,
coverImages,
@@ -88,8 +114,10 @@ Page({
avatarText: normalizedAppointment.customerNameText.slice(0, 1),
timeText,
showTransfer: Boolean(safeAppointment.canEdit) && !historicalBackfill,
showEdit: Boolean(safeAppointment.canEdit) && !historicalBackfill && (status === 0 || status === 1),
showConfirm: Boolean(safeAppointment.canEdit) && !historicalBackfill && !isUnassigned && status === 0,
showComplete: !isUnassigned && (status === 1 || status === 4),
showCollect: canOperateService && !paid,
showComplete: canOperateService && paid,
showCancel: Boolean(safeAppointment.canCancel),
loadError: ''
})
@@ -99,6 +127,29 @@ Page({
this.setData({ coverIndex: Number(event.detail.current) || 0 })
},
onCoverImageError(event) {
const index = Number(event.currentTarget.dataset.index)
if (!Number.isFinite(index)) return
if (!this._coverFailedIndexes) this._coverFailedIndexes = {}
this._coverFailedIndexes[index] = true
},
previewCoverImage(event) {
const index = Number(event.currentTarget.dataset.index)
const failed = this._coverFailedIndexes || {}
const images = (this.data.coverImages || []).filter((url, itemIndex) => url && !failed[itemIndex])
if (!images.length) {
wx.showToast({ title: '暂无可预览的图片', icon: 'none' })
return
}
const target = (this.data.coverImages || [])[Number.isFinite(index) ? index : 0]
wx.previewImage({
current: target && images.indexOf(target) >= 0 ? target : images[0],
urls: images,
fail: () => wx.showToast({ title: '图片预览失败', icon: 'none' })
})
},
async updateStatus(status) {
if (this.data.updating || !this.data.appointment.orderId) return
if (status !== 3 && this.data.isUnassigned) {
@@ -125,9 +176,84 @@ Page({
complete() {
if (!this.data.showComplete || this.data.updating) return
if (!isPaid(this.data.appointment)) {
wx.showToast({ title: '请先完成收款', icon: 'none' })
return
}
this.updateStatus(2)
},
choosePayMethod() {
return new Promise(resolve => {
wx.showActionSheet({
itemList: PAY_METHODS.map(item => item.label),
success: result => resolve(PAY_METHODS[result.tapIndex] || PAY_METHODS[0]),
fail: () => resolve(null)
})
})
},
async collect() {
if (!this.data.showCollect || this.data.paying || this.data.updating) return
const appointment = this.data.appointment || {}
const orderId = appointment.orderId
if (!orderId) return
const method = await this.choosePayMethod()
if (!method) return
const defaultAmount = appointment.payAmount !== null && appointment.payAmount !== undefined
? appointment.payAmount
: appointment.amount
const input = await showActionModal(this, {
title: '登记收款',
content: `收款方式:${method.label}`,
editable: true,
inputType: 'digit',
inputValue: defaultAmount === null || defaultAmount === undefined ? '' : defaultAmount,
placeholderText: '请输入实收金额',
cancelText: '取消',
confirmText: '确认收款'
})
if (!input.confirm) return
const text = String(input.content || '').trim()
const paidAmount = Number(text)
if (!text || !Number.isFinite(paidAmount) || paidAmount < 0) {
wx.showToast({ title: '请输入正确的收款金额', icon: 'none' })
return
}
this.setData({ paying: true })
try {
await planningApi.registerOfflinePayment(orderId, {
payMethod: method.value,
paidAmount
})
markPlanningRefresh()
const result = await showActionModal(this, {
title: '收款已登记',
content: `实收 ¥${paidAmount},是否同时完成服务?`,
cancelText: '暂不完成',
confirmText: '同时完成服务'
})
if (result.confirm) {
await planningApi.updateStatus(orderId, 2, '')
markPlanningRefresh()
wx.showToast({ title: '已完成服务' })
} else {
wx.showToast({ title: '收款已登记', icon: 'success' })
}
this.loadDetail()
} catch (error) {
showErrorToast(error, '收款登记失败')
} finally {
this.setData({ paying: false })
}
},
goEdit() {
if (!this.data.showEdit) return
this._needReload = true
wx.navigateTo({ url: `/pages/appointment-form/index?mode=edit&id=${this.data.appointment.orderItemId || this.data.id}` })
},
async cancel() {
if (!this.data.showCancel || this.data.updating) return
this._cancelReason = ''
@@ -82,20 +82,58 @@ page.applyAppointment({
assignmentStatus: 'ASSIGNED',
status: 4,
statusText: '服务中',
historicalBackfill: true,
paymentStatus: 'UNPAID',
payAmount: 268,
canEdit: false,
canCancel: true
})
assert.strictEqual(page.data.showTransfer, false)
assert.strictEqual(page.data.showComplete, true)
assert.strictEqual(page.data.showCollect, true)
assert.strictEqual(page.data.showComplete, false)
assert.strictEqual(page.data.showCancel, true)
assert.strictEqual(page.data.appointment.paymentStatusText, '未收款')
page.applyAppointment({
artistId: 9,
assignmentStatus: 'ASSIGNED',
status: 1,
statusText: '待服务',
paymentStatus: 'PAID',
paidAmount: 268,
canEdit: true,
canCancel: true
})
assert.strictEqual(page.data.showCollect, false)
assert.strictEqual(page.data.showComplete, true)
assert.strictEqual(page.data.showEdit, true)
assert.strictEqual(page.data.appointment.paymentStatusText, '已收款 ¥268')
global.wx.previewImage = options => {
global.__preview = options
}
page.data.coverImages = ['https://cdn/a.png', 'https://cdn/b.png', 'https://cdn/c.png']
page._coverFailedIndexes = { 1: true }
page.previewCoverImage({ currentTarget: { dataset: { index: 2 } } })
assert.deepStrictEqual(global.__preview.urls, ['https://cdn/a.png', 'https://cdn/c.png'])
assert.strictEqual(global.__preview.current, 'https://cdn/c.png')
page.data.coverImages = ['', '']
let toastTitle = ''
global.wx.showToast = options => { toastTitle = options.title }
page.previewCoverImage({ currentTarget: { dataset: { index: 0 } } })
assert.strictEqual(toastTitle, '暂无可预览的图片')
const markup = fs.readFileSync(path.join(__dirname, 'index.wxml'), 'utf8')
const styles = fs.readFileSync(path.join(__dirname, 'index.wxss'), 'utf8')
;['订单编号', '服务项目', '美甲师', '时长', '成交金额', '取消原因', 'remarkText', 'customerPhoneText'].forEach(text => assert(markup.includes(text)))
assert.match(markup, /class="primary-btn transfer-action"/)
assert.match(markup, /class="danger-btn"/)
assert.match(markup, /bindtap="previewCoverImage"/)
assert.match(markup, /class="cover-thumb/)
assert.match(markup, /bindtap="collect">完成收款/)
assert.match(markup, /bindtap="goEdit"/)
assert.match(markup, /appointment\.customerPhoneAvailable && appointment\.orderId/)
assert.strictEqual(markup.includes('appointment.customerId && appointment.orderId'), false)
assert.match(styles, /\.transfer-action\s*\{[^}]*box-shadow/)
assert.match(styles, /\.call-btn\s*\{/)
assert.match(styles, /\.cover-thumb\s*\{/)
@@ -22,7 +22,10 @@
</view>
</view>
</view>
<text class="status-tag {{appointment.status === 2 ? 'completed' : appointment.status === 3 ? 'cancelled' : ''}}">{{appointment.historicalBackfill ? '历史补单 · ' : ''}}{{appointment.statusText}}</text>
<view class="head-actions">
<button wx:if="{{showEdit}}" class="edit-btn" size="mini" bindtap="goEdit">编辑</button>
<text class="status-tag {{appointment.status === 2 ? 'completed' : appointment.status === 3 ? 'cancelled' : ''}}">{{appointment.historicalBackfill ? '历史补单 · ' : ''}}{{appointment.statusText}}</text>
</view>
</view>
<view class="detail-grid">
<view class="detail-field">
@@ -49,6 +52,10 @@
<text class="label">成交金额</text>
<text class="value">{{appointment.amountText}}</text>
</view>
<view class="detail-field">
<text class="label">收款状态</text>
<text class="value">{{appointment.paymentStatusText}}</text>
</view>
</view>
<view wx:if="{{appointment.cancelReasonText}}" class="cancel-reason">
<text class="label">取消原因</text>
@@ -64,14 +71,35 @@
<view class="cover-card">
<swiper class="cover-swiper" circular="{{coverImages.length > 1}}" bindchange="onCoverChange">
<swiper-item wx:for="{{coverImages}}" wx:key="*this">
<image class="cover-image" src="{{item}}" mode="aspectFill" />
<image
class="cover-image"
src="{{item}}"
mode="aspectFill"
data-index="{{index}}"
bindtap="previewCoverImage"
binderror="onCoverImageError"
/>
</swiper-item>
</swiper>
<view class="cover-dots">
<view wx:for="{{coverImages}}" wx:key="*this" class="cover-dot {{index === coverIndex ? 'active' : ''}}"></view>
</view>
</view>
<text class="cover-hint">左滑查看更多项目图</text>
<scroll-view class="cover-thumbs" scroll-x>
<view class="cover-thumb-list">
<image
wx:for="{{coverImages}}"
wx:key="*this"
class="cover-thumb {{index === coverIndex ? 'active' : ''}}"
src="{{item}}"
mode="aspectFill"
data-index="{{index}}"
bindtap="previewCoverImage"
binderror="onCoverImageError"
/>
</view>
</scroll-view>
<text class="cover-hint">点击图片可放大查看</text>
</view>
<view wx:if="{{!loadError}}" class="section">
@@ -79,10 +107,11 @@
<view class="card note-card">{{appointment.remarkText}}</view>
</view>
<view wx:if="{{!loadError && (showTransfer || showConfirm || showComplete || showCancel)}}" class="fixed-bottom action-row">
<view wx:if="{{!loadError && (showTransfer || showConfirm || showCollect || showComplete || showCancel)}}" class="fixed-bottom action-row">
<button wx:if="{{showTransfer}}" class="primary-btn transfer-action" loading="{{updating}}" disabled="{{updating}}" bindtap="goTransfer">{{isUnassigned ? '分配美甲师' : '改派美甲师'}}</button>
<button wx:if="{{showConfirm}}" class="secondary-btn" loading="{{updating}}" disabled="{{updating}}" bindtap="confirm">确认预约</button>
<button wx:if="{{showComplete}}" class="secondary-btn" loading="{{updating}}" disabled="{{updating}}" bindtap="complete">{{appointment.historicalBackfill ? '完成补单' : '完成服务'}}</button>
<button wx:if="{{showCollect}}" class="secondary-btn" loading="{{paying}}" disabled="{{paying || updating}}" bindtap="collect">完成收款</button>
<button wx:if="{{showComplete}}" class="secondary-btn" loading="{{updating}}" disabled="{{updating || paying}}" bindtap="complete">{{appointment.historicalBackfill ? '完成补单' : '完成服务'}}</button>
<button wx:if="{{showCancel}}" class="danger-btn" loading="{{updating}}" disabled="{{updating}}" bindtap="cancel">取消预约</button>
</view>
<action-modal id="actionModal" />
@@ -96,6 +96,25 @@
font-weight: 800;
}
.head-actions {
display: flex;
align-items: center;
flex-shrink: 0;
gap: 10rpx;
}
.edit-btn {
margin: 0;
padding: 0 16rpx;
border: 1rpx solid #247b63;
border-radius: 20rpx;
background: #ffffff;
color: #247b63;
font-size: 21rpx;
font-weight: 600;
line-height: 40rpx;
}
.status-tag.completed {
background: #eef2f1;
color: #67766f;
@@ -233,6 +252,31 @@
font-size: 20rpx;
}
.cover-thumbs {
margin-top: 12rpx;
width: 100%;
white-space: nowrap;
}
.cover-thumb-list {
display: flex;
align-items: center;
gap: 12rpx;
}
.cover-thumb {
flex-shrink: 0;
width: 104rpx;
height: 104rpx;
border: 2rpx solid transparent;
border-radius: 12rpx;
background: #e5f4ed;
}
.cover-thumb.active {
border-color: #247b63;
}
.note-card {
padding: 24rpx;
color: #71807a;
@@ -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>
+2
View File
@@ -12,6 +12,8 @@ function showActionModal(page, options = {}) {
layout: options.layout,
editable: options.editable,
placeholderText: options.placeholderText,
inputValue: options.inputValue,
inputType: options.inputType,
onClose: resolve
})
})