first commit
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# 前端请求前缀;部署时由 nginx 将 /admin-api 反向代理到对应后端
|
||||
VITE_API_BASE=/admin-api
|
||||
@@ -0,0 +1,4 @@
|
||||
# npm run dev:代理到测试环境后端
|
||||
VITE_API_BASE=/admin-api
|
||||
VITE_PROXY_TARGET=https://dev-vibemake-api.robotquan.com
|
||||
VITE_APP_ENV=development
|
||||
@@ -0,0 +1,4 @@
|
||||
# npm run dev:prod:本地开发代理到线上后端(谨慎操作)
|
||||
VITE_API_BASE=/admin-api
|
||||
VITE_PROXY_TARGET=https://vibemake-api.robotquan.com
|
||||
VITE_APP_ENV=production
|
||||
@@ -0,0 +1,5 @@
|
||||
# 线上构建 -> vibemake-admin.robotquan.com
|
||||
# 线上域名在前端自动选择线上接口;该地址同时用于其他域名的构建默认值。
|
||||
VITE_API_BASE=https://vibemake-api.robotquan.com/admin-api
|
||||
VITE_PROXY_TARGET=https://vibemake-api.robotquan.com
|
||||
VITE_APP_ENV=production
|
||||
@@ -0,0 +1,5 @@
|
||||
# 测试环境构建 -> dev-vibemake-admin.robotquan.com
|
||||
# dev 静态包内置 dev 后端地址,上传 dist 即可,不依赖站点 API 代理。
|
||||
VITE_API_BASE=https://dev-vibemake-api.robotquan.com/admin-api
|
||||
VITE_PROXY_TARGET=https://dev-vibemake-api.robotquan.com
|
||||
VITE_APP_ENV=test
|
||||
@@ -0,0 +1,8 @@
|
||||
node_modules
|
||||
dist
|
||||
releases/
|
||||
*.tsbuildinfo
|
||||
*.local
|
||||
.DS_Store
|
||||
playwright-report
|
||||
test-results
|
||||
@@ -0,0 +1,67 @@
|
||||
# VibeMake 管理后台
|
||||
|
||||
React 18 + TypeScript + Vite 6 + Ant Design 5 + React Router 6。对接 `community-adminapi`(`/admin-api`)。
|
||||
|
||||
## 环境
|
||||
|
||||
| 环境 | 前端 | 后端 |
|
||||
| --- | --- | --- |
|
||||
| 本地开发 | http://localhost:5188 | 代理到测试环境后端 |
|
||||
| 测试 | https://dev-vibemake-admin.robotquan.com | https://dev-vibemake-api.robotquan.com |
|
||||
| 线上 | https://vibemake-admin.robotquan.com | https://vibemake-api.robotquan.com |
|
||||
|
||||
前端在 `src/config/environment.ts` 按访问域名自动选择接口地址,已知部署域名优先于构建默认值:
|
||||
|
||||
- 本地开发:请求同源 `/admin-api`,由 Vite dev server 代理(`vite.config.ts`,目标取 `.env.*` 中的 `VITE_PROXY_TARGET`)。
|
||||
- dev 网站:`dev-vibemake-admin.robotquan.com` 请求 `https://dev-vibemake-api.robotquan.com/admin-api`。
|
||||
- 线上网站:`vibemake-admin.robotquan.com` 请求 `https://vibemake-api.robotquan.com/admin-api`。
|
||||
- 其他部署域名:使用当前构建的 `VITE_API_BASE` 默认值。
|
||||
|
||||
界面环境标记也按网站域名选择,避免同一份静态文件部署到不同域名后显示错误的环境。localhost 本地开发和预览继续请求 `/admin-api`,使用 Vite 的环境代理。
|
||||
|
||||
注意:测试后端 http 会 301 到 https,代理目标必须写 https。
|
||||
|
||||
## 命令
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run dev # 本地开发,代理测试环境后端
|
||||
npm run dev:prod # 本地开发,代理线上后端(谨慎)
|
||||
npm run build:dev # 构建 dev 服务器静态包,内置 dev 后端地址 -> dist/
|
||||
npm run build:test # 构建测试环境包 -> dist/
|
||||
npm run build:prod # 构建线上包 -> dist/
|
||||
npm run preview # 本地预览构建产物
|
||||
npm run preview:dev # 按 dev 配置预览
|
||||
npm run preview:prod # 按线上配置预览,代理目标为线上后端
|
||||
```
|
||||
|
||||
## 部署
|
||||
|
||||
dev 更新:执行 `npm run build:dev`(与 `build:test` 相同),将 `dist/` 内的文件覆盖上传到现有 dev 网站根目录即可。构建产物已内置 dev 后端地址,后端已放行 dev 前端域名的跨域访问,无需新增接口代理。本地开发请使用 `npm run dev`。
|
||||
|
||||
线上更新:执行 `npm run build:prod`,将 `dist/` 内的文件覆盖上传到线上网站根目录。前端会根据线上域名访问线上后端,不需要在前端站点增加 API 反向代理。线上后端需要允许 `https://vibemake-admin.robotquan.com` 跨域访问(包括 Authorization、Content-Type 及各业务 HTTP 方法);目前实测该来源的预检被后端返回 403 `Invalid CORS request`,该后端限制不由前端打包控制。
|
||||
|
||||
DevTools 中 `preflight` 是浏览器发送的 OPTIONS 跨域预检,`fetch` 才是业务请求;它们不是业务执行两次。已知部署域名均直接访问对应后端,正常保留浏览器预检。`deploy/` 中的 Nginx API 代理文件仅作为同源部署方式的备用示例,当前域名自动选择方案不需要启用它们。
|
||||
|
||||
## 功能
|
||||
|
||||
- 登录 / 退出 / 修改密码(401 自动回登录页并保留返回路径)
|
||||
- 用户管理:列表筛选、详情、名下项目、编辑昵称、启用/禁用(不可禁用自己与官方账号)
|
||||
- 项目管理:列表筛选、新建(封面 OSS 直传、归属官方或普通用户)、编辑、删除
|
||||
- 发布 / 更新发布 / 撤回 / 下架 / 解除下架(发布前确认当前 main SHA,409 冲突需刷新重新确认)
|
||||
- 文件:目录浏览、预览(文本/图片)、在线编辑提交、新建文件/目录、删除文件、多文件/文件夹上传(含限额与路径预检)、鉴权下载
|
||||
- 提交历史,并可只读浏览任一历史版本
|
||||
- URDF 目录上传绑定(签名 → 并发 OSS 直传 → 确认)与移除
|
||||
- GitHub 迁移:预检 → 补充信息(可选上传封面、URDF)→ 创建任务并绑定资源 → 3 秒串行轮询阶段 → 检查后手动发布;重复来源跳转已有项目
|
||||
- 迁移重试:`FAILED`、`REVIEW` 始终提供手动重试入口,不按 `canRetry` 隐藏;列表点击重试即进入任务确认框,展示 `retryMessage`,由重试接口判断是否受理;支持 `CLEANING` 清理阶段,409 后刷新状态,网络异常时先查询确认结果
|
||||
|
||||
## 迁移功能回归
|
||||
|
||||
```bash
|
||||
npx playwright install chromium # 首次运行时安装测试浏览器
|
||||
npm run test:imports
|
||||
# 或使用本机已安装的 Chrome
|
||||
PLAYWRIGHT_CHANNEL=chrome npm run test:imports
|
||||
```
|
||||
|
||||
测试会启动独立的本地 Vite 服务并拦截全部管理 API,不向实际后端发起迁移、清理或发布操作。覆盖重试资格、确认说明、202 轮询恢复、409、网络异常、安全清理提示、页面离开停止轮询,以及重复来源和创建结果不明时的提交保护。
|
||||
@@ -0,0 +1,14 @@
|
||||
# 添加到 dev 前端站点现有的 HTTPS server { ... } 内,与 location / 同级。
|
||||
# proxy_pass 地址末尾不加 /,保留原始 /admin-api/... 路径。
|
||||
location ^~ /admin-api/ {
|
||||
proxy_pass https://dev-vibemake-api.robotquan.com;
|
||||
proxy_ssl_server_name on;
|
||||
proxy_set_header Host dev-vibemake-api.robotquan.com;
|
||||
proxy_set_header Origin "";
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 60m;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
# 添加到线上前端站点现有的 HTTPS server { ... } 内,与 location / 同级。
|
||||
# 保留 /admin-api/... 路径;此配置仅代理线上后端。
|
||||
location ^~ /admin-api/ {
|
||||
proxy_pass https://vibemake-api.robotquan.com;
|
||||
proxy_ssl_server_name on;
|
||||
proxy_set_header Host vibemake-api.robotquan.com;
|
||||
proxy_set_header Origin "";
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 60m;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name vibemake-admin.robotquan.com;
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name vibemake-admin.robotquan.com;
|
||||
|
||||
# ssl_certificate /etc/nginx/ssl/vibemake-admin.robotquan.com.pem;
|
||||
# ssl_certificate_key /etc/nginx/ssl/vibemake-admin.robotquan.com.key;
|
||||
|
||||
root /usr/share/nginx/vibemake-admin;
|
||||
index index.html;
|
||||
client_max_body_size 60m;
|
||||
|
||||
# 后台接口反向代理
|
||||
location ^~ /admin-api/ {
|
||||
proxy_pass https://vibemake-api.robotquan.com;
|
||||
proxy_ssl_server_name on;
|
||||
proxy_set_header Host vibemake-api.robotquan.com;
|
||||
# 不转发浏览器 Origin,避免后端 CORS 白名单拒绝(403);同源代理无需 CORS
|
||||
proxy_set_header Origin "";
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
}
|
||||
|
||||
location /assets/ {
|
||||
expires 30d;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
# SPA history 路由回退
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
add_header Cache-Control "no-cache";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name dev-vibemake-admin.robotquan.com;
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name dev-vibemake-admin.robotquan.com;
|
||||
|
||||
# ssl_certificate /etc/nginx/ssl/dev-vibemake-admin.robotquan.com.pem;
|
||||
# ssl_certificate_key /etc/nginx/ssl/dev-vibemake-admin.robotquan.com.key;
|
||||
|
||||
root /usr/share/nginx/vibemake-admin;
|
||||
index index.html;
|
||||
client_max_body_size 60m;
|
||||
|
||||
# 后台接口反向代理
|
||||
location ^~ /admin-api/ {
|
||||
proxy_pass https://dev-vibemake-api.robotquan.com;
|
||||
proxy_ssl_server_name on;
|
||||
proxy_set_header Host dev-vibemake-api.robotquan.com;
|
||||
# 不转发浏览器 Origin,避免后端 CORS 白名单拒绝(403);同源代理无需 CORS
|
||||
proxy_set_header Origin "";
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
}
|
||||
|
||||
location /assets/ {
|
||||
expires 30d;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
# SPA history 路由回退
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
add_header Cache-Control "no-cache";
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link rel="icon" href="/favicon.svg" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet" />
|
||||
<title>VibeMake 管理后台</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+2969
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"name": "vibemake-admin",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"dev:prod": "vite --mode prodproxy",
|
||||
"build": "tsc -b && vite build",
|
||||
"build:dev": "npm run build:test",
|
||||
"build:test": "tsc -b && vite build --mode test",
|
||||
"build:prod": "tsc -b && vite build --mode production",
|
||||
"test:imports": "playwright test",
|
||||
"preview": "vite preview",
|
||||
"preview:dev": "vite preview --mode test",
|
||||
"preview:prod": "vite preview --mode production"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ant-design/icons": "^5.5.1",
|
||||
"antd": "^5.22.2",
|
||||
"dayjs": "^1.11.13",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^6.28.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.64.1",
|
||||
"@types/node": "^22.10.1",
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"typescript": "^5.6.3",
|
||||
"vite": "^6.0.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { defineConfig } from '@playwright/test';
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './tests',
|
||||
fullyParallel: true,
|
||||
workers: 2,
|
||||
timeout: 25_000,
|
||||
use: {
|
||||
baseURL: 'http://127.0.0.1:5190',
|
||||
channel: process.env.PLAYWRIGHT_CHANNEL,
|
||||
viewport: { width: 1440, height: 1100 },
|
||||
trace: 'retain-on-failure',
|
||||
},
|
||||
webServer: {
|
||||
command: 'npm run dev -- --host 127.0.0.1 --port 5190',
|
||||
url: 'http://127.0.0.1:5190',
|
||||
reuseExistingServer: false,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#6366f1"/><stop offset=".55" stop-color="#8b5cf6"/><stop offset="1" stop-color="#06b6d4"/></linearGradient></defs><rect width="64" height="64" rx="16" fill="url(#g)"/><path d="M16 20l16 26 16-26" fill="none" stroke="#fff" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/><circle cx="32" cy="18" r="4" fill="#fff"/></svg>
|
||||
|
After Width: | Height: | Size: 483 B |
+54
@@ -0,0 +1,54 @@
|
||||
import { Navigate, Route, Routes, useLocation } from 'react-router-dom';
|
||||
import { Spin } from 'antd';
|
||||
import { useAuth } from './auth';
|
||||
import AdminLayout from './components/AdminLayout';
|
||||
import LoginPage from './pages/Login';
|
||||
import UserListPage from './pages/UserList';
|
||||
import UserDetailPage from './pages/UserDetail';
|
||||
import ProjectListPage from './pages/ProjectList';
|
||||
import ProjectCreatePage from './pages/ProjectCreate';
|
||||
import ProjectDetailPage from './pages/ProjectDetail';
|
||||
import ImportListPage from './pages/ImportList';
|
||||
import ImportCreatePage from './pages/ImportCreate';
|
||||
import ImportDetailPage from './pages/ImportDetail';
|
||||
import AccountPage from './pages/Account';
|
||||
|
||||
function RequireAuth({ children }: { children: JSX.Element }) {
|
||||
const { admin, loading } = useAuth();
|
||||
const location = useLocation();
|
||||
if (loading) {
|
||||
return <Spin fullscreen tip="加载中..." />;
|
||||
}
|
||||
if (!admin) {
|
||||
const redirect = encodeURIComponent(location.pathname + location.search);
|
||||
return <Navigate to={`/login?redirect=${redirect}`} replace />;
|
||||
}
|
||||
return children;
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route
|
||||
element={
|
||||
<RequireAuth>
|
||||
<AdminLayout />
|
||||
</RequireAuth>
|
||||
}
|
||||
>
|
||||
<Route index element={<Navigate to="/projects" replace />} />
|
||||
<Route path="users" element={<UserListPage />} />
|
||||
<Route path="users/:userCode" element={<UserDetailPage />} />
|
||||
<Route path="projects" element={<ProjectListPage />} />
|
||||
<Route path="projects/new" element={<ProjectCreatePage />} />
|
||||
<Route path="projects/:projectCode" element={<ProjectDetailPage />} />
|
||||
<Route path="imports" element={<ImportListPage />} />
|
||||
<Route path="imports/new" element={<ImportCreatePage />} />
|
||||
<Route path="imports/:taskCode" element={<ImportDetailPage />} />
|
||||
<Route path="account" element={<AccountPage />} />
|
||||
<Route path="*" element={<Navigate to="/projects" replace />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
import { downloadAdmin, queryString, requestAdmin, setToken, uploadOssFile } from './request';
|
||||
import type {
|
||||
AdminView,
|
||||
CommitInput,
|
||||
CommitView,
|
||||
CoverUploadSignature,
|
||||
FileView,
|
||||
HistoryEntry,
|
||||
ImportInput,
|
||||
ImportPreview,
|
||||
ImportUrdf,
|
||||
ImportStatus,
|
||||
LoginView,
|
||||
ManagedProjectView,
|
||||
PageResponse,
|
||||
ProjectInput,
|
||||
ProjectView,
|
||||
PublishStatus,
|
||||
RepoStatus,
|
||||
SelectedFile,
|
||||
TaskView,
|
||||
TreeView,
|
||||
TypeView,
|
||||
UrdfFile,
|
||||
UrdfUploadSignature,
|
||||
UserRole,
|
||||
UserStatus,
|
||||
UserView,
|
||||
} from './types';
|
||||
|
||||
const enc = encodeURIComponent;
|
||||
|
||||
// ---------- 认证 ----------
|
||||
export async function login(email: string, password: string): Promise<LoginView> {
|
||||
const result = await requestAdmin<LoginView>('/auth/login', {
|
||||
method: 'POST',
|
||||
anonymous: true,
|
||||
body: { email, password },
|
||||
});
|
||||
setToken(result.token);
|
||||
return result;
|
||||
}
|
||||
|
||||
export const getMe = () => requestAdmin<AdminView>('/auth/me');
|
||||
export const logout = () => requestAdmin<null>('/auth/logout', { method: 'POST' });
|
||||
export const changePassword = (oldPassword: string, newPassword: string) =>
|
||||
requestAdmin<null>('/auth/password', { method: 'PUT', body: { oldPassword, newPassword } });
|
||||
|
||||
// ---------- 用户 ----------
|
||||
export interface UserQuery {
|
||||
page?: number;
|
||||
size?: number;
|
||||
userCode?: string;
|
||||
nickname?: string;
|
||||
email?: string;
|
||||
role?: UserRole;
|
||||
status?: UserStatus;
|
||||
}
|
||||
|
||||
export const listUsers = (q: UserQuery = {}) =>
|
||||
requestAdmin<PageResponse<UserView>>(`/users${queryString({ ...q })}`);
|
||||
export const getUser = (userCode: string) => requestAdmin<UserView>(`/users/${enc(userCode)}`);
|
||||
export const updateUser = (userCode: string, nickname: string) =>
|
||||
requestAdmin<UserView>(`/users/${enc(userCode)}`, { method: 'PATCH', body: { nickname } });
|
||||
export const setUserStatus = (userCode: string, status: UserStatus) =>
|
||||
requestAdmin<null>(`/users/${enc(userCode)}/status`, { method: 'PUT', body: { status } });
|
||||
export const listUserProjects = (userCode: string, page = 1, size = 20) =>
|
||||
requestAdmin<PageResponse<ManagedProjectView>>(
|
||||
`/users/${enc(userCode)}/projects${queryString({ page, size })}`,
|
||||
);
|
||||
|
||||
// ---------- 项目 ----------
|
||||
export interface ProjectQuery {
|
||||
page?: number;
|
||||
size?: number;
|
||||
ownerUserCode?: string;
|
||||
type?: string;
|
||||
keyword?: string;
|
||||
publishStatus?: PublishStatus;
|
||||
repoStatus?: RepoStatus;
|
||||
moderationStatus?: 'NORMAL' | 'BLOCKED';
|
||||
}
|
||||
|
||||
// 项目类型基本不变,整个会话只请求一次;失败时清掉缓存以便下次重试
|
||||
let typesCache: Promise<TypeView[]> | null = null;
|
||||
export const listProjectTypes = () => {
|
||||
typesCache ??= requestAdmin<TypeView[]>('/projects/types').catch((e) => {
|
||||
typesCache = null;
|
||||
throw e;
|
||||
});
|
||||
return typesCache;
|
||||
};
|
||||
export const listProjects = (q: ProjectQuery = {}) =>
|
||||
requestAdmin<PageResponse<ManagedProjectView>>(`/projects${queryString({ ...q })}`);
|
||||
export const getProject = (code: string) =>
|
||||
requestAdmin<ManagedProjectView>(`/projects/${enc(code)}`);
|
||||
export const createProject = (project: ProjectInput, ownerUserCode?: string) =>
|
||||
requestAdmin<ProjectView>('/projects', {
|
||||
method: 'POST',
|
||||
body: ownerUserCode ? { project, ownerUserCode } : { project },
|
||||
});
|
||||
export const updateProject = (code: string, project: ProjectInput) =>
|
||||
requestAdmin<ProjectView>(`/projects/${enc(code)}`, { method: 'PATCH', body: project });
|
||||
export const deleteProject = (code: string) =>
|
||||
requestAdmin<null>(`/projects/${enc(code)}`, { method: 'DELETE' });
|
||||
|
||||
export const publishProject = (code: string, commitSha: string) =>
|
||||
requestAdmin<ProjectView>(`/projects/${enc(code)}/publication`, {
|
||||
method: 'PUT',
|
||||
body: { commitSha },
|
||||
});
|
||||
export const unpublishProject = (code: string) =>
|
||||
requestAdmin<null>(`/projects/${enc(code)}/publication`, { method: 'DELETE' });
|
||||
export const blockProject = (code: string, reason: string) =>
|
||||
requestAdmin<null>(`/projects/${enc(code)}/moderation`, { method: 'PUT', body: { reason } });
|
||||
export const unblockProject = (code: string) =>
|
||||
requestAdmin<null>(`/projects/${enc(code)}/moderation`, { method: 'DELETE' });
|
||||
|
||||
// ---------- 目录 / 文件 / 提交 ----------
|
||||
export const getTree = (code: string, path = '', commitSha?: string) =>
|
||||
requestAdmin<TreeView>(`/projects/${enc(code)}/tree${queryString({ path, commitSha })}`);
|
||||
export const getFile = (code: string, path: string, commitSha?: string) =>
|
||||
requestAdmin<FileView>(`/projects/${enc(code)}/files${queryString({ path, commitSha })}`);
|
||||
export const downloadFile = (code: string, path: string, commitSha?: string) =>
|
||||
downloadAdmin(
|
||||
`/projects/${enc(code)}/files${queryString({ path, commitSha, download: 'true' })}`,
|
||||
path.split('/').pop() || 'download',
|
||||
);
|
||||
export const listCommits = (code: string, page = 1, size = 20) =>
|
||||
requestAdmin<PageResponse<HistoryEntry>>(
|
||||
`/projects/${enc(code)}/commits${queryString({ page, size })}`,
|
||||
);
|
||||
export const createCommit = (code: string, input: CommitInput) =>
|
||||
requestAdmin<CommitView>(`/projects/${enc(code)}/commits`, { method: 'POST', body: input });
|
||||
|
||||
export function uploadProjectFiles(
|
||||
code: string,
|
||||
expectedCommitSha: string,
|
||||
message: string,
|
||||
selected: SelectedFile[],
|
||||
directory = '',
|
||||
): Promise<CommitView> {
|
||||
const form = new FormData();
|
||||
form.append('expectedCommitSha', expectedCommitSha);
|
||||
form.append('message', message);
|
||||
form.append('directory', directory);
|
||||
for (const item of selected) {
|
||||
form.append('files', item.file, item.file.name);
|
||||
form.append('paths', item.relativePath);
|
||||
}
|
||||
return requestAdmin<CommitView>(`/projects/${enc(code)}/uploads/commit`, {
|
||||
method: 'POST',
|
||||
body: form,
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- 封面 ----------
|
||||
export async function uploadCover(file: File): Promise<string> {
|
||||
const signature = await requestAdmin<CoverUploadSignature>('/uploads/project-covers/signature', {
|
||||
method: 'POST',
|
||||
body: { contentType: file.type, fileSize: file.size },
|
||||
});
|
||||
await uploadOssFile(signature.uploadUrl, signature.formFields, file);
|
||||
return signature.coverUrl;
|
||||
}
|
||||
|
||||
// ---------- URDF ----------
|
||||
type Progress = (done: number, total: number) => void;
|
||||
|
||||
const toUrdfFiles = (selected: SelectedFile[]): UrdfFile[] =>
|
||||
selected.map((item) => ({ relativePath: item.relativePath, sizeBytes: item.file.size }));
|
||||
|
||||
/** 按签名把每个文件直传 OSS(并发 4),任一失败即抛出 */
|
||||
async function uploadUrdfBatch(signature: UrdfUploadSignature, selected: SelectedFile[], onProgress?: Progress) {
|
||||
const byPath = new Map(selected.map((item) => [item.relativePath, item.file]));
|
||||
const queue = [...signature.files];
|
||||
const total = queue.length;
|
||||
let done = 0;
|
||||
const worker = async () => {
|
||||
for (let item = queue.shift(); item; item = queue.shift()) {
|
||||
const file = byPath.get(item.relativePath);
|
||||
if (!file) throw new Error(`缺少本地文件:${item.relativePath}`);
|
||||
await uploadOssFile(signature.uploadUrl, item.formFields, file);
|
||||
onProgress?.(++done, total);
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.min(4, total) }, worker));
|
||||
}
|
||||
|
||||
/** 项目 URDF:签名 → OSS 直传 → PUT 确认绑定 */
|
||||
export async function uploadUrdf(code: string, selected: SelectedFile[], onProgress?: Progress): Promise<ProjectView> {
|
||||
const files = toUrdfFiles(selected);
|
||||
const signature = await requestAdmin<UrdfUploadSignature>(`/projects/${enc(code)}/urdf/signature`, {
|
||||
method: 'POST',
|
||||
body: { files },
|
||||
});
|
||||
await uploadUrdfBatch(signature, selected, onProgress);
|
||||
return requestAdmin<ProjectView>(`/projects/${enc(code)}/urdf`, {
|
||||
method: 'PUT',
|
||||
body: { batchCode: signature.batchCode, files },
|
||||
});
|
||||
}
|
||||
|
||||
/** 迁移前 URDF:按仓库来源签名 → OSS 直传;返回值作为创建迁移任务的 urdf 字段 */
|
||||
export async function uploadImportUrdf(
|
||||
repositoryUrl: string,
|
||||
selected: SelectedFile[],
|
||||
onProgress?: Progress,
|
||||
): Promise<ImportUrdf> {
|
||||
const files = toUrdfFiles(selected);
|
||||
const signature = await requestAdmin<UrdfUploadSignature>('/project-imports/urdf/signature', {
|
||||
method: 'POST',
|
||||
body: { repositoryUrl, files },
|
||||
});
|
||||
await uploadUrdfBatch(signature, selected, onProgress);
|
||||
return { batchCode: signature.batchCode, files };
|
||||
}
|
||||
|
||||
export const removeUrdf = (code: string) =>
|
||||
requestAdmin<null>(`/projects/${enc(code)}/urdf`, { method: 'DELETE' });
|
||||
|
||||
// ---------- GitHub 迁移 ----------
|
||||
export const previewImport = (repositoryUrl: string) =>
|
||||
requestAdmin<ImportPreview>('/project-imports/preview', {
|
||||
method: 'POST',
|
||||
body: { repositoryUrl },
|
||||
});
|
||||
export const createImport = (input: ImportInput) =>
|
||||
requestAdmin<TaskView>('/project-imports', { method: 'POST', body: input });
|
||||
export const listImports = (q: {
|
||||
page?: number;
|
||||
size?: number;
|
||||
status?: ImportStatus;
|
||||
projectCode?: string;
|
||||
}) => requestAdmin<PageResponse<TaskView>>(`/project-imports${queryString({ ...q })}`);
|
||||
export const getImport = (taskCode: string, signal?: AbortSignal) =>
|
||||
requestAdmin<TaskView>(`/project-imports/${enc(taskCode)}`, { signal });
|
||||
export const retryImport = (taskCode: string) =>
|
||||
requestAdmin<TaskView>(`/project-imports/${enc(taskCode)}/retry`, { method: 'POST' });
|
||||
@@ -0,0 +1,143 @@
|
||||
import type { ApiResponse } from './types';
|
||||
import { environment } from '@/config/environment';
|
||||
|
||||
export const ADMIN_API_BASE: string = environment.apiBase;
|
||||
const TOKEN_KEY = 'vibemake_admin_token';
|
||||
|
||||
export function getToken(): string | null {
|
||||
return localStorage.getItem(TOKEN_KEY);
|
||||
}
|
||||
|
||||
export function setToken(token: string | null) {
|
||||
if (token) localStorage.setItem(TOKEN_KEY, token);
|
||||
else localStorage.removeItem(TOKEN_KEY);
|
||||
}
|
||||
|
||||
export class AdminApiError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
public code: string,
|
||||
message: string,
|
||||
public requestId: string | null,
|
||||
public details: unknown,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
let unauthorizedHandler: (() => void) | null = null;
|
||||
export function onUnauthorized(handler: () => void) {
|
||||
unauthorizedHandler = handler;
|
||||
}
|
||||
|
||||
export interface AdminRequestOptions {
|
||||
method?: string;
|
||||
body?: unknown;
|
||||
signal?: AbortSignal;
|
||||
anonymous?: boolean;
|
||||
}
|
||||
|
||||
function buildHeaders(anonymous?: boolean): Headers {
|
||||
const headers = new Headers({ Accept: 'application/json' });
|
||||
const token = getToken();
|
||||
if (!anonymous && token) headers.set('Authorization', `Bearer ${token}`);
|
||||
return headers;
|
||||
}
|
||||
|
||||
function handle401(path: string, status: number) {
|
||||
if (status === 401 && !path.startsWith('/auth/login')) {
|
||||
setToken(null);
|
||||
unauthorizedHandler?.();
|
||||
}
|
||||
}
|
||||
|
||||
export async function requestAdmin<T>(path: string, options: AdminRequestOptions = {}): Promise<T> {
|
||||
const headers = buildHeaders(options.anonymous);
|
||||
let body: BodyInit | undefined;
|
||||
if (options.body instanceof FormData) {
|
||||
body = options.body; // 不手动设置 multipart Content-Type
|
||||
} else if (options.body !== undefined) {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
body = JSON.stringify(options.body);
|
||||
}
|
||||
const response = await fetch(`${ADMIN_API_BASE}${path}`, {
|
||||
method: options.method ?? 'GET',
|
||||
headers,
|
||||
body,
|
||||
signal: options.signal,
|
||||
});
|
||||
const result = (await response.json().catch(() => null)) as ApiResponse<T> | null;
|
||||
if (!response.ok || result?.code !== 'OK') {
|
||||
handle401(path, response.status);
|
||||
throw new AdminApiError(
|
||||
response.status,
|
||||
result?.code ?? 'INVALID_RESPONSE',
|
||||
result?.message ?? `服务响应异常(HTTP ${response.status}),请稍后查看状态`,
|
||||
result?.requestId ?? response.headers.get('X-Request-Id'),
|
||||
result?.data,
|
||||
);
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** 带鉴权的二进制下载,不经过 JSON 解包 */
|
||||
export async function downloadAdmin(path: string, fallbackName: string): Promise<void> {
|
||||
const response = await fetch(`${ADMIN_API_BASE}${path}`, { headers: buildHeaders() });
|
||||
if (!response.ok) {
|
||||
const result = (await response.json().catch(() => null)) as ApiResponse<unknown> | null;
|
||||
handle401(path, response.status);
|
||||
throw new AdminApiError(
|
||||
response.status,
|
||||
result?.code ?? 'DOWNLOAD_FAILED',
|
||||
result?.message ?? `下载失败(HTTP ${response.status})`,
|
||||
result?.requestId ?? response.headers.get('X-Request-Id'),
|
||||
result?.data,
|
||||
);
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const name = parseFileName(response.headers.get('Content-Disposition')) || fallbackName;
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = name;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
|
||||
function parseFileName(disposition: string | null): string | null {
|
||||
if (!disposition) return null;
|
||||
const star = /filename\*\s*=\s*(?:UTF-8'')?([^;]+)/i.exec(disposition);
|
||||
if (star) {
|
||||
try {
|
||||
return decodeURIComponent(star[1].trim().replace(/^"|"$/g, ''));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
const plain = /filename\s*=\s*"?([^";]+)"?/i.exec(disposition);
|
||||
return plain ? plain[1] : null;
|
||||
}
|
||||
|
||||
/** OSS 直传:不带后台 Authorization,不手写 Content-Type */
|
||||
export async function uploadOssFile(
|
||||
uploadUrl: string,
|
||||
formFields: Record<string, string>,
|
||||
file: File,
|
||||
): Promise<void> {
|
||||
const form = new FormData();
|
||||
for (const [key, value] of Object.entries(formFields)) form.append(key, value);
|
||||
form.append('file', file, file.name);
|
||||
const response = await fetch(uploadUrl, { method: 'POST', body: form });
|
||||
if (!response.ok) throw new Error(`OSS 上传失败(${response.status})`);
|
||||
}
|
||||
|
||||
export function queryString(values: Record<string, string | number | null | undefined>): string {
|
||||
const query = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
if (value !== undefined && value !== null && value !== '') query.set(key, String(value));
|
||||
}
|
||||
const s = query.toString();
|
||||
return s ? `?${s}` : '';
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
export type UtcDateTime = string;
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
code: string;
|
||||
message: string;
|
||||
data: T;
|
||||
requestId: string | null;
|
||||
}
|
||||
|
||||
export interface PageResponse<T> {
|
||||
items: T[];
|
||||
page: number;
|
||||
size: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface AdminView {
|
||||
userCode: string;
|
||||
email: string;
|
||||
nickname: string;
|
||||
role: 'ADMIN';
|
||||
}
|
||||
|
||||
export interface LoginView {
|
||||
token: string;
|
||||
tokenType: 'Bearer';
|
||||
expiresIn: number;
|
||||
admin: AdminView;
|
||||
}
|
||||
|
||||
export type UserRole = 'USER' | 'ADMIN' | 'OFFICIAL';
|
||||
export type UserStatus = 'ACTIVE' | 'DISABLED';
|
||||
|
||||
export interface UserView {
|
||||
userCode: string;
|
||||
nickname: string;
|
||||
email: string;
|
||||
status: UserStatus;
|
||||
role: UserRole;
|
||||
projectCount: number;
|
||||
createdAt: UtcDateTime;
|
||||
}
|
||||
|
||||
export type RepoStatus = 'CREATING' | 'READY' | 'FAILED';
|
||||
export type PublishStatus = 'UNPUBLISHED' | 'PUBLISHED' | 'BLOCKED';
|
||||
|
||||
export interface ProjectInput {
|
||||
name: string;
|
||||
description?: string | null;
|
||||
projectType: string;
|
||||
coverUrl?: string | null;
|
||||
}
|
||||
|
||||
export interface ProjectView {
|
||||
projectCode: string;
|
||||
name: string;
|
||||
description: string;
|
||||
coverUrl: string | null;
|
||||
urdfMainUrl: string | null;
|
||||
urdfBaseUrl: string | null;
|
||||
projectType: string;
|
||||
owner: { userCode: string | null; nickname: string };
|
||||
repoStatus: RepoStatus;
|
||||
publishStatus: PublishStatus;
|
||||
publishedCommitSha: string | null;
|
||||
publishedAt: UtcDateTime | null;
|
||||
sourceProjectCode: string | null;
|
||||
sourceCommitSha: string | null;
|
||||
likeCount: number;
|
||||
commentCount: number;
|
||||
liked: boolean;
|
||||
sourceRepositoryUrl: string | null;
|
||||
sourceLicense: string | null;
|
||||
createdAt: UtcDateTime;
|
||||
updatedAt: UtcDateTime;
|
||||
}
|
||||
|
||||
export interface ManagedProjectView {
|
||||
project: ProjectView;
|
||||
moderationStatus: 'NORMAL' | 'BLOCKED';
|
||||
moderationReason: string | null;
|
||||
deleted: boolean;
|
||||
}
|
||||
|
||||
export interface TypeView {
|
||||
code: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface TreeEntry {
|
||||
path: string;
|
||||
name: string;
|
||||
type: string;
|
||||
size: number;
|
||||
blobSha: string | null;
|
||||
}
|
||||
|
||||
export interface TreeView {
|
||||
commitSha: string;
|
||||
path: string;
|
||||
entries: TreeEntry[];
|
||||
}
|
||||
|
||||
export interface FileView {
|
||||
commitSha: string;
|
||||
path: string;
|
||||
blobSha: string;
|
||||
size: number;
|
||||
encoding: 'utf-8' | 'base64';
|
||||
content: string;
|
||||
editable: boolean;
|
||||
}
|
||||
|
||||
export interface CommitView {
|
||||
commitSha: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface HistoryEntry {
|
||||
commitSha: string;
|
||||
message: string;
|
||||
authorName: string;
|
||||
authorDate: string;
|
||||
}
|
||||
|
||||
export type ChangeAction = 'CREATE_FILE' | 'UPDATE_FILE' | 'DELETE_FILE' | 'CREATE_DIRECTORY';
|
||||
|
||||
export interface FileChange {
|
||||
action: ChangeAction;
|
||||
path: string;
|
||||
content?: string | null;
|
||||
}
|
||||
|
||||
export interface CommitInput {
|
||||
expectedCommitSha: string;
|
||||
message: string;
|
||||
changes: FileChange[];
|
||||
}
|
||||
|
||||
export interface SelectedFile {
|
||||
file: File;
|
||||
relativePath: string;
|
||||
}
|
||||
|
||||
export interface CoverUploadSignature {
|
||||
uploadUrl: string;
|
||||
objectKey: string;
|
||||
coverUrl: string;
|
||||
expiresAt: UtcDateTime;
|
||||
formFields: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface UrdfFile {
|
||||
relativePath: string;
|
||||
sizeBytes: number;
|
||||
}
|
||||
|
||||
export interface UrdfFileSignature {
|
||||
relativePath: string;
|
||||
objectKey: string;
|
||||
formFields: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface UrdfUploadSignature {
|
||||
batchCode: string;
|
||||
mainRelativePath: string;
|
||||
uploadUrl: string;
|
||||
expiresAt: UtcDateTime;
|
||||
files: UrdfFileSignature[];
|
||||
}
|
||||
|
||||
export interface ImportPreview {
|
||||
repositoryUrl: string;
|
||||
defaultBranch: string;
|
||||
name: string;
|
||||
description: string;
|
||||
license: string | null;
|
||||
existingProjectCode: string | null;
|
||||
}
|
||||
|
||||
export interface ImportUrdf {
|
||||
batchCode: string;
|
||||
files: UrdfFile[];
|
||||
}
|
||||
|
||||
export interface ImportInput {
|
||||
repositoryUrl: string;
|
||||
ownerUserCode?: string;
|
||||
project: ProjectInput;
|
||||
urdf?: ImportUrdf | null;
|
||||
}
|
||||
|
||||
export type ImportStatus = 'QUEUED' | 'RUNNING' | 'SUCCEEDED' | 'FAILED' | 'REVIEW';
|
||||
export type ImportPhase =
|
||||
| 'QUEUED'
|
||||
| 'CLEANING'
|
||||
| 'PRECHECK'
|
||||
| 'MIGRATING'
|
||||
| 'MIGRATED'
|
||||
| 'NORMALIZING'
|
||||
| 'BRANCH_READY'
|
||||
| 'LINKED';
|
||||
|
||||
export interface TaskView {
|
||||
taskCode: string;
|
||||
projectCode: string;
|
||||
status: ImportStatus;
|
||||
phase: ImportPhase;
|
||||
errorCode: string | null;
|
||||
canRetry: boolean;
|
||||
retryMessage: string | null;
|
||||
warnings: string[];
|
||||
createdAt: UtcDateTime;
|
||||
startedAt: UtcDateTime | null;
|
||||
finishedAt: UtcDateTime | null;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useState, type ReactNode } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import * as api from '@/api';
|
||||
import { getToken, onUnauthorized, setToken } from '@/api/request';
|
||||
import type { AdminView } from '@/api/types';
|
||||
|
||||
interface AuthState {
|
||||
admin: AdminView | null;
|
||||
loading: boolean;
|
||||
signIn: (email: string, password: string) => Promise<void>;
|
||||
signOut: () => Promise<void>;
|
||||
clear: () => void;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthState>(null!);
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [admin, setAdmin] = useState<AdminView | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const clear = useCallback(() => {
|
||||
setToken(null);
|
||||
setAdmin(null);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
onUnauthorized(() => {
|
||||
setAdmin(null);
|
||||
const here = window.location.pathname + window.location.search;
|
||||
if (!here.startsWith('/login')) {
|
||||
navigate(`/login?redirect=${encodeURIComponent(here)}`, { replace: true });
|
||||
}
|
||||
});
|
||||
}, [navigate]);
|
||||
|
||||
useEffect(() => {
|
||||
// 页面初始化必须调用 /auth/me 确认登录状态
|
||||
if (!getToken()) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
api
|
||||
.getMe()
|
||||
.then(setAdmin)
|
||||
.catch(() => clear())
|
||||
.finally(() => setLoading(false));
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const signIn = useCallback(async (email: string, password: string) => {
|
||||
const result = await api.login(email, password);
|
||||
setAdmin(result.admin);
|
||||
}, []);
|
||||
|
||||
const signOut = useCallback(async () => {
|
||||
try {
|
||||
await api.logout();
|
||||
} catch {
|
||||
/* 无论成功与否都清空本地状态 */
|
||||
}
|
||||
clear();
|
||||
navigate('/login', { replace: true });
|
||||
}, [clear, navigate]);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ admin, loading, signIn, signOut, clear }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export const useAuth = () => useContext(AuthContext);
|
||||
@@ -0,0 +1,85 @@
|
||||
.vm-shell { min-height: 100vh; }
|
||||
|
||||
/* ---------- 侧边栏 ---------- */
|
||||
.vm-sider {
|
||||
background: linear-gradient(180deg, #12143a 0%, #0f1124 38%, #0b0d1a 100%) !important;
|
||||
border-right: 1px solid rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
.vm-sider .ant-layout-sider-children {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.vm-sider-brand { height: 72px; display: flex; align-items: center; padding: 0 22px; }
|
||||
.vm-sider.ant-layout-sider-collapsed .vm-sider-brand { justify-content: center; padding: 0; }
|
||||
.vm-sider-section {
|
||||
padding: 12px 28px 8px;
|
||||
font-size: 11px;
|
||||
letter-spacing: 0.16em;
|
||||
color: rgba(226, 232, 255, 0.35);
|
||||
font-weight: 600;
|
||||
}
|
||||
.vm-sider .ant-menu-dark .ant-menu-item-selected {
|
||||
box-shadow: inset 3px 0 0 #818cf8;
|
||||
font-weight: 500;
|
||||
}
|
||||
.vm-sider .ant-menu-dark .ant-menu-item-selected .anticon { color: #a5b4fc; }
|
||||
.vm-sider-foot { margin-top: auto; padding: 20px 16px; display: flex; justify-content: center; }
|
||||
|
||||
.vm-logo { display: flex; align-items: center; gap: 12px; }
|
||||
.vm-logo-name { font-size: 17px; font-weight: 700; letter-spacing: -0.01em; line-height: 1.2; }
|
||||
.vm-logo-sub { font-size: 11px; letter-spacing: 0.08em; margin-top: 2px; }
|
||||
|
||||
.vm-env {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 14px;
|
||||
border-radius: 10px;
|
||||
font-size: 12px;
|
||||
color: rgba(226, 232, 255, 0.75);
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
.vm-env-dot { width: 8px; height: 8px; border-radius: 50%; background: #60a5fa; box-shadow: 0 0 0 3px rgba(96, 165, 250, 0.2); display: inline-block; }
|
||||
.env-test .vm-env-dot, .vm-env-dot.env-test { background: #f59e0b; box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.2); }
|
||||
.env-prod .vm-env-dot, .vm-env-dot.env-prod { background: #ef4444; box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.25); }
|
||||
|
||||
/* ---------- 顶栏 ---------- */
|
||||
.vm-header {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
backdrop-filter: saturate(180%) blur(12px);
|
||||
border-bottom: 1px solid #eceef5;
|
||||
}
|
||||
.vm-header-left { display: flex; align-items: center; gap: 8px; }
|
||||
.vm-header-title { font-size: 16px; font-weight: 600; color: #111827; }
|
||||
.vm-user {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
cursor: pointer;
|
||||
padding: 4px 10px 4px 4px;
|
||||
border-radius: 999px;
|
||||
line-height: 1.2;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
.vm-user:hover { background: #f3f4f8; }
|
||||
.vm-avatar { background: linear-gradient(135deg, #6366f1, #8b5cf6) !important; font-weight: 600; }
|
||||
.vm-user-name { font-size: 13px; font-weight: 600; color: #111827; }
|
||||
.vm-user-mail { font-size: 12px; color: #9ca3af; }
|
||||
|
||||
/* ---------- 内容区 ---------- */
|
||||
.vm-content { padding: 24px 28px 40px; max-width: 1600px; width: 100%; box-sizing: border-box; margin: 0 auto; }
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.vm-user-meta { display: none; }
|
||||
.vm-content { padding: 16px; }
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { useState } from 'react';
|
||||
import { Avatar, Button, Dropdown, Layout, Menu, Tooltip } from 'antd';
|
||||
import {
|
||||
AppstoreOutlined,
|
||||
CloudDownloadOutlined,
|
||||
DownOutlined,
|
||||
KeyOutlined,
|
||||
LogoutOutlined,
|
||||
MenuFoldOutlined,
|
||||
MenuUnfoldOutlined,
|
||||
TeamOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
|
||||
import { useAuth } from '@/auth';
|
||||
import { environment } from '@/config/environment';
|
||||
import Logo, { LogoMark } from './Logo';
|
||||
import './AdminLayout.css';
|
||||
|
||||
const envName: Record<string, { text: string; cls: string }> = {
|
||||
development: { text: '本地开发 · 测试接口', cls: 'env-dev' },
|
||||
test: { text: '测试环境', cls: 'env-test' },
|
||||
production: { text: '线上环境', cls: 'env-prod' },
|
||||
};
|
||||
|
||||
const nav = [
|
||||
{ key: '/projects', icon: <AppstoreOutlined />, label: '项目管理' },
|
||||
{ key: '/imports', icon: <CloudDownloadOutlined />, label: 'GitHub 迁移' },
|
||||
{ key: '/users', icon: <TeamOutlined />, label: '用户管理' },
|
||||
];
|
||||
|
||||
export default function AdminLayout() {
|
||||
const { admin, signOut } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const { pathname } = useLocation();
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
const selected = '/' + (pathname.split('/')[1] || 'projects');
|
||||
const current = nav.find((n) => n.key === selected);
|
||||
const env = envName[environment.appEnvironment];
|
||||
const initial = (admin?.nickname || admin?.email || 'A').slice(0, 1).toUpperCase();
|
||||
|
||||
return (
|
||||
<Layout className="vm-shell">
|
||||
<Layout.Sider
|
||||
width={232}
|
||||
collapsedWidth={76}
|
||||
collapsed={collapsed}
|
||||
breakpoint="lg"
|
||||
onBreakpoint={setCollapsed}
|
||||
trigger={null}
|
||||
className="vm-sider"
|
||||
>
|
||||
<div className="vm-sider-brand">{collapsed ? <LogoMark size={34} /> : <Logo dark subtitle="Admin Console" />}</div>
|
||||
{!collapsed && <div className="vm-sider-section">工作台</div>}
|
||||
<Menu theme="dark" mode="inline" selectedKeys={[selected]} onClick={(e) => navigate(e.key)} items={nav} />
|
||||
<div className="vm-sider-foot">
|
||||
{collapsed ? (
|
||||
<Tooltip title={env?.text} placement="right"><span className={`vm-env-dot ${env?.cls ?? ''}`} /></Tooltip>
|
||||
) : (
|
||||
env && <div className={`vm-env ${env.cls}`}><span className="vm-env-dot" />{env.text}</div>
|
||||
)}
|
||||
</div>
|
||||
</Layout.Sider>
|
||||
<Layout>
|
||||
<Layout.Header className="vm-header">
|
||||
<div className="vm-header-left">
|
||||
<Button
|
||||
type="text"
|
||||
icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
|
||||
onClick={() => setCollapsed(!collapsed)}
|
||||
/>
|
||||
<span className="vm-header-title">{current?.label ?? '账号设置'}</span>
|
||||
</div>
|
||||
<Dropdown
|
||||
trigger={['click']}
|
||||
menu={{
|
||||
items: [
|
||||
{ key: 'account', icon: <KeyOutlined />, label: '账号与密码' },
|
||||
{ type: 'divider' },
|
||||
{ key: 'logout', icon: <LogoutOutlined />, label: '退出登录', danger: true },
|
||||
],
|
||||
onClick: ({ key }) => (key === 'logout' ? signOut() : navigate('/account')),
|
||||
}}
|
||||
>
|
||||
<div className="vm-user">
|
||||
<Avatar size={34} className="vm-avatar">{initial}</Avatar>
|
||||
<div className="vm-user-meta">
|
||||
<div className="vm-user-name">{admin?.nickname || '管理员'}</div>
|
||||
<div className="vm-user-mail">{admin?.email}</div>
|
||||
</div>
|
||||
<DownOutlined style={{ fontSize: 10, color: '#9ca3af' }} />
|
||||
</div>
|
||||
</Dropdown>
|
||||
</Layout.Header>
|
||||
<Layout.Content className="vm-content">
|
||||
<Outlet />
|
||||
</Layout.Content>
|
||||
</Layout>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { useState } from 'react';
|
||||
import { App, Button, Image, Space, Upload } from 'antd';
|
||||
import { DeleteOutlined, UploadOutlined } from '@ant-design/icons';
|
||||
import * as api from '@/api';
|
||||
import { errorText, MiB } from '@/utils/format';
|
||||
|
||||
const ACCEPT = ['image/jpeg', 'image/png', 'image/webp'];
|
||||
|
||||
/** 封面:获取签名 → OSS 直传 → 回填 coverUrl。value 为 coverUrl,"" 表示清空 */
|
||||
export default function CoverUpload({
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
value?: string | null;
|
||||
onChange?: (v: string) => void;
|
||||
}) {
|
||||
const { message } = App.useApp();
|
||||
const [uploading, setUploading] = useState(false);
|
||||
|
||||
const beforeUpload = async (file: File) => {
|
||||
if (!ACCEPT.includes(file.type)) {
|
||||
message.error('仅支持 JPG / PNG / WEBP');
|
||||
return Upload.LIST_IGNORE;
|
||||
}
|
||||
if (file.size <= 0 || file.size > 5 * MiB) {
|
||||
message.error('封面大小需在 5 MiB 以内');
|
||||
return Upload.LIST_IGNORE;
|
||||
}
|
||||
setUploading(true);
|
||||
try {
|
||||
const url = await api.uploadCover(file);
|
||||
onChange?.(url);
|
||||
message.success('封面上传成功,保存表单后生效');
|
||||
} catch (e) {
|
||||
message.error(errorText(e));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
return Upload.LIST_IGNORE;
|
||||
};
|
||||
|
||||
return (
|
||||
<Space align="start">
|
||||
{value ? (
|
||||
<Image src={value} width={160} height={100} style={{ objectFit: 'cover', borderRadius: 6 }} />
|
||||
) : (
|
||||
<div style={{ width: 160, height: 100, background: '#f5f5f5', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#999' }}>
|
||||
暂无封面
|
||||
</div>
|
||||
)}
|
||||
<Space direction="vertical">
|
||||
<Upload accept={ACCEPT.join(',')} showUploadList={false} beforeUpload={beforeUpload}>
|
||||
<Button icon={<UploadOutlined />} loading={uploading}>{value ? '更换封面' : '上传封面'}</Button>
|
||||
</Upload>
|
||||
{value && <Button icon={<DeleteOutlined />} onClick={() => onChange?.('')}>清除封面</Button>}
|
||||
</Space>
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { App, Form, Input, Modal } from 'antd';
|
||||
import * as api from '@/api';
|
||||
import type { UserView } from '@/api/types';
|
||||
import { errorText } from '@/utils/format';
|
||||
|
||||
export default function EditNicknameModal({
|
||||
user,
|
||||
onClose,
|
||||
onSaved,
|
||||
}: {
|
||||
user: UserView | null;
|
||||
onClose: () => void;
|
||||
onSaved: (u: UserView) => void;
|
||||
}) {
|
||||
const [form] = Form.useForm();
|
||||
const { message } = App.useApp();
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (user) form.setFieldsValue({ nickname: user.nickname });
|
||||
}, [user, form]);
|
||||
|
||||
const onOk = async () => {
|
||||
const { nickname } = await form.validateFields();
|
||||
setLoading(true);
|
||||
try {
|
||||
const u = await api.updateUser(user!.userCode, nickname.trim());
|
||||
message.success('昵称已更新');
|
||||
onSaved(u);
|
||||
} catch (e) {
|
||||
message.error(errorText(e));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal title="编辑昵称" open={!!user} onCancel={onClose} onOk={onOk} confirmLoading={loading} destroyOnClose>
|
||||
<Form form={form} layout="vertical" preserve={false}>
|
||||
<Form.Item name="nickname" label="昵称" rules={[{ required: true, whitespace: true }, { max: 64 }]}>
|
||||
<Input maxLength={64} showCount />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Space } from 'antd';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { TaskView } from '@/api/types';
|
||||
import { canRetryImportTask } from '@/utils/imports';
|
||||
|
||||
export default function ImportTaskActions({ task }: { task: TaskView }) {
|
||||
const path = `/imports/${task.taskCode}`;
|
||||
return (
|
||||
<Space wrap>
|
||||
<Link to={path}>查看详情</Link>
|
||||
{canRetryImportTask(task) && <Link to={`${path}?retry=1`}>重试迁移</Link>}
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { useId } from 'react';
|
||||
|
||||
export function LogoMark({ size = 32 }: { size?: number }) {
|
||||
// 每个实例使用独立的渐变 id,避免隐藏元素中的同名定义导致图标不显示
|
||||
const id = `vm-logo-${useId().replace(/:/g, '')}`;
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 64 64" aria-hidden>
|
||||
<defs>
|
||||
<linearGradient id={id} x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stopColor="#6366f1" />
|
||||
<stop offset=".55" stopColor="#8b5cf6" />
|
||||
<stop offset="1" stopColor="#06b6d4" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="64" height="64" rx="16" fill={`url(#${id})`} />
|
||||
<path d="M16 20l16 26 16-26" fill="none" stroke="#fff" strokeWidth="6" strokeLinecap="round" strokeLinejoin="round" />
|
||||
<circle cx="32" cy="18" r="4" fill="#fff" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Logo({ dark, subtitle }: { dark?: boolean; subtitle?: string }) {
|
||||
return (
|
||||
<div className="vm-logo">
|
||||
<LogoMark size={34} />
|
||||
<div>
|
||||
<div className="vm-logo-name" style={{ color: dark ? '#fff' : '#0b0d1a' }}>VibeMake</div>
|
||||
{subtitle && <div className="vm-logo-sub" style={{ color: dark ? 'rgba(226,232,255,.55)' : '#6b7280' }}>{subtitle}</div>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Radio, Select, Space, Spin } from 'antd';
|
||||
import * as api from '@/api';
|
||||
import type { UserView } from '@/api/types';
|
||||
|
||||
/** 归属选择:undefined 表示社区官方;否则为正常普通用户的 userCode */
|
||||
export default function OwnerSelect({
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
value?: string;
|
||||
onChange?: (v: string | undefined) => void;
|
||||
}) {
|
||||
const [mode, setMode] = useState<'official' | 'user'>(value ? 'user' : 'official');
|
||||
const [options, setOptions] = useState<UserView[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const timer = useRef<number>();
|
||||
|
||||
const search = (keyword: string) => {
|
||||
window.clearTimeout(timer.current);
|
||||
timer.current = window.setTimeout(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const kw = keyword.trim();
|
||||
const q = kw.includes('@') ? { email: kw } : kw ? { nickname: kw } : {};
|
||||
const res = await api.listUsers({ role: 'USER', status: 'ACTIVE', page: 1, size: 20, ...q });
|
||||
setOptions(res.items);
|
||||
} catch {
|
||||
setOptions([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, 300);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (mode === 'user' && options.length === 0) search('');
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [mode]);
|
||||
|
||||
return (
|
||||
<Space direction="vertical" style={{ width: '100%' }}>
|
||||
<Radio.Group
|
||||
value={mode}
|
||||
onChange={(e) => {
|
||||
setMode(e.target.value);
|
||||
if (e.target.value === 'official') onChange?.(undefined);
|
||||
}}
|
||||
>
|
||||
<Radio value="official">社区官方</Radio>
|
||||
<Radio value="user">指定普通用户</Radio>
|
||||
</Radio.Group>
|
||||
{mode === 'user' && (
|
||||
<Select
|
||||
showSearch
|
||||
allowClear
|
||||
value={value}
|
||||
placeholder="输入昵称或邮箱搜索正常普通用户"
|
||||
filterOption={false}
|
||||
onSearch={search}
|
||||
onChange={(v) => onChange?.(v)}
|
||||
notFoundContent={loading ? <Spin size="small" /> : '无匹配用户'}
|
||||
options={options.map((u) => ({ value: u.userCode, label: `${u.nickname}(${u.email})` }))}
|
||||
style={{ maxWidth: 480 }}
|
||||
/>
|
||||
)}
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Form, Input, Select } from 'antd';
|
||||
import type { TypeView } from '@/api/types';
|
||||
import CoverUpload from './CoverUpload';
|
||||
|
||||
/** 项目基础信息字段(name/description/projectType/coverUrl),嵌在外层 Form 中 */
|
||||
export default function ProjectFields({ types }: { types: TypeView[] }) {
|
||||
return (
|
||||
<>
|
||||
<Form.Item name="name" label="项目名称" rules={[{ required: true, whitespace: true, message: '请输入项目名称' }, { max: 100 }]}>
|
||||
<Input maxLength={100} showCount />
|
||||
</Form.Item>
|
||||
<Form.Item name="description" label="项目描述" rules={[{ max: 2000 }]}>
|
||||
<Input.TextArea rows={4} maxLength={2000} showCount />
|
||||
</Form.Item>
|
||||
<Form.Item name="projectType" label="项目类型" rules={[{ required: true, message: '请选择项目类型' }]}>
|
||||
<Select placeholder="请选择" options={types.map((t) => ({ value: t.code, label: t.name }))} style={{ maxWidth: 320 }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="coverUrl" label="封面" extra="JPG / PNG / WEBP,最大 5 MiB">
|
||||
<CoverUpload />
|
||||
</Form.Item>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { Image, Table, Tooltip, Typography } from 'antd';
|
||||
import type { TablePaginationConfig } from 'antd';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { ManagedProjectView, TypeView } from '@/api/types';
|
||||
import StatusTag from './StatusTag';
|
||||
import { formatTime, shortSha } from '@/utils/format';
|
||||
import { publishStatusLabel, repoStatusLabel } from '@/utils/labels';
|
||||
|
||||
const gradients = [
|
||||
'linear-gradient(135deg,#6366f1,#8b5cf6)',
|
||||
'linear-gradient(135deg,#0ea5e9,#6366f1)',
|
||||
'linear-gradient(135deg,#14b8a6,#0ea5e9)',
|
||||
'linear-gradient(135deg,#f59e0b,#ef4444)',
|
||||
'linear-gradient(135deg,#8b5cf6,#ec4899)',
|
||||
'linear-gradient(135deg,#10b981,#14b8a6)',
|
||||
];
|
||||
|
||||
export function coverGradient(seed: string) {
|
||||
let h = 0;
|
||||
for (const c of seed) h = (h * 31 + c.charCodeAt(0)) >>> 0;
|
||||
return gradients[h % gradients.length];
|
||||
}
|
||||
|
||||
export default function ProjectTable({
|
||||
items,
|
||||
loading,
|
||||
pagination,
|
||||
types = [],
|
||||
hideOwner,
|
||||
}: {
|
||||
items: ManagedProjectView[];
|
||||
loading?: boolean;
|
||||
pagination: TablePaginationConfig;
|
||||
types?: TypeView[];
|
||||
hideOwner?: boolean;
|
||||
}) {
|
||||
const typeName = (code: string) => types.find((t) => t.code === code)?.name ?? code;
|
||||
return (
|
||||
<Table<ManagedProjectView>
|
||||
rowKey={(r) => r.project.projectCode}
|
||||
loading={loading}
|
||||
dataSource={items}
|
||||
pagination={pagination}
|
||||
scroll={{ x: 1250 }}
|
||||
columns={[
|
||||
{
|
||||
title: '项目',
|
||||
width: 300,
|
||||
render: (_, { project: p }) => (
|
||||
<div className="pt-cell">
|
||||
{p.coverUrl ? (
|
||||
<Image src={p.coverUrl} width={56} height={42} className="pt-cover" preview={false} />
|
||||
) : (
|
||||
<div className="pt-cover pt-cover-empty" style={{ background: coverGradient(p.projectCode) }}>
|
||||
{p.name.slice(0, 1).toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
<div className="pt-meta">
|
||||
<Link to={`/projects/${p.projectCode}`} className="pt-name" title={p.name}>{p.name}</Link>
|
||||
<Typography.Text type="secondary" className="mono pt-code">{p.projectCode}</Typography.Text>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{ title: '类型', width: 90, render: (_, r) => typeName(r.project.projectType) },
|
||||
...(hideOwner
|
||||
? []
|
||||
: [{
|
||||
title: '所有者',
|
||||
width: 130,
|
||||
render: (_: unknown, r: ManagedProjectView) =>
|
||||
r.project.owner.userCode ? <Link to={`/users/${r.project.owner.userCode}`}>{r.project.owner.nickname}</Link> : r.project.owner.nickname,
|
||||
}]),
|
||||
{ title: '仓库', width: 110, render: (_, r) => <StatusTag map={repoStatusLabel} value={r.project.repoStatus} /> },
|
||||
{
|
||||
title: '发布',
|
||||
width: 90,
|
||||
render: (_, r) => (
|
||||
<Tooltip title={r.moderationReason ? `下架原因:${r.moderationReason}` : undefined}>
|
||||
<span><StatusTag map={publishStatusLabel} value={r.project.publishStatus} /></span>
|
||||
</Tooltip>
|
||||
),
|
||||
},
|
||||
{ title: '发布版本', width: 120, render: (_, r) => <span className="mono">{shortSha(r.project.publishedCommitSha)}</span> },
|
||||
{ title: '点赞 / 评论', width: 110, render: (_, r) => `${r.project.likeCount} / ${r.project.commentCount}` },
|
||||
{ title: '创建时间', width: 170, render: (_, r) => <span className="nowrap">{formatTime(r.project.createdAt)}</span> },
|
||||
{ title: '操作', fixed: 'right', width: 80, render: (_, r) => <Link to={`/projects/${r.project.projectCode}`}>管理</Link> },
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Tag } from 'antd';
|
||||
|
||||
export default function StatusTag({
|
||||
map,
|
||||
value,
|
||||
}: {
|
||||
map: Record<string, { text: string; color: string }>;
|
||||
value?: string | null;
|
||||
}) {
|
||||
if (!value) return <>—</>;
|
||||
const item = map[value];
|
||||
return <Tag color={item?.color}>{item?.text ?? value}</Tag>;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { Table, Tag, Tooltip } from 'antd';
|
||||
import * as api from '@/api';
|
||||
import type { HistoryEntry } from '@/api/types';
|
||||
import { formatTime, shortSha } from '@/utils/format';
|
||||
import { usePaged } from '@/utils/usePaged';
|
||||
|
||||
export default function CommitHistory({
|
||||
projectCode,
|
||||
publishedSha,
|
||||
refreshKey,
|
||||
onBrowse,
|
||||
}: {
|
||||
projectCode: string;
|
||||
publishedSha: string | null;
|
||||
refreshKey: unknown;
|
||||
onBrowse: (sha: string) => void;
|
||||
}) {
|
||||
const list = usePaged<HistoryEntry, object>((q) => api.listCommits(projectCode, q.page, q.size), {}, [projectCode, refreshKey]);
|
||||
return (
|
||||
<Table<HistoryEntry>
|
||||
rowKey="commitSha"
|
||||
size="middle"
|
||||
loading={list.loading}
|
||||
dataSource={list.data.items}
|
||||
pagination={list.pagination}
|
||||
columns={[
|
||||
{
|
||||
title: 'Commit',
|
||||
width: 200,
|
||||
render: (_, c) => (
|
||||
<>
|
||||
<Tooltip title={c.commitSha}><span className="mono">{shortSha(c.commitSha)}</span></Tooltip>
|
||||
{c.commitSha === publishedSha && <Tag color="green" style={{ marginLeft: 8 }}>已发布</Tag>}
|
||||
</>
|
||||
),
|
||||
},
|
||||
{ title: '说明', dataIndex: 'message', ellipsis: true },
|
||||
{ title: '作者', dataIndex: 'authorName', width: 160 },
|
||||
{ title: '时间', dataIndex: 'authorDate', width: 190, render: formatTime },
|
||||
{ title: '操作', width: 110, render: (_, c) => <a onClick={() => onBrowse(c.commitSha)}>浏览此版本</a> },
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { App, Form, Modal } from 'antd';
|
||||
import * as api from '@/api';
|
||||
import type { ProjectView, TypeView } from '@/api/types';
|
||||
import ProjectFields from '@/components/ProjectFields';
|
||||
import { errorText } from '@/utils/format';
|
||||
|
||||
export default function EditProjectModal({
|
||||
project,
|
||||
types,
|
||||
open,
|
||||
onClose,
|
||||
onSaved,
|
||||
}: {
|
||||
project: ProjectView;
|
||||
types: TypeView[];
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onSaved: () => void;
|
||||
}) {
|
||||
const [form] = Form.useForm();
|
||||
const { message } = App.useApp();
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
form.setFieldsValue({
|
||||
name: project.name,
|
||||
description: project.description,
|
||||
projectType: project.projectType,
|
||||
coverUrl: project.coverUrl ?? '',
|
||||
});
|
||||
}
|
||||
}, [open, project, form]);
|
||||
|
||||
const onOk = async () => {
|
||||
const v = await form.validateFields();
|
||||
setLoading(true);
|
||||
try {
|
||||
// PATCH 仍需提交完整基础信息;coverUrl 传 "" 表示清空
|
||||
await api.updateProject(project.projectCode, {
|
||||
name: v.name.trim(),
|
||||
description: v.description ?? '',
|
||||
projectType: v.projectType,
|
||||
coverUrl: v.coverUrl ?? '',
|
||||
});
|
||||
message.success('已保存');
|
||||
onSaved();
|
||||
} catch (e) {
|
||||
message.error(errorText(e));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal title="编辑项目信息" open={open} onCancel={onClose} onOk={onOk} confirmLoading={loading} width={720} destroyOnClose>
|
||||
<Form form={form} layout="vertical">
|
||||
<ProjectFields types={types} />
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import {
|
||||
Alert,
|
||||
App,
|
||||
Breadcrumb,
|
||||
Button,
|
||||
Checkbox,
|
||||
Dropdown,
|
||||
Form,
|
||||
Input,
|
||||
Modal,
|
||||
Popconfirm,
|
||||
Space,
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import {
|
||||
DownloadOutlined,
|
||||
FileAddOutlined,
|
||||
FileOutlined,
|
||||
FolderAddOutlined,
|
||||
FolderFilled,
|
||||
ReloadOutlined,
|
||||
UploadOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import * as api from '@/api';
|
||||
import type { SelectedFile, TreeEntry, TreeView } from '@/api/types';
|
||||
import { AdminApiError } from '@/api/request';
|
||||
import { errorText, formatSize, MiB, shortSha, utf8Bytes } from '@/utils/format';
|
||||
import FileViewer from './FileViewer';
|
||||
import { joinPath, pickFiles, toSelected, validatePath } from './pickFiles';
|
||||
|
||||
interface Props {
|
||||
projectCode: string;
|
||||
/** 指定后为只读浏览历史快照 */
|
||||
snapshotSha?: string;
|
||||
onExitSnapshot?: () => void;
|
||||
/** 工作区提交成功后通知父组件刷新(历史、详情等) */
|
||||
onCommitted?: (sha: string) => void;
|
||||
onWorkspaceSha?: (sha: string) => void;
|
||||
}
|
||||
|
||||
export default function FileBrowser({ projectCode, snapshotSha, onExitSnapshot, onCommitted, onWorkspaceSha }: Props) {
|
||||
const { message } = App.useApp();
|
||||
const [dir, setDir] = useState('');
|
||||
const [tree, setTree] = useState<TreeView | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [viewing, setViewing] = useState<string | null>(null);
|
||||
const [createMode, setCreateMode] = useState<'file' | 'dir' | null>(null);
|
||||
const [uploadFiles, setUploadFiles] = useState<SelectedFile[] | null>(null);
|
||||
const readOnly = !!snapshotSha;
|
||||
|
||||
const load = useCallback(
|
||||
async (path = dir) => {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
const t = await api.getTree(projectCode, path, snapshotSha);
|
||||
setTree(t);
|
||||
if (!snapshotSha) onWorkspaceSha?.(t.commitSha);
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[projectCode, snapshotSha, dir],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
load(dir);
|
||||
}, [load, dir]);
|
||||
|
||||
useEffect(() => {
|
||||
setDir('');
|
||||
}, [snapshotSha]);
|
||||
|
||||
const committed = (sha: string) => {
|
||||
onCommitted?.(sha);
|
||||
load(dir);
|
||||
};
|
||||
|
||||
const deleteFile = async (entry: TreeEntry) => {
|
||||
if (!tree) return;
|
||||
try {
|
||||
const res = await api.createCommit(projectCode, {
|
||||
expectedCommitSha: tree.commitSha,
|
||||
message: `删除 ${entry.path}`,
|
||||
changes: [{ action: 'DELETE_FILE', path: entry.path }],
|
||||
});
|
||||
message.success(`已删除,新版本 ${shortSha(res.commitSha)}`);
|
||||
committed(res.commitSha);
|
||||
} catch (e) {
|
||||
message.error(errorText(e));
|
||||
if (e instanceof AdminApiError && e.status === 409) load(dir);
|
||||
}
|
||||
};
|
||||
|
||||
const startUpload = async (directory: boolean) => {
|
||||
const files = await pickFiles({ directory });
|
||||
if (files.length) setUploadFiles(toSelected(files, true));
|
||||
};
|
||||
|
||||
const crumbs = dir ? dir.split('/') : [];
|
||||
const entries = [...(tree?.entries ?? [])].sort((a, b) =>
|
||||
a.type === b.type ? a.name.localeCompare(b.name) : a.type === 'dir' ? -1 : b.type === 'dir' ? 1 : 0,
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{readOnly && (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
style={{ marginBottom: 12 }}
|
||||
message={<>正在只读浏览历史版本 <span className="mono">{shortSha(snapshotSha)}</span></>}
|
||||
action={<Button size="small" onClick={onExitSnapshot}>返回当前工作区</Button>}
|
||||
/>
|
||||
)}
|
||||
<Space style={{ width: '100%', justifyContent: 'space-between', marginBottom: 12 }} wrap>
|
||||
<Breadcrumb
|
||||
items={[
|
||||
{ title: <a onClick={() => setDir('')}>根目录</a> },
|
||||
...crumbs.map((c, i) => ({
|
||||
title: i === crumbs.length - 1 ? c : <a onClick={() => setDir(crumbs.slice(0, i + 1).join('/'))}>{c}</a>,
|
||||
})),
|
||||
]}
|
||||
/>
|
||||
<Space wrap>
|
||||
{tree && (
|
||||
<Typography.Text type="secondary">
|
||||
{readOnly ? '快照' : '工作区 main'} <span className="mono">{shortSha(tree.commitSha)}</span>
|
||||
</Typography.Text>
|
||||
)}
|
||||
<Button icon={<ReloadOutlined />} onClick={() => load(dir)}>刷新</Button>
|
||||
{!readOnly && (
|
||||
<>
|
||||
<Button icon={<FileAddOutlined />} onClick={() => setCreateMode('file')}>新建文件</Button>
|
||||
<Button icon={<FolderAddOutlined />} onClick={() => setCreateMode('dir')}>新建目录</Button>
|
||||
<Dropdown
|
||||
menu={{
|
||||
items: [
|
||||
{ key: 'files', label: '上传文件' },
|
||||
{ key: 'dir', label: '上传文件夹' },
|
||||
],
|
||||
onClick: ({ key }) => startUpload(key === 'dir'),
|
||||
}}
|
||||
>
|
||||
<Button type="primary" icon={<UploadOutlined />}>上传</Button>
|
||||
</Dropdown>
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
</Space>
|
||||
{error && <Alert type="error" showIcon message={error} style={{ marginBottom: 12 }} />}
|
||||
<Table<TreeEntry>
|
||||
rowKey="path"
|
||||
size="middle"
|
||||
loading={loading}
|
||||
dataSource={entries}
|
||||
pagination={false}
|
||||
locale={{ emptyText: '空目录' }}
|
||||
columns={[
|
||||
{
|
||||
title: '名称',
|
||||
render: (_, e) =>
|
||||
e.type === 'dir' ? (
|
||||
<a onClick={() => setDir(e.path)}><FolderFilled style={{ color: '#f4b400', marginRight: 8 }} />{e.name}</a>
|
||||
) : e.type === 'file' ? (
|
||||
<a onClick={() => setViewing(e.path)}><FileOutlined style={{ marginRight: 8 }} />{e.name}</a>
|
||||
) : (
|
||||
<span><FileOutlined style={{ marginRight: 8 }} />{e.name} <Tag>{e.type}</Tag></span>
|
||||
),
|
||||
},
|
||||
{ title: '大小', width: 120, render: (_, e) => (e.type === 'file' ? formatSize(e.size) : '') },
|
||||
{
|
||||
title: '操作',
|
||||
width: 180,
|
||||
render: (_, e) =>
|
||||
e.type === 'file' ? (
|
||||
<Space>
|
||||
<a onClick={() => setViewing(e.path)}>查看</a>
|
||||
<a onClick={() => api.downloadFile(projectCode, e.path, snapshotSha).catch((err) => message.error(errorText(err)))}>
|
||||
<DownloadOutlined /> 下载
|
||||
</a>
|
||||
{!readOnly && (
|
||||
<Popconfirm title={`确定删除 ${e.name}?将产生一次提交`} onConfirm={() => deleteFile(e)}>
|
||||
<a style={{ color: '#ff4d4f' }}>删除</a>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
) : null,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<FileViewer
|
||||
projectCode={projectCode}
|
||||
path={viewing}
|
||||
commitSha={snapshotSha}
|
||||
readOnly={readOnly}
|
||||
workspaceSha={tree?.commitSha}
|
||||
onClose={() => setViewing(null)}
|
||||
onCommitted={(sha) => { setViewing(null); committed(sha); }}
|
||||
/>
|
||||
{tree && !readOnly && (
|
||||
<>
|
||||
<CreateModal
|
||||
mode={createMode}
|
||||
dir={dir}
|
||||
projectCode={projectCode}
|
||||
expectedSha={tree.commitSha}
|
||||
onClose={() => setCreateMode(null)}
|
||||
onDone={(sha) => { setCreateMode(null); committed(sha); }}
|
||||
/>
|
||||
<UploadModal
|
||||
files={uploadFiles}
|
||||
dir={dir}
|
||||
projectCode={projectCode}
|
||||
expectedSha={tree.commitSha}
|
||||
onClose={() => setUploadFiles(null)}
|
||||
onDone={(sha) => { setUploadFiles(null); committed(sha); }}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function CreateModal({
|
||||
mode,
|
||||
dir,
|
||||
projectCode,
|
||||
expectedSha,
|
||||
onClose,
|
||||
onDone,
|
||||
}: {
|
||||
mode: 'file' | 'dir' | null;
|
||||
dir: string;
|
||||
projectCode: string;
|
||||
expectedSha: string;
|
||||
onClose: () => void;
|
||||
onDone: (sha: string) => void;
|
||||
}) {
|
||||
const { message } = App.useApp();
|
||||
const [form] = Form.useForm();
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const onOk = async () => {
|
||||
const v = await form.validateFields();
|
||||
const path = joinPath(dir, v.name.trim());
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await api.createCommit(projectCode, {
|
||||
expectedCommitSha: expectedSha,
|
||||
message: v.message.trim(),
|
||||
changes: [
|
||||
mode === 'file'
|
||||
? { action: 'CREATE_FILE', path, content: v.content ?? '' }
|
||||
: { action: 'CREATE_DIRECTORY', path },
|
||||
],
|
||||
});
|
||||
message.success(`已提交 ${shortSha(res.commitSha)}`);
|
||||
form.resetFields();
|
||||
onDone(res.commitSha);
|
||||
} catch (e) {
|
||||
message.error(errorText(e));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={mode === 'file' ? '新建文件' : '新建目录'}
|
||||
open={!!mode}
|
||||
onCancel={onClose}
|
||||
onOk={onOk}
|
||||
confirmLoading={loading}
|
||||
width={mode === 'file' ? 800 : 520}
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item
|
||||
name="name"
|
||||
label={`${mode === 'file' ? '文件' : '目录'}路径(相对于 ${dir || '根目录'})`}
|
||||
rules={[
|
||||
{ required: true, whitespace: true },
|
||||
{ validator: (_, v) => { const err = v ? validatePath(joinPath(dir, v.trim())) : null; return err ? Promise.reject(err) : Promise.resolve(); } },
|
||||
]}
|
||||
>
|
||||
<Input placeholder={mode === 'file' ? '例如 README.md 或 docs/说明.md' : '例如 models'} />
|
||||
</Form.Item>
|
||||
{mode === 'file' && (
|
||||
<Form.Item
|
||||
name="content"
|
||||
label="内容"
|
||||
className="file-editor"
|
||||
rules={[{ validator: (_, v) => (v && utf8Bytes(v) > MiB ? Promise.reject('在线文本不能超过 1 MiB') : Promise.resolve()) }]}
|
||||
>
|
||||
<Input.TextArea rows={14} spellCheck={false} />
|
||||
</Form.Item>
|
||||
)}
|
||||
<Form.Item name="message" label="提交说明" rules={[{ required: true, whitespace: true }, { max: 1000 }]}>
|
||||
<Input maxLength={1000} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function UploadModal({
|
||||
files,
|
||||
dir,
|
||||
projectCode,
|
||||
expectedSha,
|
||||
onClose,
|
||||
onDone,
|
||||
}: {
|
||||
files: SelectedFile[] | null;
|
||||
dir: string;
|
||||
projectCode: string;
|
||||
expectedSha: string;
|
||||
onClose: () => void;
|
||||
onDone: (sha: string) => void;
|
||||
}) {
|
||||
const { message } = App.useApp();
|
||||
const [keepRoot, setKeepRoot] = useState(true);
|
||||
const [commitMsg, setCommitMsg] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setKeepRoot(true);
|
||||
setCommitMsg(files ? `上传 ${files.length} 个文件` : '');
|
||||
}, [files]);
|
||||
|
||||
if (!files) return null;
|
||||
const isDir = files.some((f) => (f.file as File & { webkitRelativePath?: string }).webkitRelativePath);
|
||||
const selected = isDir ? toSelected(files.map((f) => f.file), keepRoot) : files;
|
||||
const total = selected.reduce((s, f) => s + f.file.size, 0);
|
||||
const tooBig = selected.filter((f) => f.file.size > 10 * MiB);
|
||||
const pathErrors = selected.map((f) => validatePath(joinPath(dir, f.relativePath))).filter(Boolean);
|
||||
const problems = [
|
||||
selected.length > 500 && '单次最多 500 个文件,请分批上传',
|
||||
total > 50 * MiB && `合计 ${formatSize(total)},超过 50 MiB,请分批上传`,
|
||||
tooBig.length > 0 && `${tooBig.length} 个文件超过单文件 10 MiB 限制:${tooBig.slice(0, 3).map((f) => f.relativePath).join('、')}`,
|
||||
pathErrors.length > 0 && `存在非法路径:${pathErrors[0]}`,
|
||||
].filter(Boolean) as string[];
|
||||
|
||||
const submit = async () => {
|
||||
if (!commitMsg.trim()) return message.warning('请填写提交说明');
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await api.uploadProjectFiles(projectCode, expectedSha, commitMsg.trim(), selected, dir);
|
||||
message.success(`上传成功,新版本 ${shortSha(res.commitSha)}`);
|
||||
onDone(res.commitSha);
|
||||
} catch (e) {
|
||||
message.error(errorText(e));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title="上传文件"
|
||||
open
|
||||
width={760}
|
||||
onCancel={loading ? undefined : onClose}
|
||||
maskClosable={false}
|
||||
footer={[
|
||||
<Button key="c" onClick={onClose} disabled={loading}>取消</Button>,
|
||||
<Button key="o" type="primary" loading={loading} disabled={problems.length > 0} onClick={submit}>提交上传</Button>,
|
||||
]}
|
||||
>
|
||||
<Space direction="vertical" style={{ width: '100%' }}>
|
||||
<Typography.Text>
|
||||
目标目录:<span className="mono">{dir || '(根目录)'}</span> · {selected.length} 个文件 · {formatSize(total)}
|
||||
</Typography.Text>
|
||||
{isDir && <Checkbox checked={keepRoot} onChange={(e) => setKeepRoot(e.target.checked)}>保留所选文件夹名称</Checkbox>}
|
||||
{problems.map((p) => <Alert key={p} type="error" showIcon message={p} />)}
|
||||
<Typography.Text type="secondary">同名路径会覆盖已有文件。最终路径预览:</Typography.Text>
|
||||
<div style={{ maxHeight: 260, overflow: 'auto', border: '1px solid #f0f0f0', borderRadius: 6, padding: 8 }}>
|
||||
{selected.map((f) => (
|
||||
<div key={f.relativePath} className="mono" style={{ fontSize: 12, display: 'flex', justifyContent: 'space-between' }}>
|
||||
<span>{joinPath(dir, f.relativePath)}</span>
|
||||
<span style={{ color: f.file.size > 10 * MiB ? '#ff4d4f' : '#999' }}>{formatSize(f.file.size)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<Input placeholder="提交说明(必填)" value={commitMsg} maxLength={1000} onChange={(e) => setCommitMsg(e.target.value)} />
|
||||
</Space>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Alert, App, Button, Drawer, Image, Input, Space, Spin, Typography } from 'antd';
|
||||
import { DownloadOutlined, EditOutlined, SaveOutlined } from '@ant-design/icons';
|
||||
import * as api from '@/api';
|
||||
import type { FileView } from '@/api/types';
|
||||
import { AdminApiError } from '@/api/request';
|
||||
import { errorText, formatSize, MiB, shortSha, utf8Bytes } from '@/utils/format';
|
||||
|
||||
const imageMime: Record<string, string> = {
|
||||
png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', svg: 'image/svg+xml', bmp: 'image/bmp',
|
||||
};
|
||||
|
||||
export default function FileViewer({
|
||||
projectCode,
|
||||
path,
|
||||
commitSha,
|
||||
readOnly,
|
||||
workspaceSha,
|
||||
onClose,
|
||||
onCommitted,
|
||||
}: {
|
||||
projectCode: string;
|
||||
path: string | null;
|
||||
commitSha?: string;
|
||||
readOnly: boolean;
|
||||
workspaceSha?: string;
|
||||
onClose: () => void;
|
||||
onCommitted: (sha: string) => void;
|
||||
}) {
|
||||
const { message } = App.useApp();
|
||||
const [file, setFile] = useState<FileView | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [draft, setDraft] = useState('');
|
||||
const [commitMsg, setCommitMsg] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [conflict, setConflict] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setFile(null);
|
||||
setError('');
|
||||
setEditing(false);
|
||||
setConflict(false);
|
||||
if (!path) return;
|
||||
api
|
||||
.getFile(projectCode, path, commitSha)
|
||||
.then((f) => { setFile(f); setDraft(f.content); })
|
||||
.catch((e) => setError(errorText(e)));
|
||||
}, [projectCode, path, commitSha]);
|
||||
|
||||
const ext = path?.split('.').pop()?.toLowerCase() ?? '';
|
||||
const imgSrc = useMemo(
|
||||
() => (file && file.encoding === 'base64' && imageMime[ext] ? `data:${imageMime[ext]};base64,${file.content}` : null),
|
||||
[file, ext],
|
||||
);
|
||||
|
||||
const save = async () => {
|
||||
if (!file || !path) return;
|
||||
if (!commitMsg.trim()) return message.warning('请填写提交说明');
|
||||
if (utf8Bytes(draft) > MiB) return message.error('在线文本不能超过 1 MiB');
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await api.createCommit(projectCode, {
|
||||
expectedCommitSha: workspaceSha || file.commitSha,
|
||||
message: commitMsg.trim(),
|
||||
changes: [{ action: 'UPDATE_FILE', path, content: draft }],
|
||||
});
|
||||
message.success(`已提交 ${shortSha(res.commitSha)}`);
|
||||
setEditing(false);
|
||||
setCommitMsg('');
|
||||
onCommitted(res.commitSha);
|
||||
} catch (e) {
|
||||
if (e instanceof AdminApiError && e.status === 409) setConflict(true);
|
||||
message.error(errorText(e));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const download = () => path && api.downloadFile(projectCode, path, commitSha).catch((e) => message.error(errorText(e)));
|
||||
const canEdit = !readOnly && file?.encoding === 'utf-8' && file.editable;
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
open={!!path}
|
||||
onClose={onClose}
|
||||
width="min(1000px, 100vw)"
|
||||
title={<span className="mono">{path}</span>}
|
||||
extra={
|
||||
<Space>
|
||||
<Button icon={<DownloadOutlined />} onClick={download}>下载</Button>
|
||||
{canEdit && !editing && <Button type="primary" icon={<EditOutlined />} onClick={() => setEditing(true)}>编辑</Button>}
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
{error && <Alert type="error" message={error} showIcon />}
|
||||
{!file && !error && <Spin />}
|
||||
{file && (
|
||||
<>
|
||||
<Typography.Paragraph type="secondary">
|
||||
版本 <span className="mono">{shortSha(file.commitSha)}</span> · {formatSize(file.size)} · {file.encoding}
|
||||
{!file.editable && file.encoding === 'utf-8' && ' · 不可在线编辑'}
|
||||
</Typography.Paragraph>
|
||||
{conflict && (
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
style={{ marginBottom: 12 }}
|
||||
message="工作区版本已变化,您的修改仍保留在编辑框中。请复制内容后关闭并刷新目录,与最新版本比对后再提交。"
|
||||
/>
|
||||
)}
|
||||
{editing ? (
|
||||
<Space direction="vertical" style={{ width: '100%' }} className="file-editor">
|
||||
<Input.TextArea value={draft} onChange={(e) => setDraft(e.target.value)} autoSize={{ minRows: 20, maxRows: 40 }} spellCheck={false} />
|
||||
<Input placeholder="提交说明(必填)" value={commitMsg} maxLength={1000} onChange={(e) => setCommitMsg(e.target.value)} />
|
||||
<Space>
|
||||
<Button type="primary" icon={<SaveOutlined />} loading={saving} onClick={save}>提交</Button>
|
||||
<Button onClick={() => { setEditing(false); setDraft(file.content); setConflict(false); }}>取消</Button>
|
||||
</Space>
|
||||
</Space>
|
||||
) : file.encoding === 'utf-8' ? (
|
||||
<pre className="file-preview">{file.content}</pre>
|
||||
) : imgSrc ? (
|
||||
<Image src={imgSrc} style={{ maxWidth: '100%' }} />
|
||||
) : (
|
||||
<Alert type="info" showIcon message="二进制文件,无法在线预览,请下载查看" />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Alert, Button, Checkbox, Space, Typography } from 'antd';
|
||||
import { CloseOutlined, FolderOpenOutlined } from '@ant-design/icons';
|
||||
import type { SelectedFile } from '@/api/types';
|
||||
import { formatSize, MiB } from '@/utils/format';
|
||||
import { pickFiles, toSelected, validatePath } from './pickFiles';
|
||||
|
||||
export interface UrdfSelection {
|
||||
selected: SelectedFile[];
|
||||
problems: string[];
|
||||
}
|
||||
|
||||
/** 校验 URDF 清单:有且仅有一个 .urdf,单文件 ≤ 50 MiB、总计 ≤ 200 MiB、最多 500 个 */
|
||||
export function checkUrdf(selected: SelectedFile[]): string[] {
|
||||
if (!selected.length) return [];
|
||||
const total = selected.reduce((s, f) => s + f.file.size, 0);
|
||||
const urdfCount = selected.filter((f) => f.relativePath.toLowerCase().endsWith('.urdf')).length;
|
||||
const paths = new Set(selected.map((f) => f.relativePath));
|
||||
return [
|
||||
urdfCount !== 1 && `目录中必须有且仅有一个 .urdf 文件(当前 ${urdfCount} 个)`,
|
||||
selected.length > 500 && '最多 500 个文件',
|
||||
total > 200 * MiB && `总大小 ${formatSize(total)} 超过 200 MiB`,
|
||||
selected.some((f) => f.file.size > 50 * MiB) && '存在超过 50 MiB 的文件',
|
||||
paths.size !== selected.length && '存在重复路径',
|
||||
selected.map((f) => validatePath(f.relativePath)).find(Boolean),
|
||||
].filter(Boolean) as string[];
|
||||
}
|
||||
|
||||
/** URDF 目录选择:生成相对路径清单并展示校验结果 */
|
||||
export default function UrdfDirPicker({
|
||||
onChange,
|
||||
disabled,
|
||||
}: {
|
||||
onChange: (v: UrdfSelection) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const [raw, setRaw] = useState<File[]>([]);
|
||||
const [keepRoot, setKeepRoot] = useState(false);
|
||||
|
||||
const selected = useMemo(() => toSelected(raw, keepRoot), [raw, keepRoot]);
|
||||
const problems = useMemo(() => checkUrdf(selected), [selected]);
|
||||
const total = selected.reduce((s, f) => s + f.file.size, 0);
|
||||
|
||||
const emit = (files: File[], keep: boolean) => {
|
||||
const sel = toSelected(files, keep);
|
||||
onChange({ selected: sel, problems: checkUrdf(sel) });
|
||||
};
|
||||
|
||||
const choose = async () => {
|
||||
const files = await pickFiles({ directory: true });
|
||||
if (files.length) {
|
||||
setRaw(files);
|
||||
emit(files, keepRoot);
|
||||
}
|
||||
};
|
||||
|
||||
const clear = () => {
|
||||
setRaw([]);
|
||||
emit([], keepRoot);
|
||||
};
|
||||
|
||||
return (
|
||||
<Space direction="vertical" style={{ width: '100%' }}>
|
||||
<Space wrap>
|
||||
<Button icon={<FolderOpenOutlined />} onClick={choose} disabled={disabled}>
|
||||
{raw.length ? '重新选择目录' : '选择 URDF 目录'}
|
||||
</Button>
|
||||
{raw.length > 0 && (
|
||||
<Button type="text" icon={<CloseOutlined />} onClick={clear} disabled={disabled}>清除</Button>
|
||||
)}
|
||||
</Space>
|
||||
{raw.length > 0 && (
|
||||
<>
|
||||
<Space wrap>
|
||||
<Checkbox
|
||||
checked={keepRoot}
|
||||
disabled={disabled}
|
||||
onChange={(e) => {
|
||||
setKeepRoot(e.target.checked);
|
||||
emit(raw, e.target.checked);
|
||||
}}
|
||||
>
|
||||
保留所选文件夹名称
|
||||
</Checkbox>
|
||||
<Typography.Text type="secondary">{selected.length} 个文件 · {formatSize(total)}</Typography.Text>
|
||||
</Space>
|
||||
<div className="file-list">
|
||||
{selected.map((f) => (
|
||||
<div key={f.relativePath} className="file-list-row">
|
||||
<span className={f.relativePath.toLowerCase().endsWith('.urdf') ? 'file-list-main' : undefined}>{f.relativePath}</span>
|
||||
<span className="file-list-size">{formatSize(f.file.size)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{problems.map((p) => <Alert key={p} type="error" showIcon message={p} />)}
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { useState } from 'react';
|
||||
import { Alert, App, Button, Descriptions, Popconfirm, Progress, Space } from 'antd';
|
||||
import { DeleteOutlined } from '@ant-design/icons';
|
||||
import * as api from '@/api';
|
||||
import type { ProjectView } from '@/api/types';
|
||||
import { errorText } from '@/utils/format';
|
||||
import UrdfDirPicker, { type UrdfSelection } from './UrdfDirPicker';
|
||||
|
||||
export default function UrdfPanel({ project, onChanged }: { project: ProjectView; onChanged: () => void }) {
|
||||
const { message } = App.useApp();
|
||||
const [selection, setSelection] = useState<UrdfSelection>({ selected: [], problems: [] });
|
||||
const [pickerKey, setPickerKey] = useState(0);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [progress, setProgress] = useState<{ done: number; total: number } | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const upload = async () => {
|
||||
setUploading(true);
|
||||
setError('');
|
||||
setProgress({ done: 0, total: selection.selected.length });
|
||||
try {
|
||||
await api.uploadUrdf(project.projectCode, selection.selected, (done, total) => setProgress({ done, total }));
|
||||
message.success('URDF 已绑定');
|
||||
setSelection({ selected: [], problems: [] });
|
||||
setPickerKey((k) => k + 1);
|
||||
setProgress(null);
|
||||
onChanged();
|
||||
} catch (e) {
|
||||
setError(errorText(e) + '。未确认绑定,可重新选择目录发起新批次。');
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async () => {
|
||||
try {
|
||||
await api.removeUrdf(project.projectCode);
|
||||
message.success('已移除 URDF 绑定');
|
||||
onChanged();
|
||||
} catch (e) {
|
||||
message.error(errorText(e));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Space direction="vertical" style={{ width: '100%' }} size="large">
|
||||
<Descriptions column={1} bordered size="small">
|
||||
<Descriptions.Item label="URDF 主文件">
|
||||
{project.urdfMainUrl ? <a href={project.urdfMainUrl} target="_blank" rel="noreferrer">{project.urdfMainUrl}</a> : '未绑定'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="资源基地址">{project.urdfBaseUrl ?? '—'}</Descriptions.Item>
|
||||
</Descriptions>
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
message="URDF 为独立资源目录上传,不产生 Git 提交;绑定或清除后直接更新项目展示资源。重新上传会替换当前绑定。"
|
||||
/>
|
||||
{project.urdfMainUrl && (
|
||||
<Popconfirm title="确定移除 URDF 绑定?(不会删除已上传对象)" onConfirm={remove}>
|
||||
<Button danger icon={<DeleteOutlined />}>移除绑定</Button>
|
||||
</Popconfirm>
|
||||
)}
|
||||
<UrdfDirPicker key={pickerKey} onChange={setSelection} disabled={uploading} />
|
||||
{progress && (
|
||||
<Progress
|
||||
percent={Math.round((progress.done / Math.max(progress.total, 1)) * 100)}
|
||||
format={() => `${progress.done}/${progress.total}`}
|
||||
/>
|
||||
)}
|
||||
{error && <Alert type="error" showIcon message={error} />}
|
||||
{selection.selected.length > 0 && (
|
||||
<Button type="primary" loading={uploading} disabled={selection.problems.length > 0} onClick={upload}>
|
||||
上传并绑定
|
||||
</Button>
|
||||
)}
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { SelectedFile } from '@/api/types';
|
||||
|
||||
/** 打开系统文件/文件夹选择框 */
|
||||
export function pickFiles(opts: { directory?: boolean; multiple?: boolean; accept?: string }): Promise<File[]> {
|
||||
return new Promise((resolve) => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.multiple = opts.multiple ?? true;
|
||||
if (opts.accept) input.accept = opts.accept;
|
||||
if (opts.directory) input.setAttribute('webkitdirectory', '');
|
||||
input.onchange = () => resolve(Array.from(input.files ?? []));
|
||||
input.click();
|
||||
});
|
||||
}
|
||||
|
||||
/** 根据 webkitRelativePath 生成相对路径;keepRoot=false 时去掉所选根目录名称 */
|
||||
export function toSelected(files: File[], keepRoot = true): SelectedFile[] {
|
||||
return files.map((file) => {
|
||||
const rel = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;
|
||||
const parts = rel.split('/');
|
||||
const relativePath = !keepRoot && parts.length > 1 ? parts.slice(1).join('/') : rel;
|
||||
return { file, relativePath };
|
||||
});
|
||||
}
|
||||
|
||||
/** 前端路径规则检查,返回错误信息或 null */
|
||||
export function validatePath(path: string): string | null {
|
||||
if (!path) return '路径不能为空';
|
||||
if (path.length > 1024) return '路径不能超过 1024 字符';
|
||||
if (path.includes('\\')) return '路径不能包含反斜杠 \\';
|
||||
if (path.includes(':')) return '路径不能包含冒号';
|
||||
// eslint-disable-next-line no-control-regex
|
||||
if (/[\x00-\x1f\x7f]/.test(path)) return '路径不能包含控制字符';
|
||||
if (path.startsWith('/') || path.endsWith('/')) return '路径不能以 / 开头或结尾';
|
||||
for (const seg of path.split('/')) {
|
||||
if (!seg) return '路径不能包含空路径段';
|
||||
if (seg === '.' || seg === '..') return '路径不能包含 . 或 ..';
|
||||
if (seg === '.git') return '路径不能包含 .git';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function joinPath(dir: string, name: string): string {
|
||||
return dir ? `${dir}/${name}` : name;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
interface EnvironmentConfig {
|
||||
apiBase: string;
|
||||
appEnvironment: string;
|
||||
}
|
||||
|
||||
/** 部署后按当前网站域名选择接口,避免 dev 和线上使用错误的构建配置。 */
|
||||
export function resolveEnvironment(
|
||||
hostname: string,
|
||||
fallbackApiBase = '/admin-api',
|
||||
fallbackEnvironment = 'development',
|
||||
): EnvironmentConfig {
|
||||
const host = hostname.toLowerCase().replace(/\.$/, '');
|
||||
if (host === 'dev-vibemake-admin.robotquan.com') {
|
||||
return {
|
||||
apiBase: 'https://dev-vibemake-api.robotquan.com/admin-api',
|
||||
appEnvironment: 'test',
|
||||
};
|
||||
}
|
||||
if (host === 'vibemake-admin.robotquan.com') {
|
||||
return {
|
||||
apiBase: 'https://vibemake-api.robotquan.com/admin-api',
|
||||
appEnvironment: 'production',
|
||||
};
|
||||
}
|
||||
if (host === 'localhost' || host.endsWith('.localhost') || host === '127.0.0.1' || host === '[::1]') {
|
||||
return { apiBase: '/admin-api', appEnvironment: fallbackEnvironment };
|
||||
}
|
||||
return {
|
||||
apiBase: fallbackApiBase || '/admin-api',
|
||||
appEnvironment: fallbackEnvironment || 'development',
|
||||
};
|
||||
}
|
||||
|
||||
export const environment = resolveEnvironment(
|
||||
window.location.hostname,
|
||||
import.meta.env.VITE_API_BASE,
|
||||
import.meta.env.VITE_APP_ENV,
|
||||
);
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
html, body, #root { height: 100%; margin: 0; }
|
||||
body {
|
||||
background: #f4f5fa;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
font-feature-settings: 'cv11', 'ss01';
|
||||
}
|
||||
|
||||
.mono { font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; }
|
||||
|
||||
/* 卡片:去掉生硬边框,换成柔和阴影 */
|
||||
.vm-content .ant-card {
|
||||
border: 1px solid #eceef5;
|
||||
box-shadow: 0 1px 2px rgba(16, 24, 40, 0.03), 0 4px 16px rgba(16, 24, 40, 0.04);
|
||||
}
|
||||
.vm-content .ant-card + .ant-card, .page-card + .page-card { margin-top: 20px; }
|
||||
.vm-content .ant-card-head { border-bottom-color: #f1f2f7; }
|
||||
.vm-content .ant-card-head-title { font-weight: 600; }
|
||||
.vm-content .ant-card-head-title a { color: #9ca3af; font-weight: 500; }
|
||||
.vm-content .ant-card-head-title a:hover { color: #4f46e5; }
|
||||
|
||||
/* 筛选栏 */
|
||||
.vm-content .ant-form-inline {
|
||||
padding: 16px;
|
||||
background: #f8f9fc;
|
||||
border: 1px solid #f0f1f6;
|
||||
border-radius: 12px;
|
||||
}
|
||||
.vm-content .ant-form-inline .ant-form-item { margin-inline-end: 12px; }
|
||||
|
||||
/* 表格 */
|
||||
.vm-content .ant-table-thead > tr > th { font-weight: 500; font-size: 13px; }
|
||||
.vm-content .ant-table-wrapper .ant-table { border-radius: 12px; }
|
||||
.vm-content .ant-table-tbody > tr > td { border-bottom-color: #f3f4f8; }
|
||||
|
||||
.vm-content .ant-tag { font-weight: 500; border: none; padding: 1px 8px; }
|
||||
.vm-content .ant-descriptions-item-label { color: #6b7280; }
|
||||
|
||||
/* 文件编辑与预览 */
|
||||
.file-editor textarea { font-family: 'JetBrains Mono', ui-monospace, Menlo, monospace; font-size: 13px; line-height: 1.6; }
|
||||
pre.file-preview {
|
||||
background: #0f1124;
|
||||
color: #e6e8ff;
|
||||
border-radius: 12px;
|
||||
padding: 16px 18px;
|
||||
max-height: 64vh;
|
||||
overflow: auto;
|
||||
font-family: 'JetBrains Mono', ui-monospace, Menlo, monospace;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
margin: 0;
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
/* 滚动条 */
|
||||
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||
::-webkit-scrollbar-thumb { background: #d4d7e3; border-radius: 10px; border: 2px solid transparent; background-clip: content-box; }
|
||||
::-webkit-scrollbar-thumb:hover { background-color: #b8bcd0; }
|
||||
|
||||
.nowrap { white-space: nowrap; }
|
||||
|
||||
/* 项目单元格 */
|
||||
.pt-cell { display: flex; align-items: center; gap: 12px; min-width: 0; }
|
||||
.pt-cover { width: 56px !important; height: 42px !important; border-radius: 8px; object-fit: cover; flex-shrink: 0; }
|
||||
.pt-cover-empty {
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
color: #fff; font-weight: 700; font-size: 16px;
|
||||
box-shadow: inset 0 0 0 1px rgba(255,255,255,.15);
|
||||
}
|
||||
.pt-meta { display: flex; flex-direction: column; min-width: 0; line-height: 1.4; }
|
||||
.pt-name { font-weight: 600; color: #111827; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.pt-name:hover { color: #4f46e5; }
|
||||
.pt-code { font-size: 12px !important; white-space: nowrap; }
|
||||
|
||||
/* 项目详情头部 */
|
||||
.pd-hero { display: flex; gap: 24px; align-items: flex-start; margin-bottom: 20px; }
|
||||
.pd-cover { width: 168px !important; height: 120px !important; border-radius: 14px; object-fit: cover; flex-shrink: 0; }
|
||||
.pd-cover-empty { display: flex; align-items: center; justify-content: center; color: #fff; font-size: 44px; font-weight: 700; }
|
||||
.pd-hero-main { flex: 1; min-width: 0; }
|
||||
.pd-title-row { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin-bottom: 8px; }
|
||||
.pd-title { font-size: 22px; font-weight: 700; margin: 0 8px 0 0; color: #0b0d1a; letter-spacing: -0.01em; }
|
||||
.pd-desc { color: #4b5563; margin-bottom: 12px !important; max-width: 820px; }
|
||||
.pd-meta { display: flex; flex-wrap: wrap; gap: 8px 28px; color: #111827; font-size: 13px; }
|
||||
.pd-meta label { color: #9ca3af; margin-right: 8px; }
|
||||
.pd-stats { display: flex; gap: 12px; flex-shrink: 0; }
|
||||
.pd-stats > div {
|
||||
min-width: 84px; padding: 14px 16px; border-radius: 12px;
|
||||
background: #f8f9fc; border: 1px solid #f0f1f6; text-align: center;
|
||||
}
|
||||
.pd-stats b { display: block; font-size: 22px; font-weight: 700; color: #111827; line-height: 1.2; }
|
||||
.pd-stats span { font-size: 12px; color: #9ca3af; }
|
||||
.pd-info .ant-descriptions-view { border-radius: 12px; }
|
||||
@media (max-width: 900px) {
|
||||
.pd-hero { flex-direction: column; }
|
||||
}
|
||||
|
||||
/* 文件清单(上传预览) */
|
||||
.file-list { max-height: 260px; overflow: auto; border: 1px solid #eceef5; border-radius: 10px; padding: 8px 12px; background: #fafbfd; }
|
||||
.file-list-row { display: flex; justify-content: space-between; gap: 16px; font-family: 'JetBrains Mono', ui-monospace, Menlo, monospace; font-size: 12px; line-height: 1.9; }
|
||||
.file-list-main { font-weight: 600; color: #4f46e5; }
|
||||
.file-list-size { color: #9ca3af; white-space: nowrap; }
|
||||
@@ -0,0 +1,24 @@
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import { App as AntApp, ConfigProvider } from 'antd';
|
||||
import zhCN from 'antd/locale/zh_CN';
|
||||
import dayjs from 'dayjs';
|
||||
import 'dayjs/locale/zh-cn';
|
||||
import App from './App';
|
||||
import { AuthProvider } from './auth';
|
||||
import './index.css';
|
||||
import { theme } from './theme';
|
||||
|
||||
dayjs.locale('zh-cn');
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<ConfigProvider locale={zhCN} theme={theme}>
|
||||
<AntApp>
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<App />
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
</AntApp>
|
||||
</ConfigProvider>
|
||||
);
|
||||
@@ -0,0 +1,78 @@
|
||||
import { useState } from 'react';
|
||||
import { App, Button, Card, Descriptions, Form, Input } from 'antd';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import * as api from '@/api';
|
||||
import { useAuth } from '@/auth';
|
||||
import { AdminApiError } from '@/api/request';
|
||||
import { errorText, utf8Bytes } from '@/utils/format';
|
||||
|
||||
export default function AccountPage() {
|
||||
const { admin, clear } = useAuth();
|
||||
const { message } = App.useApp();
|
||||
const navigate = useNavigate();
|
||||
const [form] = Form.useForm();
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const onFinish = async (v: { oldPassword: string; newPassword: string }) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await api.changePassword(v.oldPassword, v.newPassword);
|
||||
message.success('密码已修改,请重新登录');
|
||||
clear();
|
||||
navigate('/login', { replace: true });
|
||||
} catch (e) {
|
||||
if (e instanceof AdminApiError && e.code === 'PASSWORD_INVALID') {
|
||||
form.setFields([{ name: 'oldPassword', errors: ['原密码不正确'] }]);
|
||||
} else {
|
||||
message.error(errorText(e));
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card title="当前账号" className="page-card">
|
||||
<Descriptions column={1}>
|
||||
<Descriptions.Item label="昵称">{admin?.nickname}</Descriptions.Item>
|
||||
<Descriptions.Item label="邮箱">{admin?.email}</Descriptions.Item>
|
||||
<Descriptions.Item label="用户编码"><span className="mono">{admin?.userCode}</span></Descriptions.Item>
|
||||
</Descriptions>
|
||||
</Card>
|
||||
<Card title="修改密码" className="page-card">
|
||||
<Form form={form} layout="vertical" style={{ maxWidth: 420 }} onFinish={onFinish}>
|
||||
<Form.Item name="oldPassword" label="原密码" rules={[{ required: true, whitespace: true }]}>
|
||||
<Input.Password autoComplete="current-password" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="newPassword"
|
||||
label="新密码"
|
||||
extra="至少 12 个字符,UTF-8 不超过 72 字节;修改后所有会话失效"
|
||||
rules={[
|
||||
{ required: true, whitespace: true },
|
||||
{ min: 12, message: '新密码至少 12 个字符' },
|
||||
{ validator: (_, v) => (v && utf8Bytes(v) > 72 ? Promise.reject('新密码不能超过 72 字节') : Promise.resolve()) },
|
||||
]}
|
||||
>
|
||||
<Input.Password autoComplete="new-password" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="confirm"
|
||||
label="确认新密码"
|
||||
dependencies={['newPassword']}
|
||||
rules={[
|
||||
{ required: true },
|
||||
({ getFieldValue }) => ({
|
||||
validator: (_, v) => (!v || v === getFieldValue('newPassword') ? Promise.resolve() : Promise.reject('两次输入不一致')),
|
||||
}),
|
||||
]}
|
||||
>
|
||||
<Input.Password autoComplete="new-password" />
|
||||
</Form.Item>
|
||||
<Button type="primary" htmlType="submit" loading={loading}>保存</Button>
|
||||
</Form>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Card, Descriptions, Form, Input, Progress, Space, Tag, Typography } from 'antd';
|
||||
import { CheckCircleFilled, GithubOutlined } from '@ant-design/icons';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import * as api from '@/api';
|
||||
import type { ImportPreview, ImportUrdf, SelectedFile, TypeView } from '@/api/types';
|
||||
import { AdminApiError } from '@/api/request';
|
||||
import ProjectFields from '@/components/ProjectFields';
|
||||
import OwnerSelect from '@/components/OwnerSelect';
|
||||
import UrdfDirPicker, { type UrdfSelection } from '@/components/project/UrdfDirPicker';
|
||||
import { errorText } from '@/utils/format';
|
||||
|
||||
const GITHUB_RE = /^https:\/\/github\.com\/[A-Za-z0-9-]+\/[A-Za-z0-9._-]+?(\.git)?\/?$/;
|
||||
|
||||
/** 已上传的 URDF 批次,与仓库来源和文件清单绑定 */
|
||||
interface UploadedBatch extends ImportUrdf {
|
||||
repositoryUrl: string;
|
||||
fingerprint: string;
|
||||
}
|
||||
|
||||
const fingerprint = (selected: SelectedFile[]) =>
|
||||
selected.map((f) => `${f.relativePath}:${f.file.size}:${f.file.lastModified}`).sort().join('|');
|
||||
|
||||
type Stage = 'idle' | 'uploading' | 'creating';
|
||||
|
||||
interface FormValues {
|
||||
name: string;
|
||||
description?: string;
|
||||
projectType: string;
|
||||
coverUrl?: string;
|
||||
ownerUserCode?: string;
|
||||
}
|
||||
|
||||
export default function ImportCreatePage() {
|
||||
const navigate = useNavigate();
|
||||
const { message } = App.useApp();
|
||||
const [urlForm] = Form.useForm();
|
||||
const [form] = Form.useForm<FormValues>();
|
||||
const [types, setTypes] = useState<TypeView[]>([]);
|
||||
const [preview, setPreview] = useState<ImportPreview | null>(null);
|
||||
const [checking, setChecking] = useState(false);
|
||||
const [stage, setStage] = useState<Stage>('idle');
|
||||
const [progress, setProgress] = useState<{ done: number; total: number } | null>(null);
|
||||
const [duplicate, setDuplicate] = useState<string | null>(null);
|
||||
const [duplicateSource, setDuplicateSource] = useState(false);
|
||||
const [creationUncertain, setCreationUncertain] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [urdf, setUrdf] = useState<UrdfSelection>({ selected: [], problems: [] });
|
||||
const [pickerKey, setPickerKey] = useState(0);
|
||||
const batchRef = useRef<UploadedBatch | null>(null);
|
||||
const [batchReady, setBatchReady] = useState(false);
|
||||
const createLock = useRef(false);
|
||||
const previewSourceRef = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
api.listProjectTypes().then(setTypes).catch(() => {});
|
||||
}, []);
|
||||
|
||||
const resetBatch = () => {
|
||||
batchRef.current = null;
|
||||
setBatchReady(false);
|
||||
};
|
||||
|
||||
const doPreview = async ({ repositoryUrl }: { repositoryUrl: string }) => {
|
||||
setChecking(true);
|
||||
setError('');
|
||||
setDuplicate(null);
|
||||
setPreview(null);
|
||||
try {
|
||||
const pv = await api.previewImport(repositoryUrl.trim());
|
||||
// 换了仓库来源,之前的 URDF 签名批次作废
|
||||
if (batchRef.current && batchRef.current.repositoryUrl !== pv.repositoryUrl) resetBatch();
|
||||
setPreview(pv);
|
||||
setDuplicateSource(false);
|
||||
setCreationUncertain(false);
|
||||
if (previewSourceRef.current !== pv.repositoryUrl) {
|
||||
form.setFieldsValue({ name: pv.name, description: pv.description, coverUrl: '' });
|
||||
}
|
||||
previewSourceRef.current = pv.repositoryUrl;
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
} finally {
|
||||
setChecking(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onUrdfChange = (v: UrdfSelection) => {
|
||||
setUrdf(v);
|
||||
if (batchRef.current && batchRef.current.fingerprint !== fingerprint(v.selected)) resetBatch();
|
||||
};
|
||||
|
||||
/** 已选 URDF 时确保本次来源和清单已完整上传;返回创建任务用的 urdf 字段 */
|
||||
const ensureUrdf = async (repositoryUrl: string): Promise<ImportUrdf | null> => {
|
||||
if (!urdf.selected.length) return null;
|
||||
const fp = fingerprint(urdf.selected);
|
||||
const cached = batchRef.current;
|
||||
if (cached && cached.repositoryUrl === repositoryUrl && cached.fingerprint === fp) {
|
||||
return { batchCode: cached.batchCode, files: cached.files };
|
||||
}
|
||||
setStage('uploading');
|
||||
setProgress({ done: 0, total: urdf.selected.length });
|
||||
const res = await api.uploadImportUrdf(repositoryUrl, urdf.selected, (done, total) => setProgress({ done, total }));
|
||||
batchRef.current = { ...res, repositoryUrl, fingerprint: fp };
|
||||
setBatchReady(true);
|
||||
return res;
|
||||
};
|
||||
|
||||
const create = async (v: FormValues) => {
|
||||
if (!preview || preview.existingProjectCode || duplicateSource || creationUncertain || createLock.current) return;
|
||||
if (urdf.problems.length) {
|
||||
setError('URDF 目录不符合要求,请重新选择或清除后再创建');
|
||||
return;
|
||||
}
|
||||
createLock.current = true;
|
||||
setStage(urdf.selected.length ? 'uploading' : 'creating');
|
||||
setError('');
|
||||
let urdfInput: ImportUrdf | null;
|
||||
try {
|
||||
urdfInput = await ensureUrdf(preview.repositoryUrl);
|
||||
} catch (e) {
|
||||
// 签名阶段也会校验来源,重复来源直接引导到已有项目
|
||||
if (e instanceof AdminApiError && e.code === 'DUPLICATE_SOURCE') {
|
||||
setDuplicateSource(true);
|
||||
setDuplicate((e.details as { projectCode?: string } | null)?.projectCode ?? null);
|
||||
setError(errorText(e));
|
||||
setStage('idle');
|
||||
createLock.current = false;
|
||||
return;
|
||||
}
|
||||
// 上传失败保留表单,不能静默去掉 URDF 后创建任务
|
||||
setError(`URDF 上传失败:${errorText(e)}。请检查后重新提交,或清除 URDF 后再创建。`);
|
||||
setStage('idle');
|
||||
createLock.current = false;
|
||||
return;
|
||||
}
|
||||
setStage('creating');
|
||||
try {
|
||||
const task = await api.createImport({
|
||||
repositoryUrl: preview.repositoryUrl,
|
||||
ownerUserCode: v.ownerUserCode,
|
||||
project: {
|
||||
name: v.name.trim(),
|
||||
description: v.description ?? '',
|
||||
projectType: v.projectType,
|
||||
coverUrl: v.coverUrl || null,
|
||||
},
|
||||
urdf: urdfInput,
|
||||
});
|
||||
message.success('迁移任务已受理');
|
||||
navigate(`/imports/${task.taskCode}`, { replace: true });
|
||||
} catch (e) {
|
||||
if (e instanceof AdminApiError && e.code === 'DUPLICATE_SOURCE') {
|
||||
setDuplicateSource(true);
|
||||
setDuplicate((e.details as { projectCode?: string } | null)?.projectCode ?? null);
|
||||
}
|
||||
// 批次文件缺失或与来源不匹配,下次提交重新上传;其他失败保留批次,避免覆盖重传
|
||||
if (e instanceof AdminApiError && e.code === 'URDF_FILE_MISSING') resetBatch();
|
||||
const uncertain = !(e instanceof AdminApiError) || e.code === 'REMOTE_RESULT_UNKNOWN' || e.status >= 500;
|
||||
setCreationUncertain(uncertain);
|
||||
setError(uncertain
|
||||
? `${errorText(e)}。创建结果待核对,请先到任务列表确认结果,再重新预检;不要重复创建。`
|
||||
: errorText(e));
|
||||
} finally {
|
||||
createLock.current = false;
|
||||
setStage('idle');
|
||||
setProgress(null);
|
||||
}
|
||||
};
|
||||
|
||||
const existing = preview?.existingProjectCode ?? duplicate;
|
||||
const busy = stage !== 'idle';
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card
|
||||
className="page-card"
|
||||
title={<Space><Link to="/imports">GitHub 迁移</Link>/<span><GithubOutlined /> 新建迁移</span></Space>}
|
||||
>
|
||||
<Typography.Paragraph type="secondary" style={{ marginTop: -4 }}>
|
||||
输入公开仓库地址并预检,补充项目信息,可同时上传封面和 URDF 模型。迁移完成后项目保持未发布,需要检查文件后手动发布。
|
||||
</Typography.Paragraph>
|
||||
<Form form={urlForm} layout="vertical" style={{ maxWidth: 720 }} onFinish={doPreview}>
|
||||
<Form.Item
|
||||
name="repositoryUrl"
|
||||
label="GitHub 仓库地址"
|
||||
extra="仅支持公开仓库根地址,例如 https://github.com/owner/repo"
|
||||
rules={[
|
||||
{ required: true, whitespace: true, message: '请输入仓库地址' },
|
||||
{ max: 2048 },
|
||||
{ pattern: GITHUB_RE, message: '请输入 https://github.com/owner/repo 格式的仓库根地址' },
|
||||
]}
|
||||
>
|
||||
<Input.Search
|
||||
placeholder="https://github.com/owner/repo"
|
||||
enterButton="预检"
|
||||
size="large"
|
||||
loading={checking}
|
||||
disabled={busy || checking}
|
||||
onSearch={() => urlForm.submit()}
|
||||
onChange={() => {
|
||||
setPreview(null);
|
||||
setDuplicate(null);
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
|
||||
{!preview && error && <Alert type="error" showIcon message={error} style={{ maxWidth: 720 }} />}
|
||||
{existing && (
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
style={{ maxWidth: 720, marginTop: 8 }}
|
||||
message="该仓库已存在对应项目,不要重复创建"
|
||||
action={<Button size="small" onClick={() => navigate(`/projects/${existing}`)}>查看已有项目</Button>}
|
||||
/>
|
||||
)}
|
||||
|
||||
{preview && !preview.existingProjectCode && (
|
||||
<Descriptions bordered size="small" column={{ xs: 1, md: 3 }} style={{ marginTop: 8 }}>
|
||||
<Descriptions.Item label="规范地址">
|
||||
<a href={preview.repositoryUrl} target="_blank" rel="noreferrer">{preview.repositoryUrl}</a>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="默认分支"><Tag>{preview.defaultBranch}</Tag></Descriptions.Item>
|
||||
<Descriptions.Item label="许可证">{preview.license ?? '未识别'}</Descriptions.Item>
|
||||
</Descriptions>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Form
|
||||
form={form}
|
||||
layout="vertical"
|
||||
onFinish={create}
|
||||
disabled={busy || checking}
|
||||
style={{ display: preview && !preview.existingProjectCode ? undefined : 'none' }}
|
||||
>
|
||||
<Card className="page-card" title="项目信息">
|
||||
<div style={{ maxWidth: 720 }}>
|
||||
<ProjectFields types={types} />
|
||||
<Form.Item name="ownerUserCode" label="归属" extra="创建后不支持变更归属">
|
||||
<OwnerSelect />
|
||||
</Form.Item>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
className="page-card"
|
||||
title={<Space>URDF 模型<Tag>可选</Tag></Space>}
|
||||
extra={batchReady && <Space style={{ color: '#10b981' }}><CheckCircleFilled />已上传,创建时一并绑定</Space>}
|
||||
>
|
||||
<Typography.Paragraph type="secondary">
|
||||
选择包含一个 .urdf 及其 mesh、贴图等资源的目录。创建任务时自动上传并与项目绑定,无需等迁移完成;不会自动识别仓库里的 URDF。
|
||||
单文件 ≤ 50 MiB,总计 ≤ 200 MiB,最多 500 个文件。
|
||||
</Typography.Paragraph>
|
||||
<UrdfDirPicker key={pickerKey} onChange={onUrdfChange} disabled={busy} />
|
||||
</Card>
|
||||
|
||||
<Card className="page-card">
|
||||
<Space direction="vertical" style={{ width: '100%' }}>
|
||||
{error && (
|
||||
<Alert
|
||||
type="error"
|
||||
showIcon
|
||||
message={error}
|
||||
action={duplicate && <Button size="small" onClick={() => navigate(`/projects/${duplicate}`)}>查看已有项目</Button>}
|
||||
/>
|
||||
)}
|
||||
{stage === 'uploading' && progress && (
|
||||
<div>
|
||||
<Typography.Text>正在上传 URDF…</Typography.Text>
|
||||
<Progress
|
||||
percent={Math.round((progress.done / Math.max(progress.total, 1)) * 100)}
|
||||
format={() => `${progress.done}/${progress.total}`}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<Space wrap>
|
||||
<Button type="primary" size="large" htmlType="submit" loading={busy} disabled={busy || duplicateSource || creationUncertain}>
|
||||
{stage === 'uploading' ? '正在上传 URDF' : stage === 'creating' ? '正在创建任务' : '创建迁移任务'}
|
||||
</Button>
|
||||
{creationUncertain && <Button size="large" onClick={() => navigate('/imports')}>查看迁移任务</Button>}
|
||||
{urdf.selected.length > 0 && !busy && (
|
||||
<Button
|
||||
size="large"
|
||||
onClick={() => {
|
||||
setUrdf({ selected: [], problems: [] });
|
||||
resetBatch();
|
||||
setPickerKey((k) => k + 1);
|
||||
}}
|
||||
>
|
||||
不上传 URDF
|
||||
</Button>
|
||||
)}
|
||||
<Link to="/imports">取消</Link>
|
||||
</Space>
|
||||
</Space>
|
||||
</Card>
|
||||
</Form>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Card, Descriptions, List, Modal, Space, Spin, Steps, Typography } from 'antd';
|
||||
import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom';
|
||||
import * as api from '@/api';
|
||||
import type { TaskView } from '@/api/types';
|
||||
import { AdminApiError } from '@/api/request';
|
||||
import StatusTag from '@/components/StatusTag';
|
||||
import { errorText, formatDuration, formatTime, isAbort } from '@/utils/format';
|
||||
import { importPhaseLabel, importPhaseOrder, importStatusLabel } from '@/utils/labels';
|
||||
import { canRetryImportTask } from '@/utils/imports';
|
||||
|
||||
const sleep = (ms: number, signal: AbortSignal) =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
if (signal.aborted) return reject(new DOMException('Aborted', 'AbortError'));
|
||||
const t = setTimeout(() => { signal.removeEventListener('abort', onAbort); resolve(); }, ms);
|
||||
const onAbort = () => { clearTimeout(t); reject(new DOMException('Aborted', 'AbortError')); };
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
});
|
||||
|
||||
const isRunning = (t: TaskView | null) => !!t && (t.status === 'QUEUED' || t.status === 'RUNNING');
|
||||
|
||||
export default function ImportDetailPage() {
|
||||
const { taskCode = '' } = useParams();
|
||||
// 切换任务时重新建立状态,避免展示上一个任务或提交到错误任务。
|
||||
return <ImportTaskDetail key={taskCode} taskCode={taskCode} />;
|
||||
}
|
||||
|
||||
function ImportTaskDetail({ taskCode }: { taskCode: string }) {
|
||||
const navigate = useNavigate();
|
||||
const [searchParams] = useSearchParams();
|
||||
const { message } = App.useApp();
|
||||
const [task, setTask] = useState<TaskView | null>(null);
|
||||
const [pollError, setPollError] = useState('');
|
||||
const [pollRound, setPollRound] = useState(0);
|
||||
const [retrying, setRetrying] = useState(false);
|
||||
const [confirmRetry, setConfirmRetry] = useState(() => searchParams.get('retry') === '1');
|
||||
const [retryError, setRetryError] = useState('');
|
||||
const [needsQuery, setNeedsQuery] = useState(false);
|
||||
const ctrlRef = useRef<AbortController>();
|
||||
const retryLock = useRef(false);
|
||||
const mountedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
return () => { mountedRef.current = false; };
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const ctrl = new AbortController();
|
||||
ctrlRef.current = ctrl;
|
||||
(async () => {
|
||||
try {
|
||||
for (;;) {
|
||||
const t = await api.getImport(taskCode, ctrl.signal);
|
||||
if (ctrl.signal.aborted) return;
|
||||
setTask(t);
|
||||
setPollError('');
|
||||
setNeedsQuery(false);
|
||||
if (!isRunning(t)) return;
|
||||
await sleep(3000, ctrl.signal);
|
||||
}
|
||||
} catch (e) {
|
||||
// 查询失败不等于迁移失败
|
||||
if (!ctrl.signal.aborted && !isAbort(e)) setPollError(`获取状态失败:${errorText(e)}`);
|
||||
}
|
||||
})();
|
||||
return () => ctrl.abort();
|
||||
}, [taskCode, pollRound]);
|
||||
|
||||
const retry = async () => {
|
||||
// 保留失败/待核对任务的手动入口;等待当前请求或查询确认期间避免重复写入。
|
||||
if (retryLock.current || !task || !canRetryImportTask(task) || needsQuery || pollError) return;
|
||||
retryLock.current = true;
|
||||
setRetrying(true);
|
||||
setNeedsQuery(true);
|
||||
setRetryError('');
|
||||
ctrlRef.current?.abort();
|
||||
try {
|
||||
const t = await api.retryImport(taskCode);
|
||||
if (!mountedRef.current) return;
|
||||
setTask(t);
|
||||
setConfirmRetry(false);
|
||||
message.success('重试迁移已受理,正在查询最新状态');
|
||||
} catch (e) {
|
||||
if (!mountedRef.current) return;
|
||||
setConfirmRetry(false);
|
||||
const text = errorText(e) || '请求已中断';
|
||||
setRetryError(
|
||||
e instanceof AdminApiError && e.status === 409
|
||||
? `${text}。已重新查询任务,请核对最新状态和重试说明。`
|
||||
: `${text}。正在重新查询任务确认结果,请勿重复提交。`,
|
||||
);
|
||||
} finally {
|
||||
retryLock.current = false;
|
||||
if (mountedRef.current) {
|
||||
setRetrying(false);
|
||||
// 受理后恢复串行轮询;失败(含 409)也只查询,不自动重发重试请求。
|
||||
setPollRound((r) => r + 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (!task) {
|
||||
return pollError ? (
|
||||
<Alert type="error" showIcon message={pollError} action={<Button onClick={() => setPollRound((r) => r + 1)}>重新查询</Button>} />
|
||||
) : (
|
||||
<Spin />
|
||||
);
|
||||
}
|
||||
|
||||
// 清理仅在后端返回 CLEANING 时展示,普通迁移不虚构已执行清理步骤。
|
||||
const phases = importPhaseOrder.filter((phase) => phase !== 'CLEANING' || task.phase === 'CLEANING');
|
||||
const phaseIdx = phases.indexOf(task.phase);
|
||||
const stepStatus = task.status === 'FAILED' ? 'error' : task.status === 'SUCCEEDED' ? 'finish' : task.status === 'REVIEW' ? 'error' : 'process';
|
||||
const needsAttention = task.status === 'FAILED' || task.status === 'REVIEW';
|
||||
const cleanupUnsafe = task.errorCode === 'CLEANUP_REPOSITORY_UNSAFE' || task.errorCode === 'CLEANUP_REPOSITORY_REPLACED';
|
||||
const retryExplanation = task.retryMessage || '服务端将核验当前仓库状态,并清理失败仓库或继续后续步骤;沿用原任务及项目,保留项目资料、封面和 URDF。';
|
||||
|
||||
return (
|
||||
<Card
|
||||
title={<Space><Link to="/imports">GitHub 迁移</Link>/<span className="mono">{task.taskCode}</span></Space>}
|
||||
extra={
|
||||
<Space>
|
||||
{isRunning(task) && <Spin size="small" />}
|
||||
<Button disabled={retrying || needsQuery} onClick={() => setPollRound((r) => r + 1)}>刷新状态</Button>
|
||||
<Button onClick={() => navigate(`/projects/${task.projectCode}`)}>查看项目</Button>
|
||||
{canRetryImportTask(task) && (
|
||||
<Button type="primary" loading={retrying} disabled={needsQuery || !!pollError} onClick={() => setConfirmRetry(true)}>
|
||||
重试迁移
|
||||
</Button>
|
||||
)}
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
{pollError && (
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
message={pollError}
|
||||
style={{ marginBottom: 16 }}
|
||||
action={<Button size="small" disabled={retrying} onClick={() => setPollRound((r) => r + 1)}>恢复查询</Button>}
|
||||
/>
|
||||
)}
|
||||
{retryError && <Alert type="error" showIcon message={retryError} style={{ marginBottom: 16 }} />}
|
||||
{task.status === 'SUCCEEDED' && (
|
||||
<Alert
|
||||
type="success"
|
||||
showIcon
|
||||
style={{ marginBottom: 16 }}
|
||||
message="迁移完成,项目仍为未发布状态,请检查文件后手动发布;迁移表单提交的封面和 URDF 已绑定,无需再次上传"
|
||||
action={<Button type="primary" size="small" onClick={() => navigate(`/projects/${task.projectCode}`)}>去检查发布</Button>}
|
||||
/>
|
||||
)}
|
||||
{needsAttention && (
|
||||
<Alert
|
||||
type={task.status === 'FAILED' ? 'error' : 'warning'}
|
||||
showIcon
|
||||
style={{ marginBottom: 16 }}
|
||||
message={`${importStatusLabel[task.status].text}${task.errorCode ? `:${task.errorCode}` : ''}`}
|
||||
description={
|
||||
<>
|
||||
{cleanupUnsafe && <div>残留仓库归属无法核实或身份已变化,后台未删除仓库,请联系维护人员处理。</div>}
|
||||
<div style={{ whiteSpace: 'pre-wrap' }}>{retryExplanation}</div>
|
||||
<div>可通过“重试迁移”重新请求处理,无需重复创建迁移任务。</div>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{task.phase === 'CLEANING' && isRunning(task) && (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
style={{ marginBottom: 16 }}
|
||||
message={importPhaseLabel.CLEANING}
|
||||
description="后台正在核验残留仓库归属并执行受保护的清理,完成后继续迁移。项目资料、封面及 URDF 会保留,请等待状态更新。"
|
||||
/>
|
||||
)}
|
||||
<Steps
|
||||
size="small"
|
||||
current={Math.max(phaseIdx, 0)}
|
||||
status={stepStatus}
|
||||
style={{ marginBottom: 24 }}
|
||||
items={phases.map((ph) => ({ title: importPhaseLabel[ph] }))}
|
||||
/>
|
||||
<Descriptions bordered size="small" column={{ xs: 1, md: 2 }}>
|
||||
<Descriptions.Item label="状态"><StatusTag map={importStatusLabel} value={task.status} /></Descriptions.Item>
|
||||
<Descriptions.Item label="阶段">{importPhaseLabel[task.phase] ?? task.phase}</Descriptions.Item>
|
||||
<Descriptions.Item label="项目"><Link className="mono" to={`/projects/${task.projectCode}`}>{task.projectCode}</Link></Descriptions.Item>
|
||||
<Descriptions.Item label="错误码">{task.errorCode ?? '—'}</Descriptions.Item>
|
||||
<Descriptions.Item label="重试操作">{canRetryImportTask(task) ? '可提交重试' : '—'}</Descriptions.Item>
|
||||
<Descriptions.Item label="重试说明"><span style={{ whiteSpace: 'pre-wrap' }}>{task.retryMessage ?? '—'}</span></Descriptions.Item>
|
||||
<Descriptions.Item label="创建时间">{formatTime(task.createdAt)}</Descriptions.Item>
|
||||
<Descriptions.Item label="开始时间">{formatTime(task.startedAt)}</Descriptions.Item>
|
||||
<Descriptions.Item label="结束时间">{formatTime(task.finishedAt)}</Descriptions.Item>
|
||||
<Descriptions.Item label="耗时">{formatDuration(task.startedAt, task.finishedAt)}</Descriptions.Item>
|
||||
</Descriptions>
|
||||
{task.warnings.length > 0 && (
|
||||
<List
|
||||
style={{ marginTop: 16 }}
|
||||
header="提醒"
|
||||
bordered
|
||||
size="small"
|
||||
dataSource={task.warnings}
|
||||
renderItem={(w) => <List.Item>{w}</List.Item>}
|
||||
/>
|
||||
)}
|
||||
<Modal
|
||||
title="重试迁移"
|
||||
open={confirmRetry && canRetryImportTask(task)}
|
||||
okText="确认重试"
|
||||
cancelText="取消"
|
||||
confirmLoading={retrying}
|
||||
okButtonProps={{ disabled: needsQuery || !!pollError || !canRetryImportTask(task) }}
|
||||
cancelButtonProps={{ disabled: retrying }}
|
||||
closable={!retrying}
|
||||
maskClosable={!retrying}
|
||||
keyboard={!retrying}
|
||||
onOk={retry}
|
||||
onCancel={() => { if (!retrying) setConfirmRetry(false); }}
|
||||
>
|
||||
<Typography.Paragraph style={{ whiteSpace: 'pre-wrap' }}>{retryExplanation}</Typography.Paragraph>
|
||||
<Typography.Paragraph type="secondary">
|
||||
使用原任务和项目继续处理,已提交的项目资料、封面及 URDF 会保留;迁移成功后仍需检查文件并手动发布。
|
||||
</Typography.Paragraph>
|
||||
</Modal>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Button, Card, Form, Input, Select, Space, Table } from 'antd';
|
||||
import { PlusOutlined } from '@ant-design/icons';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import * as api from '@/api';
|
||||
import type { ImportStatus, TaskView } from '@/api/types';
|
||||
import StatusTag from '@/components/StatusTag';
|
||||
import ImportTaskActions from '@/components/ImportTaskActions';
|
||||
import { formatDuration, formatTime } from '@/utils/format';
|
||||
import { importPhaseLabel, importStatusLabel, toOptions } from '@/utils/labels';
|
||||
import { clean, usePaged } from '@/utils/usePaged';
|
||||
|
||||
interface Q {
|
||||
status?: ImportStatus;
|
||||
projectCode?: string;
|
||||
}
|
||||
|
||||
export default function ImportListPage() {
|
||||
const navigate = useNavigate();
|
||||
const [form] = Form.useForm<Q>();
|
||||
const list = usePaged<TaskView, Q>((q) => api.listImports(q), {});
|
||||
|
||||
return (
|
||||
<Card
|
||||
title="迁移任务"
|
||||
extra={<Button type="primary" icon={<PlusOutlined />} onClick={() => navigate('/imports/new')}>新建迁移</Button>}
|
||||
>
|
||||
<Form form={form} layout="inline" onFinish={(v) => list.search(clean(v))} style={{ marginBottom: 16, rowGap: 8 }}>
|
||||
<Form.Item name="status"><Select placeholder="状态" allowClear style={{ width: 180 }} options={toOptions(importStatusLabel)} /></Form.Item>
|
||||
<Form.Item name="projectCode"><Input placeholder="项目编码" allowClear /></Form.Item>
|
||||
<Space>
|
||||
<Button type="primary" htmlType="submit">查询</Button>
|
||||
<Button onClick={() => { form.resetFields(); list.search({}); }}>重置</Button>
|
||||
<Button onClick={list.reload}>刷新</Button>
|
||||
</Space>
|
||||
</Form>
|
||||
<Table<TaskView>
|
||||
rowKey="taskCode"
|
||||
loading={list.loading}
|
||||
dataSource={list.data.items}
|
||||
pagination={list.pagination}
|
||||
scroll={{ x: 1450 }}
|
||||
columns={[
|
||||
{ title: '任务编码', dataIndex: 'taskCode', render: (v) => <Link className="mono" to={`/imports/${v}`}>{v}</Link> },
|
||||
{ title: '项目', dataIndex: 'projectCode', render: (v) => <Link className="mono" to={`/projects/${v}`}>{v}</Link> },
|
||||
{ title: '状态', dataIndex: 'status', render: (v) => <StatusTag map={importStatusLabel} value={v} /> },
|
||||
{ title: '阶段', dataIndex: 'phase', render: (v) => importPhaseLabel[v] ?? v },
|
||||
{ title: '错误码', dataIndex: 'errorCode', render: (v) => v ?? '—' },
|
||||
{ title: '重试说明', dataIndex: 'retryMessage', width: 260, render: (v) => v ?? '—' },
|
||||
{ title: '创建时间', dataIndex: 'createdAt', render: formatTime },
|
||||
{ title: '耗时', render: (_, t) => formatDuration(t.startedAt, t.finishedAt) },
|
||||
{
|
||||
title: '操作',
|
||||
fixed: 'right',
|
||||
width: 190,
|
||||
render: (_, t) => <ImportTaskActions task={t} />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
.login-page {
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.15fr) minmax(420px, 1fr);
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
/* ---------- 左侧品牌区 ---------- */
|
||||
.login-hero {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
background: radial-gradient(120% 90% at 0% 0%, #1b1d4a 0%, #0b0d1a 55%, #070814 100%);
|
||||
color: #e6e8ff;
|
||||
}
|
||||
.login-grid {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background-image:
|
||||
linear-gradient(rgba(255, 255, 255, 0.05) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(255, 255, 255, 0.05) 1px, transparent 1px);
|
||||
background-size: 44px 44px;
|
||||
mask-image: radial-gradient(ellipse 80% 70% at 30% 40%, #000 40%, transparent 100%);
|
||||
}
|
||||
.login-orb {
|
||||
position: absolute;
|
||||
border-radius: 50%;
|
||||
filter: blur(80px);
|
||||
opacity: 0.55;
|
||||
pointer-events: none;
|
||||
}
|
||||
.login-orb-a { width: 420px; height: 420px; background: #6366f1; top: -120px; right: -80px; }
|
||||
.login-orb-b { width: 360px; height: 360px; background: #06b6d4; bottom: -140px; left: 10%; opacity: 0.35; }
|
||||
|
||||
.login-hero-inner {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
height: 100%;
|
||||
min-height: 100vh;
|
||||
box-sizing: border-box;
|
||||
padding: 48px 64px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.login-hero-copy { margin-top: auto; max-width: 560px; }
|
||||
.login-eyebrow {
|
||||
font-size: 12px;
|
||||
letter-spacing: 0.24em;
|
||||
color: #a5b4fc;
|
||||
font-weight: 600;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
.login-hero-copy h1 {
|
||||
font-size: 44px;
|
||||
line-height: 1.22;
|
||||
font-weight: 700;
|
||||
margin: 0 0 18px;
|
||||
color: #fff;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
.login-gradient-text {
|
||||
background: linear-gradient(90deg, #a5b4fc 0%, #c4b5fd 45%, #67e8f9 100%);
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
color: transparent;
|
||||
}
|
||||
.login-hero-copy p { font-size: 16px; line-height: 1.7; color: rgba(226, 232, 255, 0.66); margin: 0; }
|
||||
|
||||
.login-features {
|
||||
margin: 44px 0 auto;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 14px;
|
||||
max-width: 600px;
|
||||
}
|
||||
.login-feature {
|
||||
display: flex;
|
||||
gap: 14px;
|
||||
padding: 16px 18px;
|
||||
border-radius: 14px;
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
backdrop-filter: blur(6px);
|
||||
}
|
||||
.login-feature-idx {
|
||||
font-family: 'JetBrains Mono', ui-monospace, monospace;
|
||||
font-size: 12px;
|
||||
color: #818cf8;
|
||||
padding-top: 2px;
|
||||
}
|
||||
.login-feature-title { font-weight: 600; color: #fff; margin-bottom: 4px; }
|
||||
.login-feature-desc { font-size: 13px; color: rgba(226, 232, 255, 0.55); line-height: 1.5; }
|
||||
.login-foot { font-size: 12px; color: rgba(226, 232, 255, 0.35); margin-top: 40px; }
|
||||
|
||||
/* ---------- 右侧表单 ---------- */
|
||||
.login-panel {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 48px 24px;
|
||||
background:
|
||||
radial-gradient(60% 50% at 100% 0%, rgba(99, 102, 241, 0.06), transparent 70%),
|
||||
#fff;
|
||||
}
|
||||
.login-form-wrap { width: 100%; max-width: 380px; }
|
||||
.login-form-wrap h2 { font-size: 28px; font-weight: 700; margin: 0 0 8px; color: #0b0d1a; letter-spacing: -0.01em; }
|
||||
.login-sub { color: #6b7280; margin: 0 0 32px; }
|
||||
.login-form-wrap .ant-form-item-label > label { font-weight: 500; color: #374151; }
|
||||
.login-form-wrap .ant-input-affix-wrapper { border-radius: 10px; padding-top: 9px; padding-bottom: 9px; }
|
||||
.login-icon { color: #9ca3af; margin-right: 4px; }
|
||||
.login-submit {
|
||||
height: 48px !important;
|
||||
border-radius: 10px !important;
|
||||
margin-top: 8px;
|
||||
font-weight: 600;
|
||||
background: linear-gradient(90deg, #4f46e5, #7c3aed) !important;
|
||||
border: none !important;
|
||||
}
|
||||
.login-submit:hover { filter: brightness(1.08); }
|
||||
.login-mobile-logo { display: none; margin-bottom: 32px; }
|
||||
|
||||
@media (max-width: 960px) {
|
||||
.login-page { grid-template-columns: minmax(0, 1fr); }
|
||||
.login-hero { display: none; }
|
||||
.login-mobile-logo { display: block; }
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { useState } from 'react';
|
||||
import { Alert, Button, Form, Input } from 'antd';
|
||||
import { ArrowRightOutlined, LockOutlined, MailOutlined } from '@ant-design/icons';
|
||||
import { Navigate, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { useAuth } from '@/auth';
|
||||
import { AdminApiError } from '@/api/request';
|
||||
import Logo from '@/components/Logo';
|
||||
import { errorText } from '@/utils/format';
|
||||
import './Login.css';
|
||||
|
||||
const features = [
|
||||
{ title: '项目治理', desc: '发布、撤回、下架,版本精确到 Commit' },
|
||||
{ title: '仓库文件', desc: '在线编辑、文件夹上传、历史快照浏览' },
|
||||
{ title: 'GitHub 迁移', desc: '一键预检迁移,阶段进度实时追踪' },
|
||||
{ title: 'URDF 资源', desc: '机器人模型目录直传 OSS 并绑定' },
|
||||
];
|
||||
|
||||
export default function LoginPage() {
|
||||
const { admin, signIn } = useAuth();
|
||||
const [params] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const redirect = params.get('redirect') || '/projects';
|
||||
|
||||
if (admin) return <Navigate to={redirect} replace />;
|
||||
|
||||
const onFinish = async (v: { email: string; password: string }) => {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
await signIn(v.email.trim(), v.password);
|
||||
navigate(redirect, { replace: true });
|
||||
} catch (e) {
|
||||
if (e instanceof AdminApiError && e.status === 401) setError('账号或密码错误');
|
||||
else if (e instanceof AdminApiError && e.status === 429) setError('登录失败次数过多,请 15 分钟后重试');
|
||||
else setError(errorText(e));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="login-page">
|
||||
<section className="login-hero">
|
||||
<div className="login-grid" />
|
||||
<div className="login-orb login-orb-a" />
|
||||
<div className="login-orb login-orb-b" />
|
||||
<div className="login-hero-inner">
|
||||
<Logo dark subtitle="Admin Console" />
|
||||
<div className="login-hero-copy">
|
||||
<div className="login-eyebrow">ROBOT MAKER COMMUNITY</div>
|
||||
<h1>
|
||||
让每一个机器人项目
|
||||
<br />
|
||||
<span className="login-gradient-text">被看见、被复用</span>
|
||||
</h1>
|
||||
<p>社区运营后台:用户、项目仓库、版本发布与 GitHub 迁移,一处管理。</p>
|
||||
</div>
|
||||
<div className="login-features">
|
||||
{features.map((f, i) => (
|
||||
<div className="login-feature" key={f.title}>
|
||||
<span className="login-feature-idx">0{i + 1}</span>
|
||||
<div>
|
||||
<div className="login-feature-title">{f.title}</div>
|
||||
<div className="login-feature-desc">{f.desc}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="login-foot">© {new Date().getFullYear()} VibeMake · RobotQuan</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="login-panel">
|
||||
<div className="login-form-wrap">
|
||||
<div className="login-mobile-logo"><Logo subtitle="Admin Console" /></div>
|
||||
<h2>欢迎回来</h2>
|
||||
<p className="login-sub">使用管理员账号登录后台</p>
|
||||
{error && <Alert type="error" showIcon message={error} style={{ marginBottom: 20, borderRadius: 10 }} />}
|
||||
<Form layout="vertical" size="large" onFinish={onFinish} requiredMark={false}>
|
||||
<Form.Item
|
||||
name="email"
|
||||
label="邮箱"
|
||||
rules={[{ required: true, type: 'email', message: '请输入合法邮箱' }, { max: 254 }]}
|
||||
>
|
||||
<Input prefix={<MailOutlined className="login-icon" />} placeholder="admin@example.com" autoComplete="username" />
|
||||
</Form.Item>
|
||||
<Form.Item name="password" label="密码" rules={[{ required: true, whitespace: true, message: '请输入密码' }]}>
|
||||
<Input.Password prefix={<LockOutlined className="login-icon" />} placeholder="请输入密码" autoComplete="current-password" />
|
||||
</Form.Item>
|
||||
<Button type="primary" htmlType="submit" block loading={loading} className="login-submit">
|
||||
登录 {!loading && <ArrowRightOutlined />}
|
||||
</Button>
|
||||
</Form>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { App, Button, Card, Form, Space } from 'antd';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import * as api from '@/api';
|
||||
import type { TypeView } from '@/api/types';
|
||||
import ProjectFields from '@/components/ProjectFields';
|
||||
import OwnerSelect from '@/components/OwnerSelect';
|
||||
import { errorText } from '@/utils/format';
|
||||
|
||||
export default function ProjectCreatePage() {
|
||||
const navigate = useNavigate();
|
||||
const { message } = App.useApp();
|
||||
const [form] = Form.useForm();
|
||||
const [types, setTypes] = useState<TypeView[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
api.listProjectTypes().then(setTypes).catch((e) => message.error(errorText(e)));
|
||||
}, [message]);
|
||||
|
||||
const onFinish = async (v: { name: string; description?: string; projectType: string; coverUrl?: string; ownerUserCode?: string }) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const p = await api.createProject(
|
||||
{ name: v.name.trim(), description: v.description ?? '', projectType: v.projectType, coverUrl: v.coverUrl || null },
|
||||
v.ownerUserCode,
|
||||
);
|
||||
message.success('项目已创建(未发布),可上传文件');
|
||||
navigate(`/projects/${p.projectCode}`, { replace: true });
|
||||
} catch (e) {
|
||||
message.error(errorText(e));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card title={<Space><a onClick={() => navigate('/projects')}>项目管理</a>/<span>新建项目</span></Space>}>
|
||||
<Form form={form} layout="vertical" style={{ maxWidth: 720 }} onFinish={onFinish}>
|
||||
<ProjectFields types={types} />
|
||||
<Form.Item name="ownerUserCode" label="归属" extra="创建后不支持变更归属">
|
||||
<OwnerSelect />
|
||||
</Form.Item>
|
||||
<Space>
|
||||
<Button type="primary" htmlType="submit" loading={loading}>创建</Button>
|
||||
<Button onClick={() => navigate(-1)}>取消</Button>
|
||||
</Space>
|
||||
</Form>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import {
|
||||
Alert,
|
||||
App,
|
||||
Button,
|
||||
Card,
|
||||
Descriptions,
|
||||
Form,
|
||||
Image,
|
||||
Input,
|
||||
Modal,
|
||||
Popconfirm,
|
||||
Space,
|
||||
Spin,
|
||||
Table,
|
||||
Tabs,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom';
|
||||
import * as api from '@/api';
|
||||
import type { ManagedProjectView, TaskView, TypeView } from '@/api/types';
|
||||
import { AdminApiError } from '@/api/request';
|
||||
import StatusTag from '@/components/StatusTag';
|
||||
import ImportTaskActions from '@/components/ImportTaskActions';
|
||||
import FileBrowser from '@/components/project/FileBrowser';
|
||||
import CommitHistory from '@/components/project/CommitHistory';
|
||||
import UrdfPanel from '@/components/project/UrdfPanel';
|
||||
import EditProjectModal from '@/components/project/EditProjectModal';
|
||||
import { coverGradient } from '@/components/ProjectTable';
|
||||
import { errorText, formatTime, shortSha } from '@/utils/format';
|
||||
import {
|
||||
importPhaseLabel,
|
||||
importStatusLabel,
|
||||
moderationLabel,
|
||||
publishStatusLabel,
|
||||
repoStatusLabel,
|
||||
} from '@/utils/labels';
|
||||
|
||||
export default function ProjectDetailPage() {
|
||||
const { projectCode = '' } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const { message } = App.useApp();
|
||||
const [data, setData] = useState<ManagedProjectView | null>(null);
|
||||
const [types, setTypes] = useState<TypeView[]>([]);
|
||||
const [tasks, setTasks] = useState<TaskView[]>([]);
|
||||
const [tab, setTab] = useState('files');
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [publishing, setPublishing] = useState(false);
|
||||
const [blocking, setBlocking] = useState(false);
|
||||
const [snapshot, setSnapshot] = useState<string | undefined>();
|
||||
const [historyKey, setHistoryKey] = useState(0);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const d = await api.getProject(projectCode);
|
||||
setData(d);
|
||||
// 仅仓库未就绪或迁移来的项目才需要展示迁移任务
|
||||
if (d.project.repoStatus !== 'READY' || d.project.sourceRepositoryUrl) {
|
||||
api.listImports({ projectCode, page: 1, size: 10 }).then((r) => setTasks(r.items)).catch(() => {});
|
||||
}
|
||||
} catch (e) {
|
||||
message.error(errorText(e));
|
||||
if (e instanceof AdminApiError && e.status === 404) navigate('/projects', { replace: true });
|
||||
}
|
||||
}, [projectCode, message, navigate]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
api.listProjectTypes().then(setTypes).catch(() => {});
|
||||
}, [load]);
|
||||
|
||||
if (!data) return <Spin />;
|
||||
const p = data.project;
|
||||
const ready = p.repoStatus === 'READY';
|
||||
const blocked = p.publishStatus === 'BLOCKED' || data.moderationStatus === 'BLOCKED';
|
||||
|
||||
const act = async (fn: () => Promise<unknown>, ok: string) => {
|
||||
try {
|
||||
await fn();
|
||||
message.success(ok);
|
||||
load();
|
||||
} catch (e) {
|
||||
message.error(errorText(e));
|
||||
load();
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async () => {
|
||||
try {
|
||||
await api.deleteProject(p.projectCode);
|
||||
message.success('项目已删除');
|
||||
navigate('/projects', { replace: true });
|
||||
} catch (e) {
|
||||
message.error(errorText(e));
|
||||
}
|
||||
};
|
||||
|
||||
const typeName = types.find((t) => t.code === p.projectType)?.name ?? p.projectType;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card
|
||||
className="page-card"
|
||||
title={<Space><Link to="/projects">项目管理</Link>/<span>项目详情</span></Space>}
|
||||
extra={
|
||||
<Space wrap>
|
||||
<Button onClick={() => setEditing(true)}>编辑信息</Button>
|
||||
{ready && !blocked && (
|
||||
<Button type="primary" onClick={() => setPublishing(true)}>
|
||||
{p.publishStatus === 'PUBLISHED' ? '更新发布' : '发布'}
|
||||
</Button>
|
||||
)}
|
||||
{p.publishStatus === 'PUBLISHED' && (
|
||||
<Popconfirm title="撤回后社区将不再公开此项目,确定?" onConfirm={() => act(() => api.unpublishProject(p.projectCode), '已撤回发布')}>
|
||||
<Button>撤回发布</Button>
|
||||
</Popconfirm>
|
||||
)}
|
||||
{blocked ? (
|
||||
<Popconfirm title="解除下架后变为未发布,仍需手动发布。确定?" onConfirm={() => act(() => api.unblockProject(p.projectCode), '已解除下架')}>
|
||||
<Button>解除下架</Button>
|
||||
</Popconfirm>
|
||||
) : (
|
||||
<Button danger onClick={() => setBlocking(true)}>下架</Button>
|
||||
)}
|
||||
<Popconfirm
|
||||
title="删除项目"
|
||||
description="逻辑删除,社区不可见且无法恢复。确定删除?"
|
||||
okButtonProps={{ danger: true }}
|
||||
onConfirm={remove}
|
||||
>
|
||||
<Button danger type="primary">删除</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
<div className="pd-hero">
|
||||
{p.coverUrl ? (
|
||||
<Image src={p.coverUrl} width={168} height={120} className="pd-cover" />
|
||||
) : (
|
||||
<div className="pd-cover pd-cover-empty" style={{ background: coverGradient(p.projectCode) }}>
|
||||
{p.name.slice(0, 1).toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
<div className="pd-hero-main">
|
||||
<div className="pd-title-row">
|
||||
<h2 className="pd-title">{p.name}</h2>
|
||||
<StatusTag map={publishStatusLabel} value={p.publishStatus} />
|
||||
<StatusTag map={repoStatusLabel} value={p.repoStatus} />
|
||||
{data.moderationStatus === 'BLOCKED' && <StatusTag map={moderationLabel} value={data.moderationStatus} />}
|
||||
</div>
|
||||
<Typography.Paragraph className="pd-desc" ellipsis={{ rows: 2, expandable: true, symbol: '展开' }}>
|
||||
{p.description || '暂无描述'}
|
||||
</Typography.Paragraph>
|
||||
<div className="pd-meta">
|
||||
<span><label>编码</label><Typography.Text className="mono" copyable={{ text: p.projectCode }}>{p.projectCode}</Typography.Text></span>
|
||||
<span><label>类型</label>{typeName}</span>
|
||||
<span>
|
||||
<label>所有者</label>
|
||||
{p.owner.userCode ? <Link to={`/users/${p.owner.userCode}`}>{p.owner.nickname}</Link> : p.owner.nickname}
|
||||
</span>
|
||||
<span><label>创建</label>{formatTime(p.createdAt)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="pd-stats">
|
||||
<div><b>{p.likeCount}</b><span>点赞</span></div>
|
||||
<div><b>{p.commentCount}</b><span>评论</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<Descriptions column={{ xs: 1, md: 2, xl: 3 }} size="small" bordered className="pd-info">
|
||||
<Descriptions.Item label="已发布版本">
|
||||
<Typography.Text className="mono" copyable={p.publishedCommitSha ? { text: p.publishedCommitSha } : false}>
|
||||
{shortSha(p.publishedCommitSha)}
|
||||
</Typography.Text>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="发布时间">{formatTime(p.publishedAt)}</Descriptions.Item>
|
||||
<Descriptions.Item label="更新时间">{formatTime(p.updatedAt)}</Descriptions.Item>
|
||||
{p.sourceRepositoryUrl && (
|
||||
<Descriptions.Item label="迁移来源">
|
||||
<a href={p.sourceRepositoryUrl} target="_blank" rel="noreferrer">{p.sourceRepositoryUrl}</a>
|
||||
</Descriptions.Item>
|
||||
)}
|
||||
{p.sourceRepositoryUrl && <Descriptions.Item label="许可证">{p.sourceLicense ?? '未识别'}</Descriptions.Item>}
|
||||
{p.sourceProjectCode && (
|
||||
<Descriptions.Item label="Fork 来源">
|
||||
<Link to={`/projects/${p.sourceProjectCode}`}>{p.sourceProjectCode}</Link> @ <span className="mono">{shortSha(p.sourceCommitSha)}</span>
|
||||
</Descriptions.Item>
|
||||
)}
|
||||
<Descriptions.Item label="URDF">{p.urdfMainUrl ? '已绑定' : '未绑定'}</Descriptions.Item>
|
||||
</Descriptions>
|
||||
{data.moderationReason && (
|
||||
<Alert style={{ marginTop: 16 }} type="error" showIcon message={`下架原因:${data.moderationReason}`} />
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{!ready && (
|
||||
<Card className="page-card" title="仓库未就绪">
|
||||
<Alert
|
||||
type={p.repoStatus === 'FAILED' ? 'error' : 'info'}
|
||||
showIcon
|
||||
message={p.repoStatus === 'FAILED' ? '仓库准备失败,暂不开放文件与发布操作' : '仓库准备中,暂不开放文件与发布操作'}
|
||||
style={{ marginBottom: 12 }}
|
||||
/>
|
||||
<ImportTaskTable tasks={tasks} />
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{ready && (
|
||||
<Card className="page-card">
|
||||
<Tabs
|
||||
activeKey={tab}
|
||||
onChange={setTab}
|
||||
items={[
|
||||
{
|
||||
key: 'files',
|
||||
label: '文件',
|
||||
children: (
|
||||
<FileBrowser
|
||||
projectCode={p.projectCode}
|
||||
snapshotSha={snapshot}
|
||||
onExitSnapshot={() => setSnapshot(undefined)}
|
||||
onCommitted={() => setHistoryKey((k) => k + 1)}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'history',
|
||||
label: '提交历史',
|
||||
children: (
|
||||
<CommitHistory
|
||||
projectCode={p.projectCode}
|
||||
publishedSha={p.publishedCommitSha}
|
||||
refreshKey={historyKey}
|
||||
onBrowse={(sha) => { setSnapshot(sha); setTab('files'); }}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{ key: 'urdf', label: 'URDF', children: <UrdfPanel project={p} onChanged={load} /> },
|
||||
...(tasks.length ? [{ key: 'imports', label: '迁移任务', children: <ImportTaskTable tasks={tasks} /> }] : []),
|
||||
]}
|
||||
/>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<EditProjectModal
|
||||
project={p}
|
||||
types={types}
|
||||
open={editing}
|
||||
onClose={() => setEditing(false)}
|
||||
onSaved={() => { setEditing(false); load(); }}
|
||||
/>
|
||||
<PublishModal
|
||||
open={publishing}
|
||||
projectCode={p.projectCode}
|
||||
publishedSha={p.publishedCommitSha}
|
||||
onClose={() => setPublishing(false)}
|
||||
onDone={() => { setPublishing(false); load(); setHistoryKey((k) => k + 1); }}
|
||||
/>
|
||||
<BlockModal
|
||||
open={blocking}
|
||||
onClose={() => setBlocking(false)}
|
||||
onSubmit={async (reason) => {
|
||||
await act(() => api.blockProject(p.projectCode, reason), '已下架');
|
||||
setBlocking(false);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ImportTaskTable({ tasks }: { tasks: TaskView[] }) {
|
||||
return (
|
||||
<Table<TaskView>
|
||||
rowKey="taskCode"
|
||||
size="small"
|
||||
pagination={false}
|
||||
dataSource={tasks}
|
||||
locale={{ emptyText: '无关联迁移任务' }}
|
||||
columns={[
|
||||
{ title: '任务', dataIndex: 'taskCode', render: (v) => <Link className="mono" to={`/imports/${v}`}>{v}</Link> },
|
||||
{ title: '状态', dataIndex: 'status', render: (v) => <StatusTag map={importStatusLabel} value={v} /> },
|
||||
{ title: '阶段', dataIndex: 'phase', render: (v) => importPhaseLabel[v] ?? v },
|
||||
{ title: '错误码', dataIndex: 'errorCode', render: (v) => v ?? '—' },
|
||||
{ title: '创建时间', dataIndex: 'createdAt', render: formatTime },
|
||||
{
|
||||
title: '操作',
|
||||
render: (_, t) => <ImportTaskActions task={t} />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function PublishModal({
|
||||
open,
|
||||
projectCode,
|
||||
publishedSha,
|
||||
onClose,
|
||||
onDone,
|
||||
}: {
|
||||
open: boolean;
|
||||
projectCode: string;
|
||||
publishedSha: string | null;
|
||||
onClose: () => void;
|
||||
onDone: () => void;
|
||||
}) {
|
||||
const { message } = App.useApp();
|
||||
const [sha, setSha] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [conflict, setConflict] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const fetchSha = useCallback(() => {
|
||||
setSha(null);
|
||||
setError('');
|
||||
setConflict(false);
|
||||
api.getTree(projectCode, '').then((t) => setSha(t.commitSha)).catch((e) => setError(errorText(e)));
|
||||
}, [projectCode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) fetchSha();
|
||||
}, [open, fetchSha]);
|
||||
|
||||
const publish = async () => {
|
||||
if (!sha) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
await api.publishProject(projectCode, sha);
|
||||
message.success('发布成功');
|
||||
onDone();
|
||||
} catch (e) {
|
||||
if (e instanceof AdminApiError && e.status === 409) setConflict(true);
|
||||
setError(errorText(e));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title="确认发布"
|
||||
open={open}
|
||||
onCancel={onClose}
|
||||
footer={[
|
||||
<Button key="r" onClick={fetchSha}>刷新版本</Button>,
|
||||
<Button key="c" onClick={onClose}>取消</Button>,
|
||||
<Button key="o" type="primary" loading={loading} disabled={!sha || conflict} onClick={publish}>确认发布此版本</Button>,
|
||||
]}
|
||||
>
|
||||
<Space direction="vertical" style={{ width: '100%' }}>
|
||||
<Typography.Paragraph>
|
||||
将把当前 <b>main</b> 工作区版本发布到社区。请先在「文件」中检查内容,发布后再提交的文件不会自动更新社区版本。
|
||||
</Typography.Paragraph>
|
||||
<Descriptions column={1} bordered size="small">
|
||||
<Descriptions.Item label="待发布版本">
|
||||
{sha ? <Typography.Text className="mono" copyable>{sha}</Typography.Text> : error ? '—' : <Spin size="small" />}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="当前已发布">
|
||||
<span className="mono">{publishedSha ?? '—'}</span>
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
{sha && sha === publishedSha && <Alert type="info" showIcon message="该版本已是当前发布版本" />}
|
||||
{conflict && <Alert type="warning" showIcon message="工作区版本已变化,请点击「刷新版本」并重新检查后再发布" />}
|
||||
{error && !conflict && <Alert type="error" showIcon message={error} />}
|
||||
</Space>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function BlockModal({
|
||||
open,
|
||||
onClose,
|
||||
onSubmit,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onSubmit: (reason: string) => Promise<void>;
|
||||
}) {
|
||||
const [form] = Form.useForm();
|
||||
const [loading, setLoading] = useState(false);
|
||||
return (
|
||||
<Modal
|
||||
title="下架项目"
|
||||
open={open}
|
||||
onCancel={onClose}
|
||||
confirmLoading={loading}
|
||||
okButtonProps={{ danger: true }}
|
||||
okText="确认下架"
|
||||
destroyOnClose
|
||||
onOk={async () => {
|
||||
const { reason } = await form.validateFields();
|
||||
setLoading(true);
|
||||
try {
|
||||
await onSubmit(reason.trim());
|
||||
form.resetFields();
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Typography.Paragraph type="secondary">下架后社区不可见,且所有者无法重新发布,直到管理员解除下架。</Typography.Paragraph>
|
||||
<Form form={form} layout="vertical" preserve={false}>
|
||||
<Form.Item name="reason" label="下架原因" rules={[{ required: true, whitespace: true }, { max: 500 }]}>
|
||||
<Input.TextArea rows={4} maxLength={500} showCount />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Button, Card, Form, Input, Select, Space } from 'antd';
|
||||
import { PlusOutlined } from '@ant-design/icons';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import * as api from '@/api';
|
||||
import type { ProjectQuery } from '@/api';
|
||||
import type { ManagedProjectView, TypeView } from '@/api/types';
|
||||
import ProjectTable from '@/components/ProjectTable';
|
||||
import { moderationLabel, publishStatusLabel, repoStatusLabel, toOptions } from '@/utils/labels';
|
||||
import { clean, usePaged } from '@/utils/usePaged';
|
||||
|
||||
type Q = Omit<ProjectQuery, 'page' | 'size'>;
|
||||
|
||||
export default function ProjectListPage() {
|
||||
const navigate = useNavigate();
|
||||
const [params] = useSearchParams();
|
||||
const [form] = Form.useForm<Q>();
|
||||
const [types, setTypes] = useState<TypeView[]>([]);
|
||||
const initial = clean({ ownerUserCode: params.get('ownerUserCode') ?? undefined });
|
||||
const list = usePaged<ManagedProjectView, Q>((q) => api.listProjects(q), initial);
|
||||
|
||||
useEffect(() => {
|
||||
api.listProjectTypes().then(setTypes).catch(() => {});
|
||||
form.setFieldsValue(initial);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Card
|
||||
title="全部项目"
|
||||
extra={
|
||||
<Space>
|
||||
<Button onClick={() => navigate('/imports/new')}>从 GitHub 迁移</Button>
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={() => navigate('/projects/new')}>新建项目</Button>
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
<Form form={form} layout="inline" onFinish={(v) => list.search(clean(v))} style={{ marginBottom: 16, rowGap: 8 }}>
|
||||
<Form.Item name="keyword"><Input placeholder="名称 / 描述" allowClear maxLength={254} /></Form.Item>
|
||||
<Form.Item name="ownerUserCode"><Input placeholder="所有者编码" allowClear /></Form.Item>
|
||||
<Form.Item name="type">
|
||||
<Select placeholder="类型" allowClear style={{ width: 120 }} options={types.map((t) => ({ value: t.code, label: t.name }))} />
|
||||
</Form.Item>
|
||||
<Form.Item name="publishStatus"><Select placeholder="发布状态" allowClear style={{ width: 120 }} options={toOptions(publishStatusLabel)} /></Form.Item>
|
||||
<Form.Item name="repoStatus"><Select placeholder="仓库状态" allowClear style={{ width: 130 }} options={toOptions(repoStatusLabel)} /></Form.Item>
|
||||
<Form.Item name="moderationStatus"><Select placeholder="治理状态" allowClear style={{ width: 120 }} options={toOptions(moderationLabel)} /></Form.Item>
|
||||
<Space>
|
||||
<Button type="primary" htmlType="submit">查询</Button>
|
||||
<Button onClick={() => { form.resetFields(); list.search({}); }}>重置</Button>
|
||||
</Space>
|
||||
</Form>
|
||||
<ProjectTable items={list.data.items} loading={list.loading} pagination={list.pagination} types={types} />
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { App, Button, Card, Descriptions, Popconfirm, Space, Spin } from 'antd';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import * as api from '@/api';
|
||||
import type { ManagedProjectView, TypeView, UserView } from '@/api/types';
|
||||
import { useAuth } from '@/auth';
|
||||
import StatusTag from '@/components/StatusTag';
|
||||
import ProjectTable from '@/components/ProjectTable';
|
||||
import EditNicknameModal from '@/components/EditNicknameModal';
|
||||
import { errorText, formatTime } from '@/utils/format';
|
||||
import { roleLabel, userStatusLabel } from '@/utils/labels';
|
||||
import { usePaged } from '@/utils/usePaged';
|
||||
|
||||
export default function UserDetailPage() {
|
||||
const { userCode = '' } = useParams();
|
||||
const { admin } = useAuth();
|
||||
const { message } = App.useApp();
|
||||
const navigate = useNavigate();
|
||||
const [user, setUser] = useState<UserView | null>(null);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [types, setTypes] = useState<TypeView[]>([]);
|
||||
const projects = usePaged<ManagedProjectView, object>(
|
||||
(q) => api.listUserProjects(userCode, q.page, q.size),
|
||||
{},
|
||||
[userCode],
|
||||
);
|
||||
|
||||
const load = useCallback(() => {
|
||||
api.getUser(userCode).then(setUser).catch((e) => {
|
||||
message.error(errorText(e));
|
||||
navigate('/users');
|
||||
});
|
||||
}, [userCode, message, navigate]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
api.listProjectTypes().then(setTypes).catch(() => {});
|
||||
}, [load]);
|
||||
|
||||
if (!user) return <Spin />;
|
||||
|
||||
const canToggle = user.role !== 'OFFICIAL' && user.userCode !== admin?.userCode;
|
||||
const toggle = async () => {
|
||||
try {
|
||||
await api.setUserStatus(user.userCode, user.status === 'ACTIVE' ? 'DISABLED' : 'ACTIVE');
|
||||
message.success('状态已更新');
|
||||
load();
|
||||
} catch (e) {
|
||||
message.error(errorText(e));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card
|
||||
className="page-card"
|
||||
title={<Space><a onClick={() => navigate('/users')}>用户管理</a>/<span>{user.nickname}</span></Space>}
|
||||
extra={
|
||||
<Space>
|
||||
<Button onClick={() => setEditing(true)}>编辑昵称</Button>
|
||||
{canToggle && (
|
||||
<Popconfirm title={user.status === 'ACTIVE' ? '禁用后会话立即失效,项目不会自动下架。确定?' : '确定启用?'} onConfirm={toggle}>
|
||||
<Button danger={user.status === 'ACTIVE'}>{user.status === 'ACTIVE' ? '禁用' : '启用'}</Button>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
<Descriptions column={{ xs: 1, md: 2, xl: 3 }}>
|
||||
<Descriptions.Item label="用户编码"><span className="mono">{user.userCode}</span></Descriptions.Item>
|
||||
<Descriptions.Item label="昵称">{user.nickname}</Descriptions.Item>
|
||||
<Descriptions.Item label="邮箱">{user.email}</Descriptions.Item>
|
||||
<Descriptions.Item label="角色"><StatusTag map={roleLabel} value={user.role} /></Descriptions.Item>
|
||||
<Descriptions.Item label="状态"><StatusTag map={userStatusLabel} value={user.status} /></Descriptions.Item>
|
||||
<Descriptions.Item label="项目数">{user.projectCount}</Descriptions.Item>
|
||||
<Descriptions.Item label="注册时间">{formatTime(user.createdAt)}</Descriptions.Item>
|
||||
</Descriptions>
|
||||
</Card>
|
||||
<Card className="page-card" title="名下项目">
|
||||
<ProjectTable items={projects.data.items} loading={projects.loading} pagination={projects.pagination} types={types} hideOwner />
|
||||
</Card>
|
||||
<EditNicknameModal
|
||||
user={editing ? user : null}
|
||||
onClose={() => setEditing(false)}
|
||||
onSaved={(u) => { setEditing(false); setUser(u); }}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { useState } from 'react';
|
||||
import { App, Button, Card, Form, Input, Popconfirm, Select, Space, Table, Typography } from 'antd';
|
||||
import { Link } from 'react-router-dom';
|
||||
import * as api from '@/api';
|
||||
import type { UserRole, UserStatus, UserView } from '@/api/types';
|
||||
import { useAuth } from '@/auth';
|
||||
import StatusTag from '@/components/StatusTag';
|
||||
import EditNicknameModal from '@/components/EditNicknameModal';
|
||||
import { errorText, formatTime } from '@/utils/format';
|
||||
import { roleLabel, toOptions, userStatusLabel } from '@/utils/labels';
|
||||
import { clean, usePaged } from '@/utils/usePaged';
|
||||
|
||||
interface Q {
|
||||
userCode?: string;
|
||||
nickname?: string;
|
||||
email?: string;
|
||||
role?: UserRole;
|
||||
status?: UserStatus;
|
||||
}
|
||||
|
||||
export default function UserListPage() {
|
||||
const { admin } = useAuth();
|
||||
const { message } = App.useApp();
|
||||
const [form] = Form.useForm<Q>();
|
||||
const [editing, setEditing] = useState<UserView | null>(null);
|
||||
const list = usePaged<UserView, Q>((q) => api.listUsers(q), {});
|
||||
|
||||
const toggle = async (u: UserView) => {
|
||||
try {
|
||||
await api.setUserStatus(u.userCode, u.status === 'ACTIVE' ? 'DISABLED' : 'ACTIVE');
|
||||
message.success(u.status === 'ACTIVE' ? '已禁用' : '已启用');
|
||||
list.reload();
|
||||
} catch (e) {
|
||||
message.error(errorText(e));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card title="全部用户">
|
||||
<Form form={form} layout="inline" onFinish={(v) => list.search(clean(v))} style={{ marginBottom: 16, rowGap: 8 }}>
|
||||
<Form.Item name="userCode"><Input placeholder="用户编码(精确)" allowClear /></Form.Item>
|
||||
<Form.Item name="nickname"><Input placeholder="昵称" allowClear maxLength={254} /></Form.Item>
|
||||
<Form.Item name="email"><Input placeholder="邮箱" allowClear maxLength={254} /></Form.Item>
|
||||
<Form.Item name="role"><Select placeholder="角色" allowClear style={{ width: 140 }} options={toOptions(roleLabel)} /></Form.Item>
|
||||
<Form.Item name="status"><Select placeholder="状态" allowClear style={{ width: 110 }} options={toOptions(userStatusLabel)} /></Form.Item>
|
||||
<Space>
|
||||
<Button type="primary" htmlType="submit">查询</Button>
|
||||
<Button onClick={() => { form.resetFields(); list.search({}); }}>重置</Button>
|
||||
</Space>
|
||||
</Form>
|
||||
<Table<UserView>
|
||||
rowKey="userCode"
|
||||
loading={list.loading}
|
||||
dataSource={list.data.items}
|
||||
pagination={list.pagination}
|
||||
scroll={{ x: 900 }}
|
||||
columns={[
|
||||
{
|
||||
title: '用户',
|
||||
width: 260,
|
||||
render: (_, u) => (
|
||||
<div className="pt-meta">
|
||||
<Link to={`/users/${u.userCode}`} className="pt-name" title={u.nickname}>{u.nickname}</Link>
|
||||
<Typography.Text type="secondary" className="mono pt-code" copyable={{ text: u.userCode }} title={u.userCode}>
|
||||
{u.userCode.length > 16 ? `${u.userCode.slice(0, 16)}…` : u.userCode}
|
||||
</Typography.Text>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{ title: '邮箱', dataIndex: 'email', width: 240, ellipsis: true },
|
||||
{ title: '角色', dataIndex: 'role', width: 130, render: (v) => <StatusTag map={roleLabel} value={v} /> },
|
||||
{ title: '状态', dataIndex: 'status', width: 90, render: (v) => <StatusTag map={userStatusLabel} value={v} /> },
|
||||
{ title: '项目数', dataIndex: 'projectCount', width: 90, align: 'right' },
|
||||
{ title: '注册时间', dataIndex: 'createdAt', width: 180, render: (v) => <span className="nowrap">{formatTime(v)}</span> },
|
||||
{
|
||||
title: '操作',
|
||||
fixed: 'right',
|
||||
width: 200,
|
||||
render: (_, u) => {
|
||||
const canToggle = u.role !== 'OFFICIAL' && u.userCode !== admin?.userCode;
|
||||
return (
|
||||
<Space>
|
||||
<Link to={`/users/${u.userCode}`}>详情</Link>
|
||||
<a onClick={() => setEditing(u)}>编辑昵称</a>
|
||||
{canToggle && (
|
||||
<Popconfirm
|
||||
title={u.status === 'ACTIVE' ? '确定禁用该用户?其会话将立即失效' : '确定启用该用户?'}
|
||||
onConfirm={() => toggle(u)}
|
||||
>
|
||||
<a style={{ color: u.status === 'ACTIVE' ? '#ff4d4f' : undefined }}>
|
||||
{u.status === 'ACTIVE' ? '禁用' : '启用'}
|
||||
</a>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
);
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<EditNicknameModal user={editing} onClose={() => setEditing(null)} onSaved={() => { setEditing(null); list.reload(); }} />
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { ThemeConfig } from 'antd';
|
||||
|
||||
export const brand = {
|
||||
primary: '#4f46e5',
|
||||
ink: '#0b0d1a',
|
||||
siderBg: '#0f1124',
|
||||
siderItemHover: 'rgba(255,255,255,0.06)',
|
||||
};
|
||||
|
||||
const fontFamily =
|
||||
"'Inter', -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Segoe UI', sans-serif";
|
||||
|
||||
export const theme: ThemeConfig = {
|
||||
token: {
|
||||
colorPrimary: brand.primary,
|
||||
colorInfo: brand.primary,
|
||||
colorSuccess: '#10b981',
|
||||
colorWarning: '#f59e0b',
|
||||
colorError: '#ef4444',
|
||||
colorTextBase: '#111827',
|
||||
colorBgLayout: '#f4f5fa',
|
||||
colorBorderSecondary: '#eef0f5',
|
||||
borderRadius: 8,
|
||||
borderRadiusLG: 14,
|
||||
controlHeight: 36,
|
||||
fontFamily,
|
||||
fontSize: 14,
|
||||
boxShadowTertiary: '0 1px 2px rgba(16,24,40,0.04), 0 1px 3px rgba(16,24,40,0.06)',
|
||||
},
|
||||
components: {
|
||||
Layout: {
|
||||
siderBg: brand.siderBg,
|
||||
headerBg: 'rgba(255,255,255,0.8)',
|
||||
headerHeight: 64,
|
||||
headerPadding: '0 28px',
|
||||
bodyBg: '#f4f5fa',
|
||||
},
|
||||
Menu: {
|
||||
darkItemBg: 'transparent',
|
||||
darkSubMenuItemBg: 'transparent',
|
||||
darkItemSelectedBg: 'rgba(99,102,241,0.18)',
|
||||
darkItemSelectedColor: '#ffffff',
|
||||
darkItemColor: 'rgba(226,232,255,0.62)',
|
||||
darkItemHoverBg: brand.siderItemHover,
|
||||
darkItemHoverColor: '#ffffff',
|
||||
itemHeight: 44,
|
||||
itemBorderRadius: 10,
|
||||
itemMarginInline: 12,
|
||||
iconSize: 16,
|
||||
},
|
||||
Card: {
|
||||
headerFontSize: 16,
|
||||
headerHeight: 60,
|
||||
paddingLG: 24,
|
||||
},
|
||||
Table: {
|
||||
headerBg: '#f8f9fc',
|
||||
headerColor: '#6b7280',
|
||||
headerSplitColor: 'transparent',
|
||||
rowHoverBg: '#f7f7ff',
|
||||
cellPaddingBlock: 14,
|
||||
},
|
||||
Button: {
|
||||
primaryShadow: '0 4px 12px rgba(79,70,229,0.25)',
|
||||
fontWeight: 500,
|
||||
},
|
||||
Tag: { borderRadiusSM: 6 },
|
||||
Descriptions: { labelBg: '#f8f9fc' },
|
||||
Tabs: { titleFontSize: 15 },
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
import dayjs from 'dayjs';
|
||||
import { AdminApiError } from '@/api/request';
|
||||
|
||||
export function parseServerTime(value: string): Date {
|
||||
return new Date(/(?:Z|[+-]\d{2}:?\d{2})$/i.test(value) ? value : `${value}Z`);
|
||||
}
|
||||
|
||||
export function formatTime(value?: string | null): string {
|
||||
if (!value) return '—';
|
||||
return dayjs(parseServerTime(value)).format('YYYY-MM-DD HH:mm:ss');
|
||||
}
|
||||
|
||||
export function formatDuration(start?: string | null, end?: string | null): string {
|
||||
if (!start || !end) return '—';
|
||||
const ms = parseServerTime(end).getTime() - parseServerTime(start).getTime();
|
||||
if (ms < 0) return '—';
|
||||
const s = Math.round(ms / 1000);
|
||||
if (s < 60) return `${s} 秒`;
|
||||
const m = Math.floor(s / 60);
|
||||
if (m < 60) return `${m} 分 ${s % 60} 秒`;
|
||||
return `${Math.floor(m / 60)} 小时 ${m % 60} 分`;
|
||||
}
|
||||
|
||||
export function formatSize(bytes?: number | null): string {
|
||||
if (bytes == null) return '—';
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
|
||||
}
|
||||
|
||||
export const MiB = 1024 * 1024;
|
||||
|
||||
export function utf8Bytes(s: string): number {
|
||||
return new TextEncoder().encode(s).byteLength;
|
||||
}
|
||||
|
||||
export function shortSha(sha?: string | null): string {
|
||||
return sha ? sha.slice(0, 10) : '—';
|
||||
}
|
||||
|
||||
export function errorText(e: unknown): string {
|
||||
if (e instanceof AdminApiError) {
|
||||
return e.requestId ? `${e.message}(请求编号:${e.requestId})` : e.message;
|
||||
}
|
||||
if (e instanceof DOMException && e.name === 'AbortError') return '';
|
||||
if (e instanceof TypeError) return '网络异常,请检查网络后刷新确认结果';
|
||||
return e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
|
||||
export function isAbort(e: unknown): boolean {
|
||||
return e instanceof DOMException && e.name === 'AbortError';
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { TaskView } from '@/api/types';
|
||||
|
||||
/** 失败或待核对的任务保留手动重试入口,是否受理由重试接口判断。 */
|
||||
export function canRetryImportTask(task: TaskView): boolean {
|
||||
return task.status === 'FAILED' || task.status === 'REVIEW';
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
export const roleLabel: Record<string, { text: string; color: string }> = {
|
||||
USER: { text: '普通用户', color: 'default' },
|
||||
ADMIN: { text: '管理员', color: 'purple' },
|
||||
OFFICIAL: { text: '官方托管账号', color: 'gold' },
|
||||
};
|
||||
|
||||
export const userStatusLabel: Record<string, { text: string; color: string }> = {
|
||||
ACTIVE: { text: '正常', color: 'green' },
|
||||
DISABLED: { text: '禁用', color: 'red' },
|
||||
};
|
||||
|
||||
export const repoStatusLabel: Record<string, { text: string; color: string }> = {
|
||||
CREATING: { text: '仓库准备中', color: 'processing' },
|
||||
READY: { text: '可使用', color: 'green' },
|
||||
FAILED: { text: '准备失败', color: 'red' },
|
||||
};
|
||||
|
||||
export const publishStatusLabel: Record<string, { text: string; color: string }> = {
|
||||
UNPUBLISHED: { text: '未发布', color: 'default' },
|
||||
PUBLISHED: { text: '已发布', color: 'green' },
|
||||
BLOCKED: { text: '已下架', color: 'red' },
|
||||
};
|
||||
|
||||
export const moderationLabel: Record<string, { text: string; color: string }> = {
|
||||
NORMAL: { text: '正常', color: 'green' },
|
||||
BLOCKED: { text: '已下架', color: 'red' },
|
||||
};
|
||||
|
||||
export const importStatusLabel: Record<string, { text: string; color: string }> = {
|
||||
QUEUED: { text: '排队中', color: 'default' },
|
||||
RUNNING: { text: '迁移中', color: 'processing' },
|
||||
SUCCEEDED: { text: '迁移完成,待检查发布', color: 'green' },
|
||||
FAILED: { text: '迁移失败', color: 'red' },
|
||||
REVIEW: { text: '结果待核对', color: 'orange' },
|
||||
};
|
||||
|
||||
export const importPhaseLabel: Record<string, string> = {
|
||||
QUEUED: '等待处理',
|
||||
CLEANING: '核验并清理失败仓库,准备重新迁移',
|
||||
PRECHECK: '校验来源和项目信息',
|
||||
MIGRATING: '迁移 Git 仓库与 LFS',
|
||||
MIGRATED: '仓库迁移已确认',
|
||||
NORMALIZING: '适配社区主分支',
|
||||
BRANCH_READY: '主分支已准备',
|
||||
LINKED: '已关联社区项目',
|
||||
};
|
||||
|
||||
export const importPhaseOrder = [
|
||||
'QUEUED',
|
||||
'CLEANING',
|
||||
'PRECHECK',
|
||||
'MIGRATING',
|
||||
'MIGRATED',
|
||||
'NORMALIZING',
|
||||
'BRANCH_READY',
|
||||
'LINKED',
|
||||
];
|
||||
|
||||
export function toOptions(map: Record<string, { text: string } | string>) {
|
||||
return Object.entries(map).map(([value, v]) => ({
|
||||
value,
|
||||
label: typeof v === 'string' ? v : v.text,
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { App } from 'antd';
|
||||
import type { PageResponse } from '@/api/types';
|
||||
import { errorText } from './format';
|
||||
|
||||
/** 通用分页列表 hook:fetcher 接收 page/size 与筛选条件 */
|
||||
export function usePaged<T, Q extends object>(
|
||||
fetcher: (q: Q & { page: number; size: number }) => Promise<PageResponse<T>>,
|
||||
initialQuery: Q,
|
||||
deps: unknown[] = [],
|
||||
) {
|
||||
const { message } = App.useApp();
|
||||
const [query, setQuery] = useState<Q>(initialQuery);
|
||||
const [page, setPage] = useState(1);
|
||||
const [size, setSize] = useState(20);
|
||||
const [data, setData] = useState<PageResponse<T>>({ items: [], page: 1, size: 20, total: 0 });
|
||||
const [loading, setLoading] = useState(false);
|
||||
const fetcherRef = useRef(fetcher);
|
||||
fetcherRef.current = fetcher;
|
||||
|
||||
const reload = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
setData(await fetcherRef.current({ ...query, page, size }));
|
||||
} catch (e) {
|
||||
const t = errorText(e);
|
||||
if (t) message.error(t);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [query, page, size, ...deps]);
|
||||
|
||||
useEffect(() => {
|
||||
reload();
|
||||
}, [reload]);
|
||||
|
||||
const search = (q: Q) => {
|
||||
setPage(1);
|
||||
setQuery(q);
|
||||
};
|
||||
|
||||
return {
|
||||
data,
|
||||
loading,
|
||||
reload,
|
||||
search,
|
||||
query,
|
||||
pagination: {
|
||||
current: page,
|
||||
pageSize: size,
|
||||
total: data.total,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: [10, 20, 50, 100],
|
||||
showTotal: (t: number) => `共 ${t} 条`,
|
||||
onChange: (p: number, s: number) => {
|
||||
setPage(s !== size ? 1 : p);
|
||||
setSize(s);
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** 去掉空字符串/undefined,避免发送 role= 等空枚举 */
|
||||
export function clean<T extends object>(v: T): T {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [k, val] of Object.entries(v)) {
|
||||
if (val !== undefined && val !== null && val !== '') out[k] = typeof val === 'string' ? val.trim() : val;
|
||||
}
|
||||
return out as T;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
const admin = { userCode: 'test-admin', nickname: '测试管理员', email: 'test@example.com', role: 'ADMIN' };
|
||||
|
||||
for (const deployment of [
|
||||
{
|
||||
origin: 'https://dev-vibemake-admin.robotquan.com',
|
||||
api: 'https://dev-vibemake-api.robotquan.com/admin-api',
|
||||
label: '测试环境',
|
||||
},
|
||||
{
|
||||
origin: 'https://vibemake-admin.robotquan.com',
|
||||
api: 'https://vibemake-api.robotquan.com/admin-api',
|
||||
label: '线上环境',
|
||||
},
|
||||
{
|
||||
origin: 'http://127.0.0.1:5190',
|
||||
api: 'http://127.0.0.1:5190/admin-api',
|
||||
label: '本地开发 · 测试接口',
|
||||
},
|
||||
]) {
|
||||
test(`${deployment.origin} 自动选择对应接口及环境标记`, async ({ page }) => {
|
||||
// 使用同一份本地源码模拟不同部署域名,全部业务响应均模拟,不访问真实账号。
|
||||
if (deployment.origin.startsWith('https:')) {
|
||||
await page.route(`${deployment.origin}/**`, async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const response = await route.fetch({ url: `http://127.0.0.1:5190${url.pathname}${url.search}` });
|
||||
await route.fulfill({ response });
|
||||
});
|
||||
}
|
||||
await page.route('https://fonts.googleapis.com/**', (route) => route.abort());
|
||||
const requests: { method: string; url: string }[] = [];
|
||||
await page.route('**/admin-api/**', async (route) => {
|
||||
const request = route.request();
|
||||
requests.push({ method: request.method(), url: request.url() });
|
||||
const headers = {
|
||||
'Access-Control-Allow-Origin': deployment.origin,
|
||||
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
||||
'Access-Control-Allow-Headers': 'content-type, authorization',
|
||||
};
|
||||
if (request.method() === 'OPTIONS') return route.fulfill({ status: 204, headers });
|
||||
const pathname = new URL(request.url()).pathname;
|
||||
const data = pathname.endsWith('/auth/login')
|
||||
? { token: 'test-token', tokenType: 'Bearer', expiresIn: 3600, admin }
|
||||
: pathname.endsWith('/auth/me')
|
||||
? admin
|
||||
: pathname.endsWith('/projects/types')
|
||||
? []
|
||||
: { items: [], page: 1, size: 20, total: 0 };
|
||||
await route.fulfill({ status: 200, headers, json: { code: 'OK', message: '成功', data, requestId: null } });
|
||||
});
|
||||
await page.goto(`${deployment.origin}/login`);
|
||||
await page.getByRole('textbox', { name: '邮箱', exact: true }).fill('test@example.com');
|
||||
await page.getByLabel('密码', { exact: true }).fill('mock-only-not-sent-to-server');
|
||||
await page.getByRole('button', { name: /登\s*录/ }).click();
|
||||
await expect(page).toHaveURL(`${deployment.origin}/projects`);
|
||||
await expect(page.locator('.vm-env')).toHaveText(deployment.label);
|
||||
await expect(page.getByRole('button', { name: /查\s*询/, exact: true })).toBeVisible();
|
||||
const posts = requests.filter((request) => request.method === 'POST');
|
||||
expect(posts).toEqual([{ method: 'POST', url: `${deployment.api}/auth/login` }]);
|
||||
expect(requests.every((request) => request.url.startsWith(`${deployment.api}/`))).toBe(true);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
import { expect, test, type Page, type Route } from '@playwright/test';
|
||||
import type { TaskView } from '../src/api/types';
|
||||
|
||||
const task = (overrides: Partial<TaskView> = {}): TaskView => ({
|
||||
taskCode: 'task-original',
|
||||
projectCode: 'project-original',
|
||||
status: 'FAILED',
|
||||
phase: 'MIGRATING',
|
||||
errorCode: 'GITEA_MIGRATION_REJECTED',
|
||||
canRetry: true,
|
||||
retryMessage: '核验任务归属后清理失败仓库,再重新迁移。',
|
||||
warnings: [],
|
||||
createdAt: '2026-10-20T02:30:00',
|
||||
startedAt: '2026-10-20T02:30:01',
|
||||
finishedAt: '2026-10-20T02:31:00',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
async function ok(route: Route, data: unknown, status = 200) {
|
||||
await route.fulfill({ status, json: { code: 'OK', message: '成功', data, requestId: null } });
|
||||
}
|
||||
|
||||
// 全量拦截管理接口,测试不会向真实后端提交迁移、清理或发布请求。
|
||||
async function mockAdmin(page: Page, handle: (route: Route, path: string) => Promise<void>) {
|
||||
await page.addInitScript(() => localStorage.setItem('vibemake_admin_token', 'test-token'));
|
||||
await page.route('**/admin-api/**', async (route) => {
|
||||
const path = new URL(route.request().url()).pathname.replace('/admin-api', '');
|
||||
if (path === '/auth/me') {
|
||||
return ok(route, { userCode: 'admin', nickname: '测试管理员', email: 'admin@example.com', role: 'ADMIN' });
|
||||
}
|
||||
if (path === '/projects/types') return ok(route, [{ code: 'WHEELED', name: '轮式机器人' }]);
|
||||
return handle(route, path);
|
||||
});
|
||||
}
|
||||
|
||||
async function confirmRetry(page: Page) {
|
||||
await page.getByRole('button', { name: '重试迁移', exact: true }).click();
|
||||
await page.getByRole('dialog').getByRole('button', { name: '确认重试' }).click();
|
||||
}
|
||||
|
||||
for (const status of ['FAILED', 'REVIEW'] as const) {
|
||||
test(`${status} 即使 canRetry=false 也能确认并提交重试`, async ({ page }) => {
|
||||
let writes = 0;
|
||||
await mockAdmin(page, async (route, path) => {
|
||||
if (route.request().method() === 'POST') {
|
||||
writes++;
|
||||
expect(path).toBe('/project-imports/task-original/retry');
|
||||
expect(route.request().postData()).toBeNull();
|
||||
}
|
||||
return ok(route, writes
|
||||
? task({ status: 'QUEUED', phase: 'QUEUED', canRetry: false, retryMessage: null })
|
||||
: task({ status, canRetry: false, retryMessage: '远端结果未知,请联系维护人员。' }), writes ? 202 : 200);
|
||||
});
|
||||
await page.goto('/imports/task-original');
|
||||
await expect(page.getByText('远端结果未知,请联系维护人员。').first()).toBeVisible();
|
||||
await page.getByRole('button', { name: '重试迁移', exact: true }).click();
|
||||
await expect(page.getByRole('dialog').getByText('远端结果未知,请联系维护人员。', { exact: true })).toBeVisible();
|
||||
await page.getByRole('dialog').getByRole('button', { name: '确认重试' }).click();
|
||||
await expect(page.getByRole('dialog')).toHaveCount(0);
|
||||
expect(writes).toBe(1);
|
||||
await expect(page.getByRole('button', { name: '重试迁移', exact: true })).toHaveCount(0);
|
||||
});
|
||||
}
|
||||
|
||||
for (const status of ['QUEUED', 'RUNNING', 'SUCCEEDED'] as const) {
|
||||
test(`${status} 不显示额外重试入口`, async ({ page }) => {
|
||||
await mockAdmin(page, (route) => ok(route, task({ status })));
|
||||
await page.goto('/imports/task-original');
|
||||
await expect(page.getByRole('button', { name: '查看项目' })).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: '重试迁移', exact: true })).toHaveCount(0);
|
||||
});
|
||||
}
|
||||
|
||||
test('旧接口未返回 canRetry 时仍显示重试入口', async ({ page }) => {
|
||||
const { canRetry: _, ...legacyTask } = task({ status: 'REVIEW' });
|
||||
await mockAdmin(page, (route) => ok(route, legacyTask));
|
||||
await page.goto('/imports/task-original');
|
||||
await expect(page.getByRole('button', { name: '重试迁移', exact: true })).toBeEnabled();
|
||||
});
|
||||
|
||||
test('旧 REVIEW 拒绝任务展示确认说明,取消不发送重试', async ({ page }) => {
|
||||
let writes = 0;
|
||||
const explanation = '将先核验旧仓库;缺少任务标识时不会清理。';
|
||||
await mockAdmin(page, async (route) => {
|
||||
if (route.request().method() === 'POST') writes++;
|
||||
await ok(route, task({ status: 'REVIEW', retryMessage: explanation }));
|
||||
});
|
||||
await page.goto('/imports/task-original');
|
||||
await page.getByRole('button', { name: '重试迁移', exact: true }).click();
|
||||
await expect(page.getByRole('dialog').getByText(explanation, { exact: true })).toBeVisible();
|
||||
await page.getByRole('dialog').getByRole('button', { name: /取\s*消/ }).click();
|
||||
expect(writes).toBe(0);
|
||||
});
|
||||
|
||||
test('202 无 body 重试原任务,展示 CLEANING 和提醒,成功后停止轮询且不自动发布', async ({ page }) => {
|
||||
let gets = 0;
|
||||
let writes = 0;
|
||||
await mockAdmin(page, async (route, path) => {
|
||||
if (route.request().method() === 'POST') {
|
||||
writes++;
|
||||
expect(path).toBe('/project-imports/task-original/retry');
|
||||
expect(route.request().postData()).toBeNull();
|
||||
await new Promise((resolve) => setTimeout(resolve, 350));
|
||||
return ok(route, task({ status: 'QUEUED', phase: 'QUEUED', canRetry: false, retryMessage: null }), 202);
|
||||
}
|
||||
gets++;
|
||||
if (gets === 1) return ok(route, task());
|
||||
return ok(route, task(gets === 2
|
||||
? { status: 'RUNNING', phase: 'CLEANING', errorCode: null, canRetry: false, retryMessage: null, warnings: ['Git LFS 正在迁移'], finishedAt: null }
|
||||
: { status: 'SUCCEEDED', phase: 'LINKED', errorCode: null, canRetry: false, retryMessage: null }));
|
||||
});
|
||||
await page.goto('/imports/task-original');
|
||||
await confirmRetry(page);
|
||||
await expect(page.getByRole('button', { name: '确认重试' })).toBeDisabled();
|
||||
await expect(page.getByText('后台正在核验残留仓库归属并执行受保护的清理', { exact: false })).toBeVisible();
|
||||
await expect(page.getByText('Git LFS 正在迁移')).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: '去检查发布' })).toBeVisible({ timeout: 8000 });
|
||||
const finishedGets = gets;
|
||||
await page.waitForTimeout(3300);
|
||||
expect(gets).toBe(finishedGets);
|
||||
expect(writes).toBe(1);
|
||||
await expect(page.getByRole('link', { name: 'project-original', exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
test('409 展示后端 message/requestId 并刷新任务,保留入口且不自动重发', async ({ page }) => {
|
||||
let gets = 0;
|
||||
let writes = 0;
|
||||
await mockAdmin(page, async (route) => {
|
||||
if (route.request().method() === 'POST') {
|
||||
writes++;
|
||||
return route.fulfill({
|
||||
status: 409,
|
||||
headers: { 'X-Request-Id': 'conflict-request-123' },
|
||||
json: { code: 'CONFLICT', message: '仓库归属核验未通过', data: null },
|
||||
});
|
||||
}
|
||||
gets++;
|
||||
await ok(route, gets === 1 ? task() : task({ status: 'REVIEW', canRetry: false, retryMessage: '仓库归属需要核对。' }));
|
||||
});
|
||||
await page.goto('/imports/task-original');
|
||||
await confirmRetry(page);
|
||||
await expect(page.getByText(/仓库归属核验未通过.*conflict-request-123/)).toBeVisible();
|
||||
await expect(page.getByText('仓库归属需要核对。').first()).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: '重试迁移', exact: true })).toBeEnabled();
|
||||
expect(gets).toBe(2);
|
||||
expect(writes).toBe(1);
|
||||
});
|
||||
|
||||
test('重试断网后只查询确认服务端已运行,不重复提交', async ({ page }) => {
|
||||
let gets = 0;
|
||||
let writes = 0;
|
||||
await mockAdmin(page, async (route) => {
|
||||
if (route.request().method() === 'POST') {
|
||||
writes++;
|
||||
return route.abort('failed');
|
||||
}
|
||||
gets++;
|
||||
return ok(route, gets === 1 ? task() : task({ status: 'RUNNING', phase: 'PRECHECK', canRetry: false, retryMessage: null, errorCode: null }));
|
||||
});
|
||||
await page.goto('/imports/task-original');
|
||||
await confirmRetry(page);
|
||||
await expect(page.getByText(/正在重新查询任务确认结果,请勿重复提交/)).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: '重试迁移', exact: true })).toHaveCount(0);
|
||||
expect(writes).toBe(1);
|
||||
expect(gets).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
test('重试和后续查询均失败时锁住旧重试入口,恢复查询后才重新开放', async ({ page }) => {
|
||||
let gets = 0;
|
||||
let writes = 0;
|
||||
await mockAdmin(page, async (route) => {
|
||||
if (route.request().method() === 'POST') {
|
||||
writes++;
|
||||
return route.abort('failed');
|
||||
}
|
||||
gets++;
|
||||
if (gets === 2) return route.abort('failed');
|
||||
return ok(route, task());
|
||||
});
|
||||
await page.goto('/imports/task-original');
|
||||
await confirmRetry(page);
|
||||
await expect(page.getByText(/获取状态失败/)).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: '重试迁移', exact: true })).toBeDisabled();
|
||||
await page.getByRole('button', { name: '恢复查询' }).click();
|
||||
await expect(page.getByRole('button', { name: '重试迁移', exact: true })).toBeEnabled();
|
||||
expect(writes).toBe(1);
|
||||
});
|
||||
|
||||
for (const errorCode of ['CLEANUP_REPOSITORY_UNSAFE', 'CLEANUP_REPOSITORY_REPLACED']) {
|
||||
test(`${errorCode} 保留提醒和可用的重试入口`, async ({ page }) => {
|
||||
await mockAdmin(page, (route) => ok(route, task({ status: 'REVIEW', errorCode, canRetry: false, retryMessage: null })));
|
||||
await page.goto('/imports/task-original');
|
||||
await expect(page.getByText(/后台未删除仓库,请联系维护人员处理/)).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: '重试迁移', exact: true })).toBeEnabled();
|
||||
await page.getByRole('button', { name: '重试迁移', exact: true }).click();
|
||||
await expect(page.getByRole('dialog').getByRole('button', { name: '确认重试' })).toBeEnabled();
|
||||
});
|
||||
}
|
||||
|
||||
test('查询断网不改变迁移状态,可以恢复串行轮询;离开页面后停止', async ({ page }) => {
|
||||
let gets = 0;
|
||||
await mockAdmin(page, async (route, path) => {
|
||||
if (path === '/project-imports') return ok(route, { items: [], page: 1, size: 20, total: 0 });
|
||||
gets++;
|
||||
if (gets === 2) return route.abort('failed');
|
||||
return ok(route, task({ status: 'RUNNING', phase: 'MIGRATING', errorCode: null, canRetry: false, retryMessage: null }));
|
||||
});
|
||||
await page.goto('/imports/task-original');
|
||||
await expect(page.getByText(/获取状态失败/)).toBeVisible({ timeout: 8000 });
|
||||
await expect(page.locator('.ant-tag').filter({ hasText: '迁移中' })).toBeVisible();
|
||||
await page.getByRole('button', { name: '恢复查询' }).click();
|
||||
await expect(page.getByText(/获取状态失败/)).toHaveCount(0);
|
||||
await page.getByRole('link', { name: 'GitHub 迁移', exact: true }).click();
|
||||
await expect(page).toHaveURL('/imports');
|
||||
const leftGets = gets;
|
||||
await page.waitForTimeout(3300);
|
||||
expect(gets).toBe(leftGets);
|
||||
});
|
||||
|
||||
test('慢查询完成前不发起下一轮请求', async ({ page }) => {
|
||||
let gets = 0;
|
||||
let release!: () => void;
|
||||
const delayed = new Promise<void>((resolve) => { release = resolve; });
|
||||
await mockAdmin(page, async (route) => {
|
||||
gets++;
|
||||
if (gets === 1) await delayed;
|
||||
return ok(route, task({ status: gets === 1 ? 'RUNNING' : 'REVIEW', canRetry: false }));
|
||||
});
|
||||
await page.goto('/imports/task-original');
|
||||
await expect.poll(() => gets).toBe(1);
|
||||
await page.waitForTimeout(3300);
|
||||
expect(gets).toBe(1);
|
||||
release();
|
||||
await expect(page.getByText('结果待核对', { exact: true }).first()).toBeVisible({ timeout: 8000 });
|
||||
const terminalGets = gets;
|
||||
await page.waitForTimeout(3300);
|
||||
expect(gets).toBe(terminalGets);
|
||||
});
|
||||
|
||||
test('任务查询 401 时退出并停止轮询', async ({ page }) => {
|
||||
let gets = 0;
|
||||
await mockAdmin(page, async (route) => {
|
||||
gets++;
|
||||
await route.fulfill({ status: 401, json: { code: 'UNAUTHORIZED', message: '会话已过期', data: null } });
|
||||
});
|
||||
await page.goto('/imports/task-original');
|
||||
await expect(page).toHaveURL(/\/login\?redirect=/);
|
||||
expect(await page.evaluate(() => localStorage.getItem('vibemake_admin_token'))).toBeNull();
|
||||
expect(gets).toBe(1);
|
||||
});
|
||||
|
||||
test('列表为失败和待核对任务显示重试,canRetry=false 也可进入确认框', async ({ page }) => {
|
||||
await mockAdmin(page, (route, path) => path === '/project-imports' ? ok(route, {
|
||||
items: [
|
||||
task({ status: 'REVIEW' }),
|
||||
task({ taskCode: 'task-locked', canRetry: false, retryMessage: '等待维护核对' }),
|
||||
task({ taskCode: 'task-done', status: 'SUCCEEDED' }),
|
||||
],
|
||||
page: 1, size: 20, total: 3,
|
||||
}) : ok(route, task({ taskCode: 'task-locked', canRetry: false, retryMessage: '等待维护核对' })));
|
||||
await page.goto('/imports');
|
||||
await expect(page.getByRole('link', { name: '重试迁移' })).toHaveCount(2);
|
||||
await expect(page.getByRole('link', { name: '查看详情' })).toHaveCount(3);
|
||||
await expect(page.getByRole('cell', { name: '等待维护核对' })).toBeVisible();
|
||||
await page.getByRole('row').filter({ hasText: 'task-locked' }).getByRole('link', { name: '重试迁移' }).click();
|
||||
await expect(page).toHaveURL('/imports/task-locked?retry=1');
|
||||
await expect(page.getByRole('dialog').getByText('等待维护核对', { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole('dialog').getByRole('button', { name: '确认重试' })).toBeEnabled();
|
||||
});
|
||||
|
||||
async function prepareCreate(page: Page, createHandler: (route: Route) => Promise<void>) {
|
||||
await mockAdmin(page, async (route, path) => {
|
||||
if (path === '/project-imports/preview') {
|
||||
return ok(route, {
|
||||
repositoryUrl: 'https://github.com/example/robot', defaultBranch: 'main', name: '示例机器人',
|
||||
description: '迁移描述', license: null, existingProjectCode: null,
|
||||
});
|
||||
}
|
||||
if (path === '/project-imports' && route.request().method() === 'POST') return createHandler(route);
|
||||
return ok(route, task({ status: 'QUEUED', canRetry: false, retryMessage: null }));
|
||||
});
|
||||
await page.goto('/imports/new');
|
||||
await page.getByRole('textbox', { name: 'GitHub 仓库地址' }).fill('https://github.com/example/robot');
|
||||
await page.getByRole('button', { name: /预\s*检/, exact: true }).click();
|
||||
await page.getByRole('combobox', { name: '项目类型' }).click();
|
||||
await page.getByText('轮式机器人', { exact: true }).click();
|
||||
}
|
||||
|
||||
test('创建 DUPLICATE_SOURCE 后保留表单并阻止重复创建,提供已有项目入口', async ({ page }) => {
|
||||
let writes = 0;
|
||||
await prepareCreate(page, async (route) => {
|
||||
writes++;
|
||||
await route.fulfill({ status: 409, json: { code: 'DUPLICATE_SOURCE', message: '仓库已迁移', data: { projectCode: 'existing-project' } } });
|
||||
});
|
||||
await page.getByRole('button', { name: '创建迁移任务', exact: true }).click();
|
||||
await expect(page.getByRole('button', { name: '创建迁移任务', exact: true })).toBeDisabled();
|
||||
await expect(page.getByRole('textbox', { name: '项目名称' })).toHaveValue('示例机器人');
|
||||
await expect(page.getByRole('button', { name: '查看已有项目' }).first()).toBeVisible();
|
||||
expect(writes).toBe(1);
|
||||
});
|
||||
|
||||
test('创建断网后锁定提交,重新预检仍保留已编辑的信息', async ({ page }) => {
|
||||
let writes = 0;
|
||||
await prepareCreate(page, async (route) => { writes++; await route.abort('failed'); });
|
||||
await page.getByRole('textbox', { name: '项目名称' }).fill('管理员编辑后的名称');
|
||||
await page.getByRole('button', { name: '创建迁移任务', exact: true }).click();
|
||||
await expect(page.getByText(/创建结果待核对/)).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: '创建迁移任务', exact: true })).toBeDisabled();
|
||||
await expect(page.getByRole('button', { name: '查看迁移任务' })).toBeVisible();
|
||||
await page.getByRole('button', { name: /预\s*检/, exact: true }).click();
|
||||
await expect(page.getByRole('textbox', { name: '项目名称' })).toHaveValue('管理员编辑后的名称');
|
||||
await expect(page.getByRole('button', { name: '创建迁移任务', exact: true })).toBeEnabled();
|
||||
expect(writes).toBe(1);
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"skipLibCheck": true,
|
||||
"isolatedModules": true,
|
||||
"resolveJsonModule": true,
|
||||
"allowImportingTsExtensions": false,
|
||||
"baseUrl": ".",
|
||||
"paths": { "@/*": ["src/*"] },
|
||||
"types": ["vite/client"]
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { defineConfig, loadEnv, type ProxyOptions } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import path from 'node:path';
|
||||
|
||||
export default defineConfig(({ mode }) => {
|
||||
const env = loadEnv(mode, process.cwd(), '');
|
||||
const target = env.VITE_PROXY_TARGET || 'https://dev-vibemake-api.robotquan.com';
|
||||
const proxy: Record<string, ProxyOptions> = {
|
||||
'/admin-api': {
|
||||
target,
|
||||
changeOrigin: true,
|
||||
secure: true,
|
||||
// 后端 CORS 只放行白名单来源,浏览器带的 Origin(localhost) 会被拒绝返回 403。
|
||||
// 代理请求本就同源,去掉 Origin 让后端按普通请求处理。
|
||||
configure: (p) => {
|
||||
p.on('proxyReq', (req) => {
|
||||
req.removeHeader('origin');
|
||||
req.removeHeader('referer');
|
||||
});
|
||||
},
|
||||
},
|
||||
};
|
||||
return {
|
||||
plugins: [react()],
|
||||
resolve: { alias: { '@': path.resolve(__dirname, 'src') } },
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: 5188,
|
||||
strictPort: true,
|
||||
// 开发环境统一代理 /admin-api 到后端,避免跨域
|
||||
proxy,
|
||||
},
|
||||
build: {
|
||||
chunkSizeWarningLimit: 1500,
|
||||
rollupOptions: {
|
||||
output: {
|
||||
manualChunks: {
|
||||
react: ['react', 'react-dom', 'react-router-dom'],
|
||||
antd: ['antd', '@ant-design/icons', 'dayjs'],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
preview: {
|
||||
port: 4173,
|
||||
proxy,
|
||||
},
|
||||
};
|
||||
});
|
||||
Reference in New Issue
Block a user