Add frontend and backend as main repo

This commit is contained in:
mina_yiban 2025-11-21 16:30:46 +08:00
parent 861e35602a
commit 6484e5e44f
32 changed files with 20073 additions and 1 deletions

@ -1 +0,0 @@
Subproject commit 204654c6c0b90f8e573326c050420c41ff331e5c

23
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

46
frontend/README.md Normal file
View File

@ -0,0 +1,46 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

18815
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

50
frontend/package.json Normal file
View File

@ -0,0 +1,50 @@
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"@ant-design/icons": "^6.1.0",
"@tanstack/react-query": "^5.90.10",
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.126",
"@types/react": "^19.2.5",
"@types/react-dom": "^19.2.3",
"antd": "^5.28.1",
"axios": "^1.13.2",
"dayjs": "^1.11.19",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-router-dom": "^7.9.6",
"react-scripts": "5.0.1",
"typescript": "^4.9.5",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

BIN
frontend/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

BIN
frontend/public/logo192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

BIN
frontend/public/logo512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

76
frontend/src/App.tsx Normal file
View File

@ -0,0 +1,76 @@
import { Layout, Menu, Space, Button } from 'antd';
import { Link, Outlet, Route, Routes, useLocation, useNavigate } from 'react-router-dom';
import HomePage from './pages/Home';
import ProductDetail from './pages/ProductDetail';
import CheckoutPage from './pages/Checkout';
import LoginPage from './pages/Login';
import RegisterPage from './pages/Register';
import AdminLayout from './pages/admin/AdminLayout';
import ProductManagement from './pages/admin/ProductManagement';
import OrderManagement from './pages/admin/OrderManagement';
import MemberManagement from './pages/admin/MemberManagement';
import PointsManagement from './pages/admin/PointsManagement';
import TicketManagement from './pages/admin/TicketManagement';
import { useAuth } from './context/AuthContext';
const { Header, Content, Footer } = Layout;
const PublicLayout = () => {
const { user, logout } = useAuth();
const navigate = useNavigate();
const location = useLocation();
const isAdminPage = location.pathname.startsWith('/admin');
if (isAdminPage) {
return <Outlet />;
}
return (
<Layout style={{ minHeight: '100vh' }}>
<Header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<Menu theme="dark" mode="horizontal" selectable={false} items={[{ key: 'home', label: <Link to="/"></Link> }]} />
<Space>
{user ? (
<>
<span style={{ color: '#fff' }}>{user.username}</span>
<Button onClick={() => navigate('/admin/products')}></Button>
<Button onClick={logout}>退</Button>
</>
) : (
<>
<Button onClick={() => navigate('/login')}></Button>
<Button onClick={() => navigate('/register')}></Button>
</>
)}
</Space>
</Header>
<Content style={{ padding: 24 }}>
<Outlet />
</Content>
<Footer style={{ textAlign: 'center' }}> · </Footer>
</Layout>
);
};
function App() {
return (
<Routes>
<Route element={<PublicLayout />}>
<Route path="/" element={<HomePage />} />
<Route path="/product/:id" element={<ProductDetail />} />
<Route path="/checkout/:id" element={<CheckoutPage />} />
<Route path="/login" element={<LoginPage />} />
<Route path="/register" element={<RegisterPage />} />
</Route>
<Route path="/admin" element={<AdminLayout />}>
<Route path="products" element={<ProductManagement />} />
<Route path="orders" element={<OrderManagement />} />
<Route path="members" element={<MemberManagement />} />
<Route path="points" element={<PointsManagement />} />
<Route path="tickets" element={<TicketManagement />} />
</Route>
</Routes>
);
}
export default App;

View File

@ -0,0 +1,23 @@
import axios from 'axios';
const client = axios.create({
baseURL: 'http://localhost:8080/api',
timeout: 10000,
});
client.interceptors.request.use((config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers = config.headers ?? {};
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
});
export interface ApiResponse<T> {
success: boolean;
data: T;
message?: string;
}
export default client;

46
frontend/src/api/index.ts Normal file
View File

@ -0,0 +1,46 @@
import client, { ApiResponse } from './client';
import { Member, Order, PointRecord, Product, Ticket, UserInfo } from '../types';
const unwrap = <T>(promise: Promise<{ data: ApiResponse<T> }>) => promise.then((res) => res.data.data);
export const fetchHome = () => unwrap(client.get<ApiResponse<any>>('/home'));
export const fetchProducts = () => unwrap(client.get<ApiResponse<Product[]>>('/products'));
export const fetchProduct = (id: string) => unwrap(client.get<ApiResponse<Product>>(`/products/${id}`));
export const createOrder = (payload: Partial<Order>) => unwrap(client.post<ApiResponse<Order>>('/orders', payload));
export const payDemo = (payload: { orderId: number; amount: number; method: string }) => unwrap(client.post<ApiResponse<any>>('/pay/demo', payload));
export const login = (payload: { username: string; password: string }) => unwrap(client.post<ApiResponse<{ token: string; user: UserInfo }>>('/auth/login', payload));
export const register = (payload: { username: string; password: string; email?: string }) => unwrap(client.post<ApiResponse<any>>('/auth/register', payload));
export const adminProducts = {
list: () => unwrap(client.get<ApiResponse<Product[]>>('/admin/products')),
create: (data: Partial<Product>) => unwrap(client.post<ApiResponse<Product>>('/admin/products', data)),
update: (id: number, data: Partial<Product>) => unwrap(client.put<ApiResponse<Product>>(`/admin/products/${id}`, data)),
remove: (id: number) => unwrap(client.delete<ApiResponse<any>>(`/admin/products/${id}`)),
};
export const adminOrders = {
list: () => unwrap(client.get<ApiResponse<Order[]>>('/admin/orders')),
update: (id: number, data: Partial<Order>) => unwrap(client.put<ApiResponse<Order>>(`/admin/orders/${id}`, data)),
remove: (id: number) => unwrap(client.delete<ApiResponse<any>>(`/admin/orders/${id}`)),
};
export const adminMembers = {
list: () => unwrap(client.get<ApiResponse<Member[]>>('/admin/members')),
create: (data: Partial<Member>) => unwrap(client.post<ApiResponse<Member>>('/admin/members', data)),
update: (id: number, data: Partial<Member>) => unwrap(client.put<ApiResponse<Member>>(`/admin/members/${id}`, data)),
remove: (id: number) => unwrap(client.delete<ApiResponse<any>>(`/admin/members/${id}`)),
};
export const adminPoints = {
list: () => unwrap(client.get<ApiResponse<PointRecord[]>>('/admin/points')),
create: (data: Partial<PointRecord>) => unwrap(client.post<ApiResponse<PointRecord>>('/admin/points', data)),
remove: (id: number) => unwrap(client.delete<ApiResponse<any>>(`/admin/points/${id}`)),
};
export const adminTickets = {
list: () => unwrap(client.get<ApiResponse<Ticket[]>>('/admin/tickets')),
create: (data: Partial<Ticket>) => unwrap(client.post<ApiResponse<Ticket>>('/admin/tickets', data)),
update: (id: number, data: Partial<Ticket>) => unwrap(client.put<ApiResponse<Ticket>>(`/admin/tickets/${id}`, data)),
remove: (id: number) => unwrap(client.delete<ApiResponse<any>>(`/admin/tickets/${id}`)),
};

View File

@ -0,0 +1,57 @@
import React, { createContext, useContext, useEffect, useState } from 'react';
import { UserInfo } from '../types';
import { login as loginApi } from '../api';
interface AuthContextValue {
user: UserInfo | null;
token: string | null;
login: (username: string, password: string) => Promise<void>;
logout: () => void;
}
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [user, setUser] = useState<UserInfo | null>(() => {
const stored = localStorage.getItem('user');
return stored ? JSON.parse(stored) : null;
});
const [token, setToken] = useState<string | null>(() => localStorage.getItem('token'));
useEffect(() => {
if (user) {
localStorage.setItem('user', JSON.stringify(user));
} else {
localStorage.removeItem('user');
}
}, [user]);
useEffect(() => {
if (token) {
localStorage.setItem('token', token);
} else {
localStorage.removeItem('token');
}
}, [token]);
const login = async (username: string, password: string) => {
const data = await loginApi({ username, password });
setUser(data.user);
setToken(data.token);
};
const logout = () => {
setUser(null);
setToken(null);
};
return <AuthContext.Provider value={{ user, token, login, logout }}>{children}</AuthContext.Provider>;
};
export const useAuth = () => {
const ctx = useContext(AuthContext);
if (!ctx) {
throw new Error('useAuth must be used within AuthProvider');
}
return ctx;
};

View File

@ -0,0 +1,33 @@
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
const IDLE_LIMIT = 60 * 1000;
export const useIdleLogout = () => {
const navigate = useNavigate();
const { user, logout } = useAuth();
useEffect(() => {
if (!user) return;
let timer: NodeJS.Timeout;
const reset = () => {
clearTimeout(timer);
timer = setTimeout(() => {
logout();
window.alert('登录超时,已自动登出');
navigate('/');
}, IDLE_LIMIT);
};
const events = ['click', 'mousemove', 'keypress', 'scroll'];
events.forEach((evt) => window.addEventListener(evt, reset));
reset();
return () => {
clearTimeout(timer);
events.forEach((evt) => window.removeEventListener(evt, reset));
};
}, [user, logout, navigate]);
};

9
frontend/src/index.css Normal file
View File

@ -0,0 +1,9 @@
body {
margin: 0;
font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
background-color: #f5f7fa;
}
#root {
min-height: 100vh;
}

20
frontend/src/index.tsx Normal file
View File

@ -0,0 +1,20 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { ConfigProvider } from 'antd';
import App from './App';
import './index.css';
import { AuthProvider } from './context/AuthContext';
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
<React.StrictMode>
<BrowserRouter>
<ConfigProvider theme={{ token: { colorPrimary: '#b87a36' } }}>
<AuthProvider>
<App />
</AuthProvider>
</ConfigProvider>
</BrowserRouter>
</React.StrictMode>
);

View File

@ -0,0 +1,72 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Card, Form, Input, InputNumber, Select, Button, message } from 'antd';
import { createOrder, fetchProduct, payDemo } from '../api';
import { Product } from '../types';
const CheckoutPage = () => {
const { id } = useParams();
const [product, setProduct] = useState<Product | null>(null);
const [loading, setLoading] = useState(false);
const navigate = useNavigate();
const [form] = Form.useForm();
const quantity = Form.useWatch('quantity', form) ?? 1;
const amount = (product?.price || 0) * quantity;
useEffect(() => {
if (id) {
fetchProduct(id).then(setProduct);
}
}, [id]);
const onFinish = async (values: any) => {
try {
setLoading(true);
const order = await createOrder({
customerName: values.customerName,
productId: product?.id,
quantity: values.quantity,
amount,
status: '待支付',
});
await payDemo({ orderId: order.id, amount: order.amount, method: values.payMethod });
message.success('支付流程演示完成');
navigate('/');
} finally {
setLoading(false);
}
};
return (
<Card title="支付与采购">
<Form form={form} layout="vertical" onFinish={onFinish} initialValues={{ quantity: 1, payMethod: 'bank' }}>
<Form.Item label="商品" shouldUpdate>
<Input value={product?.name || '自选商品'} disabled />
</Form.Item>
<Form.Item name="customerName" label="客户名称" rules={[{ required: true, message: '请输入采购方名称' }]}>
<Input placeholder="如:星咖科技总部" />
</Form.Item>
<Form.Item name="quantity" label="订购数量" rules={[{ required: true }]}>
<InputNumber min={1} style={{ width: '100%' }} />
</Form.Item>
<Form.Item label="预计金额">
<Input value={`${amount.toLocaleString()}`} disabled />
</Form.Item>
<Form.Item name="payMethod" label="支付方式" rules={[{ required: true }]}>
<Select
options={[
{ value: 'bank', label: '企业对公转账' },
{ value: 'lease', label: '金融租赁' },
{ value: 'credit', label: '授信分期' },
]}
/>
</Form.Item>
<Button type="primary" htmlType="submit" loading={loading}>
</Button>
</Form>
</Card>
);
};
export default CheckoutPage;

View File

@ -0,0 +1,69 @@
import { useEffect, useState } from 'react';
import { Button, Card, Col, Row, Space, Typography } from 'antd';
import { useNavigate } from 'react-router-dom';
import { fetchHome } from '../api';
import { Product } from '../types';
const { Title, Paragraph } = Typography;
interface HomeData {
hero: { title: string; subtitle: string };
categories: { name: string; description: string }[];
products: Product[];
}
const HomePage = () => {
const [data, setData] = useState<HomeData | null>(null);
const navigate = useNavigate();
useEffect(() => {
fetchHome().then(setData);
}, []);
return (
<Space direction="vertical" size="large" style={{ width: '100%' }}>
<Card style={{ background: '#001529', color: '#fff' }}>
<Title level={2} style={{ color: '#fff' }}>
{data?.hero.title || '商用咖啡机一站式平台'}
</Title>
<Paragraph style={{ color: '#d6e4ff' }}>{data?.hero.subtitle || '覆盖采购、运维、会员体系的全链路解决方案'}</Paragraph>
<Button type="primary" size="large" onClick={() => navigate('/login')}>
</Button>
</Card>
<Title level={3}></Title>
<Row gutter={[16, 16]}>
{data?.categories.map((category) => (
<Col span={8} key={category.name}>
<Card hoverable title={category.name}>
{category.description}
</Card>
</Col>
))}
</Row>
<Title level={3}></Title>
<Row gutter={[16, 16]}>
{data?.products.map((product) => (
<Col span={8} key={product.id}>
<Card hoverable cover={<div style={{ height: 160, background: '#f5f5f5' }} />}>
<Title level={4}>{product.name}</Title>
<Paragraph ellipsis={{ rows: 2 }}>{product.description}</Paragraph>
<Space>
<Button type="link" onClick={() => navigate(`/product/${product.id}`)}>
</Button>
<Button type="primary" onClick={() => navigate(`/checkout/${product.id}`)}>
</Button>
</Space>
</Card>
</Col>
))}
</Row>
</Space>
);
};
export default HomePage;

View File

@ -0,0 +1,40 @@
import { Card, Form, Input, Button, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
const LoginPage = () => {
const { login } = useAuth();
const navigate = useNavigate();
const onFinish = async (values: any) => {
try {
await login(values.username, values.password);
message.success('登录成功');
navigate('/admin/products');
} catch (error: any) {
message.error(error?.response?.data?.message || '登录失败');
}
};
return (
<Card title="商家后台登录" style={{ maxWidth: 420, margin: '0 auto' }}>
<Form layout="vertical" onFinish={onFinish} initialValues={{ username: 'demo', password: 'demo123' }}>
<Form.Item name="username" label="账号" rules={[{ required: true }]}
extra="演示账号demo / demo123">
<Input placeholder="请输入账号" />
</Form.Item>
<Form.Item name="password" label="密码" rules={[{ required: true }]}>
<Input.Password placeholder="请输入密码" />
</Form.Item>
<Button type="primary" htmlType="submit" block>
</Button>
<Button type="link" block onClick={() => navigate('/register')}>
</Button>
</Form>
</Card>
);
};
export default LoginPage;

View File

@ -0,0 +1,38 @@
import { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Descriptions, Button, Typography } from 'antd';
import { fetchProduct } from '../api';
import { Product } from '../types';
const ProductDetail = () => {
const { id } = useParams();
const [product, setProduct] = useState<Product | null>(null);
const navigate = useNavigate();
useEffect(() => {
if (id) {
fetchProduct(id).then(setProduct);
}
}, [id]);
if (!product) return <div>...</div>;
return (
<Card title={product.name}>
<Descriptions column={1} bordered>
<Descriptions.Item label="分类">{product.category}</Descriptions.Item>
<Descriptions.Item label="售价">{product.price.toLocaleString()}</Descriptions.Item>
<Descriptions.Item label="库存">{product.inventory} </Descriptions.Item>
<Descriptions.Item label="介绍">{product.description}</Descriptions.Item>
</Descriptions>
<Typography.Paragraph style={{ marginTop: 24 }}>
</Typography.Paragraph>
<Button type="primary" onClick={() => navigate(`/checkout/${product.id}`)}>
</Button>
</Card>
);
};
export default ProductDetail;

View File

@ -0,0 +1,42 @@
import { Card, Form, Input, Button, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { register as registerApi } from '../api';
const RegisterPage = () => {
const navigate = useNavigate();
const onFinish = async (values: any) => {
try {
await registerApi(values);
message.success('注册成功,请登录');
navigate('/login');
} catch (error: any) {
message.error(error?.response?.data?.message || '注册失败');
}
};
return (
<Card title="创建商家账号" style={{ maxWidth: 420, margin: '0 auto' }}>
<Form layout="vertical" onFinish={onFinish}>
<Form.Item name="username" label="账号" rules={[{ required: true, min: 3 }]}
extra="用于登录后台的管理员账号">
<Input />
</Form.Item>
<Form.Item name="email" label="邮箱">
<Input />
</Form.Item>
<Form.Item name="password" label="密码" rules={[{ required: true, min: 6 }]}>
<Input.Password />
</Form.Item>
<Button type="primary" htmlType="submit" block>
</Button>
<Button type="link" block onClick={() => navigate('/login')}>
</Button>
</Form>
</Card>
);
};
export default RegisterPage;

View File

@ -0,0 +1,51 @@
import { Layout, Menu, Button } from 'antd';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import { useAuth } from '../../context/AuthContext';
import { useIdleLogout } from '../../hooks/useIdleLogout';
const { Header, Sider, Content } = Layout;
const items = [
{ key: '/admin/products', label: '商品管理' },
{ key: '/admin/orders', label: '订单管理' },
{ key: '/admin/members', label: '会员管理' },
{ key: '/admin/points', label: '积分管理' },
{ key: '/admin/tickets', label: '工单管理' },
];
const AdminLayout = () => {
const navigate = useNavigate();
const location = useLocation();
const { user, logout } = useAuth();
useIdleLogout();
if (!user) {
navigate('/login');
return null;
}
return (
<Layout style={{ minHeight: '100vh' }}>
<Sider theme="light">
<div style={{ padding: 16, fontWeight: 600 }}></div>
<Menu
mode="inline"
selectedKeys={[location.pathname]}
items={items}
onClick={(e) => navigate(e.key)}
/>
</Sider>
<Layout>
<Header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: '#fff' }}>
<div>{user.username}</div>
<Button onClick={() => logout()}>退</Button>
</Header>
<Content style={{ padding: 24 }}>
<Outlet />
</Content>
</Layout>
</Layout>
);
};
export default AdminLayout;

View File

@ -0,0 +1,90 @@
import { useEffect, useState } from 'react';
import { Button, Form, Input, InputNumber, Modal, Space, Table, message } from 'antd';
import { Member } from '../../types';
import { adminMembers } from '../../api';
const MemberManagement = () => {
const [members, setMembers] = useState<Member[]>([]);
const [open, setOpen] = useState(false);
const [editing, setEditing] = useState<Member | null>(null);
const [form] = Form.useForm();
const load = () => adminMembers.list().then(setMembers);
useEffect(() => {
load();
}, []);
const submit = async () => {
const values = await form.validateFields();
if (editing) {
await adminMembers.update(editing.id, values);
} else {
await adminMembers.create(values);
}
message.success('操作成功');
setOpen(false);
setEditing(null);
form.resetFields();
load();
};
const remove = async (record: Member) => {
await adminMembers.remove(record.id);
message.success('删除成功');
load();
};
return (
<>
<Space style={{ marginBottom: 16 }}>
<Button type="primary" onClick={() => setOpen(true)}>
</Button>
</Space>
<Table
rowKey="id"
dataSource={members}
columns={[
{ title: '名称', dataIndex: 'name' },
{ title: '邮箱', dataIndex: 'email' },
{ title: '等级', dataIndex: 'tier' },
{ title: '积分', dataIndex: 'points' },
{
title: '操作',
render: (_, record) => (
<Space>
<Button type="link" onClick={() => { setEditing(record); setOpen(true); form.setFieldsValue(record); }}>
</Button>
<Button type="link" danger onClick={() => remove(record)}>
</Button>
</Space>
),
},
]}
/>
<Modal open={open} onCancel={() => { setOpen(false); setEditing(null); }} onOk={submit} title={editing ? '编辑会员' : '新增会员'}>
<Form form={form} layout="vertical">
<Form.Item name="name" label="名称" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="email" label="邮箱">
<Input />
</Form.Item>
<Form.Item name="phone" label="电话">
<Input />
</Form.Item>
<Form.Item name="tier" label="等级" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="points" label="积分" rules={[{ required: true }]}>
<InputNumber min={0} style={{ width: '100%' }} />
</Form.Item>
</Form>
</Modal>
</>
);
};
export default MemberManagement;

View File

@ -0,0 +1,61 @@
import { useEffect, useState } from 'react';
import { Table, Select, Space, Button, message } from 'antd';
import { Order } from '../../types';
import { adminOrders } from '../../api';
const OrderManagement = () => {
const [orders, setOrders] = useState<Order[]>([]);
const load = () => adminOrders.list().then(setOrders);
useEffect(() => {
load();
}, []);
const updateStatus = async (order: Order, status: string) => {
await adminOrders.update(order.id, { ...order, status });
message.success('状态已更新');
load();
};
const remove = async (order: Order) => {
await adminOrders.remove(order.id);
message.success('订单已删除');
load();
};
return (
<Table
rowKey="id"
dataSource={orders}
columns={[
{ title: '订单号', dataIndex: 'orderNumber' },
{ title: '客户', dataIndex: 'customerName' },
{ title: '金额', dataIndex: 'amount' },
{ title: '状态', dataIndex: 'status' },
{
title: '操作',
render: (_, record) => (
<Space>
<Select
value={record.status}
style={{ width: 140 }}
options={[
{ value: '待支付', label: '待支付' },
{ value: '生产中', label: '生产中' },
{ value: '已发货', label: '已发货' },
]}
onChange={(value) => updateStatus(record, value)}
/>
<Button type="link" danger onClick={() => remove(record)}>
</Button>
</Space>
),
},
]}
/>
);
};
export default OrderManagement;

View File

@ -0,0 +1,83 @@
import { useEffect, useState } from 'react';
import { Button, Form, InputNumber, Modal, Select, Space, Table, message } from 'antd';
import { PointRecord, Member } from '../../types';
import { adminMembers, adminPoints } from '../../api';
const PointsManagement = () => {
const [records, setRecords] = useState<PointRecord[]>([]);
const [members, setMembers] = useState<Member[]>([]);
const [open, setOpen] = useState(false);
const [form] = Form.useForm();
const load = () => adminPoints.list().then(setRecords);
useEffect(() => {
load();
adminMembers.list().then(setMembers);
}, []);
const submit = async () => {
const values = await form.validateFields();
await adminPoints.create(values);
message.success('积分记录已添加');
setOpen(false);
form.resetFields();
load();
};
const remove = async (record: PointRecord) => {
await adminPoints.remove(record.id);
message.success('已删除');
load();
};
return (
<>
<Space style={{ marginBottom: 16 }}>
<Button type="primary" onClick={() => setOpen(true)}>
</Button>
</Space>
<Table
rowKey="id"
dataSource={records}
columns={[
{ title: '会员ID', dataIndex: 'memberId' },
{ title: '变动', dataIndex: 'change' },
{ title: '原因', dataIndex: 'reason' },
{
title: '操作',
render: (_, record) => (
<Button type="link" danger onClick={() => remove(record)}>
</Button>
),
},
]}
/>
<Modal open={open} onCancel={() => setOpen(false)} onOk={submit} title="新增积分记录">
<Form form={form} layout="vertical">
<Form.Item name="memberId" label="会员" rules={[{ required: true }]}>
<Select
options={members.map((m) => ({ value: m.id, label: `${m.name} (${m.points}分)` }))}
/>
</Form.Item>
<Form.Item name="change" label="积分变化" rules={[{ required: true }]}>
<InputNumber style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="reason" label="原因" rules={[{ required: true }]}>
<Select
options={[
{ value: '采购奖励', label: '采购奖励' },
{ value: '售后补偿', label: '售后补偿' },
{ value: '营销活动', label: '营销活动' },
]}
/>
</Form.Item>
</Form>
</Modal>
</>
);
};
export default PointsManagement;

View File

@ -0,0 +1,95 @@
import { useEffect, useState } from 'react';
import { Button, Modal, Form, Input, InputNumber, Table, Space, message } from 'antd';
import { Product } from '../../types';
import { adminProducts } from '../../api';
const ProductManagement = () => {
const [products, setProducts] = useState<Product[]>([]);
const [open, setOpen] = useState(false);
const [editing, setEditing] = useState<Product | null>(null);
const [form] = Form.useForm();
const load = () => {
adminProducts.list().then(setProducts);
};
useEffect(() => {
load();
}, []);
const handleSubmit = async () => {
const values = await form.validateFields();
if (editing) {
await adminProducts.update(editing.id, values);
message.success('已更新');
} else {
await adminProducts.create(values);
message.success('已创建');
}
setOpen(false);
setEditing(null);
form.resetFields();
load();
};
const handleDelete = async (record: Product) => {
await adminProducts.remove(record.id);
message.success('已删除');
load();
};
return (
<div>
<Space style={{ marginBottom: 16 }}>
<Button type="primary" onClick={() => setOpen(true)}>
</Button>
</Space>
<Table rowKey="id" dataSource={products}
columns={[
{ title: '名称', dataIndex: 'name' },
{ title: '分类', dataIndex: 'category' },
{ title: '价格', dataIndex: 'price', render: (value: number) => `${value}` },
{ title: '库存', dataIndex: 'inventory' },
{
title: '操作',
render: (_, record) => (
<Space>
<Button type="link" onClick={() => { setEditing(record); setOpen(true); form.setFieldsValue(record); }}>
</Button>
<Button type="link" danger onClick={() => handleDelete(record)}>
</Button>
</Space>
),
},
]}
/>
<Modal open={open} onCancel={() => { setOpen(false); setEditing(null); form.resetFields(); }} onOk={handleSubmit}
title={editing ? '编辑商品' : '新增商品'}>
<Form form={form} layout="vertical" initialValues={{}}
style={{ marginTop: 16 }}>
<Form.Item name="name" label="名称" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="category" label="分类" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="price" label="价格" rules={[{ required: true }]}>
<InputNumber min={0} style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="inventory" label="库存" rules={[{ required: true }]}>
<InputNumber min={0} style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="description" label="描述">
<Input.TextArea rows={3} />
</Form.Item>
</Form>
</Modal>
</div>
);
};
export default ProductManagement;

View File

@ -0,0 +1,87 @@
import { useEffect, useState } from 'react';
import { Button, Form, Input, Modal, Select, Space, Table, Tag, message } from 'antd';
import { Ticket } from '../../types';
import { adminTickets } from '../../api';
const TicketManagement = () => {
const [tickets, setTickets] = useState<Ticket[]>([]);
const [open, setOpen] = useState(false);
const [editing, setEditing] = useState<Ticket | null>(null);
const [form] = Form.useForm();
const load = () => adminTickets.list().then(setTickets);
useEffect(() => {
load();
}, []);
const submit = async () => {
const values = await form.validateFields();
if (editing) {
await adminTickets.update(editing.id, values);
} else {
await adminTickets.create(values);
}
message.success('操作成功');
setOpen(false);
setEditing(null);
form.resetFields();
load();
};
const remove = async (ticket: Ticket) => {
await adminTickets.remove(ticket.id);
message.success('已删除');
load();
};
return (
<>
<Space style={{ marginBottom: 16 }}>
<Button type="primary" onClick={() => setOpen(true)}>
</Button>
</Space>
<Table
rowKey="id"
dataSource={tickets}
columns={[
{ title: '标题', dataIndex: 'title' },
{ title: '优先级', dataIndex: 'priority', render: (value: string) => <Tag color={value === '高' ? 'red' : value === '中' ? 'orange' : 'blue'}>{value}</Tag> },
{ title: '状态', dataIndex: 'status' },
{
title: '操作',
render: (_, record) => (
<Space>
<Button type="link" onClick={() => { setEditing(record); setOpen(true); form.setFieldsValue(record); }}>
</Button>
<Button type="link" danger onClick={() => remove(record)}>
</Button>
</Space>
),
},
]}
/>
<Modal open={open} onCancel={() => { setOpen(false); setEditing(null); }} onOk={submit} title={editing ? '编辑工单' : '新增工单'}>
<Form form={form} layout="vertical">
<Form.Item name="title" label="标题" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="description" label="描述">
<Input.TextArea rows={3} />
</Form.Item>
<Form.Item name="priority" label="优先级" rules={[{ required: true }]}>
<Select options={[{ value: '高', label: '高' }, { value: '中', label: '中' }, { value: '低', label: '低' }]} />
</Form.Item>
<Form.Item name="status" label="状态" rules={[{ required: true }]}>
<Select options={[{ value: '处理中', label: '处理中' }, { value: '已完成', label: '已完成' }]} />
</Form.Item>
</Form>
</Modal>
</>
);
};
export default TicketManagement;

1
frontend/src/react-app-env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference types="react-scripts" />

49
frontend/src/types.ts Normal file
View File

@ -0,0 +1,49 @@
export interface Product {
id: number;
name: string;
category: string;
description: string;
price: number;
inventory: number;
imageUrl: string;
}
export interface UserInfo {
id: number;
username: string;
role: string;
}
export interface Order {
id: number;
orderNumber: string;
customerName: string;
productId: number;
quantity: number;
amount: number;
status: string;
}
export interface Member {
id: number;
name: string;
email: string;
phone: string;
tier: string;
points: number;
}
export interface PointRecord {
id: number;
memberId: number;
change: number;
reason: string;
}
export interface Ticket {
id: number;
title: string;
description: string;
status: string;
priority: string;
}

26
frontend/tsconfig.json Normal file
View File

@ -0,0 +1,26 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}