/** * 首页模块角标中心。 * 第一层(registry)只决定模块是否可见;这里只负责给可见模块补 badgeKey 对应的待办数量。 * 计数口径以后端 /mobile/badges 为准:前端只传模块 id,权限/available_roles 由后端重算。 * 原则:只有接口成功或面板明确返回 count 才更新;失败/缺键时保留上一次成功值,避免红点被误清。 */ const { getSession } = require('./auth'); const { fetchMobileBadges } = require('./request'); let refreshRunId = 0; function badgeTargetsFromModules(modules) { const byKey = new Map(); (modules || []).forEach((mod) => { const badgeKey = mod && mod.badgeKey; const id = String((mod && mod.id) || '').trim(); if (!badgeKey || !id || byKey.has(badgeKey)) return; byKey.set(badgeKey, { id, badgeKey }); }); return [...byKey.values()]; } function applyBadgePatch(page, patch) { if (!page || typeof page.setData !== 'function') return 0; const keys = Object.keys(patch || {}); if (!keys.length) return 0; page.setData(patch, () => { if (typeof page.refreshMenuModules === 'function') page.refreshMenuModules(); }); return keys.length; } /** 面板已经拿到最新行数据时,可直接回传 count,避免再发一次统计请求 */ function setBadgeCount(page, badgeKey, count) { const key = String(badgeKey || '').trim(); if (!key) return 0; const value = Number(count); return applyBadgePatch(page, { [key]: Number.isFinite(value) && value > 0 ? Math.floor(value) : 0, }); } async function refreshBadges(page, modules) { if (!page || typeof page.setData !== 'function') return 0; const session = getSession(); if (!session?.access_token) return 0; const targets = badgeTargetsFromModules(modules); if (!targets.length) return 0; const runId = ++refreshRunId; try { const result = await fetchMobileBadges(targets.map((target) => target.id)); if (runId !== refreshRunId) return 0; const data = (result && result.data) || {}; const patch = {}; targets.forEach((target) => { if (data[target.badgeKey] != null) { patch[target.badgeKey] = Number(data[target.badgeKey]) || 0; } }); return applyBadgePatch(page, patch); } catch { // 失败保留旧值:403/网络抖动/服务异常都不能把已有红点抹成 0 return 0; } } function refreshBadgeForModule(page, mod) { if (!mod || !mod.badgeKey) return Promise.resolve(0); return refreshBadges(page, [mod]); } module.exports = { refreshBadges, refreshBadgeForModule, setBadgeCount, };