Files
JayuCloud/WeChatProgram/admin/pages/system-messages/index.js
T

423 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Purpose: messageApi wraps admin system-message endpoints for list, publish, revoke, and target options.
* Usage: call these methods from page event handlers instead of assembling backend URLs in the view layer.
*/
const messageApi = require('../../api/system-message')
/**
* Purpose: navigation handles custom navigation-bar back behavior.
* Usage: call goBack when returning to the management menu.
*/
const navigation = require('../../utils/navigation')
/**
* Purpose: permission checks button-level rights for create and revoke actions.
* Usage: pass stored permission codes into hasPermission before rendering or running guarded actions.
*/
const permission = require('../../utils/permission')
/**
* Purpose: auth exposes the current admin permission list stored after login.
* Usage: read user info and permissions when deciding which mobile controls are available.
*/
const auth = require('../../utils/auth')
/**
* Purpose: format converts backend times into mini-program friendly text.
* Usage: call formatDateTime before assigning message rows to data.list.
*/
const format = require('../../utils/format')
/**
* Purpose: actionGuard prevents duplicate publish and revoke submissions from rapid taps.
* Usage: wrap create and revoke requests with actionGuard.run.
*/
const actionGuard = require('../../utils/action-guard')
/**
* Purpose: TARGET_TYPE_OPTIONS defines publish target scopes supported by the backend contract.
* Usage: render it as chips and submit the selected value as targetType.
*/
const TARGET_TYPE_OPTIONS = [
{ label: '全平台', value: 'PLATFORM_ALL' },
{ label: '指定店铺', value: 'SELECTED_SHOPS' },
{ label: '指定用户', value: 'SELECTED_USERS' }
]
/**
* Purpose: BUSINESS_TYPE_OPTIONS lists common business navigation types used by order review and artist-change messages.
* Usage: render it as chips and store the selected value in the publish form.
*/
const BUSINESS_TYPE_OPTIONS = [
{ label: '无', value: '' },
{ label: '订单', value: 'ORDER' },
{ label: '评价提醒', value: 'ORDER_ARTIST_REVIEW' },
{ label: '改派申请', value: 'ORDER_ARTIST_CHANGE' }
]
/**
* Purpose: initialForm returns a clean publish form with popup enabled by default.
* Usage: call it when opening the form and after successful publish.
*/
function initialForm() {
return {
title: '',
content: '',
targetType: 'PLATFORM_ALL',
targetId: '',
popupEnabled: true,
businessType: '',
businessId: '',
actionPath: ''
}
}
Page({
/**
* Purpose: data stores system-message list, publish form state, permissions, and picker options.
* Usage: WXML binds these fields and event handlers update them through setData.
*/
data: {
/**
* Purpose: loading shows whether the message list is being refreshed.
* Usage: bind it to page loading lines and refresh controls.
*/
loading: false,
/**
* Purpose: submitting shows whether publish or revoke is currently running.
* Usage: disable action buttons while true.
*/
submitting: false,
/**
* Purpose: list contains formatted system messages visible to the current admin scope.
* Usage: render it in WXML list cards.
*/
list: [],
/**
* Purpose: targetOptions stores backend-provided shops and users for scoped publishing.
* Usage: resolve targetId names and validate selected target choices.
*/
targetOptions: { shops: [], users: [] },
/**
* Purpose: formVisible controls whether the mobile publish panel is shown.
* Usage: toggle it from header and cancel buttons.
*/
formVisible: false,
/**
* Purpose: form holds publish fields sent to createMessage after validation.
* Usage: update individual properties from inputs and chips.
*/
form: initialForm(),
/**
* Purpose: targetTypeOptions renders publish target scope choices.
* Usage: iterate it in WXML chips.
*/
targetTypeOptions: TARGET_TYPE_OPTIONS,
/**
* Purpose: businessTypeOptions renders common business navigation choices.
* Usage: iterate it in WXML chips.
*/
businessTypeOptions: BUSINESS_TYPE_OPTIONS,
/**
* Purpose: canCreate controls whether the publish action is visible for the current permission set.
* Usage: derive it from message:create permission during onLoad.
*/
canCreate: false,
/**
* Purpose: canRevoke controls whether revoke buttons are visible for the current permission set.
* Usage: derive it from message:delete permission during onLoad.
*/
canRevoke: false
},
/**
* Purpose: onLoad initializes permission flags and fetches message list data.
* Usage: mini-program runtime calls it when the operator opens the system-message page.
*/
onLoad() {
const userInfo = auth.getStoredUserInfo() || {}
const codes = userInfo.permissions || []
this.setData({
canCreate: permission.hasPermission(codes, 'message:create'),
canRevoke: permission.hasPermission(codes, 'message:delete')
})
this.loadMessages()
},
/**
* Purpose: onPullDownRefresh reloads system messages and target options.
* Usage: mini-program runtime calls it after a manual refresh gesture.
*/
async onPullDownRefresh() {
await this.loadMessages()
wx.stopPullDownRefresh()
},
/**
* Purpose: loadMessages refreshes list data and target options for the publish form.
* Usage: call it on page entry, pull refresh, publish success, and revoke success.
*/
async loadMessages() {
this.setData({ loading: true })
try {
const [messages, targetOptions] = await Promise.all([
messageApi.listMessages(),
this.data.canCreate ? messageApi.getTargetOptions() : Promise.resolve(this.data.targetOptions)
])
this.setData({
list: (Array.isArray(messages) ? messages : []).map(item => this.formatMessage(item)),
targetOptions: targetOptions || { shops: [], users: [] }
})
} catch (error) {
wx.showToast({
title: error.message || '系统消息加载失败',
icon: 'none'
})
} finally {
this.setData({ loading: false })
}
},
/**
* Purpose: formatMessage normalizes backend message metadata for compact card display.
* Usage: call it on every list item before assigning to data.list.
*/
formatMessage(item) {
return {
...item,
displayTime: format.formatDateTime(item.publishTime || item.createTime),
statusText: Number(item.status) === 1 ? '已发布' : '已撤回',
popupText: Number(item.popupEnabled) === 1 ? '弹窗' : '不弹窗',
businessText: item.businessType || '无业务跳转',
actionText: item.actionPath || (item.businessId ? `业务 ID:${item.businessId}` : '无')
}
},
/**
* Purpose: handleShowForm opens a clean publish panel for authorized operators.
* Usage: bind it to the publish button.
*/
handleShowForm() {
this.setData({
formVisible: true,
form: initialForm()
})
},
/**
* Purpose: handleHideForm closes the publish panel without submitting.
* Usage: bind it to cancel controls.
*/
handleHideForm() {
this.setData({ formVisible: false })
},
/**
* Purpose: patchForm updates one field in the publish form.
* Usage: call it from input and chip handlers with a partial form object.
*/
patchForm(patch) {
this.setData({
form: {
...this.data.form,
...patch
}
})
},
/**
* Purpose: handleTitleInput stores the publish title input value.
* Usage: bind it to the title input.
*/
handleTitleInput(event) {
this.patchForm({ title: event.detail.value })
},
/**
* Purpose: handleContentInput stores the publish content textarea value.
* Usage: bind it to the content textarea.
*/
handleContentInput(event) {
this.patchForm({ content: event.detail.value })
},
/**
* Purpose: handleTargetIdInput stores selected shop or user id values.
* Usage: bind it to the target id input when targetType is SHOP or USER.
*/
handleTargetIdInput(event) {
this.patchForm({ targetId: event.detail.value })
},
/**
* Purpose: handleBusinessIdInput stores the optional business id used for message navigation.
* Usage: bind it to the business id input.
*/
handleBusinessIdInput(event) {
this.patchForm({ businessId: event.detail.value })
},
/**
* Purpose: handleActionPathInput stores the optional frontend action path used by popup and list taps.
* Usage: bind it to the action path input.
*/
handleActionPathInput(event) {
this.patchForm({ actionPath: event.detail.value })
},
/**
* Purpose: handleTargetTypeChange changes publish target scope and clears stale target ids.
* Usage: bind it to target type chips with data-value.
*/
handleTargetTypeChange(event) {
this.patchForm({
targetType: event.currentTarget.dataset.value,
targetId: ''
})
},
/**
* Purpose: handleBusinessTypeChange changes the optional business navigation type.
* Usage: bind it to business type chips with data-value.
*/
handleBusinessTypeChange(event) {
this.patchForm({ businessType: event.currentTarget.dataset.value || '' })
},
/**
* Purpose: handlePopupToggle flips whether recipients should see a one-time popup.
* Usage: bind it to the popup switch control.
*/
handlePopupToggle(event) {
this.patchForm({ popupEnabled: Boolean(event.detail.value) })
},
/**
* Purpose: buildPublishPayload validates the form and converts it to backend DTO shape.
* Usage: call it inside handlePublish before createMessage; it returns null after showing validation errors.
*/
buildPublishPayload() {
const form = this.data.form
const title = String(form.title || '').trim()
const content = String(form.content || '').trim()
if (!title || !content) {
wx.showToast({
title: '请填写标题和内容',
icon: 'none'
})
return null
}
const payload = {
title,
content,
targetType: form.targetType,
popupEnabled: form.popupEnabled ? 1 : 0,
businessType: form.businessType || undefined,
businessId: form.businessId ? Number(form.businessId) : undefined,
actionPath: String(form.actionPath || '').trim() || undefined
}
if (form.targetType === 'SELECTED_SHOPS') {
if (!form.targetId) {
wx.showToast({ title: '请输入店铺 ID', icon: 'none' })
return null
}
payload.shopIds = [Number(form.targetId)]
}
if (form.targetType === 'SELECTED_USERS') {
if (!form.targetId) {
wx.showToast({ title: '请输入用户 ID', icon: 'none' })
return null
}
payload.userIds = [Number(form.targetId)]
}
return payload
},
/**
* Purpose: handlePublish submits the publish form with duplicate-tap protection.
* Usage: bind it to the primary publish button.
*/
async handlePublish() {
const payload = this.buildPublishPayload()
if (!payload) {
return
}
try {
await actionGuard.run(this, 'system-message:publish', async () => {
this.setData({ submitting: true })
await messageApi.createMessage(payload)
wx.showToast({
title: '消息已发布',
icon: 'none'
})
this.setData({
formVisible: false,
form: initialForm()
})
await this.loadMessages()
}, {
message: '消息发布中,请勿重复提交'
})
} catch (error) {
if (actionGuard.isGuardError(error)) {
return
}
wx.showToast({
title: error.message || '消息发布失败',
icon: 'none'
})
} finally {
this.setData({ submitting: false })
}
},
/**
* Purpose: handleRevoke revokes one message after operator confirmation.
* Usage: bind it to list-row revoke buttons with data-id.
*/
async handleRevoke(event) {
const id = event.currentTarget.dataset.id
if (!id) {
return
}
const confirmed = await new Promise(resolve => {
wx.showModal({
title: '撤回消息',
content: '确认撤回这条系统消息吗?',
confirmText: '撤回',
success: res => resolve(Boolean(res.confirm))
})
})
if (!confirmed) {
return
}
try {
await actionGuard.run(this, `system-message:revoke:${id}`, async () => {
await messageApi.revokeMessage(id)
wx.showToast({
title: '已撤回',
icon: 'none'
})
await this.loadMessages()
}, {
message: '消息撤回中,请勿重复操作'
})
} catch (error) {
if (actionGuard.isGuardError(error)) {
return
}
wx.showToast({
title: error.message || '撤回失败',
icon: 'none'
})
}
},
/**
* Purpose: handleBack returns to the management menu.
* Usage: bind it to the custom navigation bar back event.
*/
handleBack() {
navigation.goBack('/pages/manage/index')
}
})