优化:统一小程序业务引用选择交互

This commit is contained in:
2026-10-12 22:24:24 +08:00
parent fa1fed006e
commit 3b98e4746a
31 changed files with 1378 additions and 504 deletions
@@ -0,0 +1,63 @@
const assert = require('assert')
global.wx = {
getAccountInfoSync: () => ({ miniProgram: { envVersion: 'develop' } }),
getDeviceInfo: () => ({ platform: 'devtools' }),
getStorageSync: () => '',
setStorageSync: () => {},
removeStorageSync: () => {},
showToast: () => {},
navigateTo: () => {}
}
global.getApp = () => ({ globalData: { userInfo: { type: 2, id: 1, shopId: 2 } } })
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 page = createPage()
page.selectCustomer({ detail: { item: { id: 18, name: '小周', phone: '13800138000' } } })
assert.strictEqual(page.data.form.customerUserId, 18)
assert.strictEqual(page.data.form.customerName, '小周')
assert.strictEqual(page.data.form.phone, '13800138000')
assert.strictEqual(page.data.customerSheetVisible, false)
page.data.form.customerUserId = 18
page.data.manualCustomerForm = { name: '新客户', phone: '13900139000' }
page.useManualCustomer()
assert.strictEqual(page.data.form.customerUserId, '')
assert.strictEqual(page.data.form.customerName, '新客户')
assert.strictEqual(page.data.form.phone, '13900139000')
page.data.artists = [{ id: 1, name: '小周' }, { id: 2, name: '小李' }]
page.onArtistSearch({ detail: { value: '李' } })
assert.deepStrictEqual(page.data.artistSelectorItems.map(item => item.id), [2])
page.refreshAvailableTimes = async () => {}
page.checkAvailability = () => {}
page.selectArtist({ detail: { item: { id: 2, name: '小李' } } })
assert.strictEqual(page.data.form.artistId, 2)
assert.strictEqual(page.data.selectedArtist.name, '小李')
assert.strictEqual(page.data.artistSheetVisible, false)
}
run().catch(error => {
console.error(error)
process.exitCode = 1
})
+156 -33
View File
@@ -231,6 +231,25 @@ function normalizeCustomer(customer) {
}
}
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: {
@@ -253,12 +272,19 @@ Page({
remark: ''
},
customerOptions: [],
customerDropdownVisible: false,
customerSheetVisible: false,
customerKeyword: '',
customerLoading: false,
customerError: '',
manualCustomerVisible: false,
manualCustomerForm: { name: '', phone: '' },
products: [],
filteredProducts: [],
artists: [],
artistSelectorItems: [],
artistSheetVisible: false,
artistKeyword: '',
artistError: '',
selectedProduct: {},
selectedArtist: {},
productModalVisible: false,
@@ -298,7 +324,6 @@ Page({
return
}
this.loadOptions()
this.searchCustomers()
},
async loadOptions() {
@@ -319,21 +344,37 @@ Page({
this.checkAvailability()
},
async loadArtists() {
async loadArtists(preferredArtistId, fallbackEmployee) {
try {
const calendar = await planningApi.calendar({
startDate: this.data.form.appointmentDate,
endDate: this.data.form.appointmentDate
})
const artists = getCalendarArtists(calendar)
const selectedArtist = this.data.form.artistId ? findArtist(artists, this.data.form.artistId) : {}
this.setData({ artists, selectedArtist })
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'
})
@@ -345,44 +386,40 @@ Page({
const patch = {
[`form.${field}`]: event.detail.value
}
if (field === 'customerName' || field === 'phone') {
patch['form.customerUserId'] = ''
patch.customerDropdownVisible = true
}
this.setData(patch)
if (field === 'customerName' || field === 'phone') {
this.scheduleCustomerSearch(field)
}
if (field === 'durationMinutes') {
this.refreshAvailableTimes()
this.checkAvailability()
}
},
onCustomerFocus(event) {
const field = event.currentTarget.dataset.field
this.setData({ customerDropdownVisible: true })
this.searchCustomers(field)
openCustomerSheet() {
this.setData({ customerSheetVisible: true })
this.searchCustomers(this.data.customerKeyword)
},
scheduleCustomerSearch(field) {
closeCustomerSheet() {
this.setData({ customerSheetVisible: false })
},
onCustomerSearch(event) {
const keyword = event.detail.value
this.setData({ customerKeyword: keyword })
clearTimeout(this._customerTimer)
this._customerTimer = setTimeout(() => this.searchCustomers(field), 250)
this._customerTimer = setTimeout(() => this.searchCustomers(keyword), 250)
},
async searchCustomers(preferredField) {
async searchCustomers(keywordValue) {
if (!this.data.canCreateAppointment) {
return
}
const form = this.data.form
const sourceValue = preferredField === 'phone' ? form.phone : form.customerName || form.phone
const keyword = String(sourceValue || '').trim()
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),
customerOptions: list.map(normalizeCustomer).map(buildCustomerSelectorItem),
customerError: ''
})
} catch (error) {
@@ -395,8 +432,12 @@ Page({
}
},
retryCustomerSearch() {
this.searchCustomers(this.data.customerKeyword)
},
selectCustomer(event) {
const customer = this.data.customerOptions.find(item => String(item.id) === String(event.currentTarget.dataset.id))
const customer = event.detail.item
if (!customer) {
return
}
@@ -404,14 +445,48 @@ Page({
'form.customerUserId': customer.id,
'form.customerName': customer.name,
'form.phone': customer.phone,
customerDropdownVisible: false
customerSheetVisible: false,
customerKeyword: ''
})
},
hideCustomerDropdown() {
setTimeout(() => {
this.setData({ customerDropdownVisible: false })
}, 180)
openManualCustomer() {
this.setData({
customerSheetVisible: false,
manualCustomerVisible: true,
manualCustomerForm: {
name: this.data.form.customerName || '',
phone: this.data.form.phone || ''
}
})
},
closeManualCustomer() {
this.setData({ manualCustomerVisible: false })
},
onManualCustomerInput(event) {
this.setData({ [`manualCustomerForm.${event.currentTarget.dataset.field}`]: event.detail.value })
},
useManualCustomer() {
const name = String(this.data.manualCustomerForm.name || '').trim()
const phone = String(this.data.manualCustomerForm.phone || '').trim()
if (!name) {
wx.showToast({ title: '请输入客户姓名', icon: 'none' })
return
}
if (!/^1[3-9]\d{9}$/.test(phone)) {
wx.showToast({ title: '请输入正确手机号', icon: 'none' })
return
}
this.setData({
'form.customerUserId': '',
'form.customerName': name,
'form.phone': phone,
manualCustomerVisible: false,
customerKeyword: ''
})
},
onUnload() {
@@ -534,17 +609,65 @@ Page({
})
},
onArtistChange(event) {
const selectedArtist = this.data.artists[Number(event.detail.value)] || {}
filterArtistItems(artists, keywordValue) {
const keyword = String(keywordValue || '').trim().toLowerCase()
return (artists || [])
.filter(item => !keyword || String(item.name || '').toLowerCase().includes(keyword))
.map(buildArtistSelectorItem)
},
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 || {}
this.setData({
selectedArtist,
'form.artistId': selectedArtist.id,
'form.appointmentTime': ''
'form.appointmentTime': '',
artistSheetVisible: false
})
this.refreshAvailableTimes()
this.checkAvailability()
},
addEmployeeFromSelector() {
this.setData({ artistSheetVisible: false })
wx.navigateTo({
url: '/pages/employee-create/index?picker=1',
success: result => {
result.eventChannel.on('employeeCreated', employee => this.handleEmployeeCreated(employee))
}
})
},
async handleEmployeeCreated(employee) {
await this.loadArtists(employee.id, employee)
this.setData({ 'form.appointmentTime': '' })
await this.refreshAvailableTimes()
this.checkAvailability()
},
canOpenTimeSheet() {
const form = this.data.form
return Boolean(form.appointmentDate && form.artistId && normalizeDuration(form.durationMinutes))
@@ -1,3 +1,6 @@
{
"navigationBarTitleText": "新建预约"
"navigationBarTitleText": "新建预约",
"usingComponents": {
"entity-selector-sheet": "/components/entity-selector-sheet/index"
}
}
@@ -1,27 +1,14 @@
<view class="page no-tab">
<view class="card form-card">
<view class="customer-select">
<view class="field">
<text class="field-label required">客户姓名</text>
<input value="{{form.customerName}}" data-field="customerName" bindinput="onInput" bindfocus="onCustomerFocus" bindblur="hideCustomerDropdown" placeholder="搜索或输入客户姓名" />
</view>
<view class="field">
<text class="field-label required">手机号</text>
<input value="{{form.phone}}" data-field="phone" bindinput="onInput" bindfocus="onCustomerFocus" bindblur="hideCustomerDropdown" maxlength="11" type="number" placeholder="搜索或输入手机号" />
</view>
<view wx:if="{{customerDropdownVisible}}" class="customer-dropdown">
<view wx:if="{{customerLoading}}" class="customer-option muted-option">正在搜索客户...</view>
<view wx:elif="{{customerError}}" class="customer-option muted-option">{{customerError}},可继续手动输入</view>
<view wx:else>
<view wx:for="{{customerOptions}}" wx:key="id" class="customer-option" data-id="{{item.id}}" bindtap="selectCustomer">
<view class="customer-copy">
<text class="customer-name">{{item.displayName}}</text>
<text class="customer-phone">{{item.displayPhone}}</text>
</view>
<text class="customer-select-tag">选择</text>
</view>
<view wx:if="{{customerOptions.length === 0}}" class="customer-option muted-option">暂无匹配客户,可继续手动输入</view>
<view class="field customer-field" bindtap="openCustomerSheet">
<text class="field-label required">客户</text>
<view class="reference-card {{form.customerName ? 'filled' : ''}}">
<view class="reference-copy">
<text class="reference-title">{{form.customerName || '请选择客户'}}</text>
<text class="reference-subtitle">{{form.phone || '搜索已有客户或手动录入'}}</text>
</view>
<text wx:if="{{form.customerUserId}}" class="reference-badge">已有</text>
<text class="reference-arrow">›</text>
</view>
</view>
<view class="field">
@@ -44,9 +31,10 @@
</view>
<view class="field">
<text class="field-label required">指定员工</text>
<picker range="{{artists}}" range-key="name" bindchange="onArtistChange">
<view class="field-value">{{selectedArtist.name || '请选择美甲师'}}</view>
</picker>
<view class="field-value reference-value" bindtap="openArtistSheet">
<text>{{selectedArtist.name || '请选择员工'}}</text>
<text class="reference-arrow">›</text>
</view>
</view>
<view class="field">
<text class="field-label required">预约时间</text>
@@ -79,6 +67,65 @@
<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="暂无匹配客户,可手动录入"
action-text="手动录入客户"
bind:search="onCustomerSearch"
bind:select="selectCustomer"
bind:retry="retryCustomerSearch"
bind:action="openManualCustomer"
bind:close="closeCustomerSheet"
/>
<entity-selector-sheet
visible="{{artistSheetVisible}}"
title="选择员工"
keyword="{{artistKeyword}}"
placeholder="搜索员工姓名"
items="{{artistSelectorItems}}"
selected-id="{{form.artistId}}"
loading="{{false}}"
error-text="{{artistError}}"
empty-text="暂无匹配员工"
action-text="快速新增员工"
bind:search="onArtistSearch"
bind:select="selectArtist"
bind:retry="retryArtists"
bind:action="addEmployeeFromSelector"
bind:close="closeArtistSheet"
/>
<view wx:if="{{manualCustomerVisible}}" class="modal-mask" bindtap="closeManualCustomer" catchtouchmove="stopTouchMove">
<view class="manual-customer-sheet" catchtap="stopTap">
<view class="modal-head">
<view>
<text class="modal-title">手动录入客户</text>
<text class="modal-subtitle">录入后将直接带回本次预约</text>
</view>
<view class="modal-close" bindtap="closeManualCustomer">×</view>
</view>
<view class="manual-customer-form">
<view class="manual-customer-field">
<text class="required-label">客户姓名</text>
<input value="{{manualCustomerForm.name}}" data-field="name" bindinput="onManualCustomerInput" placeholder="请输入客户姓名" />
</view>
<view class="manual-customer-field">
<text class="required-label">手机号</text>
<input value="{{manualCustomerForm.phone}}" data-field="phone" bindinput="onManualCustomerInput" type="number" maxlength="11" placeholder="请输入手机号" />
</view>
</view>
<button class="primary-btn manual-customer-submit" bindtap="useManualCustomer">使用该客户</button>
</view>
</view>
<view wx:if="{{productModalVisible}}" class="modal-mask" bindtap="closeProductModal" catchtouchmove="stopTouchMove">
<view class="product-modal" catchtap="stopTap">
<view class="modal-head">
@@ -3,75 +3,81 @@
font-size: 24rpx;
}
.customer-select {
position: relative;
.customer-field {
align-items: stretch;
padding: 18rpx 0;
}
.customer-dropdown {
position: absolute;
top: 214rpx;
right: 0;
left: 180rpx;
z-index: 30;
max-height: 360rpx;
overflow-y: auto;
border: 1rpx solid #e5ded4;
border-radius: 18rpx;
background: #fffdf8;
box-shadow: 0 18rpx 40rpx rgba(58, 48, 34, 0.14);
}
.customer-option {
.customer-field > .field-label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16rpx;
min-height: 76rpx;
padding: 0 20rpx;
border-bottom: 1rpx solid #f0e9df;
}
.customer-option:last-child {
border-bottom: 0;
.reference-card,
.reference-value {
display: flex;
min-width: 0;
flex: 1;
align-items: center;
gap: 12rpx;
}
.customer-copy {
.reference-card {
min-height: 78rpx;
padding: 13rpx 16rpx;
border: 1rpx solid #e7e0d7;
border-radius: 18rpx;
background: #f8f4ee;
}
.reference-copy {
display: flex;
min-width: 0;
flex: 1;
flex-direction: column;
gap: 6rpx;
}
.customer-name {
min-width: 0;
.reference-title,
.reference-subtitle {
display: block;
overflow: hidden;
color: #2a2521;
font-size: 26rpx;
font-weight: 800;
text-overflow: ellipsis;
white-space: nowrap;
}
.customer-phone {
color: #8c8177;
font-size: 24rpx;
}
.customer-select-tag {
flex: 0 0 auto;
padding: 4rpx 12rpx;
border-radius: 999rpx;
background: #e5eee9;
color: #55786d;
font-size: 22rpx;
.reference-title {
color: #817a72;
font-size: 27rpx;
font-weight: 800;
}
.muted-option {
justify-content: center;
color: #9a9288;
font-size: 24rpx;
.reference-card.filled .reference-title { color: #29241f; }
.reference-subtitle {
margin-top: 6rpx;
color: #9a9289;
font-size: 21rpx;
}
.reference-badge {
flex: 0 0 auto;
padding: 5rpx 11rpx;
border-radius: 999rpx;
background: #e7f0ec;
color: #55786d;
font-size: 19rpx;
font-weight: 800;
}
.reference-value {
justify-content: space-between;
}
.reference-arrow {
flex: 0 0 auto;
color: #a99f95;
font-size: 38rpx;
line-height: 1;
}
.product-value {
@@ -221,6 +227,49 @@
box-shadow: 0 -18rpx 40rpx rgba(41, 31, 23, 0.16);
}
.manual-customer-sheet {
display: flex;
width: 100%;
height: 88vh;
max-height: 88vh;
flex-direction: column;
padding: 28rpx 28rpx calc(28rpx + env(safe-area-inset-bottom));
border-radius: 34rpx 34rpx 0 0;
background: #fffaf4;
box-shadow: 0 -18rpx 40rpx rgba(41, 31, 23, 0.16);
}
.manual-customer-form {
flex: 1;
padding-top: 12rpx;
}
.manual-customer-field {
margin-bottom: 20rpx;
padding: 20rpx 22rpx;
border: 1rpx solid #e7e0d7;
border-radius: 20rpx;
background: #fff;
}
.manual-customer-field text {
display: block;
margin-bottom: 10rpx;
color: #625c55;
font-size: 24rpx;
font-weight: 800;
}
.manual-customer-field input {
height: 64rpx;
color: #29241f;
font-size: 28rpx;
}
.manual-customer-submit {
flex: 0 0 auto;
}
.time-modal {
width: 100%;
max-height: 82vh;