Commit 3b182e50 by liimin

merchant 商户域复刻审计修复与交互重构

- 商户/员工/角色按源逐条取证修复(名称重复校验、createdSource、gtree 级联、开关拦截等),对账入口 DELIVERY.md
- SearchForm 组合筛选出参改整份 store,登录账号/手机号等筛选生效
- 树全选/全不选按当前可见集执行,任意条件改变重算已选;checkedKeys 统一字符串 key
- 401 登出走完整链路,避免复用旧沙箱导致重登后仍显示凭证失效
1 parent 1328acf2
Showing 33 changed files with 1647 additions and 374 deletions
......@@ -6,7 +6,6 @@ import { ConfigProvider, App as AntApp } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import { createRouter } from '@/router';
import { queryClient } from '@/queryClient';
import { useAppStore } from '@/store/useAppStore';
import { themeConfig } from '@/theme/themeConfig';
import { AccessProvider } from '@/access';
import { initSign, setUnauthorizedHandler, http } from '@/api';
......@@ -14,17 +13,20 @@ import { DownloadCenterProvider } from '@uj/download-center';
import { installGlobalUnhandledRejectionHandler } from '@uj/ui';
import type { RemoteRequestFn } from '@uj/contracts';
import { loadRuntimeManifest } from './runtime-manifest';
import { reportSessionExpired } from './subapp-lifecycle';
import { logoutEverything, reportSessionExpired } from './subapp-lifecycle';
import '@uj/design-tokens/tokens.css';
import './index.css';
import './theme/design.css';
import './theme/mfe.css';
// 401 / 10002 的统一处理出口。必须在任何请求发出(含下面的 initSign)之前注册:
// 先弹「登录已失效」提示并短暂延时,再 logout 双清 uj_token 与 session,
// RequireAuth 随即重定向;不提示直接跳会让用户莫名其妙。
// 401 / 10002 的统一处理出口。必须在任何请求发出(含下面的 initSign)之前注册。
//
// 必须走 logoutEverything,而不是只调 store.logout():后者只清主壳令牌并翻 loggedIn,
// 不会广播 <shortName>:logout、不会销毁 alive 沙箱。商户域的 TGT 失效由主壳判码,
// 若走半吊子路径,重新登录会复用带旧 QueryClient 缓存的 iframe,页面继续显示
// 「[401] 登陆凭证失效」。完整链路与手动退出、子应用 logout-host 完全一致。
setUnauthorizedHandler(() => {
void reportSessionExpired().then(() => useAppStore.getState().logout());
void reportSessionExpired().then(() => logoutEverything());
});
// 全应用未处理 promise rejection 兜底:async 调用漏 catch 时弹红色错误 toast。
......
......@@ -44,8 +44,12 @@ let loggingOut = false;
* 4. 最后清 token/session/菜单缓存并跳登录页。
*
* 子应用绝不自己 clearToken():令牌与会话的真源在主壳,两边各自清会留下半吊子状态。
*
* navigate 可选:401 回调注册在 React 挂载之前,拿不到 useNavigate。缺省用整页跳转,
* 顺带强制重建所有 alive 沙箱——否则新会话会复用带旧 QueryClient 缓存的 iframe,
* 表现为「重新登录后页面仍显示上一次账号的 401 / 业务数据」。
*/
export async function logoutEverything(navigate: (path: string) => void): Promise<void> {
export async function logoutEverything(navigate?: (path: string) => void): Promise<void> {
// 并发会话失效 / 用户连点退出只做一次完整收尾,避免重复 auth.logout 与重复导航。
if (loggingOut) return;
loggingOut = true;
......@@ -75,7 +79,8 @@ export async function logoutEverything(navigate: (path: string) => void): Promis
void destroyAppLocked(s.shortName).catch(() => {});
}
navigate('/login');
if (navigate) navigate('/login');
else window.location.replace('/login');
} finally {
loggingOut = false;
}
......
# merchant 子应用 源↔新 差异终表
> 2026-12-03 审计修复轮完成后整理。源 = `temp/account`(老 jQuery/layui),新 = `apps/web/subapps/merchant`。
> 原则:布局/交互可按本系统规范重构,功能逐字复刻;本文是「哪些逐字、哪些有意不复刻、哪些是平台化增强」的唯一对账入口。
## 1. 本轮修复清单(已对源逐条取证)
### 商户
| # | 位置 | 修复内容 | 源取证 |
| --- | --- | --- | --- |
| 1 | `Create/index.tsx` `Edit/index.tsx` | 重名判定语义反转修正:接口 `data === true` = 名称可用直接提交,`false` 才弹「商户名称已经被使用,是否确定继续使用」;统一收敛为 `Create/model.ts` 的 `isMerchantNameAvailable` | add.html:1113-1119、edit.html:1425-1438(verifyDialog add.html:1052) |
| 2 | `Create/index.tsx` | 创建子商户同样带 `createdSource=1`(原先仅创建商户带) | addSubMerchant.html:1014-1016 |
| 3 | `Edit/index.tsx` | 非工厂(等级≠1)修改商户补传 `parentId` | edit.html:1369-1373 |
| 4 | `Merchant/index.tsx` `rowFlag` | 行按钮改为纯本地计算(源拿到列表后整体覆盖 `item.btn`,服务端 btn 不可信);edit=status≠3、createStaff=status==2、createSubMerchant=status==2 且等级≠4、editPeriod=status≠1 | index.html:890-951 超管分支 |
| 5 | `Create/BasicForm.tsx` | 编辑态补地图省市一致性拦截「您选择的地址错误,请重新选择」,不匹配不写入(创建态源已注释,不复刻) | edit.html:1499-1507 |
| 6 | `Merchant/index.tsx` | 行操作「有效期」→「修改账户有效期」;导入文案逐字对齐(请选择文件 / 处理成功,系统已自动创建商户,可返回列表查看 / 处理失败,可点击 下载失败模版 查看失败原因 / 长 loading 原文警示),删自造两步引导与类型硬拦截(源对非法扩展名静默忽略) | index.html:279、585-600、725-850 |
| 7 | `PeriodModal.tsx` | 成功提示「操作成功」→「修改成功」(源关弹窗后外层 msg);有效期提交改 `new Date(...)`(源以 Date 对象入参);删自造「该账户已过期」提示 | index.html:663、validPeriodForm.html:245-246 |
| 8 | `Create/model.ts` | 子商户模式 `fieldToFormNameList` 收缩为 11 项(去掉 `effectiveTime`;`merchantModel` 由父级预置值入参,与源显式赋值等价);`effectiveStarttime/expireDate` 提交改 Date 对象 | addSubMerchant.html:843-866、900-901 |
| 9 | `Merchant/index.tsx` | 企微关联筛选「全部」= `"0"` 且始终随参(源 select 默认即 "0") | index.html:129-136 |
| 10 | `Edit/index.tsx` | 开通模式显隐补 isFactory 前置:仅工厂且(草稿或 model=='-')可改 | edit.html:1763-1771 |
| 11 | `Create/PermissionForm.tsx` | 权限树改 `checkStrictly` + `applyGtreeCheck` 手动级联(勾=子树+全部祖先强勾;取消=仅子树;回显 idList 精确直标),并同步修正 requestList 组装不再只取叶子(源 getCheckedNodes(true) 含强制勾中的祖先,逐 logo 分类) | gtree.js:38-43、add.html:2199-2246 |
### 员工
| # | 位置 | 修复内容 | 源取证 |
| --- | --- | --- | --- |
| 1 | `Employee/index.tsx` | 补序号列;商户列标题「商户名」→「商户名(商户号)」 | index.html:147、157 |
| 2 | `Employee/index.tsx` | 启停拦截改双向:源开关 `value=roleName`,为 `-`(未设角色)时启用、停用都只提示不发请求;「启用」操作补源悬停 tips(time:0 常驻) | index.html:312-317、186-206、485-491 |
| 3 | `api/modules/employee.ts` | 删 `updateValPerByStaffId` 残留(源入口早被注释下线) | employee/index.html 注释 |
| 4 | `Employee/Form/index.tsx` | 注释口径修正:源 `accountInfo`(外部嵌入态)的双列集与「刷新/创建角色」按钮组属嵌入分支,本系统按超管态复刻,有意不复刻 | index.html:136-145 |
| 5 | `Employee/Form/index.tsx`、`Employee/model.ts` | 可见商户树 checkedKeys 统一字符串 key:数字 id 写进 antd Tree 复选框点不亮(全选后计数正常但全不勾);编辑态回显同修 | add.html:758-770 |
| 6 | `Employee/Form/index.tsx`、`Merchant/Create/BasicForm.tsx` | 树勾选集恒等于「当前可见集内」:全选=整份替换为可见集;全不选=清可见集(品牌树连可见父 id 一起清,防级联残留);**任意条件改变(过滤词增删、树重载)即重算已选**;按钮态实时推导 | 用户指定,超出源口径 |
### 角色
| # | 位置 | 修复内容 | 源取证 |
| --- | --- | --- | --- |
| 1 | `Role/index.tsx` | 状态筛选顺序改 全部('')→草稿(1)→正常(0) | role/index.html:74-78 |
| 2 | `Role/PermForm.tsx` | 权限树同商户改 gtree 级联语义(共享 `applyGtreeCheck`);两层「功能菜单」caption 重复,外层改「功能权限」 | gtree.js:38-43 |
### 共享层(`packages/biz`)
| # | 位置 | 修复内容 | 源取证 |
| --- | --- | --- | --- |
| 1 | `SearchForm/index.tsx` | 查询出参改 `form.getFieldsValue(true)`(整份 store):rc-field-form 的 onFinish 只回传「已注册字段」,USelectInput 组合筛选(登录账号/手机号、员工姓名/手机号)是 setFieldValue 写入的虚拟字段,此前从未进查询参数 | merchant/index.html:88-92、employee/index.html:96-100 |
## 2. 有意不复刻(源怪癖/嵌入分支)
- 换商户后源残留 `check_arr` 报「请选择产品」的脏状态怪癖:新实现整体重置(`key={merchantId}`),不复刻。
- 员工 `accountInfo` 嵌入态分支(列集切换、刷新/创建角色按钮组、门店隐藏商户列):本系统即超管态,不复刻。
- 商户列表 `window.isDxternal==1` 的外部系统按钮裁剪:同上。
- 源被注释下线的入口(员工有效期管理、商户「修改基本信息」旧文案、角色全选按钮):不复刻。
- 创建态地图省市一致性拦截(add.html 已注释):仅编辑态复刻。
## 3. 平台化增强(超出源,需知会)
- 角色/员工详情二级页头部无「修改」按钮(保持源口径);列表删除成功 toast「删除成功」(源无提示)。
- 员工「启用」tips 用 UTooltip 挂在行内操作上,替代源 layer.tips 悬停气泡。
- 导入弹窗保留只读文件名 + 选择文件 + 下载模板一行式结构,仅文案与状态色按源。
- 所有下载走 `downloadCenter.url` 登记,不 `window.open`。
## 4. 验收口径
- `pnpm --filter @uj/web-merchant typecheck / lint` 与触及文件 `prettier --check` 全绿(2026-12-03)。
- 视觉与交互验证由用户在真实环境执行;Network 侧需抽查:重名接口 data 布尔方向、updateMerchant parentId、updateValPerByMerId ISO 时间、role/merchant requestList 中祖先节点是否随勾出现。
......@@ -7,14 +7,21 @@ import CreateMerchantPage from './pages/Merchant/Create';
import MerchantEditPage from './pages/Merchant/Edit';
import MerchantDetailPage from './pages/Merchant/Detail';
import EmployeePage from './pages/Employee';
import EmployeeFormPage from './pages/Employee/Form';
import EmployeeDetailPage from './pages/Employee/Detail';
import RolePage from './pages/Role';
import RoleFormPage from './pages/Role/Form';
import RoleDetailPage from './pages/Role/Detail';
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 表单太长,抽屉放不下),不进菜单。
* 与 employee/create、employee/create/:merchantId(商户页进入,源 channel 口径)、
* employee/edit/:id、employee/detail/:id、
* role/create、role/edit/:id、role/detail/:id
* 是二级页(老 add/detail.html 表单太长,抽屉放不下),不进菜单。
*/
const ROUTES: RouteDef[] = [
{ path: 'merchant', Page: MerchantPage },
......@@ -24,8 +31,14 @@ const ROUTES: RouteDef[] = [
{ path: 'merchant/edit/:id', Page: MerchantEditPage },
{ path: 'merchant/detail/:id', Page: MerchantDetailPage },
{ path: 'employee', Page: EmployeePage },
{ path: 'employee/create/:merchantId', Page: EmployeePage },
{ path: 'employee/create', Page: EmployeeFormPage },
{ path: 'employee/create/:merchantId', Page: EmployeeFormPage },
{ path: 'employee/edit/:id', Page: EmployeeFormPage },
{ path: 'employee/detail/:id', Page: EmployeeDetailPage },
{ path: 'role', Page: RolePage },
{ path: 'role/create', Page: RoleFormPage },
{ path: 'role/edit/:id', Page: RoleFormPage },
{ path: 'role/detail/:id', Page: RoleDetailPage },
];
function renderPage(subPath: string) {
......
......@@ -33,14 +33,6 @@ class EmployeeApi extends RpcApiClient {
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);
......
......@@ -39,7 +39,12 @@ export function useMerchantOptions(): FieldOption[] {
queryKey: ['merchant', 'allMerchant'],
queryFn: () => commonApi.findAllMerchant(),
});
return dictOptions(query.data);
// 商户行是 {id, merchantName},dictOptions 的 label 链(dictLabel/label/name)不认识 merchantName,
// 走通用映射会被整行丢弃、下拉恒空,必须在此显式映射。
const rows = Array.isArray(query.data) ? query.data : [];
return rows
.map((item) => ({ value: String(item.id ?? ''), label: String(item.merchantName ?? '') }))
.filter((item) => item.value && item.label);
}
/** 状态文案兜底:字典未下发时仍显示老系统钉死的枚举(request.js 注释逐字保留)。 */
......
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { UAlert, UButton, UCard, UEmpty, UTabs } from '@uj/ui';
import { goTo } from '@uj/platform-sdk';
import { DataTable, PageShell } from '@/components';
import type { PageParams } from '../../../routes';
import { employeeApi, merchantApi } from '@/api';
import { errorDetail } from '@/utils/error';
import { useMerchantAccess } from '@/adapter/access';
import { MC } from '@/permissions/codes';
import { asArray, nodeList, type AccountPerm } from '../../Merchant/Create/model';
import { ReadOnlyPermTree } from '../../Merchant/Create/ui';
import { staffLabelText } from '../model';
/**
* 员工详情二级页(源 temp/account/html/employee/detail.html)。
*
* 三 tab:基本信息 / 账户权限 / 修改记录。口径逐字保留:
* 空值显示「无」(:382-384)、员工标签按硬编码表翻译(:413-431)、
* 可见下级商户含本商户名时追加「(本商户)」、无值整块隐藏(:432-443)、
* 账户权限树随详情返回 accountTypeTreeResponseList(:444-475)、
* 修改记录 moduleName='员工模块' 且修改内容=module-action(:481-493)。
*/
export default function EmployeeDetailPage({ params }: { params?: PageParams } = {}) {
const { can } = useMerchantAccess();
const allowed = can(MC.EMPLOYEE_DETAIL);
const staffId = params?.id;
const [tab, setTab] = useState<'basic' | 'perm' | 'log'>('basic');
const detailQuery = useQuery({
queryKey: ['merchant', 'staffDetail', staffId],
queryFn: () => employeeApi.staffSearchRequest(staffId as string),
enabled: allowed && Boolean(staffId),
});
const detail = detailQuery.data as Record<string, unknown> | undefined;
if (!allowed) return <UEmpty description="没有查看员工权限" />;
if (!staffId) return <UEmpty description="缺少员工 id" />;
if (detailQuery.isPending) return <UEmpty description="正在读取员工详情…" />;
if (detailQuery.isError || !detail) {
return (
<UAlert
type="error"
showIcon
title="员工详情加载失败"
description={detailQuery.error ? errorDetail(detailQuery.error) : '员工不存在'}
action={
<>
<UButton type="link" onClick={() => void detailQuery.refetch()}>
重试
</UButton>
<UButton type="link" onClick={() => goTo('employee')}>
返回列表
</UButton>
</>
}
/>
);
}
// 源口径:空值显示「无」(区别于商户详情的 '-')。
const text = (value: unknown) => {
const s = String(value ?? '').trim();
return s && s !== 'null' && s !== 'undefined' ? s : '无';
};
const merchantName = text(detail.merchantName);
const permAccounts = asArray<AccountPerm>(detail.accountTypeTreeResponseList);
// 源 :432-443:可见下级商户逐项,含本商户名追加「(本商户)」;无值整块不显示。
const visibleList = String(detail.visibleInferiorMerName ?? '')
.split(',')
.map((item) => item.trim())
.filter(Boolean);
return (
<PageShell
fill
title={`员工详情 · ${text(detail.staffName)}`}
description="员工基本信息、账户权限与修改记录;均为只读展示。"
actions={
<UButton type="primary" onClick={() => goTo('employee')}>
关闭
</UButton>
}
>
<UTabs
className="uj-tabs-uniform"
activeKey={tab}
onChange={(key) => setTab(key as 'basic' | 'perm' | 'log')}
items={[
{ key: 'basic', label: '基本信息' },
{ key: 'perm', label: '账户权限' },
{ key: 'log', label: '修改记录' },
]}
/>
<div
className={tab === 'basic' ? 'uj-detail__body uj-detail__body--scroll' : 'uj-detail__body'}
>
{tab === 'basic' ? (
<div className="uj-create-card">
<section className="uj-section">
<div className="uj-detail-title-row">
<h3 className="uj-detail-title">员工基本信息</h3>
<span className="uj-detail-merchant" title={merchantName}>
{merchantName}
</span>
</div>
<dl className="uj-detail-grid">
<DetailItem label="姓名" value={text(detail.staffName)} />
<DetailItem label="登录手机号" value={text(detail.staffPhone)} />
<DetailItem label="企微号" value={text(detail.entmicroName)} />
<DetailItem label="职务" value={text(detail.staffJob)} />
<DetailItem label="角色名称" value={text(detail.roleName)} />
<DetailItem label="创建人" value={text(detail.createdAccount)} />
<DetailItem label="所属部门" value={text(detail.departmentName)} />
<DetailItem label="员工标签" value={staffLabelText(detail.staffLabel)} />
<DetailItem label="微信昵称" value={text(detail.weChatNickName)} />
<DetailItem label="微信手机号" value={text(detail.weChatPhone)} />
<DetailItem label="微信openid" value={text(detail.weChatOpenId)} />
</dl>
</section>
{visibleList.length ? (
<section className="uj-section">
<h3 className="uj-detail-title">可见下级商户</h3>
<ul className="uj-detail-visible">
{visibleList.map((name, index) => (
<li key={index}>
{name}
{merchantName !== '无' && name.includes(merchantName) ? '(本商户)' : ''}
</li>
))}
</ul>
</section>
) : null}
</div>
) : null}
{tab === 'perm' ? (
<div className="uj-create-card">
<section className="uj-section">
<h3 className="uj-detail-title">账户权限</h3>
{permAccounts.length ? (
<div className="uj-create-tabs">
<UTabs
className="uj-tabs-uniform"
items={permAccounts.map((account) => ({
key: String(account.accounttypeId),
label: account.accounttypeName ?? String(account.accounttypeId),
children: (account.products ?? []).length ? (
<UTabs
className="uj-tabs-uniform"
items={(account.products ?? []).map((product) => ({
key: String(product.productId),
label: product.productName ?? String(product.productId),
children: <ReadOnlyPermTree nodes={nodeList(product)} />,
}))}
/>
) : (
<div className="uj-create-hint">暂无产品</div>
),
}))}
/>
</div>
) : (
<div className="uj-create-hint">暂无账户权限数据</div>
)}
</section>
</div>
) : null}
{tab === 'log' ? <LogTab staffId={staffId} /> : null}
</div>
</PageShell>
);
}
function DetailItem({ label, value }: { label: string; value: string }) {
return (
<div className="uj-detail-item">
<dt>{label}</dt>
<dd title={value === '无' ? undefined : value}>{value}</dd>
</div>
);
}
function LogTab({ staffId }: { staffId: string }) {
const [page, setPage] = useState({ current: 1, size: 10 });
const logQuery = useQuery({
queryKey: ['merchant', 'staffLog', staffId, page],
queryFn: () =>
merchantApi.findLog({
bussinessId: staffId,
moduleName: '员工模块',
pageNum: page.current,
pageSize: page.size,
}),
enabled: Boolean(staffId),
});
const wrapped = (logQuery.data ?? {}) as Record<string, unknown>;
const rows = asArray<Record<string, unknown>>(wrapped.list ?? wrapped.data ?? logQuery.data);
const total = Number(wrapped.total ?? wrapped.count ?? rows.length);
return (
<UCard size="small" fill>
<DataTable<Record<string, unknown>>
fillHeight
rowKey={(row) => String(row.id ?? Math.random())}
loading={logQuery.isFetching}
dataSource={rows.map((row, index) => ({
...row,
index: (page.current - 1) * page.size + index + 1,
modifyContent: `${String(row.module ?? '')}-${String(row.action ?? '')}`,
}))}
pagination={{
current: page.current,
pageSize: page.size,
total,
showSizeChanger: false,
onChange: (current: number, size: number) => setPage({ current, size }),
}}
columns={[
{ title: '序号', dataIndex: 'index', width: 64 },
{ title: '登录账户', dataIndex: 'operator' },
{ title: '登录产品', dataIndex: 'productName', width: 180 },
{ title: '登录IP', dataIndex: 'ip', width: 180 },
{ title: '修改内容', dataIndex: 'modifyContent', width: 200 },
{ title: '操作人', dataIndex: 'userName', width: 160 },
{ title: '操作时间', dataIndex: 'createdTime', width: 190 },
]}
/>
</UCard>
);
}
/**
* 员工管理二级页的数据模型。
*
* 事实来源:temp/account/html/employee/add.html / detail.html / validPeriod.html
* - 员工标签硬编码 8 项 add.html:339-372(detail.html:417-426 同一张翻译表)
* - 密码规则 add.html:565-577(逐字两条提示)
* - 提交参数组装 add.html:519-563(visibleInferiorMer/mesVerifyFlag/merchantFileRequest/createdSource)
* 字段名、取值口径、提示文案逐字保留;布局才由本系统重排。
*/
export interface StaffFormValues {
merchantId?: string | number;
staffName?: string;
staffPhone?: string;
mesVerifyFlag?: boolean;
password?: string;
roleIds?: string | number;
staffEmail?: string;
staffJob?: string;
department?: string | number;
staffLabel?: Array<string | number>;
weChatNickName?: string;
weChatPhone?: string;
weChatOpenId?: string;
[key: string]: unknown;
}
/** add.html:339-372:value 即提交编码,顺序与源一致。 */
export const STAFF_LABEL_OPTIONS = [
{ label: '精品升级(太阳膜)', value: '1' },
{ label: '次新车转化(车衣、改色膜)', value: '4' },
{ label: '售后众筹活动', value: '3' },
{ label: '会员权益/升级', value: '0' },
{ label: '膨胀金活动', value: '2' },
{ label: '送修线索', value: '5' },
{ label: '权益核赔', value: '6' },
{ label: '二手车', value: '7' },
];
export const STAFF_LABEL_MAP: Record<string, string> = Object.fromEntries(
STAFF_LABEL_OPTIONS.map((item) => [item.value, item.label]),
);
/** 员工标签翻译(detail.html:413-431:未知值→「无」,join(','))。 */
export function staffLabelText(value: unknown): string {
const raw = String(value ?? '').trim();
if (!raw || raw === '-') return '无';
const parts = raw
.split(',')
.filter(Boolean)
.map((code) => STAFF_LABEL_MAP[code.trim()] ?? '无');
return parts.length ? parts.join(',') : '无';
}
/** add.html:566-576 逐字:空值放行(required 由字段规则另行拦截)。 */
export function staffPasswordError(value: string | undefined): string | null {
if (!value) return null;
if (value.length < 8 || value.length > 20) return '登录密码请填入8-20位字符';
if (
!/^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,20}$/.test(
value,
)
) {
return '请输入密码(8-20位,必须包含大写字母、小写字母、数字、特殊符号中3种或以上)';
}
return null;
}
export interface MerchantTreeNode {
id?: string | number;
label?: string;
children?: MerchantTreeNode[];
[key: string]: unknown;
}
/** 源特殊商户判定(add.html:599-603,611-615):单节点且 id==-1 → 全部商户。 */
export function isSpecialMerchantTree(nodes: MerchantTreeNode[]): boolean {
return nodes.length === 1 && String(nodes[0]?.id) === '-1';
}
export interface TreeItem {
key: string;
title: string;
children?: TreeItem[];
}
export function mapMerchantTree(nodes: MerchantTreeNode[]): TreeItem[] {
return nodes.map((node) => {
const children = node.children?.length ? mapMerchantTree(node.children) : undefined;
return {
key: String(node.id ?? ''),
title: String(node.label ?? ''),
...(children ? { children } : {}),
};
});
}
/** 提交只取勾选叶子(源 getCheckedNodes(true),add.html:520-536)。 */
export function collectLeafIds(nodes: MerchantTreeNode[]): Set<string> {
const result = new Set<string>();
const walk = (items: MerchantTreeNode[]) =>
items.forEach((node) => {
if (node.children?.length) walk(node.children);
else if (node.id !== undefined && node.id !== null) result.add(String(node.id));
});
walk(nodes);
return result;
}
/** 树搜索命中保留父链(源 getNodesByParamFuzzy + helper.findShowNode 同口径)。 */
export function filterMerchantTree(nodes: TreeItem[], keyword: string): TreeItem[] {
const result: TreeItem[] = [];
nodes.forEach((node) => {
const children = node.children ? filterMerchantTree(node.children, keyword) : [];
if (node.title.includes(keyword) || children.length) {
result.push({ ...node, children });
}
});
return result;
}
/**
* 「全选/全不选」的选择集:当前可见节点(过滤态=命中子树+保留父链)的 key。
* 必须用 TreeItem 的字符串 key:antd Tree 按字符串比对 checkedKeys,
* 数字 id(接口原值)写进去复选框点不亮,计数却正常(计数自己转了 String)。
*/
export function collectVisibleKeys(nodes: TreeItem[]): string[] {
return nodes.flatMap((node) => [node.key, ...collectVisibleKeys(node.children ?? [])]);
}
export interface StaffAvatar {
fileName: string;
fileUrl: string;
}
/**
* add.html:519-563 的提交组装,逐字段口径:
* - visibleInferiorMer:特殊商户 '-1',否则勾选叶子 id 逗号串;
* - mesVerifyFlag:勾选 1 / 未勾 0;
* - staffLabel:多选逗号串(xm-select name=staffLabel 的表单序列化口径);
* - merchantFileRequest:有头像才带,JSON 串 {fileName,fileUrl};
* - 编辑模式带 id;disabled 的登录手机号不参与序列化(layui 行为),
* 修改模式放开(原值为空)时才提交;
* - createdSource 固定 1(账户中心)。
*/
export function buildStaffPayload(
values: StaffFormValues,
opts: {
id?: string | number;
merchantId: string | number;
specialVisible: boolean;
checkedLeafIds: Array<string | number>;
avatar?: StaffAvatar;
phoneIncluded: boolean;
},
): Record<string, unknown> {
const params: Record<string, unknown> = {
merchantId: opts.merchantId,
visibleInferiorMer: opts.specialVisible
? '-1'
: opts.checkedLeafIds.map((id) => String(id)).join(','),
staffName: values.staffName ?? '',
password: values.password ?? '',
mesVerifyFlag: values.mesVerifyFlag ? 1 : 0,
roleIds: values.roleIds ?? '',
staffEmail: values.staffEmail ?? '',
staffJob: values.staffJob ?? '',
department: values.department ?? '',
staffLabel: (values.staffLabel ?? []).map((item) => String(item)).join(','),
createdSource: 1,
};
if (opts.phoneIncluded) params.staffPhone = values.staffPhone ?? '';
// 修改模式只读输入仍会随 layui data.field 提交(wechat 三字段同理)。
if (opts.id !== undefined) {
params.id = opts.id;
params.weChatNickName = values.weChatNickName ?? '';
params.weChatPhone = values.weChatPhone ?? '';
params.weChatOpenId = values.weChatOpenId ?? '';
}
if (opts.avatar?.fileName) {
params.merchantFileRequest = JSON.stringify(opts.avatar);
}
return params;
}
......@@ -200,10 +200,7 @@ function TimeControl({ form }: { form: FormInstance<CreateFormValues> }) {
* 编辑态登录密码(源 edit.html:361-376 + L1046-1049):
* 默认 readonly 展示详情回填值,点「重置密码」清空并解锁编辑。
*/
function PasswordEditControl({
value,
onChange,
}: ControlProps) {
function PasswordEditControl({ value, onChange }: ControlProps) {
const [reset, setReset] = useState(false);
return (
<div className="uj-time">
......@@ -214,7 +211,9 @@ function PasswordEditControl({
autoComplete="off"
readOnly={!reset}
value={String(value ?? '')}
placeholder={reset ? '请输入密码(必须包含6-20个字母+数字)' : '如需修改请点右侧「重置密码」'}
placeholder={
reset ? '请输入密码(必须包含6-20个字母+数字)' : '如需修改请点右侧「重置密码」'
}
onChange={(event) => reset && onChange?.(event.target.value)}
/>
<UButton className="uj-password__reset" onClick={() => setReset(true)}>
......@@ -254,12 +253,21 @@ function ValidityControl({
};
const quickButtons: Array<[string, number]> =
quick === 'sub'
? [['续7天', 7], ['续1年', 365], ['续2年', 730], ['续5年', 1825], ['续10年', 3650]]
: [['续7天', 7], ['续1年', 365], ['续2年', 730]];
? [
['续7天', 7],
['续1年', 365],
['续2年', 730],
['续5年', 1825],
['续10年', 3650],
]
: [
['续7天', 7],
['续1年', 365],
['续2年', 730],
];
const applyQuick = (label: string) => {
const today = dayjs().startOf('day');
const origin =
expiredAt && dayjs(expiredAt).isBefore(today, 'day') ? dayjs(expiredAt) : today;
const origin = expiredAt && dayjs(expiredAt).isBefore(today, 'day') ? dayjs(expiredAt) : today;
const years = label.includes('年') ? Number(label.replace(/[^\d]/g, '')) || 1 : 0;
const nextEnd = years ? origin.add(years, 'year') : origin.add(7, 'day');
write(origin.format('YYYY-MM-DD'), nextEnd.format('YYYY-MM-DD'));
......@@ -308,8 +316,8 @@ function BrandControl({ value, onChange, tree }: ControlProps & { tree: BrandNod
const timer = window.setTimeout(() => setDebouncedKeyword(keyword.trim()), 500);
return () => window.clearTimeout(timer);
}, [keyword]);
// 源 add.html:1266-1279:单个按钮在「全选 / 全不选」间切换。
const [checkAll, setCheckAll] = useState(false);
// 源 add.html:1266-1279:单个按钮在「全选 / 全不选」间切换;按钮态按可见集实时推导,
// 不用存的布尔(手动勾/过滤切换都会让它失真)。
const checked = useMemo(() => asArray<string | number>(value).map(String), [value]);
const visible = useMemo(() => {
const text = debouncedKeyword;
......@@ -338,6 +346,43 @@ function BrandControl({ value, onChange, tree }: ControlProps & { tree: BrandNod
walk(tree);
return keys;
}, [tree]);
// 全选只作用于过滤后可见的叶子;命中父节点在过滤树里 children 为空、会被当叶子,
// 须按全树叶子集剔除(提交口径 merchantBrandListJson 只认叶子 id)。
const visibleLeafKeys = useMemo(() => {
const leafSet = new Set(allLeafKeys.map(String));
const keys: string[] = [];
const walk = (nodes: BrandNode[]) =>
nodes.forEach((node) => {
if (node.children?.length) walk(node.children);
else if (node.id !== undefined && node.id !== null && leafSet.has(String(node.id)))
keys.push(String(node.id));
});
walk(visible);
return keys;
}, [visible, allLeafKeys]);
const allVisibleChecked = useMemo(() => {
const checkedSet = new Set(checked);
return visibleLeafKeys.length > 0 && visibleLeafKeys.every((key) => checkedSet.has(key));
}, [visibleLeafKeys, checked]);
// 与员工可见商户树同口径:任意条件改变(过滤词增删、树重载)后,勾选集重算回当前可见节点。
// 级联模式的 checkedKeys 含父节点 id,裁剪要按「可见全部节点」而不是只按叶子。
// 树为空/过滤零命中时跳过,避免误清。
const visibleAllKeys = useMemo(() => {
const keys: string[] = [];
const walk = (nodes: BrandNode[]) =>
nodes.forEach((node) => {
if (node.id !== undefined && node.id !== null) keys.push(String(node.id));
walk(node.children ?? []);
});
walk(visible);
return keys;
}, [visible]);
useEffect(() => {
if (!tree.length || !visibleAllKeys.length) return;
const visibleSet = new Set(visibleAllKeys);
const next = checked.filter((key) => visibleSet.has(key));
if (next.length !== checked.length) onChange?.(next);
}, [tree.length, visibleAllKeys, checked, onChange]);
if (!tree.length) return <span className="uj-hint">暂无数据</span>;
return (
......@@ -351,12 +396,17 @@ function BrandControl({ value, onChange, tree }: ControlProps & { tree: BrandNod
<UButton
size="small"
onClick={() => {
const next = !checkAll;
setCheckAll(next);
onChange?.(next ? allLeafKeys : []);
// 全不选要连可见父节点一起清(级联模式下 checkedKeys 含父 id,残留会亮着)。
const visibleSet = new Set(visibleAllKeys);
onChange?.(
allVisibleChecked
? checked.filter((key) => !visibleSet.has(key))
: // 全选结果=当前可见叶子(过滤态整份替换,与员工可见商户树同口径)。
[...visibleLeafKeys],
);
}}
>
{checkAll ? '全不选' : '全选'}
{allVisibleChecked ? '全不选' : '全选'}
</UButton>
</div>
<UTree
......@@ -472,7 +522,9 @@ function AddressControl({
value,
onChange,
form,
}: ControlProps & { form: FormInstance<CreateFormValues> }) {
guardRegion = false,
}: ControlProps & { form: FormInstance<CreateFormValues>; guardRegion?: boolean }) {
const message = useUMessage();
const [open, setOpen] = useState(false);
const [province, setProvince] = useState(() => String(form.getFieldValue('provinceName') ?? ''));
const [city, setCity] = useState(() => String(form.getFieldValue('cityName') ?? ''));
......@@ -549,6 +601,16 @@ function AddressControl({
initial={{ merchantAddress: address, provinceName: province, cityName: city, lat, lng }}
onCancel={() => setOpen(false)}
onOk={(next: AddressValue) => {
// 源 edit.html:1499-1507(仅编辑态启用,add.html 处已注释):
// 已选省市与落点解析出的省市不一致时提示重选,且不写入任何地址字段。
if (
guardRegion &&
province &&
(province !== next.provinceName || city !== next.cityName)
) {
message.error('您选择的地址错误,请重新选择');
return;
}
setProvince(next.provinceName ?? '');
setCity(next.cityName ?? '');
setAddress(next.merchantAddress ?? '');
......@@ -669,7 +731,7 @@ export function BasicForm({
</UFormItem>
) : null}
<UFormItem label="商户地址" name="merchantAddress" rules={[REQUIRED]} className="uj-full">
<AddressControl form={form} />
<AddressControl form={form} guardRegion={isEdit} />
</UFormItem>
<UFormItem
label="驻店联系人"
......@@ -703,14 +765,14 @@ export function BasicForm({
/>
</UFormItem>
{/* 主营品牌右侧跨两行,与左侧「经营业务类型 + 门店照片」同高;树区相应加高。 */}
<UFormItem label="主营品牌" name="merchantBrandChecked" className="uj-col-6 uj-brand-side">
<BrandControl tree={brandTree} />
</UFormItem>
<UFormItem
label="门店照片"
name="merchantFiles"
className="uj-col-6 uj-images-item"
label="主营品牌"
name="merchantBrandChecked"
className="uj-col-6 uj-brand-side"
>
<BrandControl tree={brandTree} />
</UFormItem>
<UFormItem label="门店照片" name="merchantFiles" className="uj-col-6 uj-images-item">
<ImageControl />
</UFormItem>
</div>
......
......@@ -15,6 +15,7 @@ import { PermissionForm, type PermissionFormHandle, type PermissionSeed } from '
import {
asArray,
buildCreatePayload,
isMerchantNameAvailable,
type AccountPerm,
type BrandNode,
type CreateFormValues,
......@@ -83,7 +84,8 @@ export default function CreateMerchantPage({ params }: { params?: PageParams })
if (mode === 'sub' && parent) {
// 源 getAccountLevel L2158-2174:等级须大于父级,且工厂之下不开放市代。
accountLevel = accountLevel.filter(
(item) => Number(item.value) > parentLevel && !(parentLevel === 1 && Number(item.value) === 3),
(item) =>
Number(item.value) > parentLevel && !(parentLevel === 1 && Number(item.value) === 3),
);
// 源账户类型限父级 accountType 集合(audit 1.4)。
const allowedTypes = String(parent.accountType ?? '')
......@@ -133,7 +135,8 @@ export default function CreateMerchantPage({ params }: { params?: PageParams })
channelId: parent.channelId as string | number,
merchantModel: parent.merchantModel as string | number,
// 源:上级是市代时子商户只能是门店,等级预置首项(addSubMerchant.html:630-638)。
merchantAccountLevel: form.getFieldValue('merchantAccountLevel') ?? (parentLevel === 3 ? level : undefined),
merchantAccountLevel:
form.getFieldValue('merchantAccountLevel') ?? (parentLevel === 3 ? level : undefined),
});
}, [mode, parent, parentLevel, options.accountLevel, form]);
......@@ -209,17 +212,21 @@ export default function CreateMerchantPage({ params }: { params?: PageParams })
values,
brandTree,
mode === 'sub'
? { parentId: (parent?.id ?? parentMerchantId) as string | number }
? {
parentId: (parent?.id ?? parentMerchantId) as string | number,
sub: true,
}
: {},
);
// 源 nextStepRequest L1070:createdSource 在重复名校验之后、真正提交之前补上。
if (mode === 'create') payloadParams.createdSource = 1;
// 源 nextStepRequest(add.html:1070 / addSubMerchant.html:1014-1016):
// 两种创建模式都在重复名校验之后、真正提交之前补 createdSource=1。
payloadParams.createdSource = 1;
try {
const repeated = await merchantApi.checkMerchantNameRepeat(
String(payloadParams.merchantName ?? ''),
);
if (isDuplicate(repeated)) setDuplicate(payloadParams);
else await finishCreate(payloadParams);
if (isMerchantNameAvailable(repeated)) await finishCreate(payloadParams);
else setDuplicate(payloadParams);
} catch (error) {
message.error(errorDetail(error));
}
......@@ -333,7 +340,14 @@ export default function CreateMerchantPage({ params }: { params?: PageParams })
validityQuick="sub"
/>
) : (
<PermissionForm ref={permissionRef} accounts={permissionAccounts} seed={permissionSeed} />
<PermissionForm
ref={permissionRef}
accounts={permissionAccounts}
seed={permissionSeed}
typeNameById={Object.fromEntries(
dict[DICT.ACCOUNT_TYPE].map((item) => [String(item.value), String(item.label)]),
)}
/>
)}
{brandQuery.isError ? (
<UAlert
......@@ -390,13 +404,6 @@ export default function CreateMerchantPage({ params }: { params?: PageParams })
);
}
function isDuplicate(result: unknown): boolean {
if (typeof result === 'object' && result !== null) {
return (result as { data?: unknown }).data === true;
}
return result === true;
}
function extractId(result: unknown): string | number | null {
if (typeof result === 'string' || typeof result === 'number') return result;
if (result && typeof result === 'object') {
......
......@@ -93,6 +93,17 @@ export function asArray<T>(value: unknown): T[] {
return Array.isArray(value) ? (value as T[]) : [];
}
/**
* verifyMerchantName(add.html:1113-1119 / edit.html 同款):
* 接口 data === true 表示名称仍可用,直接提交;false 才弹「商户名称已经被使用,是否确定继续使用」。
*/
export function isMerchantNameAvailable(result: unknown): boolean {
if (typeof result === 'object' && result !== null) {
return (result as { data?: unknown }).data === true;
}
return result === true;
}
export function nodeList(product: ProductPerm): PermNode[] {
return asArray<PermNode>(
product.merchantProTreeResponses ?? product.treeData ?? product.children,
......@@ -129,6 +140,8 @@ export function buildCreatePayload(
status?: string | number;
/** edit.html L1271-1273:merchantId 存在时 effectiveTime 原样回传。 */
effectiveTime?: unknown;
/** addSubMerchant.html L843-866:子商户模式 fieldToFormNameList 不含 effectiveTime。 */
sub?: boolean;
} = {},
): Record<string, unknown> {
const params: Record<string, unknown> = {
......@@ -150,7 +163,8 @@ export function buildCreatePayload(
params.cityCode = values.cityCode;
}
// fieldToFormNameList L890-904:注释掉的字段仍以空串入参,保持老协议形状。
// fieldToFormNameList(add/edit L890-904 共 13 项;addSubMerchant L843-866 共 11 项,
// 差异只有 effectiveTime——子商户模式不含它,merchantModel 由父级预置值照常入参)。
const fieldToFormNameList = [
'merchantName',
'merchantAbbreviation',
......@@ -163,7 +177,7 @@ export function buildCreatePayload(
'merchantLoginAccount',
'merchantLoginPassword',
'merchantAccountLevel',
'effectiveTime',
...(opts.sub ? [] : (['effectiveTime'] as const)),
'merchantModel',
] as const;
fieldToFormNameList.forEach((name) => {
......@@ -186,9 +200,9 @@ export function buildCreatePayload(
params.merchantFiles = JSON.stringify(values.merchantFiles);
}
// edit.html L1269-1273:门店草稿的有效期日期与原有 effectiveTime。
if (values.effectiveStarttime) params.effectiveStarttime = values.effectiveStarttime;
if (values.expireDate) params.expireDate = values.expireDate;
// edit.html L1269-1270 / addSubMerchant L900-901:有效期以 Date 对象提交(JSON 序列化为 ISO 时间)。
if (values.effectiveStarttime) params.effectiveStarttime = new Date(values.effectiveStarttime);
if (values.expireDate) params.expireDate = new Date(values.expireDate);
if (opts.id !== undefined && opts.id !== null) params.id = opts.id;
if (opts.parentId !== undefined && opts.parentId !== null) params.parentId = opts.parentId;
if (opts.effectiveTime !== undefined) params.effectiveTime = opts.effectiveTime;
......@@ -276,8 +290,8 @@ export function buildPermissionRequestList(
checked.forEach((id) => {
const node = nodeIndex.get(`${key}:${String(id)}`);
if (!node) return;
// 源 getCheckedNodes(true) 只取叶子节点;antd 的 checkedKeys 另含父节点。
if (node.children?.length) return;
// nodeChecked 即源 getCheckedNodes(true) 的全选集(含被强制勾中的祖先,
// 由 applyGtreeCheck 维持),分类逐字对齐源 L2200-2212。
if (node.logo === 'functionValue') {
const value = `${String(id)}:${node.label ?? ''}`;
const hit = functionIds.find(
......@@ -304,6 +318,63 @@ export function buildPermissionRequestList(
return result;
}
/**
* gtree.js L38-43:chkboxType {Y:'ps', N:'s'} 的级联口径(商户/角色权限树共用)。
* 勾选 → 勾满整个子树并强制勾中全部祖先(树里没有半选态);
* 取消 → 只清自身子树,祖先保持勾中。回显走 gtree.js 自定义 checkNodes(逐 id 直标,不级联),
* 所以 checkedKeys 必须原样精确显示,antd Tree 需配合 checkStrictly 再用本函数手动传播。
*/
export function applyGtreeCheck(
roots: PermNode[],
previous: Array<string | number>,
next: Array<string | number>,
): Array<string | number> {
const children = new Map<string, string[]>();
const parent = new Map<string, string | null>();
const original = new Map<string, string | number>();
const walk = (nodes: PermNode[], par: string | null) => {
nodes.forEach((node) => {
if (node.id === undefined || node.id === null) return;
const key = String(node.id);
original.set(key, node.id);
parent.set(key, par);
children.set(key, []);
if (par) children.get(par)?.push(key);
walk(node.children ?? [], key);
});
};
walk(roots, null);
const prevKeys = previous.map(String);
const nextKeys = new Set(next.map(String));
const added = [...nextKeys].filter((key) => !prevKeys.includes(key));
const removed = prevKeys.filter((key) => !nextKeys.has(key));
const result = new Set(prevKeys);
removed.forEach((key) => {
const drop = new Set<string>();
const collect = (k: string) => {
drop.add(k);
(children.get(k) ?? []).forEach(collect);
};
collect(key);
drop.forEach((k) => result.delete(k));
});
const addSubtree = (key: string) => {
result.add(key);
(children.get(key) ?? []).forEach(addSubtree);
};
added.forEach((key) => {
addSubtree(key);
let par = parent.get(key) ?? null;
while (par) {
result.add(par);
par = parent.get(par) ?? null;
}
});
return [...result].map((key) => original.get(key) ?? key);
}
/** 源 L2058-2060:勾选产品后创建权限树,默认全选所有节点。 */
export function collectNodeIndex(accounts: AccountPerm[]): {
nodeIndex: Map<string, PermNode>;
......
import type { ReactNode } from 'react';
import { useMemo, type ReactNode } from 'react';
import { UTree } from '@uj/ui';
import type { PermNode } from './model';
interface SectionTitleProps {
children: ReactNode;
......@@ -18,3 +20,32 @@ export function SectionTitle({ children, index, description }: SectionTitleProps
</div>
);
}
/** 只读权限树(商户/员工/角色详情共用):节点自带 checked 标记即回勾(源 treeTab 展示口径)。 */
export function ReadOnlyPermTree({ nodes }: { nodes: PermNode[] }) {
const checkedKeys = useMemo(() => {
const checked: Array<string | number> = [];
const walk = (items: PermNode[]) =>
items.forEach((node) => {
if ((node as { checked?: boolean }).checked && node.id !== undefined) checked.push(node.id);
walk(node.children ?? []);
});
walk(nodes);
return checked;
}, [nodes]);
if (!nodes.length) return <div className="uj-create-hint">暂无菜单功能</div>;
return (
<div className="uj-create-perm__tree">
<UTree
checkable
selectable={false}
blockNode
height={320}
disabled
fieldNames={{ title: 'label', key: 'id', children: 'children' }}
treeData={nodes as never}
checkedKeys={checkedKeys}
/>
</div>
);
}
......@@ -41,7 +41,8 @@ export function PeriodModal({
const update = useMutation({
mutationFn: (data: Record<string, unknown>) => merchantApi.updateValPerByMerId(data),
onSuccess: () => {
message.success('操作成功');
// 源 index.html:663 弹窗关闭后统一提示「修改成功」。
message.success('修改成功');
onSaved();
},
onError: (error) => message.error(errorDetail(error)),
......@@ -60,7 +61,12 @@ export function PeriodModal({
message.warning('请选择账户有效期');
return;
}
update.mutate({ id: row.id, effectiveStarttime: start, expireDate: end });
// 源 validPeriodForm.html:245-246 提交 Date 对象(JSON 序列化为完整 ISO 时间)。
update.mutate({
id: row.id,
effectiveStarttime: new Date(start),
expireDate: new Date(end),
});
return;
}
if (!effectiveTime) {
......@@ -124,9 +130,6 @@ export function PeriodModal({
<UButton size="small" onClick={() => applyQuick(10)}>
续10年
</UButton>
{overdue && hasDates ? (
<span className="uj-hint">该账户已过期,续期从今天起算</span>
) : null}
</div>
</>
) : (
......
......@@ -48,13 +48,15 @@ function labelOf(value: unknown, derived: unknown, map: Record<string, string>):
}
/**
* 行按钮可见性(源 index.html L892-951 的超管分支):后端已回 btn 时以 btn 为准;
* 缺省时按状态推导 —— edit: status!=3;createStaff: status==2;
* createSubMerchant: status==2 且等级!=4;editPeriod: status!=1。
* 行按钮可见性(源 index.html L890-951 超管分支):btn 是拿到列表后本地重算的,
* 服务端同名字段被整体覆盖,因此这里同样只看行数据推导,不读 row.btn。
* edit: status!=3;createStaff: status==2;createSubMerchant: status==2 且等级!=4;
* editPeriod: status!=1(status 1-草稿 2-正常 3-注销 4-过期)。
*/
function rowFlag(row: MerchantRow, name: 'edit' | 'createStaff' | 'createSubMerchant' | 'editPeriod'): boolean {
const flags = row['btn'] as Record<string, unknown> | undefined;
if (flags) return Boolean(flags[name]);
function rowFlag(
row: MerchantRow,
name: 'edit' | 'createStaff' | 'createSubMerchant' | 'editPeriod',
): boolean {
const status = Number(row.status);
const level = Number(row.merchantAccountLevel);
switch (name) {
......@@ -74,7 +76,8 @@ export default function MerchantPage() {
const message = useUMessage();
const queryClient = useQueryClient();
const allowed = can(MC.MERCHANT_VIEW);
const [filters, setFilters] = useState<Filters>({});
// 源 isRelevance 下拉「全部」即 value "0"(index.html:129-133),查询始终带该参数。
const [filters, setFilters] = useState<Filters>({ isRelevance: '0' });
const [page, setPage] = useState({ current: 1, size: 10 });
const [periodId, setPeriodId] = useState<MerchantRow | null>(null);
......@@ -124,10 +127,8 @@ export default function MerchantPage() {
const onPickImport = async (file: File | undefined) => {
if (!file) return;
const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
if (ext !== 'xlsx' && ext !== 'xls') {
message.error('仅支持 .xlsx / .xls 文件');
return;
}
// 源 index.html:785 只处理 xlsx/xls,其他扩展名静默忽略(文件选择框已用 accept 限定)。
if (ext !== 'xlsx' && ext !== 'xls') return;
setImportFile(file);
setUploadedUrl('');
setTemplateUrl(MERCHANT_IMPORT_TEMPLATE_URL);
......@@ -150,8 +151,9 @@ export default function MerchantPage() {
};
const submitImport = async () => {
// 源 index.html:812 未选文件直接「请选择文件」(确定按钮不置灰)。
if (!uploadedUrl) {
message.warning('请选择文件并等待上传完成');
message.warning('请选择文件');
return;
}
setSubmitting(true);
......@@ -159,9 +161,9 @@ export default function MerchantPage() {
const failureUrl = await merchantApi.import({ url: uploadedUrl });
if (failureUrl) {
setTemplateUrl(failureUrl);
message.warning('处理失败,可点击「下载失败模版」查看失败原因');
message.warning('处理失败,可点击 下载失败模版 查看失败原因');
} else {
message.success('处理成功,系统已自动创建商户');
message.success('处理成功,系统已自动创建商户,可返回列表查看');
setImportOpen(false);
await refreshList();
}
......@@ -226,7 +228,7 @@ export default function MerchantPage() {
label: '企微关联',
type: 'select',
options: [
{ label: '全部', value: '' },
{ label: '全部', value: '0' },
{ label: '已关联', value: '1' },
{ label: '未关联', value: '2' },
],
......@@ -298,7 +300,7 @@ export default function MerchantPage() {
onClick: (row) => goTo(`merchant/sub/${row.id}`),
},
{
label: '有效期',
label: '修改账户有效期',
permission: MC.MERCHANT_EDIT_PERIOD,
visible: (row) => rowFlag(row, 'editPeriod'),
onClick: (row) => setPeriodId(row),
......@@ -341,12 +343,13 @@ export default function MerchantPage() {
<UCard className="uj-filter-card" size="small">
<SearchForm
fields={fields}
initialValues={{ isRelevance: '0' }}
onSearch={(values, pagination) => {
setFilters(values);
setPage({ current: pagination.current, size: pagination.size });
}}
onReset={(_values, pagination) => {
setFilters({});
setFilters({ isRelevance: '0' });
setPage({ current: pagination.current, size: pagination.size });
}}
/>
......@@ -410,106 +413,57 @@ export default function MerchantPage() {
title="批量创建商户"
open={importOpen}
width={560}
okText="确定"
cancelText="关闭"
onCancel={() => setImportOpen(false)}
footer={
<div style={footerStyle}>
<UButton type="default" onClick={() => setImportOpen(false)}>
取消
</UButton>
onOk={() => void submitImport()}
okButtonProps={{ loading: submitting || uploading }}
>
{/* 源 index.html:730-737 结构:上传文件只读框 + 选择文件 + 下载模板;
导入中显示源 loading 文案;失败后模板链接换成红色「下载失败模版」。 */}
<div className="uj-import">
<div className="uj-import__row">
<span className="uj-import__label">上传文件:</span>
<input
className="uj-import__name"
readOnly
value={importFile?.name ?? ''}
placeholder="未选择文件"
/>
<input
ref={(node) => {
fileInput.current = node;
}}
type="file"
accept=".xlsx,.xls"
style={{ display: 'none' }}
onChange={(event) => void onPickImport(event.target.files?.[0])}
/>
<UButton onClick={() => fileInput.current?.click()}>选择文件</UButton>
<UButton
type="primary"
loading={submitting}
disabled={!uploadedUrl || uploading}
onClick={() => void submitImport()}
type="link"
className={
templateUrl === MERCHANT_IMPORT_TEMPLATE_URL ? undefined : 'uj-import__fail'
}
icon={<UExportIcon />}
onClick={() =>
downloadCenter.url({
source: 'merchant',
label: '批量创建商户导入模版',
url: templateUrl,
})
}
>
开始导入
{templateUrl === MERCHANT_IMPORT_TEMPLATE_URL ? '下载模板' : '下载失败模版'}
</UButton>
</div>
}
>
<div className="uj-import-guide">
<UAlert
type="info"
showIcon
title="导入流程"
description="先下载模板并按列填写商户数据,再上传文件;系统会自动创建商户,提交后请等待处理完成。"
/>
<section className="uj-import-step">
<div className="uj-import-step__head">
<span className="uj-import-step__no">1</span>
<span className="uj-import-step__title">下载并填写模板</span>
</div>
<div className="uj-import-step__body">
<span className="uj-import-step__desc">请按模板列填写,不要修改表头与列顺序。</span>
<UButton
type="link"
icon={<UExportIcon />}
onClick={() =>
downloadCenter.url({
source: 'merchant',
label: '批量创建商户导入模版',
url: templateUrl,
})
}
>
{templateUrl === MERCHANT_IMPORT_TEMPLATE_URL ? '下载导入模板' : '下载失败模版'}
</UButton>
</div>
</section>
<section className="uj-import-step">
<div className="uj-import-step__head">
<span className="uj-import-step__no">2</span>
<span className="uj-import-step__title">上传填写好的文件</span>
</div>
<div className="uj-import-step__body">
<button
type="button"
className={`uj-import-dropzone${uploadedUrl ? ' is-ready' : ''}`}
onClick={() => fileInput.current?.click()}
>
<input
ref={(node) => {
fileInput.current = node;
}}
type="file"
accept=".xlsx,.xls"
style={{ display: 'none' }}
onChange={(event) => void onPickImport(event.target.files?.[0])}
/>
<span className="uj-import-dropzone__icon" aria-hidden>
{uploadedUrl ? '✓' : '↑'}
</span>
<span className="uj-import-dropzone__main">
{uploading ? '文件正在上传…' : (importFile?.name ?? '点击选择 .xlsx / .xls 文件')}
</span>
<span className="uj-import-dropzone__hint">
{uploading
? '请稍候'
: uploadedUrl
? '已就绪,可点击更换文件'
: importFile
? '上传未完成,点击重新选择'
: '单次导入建议使用模板,避免列不匹配'}
</span>
</button>
</div>
</section>
{submitting ? (
<UAlert
type="warning"
showIcon
title="正在批量创建商户"
description="数据量较大,预计需等待约 1 分钟;处理过程中请勿关闭弹窗或退出当前操作,否则本次导入将失效。"
/>
<p className="uj-import__loading">
因数据量过大,系统正在加急处理,预计需等待1分钟;预计处理过程中,请不要退出当前操作,否则将导致本次批量创建商户无效。
</p>
) : null}
</div>
</UModal>
</PageShell>
);
}
/** 与 system 子系统 FormDrawer 同款:底栏右对齐。 */
const footerStyle = { display: 'flex', justifyContent: 'flex-end', gap: 8 };
import { useQuery } from '@tanstack/react-query';
import { UAlert, UButton, UEmpty, UTabs } from '@uj/ui';
import { goTo } from '@uj/platform-sdk';
import { PageShell } from '@/components';
import type { PageParams } from '../../../routes';
import { commonApi, roleApi } from '@/api';
import { errorDetail } from '@/utils/error';
import { useMerchantAccess } from '@/adapter/access';
import { MC } from '@/permissions/codes';
import { nodeList, type AccountPerm } from '../../Merchant/Create/model';
import { ReadOnlyPermTree } from '../../Merchant/Create/ui';
/**
* 角色详情二级页(源 temp/account/html/role/detail.html)。
*
* 口径逐字保留:基本信息四字段空值显示「无」(L150/L169)、所属商户在标题右侧(L97)、
* 角色权限走 findMenuFunTreeByRoleId 的「类型 tab → 产品 tab → 只读树」两层结构(L176-212)、
* 底部仅「关闭」一个按钮;源页面本就没有修改记录 tab。
*/
export default function RoleDetailPage({ params }: { params?: PageParams } = {}) {
const { can } = useMerchantAccess();
const allowed = can(MC.ROLE_DETAIL);
const roleId = params?.id;
const detailQuery = useQuery({
queryKey: ['merchant', 'roleDetail', roleId],
queryFn: () => roleApi.getById(roleId as string | number),
enabled: allowed && Boolean(roleId),
});
const detail = detailQuery.data as Record<string, unknown> | undefined;
const treeQuery = useQuery({
queryKey: ['merchant', 'rolePermTree', roleId],
queryFn: () => commonApi.findMenuFunTreeByRoleId(roleId as string | number),
enabled: allowed && Boolean(roleId),
});
const permAccounts = Array.isArray(treeQuery.data) ? (treeQuery.data as AccountPerm[]) : [];
if (!allowed) return <UEmpty description="没有查看角色权限" />;
if (!roleId) return <UEmpty description="缺少角色 id" />;
if (detailQuery.isPending) return <UEmpty description="正在读取角色详情…" />;
if (detailQuery.isError || !detail) {
return (
<UAlert
type="error"
showIcon
title="角色详情加载失败"
description={detailQuery.error ? errorDetail(detailQuery.error) : '角色不存在'}
action={
<>
<UButton type="link" onClick={() => void detailQuery.refetch()}>
重试
</UButton>
<UButton type="link" onClick={() => goTo('role')}>
返回列表
</UButton>
</>
}
/>
);
}
// 源 L169:roleData[key] || '无'。
const text = (value: unknown) => String(value ?? '').trim() || '无';
const merchantName = text(detail.merchantName);
return (
<PageShell
fill
title={`角色详情 · ${text(detail.roleName)}`}
description="角色基本信息与已授权的功能权限;均为只读展示。"
actions={
<UButton type="primary" onClick={() => goTo('role')}>
关闭
</UButton>
}
>
<div className="uj-create-card uj-detail__body--scroll">
<section className="uj-section">
<div className="uj-detail-title-row">
<h3 className="uj-detail-title">角色基本信息</h3>
<span className="uj-detail-merchant" title={merchantName}>
{merchantName}
</span>
</div>
<dl className="uj-detail-grid">
<DetailItem label="角色名称" value={text(detail.roleName)} />
<DetailItem label="角色号" value={text(detail.roleCode)} />
<DetailItem label="角色说明" value={text(detail.roleDescription)} />
</dl>
</section>
<section className="uj-section">
<h3 className="uj-detail-title">角色权限</h3>
{treeQuery.isPending ? (
<div className="uj-create-hint">权限树加载中…</div>
) : permAccounts.length ? (
<div className="uj-create-tabs">
<UTabs
className="uj-tabs-uniform"
items={permAccounts.map((account) => ({
key: String(account.accounttypeId),
label: account.accounttypeName ?? String(account.accounttypeId),
children: (account.products ?? []).length ? (
<UTabs
className="uj-tabs-uniform"
items={(account.products ?? []).map((product) => ({
key: String(product.productId),
label: product.productName ?? String(product.productId),
children: <ReadOnlyPermTree nodes={nodeList(product)} />,
}))}
/>
) : (
<div className="uj-create-hint">暂无产品</div>
),
}))}
/>
</div>
) : (
<div className="uj-create-hint">暂无角色权限数据</div>
)}
</section>
</div>
</PageShell>
);
}
function DetailItem({ label, value }: { label: string; value: string }) {
return (
<div className="uj-detail-item">
<dt>{label}</dt>
<dd title={value === '无' ? undefined : value}>{value}</dd>
</div>
);
}
import { useEffect, useRef } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import { UButton, UEmpty, UForm, UFormItem, UInput, USelect, useUMessage } from '@uj/ui';
import { goTo } from '@uj/platform-sdk';
import { PageShell } from '@/components';
import type { PageParams } from '../../../routes';
import { commonApi, roleApi } from '@/api';
import { errorDetail } from '@/utils/error';
import { useMerchantAccess } from '@/adapter/access';
import { MC } from '@/permissions/codes';
import { useMerchantOptions } from '@/hooks/useDictionaries';
import { SectionTitle } from '../../Merchant/Create/ui';
import {
asArray,
buildRolePayload,
hasAnyProduct,
type AccountPerm,
type RoleFormValues,
type RolePermSeed,
} from '../model';
import { RolePermForm, type RolePermFormHandle } from '../PermForm';
/**
* 角色创建/修改二级页(源 temp/account/html/role/add.html,按 URL id 区分两态)。
*
* 功能逐字保留:商户下拉(源 xmSelect 单选,findAllMerchant)联动重取权限树并清空已建 tab;
* 修改态所属商户为只读文本、权限按 responseList.idList 回显;
* 确定校验顺序 必填项 → '请选择角色权限' → '请选择产品';
* 存草稿仅创建态,顺序 '请选择所属商户' → '至少填一项',delFlag=1;
* 成功提示 '操作成功' 后返回列表。
* 源「全选/取消全选」按钮在源里已注释、level4 登录态商户锁定分支属老 H5 嵌入态,均不复刻。
*/
const REQUIRED = { required: true, message: '必填项' };
export default function RoleFormPage({ params }: { params?: PageParams } = {}) {
const roleId = params?.id;
const mode: 'create' | 'edit' = roleId ? 'edit' : 'create';
const { can } = useMerchantAccess();
const message = useUMessage();
const [form] = UForm.useForm<RoleFormValues>();
const allowed = can(roleId ? MC.ROLE_EDIT : MC.ROLE_CREATE);
const permRef = useRef<RolePermFormHandle>(null);
const merchantId = UForm.useWatch('merchantId', form) as string | undefined;
const merchantOptions = useMerchantOptions();
const detailQuery = useQuery({
queryKey: ['merchant', 'roleDetail', roleId],
queryFn: () => roleApi.getById(roleId as string | number),
enabled: allowed && Boolean(roleId),
});
const detail = detailQuery.data as Record<string, unknown> | undefined;
const seed = asArray<RolePermSeed>(detail?.responseList);
useEffect(() => {
if (!detail) return;
// 源 getById():merchantId 直接落到下拉值,修改态以只读文本展示。
form.setFieldsValue({
merchantId: String(detail.merchantId ?? ''),
roleName: detail.roleName as string,
roleDescription: detail.roleDescription as string,
});
}, [detail, form]);
const treeQuery = useQuery({
queryKey: ['merchant', 'roleMenuFunTree', merchantId],
queryFn: () => commonApi.findMenuFunTreeByMerId({ id: merchantId }),
enabled: allowed && Boolean(merchantId),
});
const accounts = Array.isArray(treeQuery.data) ? (treeQuery.data as AccountPerm[]) : [];
const save = useMutation({
mutationFn: (payload: Record<string, unknown>) =>
roleId ? roleApi.update(payload) : roleApi.insert(payload),
onSuccess: () => {
message.success('操作成功');
goTo('role');
},
onError: (error) => message.error(errorDetail(error)),
});
// 源 form.on('submit(roleSubmit)'):先校验必填,再 check_arr,再 getAuthList 判产品。
const submit = async () => {
let values: RoleFormValues;
try {
values = await form.validateFields();
} catch {
return;
}
if (!permRef.current?.hasTypeSelection()) {
message.error('请选择角色权限');
return;
}
const requestList = permRef.current.getRequestList();
if (!hasAnyProduct(requestList)) {
message.error('请选择产品');
return;
}
save.mutate(
buildRolePayload(values, {
id: roleId,
merchantId: merchantId ?? '',
delFlag: 0,
requestList,
}),
);
};
// 源 $('#draft'):不走必填校验,merchantId 必选 + 「至少填一项」内容检查,delFlag=1。
const saveDraft = () => {
const values = form.getFieldsValue();
if (!merchantId) {
message.error('请选择所属商户');
return;
}
const hasContent =
Boolean(values.roleName) ||
Boolean(values.roleDescription) ||
Boolean(permRef.current?.hasTypeSelection());
if (!hasContent) {
message.error('至少填一项');
return;
}
save.mutate(
buildRolePayload(values, {
merchantId,
delFlag: 1,
requestList: permRef.current?.getRequestList() ?? [],
}),
);
};
if (!allowed) return <UEmpty description="没有该操作权限" />;
if (mode === 'edit' && detailQuery.isPending) return <UEmpty description="正在读取角色详情…" />;
if (mode === 'edit' && detailQuery.isError) {
return (
<UEmpty description={detailQuery.error ? errorDetail(detailQuery.error) : '角色不存在'} />
);
}
const permBody = !merchantId ? (
<div className="uj-create-hint">请先选择所属商户</div>
) : treeQuery.isPending ? (
<div className="uj-create-hint">权限树加载中…</div>
) : accounts.length ? (
// 源 select(merchants) 回调删除所有 tab:换商户即以 key 重挂载,清空上一个商户的勾选。
<RolePermForm key={String(merchantId)} ref={permRef} accounts={accounts} seed={seed} />
) : (
<div className="uj-create-hint">该商户暂无可配置的账户类型</div>
);
return (
<PageShell
title={mode === 'edit' ? '修改角色' : '创建角色'}
description="角色归属商户与功能权限在此维护;保存后返回角色列表。"
>
<div className="uj-create-card">
<UForm
form={form}
layout="horizontal"
className="uj-edit-form"
labelCol={{ flex: '88px' }}
labelAlign="left"
>
<section className="uj-section">
<SectionTitle index="01" description="商户归属与角色标识">
角色基本信息
</SectionTitle>
{mode === 'edit' ? (
<>
<UFormItem label="所属商户" required>
<div className="uj-static-text">{String(detail?.merchantName ?? '') || '-'}</div>
</UFormItem>
{/* 修改态商户锁定(源隐藏下拉只留文本),字段仍注册供 useWatch/payload 取值。 */}
<UFormItem name="merchantId" hidden>
<UInput />
</UFormItem>
</>
) : (
<UFormItem label="所属商户" name="merchantId" rules={[REQUIRED]}>
<USelect
className="uj-edit-form__field"
showSearch
optionFilterProp="label"
placeholder="请选择商户名称"
options={merchantOptions.map((item) => ({
label: String(item.label),
value: String(item.value),
}))}
/>
</UFormItem>
)}
<UFormItem label="角色名称" name="roleName" rules={[REQUIRED]}>
<UInput className="uj-edit-form__field" maxLength={15} placeholder="请输入角色名称" />
</UFormItem>
<UFormItem label="角色说明" name="roleDescription">
<UInput className="uj-edit-form__field" maxLength={50} placeholder="请输入角色说明" />
</UFormItem>
</section>
<section className="uj-section">
<SectionTitle index="02" description="按账户类型勾选产品与功能菜单">
角色权限
</SectionTitle>
{permBody}
</section>
</UForm>
<div className="uj-create-footer">
<UButton onClick={() => goTo('role')}>取消</UButton>
{mode === 'create' ? (
<UButton loading={save.isPending} onClick={saveDraft}>
存草稿
</UButton>
) : null}
<UButton type="primary" loading={save.isPending} onClick={() => void submit()}>
确定
</UButton>
</div>
</div>
</PageShell>
);
}
import { useMemo, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { UAlert, UButton, UCard, UDrawer, UForm, useUMessage } from '@uj/ui';
import { UAlert, UButton, UCard, UTooltip, useUMessage } from '@uj/ui';
import { goTo } from '@uj/platform-sdk';
import {
CombiForm,
ConfirmModal,
DataTable,
PageShell,
......@@ -15,24 +15,51 @@ import { compactParams } from '@/utils/params';
import { errorDetail } from '@/utils/error';
import { useMerchantAccess } from '@/adapter/access';
import { MC } from '@/permissions/codes';
import { roleApi, commonApi } from '@/api';
import { roleApi } from '@/api';
import type { RoleRow } from '@/api';
import { DEL_FLAG_LABEL, useMerchantOptions } from '@/hooks/useDictionaries';
/**
* 角色列表(源 temp/account/html/role/index.html,非 level4 分支口径)。
*
* 逐字保留:筛选 商户/角色名称/状态(delFlag ''全部 · 1草稿 · 0正常,初版误加 delFlag??0
* 导致草稿角色永远不可见,已按源去掉默认值);列 序号/角色名称(两个内置角色 hover 说明)/
* 角色号/所属商户名/状态/更新时间;行操作 查看 + 修改(!(defalutRole || roleName=='系统默认角色'))
* + 删除(!defalutRole && delFlag==1,确认「是否确认删除该角色?」)。
* 查看/修改/创建全部走二级页(源 detail.html / add.html)。
*/
type Filters = { merchantId?: string; delFlag?: string; roleName?: string };
type RoleForm = Record<string, unknown>;
/** 源 index.html:145-172 layer.tips 文案逐字。 */
const ROLE_TIPS: Record<string, string> = {
'D+智享管理员': '此角色拥有嘀加智享车生活和精品升级的管理员权限。',
广联总管理员: '此角色拥有账户中心所有产品的管理员权限。',
};
function RoleNameCell({ row }: { row: RoleRow }) {
const tip = ROLE_TIPS[String(row.roleName ?? '')];
return (
<span className="uj-role-name">
{String(row.roleName ?? '')}
{tip ? (
<UTooltip title={tip}>
<span className="uj-role-name__tip" aria-label="角色说明">
ⓘ
</span>
</UTooltip>
) : null}
</span>
);
}
export default function RolePage() {
const { can } = useMerchantAccess();
const message = useUMessage();
const [form] = UForm.useForm<RoleForm>();
const queryClient = useQueryClient();
const allowed = can(MC.ROLE_VIEW);
const [filters, setFilters] = useState<Filters>({});
const [page, setPage] = useState({ current: 1, size: 10 });
const [editing, setEditing] = useState<RoleRow | null>(null);
const [formOpen, setFormOpen] = useState(false);
const [detailId, setDetailId] = useState<string | number | null>(null);
const [deleteId, setDeleteId] = useState<string | number | null>(null);
const merchantOptions = useMerchantOptions();
......@@ -40,59 +67,16 @@ export default function RolePage() {
const list = useQuery({
queryKey: ['merchant', 'roleList', params, page],
queryFn: () =>
roleApi.page({
...params,
delFlag: params.delFlag ?? 0,
pageNum: page.current,
pageSize: page.size,
}),
queryFn: () => roleApi.page({ ...params, pageNum: page.current, pageSize: page.size }),
enabled: allowed,
});
const detail = useQuery({
queryKey: ['merchant', 'roleDetail', detailId],
queryFn: async () => {
const role = await roleApi.getById(detailId as string | number);
const tree = await commonApi.findMenuFunTreeByRoleId(detailId as string | number);
return { role, tree };
},
enabled: detailId !== null,
});
const refresh = async () => {
await queryClient.invalidateQueries({ queryKey: ['merchant', 'roleList'] });
};
const closeForm = () => {
setFormOpen(false);
setEditing(null);
};
const save = useMutation({
mutationFn: (values: RoleForm) => {
const method = editing?.id ? 'update' : 'insert';
return roleApi[method]({
...values,
delFlag: values['delFlag'] ?? 0,
...(editing?.id ? { id: editing.id } : {}),
});
},
onSuccess: async () => {
message.success('保存成功');
setFormOpen(false);
setEditing(null);
await refresh();
},
onError: (error) => message.error(errorDetail(error)),
});
const remove = useMutation({
mutationFn: () => roleApi.deleteById(deleteId as string | number),
onSuccess: async () => {
message.success('删除成功');
setDeleteId(null);
await refresh();
await queryClient.invalidateQueries({ queryKey: ['merchant', 'roleList'] });
},
onError: (error) => message.error(errorDetail(error)),
});
......@@ -110,16 +94,23 @@ export default function RolePage() {
name: 'delFlag',
label: '状态',
type: 'select',
// 源 index.html:75-77 逐字顺序:全部('')/草稿(1)/正常(0)。
options: [
{ label: '全部', value: '' },
...Object.entries(DEL_FLAG_LABEL).map(([value, label]) => ({ label, value })),
{ label: DEL_FLAG_LABEL['1'], value: '1' },
{ label: DEL_FLAG_LABEL['0'], value: '0' },
],
essential: true,
},
];
const columns: DataTableColumnsType<RoleRow> = [
{ title: '角色名称', dataIndex: 'roleName', width: 180, line: 1 },
{
title: '角色名称',
dataIndex: 'roleName',
width: 200,
render: (_v, row) => <RoleNameCell row={row} />,
},
{ title: '角色号', dataIndex: 'roleCode', width: 160 },
{ title: '所属商户名', dataIndex: 'merchantName', width: 220, line: 1 },
{
......@@ -132,15 +123,16 @@ export default function RolePage() {
];
const rowActions: RowActionSchema<RoleRow>[] = [
{ label: '查看', permission: MC.ROLE_DETAIL, onClick: (row) => setDetailId(row.id ?? null) },
{
label: '查看',
permission: MC.ROLE_DETAIL,
onClick: (row) => goTo(`role/detail/${row.id}`),
},
{
label: '修改',
permission: MC.ROLE_EDIT,
visible: (row) => !row.defalutRole && row.roleName !== '系统默认角色',
onClick: (row) => {
setEditing(row);
setFormOpen(true);
},
onClick: (row) => goTo(`role/edit/${row.id}`),
},
{
label: '删除',
......@@ -151,43 +143,6 @@ export default function RolePage() {
},
];
const formFields: FieldSchema<RoleForm>[] = [
{
name: 'merchantId',
label: '所属商户',
type: 'select',
options: merchantOptions,
section: '角色信息',
},
{ name: 'roleName', label: '角色名称', type: 'input', section: '角色信息' },
{
name: 'roleDescription',
label: '角色说明',
type: 'textarea',
section: '角色信息',
itemStyle: { gridColumn: '1 / -1' },
textareaProps: { rows: 2, maxLength: 200 },
placeholder: '选填,用于说明角色的职责边界',
},
{
name: 'requestList',
label: '角色权限 requestList(JSON)',
type: 'textarea',
section: '角色权限',
itemStyle: { gridColumn: '1 / -1' },
textareaProps: { rows: 4 },
placeholder:
'[{"accountTypeId":"...","products":[{"productId":"...","functionIdList":[],"menuIdList":[]}]}]',
},
];
const detailFields: FieldSchema<Record<string, unknown>>[] = [
{ name: 'roleName', label: '角色名称', type: 'input' },
{ name: 'roleCode', label: '角色号', type: 'input' },
{ name: 'roleDescription', label: '角色说明', type: 'input' },
{ name: 'merchantName', label: '所属商户', type: 'input' },
];
return (
<PageShell
title="角色管理"
......@@ -195,13 +150,7 @@ export default function RolePage() {
fill
actions={
can(MC.ROLE_CREATE) ? (
<UButton
type="primary"
onClick={() => {
setEditing(null);
setFormOpen(true);
}}
>
<UButton type="primary" onClick={() => goTo('role/create')}>
创建角色
</UButton>
) : null
......@@ -236,6 +185,7 @@ export default function RolePage() {
<UCard size="small" fill>
<DataTable
fillHeight
showIndex
rowKey={(row) => String(row.id ?? '')}
columns={columns}
rowActions={rowActions}
......@@ -251,50 +201,6 @@ export default function RolePage() {
/>
</UCard>
<UDrawer
title={editing?.id ? '修改角色' : '创建角色'}
size={560}
open={formOpen}
onClose={closeForm}
footer={
<div style={footerStyle}>
<UButton type="default" onClick={closeForm}>
取消
</UButton>
<UButton type="primary" loading={save.isPending} onClick={() => form.submit()}>
保存
</UButton>
</div>
}
>
<CombiForm
mode="form"
form={form}
layout="vertical"
fields={formFields}
initialValues={editing ?? undefined}
sectionContentStyle={twoColumnStyle}
renderSectionTitle={(title) => <SectionTitle>{title}</SectionTitle>}
onSubmit={(values) => save.mutate(values)}
/>
</UDrawer>
<UDrawer
title="角色详情"
width={720}
open={detailId !== null}
onClose={() => setDetailId(null)}
>
<CombiForm
mode="detail"
fields={detailFields}
initialValues={detail.data?.role ?? {}}
detailColumns={2}
/>
<h4>角色权限</h4>
<pre>{JSON.stringify(detail.data?.tree ?? null, null, 2)}</pre>
</UDrawer>
<ConfirmModal
open={deleteId !== null}
content="是否确认删除该角色?"
......@@ -305,31 +211,3 @@ export default function RolePage() {
</PageShell>
);
}
/** 与 system 子系统 FormDrawer 同款:底栏右对齐、分区标题带竖条 + 下边框。 */
const footerStyle = { display: 'flex', justifyContent: 'flex-end', gap: 8 };
const twoColumnStyle = { display: 'grid', gridTemplateColumns: '1fr 1fr', columnGap: 16 };
function SectionTitle({ children }: { children: string }) {
return (
<h3 style={sectionTitleStyle}>
<span style={sectionMarkerStyle} />
{children}
</h3>
);
}
const sectionTitleStyle = {
alignItems: 'center',
borderBottom: '1px solid var(--uj-divider)',
display: 'flex',
fontSize: 14,
gap: 6,
lineHeight: '16px',
margin: '0 0 12px',
padding: '0 0 8px',
} as const;
const sectionMarkerStyle = {
backgroundColor: 'var(--uj-primary)',
borderRadius: 2,
height: 10,
width: 3,
} as const;
import {
asArray,
collectNodeIndex,
nodeList,
type AccountPerm,
type PermNode,
} from '../Merchant/Create/model';
/**
* 角色管理数据模型(源 temp/account/html/role/add.html)。
*
* requestList 组装逐字对应 getAuthList(add.html:755-833):
* logo=='function' → {id: parentId, menuId: superParentId};
* logo=='functionValue' → 聚合进同 parentId 项的 functionValue(`id:label;id:label`);
* 其余且 logo!='neglect' → menuIdList。勾选集与源 getCheckedNodes(true)(全选节点、无半选)
* 对齐:树用 checkStrictly + applyGtreeCheck 手动维持 gtree {Y:'ps',N:'s'} 级联。
*/
export type { AccountPerm, PermNode };
export { asArray, nodeList };
/** 源 getById 回显的 responseList 项:写入用 accountTypeId(getAuthList L820),
* 源回显读取用 accounttypeId(add.html:648);两种拼写都接受,避免后端归一化差异导致整棵权限不回显。 */
export interface RolePermSeed {
accountTypeId?: string | number;
accounttypeId?: string | number;
productList?: Array<{
productId?: string | number;
productName?: string;
idList?: Array<string | number>;
}>;
}
export interface RoleFormValues {
roleName?: string;
roleDescription?: string;
[key: string]: unknown;
}
export function buildRoleRequestList(
accounts: AccountPerm[],
selectedTypeIds: string[],
productChecked: Record<string, Array<string | number>>,
nodeChecked: Record<string, Array<string | number>>,
): Array<Record<string, unknown>> {
const { nodeIndex } = collectNodeIndex(accounts);
const result: Array<Record<string, unknown>> = [];
selectedTypeIds.forEach((typeId) => {
const account = accounts.find((item) => String(item.accounttypeId) === typeId);
if (!account) return;
const productList = (productChecked[typeId] ?? []).map((productId) => {
const product = (account.products ?? []).find(
(item) => String(item.productId) === String(productId),
);
const key = `${typeId}:${String(productId)}`;
if (!product || !nodeList(product).length) {
// 源 L811-817:无树数据的产品仍占位提交空清单。
return { productId, functionIdList: [], menuIdList: [] };
}
const functionValueNodes: PermNode[] = [];
const functionNodes: PermNode[] = [];
const menuIdList: Array<string | number> = [];
(nodeChecked[key] ?? []).forEach((id) => {
const node = nodeIndex.get(`${key}:${String(id)}`);
if (!node) return;
if (node.logo === 'function') functionNodes.push(node);
else if (node.logo === 'functionValue') functionValueNodes.push(node);
else if (node.logo !== 'neglect') menuIdList.push(id);
});
const functionIdList: Array<Record<string, unknown>> = [];
// 源 L782-799:functionValue 先按 parentId 归并(`;` 拼接),再落 function 项(L800-805)。
functionValueNodes.forEach((m) => {
const value = `${String(m.id)}:${String(m.label ?? '')}`;
const hit = functionIdList.find((item) => String(item.id) === String(m.parentId));
if (hit) hit.functionValue = `${String(hit.functionValue)};${value}`;
else functionIdList.push({ id: m.parentId, menuId: m.superParentId, functionValue: value });
});
functionNodes.forEach((m) => {
functionIdList.push({ id: m.parentId, menuId: m.superParentId });
});
return { productId, functionIdList, menuIdList };
});
result.push({ accountTypeId: account.accounttypeId, productList });
});
return result;
}
/** 源 insert()(add.html:576-620):delFlag 确定=0 / 草稿=1;requestList 为 JSON 串;修改带 id。 */
export function buildRolePayload(
values: RoleFormValues,
opts: {
id?: string | number;
merchantId: string | number;
delFlag: 0 | 1;
requestList: Array<Record<string, unknown>>;
},
): Record<string, unknown> {
const params: Record<string, unknown> = {
merchantId: opts.merchantId,
delFlag: opts.delFlag,
roleName: values.roleName ?? '',
roleDescription: values.roleDescription ?? '',
requestList: JSON.stringify(opts.requestList),
};
if (opts.id !== undefined && opts.id !== null) params.id = opts.id;
return params;
}
/** 源 L581:只要有一个类型带了产品即算「已选产品」。 */
export function hasAnyProduct(requestList: Array<Record<string, unknown>>): boolean {
return requestList.some((item) => asArray<unknown>(item.productList).length !== 0);
}
......@@ -3,7 +3,7 @@ import type { CSSProperties, ReactNode } from 'react';
import type { ColumnsType, TableProps } from 'antd/es/table';
import { UButton, UTable, UTooltip, UExportIcon, FillTable } from '@uj/ui';
import { PermButton } from '@/access';
import type { ActionSchema } from '../formSchema';
import type { ActionSchema, ActionTone } from '../formSchema';
/** 列表分页统一默认每页条数。 */
export const DEFAULT_PAGE_SIZE = 10;
......@@ -26,11 +26,16 @@ export interface DataTableRowSelection<T> extends NonNullable<TableProps<T>['row
}
/** 列表行操作配置;配置 permission 时自动使用权限按钮。 */
export interface RowActionSchema<T> extends Omit<ActionSchema, 'danger' | 'label' | 'onClick'> {
export interface RowActionSchema<T> extends Omit<
ActionSchema,
'danger' | 'label' | 'onClick' | 'tone'
> {
/** 可按当前行动态生成操作文案。 */
label: ReactNode | ((record: T) => ReactNode);
/** 可按当前行动态决定是否使用警示颜色。 */
danger?: boolean | ((record: T) => boolean);
/** 可按当前行动态决定语义底色('success'/'danger'),用于启用/停用这类状态切换。 */
tone?: ActionTone | ((record: T) => ActionTone);
onClick: (record: T) => void;
visible?: (record: T) => boolean;
}
......@@ -148,6 +153,11 @@ export function DataTable<T extends object>({
// tone='export' 的按钮再叠 .uj-table-action--export + 统一下载图标,
// 「导出外观统一」由这一处保证,页面只声明 tone 即可,不再各自 import 图标。
const isExport = !isRowAction && action.tone === 'export';
// 行内语义底色(启用/停用这类状态切换):tone 只认 success/danger 两档,样式在 ui 层收口。
const rowToneClass =
isRowAction && (action.tone === 'success' || action.tone === 'danger')
? `uj-row-action--${action.tone}`
: undefined;
const buttonProps = {
danger: action.danger,
disabled: action.disabled,
......@@ -157,7 +167,7 @@ export function DataTable<T extends object>({
size: 'small' as const,
icon: isExport ? <UExportIcon /> : undefined,
className: isRowAction
? undefined
? rowToneClass
: isExport
? 'uj-table-action uj-table-action--export'
: 'uj-table-action',
......@@ -214,8 +224,9 @@ export function DataTable<T extends object>({
typeof action.label === 'function' ? action.label(record) : action.label;
const danger =
typeof action.danger === 'function' ? action.danger(record) : action.danger;
const tone = typeof action.tone === 'function' ? action.tone(record) : action.tone;
return renderActionButton(
{ ...action, danger, label },
{ ...action, danger, label, tone },
() => action.onClick(record),
`row-action-${index}`,
true,
......
import { useEffect, useRef, useState } from 'react';
import type { FormInstance } from 'antd';
import {
UCascader,
UButton,
......@@ -58,6 +59,12 @@ export interface SearchFormProps<T extends Record<string, unknown>> {
pagination?: Partial<SearchPagination>;
onSearch: (values: T, pagination: SearchPagination) => void;
onReset?: (values: Partial<T>, pagination: SearchPagination) => void;
/**
* 外部传入的表单实例(默认组件内部自建)。
* 父级需要监听筛选值做级联时传入,例如员工页按「商户名称」加载「角色」选项;
* 只给这一处需求开这个口子,不要把 SearchForm 变成受控表单。
*/
form?: FormInstance;
className?: string;
/** 默认是否展开「更多筛选」,默认收起。 */
defaultExpanded?: boolean;
......@@ -68,10 +75,12 @@ export function SearchForm<T extends Record<string, unknown>>({
pagination,
onSearch,
onReset,
form: externalForm,
className,
defaultExpanded = false,
}: SearchFormProps<T>) {
const [form] = UForm.useForm();
const [innerForm] = UForm.useForm();
const form = externalForm ?? innerForm;
// 普通单选下拉以空值代表「全部」。除了补选项外,也要把未指定的初始值设为空,
// 否则组件只会显示占位状态,看起来像没有选中「全部」。
const formInitialValues = fields.reduce<Record<string, unknown>>(
......@@ -170,7 +179,7 @@ export function SearchForm<T extends Record<string, unknown>>({
const removeCondition = (condition: ActiveCondition<T>) => {
clearFields(condition.fieldNames);
if (activeConditions.length === 1) setActivePopoverOpen(false);
onSearch(form.getFieldsValue() as T, { ...searchPagination, current: 1 });
onSearch(form.getFieldsValue(true) as T, { ...searchPagination, current: 1 });
};
/** 全部清空走 onReset:页面侧把列表过滤条件一起清掉并回到第 1 页。 */
......@@ -394,7 +403,10 @@ export function SearchForm<T extends Record<string, unknown>>({
colon={false}
className={className}
size="small"
onFinish={(submitValues) => onSearch(submitValues as T, searchPagination)}
// onFinish 回传的是 validateFields 的「已注册字段」集;组合筛选(USelectInput)的
// 维度与输入值是纯 store 虚拟字段,不在其中(见上方 useWatch preserve 注释)。
// 因此整份 store 才是查询条件的真源,校验通过后按 getFieldsValue(true) 出参。
onFinish={() => onSearch(form.getFieldsValue(true) as T, searchPagination)}
>
{/* 字段与动作同处一行:动作贴最后一列底部,筛选区整体只占一条 72px 左右的横带,
而不是「一排字段 + 单独一排按钮」。窄屏由 ui.css 的媒体查询退回整行。 */}
......
......@@ -82,8 +82,9 @@ export interface FieldSchema<T extends Record<string, unknown> = Record<string,
disabled?: boolean | ((values: T) => boolean);
render?: (value: unknown, values: T) => ReactNode;
}
/** 表格工具栏动作的语义外观。导出类走统一外观(描边+下载图标),避免各页各自写图标与文案。 */
export type ActionTone = 'default' | 'primary' | 'export';
/** 表格工具栏动作的语义外观。导出类走统一外观(描边+下载图标),避免各页各自写图标与文案。
* success/danger 为状态类动作(启用/停用)的语义底色档,行内生效,样式收口在 ui 层。 */
export type ActionTone = 'default' | 'primary' | 'export' | 'success' | 'danger';
export interface ActionSchema {
label: ReactNode;
......
......@@ -19,6 +19,40 @@ const GENERIC_MESSAGE = '请求失败';
/** 各网关信封的文案键名,按常见度排列。 */
const ENVELOPE_MESSAGE_KEYS = ['msg', 'message', 'errorMessage'] as const;
/**
* 请求取消不是业务失败:切页 / 登出 / 同 key 新请求取代旧请求都会主动 abort。
*
* 判定按「语义标记 + 文案」而不是 instanceof:微前端下错误对象可能跨 realm,
* 而且 api-core / react-query / axios 各有各的取消错误类型。
* - api-core RequestError: code === 'CANCELLED',message === '请求已取消'
* - react-query CancelledError: name === 'CancelledError'
* - 原生 / axios: name === 'AbortError' / 'CanceledError',code === 'ERR_CANCELED'
*/
export function isCancelledError(error: unknown): boolean {
// 跨 realm 传递时,极少数链路会把错误拍平成字符串(如 "[CANCELLED] 请求已取消")。
if (typeof error === 'string') {
return /\[?(?:CANCELLED|CANCELED|ERR_CANCELED)\]?/.test(error) && /请求已取消|已取消/.test(error);
}
if (!error || typeof error !== 'object') return false;
const e = error as { code?: unknown; name?: unknown; message?: unknown; cause?: unknown };
const code = String(e.code ?? '');
const name = String(e.name ?? '');
const message = String(e.message ?? '');
if (
code === 'CANCELLED' ||
code === 'CANCELED' ||
code === 'ERR_CANCELED' ||
name === 'CancelledError' ||
name === 'CanceledError' ||
name === 'AbortError' ||
message === '请求已取消' ||
message === '已取消'
) {
return true;
}
return e.cause !== undefined && isCancelledError(e.cause);
}
/** 从原始响应信封里挖文案。 */
function envelopeMessage(response: unknown): string | undefined {
if (!response || typeof response !== 'object') return undefined;
......@@ -33,6 +67,10 @@ function envelopeMessage(response: unknown): string | undefined {
export function errorDetail(error: unknown): string {
if (!error) return '未知错误';
// 取消是主动行为,不是给用户看的错误;返回空串让 message.error('') 静默,
// 同时列表 Alert 的 description 也为空。判定放在最前,避免被 cause 递归钻出来。
if (isCancelledError(error)) return '';
if (typeof error === 'object') {
const e = error as { message?: unknown; code?: unknown; cause?: unknown; response?: unknown };
......
......@@ -30,23 +30,31 @@ export function SubAppLifecycle() {
queryClient.clear();
window.dispatchEvent(new CustomEvent('uj:session-changed'));
};
/**
* 顺序不能反:react-query 的 cancelQueries 会把 retryer 同步标记为已取消,
* 之后底层请求 reject 的 CANCELLED 会被它吞掉(revert 到上一次状态)。
* 反过来先 cancelRequests,queryFn 会先把 CANCELLED 当成真失败写进 cache,
* 列表随即显示「[CANCELLED] 请求已取消」。
*/
const cancelAll = (scope?: string) => {
void queryClient.cancelQueries();
// 子应用内部换页只取消「上一页」登记的请求,避免把同一事件里刚挂载的新页请求也 abort 掉。
// 菜单切换 / 登出传 undefined,按全量语义取消。
cancelRequests(scope);
};
const onLogout = () => {
cancelRequests();
cancelAll();
queryClient.clear();
};
/** 主壳切菜单:所有保活子应用一起取消上一页在途请求。 */
const onPageLeave = () => {
cancelRequests();
void queryClient.cancelQueries();
cancelAll();
};
/** 子应用内部换页:主壳 MicroApp 会在 subPath 变化时发这个事件。 */
const onNavigate = (...args: unknown[]) => {
const next = String(args[0] ?? '');
// 首屏握手时主壳会补发一次 navigate,此时没有「上一页」,不要误取消首屏请求。
if (currentScope !== undefined && currentScope !== next) {
cancelRequests();
void queryClient.cancelQueries();
}
if (currentScope !== undefined && currentScope !== next) cancelAll(currentScope);
currentScope = next;
setActiveScope(next || undefined);
};
......
......@@ -4,14 +4,42 @@ let installed = false;
const seen = new Map<string, number>();
const DEDUPE_MS = 3000;
/**
* 取消不是错误:切页 / 登出 / 同 key 请求取代都会主动 abort。
* 跨 realm 不能用 instanceof,按语义标记判定(与 @uj/biz 的 isCancelledError 同口径,
* 但 ui 是更底层包,不能反向依赖 biz,故在这里内联一份)。
*/
function isCancelled(reason: unknown): boolean {
if (typeof reason === 'string') {
return /\[?(?:CANCELLED|CANCELED|ERR_CANCELED)\]?/.test(reason) && /请求已取消|已取消/.test(reason);
}
if (!reason || typeof reason !== 'object') return false;
const e = reason as { code?: unknown; name?: unknown; message?: unknown; cause?: unknown };
const code = String(e.code ?? '');
const name = String(e.name ?? '');
const message = String(e.message ?? '');
if (
code === 'CANCELLED' ||
code === 'CANCELED' ||
code === 'ERR_CANCELED' ||
name === 'CancelledError' ||
name === 'CanceledError' ||
name === 'AbortError' ||
message === '请求已取消' ||
message === '已取消'
) {
return true;
}
return e.cause !== undefined && isCancelled(e.cause);
}
/** 从 rejection reason 里尽量取出可读错误信息。 */
function extractErrorMessage(reason: unknown): string {
if (!reason) return '请求失败,请稍后重试';
if (reason instanceof Error) return reason.message || reason.name || '请求失败,请稍后重试';
if (typeof reason === 'string') return reason;
if (typeof reason === 'object') {
const m =
(reason as { message?: unknown }).message ?? (reason as { msg?: unknown }).msg;
const m = (reason as { message?: unknown }).message ?? (reason as { msg?: unknown }).msg;
if (typeof m === 'string' && m) return m;
}
return '请求失败,请稍后重试';
......@@ -37,6 +65,10 @@ export function installGlobalUnhandledRejectionHandler(): void {
if (installed) return;
installed = true;
window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {
if (isCancelled(event.reason)) {
event.preventDefault?.();
return;
}
const text = extractErrorMessage(event.reason);
const now = Date.now();
const last = seen.get(text) ?? 0;
......
import { App as AntApp } from 'antd';
import type { JointContent } from 'antd/es/message/interface';
import { useMemo } from 'react';
/** 取当前 App 边界上的 message / notification / modal 实例。 */
......@@ -6,12 +7,31 @@ export function useUApp() {
return AntApp.useApp();
}
/** errorDetail 对取消类错误返回空串;空内容不能传给 antd,否则仍会弹一个空白通知。 */
function isEmptyContent(content: JointContent): boolean {
if (content === null || content === undefined) return true;
if (typeof content === 'string') return !content.trim();
if (typeof content === 'object' && 'content' in content) {
return isEmptyContent((content as { content: JointContent }).content);
}
return false;
}
/**
* 只要 message 的场景用这个,别在页面里解构整个 useApp。
* 返回的实例走 ConfigProvider 的主题与 locale,静态 message.xxx 拿不到,
* 在 wujie 的 shadowRoot 内还会挂到文档 body 上、脱离子应用样式作用域。
*
* error 对空内容直接短路:取消是主动行为,不该产生任何可见通知,
* 连 antd 那个只有图标的空白 toast 也不能留。
*/
export function useUMessage() {
const { message } = useUApp();
return useMemo(() => message, [message]);
return useMemo(() => {
const error: typeof message.error = (...args) => {
if (isEmptyContent(args[0])) return (() => {}) as ReturnType<typeof message.error>;
return message.error(...args);
};
return { ...message, error };
}, [message]);
}
......@@ -252,6 +252,152 @@ html body {
font-size: var(--uj-font-xl, 16px);
line-height: 24px;
}
/* 页签溢出区 .ant-tabs-nav-operations:antd 默认是无描边的裸箭头和「更多」文字按钮,
和上面的浅灰药丸轨道不是同一族。统一成轨道同族的圆形浅底按钮,并补齐四态。
这条是全局规则——所有 UTabs 都带 .uj-page__tabs,一处覆盖三个子应用。 */
.uj-page__tabs.ant-tabs > .ant-tabs-nav > .ant-tabs-nav-wrap > .ant-tabs-nav-operations {
align-self: center;
gap: 4px;
padding-left: 2px;
}
.uj-page__tabs.ant-tabs
> .ant-tabs-nav
> .ant-tabs-nav-wrap
> .ant-tabs-nav-operations
> .ant-tabs-nav-more,
.uj-page__tabs.ant-tabs
> .ant-tabs-nav
> .ant-tabs-nav-wrap
> .ant-tabs-nav-operations
> .ant-tabs-nav-operation,
.uj-page__tabs.ant-tabs > .ant-tabs-nav > .ant-tabs-nav-wrap > .ant-tabs-nav-operations > button {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
min-width: 28px;
margin: 0;
padding: 0;
border: 1px solid var(--uj-divider);
border-radius: var(--uj-radius-pill, 999px);
background: var(--uj-surface);
color: var(--uj-text-2);
font-size: 13px;
line-height: 1;
cursor: pointer;
transition:
color 0.2s ease,
background-color 0.2s ease,
border-color 0.2s ease,
transform 0.15s ease;
}
/* 「更多」是文字按钮,按内容给宽,但保持同高、同圆角、同描边。 */
.uj-page__tabs.ant-tabs
> .ant-tabs-nav
> .ant-tabs-nav-wrap
> .ant-tabs-nav-operations
> .ant-tabs-nav-more {
width: auto;
min-width: 28px;
padding: 0 8px;
}
/* antd 给「更多」挂的下划线伪元素,在药丸轨道上是多余的。 */
.uj-page__tabs.ant-tabs
> .ant-tabs-nav
> .ant-tabs-nav-wrap
> .ant-tabs-nav-operations
> .ant-tabs-nav-more::after {
display: none;
}
.uj-page__tabs.ant-tabs
> .ant-tabs-nav
> .ant-tabs-nav-wrap
> .ant-tabs-nav-operations
> .ant-tabs-nav-more:hover,
.uj-page__tabs.ant-tabs
> .ant-tabs-nav
> .ant-tabs-nav-wrap
> .ant-tabs-nav-operations
> .ant-tabs-nav-operation:hover,
.uj-page__tabs.ant-tabs
> .ant-tabs-nav
> .ant-tabs-nav-wrap
> .ant-tabs-nav-operations
> button:hover {
background: var(--uj-surface-2);
border-color: var(--uj-border-strong);
color: var(--uj-primary);
}
.uj-page__tabs.ant-tabs
> .ant-tabs-nav
> .ant-tabs-nav-wrap
> .ant-tabs-nav-operations
> .ant-tabs-nav-more:active,
.uj-page__tabs.ant-tabs
> .ant-tabs-nav
> .ant-tabs-nav-wrap
> .ant-tabs-nav-operations
> .ant-tabs-nav-operation:active,
.uj-page__tabs.ant-tabs
> .ant-tabs-nav
> .ant-tabs-nav-wrap
> .ant-tabs-nav-operations
> button:active {
transform: scale(0.94);
}
.uj-page__tabs.ant-tabs
> .ant-tabs-nav
> .ant-tabs-nav-wrap
> .ant-tabs-nav-operations
> .ant-tabs-nav-more:focus-visible,
.uj-page__tabs.ant-tabs
> .ant-tabs-nav
> .ant-tabs-nav-wrap
> .ant-tabs-nav-operations
> .ant-tabs-nav-operation:focus-visible,
.uj-page__tabs.ant-tabs
> .ant-tabs-nav
> .ant-tabs-nav-wrap
> .ant-tabs-nav-operations
> button:focus-visible {
outline: none;
box-shadow: var(--uj-ring);
}
.uj-page__tabs.ant-tabs
> .ant-tabs-nav
> .ant-tabs-nav-wrap
> .ant-tabs-nav-operations
> [aria-disabled='true'],
.uj-page__tabs.ant-tabs
> .ant-tabs-nav
> .ant-tabs-nav-wrap
> .ant-tabs-nav-operations
> button:disabled {
opacity: 0.45;
cursor: not-allowed;
transform: none;
}
/* 溢出下拉是 portal 层,拿不到 .uj-page__tabs 祖先;按同族 token 单独收口。 */
.ant-tabs-dropdown {
padding: 4px;
border: 1px solid var(--uj-divider);
border-radius: var(--uj-radius-md, 8px);
box-shadow: var(--uj-shadow-pop);
}
.ant-tabs-dropdown .ant-tabs-dropdown-menu-item {
border-radius: var(--uj-radius-sm, 4px);
color: var(--uj-text-2);
transition:
background-color 0.2s ease,
color 0.2s ease;
}
.ant-tabs-dropdown .ant-tabs-dropdown-menu-item:hover,
.ant-tabs-dropdown .ant-tabs-dropdown-menu-item.ant-tabs-dropdown-menu-item-active {
background: var(--uj-surface-2);
color: var(--uj-primary);
}
/* Tab 文案与计数角标:替代各页面手搓的 uj-num / approval-detail-tab-count。
角标底色取 border-strong(比轨道的 surface-3 深一档,在轨道上才看得见)。 */
.uj-tabs__label {
......@@ -368,12 +514,18 @@ html body {
.u-select-input__control {
flex: 1 1 auto;
}
/* borderless 变体仍有自己的 hover 底色/内边框,统一收成透明,让外框成为唯一视觉边界。 */
/* borderless 变体仍有自己的 hover 底色/内边框,统一收成透明,让外框成为唯一视觉边界。
outline 也一并压掉:antd 6 borderless 的聚焦高亮走
`&:focus-visible, &:has(input:focus-visible){outline:...}`,而 UInput 默认 allowClear,
真实 DOM 是 .ant-input-affix-wrapper 包着 input——点文本框时高亮挂在外层 wrapper 上,
只压内层 .ant-input 命不中,会和下拉那块不一致。焦点反馈统一由 .u-select-input:focus-within 承担。 */
.u-select-input__selector .ant-select-selector,
.u-select-input__control .ant-input,
.u-select-input__control .ant-input-affix-wrapper,
.u-select-input__control .ant-picker {
border: 0 !important;
box-shadow: none !important;
outline: none !important;
background: transparent !important;
}
.u-select-input__selector .ant-select-selector {
......@@ -1032,6 +1184,26 @@ html body {
outline: 2px solid var(--uj-primary);
outline-offset: 1px;
}
/* 状态切换类动作(启用/停用)用语义底色,纯文字色在密集表格里区分度不够。
tone 由 DataTable 行操作契约声明,配色只在这条链收口,页面不得自写。 */
.uj-table .uj-row-actions .ant-btn.ant-btn-text.uj-row-action--success {
color: #fff;
background: var(--uj-success);
}
.uj-table .uj-row-actions .ant-btn.ant-btn-text.uj-row-action--danger {
color: #fff;
background: var(--uj-error);
}
.uj-table .uj-row-actions .ant-btn.ant-btn-text.uj-row-action--success:hover:not(:disabled) {
color: #fff;
background: var(--uj-success);
filter: brightness(0.9);
}
.uj-table .uj-row-actions .ant-btn.ant-btn-text.uj-row-action--danger:hover:not(:disabled) {
color: #fff;
background: var(--uj-error);
filter: brightness(0.9);
}
/* 表头下边界比行线深一档,把表头「坐实」;行线仍由 Table token 的 borderColor 给。
不加阴影、不加斑马纹 —— 横向滚动 + 固定右列时斑马纹会露出错位。 */
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!