first commit

This commit is contained in:
zyc 2026-01-29 10:41:39 +08:00
commit a57a220b65
34 changed files with 8167 additions and 0 deletions

2
.env.development Normal file
View File

@ -0,0 +1,2 @@
# 环境变量配置
VITE_API_BASE_URL=http://localhost:8001

24
.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Dependencies
node_modules/
# Build output
dist/
# IDE
.vscode/
.idea/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
# Environment
.env
.env.local
.env.*.local
# Logs
*.log
npm-debug.log*

73
README.md Normal file
View File

@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

23
eslint.config.js Normal file
View File

@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

13
index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>rtc_web</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

5569
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

37
package.json Normal file
View File

@ -0,0 +1,37 @@
{
"name": "rtc_web",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@ant-design/icons": "^6.1.0",
"@ant-design/pro-components": "^2.8.10",
"antd": "^5.29.3",
"axios": "^1.13.4",
"dayjs": "^1.11.19",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-router-dom": "^7.13.0",
"zustand": "^5.0.10"
},
"devDependencies": {
"@eslint/js": "^9.39.1",
"@types/node": "^24.10.1",
"@types/react": "^19.2.5",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.1",
"eslint": "^9.39.1",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.24",
"globals": "^16.5.0",
"typescript": "~5.9.3",
"typescript-eslint": "^8.46.4",
"vite": "^7.2.4"
}
}

1
public/vite.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

42
src/App.css Normal file
View File

@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}

23
src/App.tsx Normal file
View File

@ -0,0 +1,23 @@
import { RouterProvider } from 'react-router-dom';
import { ConfigProvider } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import router from './routes';
import 'dayjs/locale/zh-cn';
function App() {
return (
<ConfigProvider
locale={zhCN}
theme={{
token: {
colorPrimary: '#1890ff',
borderRadius: 6,
},
}}
>
<RouterProvider router={router} />
</ConfigProvider>
);
}
export default App;

42
src/api/auth.ts Normal file
View File

@ -0,0 +1,42 @@
import request from './request';
import type { ApiResponse } from './request';
// 管理员信息类型
export interface AdminInfo {
id: number;
username: string;
name: string;
email: string;
phone: string;
role: 'super_admin' | 'admin' | 'operator';
is_active: boolean;
}
// 登录响应
export interface LoginResponse {
token: {
access: string;
refresh: string;
};
admin: AdminInfo;
}
// 登录
export const login = (data: { username: string; password: string }) => {
return request.post<unknown, ApiResponse<LoginResponse>>('/api/admin/auth/login/', data);
};
// 刷新Token
export const refreshToken = (refresh: string) => {
return request.post<unknown, ApiResponse<{ access: string }>>('/api/admin/auth/refresh/', { refresh });
};
// 获取当前管理员信息
export const getProfile = () => {
return request.get<unknown, ApiResponse<AdminInfo>>('/api/admin/profile/me/');
};
// 修改密码
export const changePassword = (data: { old_password: string; new_password: string }) => {
return request.put<unknown, ApiResponse<null>>('/api/admin/profile/change-password/', data);
};

90
src/api/batch.ts Normal file
View File

@ -0,0 +1,90 @@
import request from './request';
import type { ApiResponse, PaginatedResponse } from './request';
import type { DeviceType } from './deviceType';
// 设备批次
export interface DeviceBatch {
id: number;
device_type: number;
device_type_info?: DeviceType;
batch_no: string;
production_date: string;
quantity: number;
remark: string;
sn_range?: {
start: string;
end: string;
};
statistics?: {
total: number;
in_stock: number;
bound: number;
with_mac: number;
without_mac: number;
};
created_at: string;
updated_at: string;
}
// 设备
export interface Device {
id: number;
sn: string;
mac_address: string;
device_type: DeviceType;
batch: number;
status: 'in_stock' | 'bound' | 'offline';
created_at: string;
updated_at: string;
}
// 获取批次列表
export const getBatches = (params?: {
page?: number;
page_size?: number;
device_type?: number;
}) => {
return request.get<unknown, ApiResponse<PaginatedResponse<DeviceBatch>>>('/api/admin/device-batches/', { params });
};
// 获取批次详情
export const getBatch = (id: number) => {
return request.get<unknown, ApiResponse<DeviceBatch>>(`/api/admin/device-batches/${id}/`);
};
// 创建批次自动生成SN码
export const createBatch = (data: {
device_type: number;
batch_no: string;
production_date: string;
quantity: number;
remark?: string;
}) => {
return request.post<unknown, ApiResponse<DeviceBatch>>('/api/admin/device-batches/', data);
};
// 获取批次下的设备列表
export const getBatchDevices = (batchId: number, params?: { page?: number; page_size?: number }) => {
return request.get<unknown, ApiResponse<PaginatedResponse<Device>>>(`/api/admin/device-batches/${batchId}/devices/`, { params });
};
// 导出SN码Excel
export const exportBatchExcel = (batchId: number) => {
return request.get(`/api/admin/device-batches/${batchId}/export/`, {
responseType: 'blob',
});
};
// 导入MAC地址
export const importMacAddresses = (batchId: number, file: File) => {
const formData = new FormData();
formData.append('file', file);
return request.post<unknown, ApiResponse<{
total: number;
success: number;
failed: number;
errors: Array<{ row: number; sn: string; mac: string; error: string }>;
}>>(`/api/admin/device-batches/${batchId}/import_mac/`, formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
};

17
src/api/dashboard.ts Normal file
View File

@ -0,0 +1,17 @@
import request from './request';
import type { ApiResponse } from './request';
// 仪表盘统计数据
export interface DashboardStats {
user_count: number;
device_count: number;
device_type_count: number;
batch_count: number;
bound_device_count: number;
in_stock_device_count: number;
}
// 获取仪表盘统计数据
export const getDashboardStats = () => {
return request.get<unknown, ApiResponse<DashboardStats>>('/api/admin/dashboard/stats/');
};

38
src/api/deviceType.ts Normal file
View File

@ -0,0 +1,38 @@
import request from './request';
import type { ApiResponse, PaginatedResponse } from './request';
// 设备类型
export interface DeviceType {
id: number;
brand: string;
product_code: string;
name: string;
is_network_required: boolean;
created_at: string;
updated_at: string;
}
// 获取设备类型列表
export const getDeviceTypes = (params?: { page?: number; page_size?: number }) => {
return request.get<unknown, ApiResponse<PaginatedResponse<DeviceType>>>('/api/admin/device-types/', { params });
};
// 获取设备类型详情
export const getDeviceType = (id: number) => {
return request.get<unknown, ApiResponse<DeviceType>>(`/api/admin/device-types/${id}/`);
};
// 创建设备类型
export const createDeviceType = (data: { brand: string; product_code: string; name: string }) => {
return request.post<unknown, ApiResponse<DeviceType>>('/api/admin/device-types/', data);
};
// 更新设备类型
export const updateDeviceType = (id: number, data: Partial<DeviceType>) => {
return request.put<unknown, ApiResponse<DeviceType>>(`/api/admin/device-types/${id}/`, data);
};
// 删除设备类型
export const deleteDeviceType = (id: number) => {
return request.delete<unknown, ApiResponse<null>>(`/api/admin/device-types/${id}/`);
};

79
src/api/request.ts Normal file
View File

@ -0,0 +1,79 @@
import axios from 'axios';
import type { AxiosInstance, AxiosError, InternalAxiosRequestConfig } from 'axios';
// API 基础配置
// 开发环境使用代理,生产环境使用环境变量
const BASE_URL = import.meta.env.PROD
? (import.meta.env.VITE_API_BASE_URL || 'http://localhost:8001')
: ''; // 开发环境使用相对路径,通过 Vite 代理
// 创建 Axios 实例
const request: AxiosInstance = axios.create({
baseURL: BASE_URL,
timeout: 30000,
headers: {
'Content-Type': 'application/json',
},
});
// 请求拦截器 - 添加 Token
request.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
const token = localStorage.getItem('admin_token');
if (token && config.headers) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error: AxiosError) => {
return Promise.reject(error);
}
);
// 响应拦截器 - 统一处理响应
request.interceptors.response.use(
(response) => {
const data = response.data;
// 业务错误处理
if (data.code !== 0) {
// Token 过期
if (data.code === 401 || data.code === 1001) {
localStorage.removeItem('admin_token');
localStorage.removeItem('admin_info');
window.location.href = '/login';
return Promise.reject(new Error(data.message || '登录已过期'));
}
return Promise.reject(new Error(data.message || '请求失败'));
}
return data;
},
(error: AxiosError<{ code: number; message: string }>) => {
if (error.response) {
const { status, data } = error.response;
if (status === 401) {
localStorage.removeItem('admin_token');
localStorage.removeItem('admin_info');
window.location.href = '/login';
}
return Promise.reject(new Error(data?.message || `请求失败 (${status})`));
}
return Promise.reject(new Error('网络错误,请检查网络连接'));
}
);
export default request;
// 通用响应类型
export interface ApiResponse<T = unknown> {
code: number;
message: string;
data: T;
}
// 分页响应类型
export interface PaginatedResponse<T> {
items: T[];
total: number;
page: number;
page_size: number;
}

80
src/api/user.ts Normal file
View File

@ -0,0 +1,80 @@
import request from './request';
import type { ApiResponse, PaginatedResponse } from './request';
// App用户类型
export interface AppUser {
id: number;
phone: string;
nickname: string;
avatar: string;
is_active: boolean;
spirit_count: number;
device_count: number;
created_at: string;
updated_at: string;
}
// 管理员用户类型
export interface AdminUser {
id: number;
username: string;
name: string;
email: string;
phone: string;
role: 'super_admin' | 'admin' | 'operator';
is_active: boolean;
last_login: string;
created_at: string;
}
// 获取App用户列表
export const getAppUsers = (params?: {
page?: number;
page_size?: number;
phone?: string;
nickname?: string;
}) => {
return request.get<unknown, ApiResponse<PaginatedResponse<AppUser>>>('/api/admin/users/', { params });
};
// 获取App用户详情
export const getAppUser = (id: number) => {
return request.get<unknown, ApiResponse<AppUser>>(`/api/admin/users/${id}/`);
};
// 切换App用户状态
export const toggleAppUserStatus = (id: number) => {
return request.post<unknown, ApiResponse<AppUser>>(`/api/admin/users/${id}/toggle-status/`);
};
// 获取管理员列表
export const getAdminUsers = (params?: { page?: number; page_size?: number }) => {
return request.get<unknown, ApiResponse<PaginatedResponse<AdminUser>>>('/api/admin/admins/', { params });
};
// 获取管理员详情
export const getAdminUser = (id: number) => {
return request.get<unknown, ApiResponse<AdminUser>>(`/api/admin/admins/${id}/`);
};
// 创建管理员
export const createAdminUser = (data: {
username: string;
password: string;
name?: string;
email?: string;
phone?: string;
role?: string;
}) => {
return request.post<unknown, ApiResponse<AdminUser>>('/api/admin/admins/', data);
};
// 切换管理员状态
export const toggleAdminStatus = (id: number) => {
return request.post<unknown, ApiResponse<AdminUser>>(`/api/admin/admins/${id}/toggle-status/`);
};
// 重置管理员密码
export const resetAdminPassword = (id: number, data: { new_password: string }) => {
return request.post<unknown, ApiResponse<null>>(`/api/admin/admins/${id}/reset-password/`, data);
};

1
src/assets/react.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@ -0,0 +1,189 @@
import React, { useState } from 'react';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import {
Layout,
Menu,
Avatar,
Dropdown,
theme,
Button,
Space,
} from 'antd';
import {
DashboardOutlined,
AppstoreOutlined,
InboxOutlined,
MobileOutlined,
UserOutlined,
TeamOutlined,
LogoutOutlined,
MenuFoldOutlined,
MenuUnfoldOutlined,
} from '@ant-design/icons';
import { useAuthStore } from '../../store/useAuthStore';
const { Header, Sider, Content } = Layout;
const menuItems = [
{
key: '/dashboard',
icon: <DashboardOutlined />,
label: '仪表盘',
},
{
key: '/device-types',
icon: <AppstoreOutlined />,
label: '设备类型',
},
{
key: '/batches',
icon: <InboxOutlined />,
label: '批次管理',
},
{
key: '/devices',
icon: <MobileOutlined />,
label: '设备列表',
},
{
key: '/users',
icon: <UserOutlined />,
label: '用户管理',
},
{
key: '/admins',
icon: <TeamOutlined />,
label: '管理员',
},
];
const MainLayout: React.FC = () => {
const [collapsed, setCollapsed] = useState(false);
const navigate = useNavigate();
const location = useLocation();
const { adminInfo, logout } = useAuthStore();
const { token: themeToken } = theme.useToken();
const handleMenuClick = ({ key }: { key: string }) => {
navigate(key);
};
const handleLogout = () => {
logout();
navigate('/login');
};
const userMenuItems = [
{
key: 'profile',
icon: <UserOutlined />,
label: '个人信息',
},
{
type: 'divider' as const,
},
{
key: 'logout',
icon: <LogoutOutlined />,
label: '退出登录',
danger: true,
onClick: handleLogout,
},
];
const getRoleLabel = (role?: string) => {
const roleMap: Record<string, string> = {
super_admin: '超级管理员',
admin: '管理员',
operator: '操作员',
};
return roleMap[role || ''] || role;
};
return (
<Layout style={{ minHeight: '100vh' }}>
<Sider
trigger={null}
collapsible
collapsed={collapsed}
theme="dark"
style={{
overflow: 'auto',
height: '100vh',
position: 'fixed',
left: 0,
top: 0,
bottom: 0,
}}
>
<div
style={{
height: 64,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: '#fff',
fontSize: collapsed ? 16 : 20,
fontWeight: 'bold',
borderBottom: '1px solid rgba(255,255,255,0.1)',
}}
>
{collapsed ? 'RTC' : 'RTC 管理后台'}
</div>
<Menu
theme="dark"
mode="inline"
selectedKeys={[location.pathname]}
items={menuItems}
onClick={handleMenuClick}
/>
</Sider>
<Layout style={{ marginLeft: collapsed ? 80 : 200, transition: 'margin-left 0.2s' }}>
<Header
style={{
padding: '0 24px',
background: themeToken.colorBgContainer,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
boxShadow: '0 1px 4px rgba(0,0,0,0.08)',
position: 'sticky',
top: 0,
zIndex: 10,
}}
>
<Button
type="text"
icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
onClick={() => setCollapsed(!collapsed)}
style={{ fontSize: 16 }}
/>
<Space>
<Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
<Space style={{ cursor: 'pointer' }}>
<Avatar icon={<UserOutlined />} style={{ backgroundColor: themeToken.colorPrimary }} />
<span>{adminInfo?.name || adminInfo?.username}</span>
<span style={{ color: themeToken.colorTextSecondary, fontSize: 12 }}>
({getRoleLabel(adminInfo?.role)})
</span>
</Space>
</Dropdown>
</Space>
</Header>
<Content
style={{
margin: 24,
padding: 24,
background: themeToken.colorBgContainer,
borderRadius: themeToken.borderRadiusLG,
minHeight: 280,
}}
>
<Outlet />
</Content>
</Layout>
</Layout>
);
};
export default MainLayout;

41
src/index.css Normal file
View File

@ -0,0 +1,41 @@
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body, #root {
height: 100%;
width: 100%;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* 滚动条样式 */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 4px;
}
::-webkit-scrollbar-thumb {
background: #c1c1c1;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #a1a1a1;
}
/* ProTable 调整 */
.ant-pro-table-list-toolbar-title {
font-weight: 600;
}

10
src/main.tsx Normal file
View File

@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.tsx'
import './index.css'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

292
src/pages/Admin/index.tsx Normal file
View File

@ -0,0 +1,292 @@
import React, { useState, useRef } from 'react';
import { Button, message, Tag, Space, Popconfirm, Modal, Form, Input, Select } from 'antd';
import { PlusOutlined, KeyOutlined } from '@ant-design/icons';
import { ProTable } from '@ant-design/pro-components';
import type { ProColumns, ActionType } from '@ant-design/pro-components';
import {
getAdminUsers,
createAdminUser,
toggleAdminStatus,
resetAdminPassword
} from '../../api/user';
import type { AdminUser } from '../../api/user';
import { useAuthStore } from '../../store/useAuthStore';
const AdminPage: React.FC = () => {
const actionRef = useRef<ActionType>(null);
const [createModalVisible, setCreateModalVisible] = useState(false);
const [resetPasswordModalVisible, setResetPasswordModalVisible] = useState(false);
const [selectedAdminId, setSelectedAdminId] = useState<number | null>(null);
const [createForm] = Form.useForm();
const [resetForm] = Form.useForm();
const [loading, setLoading] = useState(false);
const { adminInfo } = useAuthStore();
const isSuperAdmin = adminInfo?.role === 'super_admin';
const handleCreate = async () => {
try {
const values = await createForm.validateFields();
setLoading(true);
await createAdminUser(values);
message.success('创建成功');
setCreateModalVisible(false);
createForm.resetFields();
actionRef.current?.reload();
} catch (error) {
if (error instanceof Error) {
message.error(error.message);
}
} finally {
setLoading(false);
}
};
const handleToggleStatus = async (id: number, currentStatus: boolean) => {
try {
await toggleAdminStatus(id);
message.success(currentStatus ? '已禁用' : '已启用');
actionRef.current?.reload();
} catch (error) {
message.error(error instanceof Error ? error.message : '操作失败');
}
};
const handleResetPassword = async () => {
if (!selectedAdminId) return;
try {
const values = await resetForm.validateFields();
setLoading(true);
await resetAdminPassword(selectedAdminId, values);
message.success('密码重置成功');
setResetPasswordModalVisible(false);
resetForm.resetFields();
} catch (error) {
if (error instanceof Error) {
message.error(error.message);
}
} finally {
setLoading(false);
}
};
const openResetPasswordModal = (id: number) => {
setSelectedAdminId(id);
resetForm.resetFields();
setResetPasswordModalVisible(true);
};
const getRoleLabel = (role: string) => {
const map: Record<string, { text: string; color: string }> = {
super_admin: { text: '超级管理员', color: 'red' },
admin: { text: '管理员', color: 'blue' },
operator: { text: '操作员', color: 'default' },
};
return map[role] || { text: role, color: 'default' };
};
const columns: ProColumns<AdminUser>[] = [
{
title: 'ID',
dataIndex: 'id',
width: 60,
search: false,
},
{
title: '用户名',
dataIndex: 'username',
width: 120,
},
{
title: '姓名',
dataIndex: 'name',
width: 120,
search: false,
},
{
title: '角色',
dataIndex: 'role',
width: 120,
search: false,
render: (_, record) => {
const role = getRoleLabel(record.role);
return <Tag color={role.color}>{role.text}</Tag>;
},
},
{
title: '邮箱',
dataIndex: 'email',
ellipsis: true,
search: false,
},
{
title: '状态',
dataIndex: 'is_active',
width: 80,
search: false,
render: (_, record) => (
<Tag color={record.is_active ? 'green' : 'red'}>
{record.is_active ? '正常' : '禁用'}
</Tag>
),
},
{
title: '创建时间',
dataIndex: 'created_at',
valueType: 'dateTime',
width: 180,
search: false,
},
{
title: '操作',
width: 180,
search: false,
render: (_, record) => {
// 不能操作自己
if (record.id === adminInfo?.id) {
return <span style={{ color: '#999' }}></span>;
}
return (
<Space>
<Button
type="link"
size="small"
icon={<KeyOutlined />}
onClick={() => openResetPasswordModal(record.id)}
>
</Button>
<Popconfirm
title={record.is_active ? '确定禁用该管理员吗?' : '确定启用该管理员吗?'}
onConfirm={() => handleToggleStatus(record.id, record.is_active)}
>
<Button type="link" size="small" danger={record.is_active}>
{record.is_active ? '禁用' : '启用'}
</Button>
</Popconfirm>
</Space>
);
},
},
];
if (!isSuperAdmin) {
return (
<div style={{ textAlign: 'center', padding: 100, color: '#999' }}>
访
</div>
);
}
return (
<div>
<ProTable<AdminUser>
headerTitle="管理员管理"
rowKey="id"
actionRef={actionRef}
columns={columns}
request={async (params) => {
try {
const res = await getAdminUsers({
page: params.current,
page_size: params.pageSize,
});
return {
data: res.data.items,
total: res.data.total,
success: true,
};
} catch (error) {
message.error('获取数据失败');
return { data: [], total: 0, success: false };
}
}}
toolBarRender={() => [
<Button
key="add"
type="primary"
icon={<PlusOutlined />}
onClick={() => {
createForm.resetFields();
setCreateModalVisible(true);
}}
>
</Button>,
]}
pagination={{
defaultPageSize: 10,
showSizeChanger: true,
}}
/>
{/* 创建管理员 Modal */}
<Modal
title="新增管理员"
open={createModalVisible}
onOk={handleCreate}
onCancel={() => setCreateModalVisible(false)}
confirmLoading={loading}
destroyOnClose
>
<Form form={createForm} layout="vertical" style={{ marginTop: 24 }}>
<Form.Item
name="username"
label="用户名"
rules={[{ required: true, message: '请输入用户名' }]}
>
<Input placeholder="登录用户名" />
</Form.Item>
<Form.Item
name="password"
label="密码"
rules={[
{ required: true, message: '请输入密码' },
{ min: 6, message: '密码至少6位' }
]}
>
<Input.Password placeholder="初始密码" />
</Form.Item>
<Form.Item name="name" label="姓名">
<Input placeholder="真实姓名" />
</Form.Item>
<Form.Item name="email" label="邮箱">
<Input placeholder="邮箱地址" />
</Form.Item>
<Form.Item name="role" label="角色" initialValue="operator">
<Select>
<Select.Option value="super_admin"></Select.Option>
<Select.Option value="admin"></Select.Option>
<Select.Option value="operator"></Select.Option>
</Select>
</Form.Item>
</Form>
</Modal>
{/* 重置密码 Modal */}
<Modal
title="重置密码"
open={resetPasswordModalVisible}
onOk={handleResetPassword}
onCancel={() => setResetPasswordModalVisible(false)}
confirmLoading={loading}
destroyOnClose
>
<Form form={resetForm} layout="vertical" style={{ marginTop: 24 }}>
<Form.Item
name="new_password"
label="新密码"
rules={[
{ required: true, message: '请输入新密码' },
{ min: 6, message: '密码至少6位' }
]}
>
<Input.Password placeholder="输入新密码" />
</Form.Item>
</Form>
</Modal>
</div>
);
};
export default AdminPage;

212
src/pages/Batch/Detail.tsx Normal file
View File

@ -0,0 +1,212 @@
import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
Card,
Descriptions,
Button,
Space,
Tag,
message,
Spin,
Statistic,
Row,
Col,
Typography,
} from 'antd';
import {
ArrowLeftOutlined,
DownloadOutlined,
} from '@ant-design/icons';
import { ProTable } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components';
import { getBatch, getBatchDevices, exportBatchExcel } from '../../api/batch';
import type { Device, DeviceBatch } from '../../api/batch';
const { Title } = Typography;
const BatchDetail: React.FC = () => {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [batch, setBatch] = useState<DeviceBatch | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
loadBatch();
}, [id]);
const loadBatch = async () => {
if (!id) return;
try {
const res = await getBatch(parseInt(id));
setBatch(res.data);
} catch (error) {
message.error('加载批次信息失败');
} finally {
setLoading(false);
}
};
const handleExport = async () => {
if (!id) return;
try {
const res = await exportBatchExcel(parseInt(id));
const blob = new Blob([res as unknown as BlobPart], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `batch_${id}_sn_codes.xlsx`;
link.click();
window.URL.revokeObjectURL(url);
message.success('导出成功');
} catch (error) {
message.error('导出失败');
}
};
const deviceColumns: ProColumns<Device>[] = [
{
title: 'SN码',
dataIndex: 'sn',
copyable: true,
},
{
title: 'MAC地址',
dataIndex: 'mac_address',
render: (_, record) => record.mac_address || <Tag color="orange"></Tag>,
},
{
title: '状态',
dataIndex: 'status',
width: 100,
render: (_, record) => {
const statusMap: Record<string, { color: string; text: string }> = {
in_stock: { color: 'default', text: '库存中' },
bound: { color: 'green', text: '已绑定' },
offline: { color: 'red', text: '离线' },
};
const status = statusMap[record.status] || { color: 'default', text: record.status };
return <Tag color={status.color}>{status.text}</Tag>;
},
},
{
title: '创建时间',
dataIndex: 'created_at',
valueType: 'dateTime',
width: 180,
},
];
if (loading) {
return (
<div style={{ textAlign: 'center', padding: 100 }}>
<Spin size="large" />
</div>
);
}
if (!batch) {
return <div></div>;
}
return (
<div>
<Space style={{ marginBottom: 24 }}>
<Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/batches')}>
</Button>
<Title level={4} style={{ margin: 0 }}>
- {batch.batch_no}
</Title>
</Space>
<Card style={{ marginBottom: 24 }}>
<Descriptions column={3}>
<Descriptions.Item label="设备类型">
{batch.device_type_info?.name}
</Descriptions.Item>
<Descriptions.Item label="批次号">{batch.batch_no}</Descriptions.Item>
<Descriptions.Item label="生产日期">{batch.production_date}</Descriptions.Item>
<Descriptions.Item label="数量">{batch.quantity}</Descriptions.Item>
<Descriptions.Item label="SN范围" span={2}>
{batch.sn_range ? `${batch.sn_range.start} ~ ${batch.sn_range.end}` : '-'}
</Descriptions.Item>
<Descriptions.Item label="备注" span={3}>
{batch.remark || '-'}
</Descriptions.Item>
</Descriptions>
</Card>
{batch.statistics && (
<Row gutter={16} style={{ marginBottom: 24 }}>
<Col span={6}>
<Card>
<Statistic title="总数量" value={batch.statistics.total} />
</Card>
</Col>
<Col span={6}>
<Card>
<Statistic
title="已导入MAC"
value={batch.statistics.with_mac}
valueStyle={{ color: '#52c41a' }}
/>
</Card>
</Col>
<Col span={6}>
<Card>
<Statistic
title="库存中"
value={batch.statistics.in_stock}
/>
</Card>
</Col>
<Col span={6}>
<Card>
<Statistic
title="已绑定"
value={batch.statistics.bound}
valueStyle={{ color: '#1890ff' }}
/>
</Card>
</Col>
</Row>
)}
<ProTable<Device>
headerTitle="设备列表"
rowKey="id"
columns={deviceColumns}
search={false}
request={async (params) => {
try {
const res = await getBatchDevices(parseInt(id!), {
page: params.current,
page_size: params.pageSize,
});
return {
data: res.data.items,
total: res.data.total,
success: true,
};
} catch (error) {
message.error('获取设备列表失败');
return { data: [], total: 0, success: false };
}
}}
toolBarRender={() => [
<Button key="export" icon={<DownloadOutlined />} onClick={handleExport}>
Excel
</Button>,
]}
pagination={{
defaultPageSize: 20,
showSizeChanger: true,
}}
/>
</div>
);
};
export default BatchDetail;

381
src/pages/Batch/index.tsx Normal file
View File

@ -0,0 +1,381 @@
import React, { useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import {
Button,
message,
Modal,
Form,
Input,
InputNumber,
DatePicker,
Select,
Space,
Tag,
Upload,
Progress,
} from 'antd';
import {
PlusOutlined,
EyeOutlined,
DownloadOutlined,
UploadOutlined,
InboxOutlined,
} from '@ant-design/icons';
import { ProTable } from '@ant-design/pro-components';
import type { ProColumns, ActionType } from '@ant-design/pro-components';
import dayjs from 'dayjs';
import {
getBatches,
createBatch,
exportBatchExcel,
importMacAddresses,
} from '../../api/batch';
import type { DeviceBatch } from '../../api/batch';
import { getDeviceTypes } from '../../api/deviceType';
import type { DeviceType } from '../../api/deviceType';
const BatchPage: React.FC = () => {
const navigate = useNavigate();
const actionRef = useRef<ActionType>();
const [modalVisible, setModalVisible] = useState(false);
const [importModalVisible, setImportModalVisible] = useState(false);
const [selectedBatchId, setSelectedBatchId] = useState<number | null>(null);
const [deviceTypes, setDeviceTypes] = useState<DeviceType[]>([]);
const [form] = Form.useForm();
const [loading, setLoading] = useState(false);
const [importLoading, setImportLoading] = useState(false);
// 加载设备类型列表
const loadDeviceTypes = async () => {
try {
const res = await getDeviceTypes({ page_size: 100 });
setDeviceTypes(res.data.items);
} catch (error) {
message.error('加载设备类型失败');
}
};
const handleAdd = async () => {
await loadDeviceTypes();
form.resetFields();
setModalVisible(true);
};
const handleSubmit = async () => {
try {
const values = await form.validateFields();
setLoading(true);
await createBatch({
...values,
production_date: values.production_date.format('YYYY-MM-DD'),
});
message.success('批次创建成功SN码已自动生成');
setModalVisible(false);
form.resetFields();
actionRef.current?.reload();
} catch (error) {
if (error instanceof Error) {
message.error(error.message);
}
} finally {
setLoading(false);
}
};
const handleExport = async (batchId: number) => {
try {
const res = await exportBatchExcel(batchId);
const blob = new Blob([res as unknown as BlobPart], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `batch_${batchId}_sn_codes.xlsx`;
link.click();
window.URL.revokeObjectURL(url);
message.success('导出成功');
} catch (error) {
message.error('导出失败');
}
};
const handleImportModal = (batchId: number) => {
setSelectedBatchId(batchId);
setImportModalVisible(true);
};
const handleImport = async (file: File) => {
if (!selectedBatchId) return;
setImportLoading(true);
try {
const res = await importMacAddresses(selectedBatchId, file);
const { success, failed, total, errors } = res.data;
if (failed === 0) {
message.success(`导入完成:共 ${total} 条,全部成功`);
} else {
message.warning(`导入完成:成功 ${success} 条,失败 ${failed}`);
if (errors && errors.length > 0) {
Modal.error({
title: '部分导入失败',
content: (
<div style={{ maxHeight: 300, overflow: 'auto' }}>
{errors.map((err, idx) => (
<div key={idx} style={{ marginBottom: 8 }}>
{err.row} : {err.error}
</div>
))}
</div>
),
});
}
}
setImportModalVisible(false);
actionRef.current?.reload();
} catch (error) {
message.error(error instanceof Error ? error.message : '导入失败');
} finally {
setImportLoading(false);
}
};
const columns: ProColumns<DeviceBatch>[] = [
{
title: 'ID',
dataIndex: 'id',
width: 80,
search: false,
},
{
title: '设备类型',
dataIndex: ['device_type_info', 'name'],
ellipsis: true,
search: false,
},
{
title: '批次号',
dataIndex: 'batch_no',
width: 100,
},
{
title: '生产日期',
dataIndex: 'production_date',
valueType: 'date',
width: 120,
search: false,
},
{
title: '数量',
dataIndex: 'quantity',
width: 80,
search: false,
},
{
title: 'SN范围',
dataIndex: 'sn_range',
width: 280,
search: false,
render: (_, record) => {
if (!record.sn_range) return '-';
return (
<span style={{ fontSize: 12 }}>
{record.sn_range.start} ~ {record.sn_range.end}
</span>
);
},
},
{
title: '已导入MAC',
width: 120,
search: false,
render: (_, record) => {
if (!record.statistics) return '-';
const { with_mac, total } = record.statistics;
const percent = Math.round((with_mac / total) * 100);
return (
<div>
<Progress
percent={percent}
size="small"
status={percent === 100 ? 'success' : 'active'}
format={() => `${with_mac}/${total}`}
/>
</div>
);
},
},
{
title: '备注',
dataIndex: 'remark',
ellipsis: true,
search: false,
},
{
title: '创建时间',
dataIndex: 'created_at',
valueType: 'dateTime',
width: 180,
search: false,
},
{
title: '操作',
width: 220,
search: false,
render: (_, record) => (
<Space>
<Button
type="link"
size="small"
icon={<EyeOutlined />}
onClick={() => navigate(`/batches/${record.id}`)}
>
</Button>
<Button
type="link"
size="small"
icon={<DownloadOutlined />}
onClick={() => handleExport(record.id)}
>
</Button>
<Button
type="link"
size="small"
icon={<UploadOutlined />}
onClick={() => handleImportModal(record.id)}
>
</Button>
</Space>
),
},
];
return (
<div>
<ProTable<DeviceBatch>
headerTitle="批次管理"
rowKey="id"
actionRef={actionRef}
columns={columns}
request={async (params) => {
try {
const res = await getBatches({
page: params.current,
page_size: params.pageSize,
});
return {
data: res.data.items,
total: res.data.total,
success: true,
};
} catch (error) {
message.error('获取数据失败');
return { data: [], total: 0, success: false };
}
}}
toolBarRender={() => [
<Button key="add" type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
</Button>,
]}
pagination={{
defaultPageSize: 10,
showSizeChanger: true,
}}
/>
{/* 新建批次 Modal */}
<Modal
title="新建设备批次"
open={modalVisible}
onOk={handleSubmit}
onCancel={() => setModalVisible(false)}
confirmLoading={loading}
destroyOnClose
width={500}
>
<Form form={form} layout="vertical" style={{ marginTop: 24 }}>
<Form.Item
name="device_type"
label="设备类型"
rules={[{ required: true, message: '请选择设备类型' }]}
>
<Select placeholder="请选择设备类型">
{deviceTypes.map((dt) => (
<Select.Option key={dt.id} value={dt.id}>
{dt.name} ({dt.product_code})
</Select.Option>
))}
</Select>
</Form.Item>
<Form.Item
name="batch_no"
label="批次号"
rules={[{ required: true, message: '请输入批次号' }]}
>
<Input placeholder="例如: A01, B02" />
</Form.Item>
<Form.Item
name="production_date"
label="生产日期"
rules={[{ required: true, message: '请选择生产日期' }]}
>
<DatePicker style={{ width: '100%' }} />
</Form.Item>
<Form.Item
name="quantity"
label="数量"
rules={[{ required: true, message: '请输入数量' }]}
>
<InputNumber min={1} max={10000} style={{ width: '100%' }} placeholder="生成的设备数量" />
</Form.Item>
<Form.Item name="remark" label="备注">
<Input.TextArea rows={2} placeholder="可选备注信息" />
</Form.Item>
</Form>
</Modal>
{/* 导入MAC地址 Modal */}
<Modal
title="导入MAC地址"
open={importModalVisible}
onCancel={() => setImportModalVisible(false)}
footer={null}
destroyOnClose
>
<Upload.Dragger
accept=".xlsx,.xls"
maxCount={1}
beforeUpload={(file) => {
handleImport(file);
return false;
}}
disabled={importLoading}
>
<p className="ant-upload-drag-icon">
<InboxOutlined />
</p>
<p className="ant-upload-text">Excel文件到此区域</p>
<p className="ant-upload-hint">
SN码和MAC地址的Excel文件
</p>
</Upload.Dragger>
{importLoading && (
<div style={{ marginTop: 16, textAlign: 'center' }}>
<Progress type="circle" percent={50} status="active" />
<p>...</p>
</div>
)}
</Modal>
</div>
);
};
export default BatchPage;

View File

@ -0,0 +1,158 @@
import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Statistic, Typography, Spin } from 'antd';
import {
UserOutlined,
MobileOutlined,
AppstoreOutlined,
InboxOutlined,
CheckCircleOutlined,
DatabaseOutlined,
} from '@ant-design/icons';
import request from '../../api/request';
const { Title } = Typography;
interface DashboardStats {
user_count: number;
device_count: number;
device_type_count: number;
batch_count: number;
bound_device_count: number;
in_stock_device_count: number;
}
// 调用真实后端API
const getDashboardStats = async (): Promise<DashboardStats> => {
const res = await request.get<unknown, { data: DashboardStats }>('/api/admin/dashboard/stats/');
return res.data;
};
const Dashboard: React.FC = () => {
const [loading, setLoading] = useState(true);
const [stats, setStats] = useState({
user_count: 0,
device_count: 0,
device_type_count: 0,
batch_count: 0,
bound_device_count: 0,
in_stock_device_count: 0,
});
useEffect(() => {
loadStats();
}, []);
const loadStats = async () => {
try {
const data = await getDashboardStats();
setStats(data);
} catch (error) {
// 静默失败,使用默认值
} finally {
setLoading(false);
}
};
const statCards = [
{
title: '用户总数',
value: stats.user_count,
icon: <UserOutlined />,
color: '#1890ff',
},
{
title: '设备总数',
value: stats.device_count,
icon: <MobileOutlined />,
color: '#52c41a',
},
{
title: '设备类型',
value: stats.device_type_count,
icon: <AppstoreOutlined />,
color: '#722ed1',
},
{
title: '入库批次',
value: stats.batch_count,
icon: <InboxOutlined />,
color: '#fa8c16',
},
{
title: '已绑定设备',
value: stats.bound_device_count,
icon: <CheckCircleOutlined />,
color: '#13c2c2',
},
{
title: '库存设备',
value: stats.in_stock_device_count,
icon: <DatabaseOutlined />,
color: '#eb2f96',
},
];
return (
<div>
<Title level={4} style={{ marginBottom: 24 }}>
</Title>
<Spin spinning={loading}>
<Row gutter={[24, 24]}>
{statCards.map((stat, index) => (
<Col xs={24} sm={12} lg={8} xl={4} key={index}>
<Card hoverable>
<Statistic
title={stat.title}
value={stat.value}
prefix={
<span style={{ color: stat.color, fontSize: 24, marginRight: 8 }}>
{stat.icon}
</span>
}
valueStyle={{ color: stat.color }}
/>
</Card>
</Col>
))}
</Row>
</Spin>
<Row gutter={[24, 24]} style={{ marginTop: 24 }}>
<Col xs={24} lg={12}>
<Card title="设备状态分布" style={{ height: 300 }}>
<div style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: 200,
color: '#999',
flexDirection: 'column',
}}>
<div style={{ fontSize: 48, marginBottom: 16 }}>📊</div>
<div>...</div>
</div>
</Card>
</Col>
<Col xs={24} lg={12}>
<Card title="快捷操作" style={{ height: 300 }}>
<div style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: 200,
color: '#999',
flexDirection: 'column',
}}>
<div style={{ fontSize: 48, marginBottom: 16 }}>🚀</div>
<div>使</div>
</div>
</Card>
</Col>
</Row>
</div>
);
};
export default Dashboard;

View File

@ -0,0 +1,95 @@
import React from 'react';
import { Tag, message } from 'antd';
import { ProTable } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components';
import { getBatches, getBatchDevices } from '../../api/batch';
import type { Device } from '../../api/batch';
const DevicePage: React.FC = () => {
const columns: ProColumns<Device>[] = [
{
title: 'SN码',
dataIndex: 'sn',
copyable: true,
width: 280,
},
{
title: 'MAC地址',
dataIndex: 'mac_address',
width: 160,
search: false,
render: (_, record) => record.mac_address || <Tag color="orange"></Tag>,
},
{
title: '设备类型',
dataIndex: ['device_type', 'name'],
ellipsis: true,
search: false,
},
{
title: '状态',
dataIndex: 'status',
width: 100,
valueEnum: {
in_stock: { text: '库存中', status: 'Default' },
bound: { text: '已绑定', status: 'Success' },
offline: { text: '离线', status: 'Error' },
},
},
{
title: '创建时间',
dataIndex: 'created_at',
valueType: 'dateTime',
width: 180,
search: false,
},
];
return (
<div>
<ProTable<Device>
headerTitle="设备列表"
rowKey="id"
columns={columns}
request={async (params) => {
try {
// 先获取所有批次,再获取设备
// 实际应该有一个单独的设备列表API
const batchRes = await getBatches({ page_size: 100 });
const batches = batchRes.data.items;
// 合并所有批次的设备
const allDevices: Device[] = [];
for (const batch of batches.slice(0, 5)) { // 只取前5个批次
try {
const deviceRes = await getBatchDevices(batch.id, { page_size: 50 });
allDevices.push(...deviceRes.data.items);
} catch {
// 忽略单个批次的错误
}
}
// 简单分页
const start = ((params.current || 1) - 1) * (params.pageSize || 20);
const end = start + (params.pageSize || 20);
return {
data: allDevices.slice(start, end),
total: allDevices.length,
success: true,
};
} catch (error) {
message.error('获取数据失败');
return { data: [], total: 0, success: false };
}
}}
pagination={{
defaultPageSize: 20,
showSizeChanger: true,
}}
/>
</div>
);
};
export default DevicePage;

View File

@ -0,0 +1,202 @@
import React, { useState } from 'react';
import { Button, message, Modal, Form, Input, Space, Tag, Popconfirm } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { ProTable } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components';
import {
getDeviceTypes,
createDeviceType,
updateDeviceType,
deleteDeviceType,
} from '../../api/deviceType';
import type { DeviceType } from '../../api/deviceType';
const DeviceTypePage: React.FC = () => {
const [modalVisible, setModalVisible] = useState(false);
const [editingRecord, setEditingRecord] = useState<DeviceType | null>(null);
const [form] = Form.useForm();
const [loading, setLoading] = useState(false);
const handleAdd = () => {
setEditingRecord(null);
form.resetFields();
setModalVisible(true);
};
const handleEdit = (record: DeviceType) => {
setEditingRecord(record);
form.setFieldsValue(record);
setModalVisible(true);
};
const handleDelete = async (id: number) => {
try {
await deleteDeviceType(id);
message.success('删除成功');
} catch (error) {
message.error(error instanceof Error ? error.message : '删除失败');
}
};
const handleSubmit = async () => {
try {
const values = await form.validateFields();
setLoading(true);
if (editingRecord) {
await updateDeviceType(editingRecord.id, values);
message.success('更新成功');
} else {
await createDeviceType(values);
message.success('创建成功');
}
setModalVisible(false);
form.resetFields();
} catch (error) {
if (error instanceof Error) {
message.error(error.message);
}
} finally {
setLoading(false);
}
};
const columns: ProColumns<DeviceType>[] = [
{
title: 'ID',
dataIndex: 'id',
width: 80,
search: false,
},
{
title: '品牌',
dataIndex: 'brand',
width: 100,
},
{
title: '产品代号',
dataIndex: 'product_code',
width: 150,
},
{
title: '名称',
dataIndex: 'name',
ellipsis: true,
},
{
title: '联网要求',
dataIndex: 'is_network_required',
width: 100,
search: false,
render: (_, record) => (
<Tag color={record.is_network_required ? 'blue' : 'default'}>
{record.is_network_required ? '联网' : '离线'}
</Tag>
),
},
{
title: '创建时间',
dataIndex: 'created_at',
valueType: 'dateTime',
width: 180,
search: false,
},
{
title: '操作',
width: 150,
search: false,
render: (_, record) => (
<Space>
<Button
type="link"
size="small"
icon={<EditOutlined />}
onClick={() => handleEdit(record)}
>
</Button>
<Popconfirm
title="确定删除该设备类型吗?"
onConfirm={() => handleDelete(record.id)}
>
<Button type="link" size="small" danger icon={<DeleteOutlined />}>
</Button>
</Popconfirm>
</Space>
),
},
];
return (
<div>
<ProTable<DeviceType>
headerTitle="设备类型管理"
rowKey="id"
columns={columns}
request={async (params) => {
try {
const res = await getDeviceTypes({
page: params.current,
page_size: params.pageSize,
});
return {
data: res.data.items,
total: res.data.total,
success: true,
};
} catch (error) {
message.error('获取数据失败');
return { data: [], total: 0, success: false };
}
}}
toolBarRender={() => [
<Button key="add" type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
</Button>,
]}
pagination={{
defaultPageSize: 10,
showSizeChanger: true,
}}
/>
<Modal
title={editingRecord ? '编辑设备类型' : '新增设备类型'}
open={modalVisible}
onOk={handleSubmit}
onCancel={() => setModalVisible(false)}
confirmLoading={loading}
destroyOnClose
>
<Form form={form} layout="vertical" style={{ marginTop: 24 }}>
<Form.Item
name="brand"
label="品牌"
rules={[{ required: true, message: '请输入品牌' }]}
>
<Input placeholder="例如: AL" />
</Form.Item>
<Form.Item
name="product_code"
label="产品代号"
rules={[{ required: true, message: '请输入产品代号' }]}
extra="以 -ON 结尾表示联网设备,以 -OFF 结尾表示离线设备"
>
<Input placeholder="例如: DZBJ-ON (联网) 或 DZBJ-OFF (离线)" />
</Form.Item>
<Form.Item
name="name"
label="名称"
rules={[{ required: true, message: '请输入名称' }]}
>
<Input placeholder="例如: 电子吧唧-联网版" />
</Form.Item>
</Form>
</Modal>
</div>
);
};
export default DeviceTypePage;

97
src/pages/Login/index.tsx Normal file
View File

@ -0,0 +1,97 @@
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Form, Input, Button, Card, message, Typography } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { login } from '../../api/auth';
import { useAuthStore } from '../../store/useAuthStore';
const { Title } = Typography;
const LoginPage: React.FC = () => {
const [loading, setLoading] = useState(false);
const navigate = useNavigate();
const { setAuth } = useAuthStore();
const onFinish = async (values: { username: string; password: string }) => {
setLoading(true);
try {
const res = await login(values);
setAuth(res.data.token.access, res.data.token.refresh, res.data.admin);
message.success('登录成功');
navigate('/dashboard');
} catch (error) {
message.error(error instanceof Error ? error.message : '登录失败');
} finally {
setLoading(false);
}
};
return (
<div
style={{
minHeight: '100vh',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
}}
>
<Card
style={{
width: 400,
boxShadow: '0 20px 60px rgba(0,0,0,0.3)',
borderRadius: 16,
}}
bordered={false}
>
<div style={{ textAlign: 'center', marginBottom: 32 }}>
<Title level={2} style={{ marginBottom: 8, color: '#1890ff' }}>
RTC
</Title>
<Typography.Text type="secondary"> · · </Typography.Text>
</div>
<Form
name="login"
onFinish={onFinish}
size="large"
autoComplete="off"
>
<Form.Item
name="username"
rules={[{ required: true, message: '请输入用户名' }]}
>
<Input
prefix={<UserOutlined style={{ color: '#bfbfbf' }} />}
placeholder="用户名"
/>
</Form.Item>
<Form.Item
name="password"
rules={[{ required: true, message: '请输入密码' }]}
>
<Input.Password
prefix={<LockOutlined style={{ color: '#bfbfbf' }} />}
placeholder="密码"
/>
</Form.Item>
<Form.Item style={{ marginBottom: 0 }}>
<Button
type="primary"
htmlType="submit"
loading={loading}
block
style={{ height: 48, fontSize: 16 }}
>
</Button>
</Form.Item>
</Form>
</Card>
</div>
);
};
export default LoginPage;

120
src/pages/User/index.tsx Normal file
View File

@ -0,0 +1,120 @@
import React from 'react';
import { Button, message, Tag, Space, Popconfirm } from 'antd';
import { ProTable } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components';
import { getAppUsers, toggleAppUserStatus } from '../../api/user';
import type { AppUser } from '../../api/user';
const UserPage: React.FC = () => {
const handleToggleStatus = async (id: number, currentStatus: boolean) => {
try {
await toggleAppUserStatus(id);
message.success(currentStatus ? '已禁用' : '已启用');
} catch (error) {
message.error(error instanceof Error ? error.message : '操作失败');
}
};
const columns: ProColumns<AppUser>[] = [
{
title: 'ID',
dataIndex: 'id',
width: 80,
search: false,
},
{
title: '手机号',
dataIndex: 'phone',
width: 140,
render: (_, record) => {
// 手机号脱敏
const phone = record.phone;
return phone ? phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '-';
},
},
{
title: '昵称',
dataIndex: 'nickname',
ellipsis: true,
},
{
title: '智能体数',
dataIndex: 'spirit_count',
width: 100,
search: false,
},
{
title: '设备数',
dataIndex: 'device_count',
width: 100,
search: false,
},
{
title: '状态',
dataIndex: 'is_active',
width: 80,
search: false,
render: (_, record) => (
<Tag color={record.is_active ? 'green' : 'red'}>
{record.is_active ? '正常' : '禁用'}
</Tag>
),
},
{
title: '注册时间',
dataIndex: 'created_at',
valueType: 'dateTime',
width: 180,
search: false,
},
{
title: '操作',
width: 100,
search: false,
render: (_, record) => (
<Space>
<Popconfirm
title={record.is_active ? '确定禁用该用户吗?' : '确定启用该用户吗?'}
onConfirm={() => handleToggleStatus(record.id, record.is_active)}
>
<Button type="link" size="small" danger={record.is_active}>
{record.is_active ? '禁用' : '启用'}
</Button>
</Popconfirm>
</Space>
),
},
];
return (
<ProTable<AppUser>
headerTitle="用户管理"
rowKey="id"
columns={columns}
request={async (params) => {
try {
const res = await getAppUsers({
page: params.current,
page_size: params.pageSize,
phone: params.phone,
nickname: params.nickname,
});
return {
data: res.data.items,
total: res.data.total,
success: true,
};
} catch (error) {
message.error('获取数据失败');
return { data: [], total: 0, success: false };
}
}}
pagination={{
defaultPageSize: 10,
showSizeChanger: true,
}}
/>
);
};
export default UserPage;

79
src/routes/index.tsx Normal file
View File

@ -0,0 +1,79 @@
import React from 'react';
import { createBrowserRouter, Navigate } from 'react-router-dom';
import MainLayout from '../components/Layout';
import LoginPage from '../pages/Login';
import Dashboard from '../pages/Dashboard';
import DeviceTypePage from '../pages/DeviceType';
import BatchPage from '../pages/Batch';
import BatchDetail from '../pages/Batch/Detail';
import DevicePage from '../pages/Device';
import UserPage from '../pages/User';
import AdminPage from '../pages/Admin';
import { useAuthStore } from '../store/useAuthStore';
// 路由守卫组件
const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const { isAuthenticated } = useAuthStore();
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
return <>{children}</>;
};
// 创建路由
const router = createBrowserRouter([
{
path: '/login',
element: <LoginPage />,
},
{
path: '/',
element: (
<ProtectedRoute>
<MainLayout />
</ProtectedRoute>
),
children: [
{
index: true,
element: <Navigate to="/dashboard" replace />,
},
{
path: 'dashboard',
element: <Dashboard />,
},
{
path: 'device-types',
element: <DeviceTypePage />,
},
{
path: 'batches',
element: <BatchPage />,
},
{
path: 'batches/:id',
element: <BatchDetail />,
},
{
path: 'devices',
element: <DevicePage />,
},
{
path: 'users',
element: <UserPage />,
},
{
path: 'admins',
element: <AdminPage />,
},
],
},
{
path: '*',
element: <Navigate to="/dashboard" replace />,
},
]);
export default router;

59
src/store/useAuthStore.ts Normal file
View File

@ -0,0 +1,59 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { AdminInfo } from '../api/auth';
interface AuthState {
token: string | null;
refreshToken: string | null;
adminInfo: AdminInfo | null;
isAuthenticated: boolean;
// Actions
setAuth: (token: string, refreshToken: string, adminInfo: AdminInfo) => void;
setAdminInfo: (adminInfo: AdminInfo) => void;
logout: () => void;
}
export const useAuthStore = create<AuthState>()(
persist(
(set) => ({
token: null,
refreshToken: null,
adminInfo: null,
isAuthenticated: false,
setAuth: (token, refreshToken, adminInfo) => {
localStorage.setItem('admin_token', token);
set({
token,
refreshToken,
adminInfo,
isAuthenticated: true,
});
},
setAdminInfo: (adminInfo) => {
set({ adminInfo });
},
logout: () => {
localStorage.removeItem('admin_token');
set({
token: null,
refreshToken: null,
adminInfo: null,
isAuthenticated: false,
});
},
}),
{
name: 'auth-storage',
partialize: (state) => ({
token: state.token,
refreshToken: state.refreshToken,
adminInfo: state.adminInfo,
isAuthenticated: state.isAuthenticated,
}),
}
)
);

28
tsconfig.app.json Normal file
View File

@ -0,0 +1,28 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

7
tsconfig.json Normal file
View File

@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

26
tsconfig.node.json Normal file
View File

@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

17
vite.config.ts Normal file
View File

@ -0,0 +1,17 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
server: {
port: 5174,
proxy: {
'/api': {
target: 'http://localhost:8001',
changeOrigin: true,
secure: false,
},
},
},
})