wms_mp_weixin/src/utils/identity-log.ts
2026-09-26 18:00:08 +08:00

85 lines
3.2 KiB
TypeScript
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.

/**
* 身份操作流水(**排障用,当前状态:关闭**)
*
* 为什么需要它:身份切换出问题时,只看一段响应无法判断「后端到底写了什么、什么时候写的、
* 前端拿到的 token 是哪一版」。这里把每次「小程序启动 / changeRole 请求 / changeRole 响应 /
* user.info 响应 / 身份校验」的关键字段追加成一条流水(带时间),
* **一次截图就能看到完整过程**,不用手工复制一堆 JSON。
*
* ## 开 / 关
* 把 `IDENTITY_LOG_ENABLED` 改成 `true` 即可启用:
* - store / App.vue 里的 `appendIdentityLog(...)` 调用**一直都在**(关闭时只是空转),无需改它们
* - 测试页会自动出现「身份操作流水」卡(同一个开关控制)
*
* 2026-09-26 首轮使用完毕(当时定位了后端 `user.changeRole` 写库正确但 token 用旧身份的缺陷,
* 后端已修复)⇒ 先关闭,不启用;以后再排查身份 / 菜单 / 权限类问题时再打开。
*
* 两个刻意的设计:
* 1. **单独存储**(`identity_log`),**不随 token 一起清**
* ⇒ 「退出登录 → 重新登录」以及「重进小程序」之后,仍然能看到切换前后的全过程
* 2. **只记关键字段**(身份 id / store / token 指纹),**绝不记完整 token**(凭证不进日志/截图)
*
* 清空入口:测试页「身份操作流水」卡的「清空流水」按钮,或开发者工具「清除数据缓存」。
*/
/** 总开关:`false` = 不记录、不展示(埋点调用保留,空转) */
export const IDENTITY_LOG_ENABLED = false
const KEY = 'identity_log'
/** 最多保留多少条(超出丢最旧的) */
const MAX = 60
export interface IdentityLogEntry {
/** 记录时间(本地时区,`HH:mm:ss`) */
at: string
/** 事件名,如 `changeRole 响应` */
event: string
/** 关键字段 */
detail: string
}
function nowText(): string {
const date = new Date()
const pad = (n: number): string => (n < 10 ? `0${n}` : String(n))
return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}
/** 追加一条流水(关闭时空转;任何失败静默:排障工具不能影响主流程) */
export function appendIdentityLog(event: string, detail = ''): void {
if (!IDENTITY_LOG_ENABLED) return
try {
const list = readIdentityLogRaw()
list.push({ at: nowText(), event, detail })
while (list.length > MAX) list.shift()
uni.setStorageSync(KEY, JSON.stringify(list))
} catch {
// ignore
}
}
function readIdentityLogRaw(): IdentityLogEntry[] {
try {
const raw = uni.getStorageSync(KEY)
if (typeof raw !== 'string' || !raw) return []
const parsed = JSON.parse(raw)
return Array.isArray(parsed) ? (parsed as IdentityLogEntry[]) : []
} catch {
return []
}
}
/** 读取流水(**最新在前**,便于直接渲染);关闭时返回空数组 */
export function readIdentityLog(): IdentityLogEntry[] {
if (!IDENTITY_LOG_ENABLED) return []
return readIdentityLogRaw().slice().reverse()
}
/** 清空流水(含关闭状态下清掉之前遗留的记录) */
export function clearIdentityLog(): void {
try {
uni.removeStorageSync(KEY)
} catch {
// ignore
}
}