Files
wxapp_companion/utils/role.js
T
lik d70d9703ad feat(order): 订单池接单与共享入口,实习陪诊师只读
列表展示未分配/共享给我标记并新增接单按钮;详情页支持接单与共享给在职陪诊师,实习仅可查看脱敏信息。
2026-11-10 12:28:06 +08:00

249 lines
7.6 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.
// utils/role.js
// 管理端角色:admin(管理员)/ attendant(在职陪诊员)/ none(无可用身份)
//
// - 管理员身份按登录响应的 apps 判定,与 api/health/utils/permissions.js 同口径
// (wxapp-escort-admin / web-escort-admin 任一含 admin 即管理员)
// - 陪诊员身份以员工档案为准(GET /health/employee/me),不能用 app role 判断,
// 普通账号首次登录管理端时 user 服务会写入 role: ["user"]
const API = require('./api.js')
const ADMIN_APP_IDS = ['wxapp-escort-admin', 'web-escort-admin']
let cachedRole = null
// 缓存是否来自一次成功的解析:ensureRole 在接口异常时会把 none 写进缓存,
// 守卫不能把这种"失败"当成"确实无身份"
let cachedRoleOk = false
let pending = null
let pendingSafe = null
// 陪诊师阶段/等级快照:仅用于展示身份文案与实习只读提示,不参与权限判定
let cachedAttendant = null
const GRADE_LABELS = { bronze: '青铜', silver: '白银', gold: '黄金', diamond: '钻石' }
/**
* 阶段/等级归一化:后端已归一化,这里兼容旧接口与缺字段的情况
* @param {Object|null} employee 员工档案
* @returns {{stage: string, grade: string, star: number, canAcceptOrder: boolean, text: string}}
*/
function normalizeAttendant(employee) {
const info = (employee && employee.attendantInfo) || {}
const stage = info.stage === 'intern' ? 'intern' : 'certified'
const grade = GRADE_LABELS[info.grade] ? info.grade : 'bronze'
const rawStar = Number(info.star)
const star = grade === 'diamond' && isFinite(rawStar)
? Math.max(0, Math.min(5, Math.floor(rawStar)))
: 0
const gradeText = `${GRADE_LABELS[grade]}${grade === 'diamond' && star ? ' ' + '★'.repeat(star) : ''}`
return {
stage,
grade,
star,
canAcceptOrder: stage === 'certified',
text: stage === 'intern' ? '实习陪诊师' : `正式陪诊师 · ${gradeText}`
}
}
function rolesOf(entry) {
if (!entry) return []
if (Array.isArray(entry.roles)) return entry.roles
if (Array.isArray(entry.role)) return entry.role
return entry.role ? [entry.role] : []
}
/**
* 管理员判定:与后端 isAdmin 保持同一口径
* @param {Object} user 登录响应里的用户
* @returns {boolean}
*/
function isAdminUser(user) {
if (!user) return false
if (Array.isArray(user.apps)) {
return user.apps.some((m) =>
ADMIN_APP_IDS.indexOf(m && m.appId) > -1 &&
m.status !== 'disabled' &&
Array.isArray(m.roles) &&
m.roles.indexOf('admin') > -1
)
}
return ADMIN_APP_IDS.some((appId) => {
const entry = user.app && user.app[appId]
if (!entry) return false
if (rolesOf(entry).indexOf('admin') > -1) return true
// 历史兼容:role 缺失按管理员处理(后端同样兼容并告警)
return entry.role === undefined
})
}
function applyAppRole(role) {
try {
const app = getApp()
if (app && app.globalData) app.globalData.role = role
} catch (e) {
// 页面未初始化时忽略
}
}
/**
* 带失败标记的角色解析
*
* 与 ensureRole 的区别只在「解析不出来」时:ensureRole 把异常吞成 none,
* 页面守卫不能据此跳转,否则用户服务抖动一下就会把在职陪诊师弹到申请页。
*
* @returns {Promise<{ok: boolean, role: "admin"|"attendant"|"none"}>}
*/
async function resolveRoleDetail() {
let user = null
try {
const app = getApp()
if (app && app.ensureLogin) user = await app.ensureLogin()
else user = app && app.globalData ? app.globalData.user : null
} catch (e) {
return { ok: false, role: 'none' }
}
if (!user) return { ok: false, role: 'none' }
if (isAdminUser(user)) {
cachedAttendant = null
return { ok: true, role: 'admin' }
}
try {
const res = await API.employee.getMe()
if (!res || res.code !== 0) return { ok: false, role: 'none' }
const employee = res.data ? res.data.employee : null
// 实习与正式都算陪诊师:实习能进主页面,只是不能接单
if (employee && employee.status === 'active' && employee.role === 'attendant') {
cachedAttendant = normalizeAttendant(employee)
return { ok: true, role: 'attendant', attendant: cachedAttendant }
}
cachedAttendant = null
return { ok: true, role: 'none' }
} catch (e) {
// 员工接口异常:解析失败,不据此判定为无身份
return { ok: false, role: 'none' }
}
}
/**
* 解析并缓存当前角色;并发调用复用同一次请求
* @param {boolean} force 强制重新解析
* @returns {Promise<"admin"|"attendant"|"none">}
*/
function ensureRole(force) {
// cachedRoleOk=false 表示缓存来自一次失败的解析,不作为命中,下次重新解析
if (!force && cachedRole && cachedRoleOk) return Promise.resolve(cachedRole)
if (!force && pending) return pending
pending = resolveRoleDetail()
.then((detail) => {
cachedRole = detail.role
cachedRoleOk = detail.ok
applyAppRole(detail.role)
return detail.role
})
.finally(() => {
pending = null
})
return pending
}
/**
* 带失败标记的角色解析(守卫专用)
*
* 与 ensureRole 的区别:ok=false 表示「没解析出来」,调用方不能据此做跳转。
* 解析成功时同样写入缓存,后续 ensureRole 可直接复用。
*
* @param {boolean} [force] 强制重新解析
* @returns {Promise<{ok: boolean, role: "admin"|"attendant"|"none"}>}
*/
function ensureRoleSafe(force) {
if (!force && cachedRole && cachedRoleOk) {
return Promise.resolve({ ok: true, role: cachedRole, attendant: cachedAttendant })
}
if (!force && pendingSafe) return pendingSafe
pendingSafe = resolveRoleDetail()
.then((detail) => {
// 解析失败不覆盖已有缓存,守卫下一次仍有机会拿到真实身份
if (detail.ok) {
cachedRole = detail.role
cachedRoleOk = true
applyAppRole(detail.role)
}
return detail
})
.finally(() => {
pendingSafe = null
})
return pendingSafe
}
function getRoleSync() {
return cachedRole
}
// 陪诊师阶段/等级快照(仅展示用),需先调用 ensureRole/ensureRoleSafe
function getAttendantSync() {
return cachedAttendant
}
/**
* 退出登录 / 清除缓存后重置,避免沿用上一个账号的角色
*/
function resetRole() {
cachedRole = null
cachedRoleOk = false
pending = null
pendingSafe = null
cachedAttendant = null
applyAppRole(null)
}
function emptyPage() {
return { code: 0, data: { records: [], total: 0, counts: {} }, msg: '查询成功' }
}
/**
* 按角色查询订单列表:陪诊员走 /attendant,管理员走全量列表
* @param {Object} params 查询参数
* @returns {Promise<Object>}
*/
async function queryOrders(params) {
const role = await ensureRole()
if (role === 'attendant') return API.escort.getAttendantRecords(params)
if (role === 'admin') return API.escort.getAllRecords(params)
// 无身份时不打管理接口,避免必然的 403
return emptyPage()
}
/**
* 页面级守卫:非管理员提示后返回
* @param {string} [message]
* @returns {Promise<boolean>} 是否有权限继续
*/
async function guardAdminPage(message) {
const role = await ensureRole()
if (role === 'admin') return true
wx.showToast({ title: message || '仅管理员可访问', icon: 'none' })
setTimeout(() => {
wx.navigateBack({
fail: () => wx.switchTab({ url: '/pages/home/index' })
})
}, 600)
return false
}
module.exports = {
isAdminUser,
ensureRole,
ensureRoleSafe,
getRoleSync,
getAttendantSync,
resetRole,
queryOrders,
guardAdminPage
}