adapter.ts 7.21 KB
/**
 * 后端权限数据 → 前端标准化权限点集合 的【适配器】。
 *
 * 当前后端契约未定,这里实现几种常见形态;将来后端返回格式变化,
 * 只需改本文件(或新增 normalizeXxx 并切换调用),上层 PermButton / canPoint 不受影响。
 */
import type { PermissionMatrix, ResourceKey, RoleKey, PermissionState } from '../model';
import type { MenuNode } from '../../api/modules/menu';

/**
 * 权限码归一(适配器)。
 *
 * 后端下发的权限码已是冒号分隔(如 store:list:view),且资源命名与前端一致
 * (store:list / system:user / store:import / store:approve / system:role),
 * 前端直接以后端格式为唯一真源,不再做「冒号→点号」或命名转换。
 * 故此处原样透传:toFrontendPoint(x) === x。
 */
function toFrontendPoint(code: string): string {
  return code;
}

/* ---------------- 菜单树:后端 /system/menu/tree/current → 前端菜单结构 ---------------- */

/** 前端菜单项(path/label/icon 供渲染,resource 供面包屑等派生用途) */
export interface MenuItemDef {
  path: string;
  label: string;
  /** 图标名(后端下发,如 ShopOutlined);为 null 时由渲染层兜底默认图标 */
  icon: string | null;
  resource?: ResourceKey;
}
export interface MenuGroupDef {
  group: string;
  children: MenuItemDef[];
  /**
   * 一级菜单(产品分组节点)自己的图标名,取自后端 nodeType=1 的 node.icon。
   * 为 null/未登记时由渲染层回落「首个子项图标」——那会让一级图标跟着二级排序变,
   * 所以给一级菜单定图标请在后端节点上登记,别指望子项。
   */
  icon?: string | null;
  /**
   * true:不渲染分组标题,children 直接平铺为该层级的菜单项。
   * 用于「工作台」这类只有一个入口的分组——挂一个独占一行的标题纯属噪音。
   * 后端菜单树不会下发该字段,仅由前端固定组与兜底 menu.json 标注意图。
   */
  hideTitle?: boolean;
}

/**
 * 菜单的 path 与 icon 现在由后端 /system/menu/tree/current 直接下发
 * (node.route / node.icon),前端不再维护 permCode → path/icon 的映射表。
 * 后端在菜单树里登记 route,前端无需改动即可渲染对应页面菜单。
 */

/**
 * 后端菜单树 → 前端菜单分组结构。
 *
 * 规则:
 *  - 只取 nodeType 1(分组)下的 nodeType 2(页面);nodeType 3 是按钮操作点,不进菜单。
 *  - status !== 1(停用)的节点丢弃。
 *  - path 与 icon 直接取自后端下发的 node.route / node.icon,前端不再做映射。
 *    一级(分组)图标取 nodeType=1 节点自己的 icon,与二级同用一套图标名。
 *  - 菜单可见性完全由后端 /current 决定:后端已按当前登录角色装配好菜单树,前端原样渲染,
 *    不再拿登录返回的 permCodes 做交集(双保险)。曾因两个接口口径不一致,树里有页面但
 *    permCodes 缺对应 :view 码,页面被这里静默丢弃、整组连标题都不渲染且零日志。
 *  - node.route 缺失 → 跳过并告警(点了会 404,不应渲染)。
 *  - 分组/页面均按 sort 升序。
 *
 * `pathByResource` 是「权限资源 → 前端实际持有的页面路径」清单(来自兜底 menu.json),
 * 只在**后端数据缺陷**时使用:同一 route 被多个页面节点复用 → 点哪个菜单都进同一页。
 * 路由的真源仍然是后端的 node.route;这里只在复用发生时兜底,并在控制台点名,不改正常数据的行为。
 */
export function buildMenus(
  tree: MenuNode[],
  pathByResource?: ReadonlyMap<string, string>,
): MenuGroupDef[] {
  const groups: MenuGroupDef[] = [];

  // 先统计 route 复用情况(只统计会进菜单的节点)
  const routeUses = new Map<string, number>();
  (tree ?? []).forEach((g) => {
    if (g.nodeType !== 1 || g.status !== 1) return;
    (g.children ?? []).forEach((n) => {
      if (n.nodeType === 2 && n.status === 1 && n.route) {
        routeUses.set(n.route, (routeUses.get(n.route) ?? 0) + 1);
      }
    });
  });

  (tree ?? [])
    .filter((n) => n.nodeType === 1 && n.status === 1)
    .sort((a, b) => a.sort - b.sort)
    .forEach((g) => {
      const children: MenuItemDef[] = [];
      const pages = (g.children ?? [])
        .filter((n) => n.nodeType === 2 && n.status === 1)
        .sort((a, b) => a.sort - b.sort);
      pages.forEach((n) => {
        const code = n.permCode;
        // 路由由后端树直接下发;缺失则跳过(不应渲染一个点了会 404 的菜单项)
        if (!n.route) {
          console.warn(`[menu] 后端菜单「${n.label}」(${code ?? '无权限码'}) 未下发 route,已跳过`);
          return;
        }
        // resource 仅用于 route 复用时的路径兜底,与显隐无关;无 permCode 也照常渲染。
        const point = code ? toFrontendPoint(code) : '';
        const i = point.lastIndexOf(':');
        const resource = point ? ((i > 0 ? point.slice(0, i) : point) as ResourceKey) : undefined;
        let path = n.route;
        const uses = routeUses.get(path) ?? 0;
        if (uses > 1) {
          const repaired = pathByResource?.get(resource);
          if (repaired) {
            console.error(
              `[menu] 后端菜单「${n.label}」(${code}) 的 route ${path} 被 ${uses} 个页面复用,` +
                `已回落到前端页面清单的 ${repaired}。请把后端菜单节点的 route 改成互不相同。`,
            );
            path = repaired;
          }
        }
        children.push({ path, label: n.label, icon: n.icon ?? null, resource });
      });

      if (children.length) groups.push({ group: g.label, icon: g.icon ?? null, children });
    });

  return groups;
}

/** 把任意后端返回归一为扁平权限点数组 */
export function normalizePermissions(raw: unknown): string[] {
  if (!raw) return [];

  // 1) 已是扁平数组:['store:list:view', 'store:approve:pass']
  if (Array.isArray(raw)) {
    return raw.filter((x): x is string => typeof x === 'string').map(toFrontendPoint);
  }

  // 2) 登录/info 的 permCodes 为权威字段,空值也不回退到旧权限字段。
  if (typeof raw === 'object') {
    const o = raw as Record<string, unknown>;
    if (Object.hasOwn(o, 'permCodes')) return normalizePermissions(o.permCodes);
    if (Array.isArray(o.permissions)) return normalizePermissions(o.permissions);
    if (Array.isArray(o.list)) return normalizePermissions(o.list);
    if (o.data && typeof o.data === 'object') {
      const d = o.data as Record<string, unknown>;
      return normalizePermissions(d);
    }
  }

  return [];
}

/**
 * 开发期兜底:用现有角色矩阵推导出权限点(view=页面资源,ck.on 额外给 :manage)。
 * 仅用于未接入后端时本地演示;生产应由后端 permissions 取代(调用 loadPermissions)。
 */
export function matrixToPoints(matrix: PermissionMatrix, role: RoleKey): string[] {
  const out: string[] = [];
  (Object.keys(matrix) as ResourceKey[]).forEach((res) => {
    const state: PermissionState = matrix[res]?.[role] ?? 'na';
    if (state === 'na') return;
    out.push(res);
    if (state === 'ck.on') out.push(`${res}:manage`);
  });
  return out;
}