#!/usr/bin/env node
/**
* 「统一底座」新设计图生成器(2026-09-29)
*
* ⚠️ 与 `gen.mjs` 的区别(这两个必须分清):
* · `gen.mjs` → `整体系统设计图.html` = **当前正在运行的系统**(实况)
* · `gen-base.mjs`(本文件)→ `统一底座设计图.html` = **V3 §十五 设计的统一底座**(目标态)
*
* 内容全部取自 V3 §十五「超级底座与三级模块授权」的正式定义:
* 四层模型 / 三级授权链 / 三张表 / 判定求交 / 10 个改造点 / 供应商模板 / 分期 / E1~E12 验收。
* 校验用数字(模块数、路由条数、权限码)在生成时**现查代码与库**,不写死。
*/
import { readFileSync, writeFileSync, readdirSync, existsSync } from 'node:fs';
import { createRequire } from 'node:module';
import { execSync } from 'node:child_process';
const ROOTPATH = new URL('../../', import.meta.url).pathname;
const require = createRequire(new URL('../../server/package.json', import.meta.url));
const rd = (p) => readFileSync(ROOTPATH + p, 'utf8');
const sh = (c) => execSync(c, { cwd: ROOTPATH, encoding: 'utf8' }).trim();
// ── 现查:模块清单(= module_catalog 的行)+ 路由条数 ────────────────
const modules = (() => {
const src = rd('server/src/modules/businessModules.ts');
const marks = [...src.matchAll(/id:\s*'([a-z_]+)'/g)].map((m) => ({ id: m[1], at: m.index }));
return marks.map((mk, i) => {
const b = src.slice(mk.at, i + 1 < marks.length ? marks[i + 1].at : src.length);
return {
id: mk.id,
name: (b.match(/name:\s*'([^']+)'/) || [, mk.id])[1],
prefix: (b.match(/workflowApiPrefix:\s*'([^']+)'/) || [, null])[1],
};
});
})();
const WITH_PREFIX = modules.filter((m) => m.prefix);
const NO_PREFIX = modules.filter((m) => !m.prefix);
// ⚠️ 路由条数必须**逐文件用正则数**,不能用 `grep -rhoE "…(['\"])"`:
// 在 shell 里那个 `\"` 会被解释掉,导致漏匹配(实测 369 被数成 366)。
// V3 的 369 是三口径交叉验证过的数,不能因为我的工具口径错而"更正"它。
const ROUTES = (() => {
const dir = 'server/src/modules/workflow/routes';
let n = 0;
for (const f of readdirSync(ROOTPATH + dir)) {
if (!f.endsWith('.ts')) continue;
const src = readFileSync(ROOTPATH + dir + '/' + f, 'utf8');
n += (src.match(/router\.(get|post|put|patch|delete|all)\(\s*['"]/g) || []).length;
}
return n;
})();
// 小程序页数:代码在 `miniprogram/`(不是 src/pages/mobile),以 app.json 的 pages 为准
const MOBILE_PAGES = (() => {
try {
const j = JSON.parse(readFileSync(ROOTPATH + 'miniprogram/app.json', 'utf8'));
return (j.pages || []).length;
} catch { return 'n/a'; }
})();
// ── 现查库:权限码(第二层闸门)与模块值 ─────────────────────────────
let DB = { ok: false };
try {
const { Client } = require('pg');
const c = new Client({ connectionString: process.env.DATABASE_URL || 'postgresql://supplier@127.0.0.1:5432/supplier_delivery' });
await c.connect();
const p = (await c.query(`SELECT count(*)::int codes, count(DISTINCT module)::int mods FROM public.permissions`)).rows[0];
const br = (await c.query(`SELECT count(*)::int n FROM public.branches`)).rows[0];
const su = (await c.query(`SELECT count(*)::int n FROM tenant_br002.suppliers`)).rows[0];
DB = { ok: true, codes: p.codes, mods: p.mods, branches: br.n, suppliers: su.n };
await c.end();
} catch (e) { DB.why = e.message.slice(0, 70); }
const esc = (s) => String(s).replace(/[&<>"]/g, (x) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[x]));
const TEAL = '#0f766e', BLUE = '#1d4ed8', AMBER = '#b45309', RED = '#b91c1c', VIOLET = '#6d28d9', SLATE = '#475569';
const chip = (t, c = SLATE) => `${esc(t)}`;
const sec = (id, t, sub, body, a) => `${t}${sub ? `${esc(sub)}` : ''}
${body}
| ${x} | `).join('')}
|---|
| ${y} | `).join('')}
applyTenantScope()(tenantScope.ts:969)roleType === 'supplier'(mobileShared.ts:416)、
开放 API scope === 'supplier'(supplierAuth.ts:32,69,82)套餐 / module_entitlement / 授权模块 全仓 0 命中🔑 为什么这条链成立、不用改数据模型:供应商身份本来就是 (branch_code, supplier_code) 复合键,
不是全局唯一 —— 见 migrations/20260819_supplier_integration_clients.sql:17-23 的
public.supplier_integration_client_suppliers(主键 (client_id, branch_code, supplier_code) 三元)。
⇒ 供应商天然属于某个配送商,「平台 → 配送商 → 供应商」与数据结构正好吻合。
public.module_catalog', '① 平台', 'module_id', `平台定义"卖哪些模块";module_id 对齐 businessModules.ts 的 id(实测 ${modules.length} 个);含 tier(base/pro/flagship)与 default_on`],
['public.branch_module_entitlements', '② 配送商', '(branch_code, module_id)', '平台 → 配送商授权;含 enabled / expires_at(可订阅到期)/ granted_by'],
['public.supplier_module_entitlements', '③ 供应商', '(branch_code, supplier_code, module_id)', '配送商 → 供应商授权'],
]) + `✅ 已实测可执行(不是"看着对"):DDL 抽出后在本地库事务内执行 → ROLLBACK,
三张表全部建出、REFERENCES public.branches(branch_code) 可解析、回滚后残留 0 行。
⚠️ 本表不在任何租户 schema、不进 tenant_business_tables() —— 否则会被
ensureTenantSchemasMatchTemplate() 克隆进 5 个分公司 + 模板,而 search_path=tenant_xxx,public
会让查询读到空的租户副本;同时新增反向断言(E8″)拦截误写入。
module_unavailable / branch_module_not_entitled / supplier_module_not_entitled / module_entitlement_expired⚠️ 到期语义已裁决(DEC-6):完全禁用,不是只读;到期前 7 天提醒;错误码须可区分"没买"与"过期"。
`; // ── ⑤ 10 个改造点 ─────────────────────────────────────────────────── const L5 = tbl(['#', '改造面', '说明'], [ ['1–4', '4 条链路', `Web workflow 路由(实测 ${ROUTES} 条)·/api/mobile/*(小程序 ${MOBILE_PAGES} 页)· /api/functions · 供应商开放 API`],
['5–10', '6 类旁路', '公开溯源页 · /api/data 通用网关 · 开放 API 的独立鉴权 · 调度器 · /api/mobile 未覆盖的子路由 · AI 助手'],
]) + `🔴 「四条链路」不是全集 —— 只做 4 条会漏 6 类旁路。门禁点合计 10 个。
⛔ 两个致命前提未满足不得开工:① 平台侧自锁(门禁若把平台自己的入口也拦了,回填也解不了);
② 模块粒度比模板粒度粗(见 ⑦ 的放大效应)。
purchase + product', '开 purchase 同时得到质检报告(10) / 采购单(8) / 备货(28)'],
['猪肉供应商', '+ 对账', '+ finance', 'finance 一并开 /cost(29)'],
['冻品供应商', '+ 库存', '+ inventory', 'inventory 一并开 /trace(2)'],
['综合供应商', '+ 竞价', '+ order', '🔴 开「竞价」= 整开 order 模块(/orders 24 · /bids 15 · /after-sales 5 · /substitution 4 · /allocation 2)'],
['自定义', '逐项勾选', '同上逐项', '—'],
]) + `🔴 这张表此前只有"业务名"、没有 module_id 映射 —— 而 7 个业务名没有一个等于 module_id。
⇒ 模块粒度比模板粒度粗,"按模板开"实际是"按模块开":无法只开「备货」不开「质检报告」(同落 purchase)。
必须产品裁决:接受放大,或把目录粒度下沉到子模块(如 order.bid)。未裁决前不得作为施工依据。
/api/workflow/bids/* 与 /api/supplier/*)'],
['E2', '配送商未订阅 order,其下供应商调 /bids/* → 403 branch_module_not_entitled'],
['E3 / E4', '未授权模块不出现在小程序首页 / 前端菜单'],
['E5', 'GET /api/modules/manifest 对供应商只返回已授权模块'],
['E6', '授权到期 → 完全禁用(DEC-6);到期前 7 天提醒;错误码可区分"没买"与"过期"'],
['E7', '已授权模块内的动作权限(54 个权限码)仍然生效(模块授权不替代权限码)'],
['E8′', '在 tenant_template 建业务表但不写名单 → 迁移失败并中止(守卫方向:模板 ⊆ 名单)'],
['E8″', '三张平台表误写入租户名单后跑迁移 → 新断言失败并中止'],
['E9', '存量回归:升级后原有功能全部可用(⚠️ 原判据"均按 default_on 有行"可被自己造的数据满足,已加强)'],
['E10', '平台自救:super_admin 进入 /system/branches 与 /system/config,为某分公司成功开一个模块'],
])}`;
const html = `