Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
ujia
/
uj-admin
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit 2b32d867
authored
Nov 16, 2026
by
chenwq
Browse Files
Options
Browse Files
Tag
Download
Plain Diff
Merge branch 'v1.0.0' of
http://192.168.3.233:8090/ujia/uj-admin
into v1.0.0
2 parents
729df768
9ffc8a8e
Pipeline
#466
for
2b32d867
failed
in 0 seconds
Changes
26
Pipelines
1
Hide whitespace changes
Inline
Side-by-side
Showing
26 changed files
with
789 additions
and
230 deletions
apps/web/shell/src/MicroApp.tsx
apps/web/subapps/finance/src/pages/Payment/index.tsx
apps/web/subapps/points/src/pages/OrderList/index.tsx
apps/web/subapps/points/src/pages/ScoreUsers/index.tsx
apps/web/subapps/points/src/pages/UserScoreDetail/index.tsx
apps/web/subapps/points/src/pages/WithdrawManage/WithdrawList.tsx
apps/web/subapps/store/src/pages/StoreListing/index.tsx
apps/web/subapps/usedcar/src/pages/Assessment/index.tsx
apps/web/subapps/usedcar/src/pages/Leads/index.tsx
apps/web/subapps/usedcar/src/pages/Operation/components/ContractTab.tsx
apps/web/subapps/usedcar/src/pages/Operation/components/SunshineTab.tsx
docs/PORT_CONVERSION.md
packages/biz/src/components/DataTable/index.tsx
packages/biz/src/components/formSchema.ts
packages/download-center/src/DownloadCenterButton.tsx
packages/download-center/src/DownloadCenterProvider.tsx
packages/download-center/src/deliver.ts
packages/download-center/src/engine.ts
packages/download-center/src/handlers/asyncExport.ts
packages/download-center/src/handlers/simple.ts
packages/download-center/src/store.ts
packages/ui/src/index.ts
packages/ui/src/styles/ui.css
packages/vite-config/src/aliases.mjs
packages/vite-config/src/react.js
packages/vite-config/src/shell.js
apps/web/shell/src/MicroApp.tsx
View file @
2b32d86
...
...
@@ -77,6 +77,7 @@ export function MicroApp({ shortName, route }: { shortName: string; route: strin
let cancelled = false;
let retried = false;
let timeoutRetried = false;
let timer = 0;
/** 失败即终态,只有 retry / 新一次挂载能清掉;避免后来到的 reject 把错误态抹回 loading。 */
...
...
@@ -95,9 +96,21 @@ export function MicroApp({ shortName, route }: { shortName: string; route: strin
window.clearTimeout(timer);
timer = window.setTimeout(() => {
// alive 复用时握手表还留着上次会话的 ready,不必等新一次上报。
if (isReady(shortName)) return;
fail(new Error('启动超时(15 秒),子应用未上报就绪。请检查子应用服务与浏览器控制台。'));
}, 15_000);
if (cancelled || isReady(shortName)) return;
// 首次超时多因 dev 冷启动:Vite 临时预构建依赖触发 iframe reload,
// 恰好打断 <short>:ready 握手。重启一次让子应用重新上报,比直接甩错误页准确。
// 只自动重试一次,避免服务真挂掉时无限重启。
if (!timeoutRetried) {
timeoutRetried = true;
launch(true);
return;
}
fail(
new Error(
'启动超时(2 次 × 20 秒),子应用未上报就绪。请检查子应用服务与浏览器控制台。',
),
);
}, 20_000);
};
if (!entry) {
...
...
apps/web/subapps/finance/src/pages/Payment/index.tsx
View file @
2b32d86
...
...
@@ -336,6 +336,7 @@ export default function Payment() {
},
{
label: '导出',
tone: 'export',
permission: FC.PAYMENT_EXPORT,
onClick: handleExport,
},
...
...
apps/web/subapps/points/src/pages/OrderList/index.tsx
View file @
2b32d86
import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { UAlert, UButton, UCard, UResult, UUpload, useUMessage } from '@uj/ui';
import { DataTable, SearchForm, type FieldSchema, type RowActionSchema } from '@/components';
import {
DataTable,
SearchForm,
type ActionSchema,
type FieldSchema,
type RowActionSchema,
} from '@/components';
import { pointsApi, type WriteOffOrder } from '@/api';
import { PP } from '@/permissions/codes';
import { usePointsAccess } from '@/features/shared/access';
...
...
@@ -106,38 +112,38 @@ export default function OrderList() {
}),
},
];
const actions: ActionSchema[] = can(PP.ORDER_EXPORT)
? [
{
label: '导出',
tone: 'export',
loading: exportAction.isPending,
onClick: () => exportAction.mutate({ ...filters }),
},
]
: [];
const toolbarExtra = can(PP.ORDER_IMPORT) ? (
<UUpload
accept=".xls,.xlsx"
showUploadList={false}
maxCount={1}
disabled={importAction.isPending}
beforeUpload={(file) => {
importAction.mutate(file);
return false;
}}
>
<UButton className="uj-table-action" size="small" loading={importAction.isPending}>
批量结算导入
</UButton>
</UUpload>
) : null;
return (
<PageShell
fill
title="积分核销订单"
description="按项目与商户查询核销记录,逐笔结算或取消结算,也可用表格批量导入结算结果。"
actions={
<>
{can(PP.ORDER_IMPORT) && (
<UUpload
accept=".xls,.xlsx"
showUploadList={false}
maxCount={1}
disabled={importAction.isPending}
beforeUpload={(file) => {
importAction.mutate(file);
return false;
}}
>
<UButton loading={importAction.isPending}>批量结算导入</UButton>
</UUpload>
)}
{can(PP.ORDER_EXPORT) && (
<UButton
loading={exportAction.isPending}
onClick={() => exportAction.mutate({ ...filters })}
>
导出
</UButton>
)}
</>
}
>
<UCard className="uj-filter-card" size="small">
<SearchForm
...
...
@@ -179,6 +185,8 @@ export default function OrderList() {
dataSource={list.records}
loading={list.query.isPending || list.query.isFetching}
rowActions={rowActions}
actions={actions}
toolbarExtra={toolbarExtra}
toolbarTitle={`共 ${list.total} 条核销记录`}
pagination={{
current: page.current,
...
...
apps/web/subapps/points/src/pages/ScoreUsers/index.tsx
View file @
2b32d86
import { useMemo, useState } from 'react';
import { UAlert, UButton, UCard, UResult, UTabs, tabLabel } from '@uj/ui';
import { DataTable, SearchForm, type FieldSchema, type RowActionSchema } from '@/components';
import {
DataTable,
SearchForm,
type ActionSchema,
type FieldSchema,
type RowActionSchema,
} from '@/components';
import { pointsApi, type StaffScoreRow } from '@/api';
import { PP } from '@/permissions/codes';
import { usePointsAccess } from '@/features/shared/access';
...
...
@@ -113,29 +119,28 @@ export default function ScoreUsers() {
},
},
];
const actions: ActionSchema[] = can(PP.SCORE_EXPORT)
? [
{
label: '导出',
tone: 'export',
loading: exportAction.isPending,
onClick: () =>
exportAction.mutate({
...filters,
channelSource: tab,
currentPage: 1,
pageSize: 9999,
}),
},
]
: [];
return (
<PageShell
fill
title="用户积分明细"
description="按渠道查看每个用户当前的积分与累计收益、兑换、抵扣,点开任意一行查看他的积分流水。"
actions={
can(PP.SCORE_EXPORT) ? (
<UButton
loading={exportAction.isPending}
onClick={() =>
exportAction.mutate({
...filters,
channelSource: tab,
currentPage: 1,
pageSize: 9999,
})
}
>
导出
</UButton>
) : null
}
>
<UTabs
activeKey={tab}
...
...
@@ -186,6 +191,7 @@ export default function ScoreUsers() {
dataSource={current.records}
loading={current.query.isPending || current.query.isFetching}
rowActions={rowActions}
actions={actions}
toolbarTitle={`共 ${current.total} 条记录`}
pagination={{
current: page.current,
...
...
apps/web/subapps/points/src/pages/UserScoreDetail/index.tsx
View file @
2b32d86
import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { UAlert, UButton, UCard, UResult } from '@uj/ui';
import { DataTable, SearchForm, type FieldSchema, type RowActionSchema } from '@/components';
import {
DataTable,
SearchForm,
type ActionSchema,
type FieldSchema,
type RowActionSchema,
} from '@/components';
import { pointsApi, rows, type ScoreDetailRow, type StaffScoreRow } from '@/api';
import { PP } from '@/permissions/codes';
import { usePointsAccess } from '@/features/shared/access';
...
...
@@ -108,6 +114,17 @@ export default function UserScoreDetail({ params }: { params: PageParams }) {
onClick: (row) => setRevokeRow(row),
},
];
const actions: ActionSchema[] = can(PP.SCORE_EXPORT)
? [
{
label: '导出',
tone: 'export',
loading: exportAction.isPending,
onClick: () =>
exportAction.mutate({ ...identity, ...filters, currentPage: 1, pageSize: 9999 }),
},
]
: [];
return (
<PageShell
...
...
@@ -115,18 +132,6 @@ export default function UserScoreDetail({ params }: { params: PageParams }) {
title="积分详情"
description="这一位用户的积分流水;可按积分类型与变化时间筛选,也可导出全部记录。"
back="users"
actions={
can(PP.SCORE_EXPORT) ? (
<UButton
loading={exportAction.isPending}
onClick={() =>
exportAction.mutate({ ...identity, ...filters, currentPage: 1, pageSize: 9999 })
}
>
导出
</UButton>
) : null
}
>
<div className="uj-points-statistics">
{cards.map((card) => (
...
...
@@ -172,6 +177,7 @@ export default function UserScoreDetail({ params }: { params: PageParams }) {
dataSource={list.records}
loading={list.query.isPending || list.query.isFetching}
rowActions={rowActions}
actions={actions}
toolbarTitle={`共 ${list.total} 条流水`}
pagination={{
current: page.current,
...
...
apps/web/subapps/points/src/pages/WithdrawManage/WithdrawList.tsx
View file @
2b32d86
import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { DownOutlined } from '@ant-design/icons';
import { UAlert, UButton, UCard, UDropdown, UResult, useUMessage } from '@uj/ui';
import { UAlert, UButton, UCard, UDropdown, U
ExportIcon, U
Result, useUMessage } from '@uj/ui';
import {
ConfirmModal,
DataTable,
...
...
@@ -400,78 +400,107 @@ export default function WithdrawList() {
/>
) : null}
<UCard size="small" fill>
<div className="uj-table-toolbar">
<div className="uj-table-toolbar__title">共 {list.total} 条提现记录</div>
<div className="uj-table-toolbar__actions">
{can(PP.WITHDRAW_BATCH) ? (
<UButton onClick={() => void askBatch(true)}>全部生成批次</UButton>
) : null}
{can([PP.WITHDRAW_APPROVE, PP.WITHDRAW_PAY, PP.WITHDRAW_REJECT, PP.WITHDRAW_BATCH]) ? (
<UDropdown
open={batchMenuOpen}
onOpenChange={setBatchMenuOpen}
menu={{
items: [
{ key: '0', label: '批量审核' },
{ key: '1', label: '批量付款' },
{ key: '2', label: '批量驳回' },
{ key: '3', label: '批量生成批次' },
],
onClick: ({ key }) => void runAction(Number(key) as 0 | 1 | 2 | 3, 'batch'),
}}
>
<UButton icon={menuArrowIcon(batchMenuOpen)} iconPlacement="end">
批量操作
<DataTable<WithdrawRow>
toolbarTitle={`共 ${list.total} 条提现记录`}
toolbarExtra={
<>
{can(PP.WITHDRAW_BATCH) ? (
<UButton className="uj-table-action" size="small" onClick={() => void askBatch(true)}>
全部生成批次
</UButton>
</UDropdown>
) : null}
{can([PP.WITHDRAW_APPROVE, PP.WITHDRAW_PAY]) ? (
<UDropdown
open={allMenuOpen}
onOpenChange={setAllMenuOpen}
menu={{
items: [
{ key: '0', label: '一键审核' },
{ key: '1', label: '一键付款' },
],
onClick: ({ key }) => void runAction(Number(key) as 0 | 1, 'all'),
}}
>
<UButton icon={menuArrowIcon(allMenuOpen)} iconPlacement="end">
一键操作
) : null}
{can([PP.WITHDRAW_APPROVE, PP.WITHDRAW_PAY, PP.WITHDRAW_REJECT, PP.WITHDRAW_BATCH]) ? (
<UDropdown
open={batchMenuOpen}
onOpenChange={setBatchMenuOpen}
menu={{
items: [
{ key: '0', label: '批量审核' },
{ key: '1', label: '批量付款' },
{ key: '2', label: '批量驳回' },
{ key: '3', label: '批量生成批次' },
],
onClick: ({ key }) => void runAction(Number(key) as 0 | 1 | 2 | 3, 'batch'),
}}
>
<UButton
className="uj-table-action"
size="small"
icon={menuArrowIcon(batchMenuOpen)}
iconPlacement="end"
>
批量操作
</UButton>
</UDropdown>
) : null}
{can([PP.WITHDRAW_APPROVE, PP.WITHDRAW_PAY]) ? (
<UDropdown
open={allMenuOpen}
onOpenChange={setAllMenuOpen}
menu={{
items: [
{ key: '0', label: '一键审核' },
{ key: '1', label: '一键付款' },
],
onClick: ({ key }) => void runAction(Number(key) as 0 | 1, 'all'),
}}
>
<UButton
className="uj-table-action"
size="small"
icon={menuArrowIcon(allMenuOpen)}
iconPlacement="end"
>
一键操作
</UButton>
</UDropdown>
) : null}
{can(PP.WITHDRAW_TAG) ? (
<UButton
className="uj-table-action"
size="small"
onClick={() => {
if (!selectedIds.length) {
message.warning('请选择要标签的明细');
return;
}
setTagging(true);
}}
>
标签标注
</UButton>
</UDropdown>
) : null}
{can(PP.WITHDRAW_TAG) ? (
<UButton
onClick={() => {
if (!selectedIds.length) {
message.warning('请选择要标签的明细');
return;
}
setTagging(true);
}}
>
标签标注
</UButton>
) : null
}
{can(PP.WITHDRAW_TAG) ? (
<UButton onClick={() => setTagDrawer(true)}>自定义标签</UButton>
) : null}
{can(PP.WITHDRAW_IMPORT) ? (
<UButton onClick={() => setImporting(true)}>提现导入</UButton>
) : null}
{can(PP.WITHDRAW_EXPORT) ? (
<UButton
loading={exportAction.isPending
}
onClick={() => exportAction.mutate({ ...filters })
}
>
导出
</UButton>
) : null}
</div>
</div
>
<DataTable<WithdrawRow>
) : null}
{can(PP.WITHDRAW_TAG) ? (
<UButton
className="uj-table-action"
size="small"
onClick={() => setTagDrawer(true)}
>
自定义标签
</UButton>
) : null}
{can(PP.WITHDRAW_IMPORT) ? (
<UButton
className="uj-table-action"
size="small"
onClick={() => setImporting(true)
}
>
提现导入
</UButton>
) : null}
{can(PP.WITHDRAW_EXPORT) ? (
<UButton
className="uj-table-action uj-table-action--export"
size="small"
icon={<UExportIcon />
}
loading={exportAction.isPending
}
onClick={() => exportAction.mutate({ ...filters })}
>
导出
</UButton>
) : null}
</
>
}
columns={columns}
// rowKey 归一为字符串:后端 id 实际是 number,统一 String(id) 后,选中键(也是基于 rowKey)
// 与行 id 同为 string,selectedRowKeys 才能命中;同时提交给后端的 ids 保持 string 不变。
...
...
apps/web/subapps/store/src/pages/StoreListing/index.tsx
View file @
2b32d86
import { useEffect, useMemo, useState } from 'react';
import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
DownloadOutlined,
SettingOutlined } from '@ant-design/icons';
import { SettingOutlined } from '@ant-design/icons';
import { UAlert, UButton, UCard, UResult, useUMessage } from '@uj/ui';
import { P, useAccess } from '@/access';
import { store, type ListingPageParams, type StoreId, type StoreListingRow } from '@/api';
...
...
@@ -146,15 +146,11 @@ export default function StoreListing() {
},
},
{
label: (
<>
<DownloadOutlined aria-hidden /> {exportFile.isPending ? '正在导出…' : '导出'}
</>
),
type: 'default',
label: exportFile.isPending ? '正在导出…' : '导出',
tone: 'export',
loading: exportFile.isPending,
permission: P.STORE_LISTING_EXPORT,
disabled:
overExportLimit || listing.isFetching || Boolean(listing.error) || exportFile.isPending,
disabled: overExportLimit || listing.isFetching || Boolean(listing.error),
onClick: () => {
if (!overExportLimit && !exportFile.isPending) exportFile.mutate();
},
...
...
apps/web/subapps/usedcar/src/pages/Assessment/index.tsx
View file @
2b32d86
...
...
@@ -6,6 +6,7 @@ import {
DataTable,
PageShell,
SearchForm,
type ActionSchema,
type FieldSchema,
type RowActionSchema,
} from '@/components';
...
...
@@ -199,29 +200,28 @@ export default function Assessment() {
}),
},
];
const actions: ActionSchema[] = canPoint(UC.ASSESS_EXPORT)
? [
{
label: '导出',
tone: 'export',
onClick: () =>
downloadCenter.asyncExport({
source: 'usedcar',
sourceLabel: '二手车管理 / 评估管理 / 评估订单导出',
label: '评估订单导出',
method: '/evalOrderManage/exportEvalOrderAsync',
params: { ...params, idsStr: selectedKeys.join(','), currentPage: 1 },
dedupeKey: 'assess-orders-export',
}),
},
]
: [];
return (
<PageShell
fill
title="评估管理"
description="查询评估单、查看车辆信息与评估进度。"
actions={
canPoint(UC.ASSESS_EXPORT) ? (
<UButton
onClick={() =>
downloadCenter.asyncExport({
source: 'usedcar',
sourceLabel: '二手车管理 / 评估管理 / 评估订单导出',
label: '评估订单导出',
method: '/evalOrderManage/exportEvalOrderAsync',
params: { ...params, idsStr: selectedKeys.join(','), currentPage: 1 },
dedupeKey: 'assess-orders-export',
})
}
>
导出
</UButton>
) : null
}
>
<UCard className="uj-filter-card" size="small">
<SearchForm
...
...
@@ -259,6 +259,7 @@ export default function Assessment() {
loading={list.isPending || list.isFetching}
rowSelection={{ selectedRowKeys: selectedKeys, onChange: setSelectedKeys }}
rowActions={rowActions}
actions={actions}
actionColumnWidth={250}
toolbarTitle={`共 ${list.data?.total ?? 0} 条评估单`}
pagination={{
...
...
apps/web/subapps/usedcar/src/pages/Leads/index.tsx
View file @
2b32d86
...
...
@@ -6,6 +6,7 @@ import {
DataTable,
PageShell,
SearchForm,
type ActionSchema,
type FieldSchema,
type RowActionSchema,
} from '@/components';
...
...
@@ -311,29 +312,28 @@ export default function Leads() {
onClick: (row) => goTo(`leads/${encodeURIComponent(String(row.id))}`),
},
];
const actions: ActionSchema[] = canPoint(UC.LEAD_EXPORT)
? [
{
label: '导出',
tone: 'export',
onClick: () =>
downloadCenter.asyncExport({
source: 'usedcar',
sourceLabel: '二手车管理 / 线索管理 / 线索导出',
label: '线索导出',
method: '/clues/exportAsync',
params: toParams(filters, status, 1, page.size),
dedupeKey: 'leads-export',
}),
},
]
: [];
return (
<PageShell
fill
title="线索管理"
actions={
canPoint(UC.LEAD_EXPORT) ? (
<UButton
onClick={() =>
downloadCenter.asyncExport({
source: 'usedcar',
sourceLabel: '二手车管理 / 线索管理 / 线索导出',
label: '线索导出',
method: '/clues/exportAsync',
params: toParams(filters, status, 1, page.size),
dedupeKey: 'leads-export',
})
}
>
导出
</UButton>
) : null
}
>
{reminders.data?.nearlyExpiredCount || reminders.data?.expiredCount ? (
<div className="uc-lead-reminder">
...
...
@@ -394,6 +394,7 @@ export default function Leads() {
dataSource={list.data?.records ?? []}
loading={list.isPending || list.isFetching}
rowActions={rowActions}
actions={actions}
actionColumnWidth={100}
toolbarTitle={`共 ${list.data?.total ?? 0} 条线索`}
pagination={{
...
...
apps/web/subapps/usedcar/src/pages/Operation/components/ContractTab.tsx
View file @
2b32d86
...
...
@@ -5,6 +5,7 @@ import { DataTable, SearchForm, type FieldSchema, type RowActionSchema } from '@
import { useAccess } from '@/access';
import { operationApi, type Contract } from '@/api';
import { UC } from '@/permissions/codes';
import { downloadCenter } from '@uj/platform-sdk';
import { CONTRACT_COLUMNS } from './tableConfig';
export default function ContractTab() {
const { canPoint } = useAccess(),
...
...
@@ -74,7 +75,28 @@ export default function ContractTab() {
? [{ label: '批量导入合同', onClick: () => setImportOpen(true) }]
: []),
...(canPoint(UC.CONTRACT_EXPORT)
? [{ label: '导出', onClick: () => msg.info('导出任务已提交') }]
? [
{
label: '导出',
tone: 'export' as const,
onClick: () =>
downloadCenter.asyncExport({
source: 'usedcar',
sourceLabel: '运营管理 / 合同管理',
label: '合同管理导出',
method: '/evalElectronicContract/exportElectronicContractAsync',
// 对齐源系统合同 handleExport():server_provider_* 平铺进 exportParam,
// 指名后端导出服务用 GSC 的 gsc-vcp-web-facade 执行业务 method。
params: {
...f,
currentPage: 1,
server_provider_type: 'gsc',
server_provider_name: 'gsc-vcp-web-facade',
},
dedupeKey: 'operation-contract-export',
}),
},
]
: []),
]}
pagination={{
...
...
apps/web/subapps/usedcar/src/pages/Operation/components/SunshineTab.tsx
View file @
2b32d86
...
...
@@ -66,6 +66,7 @@ export default function SunshineTab() {
? [
{
label: '导出',
tone: 'export' as const,
onClick: () =>
operationApi.exportSunshine(f).then(() => msg.success('导出任务已提交')),
},
...
...
docs/PORT_CONVERSION.md
View file @
2b32d86
...
...
@@ -27,6 +27,7 @@
| 1.7 | 受控
`rowSelection`
的
`selectedRowKeys`
与
`rowKey`
必须
**同类型**
(都是 string 或都是 number),禁止
`keys.map(String)`
强转 | 复选框永远勾不上(等于 === 永假) | 已有真实 bug:
`apps/web/subapps/points/src/pages/WithdrawManage/WithdrawList.tsx`
|
| 1.8 |
**全系统所有下载 / 导出必须走下载中心**
:子应用禁止自行落地文件(
`createObjectURL`
/
`window.open`
/
`a[download]`
/
`<a href>`
/
`UButton href`
触发下载),也禁止只提示「导出任务已提交」 | 绕过主壳加签与 401 统一登出、丢掉轮询 / 全站通知 / 面板历史 / 去重 / 取消;
`pnpm boundaries`
的
`download-direct`
会拦直写 |
`PORT_CONVERSION.md §14`
、
`packages/platform-sdk/src/downloadCenter.ts`
、
`scripts/check-boundaries.mjs`
|
| 1.9 |
**通用工具函数先查共享层再写**
:写任何 util 前先查
`packages/biz/src/utils`
与
`@uj/platform-sdk`
的导出;已收编的实现(
`errorDetail`
/
`goTo`
/
`loadRemoteConfig`
/
`openExportUrl`
/
`formatDateTime`
等)禁止在子应用里出现第二份 | 两份实现必然漂移(错误文案格式、跳转规则已经各漂过一次);评审直接打回 |
`PORT_CONVERSION.md §15`
、
`packages/biz/src/utils/index.ts`
、
`packages/platform-sdk/src/index.ts`
|
| 1.10 |
**对整张表数据的操作按钮只进 `DataTable` 表头**
(导出 / 批量导入 / 批量结算 / 批量重推 / 导入合同 / 列配置等),走
`actions`
或
`toolbarExtra`
;禁止留在
`PageShell`
页头。页头只放创建实体类(新增角色 / 账号 / 解散批次),行级动作仍走
`rowActions`
(如按批次导明细) | 同类按钮散落页头与表头、各页尺寸/图标/间距不一致,操作与数据对象错位(放表头丢行信息、留行内无处施力) |
`PORT_CONVERSION.md §7`
、
`packages/biz/src/components/DataTable`
、
`packages/ui/src/styles/ui.css`
|
---
...
...
@@ -165,6 +166,25 @@ UResult UEmpty USteps UTimeline UDropdown UDatePicker URadio USwit
-
列表页需要「整屏定高、表体内滚、分页贴底」时,给
`DataTable`
传
`fillHeight`
并在外层用
`PageShell fill`
(见
§
9
)。
-
**
加载态
**
:页面只传
`loading={boolean}`
(如
`query.isPending || query.isFetching`
),不要自己渲染
`Spin`
去盖表格。品牌指示器由
`UTable`
/
`FillTable`
共用的
`resolveTableLoading`
注入
`SpinProps.indicator`
(
`packages/ui/src/components/TableLoader`
),所有列表一次生效;已传对象且自带
`indicator`
/
`spinning`
的调用方保持原样。
###
7.1
表格操作按钮收口到表头(整表动作
vs
行
/
实体动作)
判定标准:
**
动作对象是「整张表的数据」还是「一条记录
/
一个实体」
**
。
|
动作对象
|
落点
|
例子
|
|---------|------|------|
|
整张表的数据
|
`DataTable`
表头(
`actions`
/
`toolbarExtra`
)
|
导出、批量导入、批量结算、批量重推、批量导入合同、列配置
|
|
一条记录
|
`DataTable`
的
`rowActions`
|
按批次导明细(放表头会丢行信息)、编辑、删除
|
|
新建一个实体
|
`PageShell`
页头
`actions`
|
新增角色、新增账号、解散批次
|
**
统一由组件层保证,页面不要自己写尺寸
/
图标
/
样式
**
:
-
声明式按钮传
`actions: ActionSchema[]`
(定义于
`packages/biz/src/components/formSchema.ts`
)。
`DataTable`
的
`renderActionButton`
(
`packages/biz/src/components/DataTable/index.tsx`
)对表头动作统一强制
`size='small'`
+
class
`.uj-table-action`
(
26
px
高
/
12
px
字
/
4
px
圆角
+
focus
-
visible
),样式真源
`packages/ui/src/styles/ui.css`
;不要自己写内联尺寸。
-
**
导出外观统一
**
:声明
`tone: 'export'`
(
`ActionTone = 'default' | 'primary' | 'export'`
)即可——
`renderActionButton`
自动叠
`.uj-table-action--export`
+
`<UExportIcon/>`
并强制
`type='default'`
;
`UExportIcon`
是
`packages/ui/src/index.ts`
里对
`DownloadOutlined`
的
re
-
export
(
biz
边界不许直接引
`@ant-design/icons`
)。页面禁止各自
import
下载图标
/
写导出专用样式。
-
`loading?: boolean`
已加进
`ActionSchema`
,异步导出把
`query.isFetching`
透传进去,不要自己切
disabled
+
转圈。
-
需要包一层控件的动作(
`UUpload`
导入、
`UDropdown`
下拉)用
`DataTable`
的
`toolbarExtra?: ReactNode`
插槽塞进表头,内部按钮同样挂
`.uj-table-action`
保持同款尺寸。
-
已收口页面可作对照:
points
`OrderList`
/
`ScoreUsers`
/
`UserScoreDetail`
/
`WithdrawManage/WithdrawList`
、
usedcar
`Leads`
/
`Assessment`
/
`Operation/components/ContractTab`
+
`SunshineTab`
、
finance
`Payment`
、
store
`StoreListing`
。
-
⚠️
操作按钮
**
放哪
**
是本条约束;按钮
**
触发的下载
/
导出行为
**
仍必须遵守铁律
1.8
与
§
14
(走
`downloadCenter`
,不自行落地文件),两者独立——不要因为按钮进了表头就绕过下载中心。
---
##
8
.
权限规范
...
...
packages/biz/src/components/DataTable/index.tsx
View file @
2b32d86
import type { CSSProperties, ReactNode } from 'react';
import type { ColumnsType, TableProps } from 'antd/es/table';
import { UButton, UTable, UTooltip, FillTable } from '@uj/ui';
import { UButton, UTable, UTooltip,
UExportIcon,
FillTable } from '@uj/ui';
import { PermButton } from '@/access';
import type { ActionSchema } from '../formSchema';
...
...
@@ -51,6 +51,8 @@ export interface DataTableProps<T> extends Pick<
}
| false;
actions?: ActionSchema[];
/** 工具栏右侧自定义节点(如下拉、上传控件):与 actions 并排渲染,共享 .uj-table-toolbar__actions 布局。 */
toolbarExtra?: ReactNode;
/** 行内操作。配置 permission 时自动按权限显示,未配置则使用普通按钮。 */
rowActions?: RowActionSchema<T>[];
/** 行内操作列标题,默认“操作”。 */
...
...
@@ -75,6 +77,7 @@ export function DataTable<T extends object>({
showIndex,
pagination,
actions,
toolbarExtra,
rowActions,
rowSelection,
actionColumnTitle = '操作',
...
...
@@ -129,27 +132,38 @@ export function DataTable<T extends object>({
style?: CSSProperties,
) => {
const type = action.type ?? (isRowAction ? ('text' as const) : undefined);
// 工具栏动作统一收口:全部 small 档(默认 middle=36px 会把表头撑厚一截),
// 并挂 .uj-table-action 让 @uj/ui 用一套 class 管精致间距/字号/状态。
// tone='export' 的按钮再叠 .uj-table-action--export + 统一下载图标,
// 「导出外观统一」由这一处保证,页面只声明 tone 即可,不再各自 import 图标。
const isExport = !isRowAction && action.tone === 'export';
const buttonProps = {
danger: action.danger,
disabled: action.disabled,
loading: action.loading,
onClick,
type,
// 行内操作按 small 出:默认高度会把每一行撑到 60px 以上,
// 两个四字操作并排就会换行,整行再翻一倍(见 .uj-row-actions 的 nowrap 说明)。
size: isRowAction ? ('small' as const) : undefined,
type: isExport ? ('default' as const) : type,
size: 'small' as const,
icon: isExport ? <UExportIcon /> : undefined,
className: isRowAction
? undefined
: isExport
? 'uj-table-action uj-table-action--export'
: 'uj-table-action',
// 行内配色统一交给 @uj/ui 的 .uj-row-actions / .uj-row-action 规则。
// 旧版在这里给每个 text 按钮塞内联 color(主色或 error),内联样式会压过
// 组件层 CSS,导致「一行只留一个常驻彩色」这类规范根本无法收口。
style,
};
const content = isExport ? <span className="uj-table-action__label">{action.label}</span> : action.label;
return action.permission ? (
<PermButton key={key} permission={action.permission} {...buttonProps}>
{
action.label
}
{
content
}
</PermButton>
) : (
<UButton key={key} {...buttonProps}>
{
action.label
}
{
content
}
</UButton>
);
};
...
...
@@ -217,14 +231,15 @@ export function DataTable<T extends object>({
const TableComponent = fillHeight ? FillTable<T> : UTable<T>;
return (
<>
{toolbarTitle || actions?.length ? (
{toolbarTitle || actions?.length
|| toolbarExtra
? (
<div className={['uj-table-toolbar', toolbarClassName].filter(Boolean).join(' ')}>
<div className="uj-table-toolbar__title">{toolbarTitle}</div>
{actions?.length ? (
{actions?.length
|| toolbarExtra
? (
<div className="uj-table-toolbar__actions">
{actions.map((action, index) =>
{actions
?
.map((action, index) =>
renderActionButton(action, action.onClick, `toolbar-action-${index}`),
)}
{toolbarExtra}
</div>
) : null}
</div>
...
...
packages/biz/src/components/formSchema.ts
View file @
2b32d86
...
...
@@ -66,6 +66,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'
;
export
interface
ActionSchema
{
label
:
ReactNode
;
type
?:
ButtonProps
[
'type'
];
...
...
@@ -73,4 +76,8 @@ export interface ActionSchema {
permission
?:
string
;
danger
?:
boolean
;
disabled
?:
boolean
;
/** 语义外观;'export' 自动套统一导出样式与下载图标(图标由 ui 层提供)。 */
tone
?:
ActionTone
;
/** 加载态,用于导出等异步按钮。 */
loading
?:
boolean
;
}
packages/download-center/src/DownloadCenterButton.tsx
View file @
2b32d86
...
...
@@ -2,7 +2,7 @@ import { useMemo, useState } from 'react';
import { Badge, Button, Empty, Popover, Tag } from 'antd';
import { DownloadOutlined, ClearOutlined } from '@ant-design/icons';
import { useDownloadCenterStore } from './store';
import { cancelTask, redownload } from './engine';
import { cancelTask, re
moveTask, re
download } from './engine';
import type { DownloadTaskStatus, DownloadTask } from './types';
type TaskFilter = 'all' | 'success' | 'failed';
...
...
@@ -63,6 +63,37 @@ const KIND_LABEL: Record<string, string> = {
const IN_FLIGHT = new Set<DownloadTaskStatus>(['waiting', 'running']);
const FINISHED = new Set<DownloadTaskStatus>(['done', 'failed', 'canceled']);
/** 浏览器下载管理快捷键:macOS 用 Command+J,其它平台用 Ctrl+J。 */
const DOWNLOAD_MANAGER_SHORTCUT = (() => {
if (typeof navigator === 'undefined') return 'Ctrl+J';
const p = navigator.platform || navigator.userAgent || '';
return /Mac|iPhone|iPad|iPod/i.test(p) ? 'Command+J' : 'Ctrl+J';
})();
/**
* 复制文本到剪贴板。http 开发环境(非安全上下文)下 navigator.clipboard 不可用,
* 降级到隐藏 textarea + execCommand('copy'),保证 dev / 生产都能用。
*/
function copyText(text: string): void {
const native =
typeof navigator !== 'undefined' && navigator.clipboard?.writeText
? navigator.clipboard.writeText(text)
: Promise.reject(new Error('clipboard unavailable'));
native.catch(() => {
const ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
try {
document.execCommand('copy');
} finally {
ta.remove();
}
});
}
/**
* source 子应用标识 -> 菜单名。面板不直接展示 points/usedcar/store 这类用户看不懂的标识,
* 优先用任务自带的 sourceLabel(菜单/页面/功能面包屑),缺省时回落到本表。
...
...
@@ -85,6 +116,15 @@ export function DownloadCenterButton() {
const tasks = useDownloadCenterStore((s) => s.tasks);
const clearFinished = useDownloadCenterStore((s) => s.clearFinished);
const [filter, setFilter] = useState<TaskFilter>('all');
const [copiedId, setCopiedId] = useState<string | null>(null);
const [showHelp, setShowHelp] = useState(false);
const handleCopyLink = (t: DownloadTask) => {
if (!t.fileUrl) return;
copyText(t.fileUrl);
setCopiedId(t.id);
window.setTimeout(() => setCopiedId((cur) => (cur === t.id ? null : cur)), 1600);
};
const activeCount = tasks.filter((t) => IN_FLIGHT.has(t.status)).length;
const successCount = tasks.filter((t) => t.status === 'done').length;
...
...
@@ -137,6 +177,37 @@ export function DownloadCenterButton() {
onClick={() => setFilter('failed')}
/>
</div>
{successCount > 0 && (
<div style={{ fontSize: 11, color: '#8c8c8c', marginTop: 8, lineHeight: 1.6 }}>
<div>
文件已自动下载;找不到可按
<strong style={{ color: '#cf1322' }}> {DOWNLOAD_MANAGER_SHORTCUT} </strong>
在浏览器下载管理查看。
<a
onClick={() => setShowHelp((v) => !v)}
style={{ marginLeft: 6, cursor: 'pointer', whiteSpace: 'nowrap' }}
>
{showHelp ? '收起' : '说明'}
</a>
</div>
{showHelp && (
<div style={{ marginTop: 4 }}>
{[
'下载中心无法直接查看或获取已下载的文件。',
'部分浏览器插件可能占用该快捷键,无响应可从浏览器菜单进入下载管理。',
'链接可能过期,仅作备用。',
'删除记录或「清除已完成」不会删除已下载到本地的文件。',
].map((text, i) => (
<div key={i} style={{ display: 'flex', gap: 4 }}>
<span>{i + 1}.</span>
<span>{text}</span>
</div>
))}
</div>
)}
</div>
)}
</div>
{/* 列表:滚动条只在这里 */}
...
...
@@ -188,15 +259,31 @@ export function DownloadCenterButton() {
</Button>
)}
{t.status === 'done' && (
<Button type="link" size="small" style={{ padding: 0 }} onClick={(e) => { e.stopPropagation(); redownload(t); }}>
再次下载
</Button>
<>
<Button type="link" size="small" style={{ padding: 0 }} onClick={(e) => { e.stopPropagation(); redownload(t); }}>
再次下载
</Button>
{t.fileUrl && (
<Button type="link" size="small" style={{ padding: 0 }} onClick={(e) => { e.stopPropagation(); handleCopyLink(t); }}>
{copiedId === t.id ? '已复制' : '复制链接'}
</Button>
)}
</>
)}
{t.status === 'failed' && (
<Button type="link" size="small" style={{ padding: 0 }} onClick={(e) => { e.stopPropagation(); redownload(t); }}>
重试
</Button>
)}
<Button
type="link"
danger
size="small"
style={{ padding: 0, marginLeft: 'auto' }}
onClick={(e) => { e.stopPropagation(); removeTask(t.id); }}
>
删除
</Button>
</div>
</li>
);
...
...
packages/download-center/src/DownloadCenterProvider.tsx
View file @
2b32d86
...
...
@@ -51,28 +51,44 @@ export function DownloadCenterProvider({
bus.$on(DOWNLOAD_CENTER_REGISTER_EVENT, onRegister);
bus.$on(DOWNLOAD_CENTER_CANCEL_EVENT, onCancel);
// 只对「本次会话新进入终态」的任务弹一次;刷新后已持久化的 done 不重弹。
const fired = new Set<string>();
// 通知去重:按「任务的第几次尝试」去重,而不是按任务 id 永久去重。
//
// 背景:url 直链任务会被复用反复重下(同一 id 走 waiting→终态→waiting→终态)。
// 用户要求「点一次出错提示一次」,所以同一 id 的每次新失败都要弹;
// 但 localStorage 恢复的历史任务、以及已经提示过的那一次,不能重复弹。
//
// 用 updatedAt 当「尝试版本号」:每次进入终态时,只有版本号比已记录的新才弹。
// store 在复用重下时会刷新 updatedAt(见 store.enqueue),所以每次重跑都是新版本;
// 挂载时把已有终态任务的版本号记为「已消化」,避免刷新后补弹旧错误。
// 这同时满足:历史不补弹 + 每次新失败都提示 + 同一成功不重复弹。
const notifiedAt = new Map<string, number>();
useDownloadCenterStore.getState().tasks.forEach((t) => {
if (t.status === 'done' || t.status === 'failed') notifiedAt.set(t.id, t.updatedAt);
});
const unsubscribe = useDownloadCenterStore.subscribe((state) => {
state.tasks.forEach((t: DownloadTask) => {
if (t.status !== 'done' && t.status !== 'failed') return;
if (fired.has(t.id)) return;
fired.add(t.id);
if (t.input.silent) return;
if (notifiedAt.get(t.id) === t.updatedAt) return; // 这一次终态已提示过
notifiedAt.set(t.id, t.updatedAt);
if (t.status === 'done') {
// silent 只压「完成」类提示;失败永远要提示,不能被 silent 吞掉。
if (t.input.silent) return;
// 仅异步导出(长任务、需「稍后查看」)弹完成通知;
// 直链 / 文件流 / 本地文件等即时落地的,不再弹「下载完成」提示。
if (t.kind !== 'async-export') return;
notification.success({
messag
e: '导出完成',
titl
e: '导出完成',
description: `${t.label}${t.fileName ? ` · ${t.fileName}` : ''}`,
placement: 'top',
});
} else {
// 失败:不论来源(points/usedcar/store…)、不论是否有链接,一律弹失败通知。
// 失败:不论来源、不论是否有链接、不论 silent,一律弹失败通知。
// 典型场景:https 页面下的 http 直链被浏览器 Mixed Content 拦截——
// 过去既误报 done 又被 silent 吞掉,现在前置校验让它落到 failed 并这里提示。
notification.error({
messag
e: t.kind === 'async-export' ? '导出失败' : '下载失败',
titl
e: t.kind === 'async-export' ? '导出失败' : '下载失败',
description: t.error || t.label,
placement: 'top',
});
...
...
packages/download-center/src/deliver.ts
View file @
2b32d86
...
...
@@ -47,6 +47,133 @@ export function saveBlob(blob: Blob, fileName: string): void {
}
/**
* 下载地址前置校验:在把 URL 交给 iframe / 锚点之前,先拦截「发起前即可判定」的错误。
*
* 为什么需要:iframe 是 fire-and-forget,加载结果(404/500/网络/Mixed Content)
* 因浏览器安全模型 JS 读不到,过去 url 类任务因此总是误报成功。其中 Mixed Content
* 是发起前就能确定判定的——当前页面 https、目标为明文 http(且非本地回环)时,
* 浏览器必然 block("content must be served over HTTPS")。与其盲发 iframe 后误报
* 成功,不如在这里直接抛错,让任务进 failed 并把可操作的根因提示给用户。
*
* 注意:这里只覆盖协议冲突与 URL 非法;加载后才出现的 HTTP 错误码 / 网络中断
* 无法从 iframe 感知,需改用 stream kind(fetch + Blob)才能捕获,属调用方选型问题。
*/
export
function
assertDownloadableUrl
(
url
:
string
):
void
{
let
parsed
:
URL
;
try
{
parsed
=
new
URL
(
url
,
window
.
location
.
href
);
}
catch
{
throw
new
Error
(
'下载地址无效:URL 无法解析'
);
}
if
(
window
.
location
.
protocol
===
'https:'
&&
parsed
.
protocol
===
'http:'
&&
!
[
'localhost'
,
'127.0.0.1'
,
'::1'
].
includes
(
parsed
.
hostname
)
)
{
throw
new
Error
(
`下载地址被浏览器拦截:当前页面为 HTTPS,但文件地址是明文 HTTP(
${
parsed
.
host
}
)。`
+
'浏览器禁止 HTTPS 页面加载 HTTP 资源,文件不会下载。请改用 HTTPS 下载地址。'
,
);
}
}
/**
* 下载地址探测结果:
* - ok 可下载(响应体已备好,可直接交给浏览器落盘)
* - error 发起前能确定的失败(HTTP 错误码 / 200 伪装的 JSON 业务错误 / Mixed Content)
* - opaque 无法探测(跨域 CORS 拦截 / 非 http 协议),此时退回 iframe 盲开
*/
export
type
ProbeResult
=
|
{
kind
:
'ok'
;
blob
:
Blob
;
fileName
:
string
;
bytes
:
number
}
|
{
kind
:
'error'
;
message
:
string
}
|
{
kind
:
'opaque'
};
function
isJsonContentType
(
ct
:
string
):
boolean
{
return
/json/i
.
test
(
ct
);
}
/**
* 下载前用 fetch 探测直链,把过去 iframe 读不到的失败变成可见错误。
*
* 背景:url 直链原来一律用隐藏 iframe fire-and-forget,浏览器加载到 404/500、
* 或后端用 200 + JSON 错误码(如「请求资源不存在」)返回业务错误时,JS 无从得知,
* 任务因此误报 done、零提示。这里改成先 fetch 拿响应:
* - 同源 / 带 CORS 的地址能读到 status 与 body,失败即抛可读错误;
* - 跨域且无 CORS 的 OSS 预签名地址会 TypeError,标为 opaque 退回 iframe,
* 不破坏原有「自带鉴权直链」下载能力(这类地址的失败仍无法感知,是浏览器限制)。
*
* credentials:'include' 让同源需登录态的直链(回单等)带上会话;
* 跨域预签名地址忽略 credential,不受影响。
*/
export
async
function
probeDownloadUrl
(
url
:
string
,
fallbackName
:
string
,
signal
?:
AbortSignal
,
):
Promise
<
ProbeResult
>
{
// 发起前先做 Mixed Content / 非法 URL 校验,能确定的失败直接返回。
try
{
assertDownloadableUrl
(
url
);
}
catch
(
e
)
{
return
{
kind
:
'error'
,
message
:
e
instanceof
Error
?
e
.
message
:
'下载地址无效'
};
}
// 同源需登录态的直链(回单等)带 cookie;跨域预签名地址不带——
// 否则后端 Access-Control-Allow-Origin:* 与 include 冲突会被 CORS 拒绝,
// 白白把本来能探测的地址降级成 opaque。
let
sameOrigin
=
false
;
try
{
sameOrigin
=
new
URL
(
url
,
window
.
location
.
href
).
origin
===
window
.
location
.
origin
;
}
catch
{
/* URL 非法已在 assertDownloadableUrl 拦下,这里保持 false */
}
let
res
:
Response
;
try
{
res
=
await
fetch
(
url
,
{
method
:
'GET'
,
credentials
:
sameOrigin
?
'include'
:
'omit'
,
signal
,
});
}
catch
(
e
)
{
// 主动取消:交给外层按取消处理,这里当作 opaque 不误报失败。
if
(
signal
?.
aborted
||
(
e
instanceof
DOMException
&&
e
.
name
===
'AbortError'
))
{
return
{
kind
:
'opaque'
};
}
// 跨域无 CORS / 网络不可达:无法读取响应,退回 iframe 盲开。
return
{
kind
:
'opaque'
};
}
const
contentType
=
res
.
headers
.
get
(
'content-type'
)
??
''
;
// 200 + JSON:后端用成功态伪装的业务错误,解出 message 当失败处理。
if
(
isJsonContentType
(
contentType
))
{
const
text
=
await
res
.
text
().
catch
(()
=>
''
);
return
{
kind
:
'error'
,
message
:
invalidDownload
(
text
).
message
};
}
// 200 + HTML:网关错误页 / 登录跳板页同样会伪装成成功态。
// 文件下载不会返回 text/html(xlsx/pdf/zip/octet-stream 都不是),
// 读到就当失败,避免把错误页当成文件落盘的「假成功」。
if
(
/html/i
.
test
(
contentType
))
{
const
text
=
await
res
.
text
().
catch
(()
=>
''
);
const
title
=
/<title
[^
>
]
*>
([\s\S]
*
?)
<
\/
title>/i
.
exec
(
text
)?.[
1
]?.
trim
();
return
{
kind
:
'error'
,
message
:
`下载失败:地址返回的是页面而非文件
${
title
?
`(
${
title
}
)`
:
''
}
`
,
};
}
if
(
!
res
.
ok
)
{
return
{
kind
:
'error'
,
message
:
`下载失败:请求资源不存在或不可访问(HTTP
${
res
.
status
}
)`
,
};
}
const
disposition
=
res
.
headers
.
get
(
'content-disposition'
)
??
''
;
const
fileName
=
parseFileName
(
disposition
,
fallbackName
);
const
blob
=
await
res
.
blob
();
return
{
kind
:
'ok'
,
blob
,
fileName
,
bytes
:
blob
.
size
};
}
/**
* 打开自带鉴权的 URL。
*
* 默认(openInNewTab=true)走**隐藏 iframe 后台下载**:把下载 URL 指给一个
...
...
@@ -61,6 +188,7 @@ export function saveBlob(blob: Blob, fileName: string): void {
* 同源、需要签名头才能取到的文件必须走 stream kind,经主壳 request 拿流。
*/
export
function
openUrl
(
url
:
string
,
openInNewTab
=
true
):
void
{
assertDownloadableUrl
(
url
);
if
(
openInNewTab
)
{
const
iframe
=
document
.
createElement
(
'iframe'
);
iframe
.
style
.
position
=
'fixed'
;
...
...
packages/download-center/src/engine.ts
View file @
2b32d86
import
type
{
RemoteRequestFn
,
UrlPayload
}
from
'@uj/contracts'
;
import
type
{
RemoteRequestFn
}
from
'@uj/contracts'
;
import
{
useDownloadCenterStore
}
from
'./store'
;
import
{
deliverTools
,
openUrl
}
from
'./deliver'
;
import
{
deliverTools
}
from
'./deliver'
;
import
{
handlerOf
,
registerHandler
}
from
'./handlers/registry'
;
import
{
registerBuiltinHandlers
}
from
'./handlers/builtin'
;
import
type
{
DownloadContext
,
DownloadHandler
,
DownloadTask
}
from
'./types'
;
...
...
@@ -143,17 +143,25 @@ export function cancelTask(id: string): void {
}
/**
* 面板「再次下载」:
* - 有 URL(异步导出 / url 类)直接重新打开;
* - 流 / 本地生成类没有可复用地址,重新登记一个同类任务执行一遍。
* 删除单条记录:在途任务先 abort 让请求 / 轮询立刻停下,再移除记录。
* 只删本地记录,不触碰已由浏览器下载到本地的文件。
*/
export
function
removeTask
(
id
:
string
):
void
{
controllers
.
get
(
id
)?.
abort
();
useDownloadCenterStore
.
getState
().
remove
(
id
);
}
/**
* 面板「再次下载」:统一重新登记同类任务、走 handler 完整重跑一遍。
*
* 早期实现「有 URL 就直接 openUrl」是错路:
* - url 直链:openUrl 是 iframe 盲开,依赖后端 Content-Disposition=attachment 才落盘;
* 回单这类 inline PDF 只会在 0×0 隐藏 iframe 里渲染,用户看到「点了没反应」。
* 重跑 urlHandler 会走 probe + saveBlob(<a download>),与首次下载同一条成功链路。
* - 异步导出:重跑 asyncExport 会重新提交生成,拿到的是新地址,语义更准。
* 统一由 enqueue 去重:url 类按地址复用同一条任务(不新增条目),其它类新建任务。
*/
export
function
redownload
(
task
:
DownloadTask
):
void
{
const
url
=
task
.
fileUrl
??
(
task
.
kind
===
'url'
?
(
task
.
input
.
payload
as
UrlPayload
)?.
url
:
undefined
);
if
(
url
)
{
openUrl
(
url
);
return
;
}
useDownloadCenterStore
.
getState
().
enqueue
({
...
task
.
input
,
fileName
:
task
.
fileName
??
task
.
input
.
fileName
,
...
...
packages/download-center/src/handlers/asyncExport.ts
View file @
2b32d86
...
...
@@ -8,16 +8,38 @@ import type {
}
from
'../types'
;
/**
* 源系统 sys.base.js 的 path = 'dj.api.',拼出的完整 method 串如下。
* ⚠️ 这两个接口在老业务网关上(request.js 自带 app_key / timestamp / sessionId / sign),
* 既不是主壳 http.request 的 RSA 通道,也不是 GSC/ROP 的 HMAC 通道。
* 若新后端以 REST 路径暴露等价能力,用 submitMethod / queryMethod 覆盖,或指定 channel。
* 源系统 sys.base.js 的 path = 'dj.api.',完整 method 串如下。
* 源侧解析链(已核实):resolveApiName('dj.api.common.*') → 'dj' → baseConfig.axios
* = rop-dj-smartcarlife/router,签名 sha1(request.js 的 appKey/timestamp/sessionId/sign)。
* 即它就是 ROP 主网关,与 usedcarClient.postRop 同一套。新系统默认走 host(web-host RSA);
* 若后端已把 method 映射成 web 路由即可通,否则用 submitMethod/queryMethod + channel 覆盖。
*/
const
DEFAULT_SUBMIT_METHOD
=
'dj.api.common.async.exportExcel'
;
const
DEFAULT_QUERY_METHOD
=
'dj.api.common.query.async.exportExcel'
;
const
DEFAULT_POLL_INTERVAL
=
3000
;
const
DEFAULT_TIMEOUT_MS
=
10
*
60
*
1000
;
/** 诊断日志开关:DEV 默认开;生产用 localStorage.setItem('uj:download-center:debug','1') 临时打开。 */
const
DEBUG_KEY
=
'uj:download-center:debug'
;
function
debugLog
(
scope
:
string
,
...
args
:
unknown
[]):
void
{
let
on
=
false
;
try
{
// 库包经 vite optimizeDeps 预构建时 import.meta.env 会被擦成 undefined,
// 故加 hostname 兜底:dev server 一定是 localhost/127.0.0.1,生产默认关。
const
flag
=
localStorage
.
getItem
(
DEBUG_KEY
);
if
(
flag
===
'1'
)
on
=
true
;
else
if
(
flag
===
'0'
)
on
=
false
;
else
{
const
meta
=
import
.
meta
as
ImportMeta
&
{
env
?:
{
DEV
?:
boolean
}
};
const
host
=
typeof
location
!==
'undefined'
?
location
.
hostname
:
''
;
on
=
meta
.
env
?.
DEV
===
true
||
host
===
'localhost'
||
host
===
'127.0.0.1'
;
}
}
catch
{
on
=
false
;
}
if
(
on
)
console
.
log
(
`[download-center][
${
scope
}
]`
,
...
args
);
}
function
normalizeUuid
(
result
:
unknown
):
string
|
undefined
{
if
(
typeof
result
===
'string'
&&
result
)
return
result
;
if
(
!
result
||
typeof
result
!==
'object'
)
return
undefined
;
...
...
@@ -51,13 +73,20 @@ async function submit(
signal
:
AbortSignal
,
):
Promise
<
string
>
{
const
exportParam
=
JSON
.
stringify
({
method
:
payload
.
method
,
...(
payload
.
params
??
{})
});
const
url
=
payload
.
submitMethod
??
DEFAULT_SUBMIT_METHOD
;
debugLog
(
'submit:req'
,
{
url
,
exportParam
,
exportParamParsed
:
JSON
.
parse
(
exportParam
),
});
const
res
=
await
request
({
method
:
'POST'
,
url
:
payload
.
submitMethod
??
DEFAULT_SUBMIT_METHOD
,
url
,
data
:
{
exportParam
},
signal
,
});
const
uuid
=
normalizeUuid
(
res
);
debugLog
(
'submit:res'
,
{
url
,
res
,
uuid
});
if
(
!
uuid
)
throw
new
Error
(
'后端未返回任务 uuid'
);
return
uuid
;
}
...
...
@@ -68,12 +97,14 @@ async function query(
uuid
:
string
,
signal
:
AbortSignal
,
):
Promise
<
ExportQueryItem
[]
>
{
const
url
=
payload
.
queryMethod
??
DEFAULT_QUERY_METHOD
;
const
res
=
await
request
({
method
:
'POST'
,
url
:
payload
.
queryMethod
??
DEFAULT_QUERY_METHOD
,
url
,
data
:
{
fileUuidList
:
[
uuid
]
},
signal
,
});
debugLog
(
'poll:res'
,
{
url
,
uuid
,
res
});
if
(
Array
.
isArray
(
res
))
return
res
as
ExportQueryItem
[];
const
data
=
(
res
as
{
data
?:
ExportQueryItem
[]
}
|
undefined
)?.
data
;
return
Array
.
isArray
(
data
)
?
data
:
[];
...
...
@@ -92,6 +123,16 @@ export const asyncExportHandler: DownloadHandler = {
const
payload
=
task
.
input
.
payload
as
AsyncExportPayload
;
if
(
!
payload
?.
method
)
throw
new
Error
(
'异步导出缺少 method'
);
debugLog
(
'execute'
,
{
label
:
task
.
label
,
source
:
task
.
input
.
source
,
channel
:
task
.
input
.
channel
??
'host(默认)'
,
method
:
payload
.
method
,
submitMethod
:
payload
.
submitMethod
??
DEFAULT_SUBMIT_METHOD
,
queryMethod
:
payload
.
queryMethod
??
DEFAULT_QUERY_METHOD
,
resumedUuid
:
task
.
context
?.
uuid
??
'(无)'
,
});
const
interval
=
payload
.
pollInterval
??
DEFAULT_POLL_INTERVAL
;
const
deadline
=
Date
.
now
()
+
(
payload
.
timeoutMs
??
DEFAULT_TIMEOUT_MS
);
...
...
packages/download-center/src/handlers/simple.ts
View file @
2b32d86
...
...
@@ -5,7 +5,7 @@ import type {
DownloadResult
,
UrlPayload
,
}
from
'../types'
;
import
{
blobFromBase64
}
from
'../deliver'
;
import
{
assertDownloadableUrl
,
blobFromBase64
,
probeDownloadUrl
}
from
'../deliver'
;
/** 从 URL 路径末段推断文件名(预签名 URL 的 query 不参与)。 */
function
fileNameFromUrl
(
url
:
string
):
string
{
...
...
@@ -28,6 +28,32 @@ export const urlHandler: DownloadHandler = {
const
payload
=
task
.
input
.
payload
as
UrlPayload
;
if
(
!
payload
?.
url
)
throw
new
Error
(
'URL 下载缺少 url'
);
const
fileName
=
task
.
input
.
fileName
??
fileNameFromUrl
(
payload
.
url
);
// 先 fetch 探测:同源 / 带 CORS 的直链能读到 HTTP 状态与响应体,
// 过去 iframe 读不到的「请求资源不存在」(404 或 200+JSON 业务错误)
// 现在会走 error 分支抛错,由引擎落 failed 并触发失败通知。
const
probe
=
await
probeDownloadUrl
(
payload
.
url
,
fileName
,
ctx
.
signal
);
// 探测期间任务可能被取消(signal abort 会让 probe 返回 opaque 而非抛错)。
// 这里主动抛 AbortError,交回引擎按「已取消」落状态,避免取消后仍继续下载。
if
(
ctx
.
isCanceled
())
throw
new
DOMException
(
'已取消'
,
'AbortError'
);
if
(
probe
.
kind
===
'error'
)
throw
new
Error
(
probe
.
message
);
if
(
probe
.
kind
===
'ok'
)
{
// 探测成功即直接用响应体落盘,不再重复发一次 iframe 请求。
if
(
task
.
input
.
autoDownload
!==
false
)
{
ctx
.
deliver
.
saveBlob
(
probe
.
blob
,
probe
.
fileName
);
}
return
{
fileUrl
:
payload
.
url
,
fileName
:
probe
.
fileName
,
bytes
:
probe
.
bytes
,
note
:
'下载完成'
,
};
}
// opaque:跨域无 CORS 的 OSS 预签名地址,无法探测,退回原 iframe 行为。
// 这类地址的加载失败浏览器不让 JS 感知,是既定限制,不能因此误判为失败。
assertDownloadableUrl
(
payload
.
url
);
if
(
task
.
input
.
autoDownload
!==
false
)
{
ctx
.
deliver
.
openUrl
(
payload
.
url
,
payload
.
openInNewTab
??
true
);
}
...
...
packages/download-center/src/store.ts
View file @
2b32d86
...
...
@@ -10,6 +10,23 @@ const MAX_HISTORY = 100;
const
IN_FLIGHT
:
DownloadTaskStatus
[]
=
[
'waiting'
,
'running'
];
const
FINISHED
:
DownloadTaskStatus
[]
=
[
'done'
,
'failed'
,
'canceled'
];
/**
* 幂等键:显式 dedupeKey 优先;url 类没有显式 key 时,用地址本身兜底。
*
* 仅用于「在途防连点」:1.5s 窗口内重复登记同一 key、且上一条还在 waiting/running
* 时复用它,避免一次点击触发两次提交。终态(done/failed/canceled)一律不复用,
* 每次登记都新建一条独立记录——导出是数据快照,同名 key 不代表同一份内容,
* 合并记录会让用户误把旧文件当成最新结果(用户明确要求成功/失败都可累加)。
*/
function
idempotencyKey
(
input
:
RegisterDownloadInput
):
string
|
undefined
{
if
(
input
.
dedupeKey
)
return
input
.
dedupeKey
;
if
(
input
.
kind
===
'url'
)
{
const
url
=
(
input
.
payload
as
{
url
?:
unknown
}
|
null
)?.
url
;
if
(
typeof
url
===
'string'
&&
url
)
return
`url:
${
url
}
`
;
}
return
undefined
;
}
/** 含 Blob / 大 base64 的任务不可序列化,不进持久化。 */
export
function
isTransient
(
input
:
RegisterDownloadInput
):
boolean
{
if
(
input
.
kind
===
'blob'
||
input
.
kind
===
'base64'
)
return
true
;
...
...
@@ -75,13 +92,14 @@ export const useDownloadCenterStore = create<DownloadCenterState>((set, get) =>
enqueue
:
(
input
)
=>
{
const
now
=
Date
.
now
();
const
existing
=
input
.
dedupeKey
?
get
().
tasks
.
find
(
(
t
)
=>
t
.
input
.
dedupeKey
===
input
.
dedupeKey
&&
IN_FLIGHT
.
includes
(
t
.
status
)
&&
now
-
t
.
createdAt
<
DEDUPE_WINDOW_MS
,
)
const
key
=
idempotencyKey
(
input
);
const
existing
=
key
?
get
().
tasks
.
find
((
t
)
=>
{
if
(
idempotencyKey
(
t
.
input
)
!==
key
)
return
false
;
// 仅在途任务、且短窗口内复用(防一次点击触发两次提交);
// 终态一律返回 false → 走下方新建,成功后累加上一条独立记录。
return
IN_FLIGHT
.
includes
(
t
.
status
)
&&
now
-
t
.
createdAt
<
DEDUPE_WINDOW_MS
;
})
:
undefined
;
if
(
existing
)
return
existing
.
id
;
...
...
packages/ui/src/index.ts
View file @
2b32d86
...
...
@@ -23,6 +23,9 @@ export { installGlobalUnhandledRejectionHandler } from './components/App/globalE
export
{
UButton
}
from
'./components/Button'
;
export
type
{
UButtonProps
}
from
'./components/Button'
;
// 表格工具栏「导出」动作的统一图标。DataTable 检测 tone='export' 自动前置,
// 各列表页不再各自 import 图标,保证全站导出按钮外观一致。
export
{
DownloadOutlined
as
UExportIcon
}
from
'@ant-design/icons'
;
export
{
UInput
}
from
'./components/Input'
;
export
type
{
UInputProps
}
from
'./components/Input'
;
...
...
packages/ui/src/styles/ui.css
View file @
2b32d86
...
...
@@ -436,8 +436,8 @@ body {
overflow-y
:
auto
!important
;
}
/* 工具条:左计数、右动作。
原 DataTable 用内联 style 写死 padding/gap,
现在收成一个类,三处列表页共用同一套间距
。 */
/* 工具条:左计数、右动作。
表格数据相关的操作按钮全站统一收口在这里。
padding 从 12px 20px 收到 8px 16px,少占一截垂直空间,表头不再显笨重
。 */
.uj-table-toolbar
{
flex
:
none
;
display
:
flex
;
...
...
@@ -445,7 +445,7 @@ body {
justify-content
:
space-between
;
flex-wrap
:
wrap
;
gap
:
var
(
--uj-space-3
,
12px
);
padding
:
12px
20
px
;
padding
:
8px
16
px
;
border-bottom
:
1px
solid
var
(
--uj-divider
);
}
.uj-table-toolbar__title
{
...
...
@@ -460,6 +460,40 @@ body {
gap
:
var
(
--uj-space-2
,
8px
);
}
/* 表格工具栏动作按钮:统一精致小号,所有页一个外观。
两级类选择器压过 antd cssinjs 注入的 .ant-btn(与 .uj-row-actions 同法)。 */
.uj-table-toolbar
.uj-table-action.ant-btn
{
height
:
26px
;
padding
:
0
10px
;
border-radius
:
var
(
--uj-radius-sm
,
4px
);
font-size
:
var
(
--uj-font-xs
,
12px
);
line-height
:
24px
;
display
:
inline-flex
;
align-items
:
center
;
gap
:
5px
;
}
.uj-table-toolbar
.uj-table-action.ant-btn
.anticon
{
font-size
:
var
(
--uj-font-md
,
14px
);
line-height
:
1
;
}
.uj-table-toolbar
.uj-table-action.ant-btn
:focus-visible
{
outline
:
2px
solid
var
(
--uj-primary
);
outline-offset
:
1px
;
}
/* 导出:全站统一为描边中性按钮 + 下载图标,不用主色抢视觉,也不各自拼文案图标。 */
.uj-table-toolbar
.uj-table-action--export.ant-btn
:not
(
.ant-btn-primary
)
:not
(
.ant-btn-dangerous
)
{
color
:
var
(
--uj-text-2
,
#4a5568
);
border-color
:
var
(
--uj-border-strong
,
#d6dee9
);
background
:
var
(
--uj-surface
,
#fff
);
}
.uj-table-toolbar
.uj-table-action--export.ant-btn
:not
(
.ant-btn-primary
)
:not
(
.ant-btn-dangerous
)
:hover:not
(
:disabled
)
{
color
:
var
(
--uj-primary
);
border-color
:
var
(
--uj-primary
);
background
:
var
(
--uj-primary-soft
,
#eef3ff
);
}
/* 空态铺满表体:FillTable 把测到的可视高度写成 --uj-fill-h,
由占位单元格吃掉这段高度,表头仍然可见(用户得知道自己看的是哪几列)。 */
.uj-table-fill
.ant-table-tbody
>
tr
.ant-table-placeholder
>
td
{
...
...
packages/vite-config/src/aliases.mjs
View file @
2b32d86
...
...
@@ -6,6 +6,60 @@ const HERE = path.dirname(fileURLToPath(import.meta.url));
export const ROOT = path.resolve(HERE, '../../..');
/**
* 工作区源码包统一排除出依赖预打包(optimizeDeps),shell / 子应用配置共用。
*
* 这些包的 package.json main/types 直接指向 src/*.ts(无 dist 构建步骤),本意是
* 「源码直出、改了即生效」。但 Vite 默认把 node_modules 里的依赖(含 pnpm symlink
* 过去的 workspace 包)预打包进 node_modules/.vite/deps,结果在服务启动时固化:
* 改了 src 既不触发 HMR、缓存也不失效,表现就是「代码改了、typecheck 过了、
* 浏览器还是旧行为」,必须手动清缓存+重启。此坑已多次踩到,在此系统性根治。
*
* 排除后这些包走源码 transform,受 watcher 管辖,改 src 即时 HMR。
*/
/**
* 第三方重依赖必须显式列入 optimizeDeps.include,否则 wujie 子应用首次打开会「启动超时」。
*
* 成因:上面的 WORKSPACE_SRC_PACKAGES 被排除出预构建后,Vite 的依赖扫描器不会递归进
* @uj/ui / @uj/biz / @uj/platform-sdk 的源码,发现不了它们 import 的 antd / icons /
* antd/locale/zh_CN。浏览器首次请求到这些模块时 Vite 才临时预构建,随后打
* `optimized dependencies changed. reloading` 强制整页 reload —— wujie iframe 恰好在
* 握手窗口被重载,`<short>:ready` 丢失,主壳 15 秒内等不到上报就报启动失败。
* 启动时预构建完这批依赖,首次访问不再触发 reload。
*
* 子应用共用集:每个子应用都直接依赖(catalog:),且经 workspace 包间接引用。
* wujie 只在 shell 直接依赖(子应用 node_modules 无该链接),归到 SHELL 专有集,
* 否则子应用配了会因解析不到而启动失败。
*/
export const COMMON_PREBUNDLE_DEPS = [
'react',
'react-dom',
'react-dom/client',
'react/jsx-runtime',
'react-router-dom',
'antd',
'antd/locale/zh_CN',
'@ant-design/icons',
'@tanstack/react-query',
'dayjs',
];
export const SHELL_PREBUNDLE_DEPS = ['wujie'];
export const WORKSPACE_SRC_PACKAGES = [
'@uj/download-center',
'@uj/contracts',
'@uj/api-core',
'@uj/platform-core',
'@uj/platform-sdk',
'@uj/biz',
'@uj/design-tokens',
'@uj/ui',
'@uj/vite-config',
'@uj/eslint-config',
'@uj/typescript-config',
];
/**
* 单一真源:老项目 `src/**` 里的 `@/xxx` import 不动一个字,靠 alias 把不同职责
* 映射到不同包。这是 wujie 改造能「零 import 重写」的关键。
*
...
...
packages/vite-config/src/react.js
View file @
2b32d86
import
react
from
'@vitejs/plugin-react'
;
import
{
createAliases
}
from
'./aliases.mjs'
;
import
{
createAliases
,
COMMON_PREBUNDLE_DEPS
,
WORKSPACE_SRC_PACKAGES
,
}
from
'./aliases.mjs'
;
/**
* 子应用 Vite 配置工厂(system / store 共用)。
...
...
@@ -31,6 +35,9 @@ export function createWebAppConfig({
base
,
plugins
:
[
react
()],
resolve
:
{
alias
:
createAliases
({
appDir
,
kind
:
'subapp'
})
},
// workspace 源码包不走预打包,改 src 直接 HMR;第三方重依赖启动时预构建,
// 避免首次访问 wujie 子应用时 Vite 临时预构建触发 reload、打断 ready 握手(见 aliases.mjs)。
optimizeDeps
:
{
exclude
:
WORKSPACE_SRC_PACKAGES
,
include
:
COMMON_PREBUNDLE_DEPS
},
server
:
{
host
:
'0.0.0.0'
,
port
,
...
...
packages/vite-config/src/shell.js
View file @
2b32d86
import
fs
from
'node:fs'
;
import
path
from
'node:path'
;
import
react
from
'@vitejs/plugin-react'
;
import
{
createAliases
}
from
'./aliases.mjs'
;
import
{
createAliases
,
COMMON_PREBUNDLE_DEPS
,
SHELL_PREBUNDLE_DEPS
,
WORKSPACE_SRC_PACKAGES
,
}
from
'./aliases.mjs'
;
const
KEY_MODULES
=
{
'virtual:client-private-key'
:
{
file
:
'client_private.pem'
,
label
:
'客户端私钥'
},
...
...
@@ -123,6 +128,12 @@ export function createShellConfig({ appDir, port, base = process.env.SHELL_BASE
base
,
plugins
:
[
react
(),
virtualKeys
,
reload
,
keyGuard
],
resolve
:
{
alias
:
createAliases
({
appDir
,
kind
:
'shell'
})
},
// workspace 源码包不走预打包,改 src 直接 HMR;第三方重依赖(含 shell 独占的 wujie)
// 启动时预构建,避免首次访问触发 reload 打断子应用握手(见 aliases.mjs)。
optimizeDeps
:
{
exclude
:
WORKSPACE_SRC_PACKAGES
,
include
:
[...
COMMON_PREBUNDLE_DEPS
,
...
SHELL_PREBUNDLE_DEPS
],
},
server
:
{
host
:
'0.0.0.0'
,
port
,
...
...
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment