602 lines
20 KiB
JavaScript
602 lines
20 KiB
JavaScript
const planningApi = require('../../api/planning')
|
|
const dateUtil = require('../../utils/date')
|
|
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')
|
|
const employeesApi = require('../../api/employees')
|
|
|
|
function canCreateAppointment() {
|
|
const app = getApp()
|
|
const userInfo = app.globalData.userInfo || {}
|
|
return Number(userInfo.type) !== 3
|
|
}
|
|
|
|
function resolveCalendarErrorMessage(error) {
|
|
return error && error.message ? error.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 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}`
|
|
}
|
|
|
|
Page({
|
|
data: {
|
|
viewMode: 'month',
|
|
viewModes: [
|
|
{ value: 'day', label: '日' },
|
|
{ value: 'week', label: '周' },
|
|
{ value: 'month', 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: [],
|
|
monthDays: [],
|
|
weekDays: [],
|
|
dayLanes: [],
|
|
hours: [],
|
|
timelineHeight: 720,
|
|
laneWidth: 720,
|
|
laneItemWidth: 240,
|
|
laneHeaderHeight: 54,
|
|
dayTotal: 0,
|
|
freeArtistCount: 0,
|
|
pendingCount: 0,
|
|
canCreateAppointment: true,
|
|
loading: false,
|
|
calendarError: '',
|
|
phoneBannerVisible: false,
|
|
profilePromptVisible: false,
|
|
profileSaving: false,
|
|
profileForm: { nickname: '', avatar: '' }
|
|
},
|
|
|
|
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()
|
|
}
|
|
this.refreshAccountPrompts()
|
|
},
|
|
|
|
async refreshAccountPrompts() {
|
|
let shouldShowProfilePrompt = false
|
|
try {
|
|
const profile = await profileCache.getProfile()
|
|
const session = auth.getSession()
|
|
getApp().setSession({ ...session, userInfo: { ...(session.userInfo || {}), ...profile } })
|
|
const today = dateUtil.formatDate(new Date())
|
|
const dismissed = wx.getStorageSync(auth.PHONE_BANNER_DISMISSED_KEY)
|
|
const missingNickname = !String(profile.nickname || '').trim() || String(profile.nickname).startsWith('微信用户')
|
|
const avatar = normalizeAvatar(profile.avatar)
|
|
const skipped = wx.getStorageSync(auth.PROFILE_PROMPT_SKIPPED_KEY) === '1'
|
|
shouldShowProfilePrompt = !skipped && (missingNickname || !avatar)
|
|
this.setData({
|
|
phoneBannerVisible: Number(profile.phoneVerified) !== 1 && dismissed !== today,
|
|
profilePromptVisible: false,
|
|
profileForm: { nickname: missingNickname ? '' : profile.nickname, avatar }
|
|
})
|
|
} catch (error) {
|
|
// 资料提醒失败不影响规划数据。
|
|
}
|
|
const navigatedToReview = await this.showEmployeeReviewNotice()
|
|
if (!navigatedToReview) {
|
|
this.setData({ profilePromptVisible: shouldShowProfilePrompt })
|
|
}
|
|
},
|
|
|
|
async showEmployeeReviewNotice() {
|
|
const app = getApp()
|
|
const userInfo = app.globalData.userInfo || {}
|
|
if (Number(userInfo.type) !== 2 || app.globalData.reviewNoticeShown) return false
|
|
let summary
|
|
try {
|
|
summary = await employeesApi.reviewSummary()
|
|
} catch (error) {
|
|
return false
|
|
}
|
|
if (!summary.noticeEnabled || Number(summary.pendingCount || 0) <= 0) return false
|
|
app.globalData.reviewNoticeShown = true
|
|
const result = await new Promise(resolve => {
|
|
wx.showModal({
|
|
title: '有员工申请待审核',
|
|
content: `当前有 ${summary.pendingCount} 条员工加入申请,是否立即处理?`,
|
|
cancelText: '稍后处理',
|
|
confirmText: '立即审核',
|
|
success: resolve,
|
|
fail: () => resolve({ confirm: false })
|
|
})
|
|
})
|
|
if (!result.confirm) return false
|
|
app.globalData.openEmployeeReview = true
|
|
wx.switchTab({ url: '/pages/employees/index' })
|
|
return true
|
|
},
|
|
|
|
openAccountSettings() { wx.navigateTo({ url: '/pages/account-settings/index' }) },
|
|
|
|
dismissPhoneBanner() {
|
|
wx.setStorageSync(auth.PHONE_BANNER_DISMISSED_KEY, dateUtil.formatDate(new Date()))
|
|
this.setData({ phoneBannerVisible: false })
|
|
},
|
|
|
|
onNicknameInput(event) { this.setData({ 'profileForm.nickname': event.detail.value }) },
|
|
|
|
async chooseWechatAvatar(event) {
|
|
const filePath = event.detail && event.detail.avatarUrl
|
|
if (!filePath) return
|
|
this.setData({ profileSaving: true })
|
|
try {
|
|
const avatar = await uploadProfileImage(filePath)
|
|
this.setData({ 'profileForm.avatar': avatar })
|
|
} catch (error) {
|
|
wx.showToast({ title: error.message || '头像上传失败', icon: 'none' })
|
|
} finally {
|
|
this.setData({ profileSaving: false })
|
|
}
|
|
},
|
|
|
|
skipProfilePrompt() {
|
|
wx.setStorageSync(auth.PROFILE_PROMPT_SKIPPED_KEY, '1')
|
|
this.setData({ profilePromptVisible: false })
|
|
},
|
|
|
|
async saveWechatProfile() {
|
|
const nickname = String(this.data.profileForm.nickname || '').trim()
|
|
if (!nickname || !this.data.profileForm.avatar) {
|
|
wx.showToast({ title: '请选择头像并填写昵称', icon: 'none' }); return
|
|
}
|
|
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) {
|
|
wx.showToast({ title: error.message || '资料保存失败', icon: 'none' })
|
|
} finally {
|
|
this.setData({ profileSaving: false })
|
|
}
|
|
},
|
|
|
|
switchView(event) {
|
|
this.setData({ viewMode: event.currentTarget.dataset.mode })
|
|
this.loadCalendar()
|
|
},
|
|
|
|
switchMonthDisplay(event) {
|
|
this.setData({ monthDisplayMode: event.currentTarget.dataset.mode })
|
|
this.prepareView()
|
|
},
|
|
|
|
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)
|
|
this.setData({
|
|
currentDate,
|
|
currentDateText: currentDate,
|
|
viewMode: this.data.viewMode === 'month' ? 'day' : this.data.viewMode
|
|
})
|
|
this.prepareView()
|
|
},
|
|
|
|
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()
|
|
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 })
|
|
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)
|
|
}).catch(error => {
|
|
if (requestId !== this._calendarRequestId) return
|
|
this.clearCalendarView()
|
|
this.setData({
|
|
calendarError: resolveCalendarErrorMessage(error),
|
|
selectedArtistId: '',
|
|
selectedArtistName: '全部员工'
|
|
})
|
|
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: [],
|
|
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) {
|
|
const snapshot = {
|
|
businessStartTime: (calendar.businessStartTime || '10:00').slice(0, 5),
|
|
businessEndTime: (calendar.businessEndTime || '22:00').slice(0, 5),
|
|
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)
|
|
})
|
|
},
|
|
|
|
prepareView() {
|
|
this.setData(this.buildViewState(this._calendarData))
|
|
},
|
|
|
|
buildViewState(calendar = {}) {
|
|
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)
|
|
const state = {
|
|
dateTitle: title,
|
|
rangeText: this.data.viewMode === 'month' ? '月视图' : this.data.viewMode === 'week' ? '周视图' : '日视图',
|
|
weekRange: `${formatMonthDay(range.start)} - ${formatMonthDay(range.end)}`,
|
|
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(calendar) {
|
|
const summaryMap = this.summaryMap(calendar)
|
|
const todayText = dateUtil.formatDate(new Date())
|
|
const artistTemplate = (calendar.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 artistCounts = this.normalizeArtistCounts(summary.artistCounts || artistTemplate, calendar)
|
|
return {
|
|
...day,
|
|
isPast: day.date < todayText,
|
|
totalCount: summary.totalCount || 0,
|
|
dayStatus: summary.dayStatus || 'free',
|
|
artistCounts,
|
|
expandedBlocks: this.data.monthDisplayMode === 'blocks' ? this.buildExpandedBlocks(artistCounts) : [],
|
|
rowBlocks: this.data.monthDisplayMode === 'rows' ? this.buildRowBlocks(artistCounts) : []
|
|
}
|
|
})
|
|
},
|
|
|
|
buildWeekDays(calendar) {
|
|
const start = dateUtil.startOfWeek(this.data.currentDateText)
|
|
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 || [], calendar).filter(count => count.count > 0)
|
|
return {
|
|
date,
|
|
weekName: `周${label}`,
|
|
day: target.getDate(),
|
|
totalCount: summary.totalCount || 0,
|
|
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(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 = []
|
|
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
|
|
? (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))
|
|
.map(item => {
|
|
const itemStart = resolveAppointmentStartMinute(item)
|
|
return {
|
|
...item,
|
|
top: Math.max(0, itemStart - startMinute) + laneHeaderHeight,
|
|
height: Math.max(64, item.durationMinutes || 60),
|
|
timeText: resolveAppointmentTimeText(item)
|
|
}
|
|
})
|
|
return { ...artist, blocks }
|
|
})
|
|
const pendingCount = dayAppointments.filter(item => item.status === 0).length
|
|
return {
|
|
dayLanes: lanes,
|
|
hours,
|
|
timelineHeight: timelineHeight + laneHeaderHeight,
|
|
laneHeaderHeight,
|
|
laneItemWidth: 248,
|
|
laneWidth: Math.max(720, lanes.length * 248),
|
|
dayTotal: dayAppointments.length,
|
|
freeArtistCount: lanes.filter(item => item.blocks.length === 0).length,
|
|
pendingCount
|
|
}
|
|
},
|
|
|
|
summaryMap(calendar) {
|
|
return (calendar.daySummaries || []).reduce((map, item) => {
|
|
map[item.date] = item
|
|
return map
|
|
}, {})
|
|
},
|
|
|
|
normalizeArtistCounts(counts, calendar) {
|
|
const colorMap = (calendar.artists || []).reduce((map, artist) => {
|
|
map[artist.id] = artist
|
|
return map
|
|
}, {})
|
|
return (counts || []).map(count => {
|
|
const artist = colorMap[count.artistId] || {}
|
|
return {
|
|
...count,
|
|
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.artistId || count.shortName}-${index}`,
|
|
artistId: count.artistId,
|
|
color: count.color,
|
|
shortName: count.shortName
|
|
})
|
|
}
|
|
return blocks
|
|
}, [])
|
|
},
|
|
|
|
buildRowBlocks(artistCounts) {
|
|
return (artistCounts || []).reduce((rows, count) => {
|
|
for (let index = 0; index < Number(count.count || 0); index += 1) {
|
|
rows.push({
|
|
key: `${count.artistId || count.shortName}-row-${index}`,
|
|
artistId: count.artistId,
|
|
color: count.color,
|
|
shortName: count.shortName,
|
|
artistName: count.artistName || count.shortName
|
|
})
|
|
}
|
|
return rows
|
|
}, [])
|
|
},
|
|
|
|
createAppointment() {
|
|
if (!this.data.canCreateAppointment) {
|
|
wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' })
|
|
return
|
|
}
|
|
wx.navigateTo({
|
|
url: `/pages/appointment-form/index?date=${this.data.currentDateText}&artistId=${this.data.selectedArtistId || ''}`
|
|
})
|
|
},
|
|
|
|
openAppointment(event) {
|
|
wx.navigateTo({
|
|
url: `/pages/appointment-detail/index?id=${event.currentTarget.dataset.id}`
|
|
})
|
|
},
|
|
|
|
stopTap() {
|
|
},
|
|
|
|
async quickUpdateStatus(event) {
|
|
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))
|
|
wx.showToast({ title: '预约已确认', icon: 'success' })
|
|
this.loadCalendar()
|
|
} catch (error) {
|
|
wx.showToast({ title: error.message || '预约状态更新失败', icon: 'none' })
|
|
}
|
|
},
|
|
|
|
quickTransfer(event) {
|
|
wx.navigateTo({ url: `/pages/artist-transfer/index?id=${event.currentTarget.dataset.id}` })
|
|
},
|
|
|
|
quickCancel(event) {
|
|
const appointment = (this._calendarData && this._calendarData.appointments || []).find(item => String(item.orderItemId) === String(event.currentTarget.dataset.id))
|
|
if (!appointment) return
|
|
wx.showModal({
|
|
title: '取消预约',
|
|
content: '确定取消这条预约吗?',
|
|
success: result => {
|
|
if (result.confirm) {
|
|
this.updateAppointmentStatus(appointment.orderId, 3)
|
|
}
|
|
}
|
|
})
|
|
},
|
|
|
|
async updateAppointmentStatus(orderId, status) {
|
|
try {
|
|
await planningApi.updateStatus(orderId, status)
|
|
wx.showToast({ title: '预约已取消', icon: 'success' })
|
|
this.loadCalendar()
|
|
} catch (error) {
|
|
wx.showToast({ title: error.message || '预约取消失败', icon: 'none' })
|
|
}
|
|
}
|
|
})
|