Files
JayuCloud/JY-Salon-WeChat/pages/planning/index.js
T

759 lines
24 KiB
JavaScript

const planningApi = require('../../api/planning')
const shopApi = require('../../api/shop')
const dateUtil = require('../../utils/date')
const { markPlanningRefresh } = require('../../utils/planning-refresh')
const CALENDAR_ERROR_FALLBACK_MESSAGE = '规划数据暂时不可用,请稍后重试'
const TECHNICAL_ERROR_PATTERNS = [
/###\s*Error/i,
/SQLSyntaxErrorException/i,
/bad\s+SQL\s+grammar/i,
/Unknown\s+column/i,
/mapper\//i,
/java\./i
]
function canCreateAppointment() {
const app = getApp()
const userInfo = app.globalData.userInfo || {}
return Number(userInfo.type) !== 3
}
function resolveCalendarErrorMessage(error) {
const message = error && error.message ? String(error.message).trim() : ''
if (!message) {
return CALENDAR_ERROR_FALLBACK_MESSAGE
}
const hasTechnicalMessage = TECHNICAL_ERROR_PATTERNS.some(pattern => pattern.test(message))
return hasTechnicalMessage ? CALENDAR_ERROR_FALLBACK_MESSAGE : message
}
function toLocalDate(value) {
return value instanceof Date ? new Date(value.getTime()) : new Date(String(value).replace(/-/g, '/'))
}
function formatMonthDay(value) {
const target = toLocalDate(value)
return `${target.getMonth() + 1}月${target.getDate()}日`
}
function formatActionDate(value) {
const target = toLocalDate(value)
const weekLabels = ['日', '一', '二', '三', '四', '五', '六']
return `${target.getMonth() + 1}月${target.getDate()}日 周${weekLabels[target.getDay()]}`
}
function formatShortDate(value) {
const target = toLocalDate(value)
return `${target.getMonth() + 1}月${target.getDate()}日`
}
function buildAppointmentFormUrl(date, artistId) {
return `/pages/appointment-form/index?date=${date}&artistId=${artistId || ''}`
}
const SPECIAL_DATE_TYPES = [
{ value: 'REST', label: '休息日', desc: '当天不开放预约', icon: '休', tone: 'rest', requiresTime: false },
{ value: 'EXTRA_WORK', label: '临时营业', desc: '原休息日也可开放预约', icon: '营', tone: 'work', requiresTime: true },
{ value: 'CHANGE_SHIFT', label: '临时改班', desc: '当天改成指定营业时段', icon: '改', tone: 'shift', requiresTime: true }
]
function resolveSpecialDateType(value) {
return SPECIAL_DATE_TYPES.find(item => item.value === value) || SPECIAL_DATE_TYPES[0]
}
function buildSpecialDateTypes(activeValue) {
return SPECIAL_DATE_TYPES.map(item => ({
...item,
active: item.value === activeValue
}))
}
function resolveAppointmentDate(item) {
if (item.date) return item.date
return String(item.startTime || '').slice(0, 10)
}
function resolveAppointmentStartMinute(item) {
if (item.startMinute !== undefined && item.startMinute !== null) {
return Number(item.startMinute)
}
const timeText = String(item.startTime || '').slice(11, 16)
return dateUtil.minutesOfDay(timeText)
}
function resolveAppointmentTimeText(item) {
const startMinute = resolveAppointmentStartMinute(item)
const duration = Number(item.durationMinutes || 60)
const startText = String(item.startTime || '').slice(11, 16) || dateUtil.timeFromMinutes(startMinute)
const endText = String(item.endTime || '').slice(11, 16) || dateUtil.timeFromMinutes(startMinute + duration)
return `${startText}-${endText}`
}
function buildAppointmentBadges(item) {
const badges = []
if (item.needRemoval) {
badges.push({ key: 'needRemoval', text: '需卸甲', type: 'removal' })
}
if (item.fromMeituan) {
badges.push({ key: 'fromMeituan', text: '美团', type: 'meituan' })
}
if (item.depositPaid) {
badges.push({ key: 'depositPaid', text: '已交定金', type: 'deposit' })
}
return badges
}
function isCompletedStatus(status) {
return Number(status) === 2
}
function isCancelledStatus(status) {
return Number(status) === 3
}
function appointmentStatusClass(status) {
if (isCompletedStatus(status)) return 'is-completed'
if (isCancelledStatus(status)) return 'is-cancelled'
if (Number(status) === 0) return 'pending'
return ''
}
function completedOrCancelledClass(status) {
if (isCompletedStatus(status)) return 'is-completed'
if (isCancelledStatus(status)) return 'is-cancelled'
return ''
}
function resolveDayStatusClass(items) {
if (!items.length) return ''
if (items.every(item => isCompletedStatus(item.status))) return 'is-completed'
if (items.every(item => isCancelledStatus(item.status))) return 'is-cancelled'
return ''
}
function normalizeWorkDays(workDays, presetType) {
if (presetType === 'DOUBLE_REST') {
return [1, 2, 3, 4, 5]
}
if (presetType === 'SINGLE_REST') {
return [1, 2, 3, 4, 5, 6]
}
if (presetType === 'EVERYDAY') {
return [1, 2, 3, 4, 5, 6, 7]
}
const values = String(workDays || '')
.split(',')
.map(item => Number(String(item).trim()))
.filter(item => item >= 1 && item <= 7)
return Array.from(new Set(values.length ? values : [1, 2, 3, 4, 5, 6, 7]))
}
function buildExceptionMap(exceptions) {
return (exceptions || []).reduce((map, item) => {
if (item && item.workDate) {
map[item.workDate] = item.exceptionType
}
return map
}, {})
}
function isShopRestDate(date, workDays, exceptionMap) {
const exceptionType = exceptionMap[date]
if (exceptionType === 'REST') {
return true
}
if (exceptionType === 'EXTRA_WORK' || exceptionType === 'CHANGE_SHIFT') {
return false
}
const weekDay = toLocalDate(date).getDay() || 7
return !workDays.includes(weekDay)
}
Page({
data: {
viewMode: 'month',
viewModes: [
{ value: 'month', label: '月' },
{ value: 'week', label: '周' },
{ value: 'day', label: '日' }
],
monthDisplayMode: 'count',
monthDisplayModes: [
{ value: 'count', label: '单量' },
{ value: 'blocks', label: '点阵' },
{ value: 'rows', label: '横条' }
],
monthRowLabelVisible: false,
weekLabels: ['一', '二', '三', '四', '五', '六', '日'],
currentDate: new Date(),
currentDateText: dateUtil.formatDate(new Date()),
selectedArtistId: '',
selectedArtistName: '全部员工',
dateTitle: '',
rangeText: '',
weekRange: '',
businessStartTime: '10:00',
businessEndTime: '22:00',
artists: [],
appointments: [],
daySummaries: [],
shopRestDates: [],
monthDays: [],
weekDays: [],
dayLanes: [],
hours: [],
timelineHeight: 720,
laneWidth: 720,
laneItemWidth: 240,
laneHeaderHeight: 54,
dayTotal: 0,
freeArtistCount: 0,
pendingCount: 0,
canCreateAppointment: true,
loading: false,
calendarError: '',
emptyDateActionVisible: false,
pendingEmptyDate: '',
pendingEmptyDateTitle: '',
pendingEmptyDateLabel: '',
specialDateTypes: buildSpecialDateTypes('REST'),
pendingSpecialDateType: 'REST',
pendingSpecialDateTypeLabel: '休息日',
pendingSpecialDateRequiresTime: false,
pendingSpecialDateStartTime: '10:00',
pendingSpecialDateEndTime: '22:00',
savingSpecialDate: false
},
onLoad() {
this.setData({ canCreateAppointment: canCreateAppointment() })
this.loadCalendar()
},
onShow() {
const app = getApp()
const storageRefresh = wx.getStorageSync('planningNeedRefresh') === '1'
if (this._needRefresh || app.globalData.planningNeedRefresh || storageRefresh) {
this._needRefresh = false
app.globalData.planningNeedRefresh = false
wx.removeStorageSync('planningNeedRefresh')
this.loadCalendar()
}
},
switchView(event) {
this.setData({ viewMode: event.currentTarget.dataset.mode })
this.prepareView()
this.loadCalendar()
},
switchMonthDisplay(event) {
this.setData({ monthDisplayMode: event.currentTarget.dataset.mode })
},
toggleMonthRowLabel() {
this.setData({ monthRowLabelVisible: !this.data.monthRowLabelVisible })
},
selectArtist(event) {
const id = event.currentTarget.dataset.id || ''
const artist = this.data.artists.find(item => String(item.id) === String(id))
this.setData({
selectedArtistId: id,
selectedArtistName: artist ? artist.name : '全部员工'
})
this.loadCalendar()
},
selectDate(event) {
const currentDate = dateUtil.formatDate(event.currentTarget.dataset.date)
if (this.data.viewMode === 'month') {
const monthDay = this.data.monthDays.find(item => item.date === currentDate)
if (monthDay && monthDay.isCurrentMonth && !monthDay.isPast && Number(monthDay.totalCount || 0) === 0) {
this.openEmptyDateAction(currentDate)
return
}
}
this.setData({
currentDate,
currentDateText: currentDate,
viewMode: this.data.viewMode === 'month' ? 'day' : this.data.viewMode,
emptyDateActionVisible: false,
pendingEmptyDate: '',
pendingEmptyDateTitle: '',
pendingEmptyDateLabel: '',
savingSpecialDate: false
})
this.prepareView()
},
openEmptyDateAction(date) {
const currentDate = dateUtil.formatDate(date)
const monthDay = this.data.monthDays.find(item => item.date === currentDate)
const typeValue = monthDay && monthDay.shopRest ? 'EXTRA_WORK' : 'REST'
const option = resolveSpecialDateType(typeValue)
this.setData({
currentDate,
currentDateText: currentDate,
emptyDateActionVisible: true,
pendingEmptyDate: currentDate,
pendingEmptyDateTitle: formatActionDate(currentDate),
pendingEmptyDateLabel: formatShortDate(currentDate),
specialDateTypes: buildSpecialDateTypes(option.value),
pendingSpecialDateType: option.value,
pendingSpecialDateTypeLabel: option.label,
pendingSpecialDateRequiresTime: option.requiresTime,
pendingSpecialDateStartTime: this.data.businessStartTime,
pendingSpecialDateEndTime: this.data.businessEndTime,
savingSpecialDate: false
})
this.prepareView()
},
closeEmptyDateAction() {
const option = resolveSpecialDateType('REST')
this.setData({
emptyDateActionVisible: false,
pendingEmptyDate: '',
pendingEmptyDateTitle: '',
pendingEmptyDateLabel: '',
specialDateTypes: buildSpecialDateTypes(option.value),
pendingSpecialDateType: option.value,
pendingSpecialDateTypeLabel: option.label,
pendingSpecialDateRequiresTime: option.requiresTime,
pendingSpecialDateStartTime: this.data.businessStartTime,
pendingSpecialDateEndTime: this.data.businessEndTime,
savingSpecialDate: false
})
},
stopTap() {},
selectEmptyDateSpecialType(event) {
const value = String(event.currentTarget.dataset.value || 'REST')
const option = resolveSpecialDateType(value)
this.setData({
specialDateTypes: buildSpecialDateTypes(option.value),
pendingSpecialDateType: option.value,
pendingSpecialDateTypeLabel: option.label,
pendingSpecialDateRequiresTime: option.requiresTime
})
},
onEmptyDateStartTimeChange(event) {
this.setData({ pendingSpecialDateStartTime: event.detail.value })
},
onEmptyDateEndTimeChange(event) {
this.setData({ pendingSpecialDateEndTime: event.detail.value })
},
prevRange() {
this.shiftRange(-1)
},
nextRange() {
this.shiftRange(1)
},
goToday() {
const today = new Date()
this.setData({
currentDate: today,
currentDateText: dateUtil.formatDate(today)
})
this.loadCalendar()
},
shiftRange(direction) {
let next
if (this.data.viewMode === 'month') {
next = dateUtil.addMonths(this.data.currentDateText, direction)
} else if (this.data.viewMode === 'week') {
next = dateUtil.addDays(this.data.currentDateText, direction * 7)
} else {
next = dateUtil.addDays(this.data.currentDateText, direction)
}
this.setData({
currentDate: next,
currentDateText: dateUtil.formatDate(next)
})
this.loadCalendar()
},
async loadCalendar() {
const range = this.resolveRange()
this.setData({ loading: true })
try {
const data = await planningApi.calendar({
startDate: range.start,
endDate: range.end,
artistId: this.data.selectedArtistId || undefined
})
const shopSchedule = await this.loadShopSchedule(range)
this.applyCalendar(data, shopSchedule)
this.setData({ calendarError: '' })
} catch (error) {
this.clearCalendarView()
this.setData({
calendarError: resolveCalendarErrorMessage(error),
selectedArtistId: '',
selectedArtistName: '全部员工'
})
wx.showToast({
title: '规划数据加载失败',
icon: 'none'
})
} finally {
this.setData({ loading: false })
}
},
clearCalendarView() {
this.setData({
businessStartTime: '10:00',
businessEndTime: '22:00',
artists: [],
appointments: [],
daySummaries: [],
shopRestDates: [],
monthDays: [],
weekDays: [],
dayLanes: [],
hours: [],
dayTotal: 0,
freeArtistCount: 0,
pendingCount: 0
})
},
resolveRange() {
const current = this.data.currentDateText
if (this.data.viewMode === 'week') {
return {
start: dateUtil.formatDate(dateUtil.startOfWeek(current)),
end: dateUtil.formatDate(dateUtil.endOfWeek(current))
}
}
if (this.data.viewMode === 'month') {
return {
start: dateUtil.formatDate(dateUtil.startOfMonth(current)),
end: dateUtil.formatDate(dateUtil.endOfMonth(current))
}
}
return { start: current, end: current }
},
applyCalendar(calendar, shopSchedule) {
const artists = calendar.artists || []
this.setData({
businessStartTime: (calendar.businessStartTime || '10:00').slice(0, 5),
businessEndTime: (calendar.businessEndTime || '22:00').slice(0, 5),
artists,
appointments: calendar.appointments || [],
daySummaries: calendar.daySummaries || [],
shopRestDates: shopSchedule ? shopSchedule.restDates : []
})
this.prepareView()
},
async loadShopSchedule(range) {
const [settings, exceptions] = await Promise.all([
shopApi.settings(),
shopApi.scheduleExceptions({
startDate: range.start,
endDate: range.end
})
])
const workDays = normalizeWorkDays(settings.scheduleWorkDays, settings.schedulePresetType)
const exceptionMap = buildExceptionMap(exceptions)
const restDates = []
let cursor = range.start
while (cursor <= range.end) {
if (isShopRestDate(cursor, workDays, exceptionMap)) {
restDates.push(cursor)
}
cursor = dateUtil.formatDate(dateUtil.addDays(cursor, 1))
}
return { restDates }
},
prepareView() {
const current = this.data.currentDateText
const range = this.resolveRange()
const title = this.data.viewMode === 'month'
? dateUtil.formatMonth(current)
: this.data.viewMode === 'week'
? `${formatMonthDay(range.start)} - ${formatMonthDay(range.end)}`
: dateUtil.formatCnDate(current)
this.setData({
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()
})
},
buildMonthDays() {
const summaryMap = this.summaryMap()
const todayText = dateUtil.formatDate(new Date())
const shopRestDates = this.data.shopRestDates || []
const artistTemplate = this.data.artists.map(artist => ({
artistId: artist.id,
artistName: artist.name,
shortName: artist.shortName,
color: artist.color,
count: 0,
status: 'free'
}))
return dateUtil.monthGrid(this.data.currentDateText).map(day => {
const summary = summaryMap[day.date] || {}
const dayAppointments = this.appointmentsByDate(day.date)
const artistCounts = dayAppointments.length
? this.appointmentCountsByDate(day.date)
: this.normalizeArtistCounts(summary.artistCounts || artistTemplate)
return {
...day,
isPast: day.date < todayText,
totalCount: summary.totalCount || 0,
dayStatus: summary.dayStatus || 'free',
shopRest: shopRestDates.includes(day.date),
artistCounts,
expandedBlocks: this.buildExpandedBlocks(artistCounts),
rowBlocks: this.buildRowBlocks(artistCounts),
statusClass: resolveDayStatusClass(dayAppointments)
}
})
},
buildWeekDays() {
const start = dateUtil.startOfWeek(this.data.currentDateText)
const summaryMap = this.summaryMap()
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 dayAppointments = this.appointmentsByDate(date)
const artistCounts = (dayAppointments.length ? this.appointmentCountsByDate(date) : this.normalizeArtistCounts(summary.artistCounts || [])).filter(count => count.count > 0)
return {
date,
weekName: `周${label}`,
day: target.getDate(),
totalCount: summary.totalCount || 0,
statusClass: resolveDayStatusClass(dayAppointments),
artistCounts: artistCounts.map(count => ({
...count,
width: Math.max(12, Math.min(100, count.count * 22)),
barWidth: Math.max(14, Math.min(100, count.count * 18))
}))
}
})
},
buildDayView() {
const startMinute = dateUtil.minutesOfDay(this.data.businessStartTime)
const endMinute = dateUtil.minutesOfDay(this.data.businessEndTime)
const timelineHeight = Math.max(560, endMinute - startMinute)
const laneHeaderHeight = 54
const hours = []
for (let cursor = startMinute; cursor <= endMinute; cursor += 60) {
hours.push({
value: cursor,
label: dateUtil.timeFromMinutes(cursor),
top: cursor - startMinute + laneHeaderHeight
})
}
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)
const lanes = filteredArtists.map(artist => {
const blocks = dayAppointments
.filter(item => String(item.artistId) === String(artist.id))
.map(item => {
const itemStart = resolveAppointmentStartMinute(item)
return {
...item,
top: Math.max(0, itemStart - startMinute) + laneHeaderHeight,
height: Math.max(82, item.durationMinutes || 60),
timeText: resolveAppointmentTimeText(item),
badges: buildAppointmentBadges(item),
statusClass: appointmentStatusClass(item.status)
}
})
return { ...artist, blocks }
})
const pendingCount = dayAppointments.filter(item => item.status === 0).length
return {
dayLanes: lanes,
hours,
timelineHeight: timelineHeight + laneHeaderHeight,
laneHeaderHeight,
laneItemWidth: 268,
laneWidth: Math.max(760, lanes.length * 268),
dayTotal: dayAppointments.length,
freeArtistCount: lanes.filter(item => item.blocks.length === 0).length,
pendingCount
}
},
summaryMap() {
return (this.data.daySummaries || []).reduce((map, item) => {
map[item.date] = item
return map
}, {})
},
appointmentsByDate(date) {
return (this.data.appointments || []).filter(item => resolveAppointmentDate(item) === date)
},
appointmentCountsByDate(date) {
const artistMap = (this.data.artists || []).reduce((map, artist) => {
map[String(artist.id)] = artist
return map
}, {})
const grouped = new Map()
this.appointmentsByDate(date).forEach((item, index) => {
const artist = artistMap[String(item.artistId)] || {}
const artistName = item.artistName || artist.name
const statusClass = completedOrCancelledClass(item.status)
const key = `${String(item.artistId || item.orderItemId)}-${statusClass || 'active'}`
const existing = grouped.get(key)
if (existing) {
grouped.set(key, { ...existing, count: existing.count + 1 })
} else {
grouped.set(key, {
key: `${key}-${index}`,
orderItemId: item.orderItemId,
artistId: item.artistId || item.orderItemId,
artistName,
shortName: artist.shortName || String(artistName || '?').slice(0, 1),
color: artist.color || '#B8B0A6',
count: 1,
status: item.status,
statusClass
})
}
})
return Array.from(grouped.values())
},
normalizeArtistCounts(counts) {
const colorMap = this.data.artists.reduce((map, artist) => {
map[artist.id] = artist
return map
}, {})
return (counts || []).map(count => {
const artist = colorMap[count.artistId] || {}
return {
...count,
key: `${String(count.artistId)}-${count.status || 'summary'}`,
color: count.color || artist.color || '#B8B0A6',
shortName: count.shortName || artist.shortName || '?',
count: Number(count.count || 0)
}
})
},
buildExpandedBlocks(artistCounts) {
return (artistCounts || []).reduce((blocks, count) => {
for (let index = 0; index < Number(count.count || 0); index += 1) {
blocks.push({
key: count.key ? `${count.key}-${index}` : `${count.artistId || count.shortName}-${index}`,
artistId: count.artistId,
color: count.color,
shortName: count.shortName,
statusClass: count.statusClass
})
}
return blocks
}, [])
},
buildRowBlocks(artistCounts) {
return (artistCounts || []).reduce((rows, count) => {
for (let index = 0; index < Number(count.count || 0); index += 1) {
rows.push({
key: count.key ? `${count.key}-row-${index}` : `${count.artistId || count.shortName}-row-${index}`,
artistId: count.artistId,
color: count.color,
shortName: count.shortName,
artistName: count.artistName || count.shortName,
statusClass: count.statusClass
})
}
return rows
}, [])
},
createAppointment() {
if (!this.data.canCreateAppointment) {
wx.showToast({ title: '美甲师账号只能查看预约', icon: 'none' })
return
}
wx.navigateTo({
url: buildAppointmentFormUrl(this.data.currentDateText, this.data.selectedArtistId)
})
},
createAppointmentFromEmptyDate() {
if (!this.data.pendingEmptyDate) {
wx.showToast({ title: '请选择预约日期', icon: 'none' })
return
}
if (!this.data.canCreateAppointment) {
wx.showToast({ title: '美甲师账号只能查看预约', icon: 'none' })
return
}
this.setData({ emptyDateActionVisible: false })
wx.navigateTo({
url: buildAppointmentFormUrl(this.data.pendingEmptyDate, this.data.selectedArtistId)
})
},
async saveEmptyDateSpecialDate() {
if (!this.data.pendingEmptyDate) {
wx.showToast({ title: '请选择特殊日期', icon: 'none' })
return
}
if (this.data.savingSpecialDate) {
return
}
const option = resolveSpecialDateType(this.data.pendingSpecialDateType)
const startTime = this.data.pendingSpecialDateStartTime
const endTime = this.data.pendingSpecialDateEndTime
if (option.requiresTime && (!startTime || !endTime || startTime >= endTime)) {
wx.showToast({ title: '请设置正确营业时间', icon: 'none' })
return
}
this.setData({ savingSpecialDate: true })
try {
await shopApi.saveScheduleException({
workDate: this.data.pendingEmptyDate,
exceptionType: option.value,
startTime: option.requiresTime ? startTime : null,
endTime: option.requiresTime ? endTime : null,
remark: '规划页快速设置'
})
markPlanningRefresh()
wx.showToast({ title: '特殊日期已保存', icon: 'success' })
this.closeEmptyDateAction()
await this.loadCalendar()
} catch (error) {
wx.showToast({ title: error.message || '特殊日期保存失败', icon: 'none' })
} finally {
this.setData({ savingSpecialDate: false })
}
},
openAppointment(event) {
wx.navigateTo({
url: `/pages/appointment-detail/index?id=${event.currentTarget.dataset.id}`
})
}
})