优化:提升小程序全链路性能

This commit is contained in:
2026-10-11 16:53:02 +08:00
parent 0e7e60fefd
commit f00c753fd6
20 changed files with 403 additions and 113 deletions
@@ -1,6 +1,7 @@
const userApi = require('../../api/user')
const authApi = require('../../api/auth')
const auth = require('../../utils/auth')
const profileCache = require('../../utils/profile-cache')
Page({
data: {
@@ -16,10 +17,10 @@ Page({
onShow() { this.loadProfile() },
async loadProfile() {
async loadProfile(options = {}) {
this.setData({ loading: true })
try {
const profile = await userApi.info()
const profile = await profileCache.getProfile(options)
this.setData({ profile, 'smsForm.phone': profile.phone || '' })
const app = getApp()
const session = auth.getSession()
@@ -49,7 +50,8 @@ Page({
this.setData({ binding: true })
try {
await userApi.bindWechatPhone(phoneCode)
await this.loadProfile()
profileCache.invalidate()
await this.loadProfile({ force: true })
wx.showToast({ title: '手机号已绑定' })
} catch (error) {
wx.showToast({ title: error.message || '绑定失败', icon: 'none' })
@@ -95,7 +97,8 @@ Page({
this.setData({ binding: true })
try {
await userApi.bindPhone({ phone: form.phone, verificationCode: form.code })
await this.loadProfile()
profileCache.invalidate()
await this.loadProfile({ force: true })
wx.showToast({ title: '手机号已绑定' })
} catch (error) {
wx.showToast({ title: error.message || '绑定失败', icon: 'none' })
+81 -54
View File
@@ -4,6 +4,7 @@ const userApi = require('../../api/user')
const auth = require('../../utils/auth')
const { uploadProfileImage } = require('../../utils/upload')
const { normalizeAvatar } = require('../../utils/profile-card')
const profileCache = require('../../utils/profile-cache')
function canCreateAppointment() {
const app = getApp()
@@ -71,8 +72,6 @@ Page({
businessStartTime: '10:00',
businessEndTime: '22:00',
artists: [],
appointments: [],
daySummaries: [],
monthDays: [],
weekDays: [],
dayLanes: [],
@@ -112,7 +111,7 @@ Page({
async refreshAccountPrompts() {
try {
const profile = await userApi.info()
const profile = await profileCache.getProfile()
const session = auth.getSession()
getApp().setSession({ ...session, userInfo: { ...(session.userInfo || {}), ...profile } })
const today = dateUtil.formatDate(new Date())
@@ -166,6 +165,7 @@ Page({
this.setData({ profileSaving: true })
try {
await userApi.updateInfo({ nickname, avatar: this.data.profileForm.avatar })
profileCache.invalidate()
this.setData({ profilePromptVisible: false })
wx.showToast({ title: '资料已保存' })
} catch (error) {
@@ -177,12 +177,12 @@ Page({
switchView(event) {
this.setData({ viewMode: event.currentTarget.dataset.mode })
this.prepareView()
this.loadCalendar()
},
switchMonthDisplay(event) {
this.setData({ monthDisplayMode: event.currentTarget.dataset.mode })
this.prepareView()
},
toggleMonthRowLabel() {
@@ -196,7 +196,7 @@ Page({
selectedArtistId: id,
selectedArtistName: artist ? artist.name : '全部员工'
})
this.prepareView()
this.loadCalendar()
},
selectDate(event) {
@@ -244,38 +244,45 @@ Page({
async loadCalendar() {
const range = this.resolveRange()
const requestKey = `${range.start}|${range.end}|${this.data.selectedArtistId || ''}`
if (this._calendarInflight && this._calendarInflight.key === requestKey) {
return this._calendarInflight.promise
}
const requestId = (this._calendarRequestId || 0) + 1
this._calendarRequestId = requestId
this.setData({ loading: true })
try {
const data = await planningApi.calendar({
startDate: range.start,
endDate: range.end,
artistId: this.data.selectedArtistId || undefined
})
const promise = planningApi.calendar({
startDate: range.start,
endDate: range.end,
artistId: this.data.selectedArtistId || undefined
}).then(data => {
if (requestId !== this._calendarRequestId) return
this.applyCalendar(data)
this.setData({ calendarError: '' })
} catch (error) {
}).catch(error => {
if (requestId !== this._calendarRequestId) return
this.clearCalendarView()
this.setData({
calendarError: resolveCalendarErrorMessage(error),
selectedArtistId: '',
selectedArtistName: '全部员工'
})
wx.showToast({
title: '规划数据加载失败',
icon: 'none'
})
} finally {
this.setData({ loading: false })
}
wx.showToast({ title: '规划数据加载失败', icon: 'none' })
}).finally(() => {
if (requestId === this._calendarRequestId) this.setData({ loading: false })
if (this._calendarInflight && this._calendarInflight.promise === promise) {
this._calendarInflight = null
}
})
this._calendarInflight = { key: requestKey, promise }
return promise
},
clearCalendarView() {
this._calendarData = { artists: [], appointments: [], daySummaries: [] }
this.setData({
businessStartTime: '10:00',
businessEndTime: '22:00',
artists: [],
appointments: [],
daySummaries: [],
monthDays: [],
weekDays: [],
dayLanes: [],
@@ -304,18 +311,28 @@ Page({
},
applyCalendar(calendar) {
const artists = calendar.artists || []
this.setData({
const snapshot = {
businessStartTime: (calendar.businessStartTime || '10:00').slice(0, 5),
businessEndTime: (calendar.businessEndTime || '22:00').slice(0, 5),
artists,
appointments: calendar.appointments || [],
daySummaries: calendar.daySummaries || []
artists: Array.isArray(calendar.artists) ? calendar.artists : [],
appointments: Array.isArray(calendar.appointments) ? calendar.appointments : [],
daySummaries: Array.isArray(calendar.daySummaries) ? calendar.daySummaries : []
}
this._calendarData = snapshot
this.setData({
businessStartTime: snapshot.businessStartTime,
businessEndTime: snapshot.businessEndTime,
artists: snapshot.artists,
calendarError: '',
...this.buildViewState(snapshot)
})
this.prepareView()
},
prepareView() {
this.setData(this.buildViewState(this._calendarData))
},
buildViewState(calendar = {}) {
const current = this.data.currentDateText
const range = this.resolveRange()
const title = this.data.viewMode === 'month'
@@ -323,20 +340,30 @@ Page({
: this.data.viewMode === 'week'
? `${formatMonthDay(range.start)} - ${formatMonthDay(range.end)}`
: dateUtil.formatCnDate(current)
this.setData({
const state = {
dateTitle: title,
rangeText: this.data.viewMode === 'month' ? '月视图' : this.data.viewMode === 'week' ? '周视图' : '日视图',
weekRange: `${formatMonthDay(range.start)} - ${formatMonthDay(range.end)}`,
monthDays: this.buildMonthDays(),
weekDays: this.buildWeekDays(),
...this.buildDayView()
})
monthDays: [],
weekDays: [],
dayLanes: [],
hours: []
}
if (this.data.viewMode === 'month') {
state.monthDays = this.buildMonthDays(calendar)
return state
}
if (this.data.viewMode === 'week') {
state.weekDays = this.buildWeekDays(calendar)
return state
}
return { ...state, ...this.buildDayView(calendar) }
},
buildMonthDays() {
const summaryMap = this.summaryMap()
buildMonthDays(calendar) {
const summaryMap = this.summaryMap(calendar)
const todayText = dateUtil.formatDate(new Date())
const artistTemplate = this.data.artists.map(artist => ({
const artistTemplate = (calendar.artists || []).map(artist => ({
artistId: artist.id,
artistName: artist.name,
shortName: artist.shortName,
@@ -346,27 +373,27 @@ Page({
}))
return dateUtil.monthGrid(this.data.currentDateText).map(day => {
const summary = summaryMap[day.date] || {}
const artistCounts = this.normalizeArtistCounts(summary.artistCounts || artistTemplate)
const artistCounts = this.normalizeArtistCounts(summary.artistCounts || artistTemplate, calendar)
return {
...day,
isPast: day.date < todayText,
totalCount: summary.totalCount || 0,
dayStatus: summary.dayStatus || 'free',
artistCounts,
expandedBlocks: this.buildExpandedBlocks(artistCounts),
rowBlocks: this.buildRowBlocks(artistCounts)
expandedBlocks: this.data.monthDisplayMode === 'blocks' ? this.buildExpandedBlocks(artistCounts) : [],
rowBlocks: this.data.monthDisplayMode === 'rows' ? this.buildRowBlocks(artistCounts) : []
}
})
},
buildWeekDays() {
buildWeekDays(calendar) {
const start = dateUtil.startOfWeek(this.data.currentDateText)
const summaryMap = this.summaryMap()
const summaryMap = this.summaryMap(calendar)
return this.data.weekLabels.map((label, index) => {
const target = dateUtil.addDays(start, index)
const date = dateUtil.formatDate(target)
const summary = summaryMap[date] || { artistCounts: [], totalCount: 0 }
const artistCounts = this.normalizeArtistCounts(summary.artistCounts || []).filter(count => count.count > 0)
const artistCounts = this.normalizeArtistCounts(summary.artistCounts || [], calendar).filter(count => count.count > 0)
return {
date,
weekName: `周${label}`,
@@ -381,9 +408,9 @@ Page({
})
},
buildDayView() {
const startMinute = dateUtil.minutesOfDay(this.data.businessStartTime)
const endMinute = dateUtil.minutesOfDay(this.data.businessEndTime)
buildDayView(calendar) {
const startMinute = dateUtil.minutesOfDay(calendar.businessStartTime || '10:00')
const endMinute = dateUtil.minutesOfDay(calendar.businessEndTime || '22:00')
const timelineHeight = Math.max(560, endMinute - startMinute)
const laneHeaderHeight = 54
const hours = []
@@ -395,9 +422,9 @@ Page({
})
}
const filteredArtists = this.data.selectedArtistId
? this.data.artists.filter(item => String(item.id) === String(this.data.selectedArtistId))
: this.data.artists
const dayAppointments = this.data.appointments.filter(item => resolveAppointmentDate(item) === this.data.currentDateText)
? (calendar.artists || []).filter(item => String(item.id) === String(this.data.selectedArtistId))
: (calendar.artists || [])
const dayAppointments = (calendar.appointments || []).filter(item => resolveAppointmentDate(item) === this.data.currentDateText)
const lanes = filteredArtists.map(artist => {
const blocks = dayAppointments
.filter(item => String(item.artistId) === String(artist.id))
@@ -426,15 +453,15 @@ Page({
}
},
summaryMap() {
return (this.data.daySummaries || []).reduce((map, item) => {
summaryMap(calendar) {
return (calendar.daySummaries || []).reduce((map, item) => {
map[item.date] = item
return map
}, {})
},
normalizeArtistCounts(counts) {
const colorMap = this.data.artists.reduce((map, artist) => {
normalizeArtistCounts(counts, calendar) {
const colorMap = (calendar.artists || []).reduce((map, artist) => {
map[artist.id] = artist
return map
}, {})
@@ -498,7 +525,7 @@ Page({
},
async quickUpdateStatus(event) {
const appointment = this.data.appointments.find(item => String(item.orderItemId) === String(event.currentTarget.dataset.id))
const appointment = (this._calendarData && this._calendarData.appointments || []).find(item => String(item.orderItemId) === String(event.currentTarget.dataset.id))
if (!appointment) return
try {
await planningApi.updateStatus(appointment.orderId, Number(event.currentTarget.dataset.status))
@@ -514,7 +541,7 @@ Page({
},
quickCancel(event) {
const appointment = this.data.appointments.find(item => String(item.orderItemId) === String(event.currentTarget.dataset.id))
const appointment = (this._calendarData && this._calendarData.appointments || []).find(item => String(item.orderItemId) === String(event.currentTarget.dataset.id))
if (!appointment) return
wx.showModal({
title: '取消预约',
@@ -0,0 +1,77 @@
const assert = require('assert')
const planningApi = require('../../api/planning')
global.wx = {
getAccountInfoSync: () => ({ miniProgram: { envVersion: 'develop' } }),
getDeviceInfo: () => ({ platform: 'devtools' }),
getStorageSync: () => '',
setStorageSync: () => {},
removeStorageSync: () => {},
showToast: () => {}
}
global.getApp = () => ({ globalData: { userInfo: {} } })
let definition
global.Page = value => { definition = value }
require('./index')
function createPage(data = {}) {
const page = {
...definition,
data: { ...definition.data, ...data },
setData(values) {
Object.entries(values).forEach(([key, value]) => {
if (!key.includes('.')) {
this.data[key] = value
return
}
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
})
}
}
return page
}
async function run() {
const page = createPage({ viewMode: 'week' })
let monthBuilds = 0
let weekBuilds = 0
let dayBuilds = 0
page.buildMonthDays = () => { monthBuilds += 1; return [] }
page.buildWeekDays = () => { weekBuilds += 1; return [] }
page.buildDayView = () => { dayBuilds += 1; return {} }
page.buildViewState({ artists: [], appointments: [], daySummaries: [] })
assert.deepStrictEqual([monthBuilds, weekBuilds, dayBuilds], [0, 1, 0])
page.data.viewMode = 'month'
page.data.monthDisplayMode = 'count'
const monthDays = definition.buildMonthDays.call(page, {
artists: [{ id: 1, name: '员工', shortName: '员', color: '#000' }],
daySummaries: []
})
assert.strictEqual(monthDays.length, 42)
assert.strictEqual(monthDays.every(item => item.expandedBlocks.length === 0 && item.rowBlocks.length === 0), true)
const requestPage = createPage({ viewMode: 'day', currentDateText: '2026-10-11' })
let calendarRequests = 0
let resolveCalendar
planningApi.calendar = () => {
calendarRequests += 1
return new Promise(resolve => { resolveCalendar = resolve })
}
const requestOne = requestPage.loadCalendar()
const requestTwo = requestPage.loadCalendar()
assert.strictEqual(calendarRequests, 1)
resolveCalendar({ artists: [], appointments: [], daySummaries: [] })
await Promise.all([requestOne, requestTwo])
}
run().catch(error => {
console.error(error)
process.exitCode = 1
})
+4 -4
View File
@@ -25,7 +25,6 @@
.control-card {
padding: 18rpx;
animation: pageFadeIn 180ms ease both;
}
.calendar-error-card {
@@ -297,13 +296,14 @@
border-left: 8rpx solid #7ba7c7;
border-radius: 10px;
background: #fff7ee;
box-shadow: 0 8rpx 16rpx rgba(58, 48, 34, 0.08);
transition: transform 160ms ease, box-shadow 160ms ease;
border-top: 1rpx solid rgba(58, 48, 34, 0.06);
border-right: 1rpx solid rgba(58, 48, 34, 0.06);
border-bottom: 1rpx solid rgba(58, 48, 34, 0.06);
transition: transform 160ms ease;
}
.appointment-block:active {
transform: scale(0.98);
box-shadow: 0 4rpx 10rpx rgba(58, 48, 34, 0.08);
}
.appointment-block.pending {
+5 -3
View File
@@ -3,6 +3,7 @@ const auth = require('../../utils/auth')
const { chooseImageFilePath, uploadProfileImage } = require('../../utils/upload')
const { buildProfileCard, normalizeAvatar } = require('../../utils/profile-card')
const { BRAND_CONFIG } = require('../../utils/config')
const profileCache = require('../../utils/profile-cache')
function resolveRoleText(type) {
const role = Number(type)
@@ -56,10 +57,10 @@ Page({
this.loadProfile()
},
async loadProfile() {
async loadProfile(options = {}) {
this.setData({ loading: true })
try {
const profile = await userApi.info()
const profile = await profileCache.getProfile(options)
this.syncProfileToSession(profile)
} catch (error) {
wx.showToast({ title: error.message || '个人信息加载失败', icon: 'none' })
@@ -163,7 +164,8 @@ Page({
wechatId: String(form.wechatId || '').trim(),
signature: String(form.signature || '').trim()
})
const profile = await userApi.info()
profileCache.invalidate()
const profile = await profileCache.getProfile({ force: true })
this.syncProfileToSession(profile)
wx.showToast({ title: '已保存', icon: 'success' })
setTimeout(() => wx.navigateBack(), 350)
+11 -31
View File
@@ -1,11 +1,8 @@
const { BRAND_CONFIG } = require('../../utils/config')
const userApi = require('../../api/user')
const auth = require('../../utils/auth')
const planningApi = require('../../api/planning')
const employeesApi = require('../../api/employees')
const shopApi = require('../../api/shop')
const dateUtil = require('../../utils/date')
const { buildProfileCard } = require('../../utils/profile-card')
const profileCache = require('../../utils/profile-cache')
function resolveRoleText(type) {
const role = Number(type)
@@ -46,36 +43,19 @@ Page({
},
async loadOverview() {
const today = dateUtil.formatDate(new Date())
this.setData({ overviewLoading: true })
try {
const [calendar, shop] = await Promise.all([
planningApi.calendar({ startDate: today, endDate: today }),
shopApi.settings()
])
const appointments = Array.isArray(calendar.appointments) ? calendar.appointments : []
const now = Date.now()
const upcomingAppointments = appointments.filter(item => {
const appointmentTime = new Date(String(item.appointmentTime || item.startTime || '').replace(/-/g, '/')).getTime()
return Number.isFinite(appointmentTime) && appointmentTime >= now
}).length
const artists = Array.isArray(calendar.artists) ? calendar.artists : []
const scheduleRules = await Promise.all(artists.map(artist => employeesApi.scheduleRule({ artistId: artist.id })))
const scheduleExceptions = scheduleRules.reduce((total, setting) => {
const exceptions = Array.isArray(setting && setting.exceptions) ? setting.exceptions : []
return total + exceptions.filter(item => item.workDate === today).length
}, 0)
const shopOpen = Number(shop && shop.status) !== 0
const overview = await planningApi.todayOverview()
this.setData({
overview: {
date: `${today.slice(5, 7)}月${today.slice(8, 10)}日`,
todayAppointments: appointments.length,
pendingAppointments: appointments.filter(item => Number(item.status) === 0).length,
upcomingAppointments,
availableEmployees: artists.filter(item => Number(item.status) !== 0).length,
scheduleExceptions,
shopOpen,
shopStatus: shopOpen ? '营业中' : '已暂停'
date: overview.date || '',
todayAppointments: Number(overview.todayAppointments || 0),
pendingAppointments: Number(overview.pendingAppointments || 0),
upcomingAppointments: Number(overview.upcomingAppointments || 0),
availableEmployees: Number(overview.availableEmployees || 0),
scheduleExceptions: Number(overview.scheduleExceptions || 0),
shopOpen: overview.shopOpen !== false,
shopStatus: overview.shopStatus || (overview.shopOpen === false ? '已暂停' : '营业中')
}
})
} catch (error) {
@@ -110,7 +90,7 @@ Page({
async loadProfile() {
try {
const profile = await userApi.info()
const profile = await profileCache.getProfile()
this.syncProfileToSession(profile)
} catch (error) {
wx.showToast({ title: error.message || '个人信息加载失败', icon: 'none' })