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

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
@@ -21,6 +21,7 @@ import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmen
import com.xiaowang.jacyucloudsalon.core.modules.planning.service.PlanningService;
import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningAppointmentVO;
import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningCalendarVO;
import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningTodayOverviewVO;
import com.xiaowang.jacyucloudsalon.core.modules.product.service.ProductService;
import com.xiaowang.jacyucloudsalon.core.modules.product.vo.ProductVO;
import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper;
@@ -72,6 +73,13 @@ public class AdminManagerController {
return Result.success(planningService.getCalendar(currentUser, start, end, artistId));
}
@GetMapping("/planning/today-overview")
@RequirePermission("schedule:view")
public Result<PlanningTodayOverviewVO> todayOverview(HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
return Result.success(planningService.getTodayOverview(currentUser));
}
@PostMapping("/planning/appointments")
@RequirePermission("order:process")
@OperationGuard(action = "manager-planning-create-appointment", ttlSeconds = 10, message = "预约创建处理中,请勿重复提交")
@@ -6,12 +6,15 @@ import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmen
import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO;
import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningAppointmentVO;
import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningCalendarVO;
import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningTodayOverviewVO;
import java.time.LocalDate;
public interface PlanningService {
PlanningCalendarVO getCalendar(UserDO currentUser, LocalDate startDate, LocalDate endDate, Long artistId);
PlanningTodayOverviewVO getTodayOverview(UserDO currentUser);
PlanningAppointmentVO createAppointment(UserDO currentUser, PlanningAppointmentCreateDTO dto);
PlanningAppointmentVO getAppointment(UserDO currentUser, Long orderItemId);
@@ -6,6 +6,7 @@ import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmen
import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentStatusDTO;
import com.xiaowang.jacyucloudsalon.core.modules.planning.entity.AppointmentReservationDO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleExceptionDO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.NailArtistInfoDO;
import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderDO;
import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderItemDO;
@@ -14,6 +15,7 @@ import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO;
import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO;
import com.xiaowang.jacyucloudsalon.core.modules.planning.mapper.AppointmentReservationMapper;
import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.ArtistScheduleExceptionMapper;
import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.NailArtistInfoMapper;
import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderMapper;
@@ -26,6 +28,7 @@ import com.xiaowang.jacyucloudsalon.core.modules.planning.service.PlanningServic
import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.jacyucloudsalon.core.modules.order.support.OrderStatus;
import com.xiaowang.jacyucloudsalon.core.modules.planning.support.PlanningCalendarSupport;
import com.xiaowang.jacyucloudsalon.core.modules.planning.support.PlanningTodayOverviewSupport;
import com.xiaowang.jacyucloudsalon.core.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningAppointmentVO;
import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningArtistCountVO;
@@ -33,6 +36,7 @@ import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningArtistVO;
import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningCalendarVO;
import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningDaySummaryVO;
import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningScheduleVO;
import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningTodayOverviewVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -75,6 +79,7 @@ public class PlanningServiceImpl implements PlanningService {
private final UserMapper userMapper;
private final NailArtistInfoMapper nailArtistInfoMapper;
private final ArtistScheduleMapper artistScheduleMapper;
private final ArtistScheduleExceptionMapper artistScheduleExceptionMapper;
private final AppointmentReservationMapper appointmentReservationMapper;
private final OrderMapper orderMapper;
private final OrderItemMapper orderItemMapper;
@@ -103,8 +108,10 @@ public class PlanningServiceImpl implements PlanningService {
List<PlanningArtistVO> artists = listArtists(shopId, artistId);
List<ArtistScheduleDO> schedules = listSchedules(shopId, start, end, artistId);
Map<Long, String> artistNames = artists.stream()
.collect(Collectors.toMap(PlanningArtistVO::getId, PlanningArtistVO::getName, (a, b) -> a));
List<PlanningScheduleVO> scheduleVos = schedules.stream()
.map(schedule -> toScheduleVO(schedule, artists))
.map(schedule -> toScheduleVO(schedule, artistNames))
.sorted(Comparator.comparing(PlanningScheduleVO::getDate)
.thenComparing(PlanningScheduleVO::getStartTime)
.thenComparing(PlanningScheduleVO::getArtistName, Comparator.nullsLast(String::compareTo)))
@@ -129,6 +136,27 @@ public class PlanningServiceImpl implements PlanningService {
return vo;
}
@Override
public PlanningTodayOverviewVO getTodayOverview(UserDO currentUser) {
LocalDate today = LocalDate.now();
Long shopId = requirePlanningShopId(currentUser);
PlanningCalendarVO calendar = getCalendar(currentUser, today, today, null);
QueryWrapper<ArtistScheduleExceptionDO> exceptionWrapper = new QueryWrapper<>();
exceptionWrapper.eq("shop_id", shopId)
.eq("work_date", today)
.eq("is_delete", 0);
Long exceptionCount = artistScheduleExceptionMapper.selectCount(exceptionWrapper);
ShopDO shop = shopMapper.selectById(shopId);
boolean shopOpen = shop != null && !Integer.valueOf(0).equals(shop.getStatus());
return PlanningTodayOverviewSupport.build(
calendar,
today,
LocalTime.now(),
exceptionCount == null ? 0L : exceptionCount,
shopOpen
);
}
@Override
@Transactional
public PlanningAppointmentVO createAppointment(UserDO currentUser, PlanningAppointmentCreateDTO dto) {
@@ -340,9 +368,7 @@ public class PlanningServiceImpl implements PlanningService {
return artistScheduleMapper.selectList(wrapper);
}
private PlanningScheduleVO toScheduleVO(ArtistScheduleDO schedule, List<PlanningArtistVO> artists) {
Map<Long, String> artistNames = artists.stream()
.collect(Collectors.toMap(PlanningArtistVO::getId, PlanningArtistVO::getName, (a, b) -> a));
private PlanningScheduleVO toScheduleVO(ArtistScheduleDO schedule, Map<Long, String> artistNames) {
PlanningScheduleVO vo = new PlanningScheduleVO();
vo.setId(schedule.getId());
vo.setArtistId(schedule.getArtistId());
@@ -518,6 +544,9 @@ public class PlanningServiceImpl implements PlanningService {
Map<Long, Long> countByArtist = dayAppointments.stream()
.filter(appointment -> appointment.getArtistId() != null)
.collect(Collectors.groupingBy(PlanningAppointmentVO::getArtistId, Collectors.counting()));
Map<Long, List<PlanningAppointmentVO>> appointmentsByArtist = dayAppointments.stream()
.filter(appointment -> appointment.getArtistId() != null)
.collect(Collectors.groupingBy(PlanningAppointmentVO::getArtistId));
List<ArtistScheduleDO> daySchedules = schedulesByDate.getOrDefault(date, List.of());
Map<Long, ArtistScheduleDO> scheduleByArtist = daySchedules.stream()
.collect(Collectors.toMap(ArtistScheduleDO::getArtistId, Function.identity(), (a, b) -> a));
@@ -528,9 +557,7 @@ public class PlanningServiceImpl implements PlanningService {
for (PlanningArtistVO artist : artists) {
int count = countByArtist.getOrDefault(artist.getId(), 0L).intValue();
ArtistScheduleDO schedule = scheduleByArtist.get(artist.getId());
List<PlanningAppointmentVO> artistAppointments = dayAppointments.stream()
.filter(appointment -> Objects.equals(appointment.getArtistId(), artist.getId()))
.toList();
List<PlanningAppointmentVO> artistAppointments = appointmentsByArtist.getOrDefault(artist.getId(), List.of());
String artistStatus = resolveArtistDayStatus(artist, schedule, artistAppointments);
if (!"rest".equals(artistStatus)) {
workingArtistCount++;
@@ -0,0 +1,45 @@
package com.xiaowang.jacyucloudsalon.core.modules.planning.support;
import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningAppointmentVO;
import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningArtistVO;
import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningCalendarVO;
import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningTodayOverviewVO;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;
public final class PlanningTodayOverviewSupport {
private PlanningTodayOverviewSupport() {
}
public static PlanningTodayOverviewVO build(PlanningCalendarVO calendar,
LocalDate date,
LocalTime now,
long scheduleExceptions,
boolean shopOpen) {
List<PlanningAppointmentVO> appointments = calendar == null || calendar.getAppointments() == null
? List.of() : calendar.getAppointments();
List<PlanningArtistVO> artists = calendar == null || calendar.getArtists() == null
? List.of() : calendar.getArtists();
int currentMinute = now.getHour() * 60 + now.getMinute();
PlanningTodayOverviewVO overview = new PlanningTodayOverviewVO();
overview.setDate(String.format("%02d月%02d日", date.getMonthValue(), date.getDayOfMonth()));
overview.setTodayAppointments(appointments.size());
overview.setPendingAppointments((int) appointments.stream()
.filter(item -> Integer.valueOf(0).equals(item.getStatus()))
.count());
overview.setUpcomingAppointments((int) appointments.stream()
.filter(item -> item.getStartMinute() != null && item.getStartMinute() >= currentMinute)
.count());
overview.setAvailableEmployees((int) artists.stream()
.filter(item -> !Integer.valueOf(0).equals(item.getStatus()))
.count());
overview.setScheduleExceptions(Math.toIntExact(Math.max(0L, scheduleExceptions)));
overview.setShopOpen(shopOpen);
overview.setShopStatus(shopOpen ? "营业中" : "已暂停");
return overview;
}
}
@@ -0,0 +1,15 @@
package com.xiaowang.jacyucloudsalon.core.modules.planning.vo;
import lombok.Data;
@Data
public class PlanningTodayOverviewVO {
private String date;
private Integer todayAppointments;
private Integer pendingAppointments;
private Integer upcomingAppointments;
private Integer availableEmployees;
private Integer scheduleExceptions;
private Boolean shopOpen;
private String shopStatus;
}
+6
View File
@@ -8,6 +8,12 @@ module.exports = {
})
},
todayOverview() {
return request({
url: '/manager/planning/today-overview'
})
},
createAppointment(data) {
return request({
url: '/manager/planning/appointments',
+6 -3
View File
@@ -27,15 +27,19 @@ function reset(preference) {
navigations.length = 0
appDefinition.globalData.userInfo = null
appDefinition.globalData.wechatLoginState = null
codeSequence = 0
}
async function run() {
reset({ rememberMe: true, agreementVersions: { USER_TERMS: '1', PRIVACY_POLICY: '1' } })
authApi.wechatStatus = async () => ({ status: 'READY' })
let statusCalled = false
authApi.wechatStatus = async () => { statusCalled = true; return { status: 'READY' } }
authApi.wechatQuickLogin = async () => ({ status: 'SUCCESS', accessToken: 'token', userInfo: { id: 1 } })
await appDefinition.runWechatBootstrap()
assert.deepStrictEqual(navigations, ['/pages/planning/index'])
assert.strictEqual(appDefinition.globalData.userInfo.id, 1)
assert.strictEqual(statusCalled, false)
assert.strictEqual(codeSequence, 1)
reset({ rememberMe: false })
let quickLoginCalled = false
@@ -44,9 +48,9 @@ async function run() {
await appDefinition.runWechatBootstrap()
assert.deepStrictEqual(navigations, ['/pages/login/index'])
assert.strictEqual(quickLoginCalled, false)
assert.strictEqual(codeSequence, 1)
reset({ rememberMe: true, agreementVersions: { USER_TERMS: '1', PRIVACY_POLICY: '1' } })
authApi.wechatStatus = async () => ({ status: 'READY' })
authApi.wechatQuickLogin = async () => { throw new Error('网络异常') }
await appDefinition.runWechatBootstrap()
assert.deepStrictEqual(navigations, ['/pages/login/index'])
@@ -54,7 +58,6 @@ async function run() {
assert.strictEqual(appDefinition.globalData.wechatLoginState.status, 'ERROR')
reset({ rememberMe: true, agreementVersions: { USER_TERMS: '1', PRIVACY_POLICY: '1' } })
authApi.wechatStatus = async () => ({ status: 'READY' })
authApi.wechatQuickLogin = async () => ({ status: 'SELECT_SHOP', ticket: 'ticket', shops: [{ id: 2 }] })
await appDefinition.runWechatBootstrap()
assert.deepStrictEqual(navigations, ['/pages/login/index'])
+6 -4
View File
@@ -1,7 +1,7 @@
const auth = require('./utils/auth')
const authApi = require('./api/auth')
const { BRAND_CONFIG } = require('./utils/config')
const loginFlow = require('./utils/login-flow')
const profileCache = require('./utils/profile-cache')
App({
globalData: {
@@ -37,10 +37,10 @@ App({
async runWechatBootstrap() {
try {
const status = await authApi.wechatStatus(await this.getWechatCode())
this.publishWechatLoginState(status)
const preference = auth.getLoginPreference()
if (!loginFlow.shouldAutoLogin(preference, status)) {
if (!preference || !preference.rememberMe) {
const status = await authApi.wechatStatus(await this.getWechatCode())
this.publishWechatLoginState(status)
auth.clearSession()
this.globalData.userInfo = null
this.goLogin()
@@ -103,11 +103,13 @@ App({
clearSession() {
auth.clearSession()
profileCache.invalidate()
this.globalData.userInfo = null
},
logoutDevice() {
auth.clearDeviceLoginState()
profileCache.invalidate()
this.globalData.userInfo = null
this.globalData.wechatLoginState = null
}
+1
View File
@@ -22,6 +22,7 @@
"pages/password/index",
"pages/about/index"
],
"lazyCodeLoading": "requiredComponents",
"window": {
"navigationBarTitleText": "甲屿店务",
"navigationBarBackgroundColor": "#F8F5EF",
+1 -2
View File
@@ -220,8 +220,7 @@ button::after {
left: 0;
z-index: 20;
padding: 14rpx 24rpx calc(14rpx + env(safe-area-inset-bottom));
background: rgba(248, 245, 239, 0.94);
backdrop-filter: blur(18rpx);
background: #f8f5ef;
}
.fab {
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 MiB

After

Width:  |  Height:  |  Size: 144 KiB

@@ -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' })
+52
View File
@@ -0,0 +1,52 @@
const userApi = require('../api/user')
const DEFAULT_TTL_MS = 30 * 1000
let cachedProfile = null
let expiresAt = 0
let pendingRequest = null
function getProfile(options = {}) {
const force = options.force === true
const ttlMs = Number.isFinite(options.ttlMs) ? Math.max(0, options.ttlMs) : DEFAULT_TTL_MS
const now = Date.now()
if (!force && cachedProfile && now < expiresAt) {
return Promise.resolve(cachedProfile)
}
if (pendingRequest) return pendingRequest
pendingRequest = userApi.info()
.then(profile => {
cachedProfile = profile || {}
expiresAt = Date.now() + ttlMs
return cachedProfile
})
.finally(() => {
pendingRequest = null
})
return pendingRequest
}
function setProfile(profile, ttlMs = DEFAULT_TTL_MS) {
cachedProfile = profile || {}
expiresAt = Date.now() + Math.max(0, ttlMs)
return cachedProfile
}
function invalidate() {
cachedProfile = null
expiresAt = 0
}
function resetForTest() {
invalidate()
pendingRequest = null
}
module.exports = {
DEFAULT_TTL_MS,
getProfile,
setProfile,
invalidate,
resetForTest
}
@@ -0,0 +1,40 @@
const assert = require('assert')
const userApi = require('../api/user')
const profileCache = require('./profile-cache')
async function run() {
let requests = 0
let resolver
userApi.info = () => {
requests += 1
return new Promise(resolve => { resolver = resolve })
}
profileCache.resetForTest()
const first = profileCache.getProfile()
const second = profileCache.getProfile()
assert.strictEqual(requests, 1)
resolver({ id: 1, nickname: '甲屿' })
assert.deepStrictEqual(await first, { id: 1, nickname: '甲屿' })
assert.deepStrictEqual(await second, { id: 1, nickname: '甲屿' })
await profileCache.getProfile()
assert.strictEqual(requests, 1)
userApi.info = async () => {
requests += 1
return { id: 1, nickname: '新昵称' }
}
profileCache.invalidate()
assert.strictEqual((await profileCache.getProfile()).nickname, '新昵称')
assert.strictEqual(requests, 2)
profileCache.setProfile({ id: 2 }, 0)
await profileCache.getProfile()
assert.strictEqual(requests, 3)
}
run().catch(error => {
console.error(error)
process.exitCode = 1
})
@@ -59,7 +59,7 @@
### 首包与样式
- 将 1254×1254、约 1.49 MB 的应用图标缩放压缩到适合小程序展示的尺寸。
- 登录、启动和四个 Tab 页保留主包;预约详情、资料设置、门店设置等非首屏页面配置为分包,路由地址保持不变。
- 优先压缩主包大图并启用按需组件注入;压缩后若整体体积已低于 500 KB,则保留现有页面目录,避免为边际收益搬迁路由。只有后续主包再次明显增长时再拆分非首屏页面。
- 仅减少低端设备代价较高且不影响信息表达的模糊、常驻动画和重复阴影;保留整体视觉风格。
## 错误处理与兼容性