refactor: migrate backend framework from Express to NestJS
This commit is contained in:
@@ -72,3 +72,6 @@ temp/
|
|||||||
|
|
||||||
# Build files
|
# Build files
|
||||||
dist/
|
dist/
|
||||||
|
|
||||||
|
# NestJS
|
||||||
|
.nest-cli.json
|
||||||
|
|||||||
@@ -1,2 +1,4 @@
|
|||||||
only-built-dependencies[]=better-sqlite3
|
only-built-dependencies[]=better-sqlite3
|
||||||
only-built-dependencies[]=esbuild
|
only-built-dependencies[]=esbuild
|
||||||
|
only-built-dependencies[]=@nestjs/core
|
||||||
|
only-built-dependencies[]=unrs-resolver
|
||||||
@@ -1,13 +1,12 @@
|
|||||||
# 溯源管理平台 - 后端服务
|
# 溯源管理平台 - 后端服务
|
||||||
|
|
||||||
浙江贝凡溯源管理平台的后端服务,基于 Node.js + TypeScript + Express + SQLite。
|
浙江贝凡溯源管理平台的后端服务,基于 NestJS + TypeScript + SQLite。
|
||||||
|
|
||||||
## 技术栈
|
## 技术栈
|
||||||
|
|
||||||
- **Node.js**: 运行时环境
|
- **NestJS**: 渐进式 Node.js 框架
|
||||||
- **TypeScript**: 类型安全
|
- **TypeScript**: 类型安全
|
||||||
- **Express**: Web 框架
|
- **SQLite**: 轻量级数据库
|
||||||
- **SQLite**: 数据库
|
|
||||||
- **JWT**: 身份认证
|
- **JWT**: 身份认证
|
||||||
- **bcryptjs**: 密码加密
|
- **bcryptjs**: 密码加密
|
||||||
|
|
||||||
@@ -15,24 +14,37 @@
|
|||||||
|
|
||||||
```
|
```
|
||||||
backend/
|
backend/
|
||||||
├── routes/ # API 路由
|
├── src/
|
||||||
│ ├── auth.ts # 认证路由
|
│ ├── auth/ # 认证模块
|
||||||
│ ├── serials.ts # 序列号路由
|
│ │ ├── auth.controller.ts
|
||||||
│ └── companies.ts # 企业路由
|
│ │ ├── auth.guard.ts
|
||||||
├── middleware/ # 中间件
|
│ │ ├── auth.module.ts
|
||||||
│ └── auth.ts # 认证中间件
|
│ │ ├── auth.service.ts
|
||||||
├── scripts/ # 脚本
|
│ │ └── dto/
|
||||||
│ └── init-db.ts # 数据库初始化
|
│ ├── companies/ # 企业模块
|
||||||
├── utils/ # 工具函数
|
│ │ ├── companies.controller.ts
|
||||||
│ └── database.ts # 数据库连接
|
│ │ ├── companies.module.ts
|
||||||
├── types/ # 类型定义
|
│ │ └── companies.service.ts
|
||||||
│ └── index.d.ts # TypeScript 类型
|
│ ├── database/ # 数据库模块
|
||||||
├── data/ # 数据文件
|
│ │ ├── database.module.ts
|
||||||
│ └── database.sqlite
|
│ │ └── database.service.ts
|
||||||
├── server.ts # 服务器入口
|
│ ├── serials/ # 序列号模块
|
||||||
├── tsconfig.json # TypeScript 配置
|
│ │ ├── serials.controller.ts
|
||||||
├── .env # 环境变量
|
│ │ ├── serials.module.ts
|
||||||
└── package.json # 项目配置
|
│ │ ├── serials.service.ts
|
||||||
|
│ │ └── dto/
|
||||||
|
│ ├── types/ # 类型定义
|
||||||
|
│ │ └── index.d.ts
|
||||||
|
│ ├── utils/ # 工具函数
|
||||||
|
│ ├── app.module.ts # 根模块
|
||||||
|
│ ├── health.controller.ts
|
||||||
|
│ └── main.ts # 应用入口
|
||||||
|
├── data/ # 数据文件
|
||||||
|
├── scripts/ # 脚本
|
||||||
|
├── .env # 环境变量
|
||||||
|
├── package.json
|
||||||
|
├── tsconfig.json
|
||||||
|
└── README.md
|
||||||
```
|
```
|
||||||
|
|
||||||
## 安装
|
## 安装
|
||||||
@@ -46,7 +58,7 @@ pnpm install
|
|||||||
启动开发服务器(支持热重载):
|
启动开发服务器(支持热重载):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pnpm dev
|
pnpm start:dev
|
||||||
```
|
```
|
||||||
|
|
||||||
服务器将在 http://localhost:3000 运行
|
服务器将在 http://localhost:3000 运行
|
||||||
@@ -64,7 +76,7 @@ pnpm build
|
|||||||
启动生产服务器:
|
启动生产服务器:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pnpm start
|
pnpm start:prod
|
||||||
```
|
```
|
||||||
|
|
||||||
## 数据库初始化
|
## 数据库初始化
|
||||||
|
|||||||
@@ -1,53 +0,0 @@
|
|||||||
import jwt from 'jsonwebtoken';
|
|
||||||
import { Request, Response, NextFunction } from 'express';
|
|
||||||
import db from '../utils/database';
|
|
||||||
import { AuthUser } from '../types';
|
|
||||||
|
|
||||||
declare global {
|
|
||||||
namespace Express {
|
|
||||||
interface Request {
|
|
||||||
user?: AuthUser;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export const authenticateToken = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
|
||||||
const authHeader = req.headers['authorization'];
|
|
||||||
const token = authHeader && authHeader.split(' ')[1];
|
|
||||||
|
|
||||||
if (!token) {
|
|
||||||
res.status(401).json({ error: '访问令牌缺失' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const decoded = jwt.verify(token, process.env.JWT_SECRET!) as { userId: number; username: string; role: string };
|
|
||||||
|
|
||||||
const user = await db.get(
|
|
||||||
'SELECT id, username, name, role FROM users WHERE id = ?',
|
|
||||||
[decoded.userId]
|
|
||||||
) as AuthUser | undefined;
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
res.status(401).json({ error: '用户不存在' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
req.user = user;
|
|
||||||
next();
|
|
||||||
} catch (error: any) {
|
|
||||||
if (error.name === 'TokenExpiredError') {
|
|
||||||
res.status(401).json({ error: '令牌已过期' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
res.status(403).json({ error: '无效的令牌' });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const requireAdmin = (req: Request, res: Response, next: NextFunction): void => {
|
|
||||||
if (req.user?.role !== 'admin') {
|
|
||||||
res.status(403).json({ error: '需要管理员权限' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
next();
|
|
||||||
};
|
|
||||||
+59
-11
@@ -2,34 +2,82 @@
|
|||||||
"name": "trace-backend",
|
"name": "trace-backend",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"description": "浙江贝凡溯源管理平台 - 后端服务",
|
"description": "浙江贝凡溯源管理平台 - 后端服务",
|
||||||
"main": "dist/server.js",
|
"author": "",
|
||||||
|
"private": true,
|
||||||
|
"license": "MIT",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node dist/server.js",
|
"build": "nest build",
|
||||||
"dev": "nodemon --exec tsx server.ts",
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
"build": "tsc",
|
"start": "nest start",
|
||||||
|
"start:dev": "nest start --watch",
|
||||||
|
"start:debug": "nest start --debug --watch",
|
||||||
|
"start:prod": "node dist/main",
|
||||||
|
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||||
|
"test": "jest",
|
||||||
|
"test:watch": "jest --watch",
|
||||||
|
"test:cov": "jest --coverage",
|
||||||
|
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||||
|
"test:e2e": "jest --config ./test/jest-e2e.json",
|
||||||
"init-db": "tsx scripts/init-db.ts"
|
"init-db": "tsx scripts/init-db.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@nestjs/common": "^11.1.13",
|
||||||
|
"@nestjs/config": "^4.0.3",
|
||||||
|
"@nestjs/core": "^11.1.13",
|
||||||
|
"@nestjs/jwt": "^11.0.2",
|
||||||
|
"@nestjs/passport": "^11.0.5",
|
||||||
|
"@nestjs/platform-express": "^11.1.13",
|
||||||
|
"@nestjs/serve-static": "^5.0.4",
|
||||||
"bcryptjs": "^3.0.3",
|
"bcryptjs": "^3.0.3",
|
||||||
"better-sqlite3": "^12.6.2",
|
"better-sqlite3": "^12.6.2",
|
||||||
"cors": "^2.8.5",
|
"class-transformer": "^0.5.1",
|
||||||
|
"class-validator": "^0.14.3",
|
||||||
"dotenv": "^17.2.3",
|
"dotenv": "^17.2.3",
|
||||||
"express": "^5.2.1",
|
|
||||||
"jsonwebtoken": "^9.0.2",
|
"jsonwebtoken": "^9.0.2",
|
||||||
"qrcode": "^1.5.4"
|
"passport": "^0.7.0",
|
||||||
|
"passport-jwt": "^4.0.1",
|
||||||
|
"qrcode": "^1.5.4",
|
||||||
|
"reflect-metadata": "^0.2.2",
|
||||||
|
"rxjs": "^7.8.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@nestjs/cli": "^11.0.0",
|
||||||
|
"@nestjs/schematics": "^11.0.0",
|
||||||
|
"@nestjs/testing": "^11.1.13",
|
||||||
"@types/better-sqlite3": "^7.6.13",
|
"@types/better-sqlite3": "^7.6.13",
|
||||||
"@types/cors": "^2.8.19",
|
|
||||||
"@types/express": "^5.0.6",
|
"@types/express": "^5.0.6",
|
||||||
|
"@types/jest": "^30.0.0",
|
||||||
"@types/jsonwebtoken": "^9.0.10",
|
"@types/jsonwebtoken": "^9.0.10",
|
||||||
"@types/node": "^25.2.1",
|
"@types/node": "^25.2.1",
|
||||||
|
"@types/passport-jwt": "^4.0.1",
|
||||||
"@types/qrcode": "^1.5.6",
|
"@types/qrcode": "^1.5.6",
|
||||||
"nodemon": "^3.0.1",
|
"@types/supertest": "^6.0.2",
|
||||||
|
"jest": "^30.2.0",
|
||||||
|
"prettier": "^3.5.3",
|
||||||
|
"source-map-support": "^0.5.21",
|
||||||
|
"supertest": "^7.1.0",
|
||||||
|
"ts-jest": "^29.3.2",
|
||||||
|
"ts-loader": "^9.5.2",
|
||||||
"ts-node": "^10.9.2",
|
"ts-node": "^10.9.2",
|
||||||
|
"tsconfig-paths": "^4.2.0",
|
||||||
"tsx": "^4.21.0",
|
"tsx": "^4.21.0",
|
||||||
"typescript": "^5.9.3"
|
"typescript": "^5.9.3"
|
||||||
},
|
},
|
||||||
"author": "",
|
"jest": {
|
||||||
"license": "MIT"
|
"moduleFileExtensions": [
|
||||||
|
"js",
|
||||||
|
"json",
|
||||||
|
"ts"
|
||||||
|
],
|
||||||
|
"rootDir": "src",
|
||||||
|
"testRegex": ".*\\.spec\\.ts$",
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
},
|
||||||
|
"collectCoverageFrom": [
|
||||||
|
"**/*.(t|j)s"
|
||||||
|
],
|
||||||
|
"coverageDirectory": "../coverage",
|
||||||
|
"testEnvironment": "node"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
+4677
-118
File diff suppressed because it is too large
Load Diff
-159
@@ -1,159 +0,0 @@
|
|||||||
import express, { Request, Response } from 'express';
|
|
||||||
import jwt from 'jsonwebtoken';
|
|
||||||
import bcrypt from 'bcryptjs';
|
|
||||||
import db from '../utils/database';
|
|
||||||
import { authenticateToken } from '../middleware/auth';
|
|
||||||
import { User, LoginRequest, ChangePasswordRequest } from '../types';
|
|
||||||
|
|
||||||
const router = express.Router();
|
|
||||||
|
|
||||||
router.post('/login', async (req: Request<{}, {}, LoginRequest>, res: Response): Promise<void> => {
|
|
||||||
try {
|
|
||||||
const { username, password } = req.body;
|
|
||||||
|
|
||||||
if (!username || !password) {
|
|
||||||
res.status(400).json({ error: '用户名和密码不能为空' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const user = await db.get<User>('SELECT * FROM users WHERE username = ?', [username]);
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
res.status(401).json({ error: '用户名或密码错误' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const isValidPassword = await bcrypt.compare(password, user.password);
|
|
||||||
|
|
||||||
if (!isValidPassword) {
|
|
||||||
res.status(401).json({ error: '用户名或密码错误' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const token = jwt.sign(
|
|
||||||
{ userId: user.id, username: user.username, role: user.role },
|
|
||||||
process.env.JWT_SECRET!,
|
|
||||||
{ expiresIn: '24h' }
|
|
||||||
);
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
accessToken: token,
|
|
||||||
user: {
|
|
||||||
id: user.id,
|
|
||||||
username: user.username,
|
|
||||||
name: user.name,
|
|
||||||
email: user.email,
|
|
||||||
role: user.role,
|
|
||||||
createdAt: user.created_at
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('登录错误:', error);
|
|
||||||
res.status(500).json({ error: '服务器内部错误' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.get('/profile', authenticateToken, async (req: Request, res: Response): Promise<void> => {
|
|
||||||
try {
|
|
||||||
const user = await db.get<User>(
|
|
||||||
'SELECT id, username, name, email, role, created_at FROM users WHERE id = ?',
|
|
||||||
[req.user!.id]
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
res.status(404).json({ error: '用户不存在' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
id: user.id,
|
|
||||||
username: user.username,
|
|
||||||
name: user.name,
|
|
||||||
email: user.email,
|
|
||||||
role: user.role,
|
|
||||||
createdAt: user.created_at
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('获取用户信息错误:', error);
|
|
||||||
res.status(500).json({ error: '服务器内部错误' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.post('/change-password', authenticateToken, async (req: Request<{}, {}, ChangePasswordRequest>, res: Response): Promise<void> => {
|
|
||||||
try {
|
|
||||||
const { currentPassword, newPassword } = req.body;
|
|
||||||
|
|
||||||
if (!currentPassword || !newPassword) {
|
|
||||||
res.status(400).json({ error: '当前密码和新密码不能为空' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (newPassword.length < 6) {
|
|
||||||
res.status(400).json({ error: '新密码长度至少为6位' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const user = await db.get<Pick<User, 'password'>>('SELECT password FROM users WHERE id = ?', [req.user!.id]);
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
res.status(404).json({ error: '用户不存在' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const isValidPassword = await bcrypt.compare(currentPassword, user.password);
|
|
||||||
|
|
||||||
if (!isValidPassword) {
|
|
||||||
res.status(401).json({ error: '当前密码错误' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const hashedPassword = await bcrypt.hash(newPassword, 10);
|
|
||||||
|
|
||||||
await db.run('UPDATE users SET password = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', [hashedPassword, req.user!.id]);
|
|
||||||
|
|
||||||
res.json({ message: '密码修改成功' });
|
|
||||||
} catch (error) {
|
|
||||||
console.error('修改密码错误:', error);
|
|
||||||
res.status(500).json({ error: '服务器内部错误' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.put('/profile', authenticateToken, async (req: Request, res: Response): Promise<void> => {
|
|
||||||
try {
|
|
||||||
const { name, email } = req.body;
|
|
||||||
|
|
||||||
if (!name) {
|
|
||||||
res.status(400).json({ error: '姓名不能为空' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (email && !email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
|
|
||||||
res.status(400).json({ error: '邮箱格式不正确' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await db.run(
|
|
||||||
'UPDATE users SET name = ?, email = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
|
|
||||||
[name, email, req.user!.id]
|
|
||||||
);
|
|
||||||
|
|
||||||
const updatedUser = await db.get<User>(
|
|
||||||
'SELECT id, username, name, email, role, created_at FROM users WHERE id = ?',
|
|
||||||
[req.user!.id]
|
|
||||||
);
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
id: updatedUser!.id,
|
|
||||||
username: updatedUser!.username,
|
|
||||||
name: updatedUser!.name,
|
|
||||||
email: updatedUser!.email,
|
|
||||||
role: updatedUser!.role,
|
|
||||||
createdAt: updatedUser!.created_at
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('更新用户资料错误:', error);
|
|
||||||
res.status(500).json({ error: '服务器内部错误' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
export default router;
|
|
||||||
@@ -1,379 +0,0 @@
|
|||||||
import express, { Request, Response } from 'express';
|
|
||||||
import QRCode from 'qrcode';
|
|
||||||
import db from '../utils/database';
|
|
||||||
import { authenticateToken, requireAdmin } from '../middleware/auth';
|
|
||||||
import { GenerateSerialRequest, GenerateSerialWithPrefixRequest, QRCodeRequest, UpdateSerialRequest, PaginationQuery, SerialListItem } from '../types';
|
|
||||||
|
|
||||||
const router = express.Router();
|
|
||||||
|
|
||||||
router.post('/generate', authenticateToken, requireAdmin, async (req: Request<{}, {}, GenerateSerialRequest>, res: Response): Promise<void> => {
|
|
||||||
try {
|
|
||||||
const { companyName, quantity = 1, validDays = 365 } = req.body;
|
|
||||||
|
|
||||||
if (!companyName) {
|
|
||||||
res.status(400).json({ error: '企业名称不能为空' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (quantity < 1 || quantity > 100) {
|
|
||||||
res.status(400).json({ error: '生成数量必须在1-100之间' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const validUntil = new Date();
|
|
||||||
validUntil.setDate(validUntil.getDate() + validDays);
|
|
||||||
|
|
||||||
const existingCompany = await db.get('SELECT * FROM companies WHERE company_name = ?', [companyName]);
|
|
||||||
if (!existingCompany) {
|
|
||||||
await db.run('INSERT INTO companies (company_name, is_active) VALUES (?, 1)', [companyName]);
|
|
||||||
}
|
|
||||||
|
|
||||||
const serials: SerialListItem[] = [];
|
|
||||||
const prefix = 'BF';
|
|
||||||
const datePart = new Date().getFullYear().toString().substr(2);
|
|
||||||
|
|
||||||
for (let i = 0; i < quantity; i++) {
|
|
||||||
const randomPart = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
|
|
||||||
const serialNumber = `${prefix}${datePart}${randomPart}`;
|
|
||||||
|
|
||||||
await db.run(
|
|
||||||
'INSERT INTO serials (serial_number, company_name, valid_until, created_by) VALUES (?, ?, ?, ?)',
|
|
||||||
[serialNumber, companyName, validUntil.toISOString().slice(0, 19).replace('T', ' '), req.user!.id]
|
|
||||||
);
|
|
||||||
|
|
||||||
serials.push({
|
|
||||||
serialNumber,
|
|
||||||
companyName,
|
|
||||||
validUntil: validUntil.toISOString(),
|
|
||||||
isActive: true,
|
|
||||||
createdAt: new Date().toISOString()
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
message: `成功生成${quantity}个序列号`,
|
|
||||||
serials
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('生成序列号错误:', error);
|
|
||||||
res.status(500).json({ error: '服务器内部错误' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.post('/:serialNumber/qrcode', authenticateToken, async (req: Request<{ serialNumber: string }, {}, QRCodeRequest>, res: Response): Promise<void> => {
|
|
||||||
try {
|
|
||||||
const { serialNumber } = req.params;
|
|
||||||
let { baseUrl } = req.body;
|
|
||||||
|
|
||||||
if (!serialNumber) {
|
|
||||||
res.status(400).json({ error: '序列号不能为空' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const serial = await db.get<{ serial_number: string; company_name: string; is_active: number; valid_until: string | null }>(
|
|
||||||
'SELECT s.*, u.name as created_by_name FROM serials s LEFT JOIN users u ON s.created_by = u.id WHERE s.serial_number = ?',
|
|
||||||
[serialNumber.toUpperCase()]
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!serial) {
|
|
||||||
res.status(404).json({ error: '序列号不存在' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!serial.is_active) {
|
|
||||||
res.status(400).json({ error: '序列号已被禁用' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (serial.valid_until && new Date(serial.valid_until) < new Date()) {
|
|
||||||
res.status(400).json({ error: '序列号已过期' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!baseUrl) {
|
|
||||||
baseUrl = `${req.protocol}://${req.get('host')}/query.html`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const queryUrl = baseUrl.includes('?')
|
|
||||||
? `${baseUrl}&serial=${serial.serial_number}`
|
|
||||||
: `${baseUrl}?serial=${serial.serial_number}`;
|
|
||||||
|
|
||||||
const qrCodeData = await QRCode.toDataURL(queryUrl, {
|
|
||||||
width: 200,
|
|
||||||
color: {
|
|
||||||
dark: '#165DFF',
|
|
||||||
light: '#ffffff'
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
message: '二维码生成成功',
|
|
||||||
qrCodeData,
|
|
||||||
queryUrl,
|
|
||||||
serialNumber: serial.serial_number,
|
|
||||||
companyName: serial.company_name,
|
|
||||||
validUntil: serial.valid_until
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('生成二维码错误:', error);
|
|
||||||
res.status(500).json({ error: '服务器内部错误' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.get('/:serialNumber/query', async (req: Request<{ serialNumber: string }>, res: Response): Promise<void> => {
|
|
||||||
try {
|
|
||||||
const { serialNumber } = req.params;
|
|
||||||
|
|
||||||
if (!serialNumber) {
|
|
||||||
res.status(400).json({ error: '序列号不能为空' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const serial = await db.get<{ serial_number: string; company_name: string; valid_until: string | null; is_active: number; created_at: string; created_by_name: string }>(
|
|
||||||
'SELECT s.*, u.name as created_by_name FROM serials s LEFT JOIN users u ON s.created_by = u.id WHERE s.serial_number = ?',
|
|
||||||
[serialNumber.toUpperCase()]
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!serial) {
|
|
||||||
res.status(404).json({ error: '序列号不存在' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (serial.valid_until && new Date(serial.valid_until) < new Date()) {
|
|
||||||
res.status(400).json({ error: '序列号已过期' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
message: '查询成功',
|
|
||||||
serial: {
|
|
||||||
serialNumber: serial.serial_number,
|
|
||||||
companyName: serial.company_name,
|
|
||||||
validUntil: serial.valid_until,
|
|
||||||
status: serial.is_active ? 'active' : 'disabled',
|
|
||||||
isActive: !!serial.is_active,
|
|
||||||
createdAt: serial.created_at,
|
|
||||||
createdBy: serial.created_by_name
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('查询序列号错误:', error);
|
|
||||||
res.status(500).json({ error: '服务器内部错误' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.get('/', authenticateToken, async (req: Request<{}, {}, {}, PaginationQuery>, res: Response): Promise<void> => {
|
|
||||||
try {
|
|
||||||
const { page = 1, limit = 20, search = '' } = req.query;
|
|
||||||
const offset = (page - 1) * limit;
|
|
||||||
|
|
||||||
let query = 'SELECT s.*, u.name as created_by_name FROM serials s LEFT JOIN users u ON s.created_by = u.id';
|
|
||||||
let countQuery = 'SELECT COUNT(*) as total FROM serials s';
|
|
||||||
let params: any[] = [];
|
|
||||||
|
|
||||||
if (search) {
|
|
||||||
query += ' WHERE s.serial_number LIKE ? OR s.company_name LIKE ?';
|
|
||||||
countQuery += ' WHERE s.serial_number LIKE ? OR s.company_name LIKE ?';
|
|
||||||
const searchParam = `%${search}%`;
|
|
||||||
params.push(searchParam, searchParam);
|
|
||||||
}
|
|
||||||
|
|
||||||
query += ' ORDER BY s.created_at DESC LIMIT ? OFFSET ?';
|
|
||||||
params.push(parseInt(limit.toString()), parseInt(offset.toString()));
|
|
||||||
|
|
||||||
const [serials, countResult] = await Promise.all([
|
|
||||||
db.all(query, params),
|
|
||||||
db.get<{ total: number }>(countQuery, params.slice(0, -2))
|
|
||||||
]);
|
|
||||||
|
|
||||||
const total = countResult?.total || 0;
|
|
||||||
const totalPages = Math.ceil(total / limit);
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
message: '获取序列号列表成功',
|
|
||||||
data: serials.map((s: any) => ({
|
|
||||||
serialNumber: s.serial_number,
|
|
||||||
companyName: s.company_name,
|
|
||||||
validUntil: s.valid_until,
|
|
||||||
isActive: s.is_active,
|
|
||||||
createdAt: s.created_at,
|
|
||||||
createdBy: s.created_by_name
|
|
||||||
})),
|
|
||||||
pagination: {
|
|
||||||
page: parseInt(page.toString()),
|
|
||||||
limit: parseInt(limit.toString()),
|
|
||||||
total,
|
|
||||||
totalPages
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('获取序列号列表错误:', error);
|
|
||||||
res.status(500).json({ error: '服务器内部错误' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.patch('/:serialNumber', authenticateToken, requireAdmin, async (req: Request<{ serialNumber: string }, {}, UpdateSerialRequest>, res: Response): Promise<void> => {
|
|
||||||
try {
|
|
||||||
const { serialNumber } = req.params;
|
|
||||||
const { companyName, validUntil, isActive } = req.body;
|
|
||||||
|
|
||||||
if (!serialNumber) {
|
|
||||||
res.status(400).json({ error: '序列号不能为空' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const existingSerial = await db.get<{ is_active: number }>('SELECT * FROM serials WHERE serial_number = ?', [serialNumber.toUpperCase()]);
|
|
||||||
|
|
||||||
if (!existingSerial) {
|
|
||||||
res.status(404).json({ error: '序列号不存在' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const updateFields: string[] = [];
|
|
||||||
const params: any[] = [];
|
|
||||||
|
|
||||||
if (companyName !== undefined) {
|
|
||||||
updateFields.push('company_name = ?');
|
|
||||||
params.push(companyName);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (validUntil !== undefined) {
|
|
||||||
updateFields.push('valid_until = ?');
|
|
||||||
params.push(validUntil);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isActive !== undefined) {
|
|
||||||
updateFields.push('is_active = ?');
|
|
||||||
params.push(isActive ? 1 : 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (updateFields.length === 0) {
|
|
||||||
res.status(400).json({ error: '没有提供更新字段' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
updateFields.push('updated_at = CURRENT_TIMESTAMP');
|
|
||||||
params.push(serialNumber.toUpperCase());
|
|
||||||
|
|
||||||
await db.run(
|
|
||||||
`UPDATE serials SET ${updateFields.join(', ')} WHERE serial_number = ?`,
|
|
||||||
params
|
|
||||||
);
|
|
||||||
|
|
||||||
const updatedSerial = await db.get('SELECT s.*, u.name as created_by_name FROM serials s LEFT JOIN users u ON s.created_by = u.id WHERE s.serial_number = ?', [serialNumber.toUpperCase()]);
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
message: '序列号更新成功',
|
|
||||||
serial: {
|
|
||||||
serialNumber: (updatedSerial as any).serial_number,
|
|
||||||
companyName: (updatedSerial as any).company_name,
|
|
||||||
validUntil: (updatedSerial as any).valid_until,
|
|
||||||
isActive: (updatedSerial as any).is_active,
|
|
||||||
createdAt: (updatedSerial as any).created_at,
|
|
||||||
updatedAt: (updatedSerial as any).updated_at,
|
|
||||||
createdBy: (updatedSerial as any).created_by_name
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('更新序列号错误:', error);
|
|
||||||
res.status(500).json({ error: '服务器内部错误' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.post('/:serialNumber/revoke', authenticateToken, requireAdmin, async (req: Request<{ serialNumber: string }>, res: Response): Promise<void> => {
|
|
||||||
try {
|
|
||||||
const { serialNumber } = req.params;
|
|
||||||
|
|
||||||
if (!serialNumber) {
|
|
||||||
res.status(400).json({ error: '序列号不能为空' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const existingSerial = await db.get<{ is_active: number }>('SELECT * FROM serials WHERE serial_number = ?', [serialNumber.toUpperCase()]);
|
|
||||||
|
|
||||||
if (!existingSerial) {
|
|
||||||
res.status(404).json({ error: '序列号不存在' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!existingSerial.is_active) {
|
|
||||||
res.status(400).json({ error: '序列号已被吊销' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await db.run(
|
|
||||||
'UPDATE serials SET is_active = 0, updated_at = CURRENT_TIMESTAMP WHERE serial_number = ?',
|
|
||||||
[serialNumber.toUpperCase()]
|
|
||||||
);
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
message: '序列号已吊销',
|
|
||||||
data: {
|
|
||||||
serialNumber: serialNumber.toUpperCase()
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('吊销序列号错误:', error);
|
|
||||||
res.status(500).json({ error: '服务器内部错误' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.post('/generate-with-prefix', authenticateToken, requireAdmin, async (req: Request<{}, {}, GenerateSerialWithPrefixRequest>, res: Response): Promise<void> => {
|
|
||||||
try {
|
|
||||||
const { companyName, quantity = 1, validDays = 365, serialPrefix } = req.body;
|
|
||||||
|
|
||||||
if (!companyName) {
|
|
||||||
res.status(400).json({ error: '企业名称不能为空' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!serialPrefix || serialPrefix.length > 10) {
|
|
||||||
res.status(400).json({ error: '自定义前缀不能为空且不能超过10个字符' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (quantity < 1 || quantity > 100) {
|
|
||||||
res.status(400).json({ error: '生成数量必须在1-100之间' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const validUntil = new Date();
|
|
||||||
validUntil.setDate(validUntil.getDate() + validDays);
|
|
||||||
|
|
||||||
const serials: SerialListItem[] = [];
|
|
||||||
const prefix = serialPrefix.toUpperCase().replace(/[^A-Z0-9]/g, '');
|
|
||||||
|
|
||||||
if (!prefix) {
|
|
||||||
res.status(400).json({ error: '自定义前缀包含无效字符,只能包含字母和数字' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let i = 0; i < quantity; i++) {
|
|
||||||
const randomPart = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
|
|
||||||
const serialNumber = `${prefix}${randomPart}`;
|
|
||||||
|
|
||||||
await db.run(
|
|
||||||
'INSERT INTO serials (serial_number, company_name, valid_until, created_by) VALUES (?, ?, ?, ?)',
|
|
||||||
[serialNumber, companyName, validUntil.toISOString(), req.user!.id]
|
|
||||||
);
|
|
||||||
|
|
||||||
serials.push({
|
|
||||||
serialNumber,
|
|
||||||
companyName,
|
|
||||||
validUntil: validUntil.toISOString(),
|
|
||||||
isActive: true,
|
|
||||||
createdAt: new Date().toISOString()
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
message: `成功生成${quantity}个序列号`,
|
|
||||||
serials
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('生成序列号错误:', error);
|
|
||||||
res.status(500).json({ error: '服务器内部错误' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
export default router;
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
import 'dotenv/config';
|
|
||||||
import express, { Request, Response, NextFunction } from 'express';
|
|
||||||
import cors from 'cors';
|
|
||||||
import path from 'path';
|
|
||||||
import authRoutes from './routes/auth';
|
|
||||||
import serialRoutes from './routes/serials';
|
|
||||||
import companyRoutes from './routes/companies';
|
|
||||||
|
|
||||||
const app = express();
|
|
||||||
const PORT = process.env.PORT || 3000;
|
|
||||||
|
|
||||||
app.use(cors());
|
|
||||||
app.use(express.json({ limit: '10mb' }));
|
|
||||||
app.use(express.urlencoded({ extended: true }));
|
|
||||||
|
|
||||||
app.use((req: Request, res: Response, next: NextFunction): void => {
|
|
||||||
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
||||||
next();
|
|
||||||
});
|
|
||||||
|
|
||||||
app.use('/api/auth', authRoutes);
|
|
||||||
app.use('/api/serials', serialRoutes);
|
|
||||||
app.use('/api/companies', companyRoutes);
|
|
||||||
|
|
||||||
app.get('/api/health', (req: Request, res: Response): void => {
|
|
||||||
res.json({ status: 'ok', message: '服务器运行正常' });
|
|
||||||
});
|
|
||||||
|
|
||||||
const frontendPath = path.join(__dirname, '..', 'frontend');
|
|
||||||
const distPath = path.join(frontendPath, 'dist');
|
|
||||||
const publicPath = path.join(frontendPath, 'public');
|
|
||||||
|
|
||||||
if (process.env.NODE_ENV === 'production') {
|
|
||||||
app.use(express.static(distPath));
|
|
||||||
} else {
|
|
||||||
app.use(express.static(publicPath));
|
|
||||||
}
|
|
||||||
|
|
||||||
app.use((req: Request, res: Response): void => {
|
|
||||||
if (req.path.startsWith('/api/')) {
|
|
||||||
res.status(404).json({ error: 'API接口不存在' });
|
|
||||||
} else {
|
|
||||||
if (process.env.NODE_ENV === 'production') {
|
|
||||||
res.sendFile(path.join(distPath, 'index.html'));
|
|
||||||
} else {
|
|
||||||
res.sendFile(path.join(publicPath, 'index.html'));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
app.use((error: Error, req: Request, res: Response, next: NextFunction): void => {
|
|
||||||
console.error('服务器错误:', error);
|
|
||||||
|
|
||||||
if (req.path.startsWith('/api/')) {
|
|
||||||
res.status(500).json({ error: '服务器内部错误' });
|
|
||||||
} else {
|
|
||||||
res.status(500).send('服务器内部错误');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
app.listen(PORT, (): void => {
|
|
||||||
console.log(`服务器运行在 http://localhost:${PORT}`);
|
|
||||||
console.log(`API文档: http://localhost:${PORT}/api/health`);
|
|
||||||
console.log(`环境: ${process.env.NODE_ENV || 'development'}`);
|
|
||||||
});
|
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { ConfigModule } from '@nestjs/config';
|
||||||
|
import { AuthModule } from './auth/auth.module';
|
||||||
|
import { SerialsModule } from './serials/serials.module';
|
||||||
|
import { CompaniesModule } from './companies/companies.module';
|
||||||
|
import { DatabaseModule } from './database/database.module';
|
||||||
|
import { HealthController } from './health.controller';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
ConfigModule.forRoot({
|
||||||
|
isGlobal: true,
|
||||||
|
envFilePath: '.env',
|
||||||
|
}),
|
||||||
|
DatabaseModule,
|
||||||
|
AuthModule,
|
||||||
|
SerialsModule,
|
||||||
|
CompaniesModule,
|
||||||
|
],
|
||||||
|
controllers: [HealthController],
|
||||||
|
})
|
||||||
|
export class AppModule {}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AdminGuard implements CanActivate {
|
||||||
|
canActivate(context: ExecutionContext): boolean {
|
||||||
|
const request = context.switchToHttp().getRequest();
|
||||||
|
const user = request.user;
|
||||||
|
|
||||||
|
if (user?.role !== 'admin') {
|
||||||
|
throw new ForbiddenException('需要管理员权限');
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { Controller, Post, Get, Put, Body, UseGuards, Request, HttpCode, HttpStatus } from '@nestjs/common';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
import { AuthGuard } from './auth.guard';
|
||||||
|
import { LoginDto, ChangePasswordDto, UpdateProfileDto } from './dto';
|
||||||
|
|
||||||
|
@Controller('auth')
|
||||||
|
export class AuthController {
|
||||||
|
constructor(private authService: AuthService) {}
|
||||||
|
|
||||||
|
@Post('login')
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
async login(@Body() loginDto: LoginDto) {
|
||||||
|
const user = await this.authService.validateUser(loginDto.username, loginDto.password);
|
||||||
|
return this.authService.login(user);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('profile')
|
||||||
|
@UseGuards(AuthGuard)
|
||||||
|
async getProfile(@Request() req) {
|
||||||
|
return this.authService.getProfile(req.user.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('change-password')
|
||||||
|
@UseGuards(AuthGuard)
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
async changePassword(@Request() req, @Body() changePasswordDto: ChangePasswordDto) {
|
||||||
|
return this.authService.changePassword(
|
||||||
|
req.user.id,
|
||||||
|
changePasswordDto.currentPassword,
|
||||||
|
changePasswordDto.newPassword,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Put('profile')
|
||||||
|
@UseGuards(AuthGuard)
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
async updateProfile(@Request() req, @Body() updateProfileDto: UpdateProfileDto) {
|
||||||
|
return this.authService.updateProfile(req.user.id, updateProfileDto.name, updateProfileDto.email);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
|
||||||
|
import { JwtService } from '@nestjs/jwt';
|
||||||
|
import { DatabaseService } from '../database/database.service';
|
||||||
|
import { AuthUser } from '../types';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AuthGuard implements CanActivate {
|
||||||
|
constructor(
|
||||||
|
private jwtService: JwtService,
|
||||||
|
private dbService: DatabaseService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||||
|
const request = context.switchToHttp().getRequest();
|
||||||
|
const authHeader = request.headers['authorization'];
|
||||||
|
const token = authHeader && authHeader.split(' ')[1];
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
throw new UnauthorizedException('访问令牌缺失');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const decoded = this.jwtService.verify(token) as { userId: number; username: string; role: string };
|
||||||
|
|
||||||
|
const user = await this.dbService.get<AuthUser>(
|
||||||
|
'SELECT id, username, name, role FROM users WHERE id = ?',
|
||||||
|
[decoded.userId]
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
throw new UnauthorizedException('用户不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
request.user = user;
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
if (error.name === 'TokenExpiredError') {
|
||||||
|
throw new UnauthorizedException('令牌已过期');
|
||||||
|
}
|
||||||
|
throw new UnauthorizedException('无效的令牌');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { Module, Global } from '@nestjs/common';
|
||||||
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
import { AuthController } from './auth.controller';
|
||||||
|
import { AuthGuard } from './auth.guard';
|
||||||
|
import { AdminGuard } from './admin.guard';
|
||||||
|
|
||||||
|
@Global()
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
JwtModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
useFactory: async (configService: ConfigService) => ({
|
||||||
|
secret: configService.get<string>('JWT_SECRET'),
|
||||||
|
signOptions: { expiresIn: '24h' },
|
||||||
|
}),
|
||||||
|
inject: [ConfigService],
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
controllers: [AuthController],
|
||||||
|
providers: [AuthService, AuthGuard, AdminGuard],
|
||||||
|
exports: [AuthGuard, AdminGuard, JwtModule],
|
||||||
|
})
|
||||||
|
export class AuthModule {}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||||
|
import { JwtService } from '@nestjs/jwt';
|
||||||
|
import * as bcrypt from 'bcryptjs';
|
||||||
|
import { DatabaseService } from '../database/database.service';
|
||||||
|
import { User, AuthUser } from '../types';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AuthService {
|
||||||
|
constructor(
|
||||||
|
private dbService: DatabaseService,
|
||||||
|
private jwtService: JwtService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async validateUser(username: string, password: string) {
|
||||||
|
const user = await this.dbService.get<User>('SELECT * FROM users WHERE username = ?', [username]);
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
throw new UnauthorizedException('用户名或密码错误');
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValidPassword = await bcrypt.compare(password, user.password);
|
||||||
|
|
||||||
|
if (!isValidPassword) {
|
||||||
|
throw new UnauthorizedException('用户名或密码错误');
|
||||||
|
}
|
||||||
|
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
async login(user: User) {
|
||||||
|
const payload = { userId: user.id, username: user.username, role: user.role };
|
||||||
|
const token = this.jwtService.sign(payload);
|
||||||
|
|
||||||
|
return {
|
||||||
|
accessToken: token,
|
||||||
|
user: {
|
||||||
|
id: user.id,
|
||||||
|
username: user.username,
|
||||||
|
name: user.name,
|
||||||
|
email: user.email,
|
||||||
|
role: user.role,
|
||||||
|
createdAt: user.created_at,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async getProfile(userId: number) {
|
||||||
|
const user = await this.dbService.get<User>(
|
||||||
|
'SELECT id, username, name, email, role, created_at FROM users WHERE id = ?',
|
||||||
|
[userId],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
throw new UnauthorizedException('用户不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: user.id,
|
||||||
|
username: user.username,
|
||||||
|
name: user.name,
|
||||||
|
email: user.email,
|
||||||
|
role: user.role,
|
||||||
|
createdAt: user.created_at,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async changePassword(userId: number, currentPassword: string, newPassword: string) {
|
||||||
|
const user = await this.dbService.get<Pick<User, 'password'>>('SELECT password FROM users WHERE id = ?', [
|
||||||
|
userId,
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
throw new UnauthorizedException('用户不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValidPassword = await bcrypt.compare(currentPassword, user.password);
|
||||||
|
|
||||||
|
if (!isValidPassword) {
|
||||||
|
throw new UnauthorizedException('当前密码错误');
|
||||||
|
}
|
||||||
|
|
||||||
|
const hashedPassword = await bcrypt.hash(newPassword, 10);
|
||||||
|
|
||||||
|
await this.dbService.run('UPDATE users SET password = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', [
|
||||||
|
hashedPassword,
|
||||||
|
userId,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return { message: '密码修改成功' };
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateProfile(userId: number, name: string, email: string | null) {
|
||||||
|
await this.dbService.run(
|
||||||
|
'UPDATE users SET name = ?, email = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
|
||||||
|
[name, email, userId],
|
||||||
|
);
|
||||||
|
|
||||||
|
const updatedUser = await this.dbService.get<User>(
|
||||||
|
'SELECT id, username, name, email, role, created_at FROM users WHERE id = ?',
|
||||||
|
[userId],
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: updatedUser!.id,
|
||||||
|
username: updatedUser!.username,
|
||||||
|
name: updatedUser!.name,
|
||||||
|
email: updatedUser!.email,
|
||||||
|
role: updatedUser!.role,
|
||||||
|
createdAt: updatedUser!.created_at,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { IsString, IsNotEmpty, MinLength, IsEmail, IsOptional } from 'class-validator';
|
||||||
|
|
||||||
|
export class LoginDto {
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty({ message: '用户名不能为空' })
|
||||||
|
username: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty({ message: '密码不能为空' })
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ChangePasswordDto {
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty({ message: '当前密码不能为空' })
|
||||||
|
currentPassword: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@MinLength(6, { message: '新密码长度至少为6位' })
|
||||||
|
newPassword: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UpdateProfileDto {
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty({ message: '姓名不能为空' })
|
||||||
|
name: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsEmail({}, { message: '邮箱格式不正确' })
|
||||||
|
email?: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import { Controller, Get, Post, Patch, Delete, Body, Param, Query, UseGuards, Req, HttpCode, HttpStatus } from '@nestjs/common';
|
||||||
|
import { Request } from 'express';
|
||||||
|
import { CompaniesService } from './companies.service';
|
||||||
|
import { AuthGuard } from '../auth/auth.guard';
|
||||||
|
import { AdminGuard } from '../auth/admin.guard';
|
||||||
|
|
||||||
|
@Controller('companies')
|
||||||
|
export class CompaniesController {
|
||||||
|
constructor(private readonly companiesService: CompaniesService) {}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
@UseGuards(AuthGuard, AdminGuard)
|
||||||
|
async findAll(
|
||||||
|
@Query('page') page: string = '1',
|
||||||
|
@Query('limit') limit: string = '20',
|
||||||
|
@Query('search') search: string = '',
|
||||||
|
) {
|
||||||
|
return this.companiesService.findAll(parseInt(page), parseInt(limit), search);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('stats/overview')
|
||||||
|
@UseGuards(AuthGuard, AdminGuard)
|
||||||
|
async getStats() {
|
||||||
|
return this.companiesService.getStats();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':companyName')
|
||||||
|
@UseGuards(AuthGuard, AdminGuard)
|
||||||
|
async findOne(
|
||||||
|
@Param('companyName') companyName: string,
|
||||||
|
@Query('page') page: string = '1',
|
||||||
|
@Query('limit') limit: string = '20',
|
||||||
|
) {
|
||||||
|
return this.companiesService.findOne(decodeURIComponent(companyName), parseInt(page), parseInt(limit));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch(':companyName')
|
||||||
|
@UseGuards(AuthGuard, AdminGuard)
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
async update(
|
||||||
|
@Param('companyName') companyName: string,
|
||||||
|
@Body('newCompanyName') newCompanyName: string,
|
||||||
|
) {
|
||||||
|
return this.companiesService.update(decodeURIComponent(companyName), newCompanyName);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete(':companyName')
|
||||||
|
@UseGuards(AuthGuard, AdminGuard)
|
||||||
|
async delete(@Param('companyName') companyName: string) {
|
||||||
|
return this.companiesService.delete(decodeURIComponent(companyName));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete(':companyName/serials/:serialNumber')
|
||||||
|
@UseGuards(AuthGuard, AdminGuard)
|
||||||
|
async deleteSerial(
|
||||||
|
@Param('companyName') companyName: string,
|
||||||
|
@Param('serialNumber') serialNumber: string,
|
||||||
|
) {
|
||||||
|
return this.companiesService.deleteSerial(decodeURIComponent(companyName), serialNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post(':companyName/revoke')
|
||||||
|
@UseGuards(AuthGuard, AdminGuard)
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
async revoke(@Param('companyName') companyName: string) {
|
||||||
|
return this.companiesService.revoke(decodeURIComponent(companyName));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { CompaniesService } from './companies.service';
|
||||||
|
import { CompaniesController } from './companies.controller';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
controllers: [CompaniesController],
|
||||||
|
providers: [CompaniesService],
|
||||||
|
})
|
||||||
|
export class CompaniesModule {}
|
||||||
@@ -1,16 +1,14 @@
|
|||||||
import express, { Request, Response } from 'express';
|
import { Injectable } from '@nestjs/common';
|
||||||
import db from '../utils/database';
|
import { DatabaseService } from '../database/database.service';
|
||||||
import { authenticateToken, requireAdmin } from '../middleware/auth';
|
|
||||||
import { PaginationQuery, UpdateCompanyRequest, CompanyDetail, StatsOverview, MonthlyStat, SerialListItem, CompanyListItem } from '../types';
|
|
||||||
|
|
||||||
const router = express.Router();
|
@Injectable()
|
||||||
|
export class CompaniesService {
|
||||||
|
constructor(private dbService: DatabaseService) {}
|
||||||
|
|
||||||
router.get('/', authenticateToken, requireAdmin, async (req: Request<{}, {}, {}, PaginationQuery>, res: Response): Promise<void> => {
|
async findAll(page: number, limit: number, search: string) {
|
||||||
try {
|
|
||||||
const { page = 1, limit = 20, search = '' } = req.query;
|
|
||||||
const offset = (page - 1) * limit;
|
const offset = (page - 1) * limit;
|
||||||
|
|
||||||
let query = 'SELECT c.company_name, c.created_at as first_created, c.updated_at as last_created, c.is_active, (SELECT COUNT(*) FROM serials s WHERE s.company_name = c.company_name) as serial_count, (SELECT COUNT(*) FROM serials s WHERE s.company_name = c.company_name AND s.is_active = 1) as active_count FROM companies c';
|
let query = `SELECT c.company_name, c.created_at as first_created, c.updated_at as last_created, c.is_active, (SELECT COUNT(*) FROM serials s WHERE s.company_name = c.company_name) as serial_count, (SELECT COUNT(*) FROM serials s WHERE s.company_name = c.company_name AND s.is_active = 1) as active_count FROM companies c`;
|
||||||
let countQuery = 'SELECT COUNT(*) as total FROM companies';
|
let countQuery = 'SELECT COUNT(*) as total FROM companies';
|
||||||
let params: any[] = [];
|
let params: any[] = [];
|
||||||
|
|
||||||
@@ -24,14 +22,14 @@ router.get('/', authenticateToken, requireAdmin, async (req: Request<{}, {}, {},
|
|||||||
params.push(parseInt(limit.toString()), parseInt(offset.toString()));
|
params.push(parseInt(limit.toString()), parseInt(offset.toString()));
|
||||||
|
|
||||||
const [companies, countResult] = await Promise.all([
|
const [companies, countResult] = await Promise.all([
|
||||||
db.all(query, params),
|
this.dbService.all(query, params),
|
||||||
db.get<{ total: number }>(countQuery, params.slice(0, -2))
|
this.dbService.get<{ total: number }>(countQuery, params.slice(0, -2))
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const total = countResult?.total || 0;
|
const total = countResult?.total || 0;
|
||||||
const totalPages = Math.ceil(total / limit);
|
const totalPages = Math.ceil(total / limit);
|
||||||
|
|
||||||
res.json({
|
return {
|
||||||
message: '获取企业列表成功',
|
message: '获取企业列表成功',
|
||||||
data: companies.map((company: any) => ({
|
data: companies.map((company: any) => ({
|
||||||
companyName: company.company_name,
|
companyName: company.company_name,
|
||||||
@@ -47,46 +45,37 @@ router.get('/', authenticateToken, requireAdmin, async (req: Request<{}, {}, {},
|
|||||||
total,
|
total,
|
||||||
totalPages
|
totalPages
|
||||||
}
|
}
|
||||||
});
|
};
|
||||||
} catch (error) {
|
|
||||||
console.error('获取企业列表错误:', error);
|
|
||||||
res.status(500).json({ error: '服务器内部错误' });
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
router.get('/:companyName', authenticateToken, requireAdmin, async (req: Request<{ companyName: string }, {}, {}, PaginationQuery>, res: Response): Promise<void> => {
|
async findOne(companyName: string, page: number, limit: number) {
|
||||||
try {
|
|
||||||
const { companyName } = req.params;
|
|
||||||
const decodedCompanyName = decodeURIComponent(companyName);
|
|
||||||
const { page = 1, limit = 20 } = req.query;
|
|
||||||
const offset = (page - 1) * limit;
|
const offset = (page - 1) * limit;
|
||||||
|
|
||||||
const companyInfo = await db.get('SELECT * FROM companies WHERE company_name = ?', [decodedCompanyName]);
|
const companyInfo = await this.dbService.get('SELECT * FROM companies WHERE company_name = ?', [companyName]);
|
||||||
|
|
||||||
if (!companyInfo) {
|
if (!companyInfo) {
|
||||||
res.status(404).json({ error: '企业不存在' });
|
throw new Error('企业不存在');
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const serialStats = await db.get(`
|
const serialStats = await this.dbService.get(`
|
||||||
SELECT COUNT(*) as serial_count,
|
SELECT COUNT(*) as serial_count,
|
||||||
SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active_count,
|
SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active_count,
|
||||||
SUM(CASE WHEN is_active = 0 THEN 1 ELSE 0 END) as disabled_count,
|
SUM(CASE WHEN is_active = 0 THEN 1 ELSE 0 END) as disabled_count,
|
||||||
SUM(CASE WHEN valid_until IS NOT NULL AND valid_until <= datetime('now') THEN 1 ELSE 0 END) as expired_count
|
SUM(CASE WHEN valid_until IS NOT NULL AND valid_until <= datetime('now') THEN 1 ELSE 0 END) as expired_count
|
||||||
FROM serials
|
FROM serials
|
||||||
WHERE company_name = ?
|
WHERE company_name = ?
|
||||||
`, [decodedCompanyName]);
|
`, [companyName]);
|
||||||
|
|
||||||
const serials = await db.all(`
|
const serials = await this.dbService.all(`
|
||||||
SELECT s.*, u.name as created_by_name
|
SELECT s.*, u.name as created_by_name
|
||||||
FROM serials s
|
FROM serials s
|
||||||
LEFT JOIN users u ON s.created_by = u.id
|
LEFT JOIN users u ON s.created_by = u.id
|
||||||
WHERE s.company_name = ?
|
WHERE s.company_name = ?
|
||||||
ORDER BY s.created_at DESC
|
ORDER BY s.created_at DESC
|
||||||
LIMIT ? OFFSET ?
|
LIMIT ? OFFSET ?
|
||||||
`, [decodedCompanyName, parseInt(limit.toString()), parseInt(offset.toString())]);
|
`, [companyName, parseInt(limit.toString()), parseInt(offset.toString())]);
|
||||||
|
|
||||||
const stats = await db.all<{ month: string; count: number }>(`
|
const stats = await this.dbService.all<{ month: string; count: number }>(`
|
||||||
SELECT strftime('%Y-%m', created_at) as month,
|
SELECT strftime('%Y-%m', created_at) as month,
|
||||||
COUNT(*) as count
|
COUNT(*) as count
|
||||||
FROM serials
|
FROM serials
|
||||||
@@ -94,12 +83,12 @@ router.get('/:companyName', authenticateToken, requireAdmin, async (req: Request
|
|||||||
GROUP BY strftime('%Y-%m', created_at)
|
GROUP BY strftime('%Y-%m', created_at)
|
||||||
ORDER BY month DESC
|
ORDER BY month DESC
|
||||||
LIMIT 12
|
LIMIT 12
|
||||||
`, [decodedCompanyName]);
|
`, [companyName]);
|
||||||
|
|
||||||
res.json({
|
return {
|
||||||
message: '获取企业详情成功',
|
message: '获取企业详情成功',
|
||||||
data: {
|
data: {
|
||||||
companyName: decodedCompanyName,
|
companyName: companyName,
|
||||||
serialCount: serialStats?.serial_count || 0,
|
serialCount: serialStats?.serial_count || 0,
|
||||||
activeCount: serialStats?.active_count || 0,
|
activeCount: serialStats?.active_count || 0,
|
||||||
disabledCount: serialStats?.disabled_count || 0,
|
disabledCount: serialStats?.disabled_count || 0,
|
||||||
@@ -119,129 +108,142 @@ router.get('/:companyName', authenticateToken, requireAdmin, async (req: Request
|
|||||||
count: stat.count
|
count: stat.count
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
});
|
};
|
||||||
} catch (error) {
|
|
||||||
console.error('获取企业详情错误:', error);
|
|
||||||
res.status(500).json({ error: '服务器内部错误' });
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
router.patch('/:companyName', authenticateToken, requireAdmin, async (req: Request<{ companyName: string }, {}, UpdateCompanyRequest>, res: Response): Promise<void> => {
|
async update(companyName: string, newCompanyName: string) {
|
||||||
try {
|
const existingCompany = await this.dbService.get(
|
||||||
const { companyName } = req.params;
|
|
||||||
const decodedCompanyName = decodeURIComponent(companyName);
|
|
||||||
const { newCompanyName } = req.body;
|
|
||||||
|
|
||||||
if (!newCompanyName || newCompanyName.trim() === '') {
|
|
||||||
res.status(400).json({ error: '新企业名称不能为空' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const existingCompany = db.get(
|
|
||||||
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
||||||
[decodedCompanyName]
|
[companyName]
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!existingCompany || existingCompany.count === 0) {
|
if (!existingCompany || (existingCompany as any).count === 0) {
|
||||||
res.status(404).json({ error: '企业不存在' });
|
throw new Error('企业不存在');
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const duplicateCompany = db.get(
|
const duplicateCompany = await this.dbService.get(
|
||||||
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
||||||
[newCompanyName]
|
[newCompanyName]
|
||||||
);
|
);
|
||||||
|
|
||||||
if (duplicateCompany && duplicateCompany.count > 0) {
|
if (duplicateCompany && (duplicateCompany as any).count > 0) {
|
||||||
res.status(400).json({ error: '企业名称已存在' });
|
throw new Error('企业名称已存在');
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
db.run(
|
this.dbService.run(
|
||||||
'UPDATE serials SET company_name = ?, updated_at = CURRENT_TIMESTAMP WHERE company_name = ?',
|
'UPDATE serials SET company_name = ?, updated_at = CURRENT_TIMESTAMP WHERE company_name = ?',
|
||||||
[newCompanyName, decodedCompanyName]
|
[newCompanyName, companyName]
|
||||||
);
|
);
|
||||||
|
|
||||||
res.json({
|
return {
|
||||||
message: '企业名称更新成功',
|
message: '企业名称更新成功',
|
||||||
data: {
|
data: {
|
||||||
oldCompanyName: decodedCompanyName,
|
oldCompanyName: companyName,
|
||||||
newCompanyName
|
newCompanyName
|
||||||
}
|
}
|
||||||
});
|
};
|
||||||
} catch (error) {
|
|
||||||
console.error('更新企业信息错误:', error);
|
|
||||||
res.status(500).json({ error: '服务器内部错误' });
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
router.delete('/:companyName', authenticateToken, requireAdmin, async (req: Request<{ companyName: string }>, res: Response): Promise<void> => {
|
async delete(companyName: string) {
|
||||||
try {
|
const existingCompany = await this.dbService.get(
|
||||||
const { companyName } = req.params;
|
|
||||||
const decodedCompanyName = decodeURIComponent(companyName);
|
|
||||||
|
|
||||||
const existingCompany = await db.get(
|
|
||||||
'SELECT * FROM companies WHERE company_name = ?',
|
'SELECT * FROM companies WHERE company_name = ?',
|
||||||
[decodedCompanyName]
|
[companyName]
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!existingCompany) {
|
if (!existingCompany) {
|
||||||
res.status(404).json({ error: '企业不存在' });
|
throw new Error('企业不存在');
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
db.run('BEGIN TRANSACTION');
|
this.dbService.run('BEGIN TRANSACTION');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const serialDeleteResult = db.run(
|
const serialDeleteResult = this.dbService.run(
|
||||||
'DELETE FROM serials WHERE company_name = ?',
|
'DELETE FROM serials WHERE company_name = ?',
|
||||||
[decodedCompanyName]
|
[companyName]
|
||||||
);
|
);
|
||||||
|
|
||||||
const companyDeleteResult = db.run(
|
const companyDeleteResult = this.dbService.run(
|
||||||
'DELETE FROM companies WHERE company_name = ?',
|
'DELETE FROM companies WHERE company_name = ?',
|
||||||
[decodedCompanyName]
|
[companyName]
|
||||||
);
|
);
|
||||||
|
|
||||||
if (companyDeleteResult.changes === 0) {
|
if (companyDeleteResult.changes === 0) {
|
||||||
db.run('ROLLBACK');
|
this.dbService.run('ROLLBACK');
|
||||||
res.status(404).json({ error: '企业不存在' });
|
throw new Error('企业不存在');
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
db.run('COMMIT');
|
this.dbService.run('COMMIT');
|
||||||
|
|
||||||
res.json({
|
return {
|
||||||
message: '企业已完全删除,所有相关序列号已删除',
|
message: '企业已完全删除,所有相关序列号已删除',
|
||||||
data: {
|
data: {
|
||||||
companyName: decodedCompanyName,
|
companyName: companyName,
|
||||||
deletedSerialCount: serialDeleteResult.changes,
|
deletedSerialCount: serialDeleteResult.changes,
|
||||||
deletedCompanyCount: companyDeleteResult.changes
|
deletedCompanyCount: companyDeleteResult.changes
|
||||||
}
|
}
|
||||||
});
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('删除企业过程中错误:', error);
|
this.dbService.run('ROLLBACK');
|
||||||
db.run('ROLLBACK');
|
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
} catch (error) {
|
|
||||||
console.error('删除企业错误:', error);
|
|
||||||
res.status(500).json({ error: '服务器内部错误' });
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
router.get('/stats/overview', authenticateToken, requireAdmin, async (req: Request, res: Response): Promise<void> => {
|
async deleteSerial(companyName: string, serialNumber: string) {
|
||||||
try {
|
const serial = await this.dbService.get(
|
||||||
const companyCount = await db.get<{ count: number }>('SELECT COUNT(*) as count FROM companies');
|
'SELECT * FROM serials WHERE serial_number = ? AND company_name = ?',
|
||||||
|
[serialNumber.toUpperCase(), companyName]
|
||||||
|
);
|
||||||
|
|
||||||
const serialCount = await db.get<{ count: number }>('SELECT COUNT(*) as count FROM serials');
|
if (!serial) {
|
||||||
|
throw new Error('序列号不存在或不属于该企业');
|
||||||
|
}
|
||||||
|
|
||||||
const activeCount = await db.get<{ count: number }>(`
|
await this.dbService.run(
|
||||||
|
'DELETE FROM serials WHERE serial_number = ? AND company_name = ?',
|
||||||
|
[serialNumber.toUpperCase(), companyName]
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
message: '序列号已成功删除',
|
||||||
|
data: {
|
||||||
|
serialNumber: serialNumber.toUpperCase(),
|
||||||
|
companyName
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async revoke(companyName: string) {
|
||||||
|
const existingCompany = await this.dbService.get(
|
||||||
|
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
||||||
|
[companyName]
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!existingCompany || (existingCompany as any).count === 0) {
|
||||||
|
throw new Error('企业不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.dbService.run(
|
||||||
|
'UPDATE serials SET is_active = 0, updated_at = CURRENT_TIMESTAMP WHERE company_name = ?',
|
||||||
|
[companyName]
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
message: '企业已吊销,所有序列号已失效',
|
||||||
|
data: {
|
||||||
|
companyName: companyName
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async getStats() {
|
||||||
|
const companyCount = await this.dbService.get<{ count: number }>('SELECT COUNT(*) as count FROM companies');
|
||||||
|
const serialCount = await this.dbService.get<{ count: number }>('SELECT COUNT(*) as count FROM serials');
|
||||||
|
const activeCount = await this.dbService.get<{ count: number }>(`
|
||||||
SELECT COUNT(*) as count FROM serials
|
SELECT COUNT(*) as count FROM serials
|
||||||
WHERE is_active = 1 AND (valid_until IS NULL OR valid_until > datetime('now'))
|
WHERE is_active = 1 AND (valid_until IS NULL OR valid_until > datetime('now'))
|
||||||
`);
|
`);
|
||||||
|
|
||||||
const monthlyStats = await db.all<{ month: string; company_count: number; serial_count: number }>(`
|
const monthlyStats = await this.dbService.all<{ month: string; company_count: number; serial_count: number }>(`
|
||||||
SELECT strftime('%Y-%m', created_at) as month,
|
SELECT strftime('%Y-%m', created_at) as month,
|
||||||
COUNT(DISTINCT company_name) as company_count,
|
COUNT(DISTINCT company_name) as company_count,
|
||||||
COUNT(*) as serial_count
|
COUNT(*) as serial_count
|
||||||
@@ -251,14 +253,14 @@ router.get('/stats/overview', authenticateToken, requireAdmin, async (req: Reque
|
|||||||
ORDER BY month ASC
|
ORDER BY month ASC
|
||||||
`);
|
`);
|
||||||
|
|
||||||
const recentCompanies = await db.all<{ company_name: string; last_created: string; is_active: number }>(`
|
const recentCompanies = await this.dbService.all<{ company_name: string; last_created: string; is_active: number }>(`
|
||||||
SELECT c.company_name, c.created_at as last_created, c.is_active
|
SELECT c.company_name, c.created_at as last_created, c.is_active
|
||||||
FROM companies c
|
FROM companies c
|
||||||
ORDER BY c.updated_at DESC
|
ORDER BY c.updated_at DESC
|
||||||
LIMIT 10
|
LIMIT 10
|
||||||
`);
|
`);
|
||||||
|
|
||||||
const recentSerials = await db.all<{ serial_number: string; company_name: string; is_active: number; created_at: string }>(`
|
const recentSerials = await this.dbService.all<{ serial_number: string; company_name: string; is_active: number; created_at: string }>(`
|
||||||
SELECT s.serial_number, s.company_name, s.is_active, s.created_at
|
SELECT s.serial_number, s.company_name, s.is_active, s.created_at
|
||||||
FROM serials s
|
FROM serials s
|
||||||
ORDER BY s.created_at DESC
|
ORDER BY s.created_at DESC
|
||||||
@@ -280,7 +282,7 @@ router.get('/stats/overview', authenticateToken, requireAdmin, async (req: Reque
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
res.json({
|
return {
|
||||||
message: '获取统计数据成功',
|
message: '获取统计数据成功',
|
||||||
data: {
|
data: {
|
||||||
overview: {
|
overview: {
|
||||||
@@ -306,75 +308,6 @@ router.get('/stats/overview', authenticateToken, requireAdmin, async (req: Reque
|
|||||||
createdAt: s.created_at
|
createdAt: s.created_at
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
});
|
};
|
||||||
} catch (error) {
|
|
||||||
console.error('获取统计数据错误:', error);
|
|
||||||
res.status(500).json({ error: '服务器内部错误' });
|
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
|
|
||||||
router.delete('/:companyName/serials/:serialNumber', authenticateToken, requireAdmin, async (req: Request<{ companyName: string; serialNumber: string }>, res: Response): Promise<void> => {
|
|
||||||
try {
|
|
||||||
const { companyName, serialNumber } = req.params;
|
|
||||||
|
|
||||||
const serial = await db.get(
|
|
||||||
'SELECT * FROM serials WHERE serial_number = ? AND company_name = ?',
|
|
||||||
[serialNumber.toUpperCase(), companyName]
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!serial) {
|
|
||||||
res.status(404).json({ error: '序列号不存在或不属于该企业' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await db.run(
|
|
||||||
'DELETE FROM serials WHERE serial_number = ? AND company_name = ?',
|
|
||||||
[serialNumber.toUpperCase(), companyName]
|
|
||||||
);
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
message: '序列号已成功删除',
|
|
||||||
data: {
|
|
||||||
serialNumber: serialNumber.toUpperCase(),
|
|
||||||
companyName
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('删除序列号错误:', error);
|
|
||||||
res.status(500).json({ error: '服务器内部错误' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.post('/:companyName/revoke', authenticateToken, requireAdmin, async (req: Request<{ companyName: string }>, res: Response): Promise<void> => {
|
|
||||||
try {
|
|
||||||
const { companyName } = req.params;
|
|
||||||
const decodedCompanyName = decodeURIComponent(companyName);
|
|
||||||
|
|
||||||
const existingCompany = await db.get(
|
|
||||||
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
|
||||||
[decodedCompanyName]
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!existingCompany || existingCompany.count === 0) {
|
|
||||||
res.status(404).json({ error: '企业不存在' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await db.run(
|
|
||||||
'UPDATE serials SET is_active = 0, updated_at = CURRENT_TIMESTAMP WHERE company_name = ?',
|
|
||||||
[decodedCompanyName]
|
|
||||||
);
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
message: '企业已吊销,所有序列号已失效',
|
|
||||||
data: {
|
|
||||||
companyName: decodedCompanyName
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('吊销企业错误:', error);
|
|
||||||
res.status(500).json({ error: '服务器内部错误' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
export default router;
|
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { Module, Global } from '@nestjs/common';
|
||||||
|
import { DatabaseService } from './database.service';
|
||||||
|
|
||||||
|
@Global()
|
||||||
|
@Module({
|
||||||
|
providers: [DatabaseService],
|
||||||
|
exports: [DatabaseService],
|
||||||
|
})
|
||||||
|
export class DatabaseModule {}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import Database from 'better-sqlite3';
|
||||||
|
import * as path from 'path';
|
||||||
|
import * as fs from 'fs';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class DatabaseService implements OnModuleInit, OnModuleDestroy {
|
||||||
|
private db: Database.Database;
|
||||||
|
private dbPath: string;
|
||||||
|
|
||||||
|
constructor(private configService: ConfigService) {}
|
||||||
|
|
||||||
|
onModuleInit() {
|
||||||
|
this.dbPath = this.configService.get<string>('DB_PATH', path.join(process.cwd(), 'data/database.sqlite'));
|
||||||
|
const dbDir = path.dirname(this.dbPath);
|
||||||
|
|
||||||
|
if (!fs.existsSync(dbDir)) {
|
||||||
|
fs.mkdirSync(dbDir, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
this.db = new Database(this.dbPath, { verbose: console.log });
|
||||||
|
}
|
||||||
|
|
||||||
|
onModuleDestroy() {
|
||||||
|
this.db.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
get<T = any>(sql: string, params: any[] = []): T | undefined {
|
||||||
|
try {
|
||||||
|
const stmt = this.db.prepare(sql);
|
||||||
|
return stmt.get(params) as T | undefined;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('数据库查询错误:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
all<T = any>(sql: string, params: any[] = []): T[] {
|
||||||
|
try {
|
||||||
|
const stmt = this.db.prepare(sql);
|
||||||
|
return stmt.all(params) as T[];
|
||||||
|
} catch (error) {
|
||||||
|
console.error('数据库查询错误:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
run(sql: string, params: any[] = []): { id: number; changes: number } {
|
||||||
|
try {
|
||||||
|
const stmt = this.db.prepare(sql);
|
||||||
|
const result = stmt.run(params);
|
||||||
|
return { id: result.lastInsertRowid as number, changes: result.changes };
|
||||||
|
} catch (error) {
|
||||||
|
console.error('数据库操作错误:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import Database from 'better-sqlite3';
|
||||||
|
import path from 'path';
|
||||||
|
import fs from 'fs';
|
||||||
|
|
||||||
|
class DatabaseWrapper {
|
||||||
|
private db: Database.Database;
|
||||||
|
private dbPath: string;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.dbPath = process.env.DB_PATH || path.join(process.cwd(), 'data/database.sqlite');
|
||||||
|
const dbDir = path.dirname(this.dbPath);
|
||||||
|
|
||||||
|
if (!fs.existsSync(dbDir)) {
|
||||||
|
fs.mkdirSync(dbDir, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
this.db = new Database(this.dbPath, { verbose: console.log });
|
||||||
|
}
|
||||||
|
|
||||||
|
get<T = any>(sql: string, params: any[] = []): T | undefined {
|
||||||
|
try {
|
||||||
|
const stmt = this.db.prepare(sql);
|
||||||
|
return stmt.get(params) as T | undefined;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('数据库查询错误:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
all<T = any>(sql: string, params: any[] = []): T[] {
|
||||||
|
try {
|
||||||
|
const stmt = this.db.prepare(sql);
|
||||||
|
return stmt.all(params) as T[];
|
||||||
|
} catch (error) {
|
||||||
|
console.error('数据库查询错误:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
run(sql: string, params: any[] = []): { id: number; changes: number } {
|
||||||
|
try {
|
||||||
|
const stmt = this.db.prepare(sql);
|
||||||
|
const result = stmt.run(params);
|
||||||
|
return { id: result.lastInsertRowid as number, changes: result.changes };
|
||||||
|
} catch (error) {
|
||||||
|
console.error('数据库操作错误:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
close(): void {
|
||||||
|
this.db.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default new DatabaseWrapper();
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { Controller, Get } from '@nestjs/common';
|
||||||
|
|
||||||
|
@Controller('health')
|
||||||
|
export class HealthController {
|
||||||
|
@Get()
|
||||||
|
check() {
|
||||||
|
return { status: 'ok', message: '服务器运行正常' };
|
||||||
|
}
|
||||||
|
}
|
||||||
+34
@@ -0,0 +1,34 @@
|
|||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import { AppModule } from './app.module';
|
||||||
|
import { ValidationPipe } from '@nestjs/common';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { join } from 'path';
|
||||||
|
import { NestExpressApplication } from '@nestjs/platform-express';
|
||||||
|
|
||||||
|
async function bootstrap() {
|
||||||
|
const app = await NestFactory.create<NestExpressApplication>(AppModule);
|
||||||
|
const configService = app.get(ConfigService);
|
||||||
|
|
||||||
|
app.enableCors();
|
||||||
|
app.useGlobalPipes(new ValidationPipe({ transform: true }));
|
||||||
|
app.setGlobalPrefix('api');
|
||||||
|
|
||||||
|
// 静态文件服务
|
||||||
|
const frontendPath = join(__dirname, '..', 'frontend');
|
||||||
|
const distPath = join(frontendPath, 'dist');
|
||||||
|
const publicPath = join(frontendPath, 'public');
|
||||||
|
|
||||||
|
if (process.env.NODE_ENV === 'production') {
|
||||||
|
app.useStaticAssets(distPath);
|
||||||
|
} else {
|
||||||
|
app.useStaticAssets(publicPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
const port = configService.get<number>('PORT', 3000);
|
||||||
|
await app.listen(port);
|
||||||
|
|
||||||
|
console.log(`服务器运行在 http://localhost:${port}`);
|
||||||
|
console.log(`API文档: http://localhost:${port}/api/health`);
|
||||||
|
console.log(`环境: ${process.env.NODE_ENV || 'development'}`);
|
||||||
|
}
|
||||||
|
bootstrap();
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import { IsString, IsNotEmpty, IsNumber, IsOptional, IsBoolean, Min, Max } from 'class-validator';
|
||||||
|
|
||||||
|
export class GenerateSerialDto {
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty({ message: '企业名称不能为空' })
|
||||||
|
companyName: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsNumber()
|
||||||
|
@Min(1)
|
||||||
|
@Max(100)
|
||||||
|
quantity?: number;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsNumber()
|
||||||
|
validDays?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GenerateWithPrefixDto extends GenerateSerialDto {
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty({ message: '自定义前缀不能为空' })
|
||||||
|
serialPrefix: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class QRCodeDto {
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
baseUrl?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UpdateSerialDto {
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
companyName?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
validUntil?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
isActive?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Serial {
|
||||||
|
id: number;
|
||||||
|
serial_number: string;
|
||||||
|
company_name: string;
|
||||||
|
valid_until: string | null;
|
||||||
|
is_active: boolean;
|
||||||
|
created_by: number | null;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SerialListItem {
|
||||||
|
serialNumber: string;
|
||||||
|
companyName: string;
|
||||||
|
validUntil: string | null;
|
||||||
|
isActive: boolean;
|
||||||
|
createdAt: string;
|
||||||
|
createdBy?: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import { Controller, Get, Post, Patch, Body, Param, Query, UseGuards, Req, HttpCode, HttpStatus } from '@nestjs/common';
|
||||||
|
import { Request } from 'express';
|
||||||
|
import { SerialsService } from './serials.service';
|
||||||
|
import { AuthGuard } from '../auth/auth.guard';
|
||||||
|
import { AdminGuard } from '../auth/admin.guard';
|
||||||
|
import { GenerateSerialDto, GenerateWithPrefixDto, QRCodeDto, UpdateSerialDto } from './dto';
|
||||||
|
|
||||||
|
@Controller('serials')
|
||||||
|
export class SerialsController {
|
||||||
|
constructor(private readonly serialsService: SerialsService) {}
|
||||||
|
|
||||||
|
@Post('generate')
|
||||||
|
@UseGuards(AuthGuard, AdminGuard)
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
async generate(@Body() generateDto: GenerateSerialDto, @Req() req: Request) {
|
||||||
|
const serials = await this.serialsService.generate(
|
||||||
|
generateDto.companyName,
|
||||||
|
generateDto.quantity || 1,
|
||||||
|
generateDto.validDays || 365,
|
||||||
|
(req as any).user.id,
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
message: `成功生成${serials.length}个序列号`,
|
||||||
|
serials,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('generate-with-prefix')
|
||||||
|
@UseGuards(AuthGuard, AdminGuard)
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
async generateWithPrefix(@Body() generateDto: GenerateWithPrefixDto, @Req() req: Request) {
|
||||||
|
const serials = await this.serialsService.generate(
|
||||||
|
generateDto.companyName,
|
||||||
|
generateDto.quantity || 1,
|
||||||
|
generateDto.validDays || 365,
|
||||||
|
(req as any).user.id,
|
||||||
|
generateDto.serialPrefix,
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
message: `成功生成${serials.length}个序列号`,
|
||||||
|
serials,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post(':serialNumber/qrcode')
|
||||||
|
@UseGuards(AuthGuard)
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
async generateQRCode(
|
||||||
|
@Param('serialNumber') serialNumber: string,
|
||||||
|
@Body() qrCodeDto: QRCodeDto,
|
||||||
|
@Req() req: Request,
|
||||||
|
) {
|
||||||
|
return this.serialsService.generateQRCode(
|
||||||
|
serialNumber,
|
||||||
|
qrCodeDto.baseUrl,
|
||||||
|
req.get('host'),
|
||||||
|
req.protocol,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':serialNumber/query')
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
async query(@Param('serialNumber') serialNumber: string) {
|
||||||
|
return this.serialsService.query(serialNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
@UseGuards(AuthGuard)
|
||||||
|
async findAll(
|
||||||
|
@Query('page') page: string = '1',
|
||||||
|
@Query('limit') limit: string = '20',
|
||||||
|
@Query('search') search: string = '',
|
||||||
|
) {
|
||||||
|
return this.serialsService.findAll(parseInt(page), parseInt(limit), search);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch(':serialNumber')
|
||||||
|
@UseGuards(AuthGuard, AdminGuard)
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
async update(
|
||||||
|
@Param('serialNumber') serialNumber: string,
|
||||||
|
@Body() updateDto: UpdateSerialDto,
|
||||||
|
) {
|
||||||
|
return this.serialsService.update(serialNumber, {
|
||||||
|
companyName: updateDto.companyName,
|
||||||
|
validUntil: updateDto.validUntil,
|
||||||
|
isActive: updateDto.isActive,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post(':serialNumber/revoke')
|
||||||
|
@UseGuards(AuthGuard, AdminGuard)
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
async revoke(@Param('serialNumber') serialNumber: string) {
|
||||||
|
return this.serialsService.revoke(serialNumber);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { SerialsService } from './serials.service';
|
||||||
|
import { SerialsController } from './serials.controller';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
controllers: [SerialsController],
|
||||||
|
providers: [SerialsService],
|
||||||
|
})
|
||||||
|
export class SerialsModule {}
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { DatabaseService } from '../database/database.service';
|
||||||
|
import * as QRCode from 'qrcode';
|
||||||
|
import { Serial, SerialListItem } from './dto';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SerialsService {
|
||||||
|
constructor(private dbService: DatabaseService) {}
|
||||||
|
|
||||||
|
async generate(companyName: string, quantity: number, validDays: number, userId: number, serialPrefix?: string): Promise<SerialListItem[]> {
|
||||||
|
const validUntil = new Date();
|
||||||
|
validUntil.setDate(validUntil.getDate() + validDays);
|
||||||
|
|
||||||
|
const existingCompany = await this.dbService.get('SELECT * FROM companies WHERE company_name = ?', [companyName]);
|
||||||
|
if (!existingCompany) {
|
||||||
|
await this.dbService.run('INSERT INTO companies (company_name, is_active) VALUES (?, 1)', [companyName]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const serials: SerialListItem[] = [];
|
||||||
|
const prefix = serialPrefix ? serialPrefix.toUpperCase().replace(/[^A-Z0-9]/g, '') : 'BF' + new Date().getFullYear().toString().substr(2);
|
||||||
|
|
||||||
|
for (let i = 0; i < quantity; i++) {
|
||||||
|
const randomPart = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
|
||||||
|
const serialNumber = `${prefix}${randomPart}`;
|
||||||
|
|
||||||
|
await this.dbService.run(
|
||||||
|
'INSERT INTO serials (serial_number, company_name, valid_until, created_by) VALUES (?, ?, ?, ?)',
|
||||||
|
[serialNumber, companyName, validUntil.toISOString().slice(0, 19).replace('T', ' '), userId]
|
||||||
|
);
|
||||||
|
|
||||||
|
serials.push({
|
||||||
|
serialNumber,
|
||||||
|
companyName,
|
||||||
|
validUntil: validUntil.toISOString(),
|
||||||
|
isActive: true,
|
||||||
|
createdAt: new Date().toISOString()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return serials;
|
||||||
|
}
|
||||||
|
|
||||||
|
async generateQRCode(serialNumber: string, baseUrl?: string, requestHost?: string, protocol?: string) {
|
||||||
|
const serial = await this.dbService.get<{ serial_number: string; company_name: string; is_active: number; valid_until: string | null }>(
|
||||||
|
'SELECT s.*, u.name as created_by_name FROM serials s LEFT JOIN users u ON s.created_by = u.id WHERE s.serial_number = ?',
|
||||||
|
[serialNumber.toUpperCase()]
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!serial) {
|
||||||
|
throw new Error('序列号不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!serial.is_active) {
|
||||||
|
throw new Error('序列号已被禁用');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (serial.valid_until && new Date(serial.valid_until) < new Date()) {
|
||||||
|
throw new Error('序列号已过期');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!baseUrl) {
|
||||||
|
baseUrl = `${protocol}://${requestHost}/query.html`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const queryUrl = baseUrl.includes('?')
|
||||||
|
? `${baseUrl}&serial=${serial.serial_number}`
|
||||||
|
: `${baseUrl}?serial=${serial.serial_number}`;
|
||||||
|
|
||||||
|
const qrCodeData = await QRCode.toDataURL(queryUrl, {
|
||||||
|
width: 200,
|
||||||
|
color: {
|
||||||
|
dark: '#165DFF',
|
||||||
|
light: '#ffffff'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
message: '二维码生成成功',
|
||||||
|
qrCodeData,
|
||||||
|
queryUrl,
|
||||||
|
serialNumber: serial.serial_number,
|
||||||
|
companyName: serial.company_name,
|
||||||
|
validUntil: serial.valid_until
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async query(serialNumber: string) {
|
||||||
|
const serial = await this.dbService.get<{ serial_number: string; company_name: string; valid_until: string | null; is_active: number; created_at: string; created_by_name: string }>(
|
||||||
|
'SELECT s.*, u.name as created_by_name FROM serials s LEFT JOIN users u ON s.created_by = u.id WHERE s.serial_number = ?',
|
||||||
|
[serialNumber.toUpperCase()]
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!serial) {
|
||||||
|
throw new Error('序列号不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (serial.valid_until && new Date(serial.valid_until) < new Date()) {
|
||||||
|
throw new Error('序列号已过期');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
message: '查询成功',
|
||||||
|
serial: {
|
||||||
|
serialNumber: serial.serial_number,
|
||||||
|
companyName: serial.company_name,
|
||||||
|
validUntil: serial.valid_until,
|
||||||
|
status: serial.is_active ? 'active' : 'disabled',
|
||||||
|
isActive: !!serial.is_active,
|
||||||
|
createdAt: serial.created_at,
|
||||||
|
createdBy: serial.created_by_name
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAll(page: number, limit: number, search: string) {
|
||||||
|
const offset = (page - 1) * limit;
|
||||||
|
|
||||||
|
let query = 'SELECT s.*, u.name as created_by_name FROM serials s LEFT JOIN users u ON s.created_by = u.id';
|
||||||
|
let countQuery = 'SELECT COUNT(*) as total FROM serials s';
|
||||||
|
let params: any[] = [];
|
||||||
|
|
||||||
|
if (search) {
|
||||||
|
query += ' WHERE s.serial_number LIKE ? OR s.company_name LIKE ?';
|
||||||
|
countQuery += ' WHERE s.serial_number LIKE ? OR s.company_name LIKE ?';
|
||||||
|
const searchParam = `%${search}%`;
|
||||||
|
params.push(searchParam, searchParam);
|
||||||
|
}
|
||||||
|
|
||||||
|
query += ' ORDER BY s.created_at DESC LIMIT ? OFFSET ?';
|
||||||
|
params.push(parseInt(limit.toString()), parseInt(offset.toString()));
|
||||||
|
|
||||||
|
const [serials, countResult] = await Promise.all([
|
||||||
|
this.dbService.all(query, params),
|
||||||
|
this.dbService.get<{ total: number }>(countQuery, params.slice(0, -2))
|
||||||
|
]);
|
||||||
|
|
||||||
|
const total = countResult?.total || 0;
|
||||||
|
const totalPages = Math.ceil(total / limit);
|
||||||
|
|
||||||
|
return {
|
||||||
|
message: '获取序列号列表成功',
|
||||||
|
data: serials.map((s: any) => ({
|
||||||
|
serialNumber: s.serial_number,
|
||||||
|
companyName: s.company_name,
|
||||||
|
validUntil: s.valid_until,
|
||||||
|
isActive: s.is_active,
|
||||||
|
createdAt: s.created_at,
|
||||||
|
createdBy: s.created_by_name
|
||||||
|
})),
|
||||||
|
pagination: {
|
||||||
|
page: parseInt(page.toString()),
|
||||||
|
limit: parseInt(limit.toString()),
|
||||||
|
total,
|
||||||
|
totalPages
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(serialNumber: string, updateData: { companyName?: string; validUntil?: string; isActive?: boolean }) {
|
||||||
|
const existingSerial = await this.dbService.get<{ is_active: number }>('SELECT * FROM serials WHERE serial_number = ?', [serialNumber.toUpperCase()]);
|
||||||
|
|
||||||
|
if (!existingSerial) {
|
||||||
|
throw new Error('序列号不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateFields: string[] = [];
|
||||||
|
const params: any[] = [];
|
||||||
|
|
||||||
|
if (updateData.companyName !== undefined) {
|
||||||
|
updateFields.push('company_name = ?');
|
||||||
|
params.push(updateData.companyName);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (updateData.validUntil !== undefined) {
|
||||||
|
updateFields.push('valid_until = ?');
|
||||||
|
params.push(updateData.validUntil);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (updateData.isActive !== undefined) {
|
||||||
|
updateFields.push('is_active = ?');
|
||||||
|
params.push(updateData.isActive ? 1 : 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (updateFields.length === 0) {
|
||||||
|
throw new Error('没有提供更新字段');
|
||||||
|
}
|
||||||
|
|
||||||
|
updateFields.push('updated_at = CURRENT_TIMESTAMP');
|
||||||
|
params.push(serialNumber.toUpperCase());
|
||||||
|
|
||||||
|
await this.dbService.run(
|
||||||
|
`UPDATE serials SET ${updateFields.join(', ')} WHERE serial_number = ?`,
|
||||||
|
params
|
||||||
|
);
|
||||||
|
|
||||||
|
const updatedSerial = await this.dbService.get('SELECT s.*, u.name as created_by_name FROM serials s LEFT JOIN users u ON s.created_by = u.id WHERE s.serial_number = ?', [serialNumber.toUpperCase()]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
message: '序列号更新成功',
|
||||||
|
serial: {
|
||||||
|
serialNumber: (updatedSerial as any).serial_number,
|
||||||
|
companyName: (updatedSerial as any).company_name,
|
||||||
|
validUntil: (updatedSerial as any).valid_until,
|
||||||
|
isActive: (updatedSerial as any).is_active,
|
||||||
|
createdAt: (updatedSerial as any).created_at,
|
||||||
|
updatedAt: (updatedSerial as any).updated_at,
|
||||||
|
createdBy: (updatedSerial as any).created_by_name
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async revoke(serialNumber: string) {
|
||||||
|
const existingSerial = await this.dbService.get<{ is_active: number }>('SELECT * FROM serials WHERE serial_number = ?', [serialNumber.toUpperCase()]);
|
||||||
|
|
||||||
|
if (!existingSerial) {
|
||||||
|
throw new Error('序列号不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!existingSerial.is_active) {
|
||||||
|
throw new Error('序列号已被吊销');
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.dbService.run(
|
||||||
|
'UPDATE serials SET is_active = 0, updated_at = CURRENT_TIMESTAMP WHERE serial_number = ?',
|
||||||
|
[serialNumber.toUpperCase()]
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
message: '序列号已吊销',
|
||||||
|
data: {
|
||||||
|
serialNumber: serialNumber.toUpperCase()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+160
@@ -0,0 +1,160 @@
|
|||||||
|
export interface User {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
password: string;
|
||||||
|
name: string;
|
||||||
|
email: string | null;
|
||||||
|
role: 'admin' | 'user';
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Company {
|
||||||
|
id: number;
|
||||||
|
company_name: string;
|
||||||
|
is_active: boolean;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Serial {
|
||||||
|
id: number;
|
||||||
|
serial_number: string;
|
||||||
|
company_name: string;
|
||||||
|
valid_until: string | null;
|
||||||
|
is_active: boolean;
|
||||||
|
created_by: number | null;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
created_by_name?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AuthUser {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
name: string;
|
||||||
|
role: 'admin' | 'user';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface JWTPayload {
|
||||||
|
userId: number;
|
||||||
|
username: string;
|
||||||
|
role: 'admin' | 'user';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoginRequest {
|
||||||
|
username: string;
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChangePasswordRequest {
|
||||||
|
currentPassword: string;
|
||||||
|
newPassword: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GenerateSerialRequest {
|
||||||
|
companyName: string;
|
||||||
|
quantity?: number;
|
||||||
|
validDays?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GenerateSerialWithPrefixRequest {
|
||||||
|
companyName: string;
|
||||||
|
quantity?: number;
|
||||||
|
validDays?: number;
|
||||||
|
serialPrefix: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QRCodeRequest {
|
||||||
|
baseUrl?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpdateSerialRequest {
|
||||||
|
companyName?: string;
|
||||||
|
validUntil?: string;
|
||||||
|
isActive?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpdateCompanyRequest {
|
||||||
|
newCompanyName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PaginationQuery {
|
||||||
|
page?: number;
|
||||||
|
limit?: number;
|
||||||
|
search?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PaginationResponse {
|
||||||
|
page: number;
|
||||||
|
limit: number;
|
||||||
|
total: number;
|
||||||
|
totalPages: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiResponse<T = any> {
|
||||||
|
message: string;
|
||||||
|
data?: T;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoginResponse {
|
||||||
|
accessToken: string;
|
||||||
|
user: {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
name: string;
|
||||||
|
email: string | null;
|
||||||
|
role: 'admin' | 'user';
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SerialListItem {
|
||||||
|
serialNumber: string;
|
||||||
|
companyName: string;
|
||||||
|
validUntil: string | null;
|
||||||
|
isActive: boolean;
|
||||||
|
createdAt: string;
|
||||||
|
createdBy?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CompanyListItem {
|
||||||
|
companyName: string;
|
||||||
|
firstCreated: string;
|
||||||
|
lastCreated: string;
|
||||||
|
serialCount: number;
|
||||||
|
activeCount: number;
|
||||||
|
status: 'active' | 'disabled';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CompanyDetail {
|
||||||
|
companyName: string;
|
||||||
|
serialCount: number;
|
||||||
|
activeCount: number;
|
||||||
|
disabledCount: number;
|
||||||
|
expiredCount: number;
|
||||||
|
firstCreated: string;
|
||||||
|
lastCreated: string;
|
||||||
|
status: 'active' | 'disabled';
|
||||||
|
serials: SerialListItem[];
|
||||||
|
monthlyStats: MonthlyStat[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MonthlyStat {
|
||||||
|
month: string;
|
||||||
|
count: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StatsOverview {
|
||||||
|
totalCompanies: number;
|
||||||
|
totalSerials: number;
|
||||||
|
activeSerials: number;
|
||||||
|
inactiveSerials: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StatsResponse {
|
||||||
|
overview: StatsOverview;
|
||||||
|
monthlyStats: Array<{ month: string; company_count: number; serial_count: number }>;
|
||||||
|
recentCompanies: Array<{ companyName: string; lastCreated: string; status: 'active' | 'disabled' }>;
|
||||||
|
recentSerials: Array<{ serialNumber: string; companyName: string; isActive: boolean; createdAt: string }>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import Database from 'better-sqlite3';
|
||||||
|
import path from 'path';
|
||||||
|
import fs from 'fs';
|
||||||
|
|
||||||
|
class DatabaseWrapper {
|
||||||
|
private db: Database.Database;
|
||||||
|
private dbPath: string;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.dbPath = process.env.DB_PATH || path.join(process.cwd(), 'data/database.sqlite');
|
||||||
|
const dbDir = path.dirname(this.dbPath);
|
||||||
|
|
||||||
|
if (!fs.existsSync(dbDir)) {
|
||||||
|
fs.mkdirSync(dbDir, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
this.db = new Database(this.dbPath, { verbose: console.log });
|
||||||
|
}
|
||||||
|
|
||||||
|
get<T = any>(sql: string, params: any[] = []): T | undefined {
|
||||||
|
try {
|
||||||
|
const stmt = this.db.prepare(sql);
|
||||||
|
return stmt.get(params) as T | undefined;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('数据库查询错误:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
all<T = any>(sql: string, params: any[] = []): T[] {
|
||||||
|
try {
|
||||||
|
const stmt = this.db.prepare(sql);
|
||||||
|
return stmt.all(params) as T[];
|
||||||
|
} catch (error) {
|
||||||
|
console.error('数据库查询错误:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
run(sql: string, params: any[] = []): { id: number; changes: number } {
|
||||||
|
try {
|
||||||
|
const stmt = this.db.prepare(sql);
|
||||||
|
const result = stmt.run(params);
|
||||||
|
return { id: result.lastInsertRowid as number, changes: result.changes };
|
||||||
|
} catch (error) {
|
||||||
|
console.error('数据库操作错误:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
close(): void {
|
||||||
|
this.db.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default new DatabaseWrapper();
|
||||||
+17
-12
@@ -1,19 +1,24 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"target": "ES2020",
|
|
||||||
"module": "commonjs",
|
"module": "commonjs",
|
||||||
"lib": ["ES2020"],
|
"declaration": true,
|
||||||
"outDir": "./dist",
|
"removeComments": true,
|
||||||
"rootDir": "./",
|
"emitDecoratorMetadata": true,
|
||||||
"strict": true,
|
"experimentalDecorators": true,
|
||||||
"esModuleInterop": true,
|
|
||||||
"skipLibCheck": true,
|
|
||||||
"forceConsistentCasingInFileNames": true,
|
|
||||||
"resolveJsonModule": true,
|
|
||||||
"moduleResolution": "node",
|
|
||||||
"allowSyntheticDefaultImports": true,
|
"allowSyntheticDefaultImports": true,
|
||||||
"types": ["node"]
|
"target": "ES2021",
|
||||||
|
"sourceMap": true,
|
||||||
|
"outDir": "./dist",
|
||||||
|
"baseUrl": "./",
|
||||||
|
"incremental": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"strictNullChecks": false,
|
||||||
|
"noImplicitAny": false,
|
||||||
|
"strictBindCallApply": false,
|
||||||
|
"forceConsistentCasingInFileNames": false,
|
||||||
|
"noFallthroughCasesInSwitch": false,
|
||||||
|
"esModuleInterop": true
|
||||||
},
|
},
|
||||||
"include": ["**/*.ts"],
|
"include": ["src/**/*"],
|
||||||
"exclude": ["node_modules", "dist"]
|
"exclude": ["node_modules", "dist"]
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user