Commit 1328acf2 by liimin

增加merchant 商户帐户管理 子系统

1 parent be0ca491
Pipeline #752 for 1328acf2 failed in 0 seconds
Showing 71 changed files with 2736 additions and 44 deletions
...@@ -31,3 +31,12 @@ VITE_STRICT_VERIFY=false ...@@ -31,3 +31,12 @@ VITE_STRICT_VERIFY=false
# ⚠ 生产必填:uj.entry 写的是 localhost 开发机地址,生产环境 entryOf() 会拒绝回落到它, # ⚠ 生产必填:uj.entry 写的是 localhost 开发机地址,生产环境 entryOf() 会拒绝回落到它,
# 没清单时子应用会显示「未找到子应用入口」。该 URL 必须响应 Cache-Control: no-cache。 # 没清单时子应用会显示「未找到子应用入口」。该 URL 必须响应 Cache-Control: no-cache。
# VITE_MANIFEST_URL=/mfe/manifest.json # VITE_MANIFEST_URL=/mfe/manifest.json
# ---------------------------------------------------------------------------
# 商户管理子系统(apps/web/subapps/merchant)不接 VITE_* 网关密钥:
# 地址 / appKey / secret 运行时从配置中心模块 uj-admin-merchant 的 external 块读取,
# 字段与老 H5 一致(新模块未建好时过渡回退 glsx-oss-account-config)。
# 见 apps/web/subapps/merchant/src/adapter/credentials.ts。
# ---------------------------------------------------------------------------
# 权限闸门:本地联调可设 false 放行全部按钮
# VITE_MERCHANT_PERMISSION_ENFORCE=false
import { app } from '@uj/eslint-config';
export default app({ noRestrictedImports: true });
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>商户管理 · 子应用</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
{
"name": "@uj/web-merchant",
"version": "0.0.1",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"lint": "eslint . --max-warnings=0",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@uj/api-core": "workspace:*",
"@uj/biz": "workspace:*",
"@uj/contracts": "workspace:*",
"@uj/design-tokens": "workspace:*",
"@uj/platform-sdk": "workspace:*",
"@uj/ui": "workspace:*",
"@ant-design/icons": "catalog:",
"@tanstack/react-query": "catalog:",
"antd": "catalog:",
"dayjs": "catalog:",
"react": "catalog:",
"react-dom": "catalog:",
"react-router-dom": "catalog:"
},
"devDependencies": {
"@types/node": "catalog:",
"@types/react": "catalog:",
"@types/react-dom": "catalog:",
"@uj/eslint-config": "workspace:*",
"@uj/typescript-config": "workspace:*",
"@uj/vite-config": "workspace:*",
"eslint": "catalog:",
"typescript": "catalog:",
"vite": "catalog:"
},
"uj": {
"route": "merchant",
"entry": "http://localhost:5179/"
}
}
import { useEffect, useMemo, useState } from 'react';
import { busEvents } from '@uj/contracts';
import { SubAppProvider, readInitialPage, shortName, subappBus } from '@uj/platform-sdk';
import { UEmpty, UPageTransition } from '@uj/ui';
import MerchantPage from './pages/Merchant';
import CreateMerchantPage from './pages/Merchant/Create';
import MerchantEditPage from './pages/Merchant/Edit';
import MerchantDetailPage from './pages/Merchant/Detail';
import EmployeePage from './pages/Employee';
import RolePage from './pages/Role';
import type { PageParams, RouteDef } from './routes';
import { matchRoute } from './routes';
/**
* 三条主路由逐字对应菜单 SQL 的 route 末段:merchant / employee / role。
* merchant/create、merchant/create/:parentId(子商户)、merchant/edit/:id、merchant/detail/:id
* 是二级页(老 add/addSubMerchant/edit/detail.html 表单太长,抽屉放不下),不进菜单。
*/
const ROUTES: RouteDef[] = [
{ path: 'merchant', Page: MerchantPage },
{ path: 'merchant/create', Page: CreateMerchantPage },
{ path: 'merchant/create/:parentId', Page: CreateMerchantPage },
{ path: 'merchant/sub/:parentId', Page: CreateMerchantPage },
{ path: 'merchant/edit/:id', Page: MerchantEditPage },
{ path: 'merchant/detail/:id', Page: MerchantDetailPage },
{ path: 'employee', Page: EmployeePage },
{ path: 'employee/create/:merchantId', Page: EmployeePage },
{ path: 'role', Page: RolePage },
];
function renderPage(subPath: string) {
const matched = matchRoute(ROUTES, subPath);
if (!matched) {
return <UEmpty description={`没有匹配「${subPath}」的页面,请从菜单进入`} />;
}
const { Page, params } = matched;
return <Page params={params as PageParams} />;
}
function MerchantApp() {
const [subPath, setSubPath] = useState<string>(readInitialPage);
useEffect(() => {
const bus = subappBus();
if (!bus) return;
const events = busEvents(shortName());
const onNavigate = (...args: unknown[]) => setSubPath(String(args[0] ?? ''));
const onLogout = () => setSubPath('');
bus.$on(events.navigate, onNavigate);
bus.$on(events.logout, onLogout);
bus.$emit(events.ready);
return () => {
bus.$off(events.navigate, onNavigate);
bus.$off(events.logout, onLogout);
};
}, []);
const page = useMemo(() => renderPage(subPath), [subPath]);
return <UPageTransition pageKey={subPath}>{page}</UPageTransition>;
}
export function App() {
return (
<SubAppProvider>
<div className="uj-scope uj-merchant-app">{MerchantApp()}</div>
</SubAppProvider>
);
}
import { useAccess } from '@/access';
import type { PermissionCode } from '../permissions/codes';
import { matchPermission } from './perms';
/** 页面侧唯一权限入口:只交码,判定交给适配层。 */
export function useMerchantAccess() {
const { points } = useAccess();
return {
can: (code: PermissionCode | PermissionCode[]) =>
matchPermission(points, Array.isArray(code) ? code : [code]),
points,
};
}
import { loadRemoteConfig, type RemoteConfig } from '@uj/platform-sdk';
import { applyGatewayConfig, splitEndpoint } from './gateways';
import type { AccountExternalConfig, GatewayCredential, GatewayId } from './types';
/**
* 商户域网关凭据唯一真源:运行时配置中心。
*
* 首选新模块 `uj-admin-merchant`,配置体只需下发 old H5 的 `external` 块:
* {
* "sysName": "uj-admin-merchant",
* "external": {
* "baseURL": "<origin>/rop-merchants/router",
* "secret": "...",
* "fileUploadURL": "https://.../router",
* "params": { "appKey": "...", "v": "1.0.0", "source": "glsx", "format": "json" }
* }
* }
* `sysName` 是平台配置中心的识别标记;不用下发 axios / accountUrl / result 等块。
*
* 过渡期:新模块尚未创建或读取失败时回退到老 H5 的 `glsx-oss-account-config`。
* 回退只发生在「拉取失败」,新模块拉到了但字段缺失会直接报出模块名,不静默吞错。
*/
export const MERCHANT_CONFIG_MODULE = 'uj-admin-merchant';
const LEGACY_CONFIG_MODULE = 'glsx-oss-account-config';
/** 兼容旧调用方的导出名;语义已指向新模块。 */
export const ACCOUNT_CONFIG_MODULE = MERCHANT_CONFIG_MODULE;
const injected = new Map<GatewayId, GatewayCredential>();
let pending: Promise<void> | undefined;
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function text(value: unknown, field: string, module: string): string {
if (typeof value !== 'string' || !value.trim()) {
throw new Error(`配置中心 ${module} 的 external.${field} 为空。`);
}
return value.trim();
}
function readExternal(raw: unknown, module: string): AccountExternalConfig {
if (!raw || typeof raw !== 'object') {
throw new Error(`配置中心 ${module} 未下发 external 配置块。`);
}
const external = raw as Record<string, unknown>;
const params = external['params'];
if (!params || typeof params !== 'object') {
throw new Error(`配置中心 ${module} 的 external.params 缺失。`);
}
const p = params as Record<string, unknown>;
return {
baseURL: text(external['baseURL'], 'baseURL', module),
secret: text(external['secret'], 'secret', module),
fileUploadURL: text(external['fileUploadURL'], 'fileUploadURL', module),
params: {
appKey: text(p['appKey'], 'params.appKey', module),
v: typeof p['v'] === 'string' && p['v'].trim() ? p['v'].trim() : undefined,
source: text(p['source'], 'params.source', module),
format: text(p['format'], 'params.format', module),
},
};
}
async function loadWithLegacyFallback(): Promise<{ raw: RemoteConfig; module: string }> {
try {
return {
raw: await loadRemoteConfig({ moduleUrl: MERCHANT_CONFIG_MODULE }),
module: MERCHANT_CONFIG_MODULE,
};
} catch (primaryError) {
try {
return {
raw: await loadRemoteConfig({ moduleUrl: LEGACY_CONFIG_MODULE }),
module: LEGACY_CONFIG_MODULE,
};
} catch (legacyError) {
throw new Error(
`配置中心 ${MERCHANT_CONFIG_MODULE} 读取失败,旧模块 ${LEGACY_CONFIG_MODULE} 也不可用:` +
`${errorMessage(primaryError)};${errorMessage(legacyError)}`,
);
}
}
}
/** 首次请求前拉取一次配置;单飞,失败后允许重试(与 loadRemoteConfig 同语义)。 */
export function ensureAccountConfig(): Promise<void> {
if (!pending) {
pending = (async () => {
const { raw, module } = await loadWithLegacyFallback();
const external = readExternal(raw['external'], module);
applyGatewayConfig(external);
const business = splitEndpoint(external.baseURL, 'external.baseURL');
const upload = splitEndpoint(external.fileUploadURL, 'external.fileUploadURL');
const credential = {
appKey: external.params.appKey,
secret: external.secret,
version: external.params.v || '1.0.0',
format: external.params.format || 'json',
};
injected.set('entmicro-account', { ...credential, origin: business.origin });
injected.set('account-upload', { ...credential, origin: upload.origin });
})().catch((error: unknown) => {
pending = undefined;
throw error;
});
}
return pending;
}
/** 仅供测试/联调注入;生产凭据只由配置中心写入。 */
export function setGatewayCredential(id: GatewayId, credential: Partial<GatewayCredential>): void {
const previous = injected.get(id);
injected.set(id, {
origin: credential.origin ?? previous?.origin ?? '',
appKey: credential.appKey ?? previous?.appKey ?? '',
secret: credential.secret ?? previous?.secret ?? '',
version: credential.version ?? previous?.version ?? '1.0.0',
format: credential.format ?? previous?.format ?? 'json',
});
}
export function getGatewayCredential(id: GatewayId): GatewayCredential {
const credential = injected.get(id);
if (!credential?.origin || !credential.appKey) {
throw new Error(
`${id} 网关凭据尚未就绪:请先完成 ensureAccountConfig()(配置中心模块 ${MERCHANT_CONFIG_MODULE})。`,
);
}
return credential;
}
import { createSigner, type GatewayStrategy, type NormalizedEnvelope } from '@uj/api-core';
import type { AccountExternalConfig, GatewayId } from '../types';
/**
* 账户中心老 H5 的两套网关策略(事实来源:temp/account/js/request.js + js/load.js)。
*
* 1) 业务网关 external.baseURL:method 与业务参数平铺进 form 体,固定 sessionAuth='st',
* sign = SHA1(secret + 排序后的 key+value 串 + secret).toUpperCase();
* 请求头 TGT 取会话值 —— 本系统取 points 请求的 loginToken,经注册式头策略注入。
* 2) 文件上传网关 external.fileUploadURL:lettername app_key,MD5 同规则签名,
* file 走 noSignAttr 不进原文,URL 查询串带 method,且**不带 TGT / 不带会话字段**。
*
* 地址、appKey、secret、source 全部由配置中心 uj-admin-merchant 运行时下发,
* 这里只留「协议形状」,不留任何环境常量。新网关接入 = 新策略 + 登记,dispatcher 不改。
*/
function parseRawBody(raw: unknown): unknown {
if (typeof raw !== 'string') return raw;
try {
return JSON.parse(raw) as unknown;
} catch {
return raw;
}
}
/**
* 老账户中心的分页信封是 `data.data[] + data.count + pageNum/pageSize`(事实来源:
* temp/account/html/{merchant,role,employee}/index.html 的 getTabelList 均取
* `data.data` 与 `data.count`)。主壳 DataTable 按 `list/total/current/size` 读。
*
* 这里的 `data` 数组**必须改名,不能保留**:web 子应用走双层门面(主壳 request → 子应用
* 门面),主壳已把 `{code,data}` 拆过一层;子应用门面见到业务对象里还有 `data` 数组,
* 会再拆一次,最终页面拿到行数组、分页信息全丢。改名后门面不再误判为信封。
* count/pageNum/pageSize 保留,老代码的读取口径不丢。
*/
function normalizePagedPayload(payload: unknown): unknown {
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return payload;
const paged = payload as Record<string, unknown>;
if (
!Array.isArray(paged['data']) ||
(paged['count'] === undefined && paged['pageNum'] === undefined)
) {
return payload;
}
const { data: rows, ...rest } = paged;
return {
...rest,
list: paged['list'] ?? rows,
total: paged['total'] ?? paged['count'],
current: paged['current'] ?? paged['pageNum'],
size: paged['size'] ?? paged['pageSize'],
};
}
export function normalizeAccountEnvelope(raw: unknown): NormalizedEnvelope {
const body = parseRawBody(raw);
if (!body || typeof body !== 'object') return { data: body };
const envelope = body as Record<string, unknown>;
const code = envelope['code'] ?? envelope['returnCode'];
const message = typeof envelope['message'] === 'string' ? envelope['message'] : '';
if (String(code) === '0') return { data: normalizePagedPayload(envelope['data']) };
// errId='21' 是老系统钉死的 TGT 失效码(request.js:85)。这里归一成主壳的 401 而不是
// 原样保留 21:业务码由主壳统一判,主壳的 onLoginRequired 才会 clearToken 并跳 /login。
// 保留 21 只能让子应用自己广播 bus,绕开主壳的令牌清理与 RequireAuth 重定向。
if (String(envelope['errId'] ?? code) === '21') {
return { code: 401, message: message || '登录已失效,请重新登录' };
}
const numeric = Number(code);
return {
code: Number.isFinite(numeric) && numeric !== 200 ? numeric : 500,
message: message || `接口返回失败(${String(code ?? '')})`,
};
}
/** 把配置中心 URL 拆成 origin + 相对路径;协议相对地址按当前页面协议补全。 */
export function splitEndpoint(raw: string, label: string): { origin: string; path: string } {
if (!raw) throw new Error(`配置中心模块未下发 ${label}。`);
const protocol = typeof window === 'undefined' ? 'https:' : window.location.protocol;
const absolute = raw.startsWith('//') ? `${protocol}${raw}` : raw;
const url = new URL(absolute);
return { origin: url.origin, path: `${url.pathname}${url.search}` };
}
export const accountGateway: GatewayStrategy = {
id: 'entmicro-account' satisfies GatewayId,
// 真值由配置中心在首次请求前注入;空串时不静默发往错误落点。
router: '',
// TGT 由注册式头策略提供;留空表示不走 tokenHeader 老通道,避免同一个头两个真源。
tokenHeader: '',
headerProviders: ['tgt-session'],
signer: createSigner(),
fixedParams: { sessionAuth: 'st' },
normalize: normalizeAccountEnvelope,
// 登出码归一成主壳的 401:由主壳 onLoginRequired 统一清令牌并跳 /login。
response: { codeKey: 'code', successCodes: ['0'], logoutCodes: [401] },
};
export const uploadGateway: GatewayStrategy = {
id: 'account-upload' satisfies GatewayId,
router: '',
// request.js 的 isOtherUrl 分支显式删除 beforeSend:上传网关不认 TGT。
tokenHeader: '',
headerProviders: [],
signer: createSigner({
kind: 'custom',
id: 'account-upload-md5',
algorithm: 'md5',
secretWrap: 'both',
uppercase: true,
// 老系统 isOtherUrl 把 appKey 改名为 app_key 后再签名。
fieldNames: { appKey: 'app_key' },
}),
fixedParams: { sessionAuth: 'st' },
normalize: normalizeAccountEnvelope,
// 登出码归一成主壳的 401:由主壳 onLoginRequired 统一清令牌并跳 /login。
response: { codeKey: 'code', successCodes: ['0'], logoutCodes: [401] },
};
/** 配置中心下发后一次性刷新两套协议的落点与固定参数。 */
export function applyGatewayConfig(config: AccountExternalConfig): void {
const business = splitEndpoint(config.baseURL, 'external.baseURL');
const upload = splitEndpoint(config.fileUploadURL, 'external.fileUploadURL');
accountGateway.router = business.path;
// 老 request.js 在 isOtherUrl 分支仍带 common.params(含 source),只是把 appKey 改名 app_key。
// 两套策略的 fixedParams 必须同源,否则上传签名原文会少一个 source。
const fixedParams = { sessionAuth: 'st', source: config.params.source };
accountGateway.fixedParams = fixedParams;
uploadGateway.fixedParams = fixedParams;
uploadGateway.router = `${upload.path}${upload.path.includes('?') ? '&' : '?'}method=glsx.accounts.biz.common.pictureUpload`;
}
import { registerGateway } from '@uj/api-core';
import { accountGateway, uploadGateway } from './account';
// 显式 import + 登记:未登记则 resolveGateway 当场抛错,不会静默走默认签名。
registerGateway(accountGateway);
registerGateway(uploadGateway);
export {
accountGateway,
uploadGateway,
applyGatewayConfig,
normalizeAccountEnvelope,
splitEndpoint,
} from './account';
export { rpcCall, request } from './rpc';
export {
accountGateway,
uploadGateway,
applyGatewayConfig,
normalizeAccountEnvelope,
} from './gateways';
export {
ACCOUNT_CONFIG_MODULE,
ensureAccountConfig,
getGatewayCredential,
setGatewayCredential,
} from './credentials';
export { matchPermission } from './perms';
export type {
AccountExternalConfig,
GatewayCredential,
GatewayHeaderProvider,
GatewayId,
GatewayStrategy,
NormalizedEnvelope,
RpcCall,
Signer,
} from './types';
/**
* 商户管理域权限三态闸门。
* 后端未下发任何 merchant: 码 → 按钮全部放行(权限未接入,避免整页按钮消失);
* 下发了本域任一码 → 严格按码命中;显式 VITE_MERCHANT_PERMISSION_ENFORCE=false → 放行。
*/
const DOMAIN_PREFIX = 'merchant:';
const warned = new Set<string>();
function warnOnce(key: string, text: string): void {
if (warned.has(key)) return;
warned.add(key);
console.info(`[merchant:perm] ${text}`);
}
const enforceDisabled = import.meta.env.VITE_MERCHANT_PERMISSION_ENFORCE === 'false';
export function matchPermission(granted: Set<string>, aliases: string[]): boolean {
if (enforceDisabled) {
warnOnce('off', '已按 VITE_MERCHANT_PERMISSION_ENFORCE=false 放行全部按钮。');
return true;
}
if (![...granted].some((code) => code.startsWith(DOMAIN_PREFIX))) {
warnOnce(
'pending',
'后端尚未下发 merchant:* 权限码,商户管理按钮暂按全部放行;一旦开始下发,未命中的按钮会自动隐藏。',
);
return true;
}
return aliases.some((code) => granted.has(code));
}
import { createClient } from '@uj/api-core';
import { requestViaHost } from '@uj/platform-sdk';
import { getLoginSession } from '@/access';
import { ensureAccountConfig, getGatewayCredential } from './credentials';
import type { GatewayId, RpcCall } from './types';
// 显式 import 保证任何调用路径下网关策略与 TGT 头策略都已登记。
import './gateways';
/** 老系统统一 3 分钟超时(同 points 的 LEGACY_TIMEOUT)。 */
const LEGACY_TIMEOUT = 180000;
/**
* 商户域唯一请求出口:与 points / finance 一样走主壳 props.request,请求层保持统一。
*
* 差异只用一条声明表达:`hostPolicy: 'legacy-external'`。该策略只关闭主壳为自家 REST
* 网关准备的两件事 —— RSA 请求头(老 ROP 的 CORS 白名单不认 X-Sign-Algorithm)、
* Bearer 令牌(老网关用 TGT)。业务码判定**仍留在主壳**:本域网关的 normalize 把老信封
* 翻成主壳认得的形状(成功 `{ data }`、TGT 失效 `code:401`),主壳的 onLoginRequired
* 因此会 clearToken + 跳 /login,与全站 401 走同一条登出链路。
*
* TGT 按需求取「points 请求用到的 session」——即登录响应 data.loginToken,
* 由 session.sessionId 注入;api-core 的 'tgt-session' 头策略把它写入全大写 TGT。
*/
export const request = createClient({
transport: 'host',
hostSend: requestViaHost(),
hostPolicy: 'legacy-external',
timeout: LEGACY_TIMEOUT,
gatewayCredential: (id) => getGatewayCredential(id as GatewayId),
gatewayToken: () => '',
session: {
sessionId: () => getLoginSession()?.loginToken ?? '',
paramName: 'sessionId',
},
errorHandler: (err) => {
throw err.cause ?? err;
},
});
export async function rpcCall<T = unknown>(call: RpcCall): Promise<T> {
// 网关落点 / appKey / secret 来自配置中心 uj-admin-merchant;首次调用前等它就绪,
// 避免 prepare 阶段因缺凭据抛错、Network 里看不到任何请求。
await ensureAccountConfig();
return request.post<T>(call.method, call.params, {
gateway: call.gateway,
signed: call.signed,
unsignedKeys: call.unsignedKeys,
noSession: call.noSession,
});
}
/** 商户管理子域的网关标识:账户中心业务网关 + 老系统的独立文件上传网关。 */
export type GatewayId = 'entmicro-account' | 'account-upload';
export type {
GatewayCredential,
GatewayStrategy,
NormalizedEnvelope,
RpcCall,
Signer,
GatewayHeaderProvider,
} from '@uj/api-core';
/** 配置中心 uj-admin-merchant 的 external 块(逐字保留老系统字段名)。 */
export interface AccountExternalConfig {
baseURL: string;
secret: string;
fileUploadURL: string;
params: {
appKey: string;
v?: string;
source: string;
format: string;
};
}
/**
* 子应用请求客户端出口(reconcile 要求的固定文件路径)。
*
* 真正的装配在 @/adapter/rpc.ts:createClient({ transport: 'host', hostSend: requestViaHost() })
* 走主壳唯一那份 axios,差异用 hostPolicy:'legacy-external' 声明(关闭主壳 RSA/Bearer/验签);
* 这里只做转发,避免「子应用自带第二份客户端」被误读。
*/
export { request, rpcCall } from '@/adapter/rpc';
export { RpcApiClient } from './rpc-client';
import { rpcCall } from '@/adapter';
import type { GatewayId } from '@/adapter';
/**
* 账户中心接口是一个 RPC 方法名 + 一层平铺参数;业务模块只描述这两件事。
* 落点、加签、TGT 头、响应归一全部由适配层策略决定,业务层没有第二条请求出口。
*/
export class RpcApiClient {
constructor() {
// 方法引用会直接交给 react-query 的 fetcher,构造期统一 bind this。
const proto = Object.getPrototypeOf(this);
for (const name of Object.getOwnPropertyNames(proto)) {
if (name === 'constructor') continue;
const value = (this as unknown as Record<string, unknown>)[name];
if (typeof value === 'function') {
(this as unknown as Record<string, unknown>)[name] = value.bind(this);
}
}
}
protected rpc<T>(
gateway: GatewayId,
method: string,
params: Record<string, unknown> = {},
options: { signed?: boolean; unsignedKeys?: string[]; noSession?: boolean } = {},
): Promise<T> {
return rpcCall<T>({
gateway,
method,
params,
signed: options.signed,
unsignedKeys: options.unsignedKeys,
noSession: options.noSession,
});
}
}
/**
* 老系统的接口没有 DTO 定义(js/request.js 只收平铺 params),这里不臆造字段:
* 行类型列出页面已确认使用的列,同时保留索引签名承接后端新增字段。
*/
export type RpcListResult<T> = {
/** 老信封原字段:data 行数组在网关归一时改名为 list(避免双层门面二次拆包);count 保留。 */
data?: T[];
count?: number;
/** 主壳 DataTable 约定的分页字段。 */
list?: T[];
records?: T[];
total?: number;
current?: number;
size?: number;
pageNum?: number;
pageSize?: number;
[key: string]: unknown;
};
export interface MerchantRow {
id?: string | number;
merchantNo?: string;
merchantName?: string;
merchantModelName?: string;
accessModeName?: string;
accountTypeNames?: string;
merchantLoginAccount?: string;
accountLevelName?: string;
parentMerchant?: string;
statusName?: string;
merchantLegalPerson?: string;
merchantLegalPersonPhone?: string;
entmicroName?: string;
createdSourceStr?: string;
createdAccount?: string;
createdTime?: string;
updatedTime?: string;
effectiveTime?: string;
effectiveStarttime?: string;
expireDate?: string;
merchantAccountLevel?: string | number;
accessMode?: string | number;
status?: string | number;
[key: string]: unknown;
}
export interface EmployeeRow {
id?: string | number;
staffName?: string;
roleName?: string;
staffPhone?: string;
entmicroName?: string;
statusName?: string;
status?: string | number;
createdAccount?: string;
merchantName?: string;
merchantId?: string | number;
createdSourceStr?: string;
createdTime?: string;
updatedTime?: string;
effectiveTime?: string | number;
[key: string]: unknown;
}
export interface RoleRow {
id?: string | number;
roleName?: string;
roleCode?: string;
merchantName?: string;
merchantId?: string | number;
statusName?: string;
delFlag?: string | number;
roleDescription?: string;
defalutRole?: boolean;
updatedTime?: string;
createdTime?: string;
[key: string]: unknown;
}
export interface DictItem {
dictValue?: string | number;
dictLabel?: string;
value?: string | number;
label?: string;
id?: string | number;
name?: string;
[key: string]: unknown;
}
/** 商户管理子系统 `@/api` 出口:全部接口经本域 RpcApiClient → 主壳唯一请求出口。 */
export * from './modules/common';
export * from './modules/merchant';
export * from './modules/employee';
export * from './modules/role';
export type { DictItem, EmployeeRow, MerchantRow, RoleRow, RpcListResult } from './core/types';
import { RpcApiClient } from '../core/rpc-client';
import type { DictItem, MerchantRow } from '../core/types';
/** 下拉 / 字典 / 权限树公共接口。method 名逐字取自老 H5 源码。 */
class CommonApi extends RpcApiClient {
findAllDictData(dictType: string) {
return this.rpc<DictItem[]>('entmicro-account', 'merchants.api.menu.findAllDictData', {
dictType,
});
}
findAllMerchant() {
return this.rpc<MerchantRow[]>('entmicro-account', 'merchants.api.menu.findAllMerchant');
}
findMerchantTree(id?: string | number) {
return this.rpc<unknown>('entmicro-account', 'merchants.api.merchant.findMerchantTree', { id });
}
findMenuFunTreeByMerId(params: Record<string, unknown>) {
return this.rpc<unknown>(
'entmicro-account',
'merchants.api.merchant.findMenuFunTreeByMerId',
params,
);
}
findMenuFunTreeByRoleId(id: string | number) {
return this.rpc<unknown>('entmicro-account', 'merchants.api.merchant.findMenuFunTreeByRoleId', {
id,
});
}
getCarbrandTree() {
return this.rpc<unknown>('entmicro-account', 'merchants.api.merchantCommon.getCarbrandTree');
}
accountTypeSearchRequest(params: Record<string, unknown>) {
return this.rpc<unknown>(
'entmicro-account',
'merchants.api.merchant.accountTypeSearchRequest',
params,
);
}
findPermissionsByMerId(id: string | number) {
return this.rpc<unknown>('entmicro-account', 'merchants.api.merchant.findPermissionsByMerId', {
id,
});
}
roleList(id: string | number) {
return this.rpc<unknown>('entmicro-account', 'merchants.api.role.list', {
id,
delFlag: 0,
});
}
/**
* 老 request.js 的 isOtherUrl 分支:独立上传网关、app_key、MD5、file 不参与签名。
* file 的值逐字保留 `<扩展名>@<base64>` 拼法;不做任何本地 fetch / Blob 落地。
*/
uploadFile(file: string) {
return this.rpc<string>(
'account-upload',
'glsx.accounts.biz.common.pictureUpload',
{ file },
{ unsignedKeys: ['file'], noSession: true },
);
}
}
export const commonApi = new CommonApi();
import { RpcApiClient } from '../core/rpc-client';
import type { EmployeeRow, RpcListResult } from '../core/types';
/** 员工管理接口。method 与参数名逐字保留老 H5(html/employee/*.html)。 */
class EmployeeApi extends RpcApiClient {
findStaffByPage(params: Record<string, unknown> = {}) {
return this.rpc<RpcListResult<EmployeeRow>>(
'entmicro-account',
'merchants.api.staff.findStaffByPage',
params,
);
}
staffSearchRequest(id: string | number) {
return this.rpc<EmployeeRow>('entmicro-account', 'merchants.api.staff.staffSearchRequest', {
id,
});
}
saveStaff(params: Record<string, unknown>) {
return this.rpc<unknown>('entmicro-account', 'merchants.api.staff.saveStaff', params);
}
updateStaff(params: Record<string, unknown>) {
return this.rpc<unknown>('entmicro-account', 'merchants.api.staff.updateStaff', params);
}
deleteStaff(id: string | number) {
return this.rpc<unknown>('entmicro-account', 'merchants.api.staff.deleteStaff', { id });
}
updateStatus(params: Record<string, unknown>) {
return this.rpc<unknown>('entmicro-account', 'merchants.api.staff.updateStatus', params);
}
updateValPerByStaffId(params: Record<string, unknown>) {
return this.rpc<unknown>(
'entmicro-account',
'merchants.api.staff.updateValPerByStaffId',
params,
);
}
/** 返回后端给出的文件地址;页面必须交给 downloadCenter.url 登记,禁止 window.open。 */
exportData(params: Record<string, unknown>) {
return this.rpc<string>('entmicro-account', 'merchants.api.staff.exportData', params);
}
}
export const employeeApi = new EmployeeApi();
import { RpcApiClient } from '../core/rpc-client';
import type { EmployeeRow, MerchantRow, RpcListResult } from '../core/types';
/** 老系统「批量创建商户」弹窗的模板直链(html/merchant/index.html:735 逐字保留)。 */
export const MERCHANT_IMPORT_TEMPLATE_URL =
'https://img01.glsx.com.cn/weapp/resource/saas/scrm/xlsx/批量创建商户导入模版.xlsx';
/** 商户管理接口。method 与参数名逐字保留老 H5(html/merchant/*.html)。 */
class MerchantApi extends RpcApiClient {
findMerchantByPage(params: Record<string, unknown> = {}) {
return this.rpc<RpcListResult<MerchantRow>>(
'entmicro-account',
'merchants.api.menu.findMerchantByPage',
params,
);
}
findMerchantDetail(id: string | number) {
return this.rpc<MerchantRow>('entmicro-account', 'merchants.api.merchant.findMerchantDetail', {
id,
});
}
saveMerchant(params: Record<string, unknown>) {
return this.rpc<unknown>('entmicro-account', 'merchants.api.merchant.saveMerchant', params);
}
updateMerchant(params: Record<string, unknown>) {
return this.rpc<unknown>('entmicro-account', 'merchants.api.merchant.updateMerchant', params);
}
checkMerchantNameRepeat(merchantName: string) {
return this.rpc<unknown>('entmicro-account', 'merchants.api.merchant.checkMerchantNameRepeat', {
merchantName,
});
}
findSubordinateRelationship(id: string | number) {
return this.rpc<unknown>('entmicro-account', 'merchants.api.menu.findSubordinateRelationship', {
id,
});
}
findLog(params: Record<string, unknown>) {
return this.rpc<RpcListResult<unknown>>(
'entmicro-account',
'merchants.api.menu.findLog',
params,
);
}
updateValPerByMerId(params: Record<string, unknown>) {
return this.rpc<unknown>(
'entmicro-account',
'merchants.api.merchant.updateValPerByMerId',
params,
);
}
updateAccessMode(params: Record<string, unknown>) {
return this.rpc<unknown>('entmicro-account', 'merchants.api.merchant.updateAccessMode', params);
}
updatePermissions(params: Record<string, unknown>) {
return this.rpc<unknown>(
'entmicro-account',
'merchants.api.merchant.updatePermissions',
params,
);
}
/** 成功返回空;失败返回失败模版 URL(老系统用它替换「下载模板」链接)。 */
import(params: Record<string, unknown>) {
return this.rpc<string | null>('entmicro-account', 'merchants.api.merchant.import', params);
}
findMerchantStaffList(params: Record<string, unknown>) {
return this.rpc<EmployeeRow[]>(
'entmicro-account',
'merchants.api.staff.findMerchantStaffList',
params,
);
}
openFindMerchantListByPage(params: Record<string, unknown>) {
return this.rpc<RpcListResult<MerchantRow>>(
'entmicro-account',
'merchants.api.open.findMerchantListByPage',
params,
);
}
}
export const merchantApi = new MerchantApi();
import { RpcApiClient } from '../core/rpc-client';
import type { RoleRow, RpcListResult } from '../core/types';
/** 角色管理接口。method 与参数名逐字保留老 H5(html/role/*.html)。 */
class RoleApi extends RpcApiClient {
page(params: Record<string, unknown> = {}) {
return this.rpc<RpcListResult<RoleRow>>('entmicro-account', 'merchants.api.role.page', params);
}
insert(params: Record<string, unknown>) {
return this.rpc<unknown>('entmicro-account', 'merchants.api.role.insert', params);
}
update(params: Record<string, unknown>) {
return this.rpc<unknown>('entmicro-account', 'merchants.api.role.update', params);
}
deleteById(id: string | number) {
return this.rpc<unknown>('entmicro-account', 'merchants.api.role.deleteById', { id });
}
getById(id: string | number) {
return this.rpc<RoleRow>('entmicro-account', 'merchants.api.role.getById', { id });
}
}
export const roleApi = new RoleApi();
import { useQueries, useQuery } from '@tanstack/react-query';
import { commonApi } from '@/api';
import { dictOptions } from '@/utils/options';
import type { FieldOption } from '@/components';
/**
* 老系统的字典类型逐字保留(html/merchant/index.html 的 getDictData 调用)。
* 页面只声明自己要哪几份,单飞缓存由 react-query 承担。
*/
export const DICT = {
MERCHANT_STATUS: 'merchant_status',
CHANNEL: 'channel',
ACCOUNT_LEVEL: 'account_level',
ACCOUNT_TYPE: 'account_type',
MERCHANT_MODEL: 'merchant_model',
STAFF_STATUS: 'staff_status',
STAFF_DEPARTMENT: 'staff_department',
STAFF_VALIDITY_PERIOD: 'staff_validity_period',
ACCOUNT_VALIDITY_PERIOD: 'account_validity_period',
BUSINESS_TYPE: 'business_type',
} as const;
/** 返回「含全部」的下拉项,键为 dictType。 */
export function useDictionaries(types: readonly string[]): Record<string, FieldOption[]> {
const results = useQueries({
queries: types.map((dictType) => ({
queryKey: ['merchant', 'dict', dictType],
queryFn: () => commonApi.findAllDictData(dictType),
})),
});
return Object.fromEntries(
types.map((dictType, index) => [dictType, dictOptions(results[index]?.data, true)]),
);
}
/** 商户下拉:员工页与角色页共用,method 逐字来自 merchants.api.menu.findAllMerchant。 */
export function useMerchantOptions(): FieldOption[] {
const query = useQuery({
queryKey: ['merchant', 'allMerchant'],
queryFn: () => commonApi.findAllMerchant(),
});
return dictOptions(query.data);
}
/** 状态文案兜底:字典未下发时仍显示老系统钉死的枚举(request.js 注释逐字保留)。 */
export const MERCHANT_STATUS_LABEL: Record<string, string> = {
'1': '草稿',
'2': '正常',
'3': '注销',
'4': '过期',
};
export const MERCHANT_LEVEL_LABEL: Record<string, string> = {
'1': '工厂',
'2': '省代',
'3': '市代',
'4': '门店',
};
export const DEL_FLAG_LABEL: Record<string, string> = {
'0': '正常',
'1': '草稿',
};
export const CREATED_SOURCE_LABEL: Record<string, string> = {
'1': '账户中心',
'2': 'SCRM',
'3': '生意助手',
'4': '门店助手',
};
export const ACCOUNT_OR_PHONE_OPTIONS: FieldOption[] = [
{ label: '登录账号', value: '0' },
{ label: '手机号', value: '1' },
];
import { StrictMode } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { App } from './App';
import { installGlobalUnhandledRejectionHandler } from '@uj/ui';
import '@uj/design-tokens/tokens.css';
import './index.css';
installGlobalUnhandledRejectionHandler();
let root: Root | null = null;
/** wujie alive 模式下切路由会重复挂载,复用同一个 root 避免 createRoot 报错。 */
function render(): void {
const el = document.getElementById('root');
if (!el) throw new Error('Root container #root not found');
root?.unmount();
root = createRoot(el);
root.render(
<StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</StrictMode>,
);
}
if (window.__POWERED_BY_WUJIE__) {
window.__WUJIE_MOUNT = () => render();
window.__WUJIE_UNMOUNT = () => {
root?.unmount();
root = null;
};
} else {
render();
}
import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { UModal, URadio, useUMessage } from '@uj/ui';
import { merchantApi } from '@/api';
import type { MerchantRow } from '@/api';
import { errorDetail } from '@/utils/error';
/**
* 企微接入模式弹窗(源 accessModeForm.html):
* 3 应用代开发模式(SCRM非独立部署)/ 0 自建应用模式(SCRM需独立部署,且生成独立接口域名)。
* 源不回填当前值,未选择时提交给红字「请选择企微接入模式」。
*/
export function AccessModeModal({
row,
onClose,
onSaved,
}: {
row: MerchantRow;
onClose: () => void;
onSaved: () => void;
}) {
const message = useUMessage();
const [accessMode, setAccessMode] = useState('');
const [modeError, setModeError] = useState(false);
const update = useMutation({
mutationFn: (data: Record<string, unknown>) => merchantApi.updateAccessMode(data),
onSuccess: () => {
message.success('操作成功');
onSaved();
},
onError: (error) => message.error(errorDetail(error)),
});
return (
<UModal
title="接入模式"
open
onCancel={onClose}
onOk={() => {
if (!accessMode) {
setModeError(true);
return;
}
update.mutate({ id: row.id, accessMode });
}}
okButtonProps={{ loading: update.isPending }}
>
<div className="uj-period-modal">
<p className="uj-period-modal__row">商户名称:{row.merchantName ?? '-'}</p>
<URadio.Group
className="uj-period-modal__radios"
value={accessMode || undefined}
onChange={(event) => {
setAccessMode(String(event.target.value));
setModeError(false);
}}
>
<div className="uj-period-modal__radio-line">
<URadio value="3">应用代开发模式</URadio>
<span className="uj-hint">(SCRM非独立部署)</span>
</div>
<div className="uj-period-modal__radio-line">
<URadio value="0">自建应用模式</URadio>
<span className="uj-hint">(SCRM需独立部署,且生成独立接口域名)</span>
</div>
</URadio.Group>
{modeError ? <p className="uj-period-modal__error">请选择企微接入模式</p> : null}
</div>
</UModal>
);
}
import { useCallback, useEffect, useRef, useState } from 'react';
import { UAlert, UButton, UModal, useUMessage } from '@uj/ui';
import { buildMapFrameHtml, type MapFrameEvent, type MapFrameValue } from './mapFrame';
/**
* 源 temp/account/html/merchant/map.html 的选点流程移植。
*
* 地图本体跑在 srcdoc iframe(独立 realm)里,原因见 mapFrame.ts 头部:
* wujie 会劫持子应用动态 <script src> 走 fetch,百度 3.0 的 verify/风控脚本
* 无 CORS 头必失败;源 map.html 本身就是独立页面,iframe 才是对等运行环境。
* 这里只负责拿配置中心 apiUrl 与收发选点结果,与源页父窗口的
* helper.store('merchantMapObj') 对等(源 map.html:132)。
*/
/** 配置中心 map-api-js 地址,逐字取自源 js/glsk-mapapi-sdk.js(env=3 → production)。 */
const GLMAP_CONFIG_URL =
'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=map-api-js&env=production';
interface MapFrameWindow extends Window {
__ujMapCallback?: (event: MapFrameEvent) => void;
__ujMapFlush?: () => void;
}
let apiUrlPromise: Promise<string> | undefined;
function loadApiUrl(): Promise<string> {
if (!apiUrlPromise) {
apiUrlPromise = (async () => {
const response = await fetch(GLMAP_CONFIG_URL);
const config = (await response.json()) as { apiUrl?: string };
if (!config.apiUrl) throw new Error('配置中心 map-api-js 未下发 apiUrl');
return config.apiUrl;
})().catch((error: unknown) => {
apiUrlPromise = undefined;
throw error;
});
}
return apiUrlPromise;
}
export interface AddressValue {
merchantAddress?: string;
lat?: string;
lng?: string;
provinceName?: string;
cityName?: string;
}
interface AddressModalProps {
open: boolean;
initial?: AddressValue;
onOk: (value: AddressValue) => void;
onCancel: () => void;
}
export function AddressModal({ open, initial, onOk, onCancel }: AddressModalProps) {
const message = useUMessage();
const messageRef = useRef(message);
messageRef.current = message;
const frameRef = useRef<HTMLIFrameElement | null>(null);
const [frameHtml, setFrameHtml] = useState('');
const [error, setError] = useState('');
const valueRef = useRef<MapFrameValue | null>(null);
const handleFrameEvent = useCallback((event: MapFrameEvent) => {
switch (event.type) {
case 'change':
valueRef.current = event.payload;
break;
case 'warn':
messageRef.current.warning(event.payload.message);
break;
case 'error':
setError(event.payload.message);
break;
case 'ready':
break;
}
}, []);
// srcdoc iframe 的 parent 是主 window(wujie 非降级把 DOM 放在 shadowRoot),
// postMessage 到不了子应用执行 iframe window。改为 onLoad 时直接注入函数引用。
const handleFrameLoad = useCallback(() => {
const win = frameRef.current?.contentWindow as MapFrameWindow | null;
if (!win) return;
win.__ujMapCallback = handleFrameEvent;
win.__ujMapFlush?.();
}, [handleFrameEvent]);
useEffect(() => {
if (!open) return;
let cancelled = false;
setError('');
setFrameHtml('');
valueRef.current =
initial?.lat && initial?.lng
? {
lat: Number(initial.lat),
lng: Number(initial.lng),
merchantAddress: initial?.merchantAddress ?? '',
provinceName: initial?.provinceName ?? '',
cityName: initial?.cityName ?? '',
}
: null;
loadApiUrl()
.then((apiUrl) => {
if (cancelled) return;
setFrameHtml(
buildMapFrameHtml(apiUrl, {
lat: initial?.lat,
lng: initial?.lng,
merchantAddress: initial?.merchantAddress,
}),
);
})
.catch((loadError: unknown) => {
if (!cancelled)
setError(loadError instanceof Error ? loadError.message : String(loadError));
});
return () => {
cancelled = true;
};
}, [
open,
initial?.lat,
initial?.lng,
initial?.merchantAddress,
initial?.provinceName,
initial?.cityName,
]);
function confirm() {
const value = valueRef.current;
if (!value?.lat || !value?.lng || !value.merchantAddress.trim()) {
message.warning('请选择地址');
return;
}
onOk({
lat: value.lat.toFixed(6),
lng: value.lng.toFixed(6),
merchantAddress: value.merchantAddress.trim(),
provinceName: value.provinceName,
cityName: value.cityName,
});
}
return (
<UModal
className="uj-map-modal"
title="选择地址"
open={open}
width="min(1080px, 92vw)"
onCancel={onCancel}
footer={
<div className="uj-map-modal__footer">
<UButton onClick={onCancel}>取消</UButton>
<UButton type="primary" onClick={confirm}>
确定
</UButton>
</div>
}
>
{error ? <UAlert type="error" showIcon title="地图不可用" description={error} /> : null}
{frameHtml ? (
// srcdoc 变化(换初始坐标)时强制重建 iframe,避免沿用上一次的地图实例。
<iframe
ref={frameRef}
key={frameHtml}
title="地图选点"
srcDoc={frameHtml}
className="uj-create-address__frame"
onLoad={handleFrameLoad}
/>
) : null}
</UModal>
);
}
/**
* 省 / 市下拉的兜底数据。
*
* 源 add.html:1807-1874 从 external.provinceUrl 拉省市区列表,生成 provinceName / cityName
* 两个可编辑级联下拉。当前配置中心模块 uj-admin-merchant 未下发 provinceUrl,若完全不提供
* 选项,这两个下拉就只剩「点开但没有内容」,等同于不可用。这里按行政区划内置一份常用省市
* 作为兜底;字段口径仍是源里的 provinceName / cityName,字段名和联动行为(选省清空市与详细
* 地址,L1842/L1848-1849)不变。配置中心后续下发 provinceUrl 时,应改由接口数据覆盖此表。
*/
export const PROVINCES: string[] = [
'北京市',
'天津市',
'河北省',
'山西省',
'内蒙古自治区',
'辽宁省',
'吉林省',
'黑龙江省',
'上海市',
'江苏省',
'浙江省',
'安徽省',
'福建省',
'江西省',
'山东省',
'河南省',
'湖北省',
'湖南省',
'广东省',
'广西壮族自治区',
'海南省',
'重庆市',
'四川省',
'贵州省',
'云南省',
'西藏自治区',
'陕西省',
'甘肃省',
'青海省',
'宁夏回族自治区',
'新疆维吾尔自治区',
'香港特别行政区',
'澳门特别行政区',
'台湾省',
];
/** 只列常用地级市;未列出的城市仍可由地图选点反查回填。 */
const CITIES: Record<string, string[]> = {
北京市: ['北京市'],
天津市: ['天津市'],
上海市: ['上海市'],
重庆市: ['重庆市'],
河北省: ['石家庄市', '唐山市', '秦皇岛市', '邯郸市', '保定市', '廊坊市'],
山西省: ['太原市', '大同市', '阳泉市', '长治市', '晋中市'],
内蒙古自治区: ['呼和浩特市', '包头市', '赤峰市', '鄂尔多斯市'],
辽宁省: ['沈阳市', '大连市', '鞍山市', '抚顺市', '锦州市'],
吉林省: ['长春市', '吉林市', '四平市', '延边朝鲜族自治州'],
黑龙江省: ['哈尔滨市', '齐齐哈尔市', '牡丹江市', '大庆市'],
江苏省: ['南京市', '无锡市', '徐州市', '常州市', '苏州市', '南通市'],
浙江省: ['杭州市', '宁波市', '温州市', '嘉兴市', '金华市', '绍兴市'],
安徽省: ['合肥市', '芜湖市', '蚌埠市', '安庆市', '滁州市'],
福建省: ['福州市', '厦门市', '莆田市', '泉州市', '漳州市'],
江西省: ['南昌市', '景德镇市', '萍乡市', '九江市', '赣州市'],
山东省: ['济南市', '青岛市', '淄博市', '烟台市', '潍坊市', '济宁市'],
河南省: ['郑州市', '开封市', '洛阳市', '新乡市', '南阳市'],
湖北省: ['武汉市', '黄石市', '宜昌市', '襄阳市', '荆州市'],
湖南省: ['长沙市', '株洲市', '湘潭市', '衡阳市', '岳阳市'],
广东省: ['广州市', '深圳市', '珠海市', '佛山市', '东莞市', '中山市', '惠州市'],
广西壮族自治区: ['南宁市', '柳州市', '桂林市', '北海市', '玉林市'],
海南省: ['海口市', '三亚市', '儋州市'],
四川省: ['成都市', '自贡市', '绵阳市', '德阳市', '宜宾市'],
贵州省: ['贵阳市', '六盘水市', '遵义市', '安顺市'],
云南省: ['昆明市', '曲靖市', '玉溪市', '大理白族自治州'],
西藏自治区: ['拉萨市', '日喀则市', '昌都市'],
陕西省: ['西安市', '宝鸡市', '咸阳市', '渭南市'],
甘肃省: ['兰州市', '嘉峪关市', '金昌市', '天水市'],
青海省: ['西宁市', '海东市'],
宁夏回族自治区: ['银川市', '石嘴山市', '吴忠市'],
新疆维吾尔自治区: ['乌鲁木齐市', '克拉玛依市', '吐鲁番市', '哈密市'],
香港特别行政区: ['香港'],
澳门特别行政区: ['澳门'],
台湾省: ['台北市', '高雄市', '台中市', '台南市'],
};
export function citiesOf(province?: string): string[] {
if (!province) return [];
const direct = CITIES[province];
if (direct) return direct;
// 地图反查可能给出简称(广东 / 内蒙古),按行政后缀归一后再匹配一次,
// 否则省虽然回填了、市下拉仍是空的。
const short = (name: string) => name.replace(/(省|市|自治区|特别行政区)$/, '');
const matched = Object.keys(CITIES).find((name) => short(name) === short(province));
return matched ? CITIES[matched] : [];
}
import type { ReactNode } from 'react';
interface SectionTitleProps {
children: ReactNode;
index?: string;
description?: string;
}
/** 分区标题:序号徽章 + 标题 + 说明,给长表单建立清晰的视觉层级。 */
export function SectionTitle({ children, index, description }: SectionTitleProps) {
return (
<div className="uj-section-head">
{index ? <span className="uj-section-head__index">{index}</span> : null}
<div className="uj-section-head__text">
<h3 className="uj-section-head__title">{children}</h3>
{description ? <p className="uj-section-head__desc">{description}</p> : null}
</div>
</div>
);
}
import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { UButton, UDatePicker, UModal, URadio, useUMessage } from '@uj/ui';
import dayjs from 'dayjs';
import { merchantApi } from '@/api';
import type { MerchantRow } from '@/api';
import { errorDetail } from '@/utils/error';
/**
* 有效期管理弹窗(源 validPeriodForm.html,弹窗打开即挂载一次,状态从行数据初始化)。
*
* 门店(等级 4):双日期 + 5 个快捷续期按钮;起算点取 max(原到期日, 今天),
* 未过期时开始日期锁定(源 #effectiveStarttime 仅 overdue 才 removeAttr('disabled'))。
* 非门店:启用(2)/禁用(4) radio,初始值 = 行 status;下方文案随选项切换(源 setText L289-295)。
*/
export function PeriodModal({
row,
onClose,
onSaved,
}: {
row: MerchantRow;
onClose: () => void;
onSaved: () => void;
}) {
const message = useUMessage();
const isStore = String(row.merchantAccountLevel ?? '') === '4';
const text = (value: unknown) => {
const s = String(value ?? '');
return s && s !== '-' ? s : '';
};
const initialStart = text(row.effectiveStarttime);
const initialEnd = text(row.expireDate);
const hasDates = Boolean(initialStart && initialEnd);
const today = dayjs().startOf('day');
// 源 getStartTime L297-311:到期日晚于当前时间则以到期日起算,否则视为已过期。
const overdue = !hasDates || !dayjs(initialEnd).isAfter(dayjs());
const [start, setStart] = useState(initialStart);
const [end, setEnd] = useState(initialEnd);
const [effectiveTime, setEffectiveTime] = useState(text(row.status));
const update = useMutation({
mutationFn: (data: Record<string, unknown>) => merchantApi.updateValPerByMerId(data),
onSuccess: () => {
message.success('操作成功');
onSaved();
},
onError: (error) => message.error(errorDetail(error)),
});
const applyQuick = (years: number) => {
const origin = overdue ? today : dayjs(initialEnd).startOf('day');
const nextEnd = years ? origin.add(years, 'year') : origin.add(7, 'day');
if (overdue) setStart(today.format('YYYY-MM-DD'));
setEnd(nextEnd.format('YYYY-MM-DD'));
};
const onOk = () => {
if (isStore) {
if (!start || !end) {
message.warning('请选择账户有效期');
return;
}
update.mutate({ id: row.id, effectiveStarttime: start, expireDate: end });
return;
}
if (!effectiveTime) {
message.warning('请选择账户有效期');
return;
}
update.mutate({ id: row.id, effectiveTime });
};
return (
<UModal
title="修改账户有效期"
open
onCancel={onClose}
onOk={onOk}
okButtonProps={{ loading: update.isPending }}
>
<div className="uj-period-modal">
<p className="uj-period-modal__row">
商户名称:{row.merchantName ?? '-'}(商户号 {row.merchantNo ?? '-'})
</p>
{isStore ? (
<>
<div className="uj-validity">
<UDatePicker
value={start ? dayjs(start) : null}
disabled={!overdue && hasDates}
minDate={today}
placeholder="开始时间"
onChange={(next) => {
// 源 laydate done L167-174:改开始时间即清空结束时间。
const d = Array.isArray(next) ? next[0] : next;
setStart(d ? d.format('YYYY-MM-DD') : '');
setEnd('');
}}
/>
<span className="uj-time__sep">—</span>
<UDatePicker
value={end ? dayjs(end) : null}
minDate={start ? dayjs(start).add(1, 'day') : today.add(1, 'day')}
placeholder="结束时间"
onChange={(next) => {
const d = Array.isArray(next) ? next[0] : next;
setEnd(d ? d.format('YYYY-MM-DD') : '');
}}
/>
</div>
<div className="uj-period-modal__quick">
<UButton size="small" onClick={() => applyQuick(0)}>
续7天
</UButton>
<UButton size="small" onClick={() => applyQuick(1)}>
续1年
</UButton>
<UButton size="small" onClick={() => applyQuick(2)}>
续2年
</UButton>
<UButton size="small" onClick={() => applyQuick(5)}>
续5年
</UButton>
<UButton size="small" onClick={() => applyQuick(10)}>
续10年
</UButton>
{overdue && hasDates ? (
<span className="uj-hint">该账户已过期,续期从今天起算</span>
) : null}
</div>
</>
) : (
<>
<URadio.Group
className="uj-period-modal__radios"
value={effectiveTime || undefined}
onChange={(event) => setEffectiveTime(String(event.target.value))}
>
<URadio value="2">启用</URadio>
<URadio value="4">禁用</URadio>
</URadio.Group>
<p className="uj-hint">
{effectiveTime === '2'
? '启用商户,其下级商户也会启用,但门店账户由门店本身的有效期控制。'
: effectiveTime === '4'
? '禁用商户,其下级商户及门店全部禁止登录。'
: '请选择启用或禁用。'}
</p>
</>
)}
</div>
</UModal>
);
}
/**
* 商户管理域权限码表(本子应用独占)。
*
* 逐字对应 scripts/merchant-menu-migration.sql 的 perm_code 列:
* 3 个页面 :view(menu_type=2)+ 19 个动作(menu_type=3),域前缀 merchant:。
* 老 H5 没有权限码概念(按钮由行数据字段控制),这里按现系统 `资源:动作` 格式新定义,
* 动作名逐字取自老系统页面按钮;判定见 adapter/perms.ts 的三态闸门。
*/
export const MC = {
// 商户管理 1002801
MERCHANT_VIEW: 'merchant:merchant:view',
MERCHANT_CREATE: 'merchant:merchant:create',
MERCHANT_EDIT: 'merchant:merchant:edit',
MERCHANT_DETAIL: 'merchant:merchant:detail',
MERCHANT_CREATE_SUB: 'merchant:merchant:create-sub',
MERCHANT_CREATE_STAFF: 'merchant:merchant:create-staff',
MERCHANT_EDIT_PERIOD: 'merchant:merchant:edit-period',
MERCHANT_EDIT_ACCESS_MODE: 'merchant:merchant:edit-access-mode',
MERCHANT_IMPORT: 'merchant:merchant:import',
// 员工管理 1002802
EMPLOYEE_VIEW: 'merchant:employee:view',
EMPLOYEE_CREATE: 'merchant:employee:create',
EMPLOYEE_EDIT: 'merchant:employee:edit',
EMPLOYEE_DETAIL: 'merchant:employee:detail',
EMPLOYEE_DELETE: 'merchant:employee:delete',
EMPLOYEE_TOGGLE_STATUS: 'merchant:employee:toggle-status',
EMPLOYEE_EDIT_PERIOD: 'merchant:employee:edit-period',
EMPLOYEE_EXPORT: 'merchant:employee:export',
// 角色管理 1002803
ROLE_VIEW: 'merchant:role:view',
ROLE_CREATE: 'merchant:role:create',
ROLE_EDIT: 'merchant:role:edit',
ROLE_DETAIL: 'merchant:role:detail',
ROLE_DELETE: 'merchant:role:delete',
} as const;
export type PermissionCode = (typeof MC)[keyof typeof MC];
import type { ComponentType } from 'react';
/** 路径参数全部是字符串(来自主壳下发的 subPath),页面自己按需 Number()。 */
export type PageParams = Record<string, string>;
export interface RouteDef {
/** 相对子应用首段的路径,全小写,不含查询串。 */
path: string;
Page: ComponentType<{ params: PageParams }>;
}
export interface MatchedRoute {
Page: RouteDef['Page'];
params: PageParams;
}
/** 按段匹配;空 subPath 落第一条,未知路径由 App 渲染明确错误页。 */
export function matchRoute(routes: RouteDef[], subPath: string): MatchedRoute | undefined {
const segments = subPath
.split('/')
.filter(Boolean)
.map((segment) => {
try {
return decodeURIComponent(segment);
} catch {
return segment;
}
});
if (!segments.length) {
const first = routes[0];
return first ? { Page: first.Page, params: {} } : undefined;
}
for (const route of routes) {
const pattern = route.path.split('/').filter(Boolean);
if (pattern.length !== segments.length) continue;
const params: PageParams = {};
const matched = pattern.every((segment, index) => {
if (!segment.startsWith(':')) return segment === segments[index];
params[segment.slice(1)] = segments[index];
return true;
});
if (matched) return { Page: route.Page, params };
}
return undefined;
}
# 主题
本子应用不自定义主题。色彩来自 `@uj/design-tokens` 的 `palette.ts` / `tokens.css`,
根节点带 `uj-scope`(见 `src/App.tsx`),禁止页面内写死颜色。
此目录保留为别名 `@/theme/*` 的落点,与 finance 等子应用一致。
/** 与 finance/points 同款:只有 window.$wujie 持有 props 与 bus。 */
export {};
declare global {
interface WujieBus {
$on: (event: string, handler: (...args: unknown[]) => void) => void;
$off: (event: string, handler: (...args: unknown[]) => void) => void;
$emit: (event: string, ...args: unknown[]) => void;
}
interface Window {
$wujie?: { bus: WujieBus; props?: Record<string, unknown> };
__POWERED_BY_WUJIE__?: boolean;
__WUJIE_MOUNT?: () => void;
__WUJIE_UNMOUNT?: () => void;
}
}
{
"extends": "../../../../packages/typescript-config/react-app.json",
"compilerOptions": {
"paths": {
"@/api/core": ["../../../../packages/platform-sdk/src/compat/api-core/index.ts"],
"@/api/core/*": ["../../../../packages/platform-sdk/src/compat/api-core/*"],
"@/access": ["../../../../packages/platform-sdk/src/compat/access/index.ts"],
"@/access/*": ["../../../../packages/platform-sdk/src/compat/access/*"],
"@/store/*": ["../../../../packages/platform-sdk/src/compat/store/*"],
"@/queryClient": ["../../../../packages/platform-sdk/src/compat/queryClient.ts"],
"@/theme/themeConfig": ["../../../../packages/design-tokens/src/themeConfig.ts"],
"@/components": ["../../../../packages/biz/src/components/index.ts"],
"@/components/*": ["../../../../packages/biz/src/components/*"],
"@/constants/*": ["../../../../packages/biz/src/constants/*"],
"@/config/*": ["../../../../packages/biz/src/config/*"],
"@/utils": ["../../../../packages/biz/src/utils/index.ts"],
"@/utils/*": ["../../../../packages/biz/src/utils/*"],
"@/api": ["./src/api/index.ts"],
"@/api/*": ["./src/api/*"],
"@/theme/*": ["./src/theme/*"],
"@uj/ui": ["../../../../packages/ui/src/index.ts"],
"@uj/contracts": ["../../../../packages/contracts/src/index.ts"],
"@uj/platform-core": ["../../../../packages/platform-core/src/index.ts"],
"@uj/platform-sdk": ["../../../../packages/platform-sdk/src/index.ts"],
"@uj/biz": ["../../../../packages/biz/src/index.ts"],
"@uj/design-tokens": ["../../../../packages/design-tokens/src/index.ts"],
"@uj/api-core": ["../../../../packages/api-core/src/index.ts"],
"@/*": ["./src/*"]
}
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.d.ts", "vite.config.ts"]
}
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createWebAppConfig } from '@uj/vite-config/react';
const appDir = path.dirname(fileURLToPath(import.meta.url));
/**
* merchant(商户管理)子应用构建配置。
* 端口 5179:system 5174 / store 5175 / points 5176 / usedcar 5177 / finance 5178 已占用,
* 工厂开了 strictPort;这里与 package.json 的 uj.entry 必须一致(reconcile 会校验)。
*/
export default createWebAppConfig({ appDir, port: 5179 });
...@@ -19,6 +19,8 @@ export default [ ...@@ -19,6 +19,8 @@ export default [
'**/miniprogram_dist/**', '**/miniprogram_dist/**',
'**/node_modules/**', '**/node_modules/**',
'**/.turbo/**', '**/.turbo/**',
// .tmp 是已 gitignore 的临时产物目录(如 dc-sim-bundle.cjs),不是源码。
'**/.tmp/**',
'**/coverage/**', '**/coverage/**',
'.release/**', '.release/**',
'**/temp/**', '**/temp/**',
......
...@@ -26,6 +26,12 @@ export interface RpcCall { ...@@ -26,6 +26,12 @@ export interface RpcCall {
signed?: boolean; signed?: boolean;
/** 参与请求但不进签名原文的参数名(老系统的 noSignAttr,文件 Base64 这类大字段) */ /** 参与请求但不进签名原文的参数名(老系统的 noSignAttr,文件 Base64 这类大字段) */
unsignedKeys?: string[]; unsignedKeys?: string[];
/**
* 该接口是否跳过会话注入;缺省注入。
* 老系统的文件上传网关不认识业务会话字段,注入会同时污染签名原文。
* 这是与 signed 同级的单次开关,网关策略与既有调用都不用改。
*/
noSession?: boolean;
} }
/** 签名入参:平铺到方法名级别的字段,签名器自己决定取哪些。 */ /** 签名入参:平铺到方法名级别的字段,签名器自己决定取哪些。 */
...@@ -94,6 +100,12 @@ export interface GatewayStrategy { ...@@ -94,6 +100,12 @@ export interface GatewayStrategy {
router: string; router: string;
/** 会话令牌放哪个请求头:scrm 用 token,dj 用 TGT */ /** 会话令牌放哪个请求头:scrm 用 token,dj 用 TGT */
tokenHeader: string; tokenHeader: string;
/**
* 额外的请求头策略 id 列表(按声明顺序执行、后者可覆盖前者)。
* 用于「头值来自会话/凭据、且不止一个头」的系统;老网关不声明即行为不变。
* 策略注册表见 gateway/headers.ts,勿与 tokenHeader 表达同一个头。
*/
headerProviders?: string[];
/** 签名策略 */ /** 签名策略 */
signer: Signer; signer: Signer;
/** 返回值映射:把该系统的响应包归一成主壳拦截器认得的形状 */ /** 返回值映射:把该系统的响应包归一成主壳拦截器认得的形状 */
...@@ -140,6 +152,8 @@ export interface RawRequest { ...@@ -140,6 +152,8 @@ export interface RawRequest {
response?: ResponseOptions; response?: ResponseOptions;
/** 中止信号:由门面创建,一路透到 axios / fetch;页面切换或相同请求取代时触发。 */ /** 中止信号:由门面创建,一路透到 axios / fetch;页面切换或相同请求取代时触发。 */
signal?: AbortSignal; signal?: AbortSignal;
/** 宿主策略 id(transport==='host' 时生效):由策略决定关闭哪些主壳公共逻辑。 */
hostPolicy?: string;
} }
/** /**
......
...@@ -5,6 +5,7 @@ import type { ...@@ -5,6 +5,7 @@ import type {
RpcCall, RpcCall,
RequestSender, RequestSender,
} from '../core/types'; } from '../core/types';
import { applyHeaderProviders } from './headers';
import { resolveGateway } from './registry'; import { resolveGateway } from './registry';
/** 网关归一后的失败:携带后端语义码,便于上层按 10002 等做登出 / 提示。 */ /** 网关归一后的失败:携带后端语义码,便于上层按 10002 等做登出 / 提示。 */
...@@ -92,7 +93,7 @@ export async function prepareRpcCall(call: RpcCall, deps: RpcPrepareDeps): Promi ...@@ -92,7 +93,7 @@ export async function prepareRpcCall(call: RpcCall, deps: RpcPrepareDeps): Promi
const effectiveParams = flattenFormParams({ const effectiveParams = flattenFormParams({
...strategy.fixedParams, ...strategy.fixedParams,
...call.params, ...call.params,
...(deps.session && !call.params[deps.session.name] ...(deps.session && !call.noSession && !call.params[deps.session.name]
? { [deps.session.name]: deps.session.value } ? { [deps.session.name]: deps.session.value }
: {}), : {}),
}); });
...@@ -122,6 +123,18 @@ export async function prepareRpcCall(call: RpcCall, deps: RpcPrepareDeps): Promi ...@@ -122,6 +123,18 @@ export async function prepareRpcCall(call: RpcCall, deps: RpcPrepareDeps): Promi
const token = deps.resolveToken?.() ?? ''; const token = deps.resolveToken?.() ?? '';
const origin = credential.origin.replace(/\/+$/, ''); const origin = credential.origin.replace(/\/+$/, '');
// 扩展点:网关声明的头策略在基础头之后合并,同名由策略覆盖。
// 未声明 headerProviders 时 applyHeaderProviders 返回空对象,既有网关的字节完全不变。
// noSession 是单次调用的「无会话」语义:既不加会话参数,也不执行依赖会话的头策略,
// 否则上传这类免会话网关会因为 required 头策略而误报「会话为空」。
const extraHeaders = call.noSession
? {}
: await applyHeaderProviders(strategy.headerProviders, {
gateway: call.gateway,
token,
credential,
session: deps.session,
});
return { return {
method: 'POST', method: 'POST',
url: `${origin}/${strategy.router.replace(/^\/+/, '')}`, url: `${origin}/${strategy.router.replace(/^\/+/, '')}`,
...@@ -132,6 +145,7 @@ export async function prepareRpcCall(call: RpcCall, deps: RpcPrepareDeps): Promi ...@@ -132,6 +145,7 @@ export async function prepareRpcCall(call: RpcCall, deps: RpcPrepareDeps): Promi
headers: { headers: {
'content-type': 'application/x-www-form-urlencoded', 'content-type': 'application/x-www-form-urlencoded',
...(token ? { [strategy.tokenHeader]: token } : {}), ...(token ? { [strategy.tokenHeader]: token } : {}),
...extraHeaders,
}, },
timeout: deps.timeout, timeout: deps.timeout,
normalize: strategy.normalize, normalize: strategy.normalize,
......
import type { GatewayCredential } from '../core/types';
/**
* 网关请求头策略 —— 对「某系统要求额外的头、头值来自会话/凭据」这一变化点做隔离。
*
* 设计取舍:
* - 策略模式:每种头怎么取值由 provider 自己实现,dispatcher 不认识任何具体系统;
* - 注册表模式:新系统接新头 = registerHeaderProvider 一次 + 网关策略声明 id,
* 不改 dispatcher / facade / sender / signer(开闭原则的「对扩展开放、对修改关闭」);
* - 责任链:按网关声明的顺序依次产出并覆盖合并,后者可显式覆盖前者;
* - 工厂:createSessionHeaderProvider 把「会话值 → 指定头名」这一类需求参数化,
* TGT 只是其中一个实例,不是写死在核心里的常量。
*
* 与既有 tokenHeader 的关系:tokenHeader 是单令牌头的老通道,行为逐字不变;
* headerProviders 是它之外的扩展通道。两者不要用来表达同一个头。
*/
export interface GatewayHeaderContext {
/** 网关 id,供报错信息定位。 */
gateway: string;
/** dispatcher 解析出的令牌(tokenHeader 通道的值),provider 可按需使用。 */
token: string;
/** 本网关运行时凭据;provider 不持有任何密钥字面量。 */
credential: GatewayCredential;
/** 门面解析出的会话字段(name 通常为 sessionId,value 即 points 用的那一份会话)。 */
session?: { name: string; value: string };
}
/** 一次请求头贡献:返回要合并进 RawRequest.headers 的键值对。 */
export interface GatewayHeaderProvider {
id: string;
headers(context: GatewayHeaderContext): Record<string, string> | Promise<Record<string, string>>;
}
const providers = new Map<string, GatewayHeaderProvider>();
/** 注册(或按 id 覆盖)一个头策略。 */
export function registerHeaderProvider(provider: GatewayHeaderProvider): void {
providers.set(provider.id, provider);
}
export function resolveHeaderProvider(id: string): GatewayHeaderProvider {
const provider = providers.get(id);
if (!provider) {
throw new Error(
`请求头策略「${id}」尚未注册:请调用 registerHeaderProvider 登记后再在网关策略中引用。`,
);
}
return provider;
}
export function listHeaderProviders(): string[] {
return [...providers.keys()];
}
/**
* 按声明顺序执行策略并合并结果;同名头由后声明者覆盖。
* 空数组直接返回空对象,因此未声明该能力的既有网关字节不变。
*/
export async function applyHeaderProviders(
ids: string[] | undefined,
context: GatewayHeaderContext,
): Promise<Record<string, string>> {
const headers: Record<string, string> = {};
for (const id of ids ?? []) {
Object.assign(headers, await Promise.resolve(resolveHeaderProvider(id).headers(context)));
}
return headers;
}
export interface SessionHeaderProviderOptions {
/** 注册名,供网关策略的 headerProviders 引用。 */
id: string;
/** 要写入的请求头名,逐字保留老系统写法(如全大写 TGT)。 */
header: string;
/** 缺值时是否抛错;默认抛错,避免静默发出一个必然鉴权失败的请求。 */
required?: boolean;
}
/**
* 「把会话值放进指定请求头」的通用策略工厂。
*
* 会话值由消费方在 createClient({ session: {...} }) 注入,api-core 只负责搬运:
* 因此子应用换成哪一份会话、值从配置中心还是登录态取,都不需要改这里。
*/
export function createSessionHeaderProvider(
options: SessionHeaderProviderOptions,
): GatewayHeaderProvider {
return {
id: options.id,
headers(context) {
const value = context.session?.value ?? '';
if (!value && options.required !== false) {
throw new Error(
`网关 ${context.gateway} 需要请求头 ${options.header},但会话 ${context.session?.name ?? 'sessionId'} 为空;请检查登录态与会话注入配置。`,
);
}
return value ? { [options.header]: value } : {};
},
};
}
// 内建实例:账户中心老 H5 的全大写 TGT 头。值由消费方注入的 session 决定。
registerHeaderProvider(createSessionHeaderProvider({ id: 'tgt-session', header: 'TGT' }));
...@@ -31,6 +31,19 @@ export type { ...@@ -31,6 +31,19 @@ export type {
} from './core/types'; } from './core/types';
export { registerGateway, resolveGateway } from './gateway/registry'; export { registerGateway, resolveGateway } from './gateway/registry';
// 网关请求头策略:注册式扩展点,新增头不改 dispatcher / sender / signer。
export {
applyHeaderProviders,
createSessionHeaderProvider,
listHeaderProviders,
registerHeaderProvider,
resolveHeaderProvider,
} from './gateway/headers';
export type {
GatewayHeaderContext,
GatewayHeaderProvider,
SessionHeaderProviderOptions,
} from './gateway/headers';
export { export {
createRpcDispatcher, createRpcDispatcher,
flattenFormParams, flattenFormParams,
...@@ -50,6 +63,16 @@ export { ...@@ -50,6 +63,16 @@ export {
} from './transport/senders'; } from './transport/senders';
export type { HostRequestConfig, HostSendFn } from './transport/senders'; export type { HostRequestConfig, HostSendFn } from './transport/senders';
// 宿主策略:注册式扩展点,新增一类外部网关不改 sender / 主壳 / 业务子应用。
export {
defaultHostPolicy,
legacyExternalHostPolicy,
listHostPolicies,
registerHostPolicy,
resolveHostPolicy,
} from './transport/hostPolicies';
export type { HostPolicy } from './transport/hostPolicies';
// 【统一门面 1/3】签名器:所有算法 / 预设都通过参数确定。 // 【统一门面 1/3】签名器:所有算法 / 预设都通过参数确定。
export { createSigner } from './signing/signers'; export { createSigner } from './signing/signers';
export type { export type {
......
import type { HostRequestConfig } from './senders';
/**
* 宿主策略:在请求交给主壳 `props.request` 之前,声明这次请求要关闭哪些主壳公共逻辑。
*
* 主壳的公共逻辑(RSA 请求头 / Bearer 令牌 / 响应验签 / ApiResult 业务码拦截)是为自家
* REST 网关设计的。接入外部老网关时,这些逻辑不是「配置一下就行」,而是会直接破坏协议:
* RSA 头不在对方 CORS 白名单里、Bearer 不是对方的鉴权方式、code:'0' 会被主壳误判为失败。
*
* 与其在每个子应用里散落 `_skipHostSignature` 之类的布尔开关,这里把它们收成一份可注册
* 的策略:消费层只声明策略名,新增一类网关 = 注册一个新策略,sender 与主壳都不用改。
*/
export interface HostPolicy {
id: string;
/** 返回一个新的请求配置;不要原地修改入参。 */
apply(config: HostRequestConfig): HostRequestConfig;
}
const registry = new Map<string, HostPolicy>();
/** 注册宿主策略;同名覆盖视为配置错误,避免两个真源悄悄打架。 */
export function registerHostPolicy(policy: HostPolicy): void {
if (!policy?.id) throw new Error('宿主策略必须提供 id。');
if (registry.has(policy.id)) throw new Error(`宿主策略 ${policy.id} 已注册。`);
registry.set(policy.id, policy);
}
export function resolveHostPolicy(id = 'default'): HostPolicy {
const policy = registry.get(id);
if (!policy) {
throw new Error(`宿主策略 ${id} 尚未注册。可用策略:${listHostPolicies().join('、')}`);
}
return policy;
}
export function listHostPolicies(): string[] {
return [...registry.keys()];
}
/** 默认策略:完全沿用主壳公共逻辑,行为与注册机制引入前逐字节一致。 */
export const defaultHostPolicy: HostPolicy = {
id: 'default',
apply: (config) => config,
};
/**
* 老外部网关专用策略:把请求交回主壳 axios 发送,但关掉主壳为自家网关准备的那套语义。
*
* 三个开关各管一段,缺一不可:
* - `_skipHostSignature`:主壳改用 signature:'none',不再注入 X-App-Id / X-Timestamp /
* X-Nonce / X-Sign / X-Sign-Algorithm。老 ROP 网关的 CORS 白名单只认 TGT,多一个头就预检失败。
* - `_skipAuthorization`:主壳不注入 Bearer;老网关用 TGT(由 api-core 头策略注入)鉴权。
* 业务码 / 登出码**仍由主壳判**:网关策略的 normalize 把对方信封翻成主壳认得的形状
* (成功 `{ data }`、失效 `code:401`),主壳的 onLoginRequired 因此能清令牌并跳登录页。
* 不设 `_noVerify` 是刻意的 —— 一旦 returnAll,主壳就不再判登出码,子应用只能自己广播
* bus 请求登出;那条链路跨 wujie 沙箱,且绕开了主壳的 clearToken 与 RequireAuth 重定向。
* 老网关响应没有 `X-Sign` 头,RSA 验签器按既有规则直接放行,不会因此失败。
*
* 注意这里**没有**绕过主壳的 axios 实例:请求仍然走 props.request,超时、取消、日志、
* 代理和唯一一份传输层都保持统一;被关掉的只是这套特定网关不适用的公共逻辑。
*/
export const legacyExternalHostPolicy: HostPolicy = {
id: 'legacy-external',
apply: (config) => ({
...config,
_skipHostSignature: true,
_skipAuthorization: true,
}),
};
registerHostPolicy(defaultHostPolicy);
registerHostPolicy(legacyExternalHostPolicy);
import type { HttpMethod } from '@uj/contracts'; import type { HttpMethod } from '@uj/contracts';
import type { RawRequest, RawResponse, RequestSender } from '../core/types'; import type { RawRequest, RawResponse, RequestSender } from '../core/types';
import { resolveHostPolicy, type HostPolicy } from './hostPolicies';
import '../core/polyfill'; import '../core/polyfill';
/** /**
...@@ -52,23 +53,32 @@ function mergeSignal(...signals: Array<AbortSignal | undefined>): AbortSignal | ...@@ -52,23 +53,32 @@ function mergeSignal(...signals: Array<AbortSignal | undefined>): AbortSignal |
* 这是「请求层绝不下放」在 web 子应用的唯一正确接法:子应用不打包 axios / 签名 / PEM, * 这是「请求层绝不下放」在 web 子应用的唯一正确接法:子应用不打包 axios / 签名 / PEM,
* 把请求交回主壳那唯一一份 axios 实例。原生小程序则走下面的 wx / uni / fetch sender。 * 把请求交回主壳那唯一一份 axios 实例。原生小程序则走下面的 wx / uni / fetch sender。
*/ */
export function createHostSender(send: HostSendFn): RequestSender { export function createHostSender(send: HostSendFn, policy?: string | HostPolicy): RequestSender {
// 未声明时走默认策略:主壳公共逻辑一字不动,既有子应用行为不变。
const resolved =
typeof policy === 'string' ? resolveHostPolicy(policy) : (policy ?? resolveHostPolicy());
return { return {
async send(req: RawRequest): Promise<RawResponse> { async send(req: RawRequest): Promise<RawResponse> {
const res = (await send({ const config = resolved.apply({
method: req.method, method: req.method,
url: req.url, url: req.url,
data: req.data, data: req.data,
headers: req.headers, headers: req.headers,
timeout: req.timeout, timeout: req.timeout,
withCredentials: true, withCredentials: req.withCredentials ?? true,
responseType: req.responseType, responseType: req.responseType,
signal: req.signal, signal: req.signal,
transformResponse: req.transformResponse transformResponse:
?? (req.normalize req.transformResponse ??
(req.normalize
? [req.normalize as (raw: unknown, headers: Record<string, string>) => unknown] ? [req.normalize as (raw: unknown, headers: Record<string, string>) => unknown]
: undefined), : undefined),
})) as { status?: number; data: unknown; headers?: Record<string, string> }; });
const res = (await send(config)) as {
status?: number;
data: unknown;
headers?: Record<string, string>;
};
return { status: res?.status ?? 200, data: res?.data, headers: res?.headers }; return { status: res?.status ?? 200, data: res?.data, headers: res?.headers };
}, },
}; };
...@@ -181,7 +191,9 @@ export function createFetchSender(init?: RequestInit): RequestSender { ...@@ -181,7 +191,9 @@ export function createFetchSender(init?: RequestInit): RequestSender {
const contentType = req.headers const contentType = req.headers
? new Headers(req.headers as HeadersInit).get('content-type') ? new Headers(req.headers as HeadersInit).get('content-type')
: null; : null;
const isForm = (contentType ?? '').toLowerCase().includes('application/x-www-form-urlencoded'); const isForm = (contentType ?? '')
.toLowerCase()
.includes('application/x-www-form-urlencoded');
const body = const body =
req.data == null req.data == null
? undefined ? undefined
......
...@@ -20,6 +20,12 @@ const { ...@@ -20,6 +20,12 @@ const {
createSigner, createSigner,
RequestError, RequestError,
registerGateway, registerGateway,
registerHeaderProvider,
createSessionHeaderProvider,
createClient,
createHostSender,
registerHostPolicy,
resolveHostPolicy,
prepareRpcCall, prepareRpcCall,
createRpcDispatcher, createRpcDispatcher,
} = core; } = core;
...@@ -632,7 +638,230 @@ test('ST-RPC-009 双层门面:主壳按自身码判失败后,子应用仍能 ...@@ -632,7 +638,230 @@ test('ST-RPC-009 双层门面:主壳按自身码判失败后,子应用仍能
}), }),
); );
await assert.rejects(() => api.post('m.missing.session', {}, { gateway: 'st-rpc' }), /Missing Session/); await assert.rejects(
() => api.post('m.missing.session', {}, { gateway: 'st-rpc' }),
/Missing Session/,
);
assert.ok(required, '主壳 reject 后,子应用门面必须按自己的 logoutCodes 再判一次'); assert.ok(required, '主壳 reject 后,子应用门面必须按自己的 logoutCodes 再判一次');
assert.equal(requiredCode, 20); assert.equal(requiredCode, 20);
}); });
// ---------------------------------------------------------------------------
// 10. 网关请求头策略(账户中心 TGT 扩展点)
// ---------------------------------------------------------------------------
test('ST-RPC-010 头策略按 id 注册后由网关声明消费:TGT 取会话值,tokenHeader 老通道不受影响', async () => {
registerHeaderProvider(createSessionHeaderProvider({ id: 'st-tgt', header: 'TGT' }));
registerGateway({
id: 'st-header',
router: 'rop-st/router',
// TGT 由头策略提供;tokenHeader 留空表示不走老的单令牌头通道。
tokenHeader: '',
headerProviders: ['st-tgt'],
signer: { id: 'st-noop', fields: () => ({}) },
normalize: (raw) => ({ data: raw }),
});
const req = await prepareRpcCall(
{ gateway: 'st-header', method: 'st.api.page', params: { a: 1 } },
{ ...rpcDeps, session: { name: 'sessionId', value: 'SESSION-1' } },
);
assert.equal(req.headers.TGT, 'SESSION-1');
assert.equal(req.headers.token, undefined);
assert.equal(req.headers['content-type'], 'application/x-www-form-urlencoded');
const old = await prepareRpcCall(
{ gateway: 'st-rpc', method: 'scrm.api.st.order.page', params: {} },
rpcDeps,
);
assert.equal(old.headers.token, 'T-1');
assert.equal(old.headers.TGT, undefined);
});
test('ST-RPC-011 头策略缺会话值时明确报错,未知策略 id 也不静默退化', async () => {
await assert.rejects(
() =>
prepareRpcCall(
{ gateway: 'st-header', method: 'st.api.page', params: {} },
{ ...rpcDeps, session: { name: 'sessionId', value: '' } },
),
/需要请求头 TGT/,
);
registerGateway({
id: 'st-header-unknown',
router: 'rop-st/router',
tokenHeader: '',
headerProviders: ['st-not-registered'],
signer: { id: 'st-noop', fields: () => ({}) },
normalize: (raw) => ({ data: raw }),
});
await assert.rejects(
() => prepareRpcCall({ gateway: 'st-header-unknown', method: 'm', params: {} }, rpcDeps),
/尚未注册/,
);
});
test('ST-RPC-012 noSession 只作用于单次调用:上传网关不进会话体、也不触发 TGT 头策略', async () => {
const normal = await prepareRpcCall(
{ gateway: 'st-header', method: 'st.api.page', params: {} },
{ ...rpcDeps, session: { name: 'sessionId', value: 'SESSION-1' } },
);
assert.equal(normal.data.sessionId, 'SESSION-1');
assert.equal(normal.headers.TGT, 'SESSION-1');
const upload = await prepareRpcCall(
{
gateway: 'st-header',
method: 'st.api.upload',
params: { file: 'xlsx@BASE64' },
noSession: true,
},
{ ...rpcDeps, session: { name: 'sessionId', value: 'SESSION-1' } },
);
assert.equal(upload.data.sessionId, undefined);
assert.equal(upload.headers.TGT, undefined);
assert.equal(upload.data.file, 'xlsx@BASE64');
});
// ---------------------------------------------------------------------------
// 宿主策略(transport='host'):统一走主壳代发,差异只由策略声明
// ---------------------------------------------------------------------------
test('ST-HOST-001 默认宿主策略不注入任何开关,既有主壳行为逐字节不变', async () => {
let seen;
const sender = createHostSender(async (cfg) => {
seen = cfg;
return { status: 200, data: {} };
});
await sender.send({ method: 'POST', url: 'http://host/api', headers: {}, data: { a: 1 } });
assert.equal(seen._skipHostSignature, undefined);
assert.equal(seen._skipAuthorization, undefined);
assert.equal(seen._noVerify, undefined);
assert.equal(seen.withCredentials, true);
assert.equal(resolveHostPolicy().id, 'default');
});
test('ST-HOST-002 legacy-external 关闭主壳公共逻辑,但仍经同一个 send 发出且保留 TGT', async () => {
let seen;
let sendCount = 0;
const sender = createHostSender(async (cfg) => {
sendCount += 1;
seen = cfg;
return { status: 200, data: { code: '0', data: { ok: true } } };
}, 'legacy-external');
const res = await sender.send({
method: 'POST',
url: 'http://rop-merchant.dev.glsx.com.cn/rop-merchants/router',
headers: { TGT: 'SESSION-1', 'content-type': 'application/x-www-form-urlencoded' },
data: { appKey: 'k' },
withCredentials: false,
});
assert.equal(sendCount, 1);
assert.equal(seen._skipHostSignature, true);
assert.equal(seen._skipAuthorization, true);
assert.equal(seen._noVerify, undefined, '业务码判定仍留在主壳');
assert.equal(seen.headers.TGT, 'SESSION-1');
assert.equal(seen.headers['content-type'], 'application/x-www-form-urlencoded');
assert.equal(seen.withCredentials, false, '请求声明优先于 sender 默认值');
assert.deepEqual(res.data, { code: '0', data: { ok: true } });
});
test('ST-HOST-003 宿主策略可注册扩展,未知名明确报错不静默退化', async () => {
registerHostPolicy({
id: 'st-host-custom',
apply: (cfg) => ({ ...cfg, marker: 'custom' }),
});
let seen;
await createHostSender(async (cfg) => {
seen = cfg;
return { status: 200, data: {} };
}, 'st-host-custom').send({ method: 'GET', url: 'http://host/api', headers: {} });
assert.equal(seen.marker, 'custom');
assert.throws(
() => createHostSender(async () => ({ status: 200, data: {} }), 'st-host-missing'),
/尚未注册/,
);
});
test('ST-HOST-004 门面把 hostPolicy 从客户端配置贯通到主壳请求', async () => {
let seen;
const api = createClient({
transport: 'host',
hostSend: async (cfg) => {
seen = cfg;
return { status: 200, data: { code: '0', data: { ok: 1 } } };
},
hostPolicy: 'legacy-external',
gatewayCredential: rpcCredential,
gatewayToken: rpcToken,
timeout: 180000,
});
const data = await api.post('st.api.page', { a: 1 }, { gateway: 'st-rpc' });
assert.deepEqual(data, { ok: 1 });
assert.equal(seen._skipHostSignature, true);
assert.equal(seen._skipAuthorization, true);
assert.equal(seen._noVerify, undefined);
assert.equal(seen.url, 'https://rpc.test/rop-st/router');
assert.equal(seen.headers.token, 'T-1');
});
test('ST-HOST-005 errId=21 归一成主壳 401,由主壳 onLoginRequired 统一登出', async () => {
registerGateway({
id: 'st-logout',
router: 'rop-st/router',
tokenHeader: '',
signer: { id: 'st-noop', fields: () => ({}) },
normalize: (raw) => {
const body = typeof raw === 'string' ? JSON.parse(raw) : raw;
// 与商户域 account.ts 一致:老网关 errId 21 翻成主壳的 401。
if (String(body?.errId) === '21') return { code: 401, message: body.message };
return { data: body };
},
response: { codeKey: 'code', successCodes: ['0'], logoutCodes: [401] },
});
// 模拟主壳那一份 web-host client:transformResponse 归一 + codeKey 判码 + 401 登出回调。
let shellLogoutCalls = 0;
const shellClient = createClient({
kind: 'web-host',
sender: {
async send() {
return {
status: 200,
data: JSON.stringify({ errId: '21', message: '登陆凭证失效', code: '-1' }),
headers: { 'content-type': 'application/json' },
};
},
},
responseParser: (s) => JSON.parse(s),
onLoginRequired: () => {
shellLogoutCalls += 1;
},
});
let seen;
const api = createClient({
transport: 'host',
hostSend: async (cfg) => {
seen = cfg;
return shellClient.request({ ...cfg, headers: cfg.headers ?? {}, signature: 'none' });
},
hostPolicy: 'legacy-external',
gatewayCredential: rpcCredential,
});
await assert.rejects(
() => api.post('st.api.logout', {}, { gateway: 'st-logout' }),
/登陆凭证失效/,
);
assert.equal(shellLogoutCalls, 1, '清令牌与跳 /login 由主壳 onLoginRequired 完成');
assert.equal(seen._noVerify, undefined, 'returnAll 会让主壳不判登出码,必须保持关闭');
assert.equal(seen._skipHostSignature, true);
assert.equal(seen._skipAuthorization, true);
});
...@@ -9,6 +9,7 @@ import { ...@@ -9,6 +9,7 @@ import {
UPopover, UPopover,
URadio, URadio,
USelect, USelect,
USelectInput,
} from '@uj/ui'; } from '@uj/ui';
import type { FieldOption, FieldSchema } from '../formSchema'; import type { FieldOption, FieldSchema } from '../formSchema';
import { DEFAULT_PAGE_SIZE } from '../DataTable'; import { DEFAULT_PAGE_SIZE } from '../DataTable';
...@@ -84,7 +85,11 @@ export function SearchForm<T extends Record<string, unknown>>({ ...@@ -84,7 +85,11 @@ export function SearchForm<T extends Record<string, unknown>>({
) as Partial<T>; ) as Partial<T>;
// 空数组 = 监听整张表单。用于「收起状态下已设条件」的角标计数与悬浮卡: // 空数组 = 监听整张表单。用于「收起状态下已设条件」的角标计数与悬浮卡:
// 收起了不等于没生效,用户必须看得见自己身上还挂着几个条件、分别是什么。 // 收起了不等于没生效,用户必须看得见自己身上还挂着几个条件、分别是什么。
const values = UForm.useWatch([], form) as Partial<T> | undefined; // preserve:true 必须带:组合筛选(USelectInput)的维度字段(accountOrPhone 等)
// 和它的输入值都没有对应的 Form.Item,是纯靠 setFieldValue 写进 store 的虚拟字段。
// rc-field-form 的 getFieldsValue() 只回读「已注册」字段,默认口径下 useWatch 永远看不到
// 这些值 → 下拉切了不生效、placeholder 不联动。preserve 让它读整份 store(getFieldsValue(true))。
const values = UForm.useWatch([], { form, preserve: true }) as Partial<T> | undefined;
const [expanded, setExpanded] = useState(defaultExpanded); const [expanded, setExpanded] = useState(defaultExpanded);
const [activePopoverOpen, setActivePopoverOpen] = useState(false); const [activePopoverOpen, setActivePopoverOpen] = useState(false);
// 触发区只有主色实心的「已填数」角标。antd Popover 的 hover 触发器绑在 children 上时, // 触发区只有主色实心的「已填数」角标。antd Popover 的 hover 触发器绑在 children 上时,
...@@ -253,8 +258,14 @@ export function SearchForm<T extends Record<string, unknown>>({ ...@@ -253,8 +258,14 @@ export function SearchForm<T extends Record<string, unknown>>({
const control = (field: FieldSchema<T>) => { const control = (field: FieldSchema<T>) => {
const label = typeof field.label === 'string' ? field.label : ''; const label = typeof field.label === 'string' ? field.label : '';
// useWatch 首帧 store 未注入初值时也要拿到「登录账号」这类维度文案,
// 否则 placeholder 会退化成字段标签「请输入登录账号/手机号」。
const selectorName = field.selector?.name;
const selectorCurrentValue =
(selectorName !== undefined ? values?.[selectorName] : undefined) ??
(selectorName !== undefined ? formInitialValues[selectorName] : undefined);
const selectorLabel = field.selector?.options.find( const selectorLabel = field.selector?.options.find(
(option) => option.value === values?.[field.selector?.name ?? ''], (option) => option.value === selectorCurrentValue,
)?.label; )?.label;
const isTextInput = field.type === 'input' || field.type === 'textarea'; const isTextInput = field.type === 'input' || field.type === 'textarea';
const common = { const common = {
...@@ -293,27 +304,33 @@ export function SearchForm<T extends Record<string, unknown>>({ ...@@ -293,27 +304,33 @@ export function SearchForm<T extends Record<string, unknown>>({
if (field.type === 'date') if (field.type === 'date')
return <UDatePicker {...common} disabledDate={field.disabledDate} style={{ width }} />; return <UDatePicker {...common} disabledDate={field.disabledDate} style={{ width }} />;
if (field.type === 'dateRange') { if (field.type === 'dateRange') {
const picker = ( if (!field.selector)
<UDatePicker.RangePicker return (
disabled={common.disabled} <UDatePicker.RangePicker
disabledDate={field.disabledDate} disabled={common.disabled}
style={{ width }} disabledDate={field.disabledDate}
/> style={{ width }}
); />
if (!field.selector) return picker; );
const selector = field.selector;
// 右段是日期区间:用 children 插槽替掉默认输入框,值仍由这个 Form.Item 托管。
return ( return (
<div style={{ display: 'flex', width, minWidth: 0 }}> <USelectInput
<UFormItem name={field.selector.name as string} noStyle> options={selector.options}
<USelect selectorValue={values?.[selector.name] as string | number}
allowClear={false} onSelectorChange={(next) => form.setFieldValue(selector.name, next)}
style={{ width: 165, flex: '0 0 165px' }} width={width}
options={field.selector.options} disabled={common.disabled}
/> >
</UFormItem>
<UFormItem name={field.name as string} noStyle> <UFormItem name={field.name as string} noStyle>
{picker} <UDatePicker.RangePicker
variant="borderless"
disabled={common.disabled}
disabledDate={field.disabledDate}
style={{ flex: 1, minWidth: 0 }}
/>
</UFormItem> </UFormItem>
</div> </USelectInput>
); );
} }
if (field.type === 'radio') return <URadio.Group {...common} options={field.options} />; if (field.type === 'radio') return <URadio.Group {...common} options={field.options} />;
...@@ -324,19 +341,20 @@ export function SearchForm<T extends Record<string, unknown>>({ ...@@ -324,19 +341,20 @@ export function SearchForm<T extends Record<string, unknown>>({
<UInput {...common} style={{ width }} /> <UInput {...common} style={{ width }} />
); );
if (!field.selector) return input; if (!field.selector) return input;
// 组合筛选统一走 @uj/ui 的 USelectInput:一体化外框、自适应下拉宽、placeholder 联动、
// 切换语义时自动清空输入。两个字段的值通过 useWatch + setFieldValue 桥接,表单仍是真源。
const selector = field.selector;
return ( return (
<div style={{ display: 'flex', width, minWidth: 0 }}> <USelectInput
<UFormItem name={field.selector.name as string} noStyle> options={selector.options}
<USelect selectorValue={values?.[selector.name] as string | number}
allowClear={false} onSelectorChange={(next) => form.setFieldValue(selector.name, next)}
style={{ width: 140, flex: '0 0 140px' }} value={values?.[field.name] as string}
options={field.selector.options} onChange={(next) => form.setFieldValue(field.name, next)}
/> placeholder={common.placeholder}
</UFormItem> disabled={common.disabled}
<UFormItem name={field.name as string} noStyle> width={width}
{input} />
</UFormItem>
</div>
); );
}; };
...@@ -380,7 +398,10 @@ export function SearchForm<T extends Record<string, unknown>>({ ...@@ -380,7 +398,10 @@ export function SearchForm<T extends Record<string, unknown>>({
> >
{/* 字段与动作同处一行:动作贴最后一列底部,筛选区整体只占一条 72px 左右的横带, {/* 字段与动作同处一行:动作贴最后一列底部,筛选区整体只占一条 72px 左右的横带,
而不是「一排字段 + 单独一排按钮」。窄屏由 ui.css 的媒体查询退回整行。 */} 而不是「一排字段 + 单独一排按钮」。窄屏由 ui.css 的媒体查询退回整行。 */}
<div className="uj-filter-grid"> {/* data-field-cols 让 CSS 把列数收敛到「实际常显字段数」:宽屏按卡片宽可能分到 4 列,
但只有 3 个常显条件时会空出整列,按钮被顶到最右、中间一大片空白。
下限 2:只有 1 个常显条件时不让它独占整行的超宽输入框。 */}
<div className="uj-filter-grid" data-field-cols={Math.max(2, primaryFields.length)}>
{primaryFields.map(renderField)} {primaryFields.map(renderField)}
<div className="uj-filter-actions"> <div className="uj-filter-actions">
......
export * from './datetime'; export * from './datetime';
export * from './error'; export * from './error';
export * from './options';
export * from './params';
import type { FieldOption } from '../components/formSchema';
/**
* 老网关字典项 → SearchForm/CombiForm 的 FieldOption。
*
* 老系统两种形状并存:字典接口给 dictValue/dictLabel,商户/角色下拉给 id/name 或 value/label。
* 只做这一层归一,不在这里改文案、不去重、不排序 —— 后端返回顺序即页面顺序。
*/
export interface DictLike {
dictValue?: unknown;
dictLabel?: unknown;
value?: unknown;
label?: unknown;
id?: unknown;
name?: unknown;
[key: string]: unknown;
}
function optionValue(item: DictLike): string | number | undefined {
for (const value of [item.dictValue, item.value, item.id]) {
if (value === undefined || value === null || value === '') continue;
if (typeof value === 'string' || typeof value === 'number') return value;
}
return undefined;
}
function optionLabel(item: DictLike): string | undefined {
for (const value of [item.dictLabel, item.label, item.name]) {
if (typeof value === 'string' && value !== '') return value;
if (typeof value === 'number') return String(value);
}
return undefined;
}
export function dictOptions(items: unknown, includeAll = false): FieldOption[] {
const options: FieldOption[] = (Array.isArray(items) ? items : [])
.filter((item): item is DictLike => !!item && typeof item === 'object')
.map((item) => {
const value = optionValue(item);
const label = optionLabel(item);
return value === undefined || label === undefined ? null : { value, label };
})
.filter((item): item is FieldOption => item !== null);
return includeAll ? [{ label: '全部', value: '' }, ...options] : options;
}
/**
* 老网关的平铺参数统一去空值:空串、null、undefined、空数组都不发。
* 与老页面 getSearch() 的 delete 循环同源;导出与查询必须共用同一口径。
*/
export function compactParams(params: Record<string, unknown>): Record<string, unknown> {
return Object.fromEntries(
Object.entries(params).filter(
([, value]) =>
value !== null &&
value !== undefined &&
value !== '' &&
!(Array.isArray(value) && value.length === 0),
),
);
}
...@@ -16,6 +16,10 @@ export interface RemoteRequest { ...@@ -16,6 +16,10 @@ export interface RemoteRequest {
responseType?: 'json' | 'blob' | 'arraybuffer' | 'text'; responseType?: 'json' | 'blob' | 'arraybuffer' | 'text';
transformResponse?: Array<(raw: unknown, headers: Record<string, string>) => unknown>; transformResponse?: Array<(raw: unknown, headers: Record<string, string>) => unknown>;
_noVerify?: boolean; _noVerify?: boolean;
/** 外部老网关:跳过主壳 RSA 请求头(由 api-core 宿主策略声明,主壳 http.ts 消费)。 */
_skipHostSignature?: boolean;
/** 外部老网关:跳过主壳 Bearer 登录令牌,改用网关自己的会话头。 */
_skipAuthorization?: boolean;
/** 中止信号:wujie props 是同源引用传递,可原样跨到主壳 axios(不走 postMessage 序列化)。 */ /** 中止信号:wujie props 是同源引用传递,可原样跨到主壳 axios(不走 postMessage 序列化)。 */
signal?: AbortSignal; signal?: AbortSignal;
[key: string]: unknown; [key: string]: unknown;
......
...@@ -109,7 +109,8 @@ export function buildMenus( ...@@ -109,7 +109,8 @@ export function buildMenus(
let path = n.route; let path = n.route;
const uses = routeUses.get(path) ?? 0; const uses = routeUses.get(path) ?? 0;
if (uses > 1) { if (uses > 1) {
const repaired = pathByResource?.get(resource); // resource 在无 permCode / 权限码无冒号时为 undefined;此时不参与 route 修复。
const repaired = resource ? pathByResource?.get(resource) : undefined;
if (repaired) { if (repaired) {
console.error( console.error(
`[menu] 后端菜单「${n.label}」(${code}) 的 route ${path} 被 ${uses} 个页面复用,` + `[menu] 后端菜单「${n.label}」(${code}) 的 route ${path} 被 ${uses} 个页面复用,` +
......
...@@ -4,4 +4,7 @@ export type UDatePickerProps = DatePickerProps; ...@@ -4,4 +4,7 @@ export type UDatePickerProps = DatePickerProps;
export const UDatePicker = Object.assign((props: UDatePickerProps) => <DatePicker {...props} />, { export const UDatePicker = Object.assign((props: UDatePickerProps) => <DatePicker {...props} />, {
RangePicker: DatePicker.RangePicker, RangePicker: DatePicker.RangePicker,
// 老系统营业时间用 HH:mm:ss 时间选择器;直接复用 antd 的 TimePicker,
// 保持 U* 组件出口一致,业务侧不必绕过 UI 包直接 import antd。
TimePicker: DatePicker.TimePicker,
}); });
import { useMemo, type ChangeEvent, type CSSProperties, type ReactNode } from 'react';
import { UInput } from '../Input';
import { USelect } from '../Select';
export interface USelectInputOption {
label: ReactNode;
value: string | number;
}
/**
* 「前置下拉 + 输入」组合筛选控件。
*
* 为什么单独做一个组件:过去 SearchForm 里两处(普通输入、日期区间)各自手写
* flex 容器 + 两个 antd 控件拼接,视觉上是「两个控件挤在一起」——双边框、双圆角、
* 中间接缝突兀,placeholder 与下拉文案还要在调用处各自维护。这里把它们收敛成一个
* 一体化控件:统一外框、一条分隔线、聚焦环包住整体;宽度自适应、placeholder 联动、
* 切换语义时清空输入都内聚在组件里。
*
* 受控设计:value/selectorValue 由调用方给出,组件不碰 Form store,因此既能塞进
* antd Form(调用方用 Form.useWatch + setFieldValue 桥接),也能独立用在任何页面。
* 右段传 children 即可替换为日期区间等自定义控件(见 SearchForm 的 dateRange)。
*/
export interface USelectInputProps {
/** 前置下拉的选项。类型与设计系统的 FieldOption 结构兼容。 */
options: USelectInputOption[];
/**
* 前置下拉当前值。不传 / undefined / null 时自动选中 options 第一项——
* 维度选择器不允许出现空态(空态会让 placeholder 一起退化)。
*/
selectorValue?: string | number;
/** 前置下拉变化。切换语义时组件会同时回调 onChange('') 清空右段(可关闭)。 */
onSelectorChange?: (value: string | number) => void;
/** 右段输入值。 */
value?: string;
/** 右段输入变化,直接回传字符串,调用方不必读 event.target.value。 */
onChange?: (value: string) => void;
/** 输入占位符。不传时按当前下拉文案生成「请输入XX」。 */
placeholder?: string;
/** 前置下拉宽度。不传则按最长选项文案自适应(保底 112 / 封顶 160px)。 */
selectorWidth?: number;
/** 整体宽度,默认撑满父容器。 */
width?: string | number;
/** 尺寸档,与 antd 保持一致。 */
size?: 'small' | 'middle';
disabled?: boolean;
/** 右段输入是否可清空,默认 true。 */
allowClear?: boolean;
/** 切换前置下拉时是否清空右段,默认 true,避免「账号 → 手机号」后语义错配。 */
clearValueOnSelectorChange?: boolean;
/** 自定义右段控件(如 UDatePicker.RangePicker)。传了就替代内置输入框。 */
children?: ReactNode;
/** 无障碍标签:不传时用「筛选字段」/ 解析后的 placeholder。 */
selectorAriaLabel?: string;
inputAriaLabel?: string;
className?: string;
style?: CSSProperties;
}
/**
* 按最长选项文案估宽:中文 12px/字(small 档),ASCII 0.6 字;箭头 + 左右内边距约 40px。
* 保底 112px 让「登录账号」这类 4 字文案完整显示;封顶 160px 避免长文案把输入框压没。
*/
function measureSelectorWidth(options: USelectInputOption[]): number {
const chars = options.reduce((max, option) => {
const label = typeof option.label === 'string' ? option.label : '';
const width = [...label].reduce((sum, ch) => {
const code = ch.codePointAt(0) ?? 0;
// 等价于原 [\x00-\xff] 的 ASCII 宽度口径,但排除控制字符(no-control-regex)。
return sum + (code > 31 && code < 256 ? 0.6 : 1);
}, 0);
return Math.max(max, width);
}, 4);
return Math.min(160, Math.max(112, Math.round(chars * 12 + 40)));
}
export function USelectInput({
options,
selectorValue,
onSelectorChange,
value,
onChange,
placeholder,
selectorWidth,
width = '100%',
size = 'small',
disabled = false,
allowClear = true,
clearValueOnSelectorChange = true,
children,
selectorAriaLabel,
inputAriaLabel,
className,
style,
}: USelectInputProps) {
const measuredWidth = useMemo(
() => selectorWidth ?? measureSelectorWidth(options),
[options, selectorWidth],
);
// 前置下拉是「按哪个字段筛」的维度选择,必须始终有一个确定值:
// 调用方首帧还没从 Form 读到初值(useWatch 首帧 store 为空)时,不能让下拉空着,
// 否则 placeholder 也跟着退化成「请输入」,用户会以为控件失效。
// 约定:undefined / null 视为「调用方尚未给值」→ 回落第一项;空串是合法选项值(如「全部」),
// 由调用方按需传,组件不改写。
const resolvedSelectorValue =
selectorValue === undefined || selectorValue === null
? (options[0]?.value ?? '')
: selectorValue;
const activeLabel = options.find((option) => option.value === resolvedSelectorValue)?.label;
const resolvedPlaceholder =
placeholder ??
(typeof activeLabel === 'string' && activeLabel ? `请输入${activeLabel}` : '请输入');
const classes = [
'u-select-input',
`u-select-input--${size}`,
disabled ? 'is-disabled' : '',
className ?? '',
]
.filter(Boolean)
.join(' ');
return (
<div className={classes} style={{ width, ...style }}>
<USelect
className="u-select-input__selector"
variant="borderless"
size={size}
allowClear={false}
disabled={disabled}
value={resolvedSelectorValue}
options={options}
aria-label={selectorAriaLabel ?? '筛选字段'}
style={{ width: measuredWidth, flex: `0 0 ${measuredWidth}px` }}
onChange={(next) => {
onSelectorChange?.(next as string | number);
if (clearValueOnSelectorChange && next !== resolvedSelectorValue) onChange?.('');
}}
/>
<span className="u-select-input__divider" aria-hidden="true" />
<div className="u-select-input__control">
{children ?? (
<UInput
className="u-select-input__input"
variant="borderless"
size={size}
allowClear={allowClear}
disabled={disabled}
value={value}
placeholder={resolvedPlaceholder}
aria-label={inputAriaLabel ?? resolvedPlaceholder}
onChange={(event: ChangeEvent<HTMLInputElement>) => onChange?.(event.target.value)}
/>
)}
</div>
</div>
);
}
export default USelectInput;
...@@ -47,6 +47,8 @@ export interface TabLabelOptions { ...@@ -47,6 +47,8 @@ export interface TabLabelOptions {
* label: tabLabel('待我审批', { count: total, tone: 'primary' }) // 主色强调角标 * label: tabLabel('待我审批', { count: total, tone: 'primary' }) // 主色强调角标
* label: tabLabel('管理层市场费', { count: n, countLabel: `共 ${n} 项` }) // 带朗读 * label: tabLabel('管理层市场费', { count: n, countLabel: `共 ${n} 项` }) // 带朗读
*/ */
// 角标文案是与 UTabs 同包的展示型 helper(无 hooks/状态);fast-refresh 规则按文件粒度误判。
// eslint-disable-next-line react-refresh/only-export-components
export function tabLabel(text: ReactNode, options?: TabLabelOptions): ReactNode { export function tabLabel(text: ReactNode, options?: TabLabelOptions): ReactNode {
const count = options?.count; const count = options?.count;
const visible = count !== null && count !== undefined && count !== ''; const visible = count !== null && count !== undefined && count !== '';
...@@ -55,7 +57,9 @@ export function tabLabel(text: ReactNode, options?: TabLabelOptions): ReactNode ...@@ -55,7 +57,9 @@ export function tabLabel(text: ReactNode, options?: TabLabelOptions): ReactNode
{text} {text}
{visible ? ( {visible ? (
<span <span
className={'uj-tabs__count' + (options?.tone === 'primary' ? ' uj-tabs__count--primary' : '')} className={
'uj-tabs__count' + (options?.tone === 'primary' ? ' uj-tabs__count--primary' : '')
}
aria-hidden={options?.countLabel ? undefined : true} aria-hidden={options?.countLabel ? undefined : true}
aria-label={options?.countLabel} aria-label={options?.countLabel}
> >
......
import { Tree, type TreeProps } from 'antd';
/** 项目统一树组件。老系统的 ztree 节点字段(id / label / children)由调用方映射成 fieldNames。 */
export const UTree = Tree;
export type UTreeProps = TreeProps;
...@@ -33,6 +33,10 @@ export type { UInputProps } from './components/Input'; ...@@ -33,6 +33,10 @@ export type { UInputProps } from './components/Input';
export { USelect } from './components/Select'; export { USelect } from './components/Select';
export type { USelectProps } from './components/Select'; export type { USelectProps } from './components/Select';
/** 前置下拉 + 输入框的一体化组合筛选控件(支持 children 替换为日期区间等右段)。 */
export { USelectInput } from './components/SelectInput';
export type { USelectInputProps, USelectInputOption } from './components/SelectInput';
export { UCascader } from './components/Cascader'; export { UCascader } from './components/Cascader';
export type { UCascaderProps } from './components/Cascader'; export type { UCascaderProps } from './components/Cascader';
...@@ -62,6 +66,8 @@ export type { SkeletonVariant } from './components/Skeleton'; ...@@ -62,6 +66,8 @@ export type { SkeletonVariant } from './components/Skeleton';
export { UTabs, tabLabel } from './components/Tabs'; export { UTabs, tabLabel } from './components/Tabs';
export type { UTabsProps, UTabsSize, TabLabelOptions } from './components/Tabs'; export type { UTabsProps, UTabsSize, TabLabelOptions } from './components/Tabs';
export { UCheckbox } from './components/Checkbox'; export { UCheckbox } from './components/Checkbox';
export { UTree } from './components/Tree';
export type { UTreeProps } from './components/Tree';
export { UList } from './components/List'; export { UList } from './components/List';
export { UTooltip } from './components/Tooltip'; export { UTooltip } from './components/Tooltip';
export { UPopover } from './components/Popover'; export { UPopover } from './components/Popover';
......
...@@ -322,6 +322,107 @@ html body { ...@@ -322,6 +322,107 @@ html body {
padding: 0; padding: 0;
} }
/* ============ 下拉 + 输入组合控件(USelectInput) ============ */
/* 一体化:外框只有一层,内部两个 antd 控件走 borderless 变体,中间一条分隔线。
hover / focus 作用在外框上,视觉上是一个控件而不是两个拼起来的控件。
高度 24 / 32 对齐 antd small / middle 的 controlHeight,不让接缝处错位。 */
.u-select-input {
display: inline-flex;
align-items: stretch;
box-sizing: border-box;
min-width: 0;
/* 不写死 height:由内部 antd 控件撑高,避免外框 2px 边框把文字裁掉。 */
min-height: 24px;
border: 1px solid var(--uj-border);
border-radius: var(--uj-radius-md);
background: var(--uj-surface);
overflow: hidden;
transition:
border-color 150ms var(--uj-ease-out),
box-shadow 150ms var(--uj-ease-out);
}
.u-select-input--middle {
min-height: 32px;
}
.u-select-input:hover {
border-color: var(--uj-border-strong);
}
/* 焦点反馈落在外框:点前置下拉、点输入框、日期区间聚焦时,整框统一亮起。
下拉自身的高亮在下面单独压掉,避免出现「框里还有一块亮的」两层高亮。 */
.u-select-input:focus-within {
border-color: var(--uj-primary);
box-shadow: var(--uj-ring);
}
.u-select-input.is-disabled {
background: var(--uj-surface-3);
border-color: var(--uj-border);
cursor: not-allowed;
}
.u-select-input__selector,
.u-select-input__control {
display: flex;
align-items: center;
min-width: 0;
height: 100%;
}
.u-select-input__control {
flex: 1 1 auto;
}
/* borderless 变体仍有自己的 hover 底色/内边框,统一收成透明,让外框成为唯一视觉边界。 */
.u-select-input__selector .ant-select-selector,
.u-select-input__control .ant-input,
.u-select-input__control .ant-picker {
border: 0 !important;
box-shadow: none !important;
background: transparent !important;
}
.u-select-input__selector .ant-select-selector {
padding-inline: var(--uj-space-2);
}
/* ⚠ className 落点:USelectInput 把 u-select-input__selector 传给 antd Select,
antd 挂在「根元素 .ant-select」上,不是内层 .ant-select-selector。
antd 6 的 borderless 变体把 border/background 变量都设成 transparent,但仍通过
patchStyle 给根元素加了一圈 outline:
`.ant-select:not(.ant-select-disabled):has(input:focus-visible){outline:...}`
鼠标点下拉时内部 input 满足 :focus-visible,下拉那一块就亮起轮廓线——这才是
「下拉框自身高亮」。之前把规则压在内层 .ant-select-selector 上完全没命中。
这里直接在根元素上压掉,焦点反馈只由整框外框 .u-select-input 承担。 */
.u-select-input__selector.ant-select,
.u-select-input__selector.ant-select:hover,
.u-select-input__selector.ant-select-focused,
.u-select-input__selector.ant-select:not(.ant-select-disabled):has(input:focus-visible),
.u-select-input__selector.ant-select:not(.ant-select-disabled):has(textarea:focus-visible),
.u-select-input__selector.ant-select:focus-visible {
outline: none !important;
box-shadow: none !important;
}
/* 内层 selector 兜底:确保没有残留的边框、底色或阴影。 */
.u-select-input__selector.ant-select .ant-select-selector,
.u-select-input__selector.ant-select:hover .ant-select-selector,
.u-select-input__selector.ant-select-focused .ant-select-selector,
.u-select-input__selector.ant-select:has(input:focus-visible) .ant-select-selector {
border-color: transparent !important;
background: transparent !important;
box-shadow: none !important;
outline: none !important;
}
.u-select-input__control .ant-input {
padding-inline: var(--uj-space-2);
}
/* 分隔线只提示「两段」,不抢外框的视觉重量;聚焦时不变色,避免被误读为可点击元素。 */
.u-select-input__divider {
flex: 0 0 1px;
align-self: center;
height: 14px;
background: var(--uj-divider);
}
.u-select-input__selector .ant-select-arrow {
color: var(--uj-text-3);
}
.u-select-input:hover .ant-select-arrow {
color: var(--uj-text-2);
}
/* ============ 筛选面板 ============ */ /* ============ 筛选面板 ============ */
/* 筛选卡是布局容器:列数按「卡片自身宽度」分档,不按视口宽度。 /* 筛选卡是布局容器:列数按「卡片自身宽度」分档,不按视口宽度。
...@@ -364,29 +465,55 @@ html body { ...@@ -364,29 +465,55 @@ html body {
动作列按最宽态留安全宽:更多筛选按钮固定 126px(含两位数角标)+ 重置 + 查询 + 间隙, 动作列按最宽态留安全宽:更多筛选按钮固定 126px(含两位数角标)+ 重置 + 查询 + 间隙,
否则角标一出现按钮就变宽、flex-end 向左溢出压住紧邻的最后一个字段。 否则角标一出现按钮就变宽、flex-end 向左溢出压住紧邻的最后一个字段。
容器查询按「筛选卡宽」判定,整页与抽屉共用同一套数字。 */ 容器查询按「筛选卡宽」判定,整页与抽屉共用同一套数字。 */
/* 常显行还要再按「实际字段数」收口:宽屏卡按宽度能排 4 列,但页面只常显 3 个条件时,
第 4 列整列空着、按钮被顶到最右边,中间留出一大片空白。data-field-cols 由 SearchForm
写在 .uj-filter-grid 上,这里只在各档位内向下取整(不会把列数撑超过容器容量)。 */
@container (min-width: 928px) { @container (min-width: 928px) {
.uj-filter-grid, .uj-filter-grid,
.uj-filter-more { .uj-filter-more {
--uj-filter-cols: 2; --uj-filter-cols: 2;
} }
.uj-filter-grid[data-field-cols='1'] {
--uj-filter-cols: 1;
}
} }
@container (min-width: 1264px) { @container (min-width: 1264px) {
.uj-filter-grid, .uj-filter-grid,
.uj-filter-more { .uj-filter-more {
--uj-filter-cols: 3; --uj-filter-cols: 3;
} }
.uj-filter-grid[data-field-cols='1'] {
--uj-filter-cols: 1;
}
.uj-filter-grid[data-field-cols='2'] {
--uj-filter-cols: 2;
}
} }
@container (min-width: 1600px) { @container (min-width: 1600px) {
.uj-filter-grid, .uj-filter-grid,
.uj-filter-more { .uj-filter-more {
--uj-filter-cols: 4; --uj-filter-cols: 4;
} }
.uj-filter-grid[data-field-cols='1'] {
--uj-filter-cols: 1;
}
.uj-filter-grid[data-field-cols='2'] {
--uj-filter-cols: 2;
}
.uj-filter-grid[data-field-cols='3'] {
--uj-filter-cols: 3;
}
} }
.uj-filter-grid .ant-form-item, .uj-filter-grid .ant-form-item,
.uj-filter-more .ant-form-item { .uj-filter-more .ant-form-item {
margin-bottom: 0; margin-bottom: 0;
min-width: 0; min-width: 0;
} }
/* 列数按字段数收口后,1~2 个常显字段的列会很宽;给单项封顶,避免输入框被拉成
几百像素的长条。3 项及以上的常规档位列宽本就小于封顶值,不受影响。 */
.uj-filter-grid .ant-form-item {
max-width: 520px;
}
/* 标签是字段名,不是正文:压小一档、不换行、右侧留 8px 与控件分开。 /* 标签是字段名,不是正文:压小一档、不换行、右侧留 8px 与控件分开。
宽度由 labelCol 内联给出(104px),这里只管排版。 */ 宽度由 labelCol 内联给出(104px),这里只管排版。 */
.uj-filter-grid .ant-form-item-label, .uj-filter-grid .ant-form-item-label,
......
...@@ -438,6 +438,76 @@ importers: ...@@ -438,6 +438,76 @@ importers:
specifier: 'catalog:' specifier: 'catalog:'
version: 6.4.5(@types/node@22.20.5) version: 6.4.5(@types/node@22.20.5)
apps/web/subapps/merchant:
dependencies:
'@ant-design/icons':
specifier: 'catalog:'
version: 6.3.4(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@tanstack/react-query':
specifier: 'catalog:'
version: 5.106.1(@types/react@19.3.0)(react@19.3.1)
'@uj/api-core':
specifier: workspace:*
version: link:../../../../packages/api-core
'@uj/biz':
specifier: workspace:*
version: link:../../../../packages/biz
'@uj/contracts':
specifier: workspace:*
version: link:../../../../packages/contracts
'@uj/design-tokens':
specifier: workspace:*
version: link:../../../../packages/design-tokens
'@uj/platform-sdk':
specifier: workspace:*
version: link:../../../../packages/platform-sdk
'@uj/ui':
specifier: workspace:*
version: link:../../../../packages/ui
antd:
specifier: 'catalog:'
version: 6.7.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
dayjs:
specifier: 'catalog:'
version: 1.11.23
react:
specifier: 'catalog:'
version: 19.3.1
react-dom:
specifier: 'catalog:'
version: 19.3.1(react@19.3.1)
react-router-dom:
specifier: 'catalog:'
version: 7.18.5(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
devDependencies:
'@types/node':
specifier: 'catalog:'
version: 22.20.5
'@types/react':
specifier: 'catalog:'
version: 19.3.0
'@types/react-dom':
specifier: 'catalog:'
version: 19.3.0(@types/react@19.3.0)
'@uj/eslint-config':
specifier: workspace:*
version: link:../../../../packages/eslint-config
'@uj/typescript-config':
specifier: workspace:*
version: link:../../../../packages/typescript-config
'@uj/vite-config':
specifier: workspace:*
version: link:../../../../packages/vite-config
eslint:
specifier: 'catalog:'
version: 9.39.4
typescript:
specifier: 'catalog:'
version: 5.9.3
vite:
specifier: 'catalog:'
version: 6.4.5(@types/node@22.20.5)
apps/web/subapps/points: apps/web/subapps/points:
dependencies: dependencies:
'@ant-design/icons': '@ant-design/icons':
......
-- =====================================================================
-- merchant-menu-migration.sql 的回滚
--
-- 删除「商户管理」10028 整棵子树(1 目录 + 3 页面 + 19 按钮)及其角色授权,
-- 并把排在它后面的一级目录 sort 恢复 -1(系统设置回到原位)。
-- 前端代码需同步回退(merchant 子应用下线),否则菜单消失但代码仍在。
--
-- 幂等:只跑一次;重跑前先确认 merchant-menu-migration.sql 已执行过。
-- =====================================================================
USE `yj_service`;
-- 0) 预检:确认当前确实处于「已新增」状态
SELECT `menu_id`, `menu_code`, `parent_code`, `menu_name`, `menu_type`, `perm_code`, `route`, `sort`
FROM `sys_menu`
WHERE `menu_code` LIKE '10028%'
ORDER BY `menu_code`;
START TRANSACTION;
SET @merchant_sort = (
SELECT `sort` FROM `sys_menu`
WHERE `menu_type` = 1 AND `is_deleted` = 0 AND `menu_code` = '10028'
LIMIT 1
);
-- 1) 先清角色授权(外键开启的库必须先清,否则删菜单报错)
DELETE rm FROM `sys_role_menu` rm
JOIN `sys_menu` m ON m.`menu_id` = rm.`menu_id`
WHERE m.`menu_code` LIKE '10028%';
-- 2) 删整棵子树,恢复一级 sort
DELETE FROM `sys_menu` WHERE `menu_code` LIKE '10028%';
UPDATE `sys_menu` SET `sort` = `sort` - 1
WHERE `menu_type` = 1 AND `is_deleted` = 0 AND `sort` > @merchant_sort;
-- 3) 回查:10028* 应为 0 行;一级顺序恢复
SELECT COUNT(*) AS remaining_merchant FROM `sys_menu` WHERE `menu_code` LIKE '10028%';
SELECT `menu_name`, `sort` FROM `sys_menu`
WHERE `menu_type` = 1 AND `is_deleted` = 0
ORDER BY `sort`, `menu_code`;
COMMIT;
...@@ -76,6 +76,7 @@ const APPS = [ ...@@ -76,6 +76,7 @@ const APPS = [
// 新增子应用登记进来即纳入必需文件 / 端口一致性检查。 // 新增子应用登记进来即纳入必需文件 / 端口一致性检查。
// points / usedcar 是历史未登记项,本次不扩大范围补登。 // points / usedcar 是历史未登记项,本次不扩大范围补登。
{ dir: 'apps/web/subapps/finance', kind: 'subapp' }, { dir: 'apps/web/subapps/finance', kind: 'subapp' },
{ dir: 'apps/web/subapps/merchant', kind: 'subapp' },
]; ];
for (const { dir, kind } of APPS) { for (const { dir, kind } of APPS) {
const appDir = path.join(ROOT, dir); const appDir = path.join(ROOT, dir);
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!