/** * 侧栏「工单与任务」菜单计数徽标(2026-11-17)。 * * 需求:菜单项右侧补数字(待分派几张、我的待办几张、待回执几张…),让人不进页面就知道有没有活。 * * 口径纪律(与 `work-order-counts.ts` 同一套): * - 每个数字都来自服务端 `total` 的 **count-only** 查询(`page=1&page_size=1`), * ⛔ 用当页行数、⛔ 用本地列表缓存推算; * - 取不到(失败/该角色无此口)就**不显示**,⛔ 折成 0(0 是「确实没有」,查不到不是没有); * - 只有运营侧五个角色有工单菜单;客户/合伙人/运营商一个都不发请求。 * * 性能:模块级单例缓存 + TTL。桌面与移动两个侧栏同时挂载时只发一轮请求; * 路由切换只在缓存过期时重取(超过 {@link STALE_MS}),⛔ 每次点击都打一遍计数口。 */ import { useSyncExternalStore } from "react"; import * as ticketApi from "./api/ticket.ts"; import type { DemoIdentity } from "./demo-identities.ts"; export type NavBadges = Partial>; /** 徽标键=菜单 id(与 `access/navigation.ts` 对齐,只列本节用到的)。 */ const KEY_ALL = "workOrders"; const KEY_MINE = "workOrderMine"; const KEY_QUEUE = "workOrderQueue"; const KEY_DELIVERY = "workOrderDelivery"; /** 缓存有效期:身份变化立即重取;同一身份的路由切换超过该间隔才重取 * (避免连点菜单把计数口当成心跳)。 */ const STALE_MS = 15_000; const OPS_SIDE = new Set(["admin", "regAdmin", "teamLead", "ops", "worker"]); const MEMBER_ROLES = new Set(["ops", "worker"]); /** 与「我的待办」页同口径:在办 + 待确认(⛔ 把已办结/已作废算进来)。 */ const MINE_STATUSES = ["unassigned", "pending", "processing", "completed", "rejected"]; /** 与「交付与回执」页同口径:待回执 + 已驳回。 */ const DELIVERY_STATUSES = ["completed", "rejected"]; let snapshot: NavBadges = {}; let signature = ""; let fetchedAt = 0; let generation = 0; let inflightSignature = ""; const listeners = new Set<() => void>(); function emit() { for (const listener of listeners) listener(); } function signatureOf(identity: DemoIdentity | null): string { if (!identity || !OPS_SIDE.has(identity.role)) return ""; // 团队主与运维成员的可见范围随团队/成员变化,签名带上它们,换身份即重取。 return [identity.role, identity.maintenanceTeamId ?? "", identity.memberId ?? "", identity.operationsTeamId ?? ""].join("|"); } /** 按身份决定要问哪几个数:没有那个菜单就不发那个请求(服务端对无权限角色直接拒)。 */ function planFor(identity: DemoIdentity): { key: string; run: () => Promise }[] { const plan: { key: string; run: () => Promise }[] = [ { key: KEY_ALL, run: () => ticketApi.ticketList({ page: 1, page_size: 1 }).then((r) => r.total) }, // 「我的待办」运营侧五档都有(2026-11-17 扩到运营主/子账号与团队主), // 一律带 `assignee=me`:可见范围先由服务端收窄,再取交「本人名下」,与页面同一条口径。 { key: KEY_MINE, run: () => ticketApi.ticketList({ statuses: MINE_STATUSES, assignee: "me", page: 1, page_size: 1 }).then((r) => r.total), }, ]; if (!MEMBER_ROLES.has(identity.role)) { const teamId = identity.role === "teamLead" ? identity.maintenanceTeamId : undefined; plan.push({ key: KEY_QUEUE, run: () => ticketApi.ticketPendingQueue({ assign_team_id: teamId, page: 1, page_size: 1, include_candidates: false }).then((r) => r.total), }); plan.push({ key: KEY_DELIVERY, run: () => ticketApi.ticketList({ statuses: DELIVERY_STATUSES, page: 1, page_size: 1 }).then((r) => r.total) }); } return plan; } async function load(identity: DemoIdentity, run: number) { const plan = planFor(identity); const settled = await Promise.allSettled(plan.map((item) => item.run())); // 期间换了身份:本轮结果作废(否则会把上一个身份的张数挂到新菜单上)。 if (run !== generation) return; const next: NavBadges = {}; settled.forEach((result, index) => { // 失败即缺键:渲染层据此不显示,⛔ 补 0 让人以为「确实没有」。 if (result.status === "fulfilled" && Number.isFinite(result.value)) next[plan[index].key] = result.value; }); fetchedAt = Date.now(); snapshot = next; emit(); } /** 由侧栏调用:身份变化立即取;路由变化仅在缓存过期时重取。 */ export function ensureNavBadges(identity: DemoIdentity | null) { const nextSignature = signatureOf(identity); if (!identity || !nextSignature) { if (signature !== "" || Object.keys(snapshot).length > 0) { signature = ""; snapshot = {}; fetchedAt = Date.now(); generation += 1; emit(); } return; } const sameIdentity = signature === nextSignature; if (sameIdentity && Date.now() - fetchedAt < STALE_MS) return; if (!sameIdentity) { signature = nextSignature; // 身份已变:丢弃旧身份在途结果,并允许立刻发新的一轮。 generation += 1; } else if (inflightSignature === nextSignature) { return; } const run = generation; inflightSignature = nextSignature; void load(identity, run) .catch(() => { /* 失败保持旧值或缺键,下次路由再试 */ }) .finally(() => { if (inflightSignature === nextSignature) inflightSignature = ""; }); } export function subscribeNavBadges(listener: () => void) { listeners.add(listener); return () => { listeners.delete(listener); }; } export function getNavBadges(): NavBadges { return snapshot; } /** 侧栏订阅用:返回 `{ 菜单id: 张数 }`,缺键=取不到或该角色没有这个口。 */ export function useNavBadges() { return useSyncExternalStore(subscribeNavBadges, getNavBadges, () => snapshot); }