Compare commits
10 Commits
1eb8abb447
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
0938cf1ccf
|
|||
|
ec3cbe7a19
|
|||
|
c07daa6e86
|
|||
|
6f0765d187
|
|||
|
ea876a76be
|
|||
|
cd9e5f5860
|
|||
|
e8a8ad389c
|
|||
|
0bf46e887d
|
|||
|
86e41b479d
|
|||
|
2dc6bf16ec
|
16
.env.example
Normal file
16
.env.example
Normal file
@@ -0,0 +1,16 @@
|
||||
# Server Port
|
||||
PORT=3000
|
||||
|
||||
# JWT Secret Key (generate a secure random string in production)
|
||||
JWT_SECRET=your-secret-key-here
|
||||
|
||||
# Database URL (SQLite file path)
|
||||
# Windows format: file:C:/path/to/database.sqlite
|
||||
# Unix format: file:/path/to/database.sqlite
|
||||
DATABASE_URL=file:./data/database.sqlite
|
||||
|
||||
# Max Request Body Size
|
||||
MAX_REQUEST_SIZE=10mb
|
||||
|
||||
# API Base URL (for frontend)
|
||||
VITE_API_BASE_URL=/api
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -75,3 +75,5 @@ dist/
|
||||
|
||||
# NestJS
|
||||
.nest-cli.json
|
||||
|
||||
/generated/prisma
|
||||
|
||||
4
.npmrc
4
.npmrc
@@ -1,4 +0,0 @@
|
||||
only-built-dependencies[]=better-sqlite3
|
||||
only-built-dependencies[]=esbuild
|
||||
only-built-dependencies[]=@nestjs/core
|
||||
only-built-dependencies[]=unrs-resolver
|
||||
159
AGENTS.md
Normal file
159
AGENTS.md
Normal file
@@ -0,0 +1,159 @@
|
||||
# AGENTS.md - Coding Guidelines for Trace Backend
|
||||
|
||||
## Build, Lint, and Test Commands
|
||||
|
||||
### Essential Commands
|
||||
- `pnpm run build` - Build the NestJS application to dist/
|
||||
- `pnpm run lint` - Run ESLint and auto-fix issues
|
||||
- `pnpm run format` - Format code with Prettier
|
||||
- `pnpm run test` - Run all Jest tests
|
||||
- `pnpm run test:watch` - Run tests in watch mode
|
||||
- `pnpm run test:cov` - Run tests with coverage report
|
||||
- `pnpm run start:dev` - Start development server with hot reload
|
||||
- `pnpm run init-db` - Initialize database (run scripts/init-db.ts)
|
||||
|
||||
### Running Single Tests
|
||||
- `jest path/to/test.spec.ts` - Run a specific test file
|
||||
- `jest -t "test name"` - Run tests matching a pattern
|
||||
|
||||
## Project Overview
|
||||
|
||||
This is a NestJS backend for the Trace (贝凡溯源) management platform with:
|
||||
- **Framework**: NestJS 11.x with TypeScript
|
||||
- **Database**: SQLite via Prisma ORM with better-sqlite3 adapter
|
||||
- **Validation**: Zod schemas with nestjs-zod global pipe
|
||||
- **Auth**: JWT-based authentication with Passport
|
||||
- **Package Manager**: pnpm 10.x
|
||||
|
||||
## Code Style Guidelines
|
||||
|
||||
### Imports and Organization
|
||||
- Use double quotes for all imports: `import { X } from "package"`
|
||||
- Group external framework imports first, then internal imports
|
||||
- Use relative imports with `../` or `./` notation
|
||||
- Example:
|
||||
```typescript
|
||||
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";
|
||||
```
|
||||
|
||||
### Naming Conventions
|
||||
- **Classes**: PascalCase - `AuthService`, `AuthGuard`, `SerialsService`
|
||||
- **Methods/Functions**: camelCase - `validateUser`, `login`, `getProfile`
|
||||
- **Variables**: camelCase - `const prisma = ...`
|
||||
- **Interfaces/Types**: PascalCase - `User`, `AuthUser`, `JWTPayload`
|
||||
- **DTOs**: PascalCase with "Dto" suffix - `LoginDto`, `ChangePasswordDto`
|
||||
- **Models**: PascalCase - `User`, `Company`, `Serial` (Prisma models)
|
||||
|
||||
### Module Structure
|
||||
Each feature follows the NestJS pattern:
|
||||
- `module-name/`
|
||||
- `module-name.module.ts` - Module definition with imports/providers
|
||||
- `module-name.controller.ts` - HTTP request handlers
|
||||
- `module-name.service.ts` - Business logic and database operations
|
||||
- `dto/` - Zod validation schemas
|
||||
- `module-name.guard.ts` - Guards (if needed)
|
||||
|
||||
### Controllers
|
||||
- Use appropriate decorators: `@Controller`, `@Get`, `@Post`, `@Patch`, `@Delete`
|
||||
- Apply guards: `@UseGuards(AuthGuard)` or `@UseGuards(AuthGuard, AdminGuard)`
|
||||
- Set status codes explicitly: `@HttpCode(HttpStatus.OK)`
|
||||
- Extract params/query with decorators: `@Param`, `@Query`, `@Body`, `@Req`
|
||||
- Validate DTOs: `@Body(LoginDto) loginDto: any`
|
||||
- Return structured responses (see Response Format below)
|
||||
|
||||
Example:
|
||||
```typescript
|
||||
@Controller("auth")
|
||||
export class AuthController {
|
||||
constructor(private authService: AuthService) {}
|
||||
|
||||
@Post("login")
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async login(@Body(LoginDto) loginDto: any) {
|
||||
const user = await this.authService.validateUser(loginDto.username, loginDto.password);
|
||||
return this.authService.login(user);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Services
|
||||
- Mark with `@Injectable()` decorator
|
||||
- Inject dependencies via constructor
|
||||
- Use `DatabaseService.getPrisma()` to get Prisma client
|
||||
- Throw `Error` for business logic failures (guards handle auth)
|
||||
- Use transactions with `prisma.$transaction()` for multi-step operations
|
||||
|
||||
### Validation (DTOs)
|
||||
- Use Zod schemas in `dto/index.ts` files
|
||||
- Define validation rules with Chinese error messages
|
||||
- Export from `dto/index.ts` barrel file
|
||||
|
||||
Example:
|
||||
```typescript
|
||||
export const LoginDto = z.object({
|
||||
username: z.string().min(1, "用户名不能为空"),
|
||||
password: z.string().min(1, "密码不能为空"),
|
||||
});
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
- Throw NestJS exceptions in controllers/guards:
|
||||
- `UnauthorizedException` - Auth failures
|
||||
- `NotFoundException` - Resource not found
|
||||
- Throw `Error` in services for business logic errors
|
||||
- Provide Chinese error messages: `throw new Error("用户名或密码错误")`
|
||||
|
||||
### Response Format
|
||||
API responses follow this structure:
|
||||
```typescript
|
||||
{
|
||||
message: "操作描述(中文)",
|
||||
data?: any,
|
||||
pagination?: {
|
||||
page: number,
|
||||
limit: number,
|
||||
total: number,
|
||||
totalPages: number
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Database (Prisma)
|
||||
- Access Prisma client via `DatabaseService.getPrisma()`
|
||||
- Use `select` to limit returned fields for security
|
||||
- Use `include` for relations (user, company)
|
||||
- Serial numbers should be uppercase: `serialNumber.toUpperCase()`
|
||||
|
||||
### Authentication
|
||||
- Use `@UseGuards(AuthGuard)` for authenticated routes
|
||||
- Use `@UseGuards(AuthGuard, AdminGuard)` for admin-only routes
|
||||
- Access user via `@Req() req: Request` and cast: `(req as any).user`
|
||||
- User object contains: `id`, `username`, `name`, `role`
|
||||
|
||||
### TypeScript Configuration
|
||||
- Target: ES2021
|
||||
- Strict mode disabled (per tsconfig.json)
|
||||
- Experimental decorators enabled
|
||||
- Module: commonjs
|
||||
|
||||
### Database Schema
|
||||
Located in `prisma/schema.prisma`:
|
||||
- Models: User, Company, Serial
|
||||
- Relations: User -> Serial, Company -> Serial
|
||||
- After schema changes: `npx prisma migrate dev` then `npx prisma generate`
|
||||
|
||||
### Static Files
|
||||
- Production: serves from `frontend/dist/`
|
||||
- Development: serves from `frontend/public/`
|
||||
- Static assets served via `@nestjs/serve-static`
|
||||
|
||||
## Development Notes
|
||||
- Global API prefix: `/api`
|
||||
- CORS enabled
|
||||
- QR code color: dark="#165DFF", light="#ffffff"
|
||||
- Default serial prefix: "BF" + current year (e.g., "BF26")
|
||||
36
README.md
36
README.md
@@ -1,4 +1,4 @@
|
||||
# 溯源管理平台 - 后端服务
|
||||
# 溯源管理平台 - 后端服务(Node.js 版本)
|
||||
|
||||
浙江贝凡溯源管理平台的后端服务,基于 NestJS + TypeScript + SQLite。
|
||||
|
||||
@@ -6,9 +6,13 @@
|
||||
|
||||
- **NestJS**: 渐进式 Node.js 框架
|
||||
- **TypeScript**: 类型安全
|
||||
- **Prisma**: 现代化 ORM(使用 better-sqlite3 适配器)
|
||||
- **SQLite**: 轻量级数据库
|
||||
- **JWT**: 身份认证
|
||||
- **better-sqlite3**: 高性能 SQLite 驱动
|
||||
- **@nestjs/jwt**: JWT 身份认证
|
||||
- **bcryptjs**: 密码加密
|
||||
- **Zod**: 运行时类型验证
|
||||
- **nestjs-zod**: NestJS 与 Zod 集成
|
||||
|
||||
## 项目结构
|
||||
|
||||
@@ -49,10 +53,20 @@ backend/
|
||||
|
||||
## 安装
|
||||
|
||||
1. 安装依赖:
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
```
|
||||
|
||||
2. 配置环境变量:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
3. 编辑 `.env` 文件,设置你的配置(特别是 `JWT_SECRET`)
|
||||
|
||||
## 开发
|
||||
|
||||
启动开发服务器(支持热重载):
|
||||
@@ -89,16 +103,26 @@ pnpm init-db
|
||||
|
||||
## 环境变量
|
||||
|
||||
创建 `.env` 文件:
|
||||
创建 `.env` 文件(参考 `.env.example`):
|
||||
|
||||
```env
|
||||
PORT=3000
|
||||
JWT_SECRET=your-secret-key-here
|
||||
| 变量名 | 说明 | 默认值 |
|
||||
| ------------------- | ------------------------ | ----------------------------- |
|
||||
| `PORT` | 服务器端口 | `3000` |
|
||||
| `JWT_SECRET` | JWT 签名密钥(必须修改) | - |
|
||||
| `DATABASE_URL` | SQLite 数据库文件路径 | `file:./data/database.sqlite` |
|
||||
| `MAX_REQUEST_SIZE` | 最大请求体大小 | `10mb` |
|
||||
| `VITE_API_BASE_URL` | API 基础路径 | `/api` |
|
||||
|
||||
**安全提示**:在生产环境中,请务必设置一个强随机字符串作为 `JWT_SECRET`。可以使用以下命令生成:
|
||||
|
||||
```bash
|
||||
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
|
||||
```
|
||||
|
||||
## 默认账户
|
||||
|
||||
初始化后默认创建的管理员账户:
|
||||
|
||||
- 用户名: admin
|
||||
- 密码: Beifan@2026
|
||||
|
||||
|
||||
26
package.json
26
package.json
@@ -5,6 +5,7 @@
|
||||
"author": "",
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"packageManager": "pnpm@10.27.0",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
@@ -28,26 +29,26 @@
|
||||
"@nestjs/passport": "^11.0.5",
|
||||
"@nestjs/platform-express": "^11.1.13",
|
||||
"@nestjs/serve-static": "^5.0.4",
|
||||
"@prisma/adapter-better-sqlite3": "^7.3.0",
|
||||
"@prisma/client": "^7.3.0",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"better-sqlite3": "^12.6.2",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.3",
|
||||
"dotenv": "^17.2.3",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"nestjs-zod": "^5.1.1",
|
||||
"passport": "^0.7.0",
|
||||
"passport-jwt": "^4.0.1",
|
||||
"prisma": "^7.3.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.2"
|
||||
"rxjs": "^7.8.2",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^11.0.0",
|
||||
"@nestjs/schematics": "^11.0.0",
|
||||
"@nestjs/cli": "^11.0.16",
|
||||
"@nestjs/schematics": "^11.0.9",
|
||||
"@nestjs/testing": "^11.1.13",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/express": "^5.0.6",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"@types/node": "^25.2.1",
|
||||
"@types/passport-jwt": "^4.0.1",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
@@ -63,6 +64,15 @@
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"pnpm": {
|
||||
"onlyBuiltDependencies": [
|
||||
"@nestjs/core",
|
||||
"@prisma/engines",
|
||||
"better-sqlite3",
|
||||
"esbuild",
|
||||
"unrs-resolver"
|
||||
]
|
||||
},
|
||||
"jest": {
|
||||
"moduleFileExtensions": [
|
||||
"js",
|
||||
|
||||
761
pnpm-lock.yaml
generated
761
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
15
prisma.config.ts
Normal file
15
prisma.config.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import "dotenv/config";
|
||||
import { defineConfig } from "prisma/config";
|
||||
import path from "path";
|
||||
|
||||
export default defineConfig({
|
||||
schema: "prisma/schema.prisma",
|
||||
migrations: {
|
||||
path: "prisma/migrations",
|
||||
},
|
||||
datasource: {
|
||||
url:
|
||||
process.env["DATABASE_URL"] ||
|
||||
"file:" + path.join(process.cwd(), "data/database.sqlite"),
|
||||
},
|
||||
});
|
||||
41
prisma/schema.prisma
Normal file
41
prisma/schema.prisma
Normal file
@@ -0,0 +1,41 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
}
|
||||
|
||||
model User {
|
||||
id Int @id @default(autoincrement())
|
||||
username String @unique
|
||||
password String
|
||||
name String
|
||||
email String?
|
||||
role String @default("user")
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
serials Serial[]
|
||||
}
|
||||
|
||||
model Company {
|
||||
id Int @id @default(autoincrement())
|
||||
companyName String @unique
|
||||
isActive Boolean @default(true)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
serials Serial[]
|
||||
}
|
||||
|
||||
model Serial {
|
||||
id Int @id @default(autoincrement())
|
||||
serialNumber String @unique
|
||||
companyName String
|
||||
validUntil DateTime?
|
||||
isActive Boolean @default(true)
|
||||
createdBy Int?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
user User? @relation(fields: [createdBy], references: [id])
|
||||
company Company? @relation(fields: [companyName], references: [companyName])
|
||||
}
|
||||
@@ -1,91 +1,55 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import bcrypt from "bcryptjs";
|
||||
import path from "path";
|
||||
import { PrismaBetterSqlite3 } from "@prisma/adapter-better-sqlite3";
|
||||
|
||||
const dbPath = path.join(process.cwd(), 'data/database.sqlite');
|
||||
const dbDir = path.dirname(dbPath);
|
||||
const url =
|
||||
process.env.DATABASE_URL ||
|
||||
"file:" + path.join(process.cwd(), "data/database.sqlite");
|
||||
|
||||
if (!fs.existsSync(dbDir)) {
|
||||
fs.mkdirSync(dbDir, { recursive: true });
|
||||
}
|
||||
const adapter = new PrismaBetterSqlite3({
|
||||
url,
|
||||
});
|
||||
|
||||
const db = new Database(dbPath, { verbose: console.log });
|
||||
|
||||
const createTables = (): void => {
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
email TEXT,
|
||||
role TEXT DEFAULT 'user',
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS companies (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
company_name TEXT UNIQUE NOT NULL,
|
||||
is_active BOOLEAN BOOLEAN DEFAULT 1,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS serials (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
serial_number TEXT UNIQUE NOT NULL,
|
||||
company_name TEXT NOT NULL,
|
||||
valid_until DATETIME,
|
||||
is_active BOOLEAN DEFAULT 1,
|
||||
created_by INTEGER,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (created_by) REFERENCES users (id),
|
||||
FOREIGN KEY (company_name) REFERENCES companies (company_name)
|
||||
)
|
||||
`);
|
||||
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_company_name_companies ON companies (company_name)');
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_serial_number ON serials (serial_number)');
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_company_name_serials ON serials (company_name)');
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_created_by ON serials (created_by)');
|
||||
|
||||
console.log('数据库表创建完成');
|
||||
};
|
||||
const prisma = new PrismaClient({
|
||||
log: ["query", "error", "warn"],
|
||||
adapter,
|
||||
});
|
||||
|
||||
const createDefaultUser = async (): Promise<void> => {
|
||||
const username = 'admin';
|
||||
const password = 'Beifan@2026';
|
||||
const name = '系统管理员';
|
||||
const username = "admin";
|
||||
const password = "Beifan@2026";
|
||||
const name = "系统管理员";
|
||||
|
||||
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { username },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
const hashedPassword = await bcrypt.hash(password, 10);
|
||||
|
||||
db.prepare(
|
||||
'INSERT INTO users (username, password, name, email, role) VALUES (?, ?, ?, ?, ?)'
|
||||
).run(username, hashedPassword, name, 'admin@example.com', 'admin');
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
username,
|
||||
password: hashedPassword,
|
||||
name,
|
||||
email: "admin@example.com",
|
||||
role: "admin",
|
||||
},
|
||||
});
|
||||
|
||||
console.log('默认管理员用户创建完成:');
|
||||
console.log('用户名:', username);
|
||||
console.log('密码:', password);
|
||||
console.log("默认管理员用户创建完成:");
|
||||
console.log("用户名:", username);
|
||||
console.log("密码:", password);
|
||||
} else {
|
||||
console.log('默认管理员用户已存在');
|
||||
console.log("默认管理员用户已存在");
|
||||
}
|
||||
};
|
||||
|
||||
const initDatabase = async (): Promise<void> => {
|
||||
createTables();
|
||||
await createDefaultUser();
|
||||
db.close();
|
||||
console.log('数据库连接已关闭');
|
||||
await prisma.$disconnect();
|
||||
console.log("数据库连接已关闭");
|
||||
};
|
||||
|
||||
initDatabase();
|
||||
|
||||
@@ -1,29 +1,45 @@
|
||||
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';
|
||||
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')
|
||||
@Controller("auth")
|
||||
export class AuthController {
|
||||
constructor(private authService: AuthService) {}
|
||||
|
||||
@Post('login')
|
||||
@Post("login")
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async login(@Body() loginDto: LoginDto) {
|
||||
const user = await this.authService.validateUser(loginDto.username, loginDto.password);
|
||||
async login(@Body(LoginDto) loginDto: any) {
|
||||
const user = await this.authService.validateUser(
|
||||
loginDto.username,
|
||||
loginDto.password,
|
||||
);
|
||||
return this.authService.login(user);
|
||||
}
|
||||
|
||||
@Get('profile')
|
||||
@Get("profile")
|
||||
@UseGuards(AuthGuard)
|
||||
async getProfile(@Request() req) {
|
||||
return this.authService.getProfile(req.user.id);
|
||||
}
|
||||
|
||||
@Post('change-password')
|
||||
@Post("change-password")
|
||||
@UseGuards(AuthGuard)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async changePassword(@Request() req, @Body() changePasswordDto: ChangePasswordDto) {
|
||||
async changePassword(
|
||||
@Request() req,
|
||||
@Body(ChangePasswordDto) changePasswordDto: any,
|
||||
) {
|
||||
return this.authService.changePassword(
|
||||
req.user.id,
|
||||
changePasswordDto.currentPassword,
|
||||
@@ -31,10 +47,17 @@ export class AuthController {
|
||||
);
|
||||
}
|
||||
|
||||
@Put('profile')
|
||||
@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);
|
||||
async updateProfile(
|
||||
@Request() req,
|
||||
@Body(UpdateProfileDto) updateProfileDto: any,
|
||||
) {
|
||||
return this.authService.updateProfile(
|
||||
req.user.id,
|
||||
updateProfileDto.name,
|
||||
updateProfileDto.email,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { AuthUser } from '../types';
|
||||
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 {
|
||||
@@ -12,32 +17,42 @@ export class AuthGuard implements CanActivate {
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const authHeader = request.headers['authorization'];
|
||||
const token = authHeader && authHeader.split(' ')[1];
|
||||
const authHeader = request.headers["authorization"];
|
||||
const token = authHeader && authHeader.split(" ")[1];
|
||||
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('访问令牌缺失');
|
||||
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]
|
||||
);
|
||||
|
||||
const decoded = this.jwtService.verify(token) as {
|
||||
userId: number;
|
||||
username: string;
|
||||
role: string;
|
||||
};
|
||||
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: decoded.userId },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
name: true,
|
||||
role: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('用户不存在');
|
||||
throw new UnauthorizedException("用户不存在");
|
||||
}
|
||||
|
||||
request.user = user;
|
||||
|
||||
request.user = user as AuthUser;
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error.name === 'TokenExpiredError') {
|
||||
throw new UnauthorizedException('令牌已过期');
|
||||
if (error.name === "TokenExpiredError") {
|
||||
throw new UnauthorizedException("令牌已过期");
|
||||
}
|
||||
throw new UnauthorizedException('无效的令牌');
|
||||
throw new UnauthorizedException("无效的令牌");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
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';
|
||||
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 {
|
||||
@@ -12,23 +12,30 @@ export class AuthService {
|
||||
) {}
|
||||
|
||||
async validateUser(username: string, password: string) {
|
||||
const user = await this.dbService.get<User>('SELECT * FROM users WHERE username = ?', [username]);
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { username },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('用户名或密码错误');
|
||||
throw new UnauthorizedException("用户名或密码错误");
|
||||
}
|
||||
|
||||
const isValidPassword = await bcrypt.compare(password, user.password);
|
||||
|
||||
if (!isValidPassword) {
|
||||
throw new UnauthorizedException('用户名或密码错误');
|
||||
throw new UnauthorizedException("用户名或密码错误");
|
||||
}
|
||||
|
||||
return user;
|
||||
return user as User;
|
||||
}
|
||||
|
||||
async login(user: User) {
|
||||
const payload = { userId: user.id, username: user.username, role: user.role };
|
||||
const payload = {
|
||||
userId: user.id,
|
||||
username: user.username,
|
||||
role: user.role,
|
||||
};
|
||||
const token = this.jwtService.sign(payload);
|
||||
|
||||
return {
|
||||
@@ -39,74 +46,81 @@ export class AuthService {
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
createdAt: user.created_at,
|
||||
createdAt: user.createdAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async getProfile(userId: number) {
|
||||
const user = await this.dbService.get<User>(
|
||||
'SELECT id, username, name, email, role, created_at FROM users WHERE id = ?',
|
||||
[userId],
|
||||
);
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
name: true,
|
||||
email: true,
|
||||
role: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('用户不存在');
|
||||
throw new UnauthorizedException("用户不存在");
|
||||
}
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
createdAt: user.created_at,
|
||||
};
|
||||
return user;
|
||||
}
|
||||
|
||||
async changePassword(userId: number, currentPassword: string, newPassword: string) {
|
||||
const user = await this.dbService.get<Pick<User, 'password'>>('SELECT password FROM users WHERE id = ?', [
|
||||
userId,
|
||||
]);
|
||||
async changePassword(
|
||||
userId: number,
|
||||
currentPassword: string,
|
||||
newPassword: string,
|
||||
) {
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { password: true },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('用户不存在');
|
||||
throw new UnauthorizedException("用户不存在");
|
||||
}
|
||||
|
||||
const isValidPassword = await bcrypt.compare(currentPassword, user.password);
|
||||
const isValidPassword = await bcrypt.compare(
|
||||
currentPassword,
|
||||
user.password,
|
||||
);
|
||||
|
||||
if (!isValidPassword) {
|
||||
throw new UnauthorizedException('当前密码错误');
|
||||
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,
|
||||
]);
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { password: hashedPassword },
|
||||
});
|
||||
|
||||
return { message: '密码修改成功' };
|
||||
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 prisma = this.dbService.getPrisma();
|
||||
const updatedUser = await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { name, email },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
name: true,
|
||||
email: true,
|
||||
role: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
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,
|
||||
};
|
||||
return updatedUser;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,31 +1,16 @@
|
||||
import { IsString, IsNotEmpty, MinLength, IsEmail, IsOptional } from 'class-validator';
|
||||
import { z } from "zod";
|
||||
|
||||
export class LoginDto {
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: '用户名不能为空' })
|
||||
username: string;
|
||||
export const LoginDto = z.object({
|
||||
username: z.string().min(1, "用户名不能为空"),
|
||||
password: z.string().min(1, "密码不能为空"),
|
||||
});
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: '密码不能为空' })
|
||||
password: string;
|
||||
}
|
||||
export const ChangePasswordDto = z.object({
|
||||
currentPassword: z.string().min(1, "当前密码不能为空"),
|
||||
newPassword: z.string().min(6, "新密码长度至少为6位"),
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
export const UpdateProfileDto = z.object({
|
||||
name: z.string().min(1, "姓名不能为空"),
|
||||
email: z.string().email("邮箱格式不正确").optional(),
|
||||
});
|
||||
|
||||
@@ -1,313 +1,324 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { DatabaseService } from "../database/database.service";
|
||||
|
||||
@Injectable()
|
||||
export class CompaniesService {
|
||||
constructor(private dbService: DatabaseService) {}
|
||||
|
||||
async findAll(page: number, limit: number, search: string) {
|
||||
const prisma = this.dbService.getPrisma();
|
||||
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 countQuery = 'SELECT COUNT(*) as total FROM companies';
|
||||
let params: any[] = [];
|
||||
const where = search
|
||||
? {
|
||||
companyName: { contains: search },
|
||||
}
|
||||
: undefined;
|
||||
|
||||
if (search) {
|
||||
query += ' WHERE c.company_name LIKE ?';
|
||||
countQuery += ' WHERE company_name LIKE ?';
|
||||
params.push(`%${search}%`);
|
||||
}
|
||||
|
||||
query += ' ORDER BY c.updated_at DESC LIMIT ? OFFSET ?';
|
||||
params.push(parseInt(limit.toString()), parseInt(offset.toString()));
|
||||
|
||||
const [companies, countResult] = await Promise.all([
|
||||
this.dbService.all(query, params),
|
||||
this.dbService.get<{ total: number }>(countQuery, params.slice(0, -2))
|
||||
const [companies, total] = await Promise.all([
|
||||
prisma.company.findMany({
|
||||
where,
|
||||
include: {
|
||||
serials: true,
|
||||
},
|
||||
orderBy: { updatedAt: "desc" },
|
||||
skip: offset,
|
||||
take: limit,
|
||||
}),
|
||||
prisma.company.count({ where }),
|
||||
]);
|
||||
|
||||
const total = countResult?.total || 0;
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
|
||||
return {
|
||||
message: '获取企业列表成功',
|
||||
message: "获取企业列表成功",
|
||||
data: companies.map((company: any) => ({
|
||||
companyName: company.company_name,
|
||||
firstCreated: company.first_created,
|
||||
lastCreated: company.last_created,
|
||||
serialCount: company.serial_count,
|
||||
activeCount: company.active_count,
|
||||
status: company.is_active ? 'active' : 'disabled'
|
||||
companyName: company.companyName,
|
||||
firstCreated: company.createdAt,
|
||||
lastCreated: company.updatedAt,
|
||||
serialCount: company.serials.length,
|
||||
activeCount: company.serials.filter((s: any) => s.isActive).length,
|
||||
status: company.isActive ? "active" : "disabled",
|
||||
})),
|
||||
pagination: {
|
||||
page: parseInt(page.toString()),
|
||||
limit: parseInt(limit.toString()),
|
||||
total,
|
||||
totalPages
|
||||
}
|
||||
totalPages,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async findOne(companyName: string, page: number, limit: number) {
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const companyInfo = await this.dbService.get('SELECT * FROM companies WHERE company_name = ?', [companyName]);
|
||||
const company = await prisma.company.findUnique({
|
||||
where: { companyName },
|
||||
include: {
|
||||
serials: {
|
||||
include: {
|
||||
user: {
|
||||
select: { name: true },
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!companyInfo) {
|
||||
throw new Error('企业不存在');
|
||||
if (!company) {
|
||||
throw new Error("企业不存在");
|
||||
}
|
||||
|
||||
const serialStats = await this.dbService.get(`
|
||||
SELECT COUNT(*) as serial_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 valid_until IS NOT NULL AND valid_until <= datetime('now') THEN 1 ELSE 0 END) as expired_count
|
||||
FROM serials
|
||||
WHERE company_name = ?
|
||||
`, [companyName]);
|
||||
const now = new Date();
|
||||
const serialCount = company.serials.length;
|
||||
const activeCount = company.serials.filter(
|
||||
(s) => s.isActive && (!s.validUntil || s.validUntil > now),
|
||||
).length;
|
||||
const disabledCount = company.serials.filter((s) => !s.isActive).length;
|
||||
const expiredCount = company.serials.filter(
|
||||
(s) => s.validUntil && s.validUntil <= now,
|
||||
).length;
|
||||
|
||||
const serials = await this.dbService.all(`
|
||||
SELECT s.*, u.name as created_by_name
|
||||
FROM serials s
|
||||
LEFT JOIN users u ON s.created_by = u.id
|
||||
WHERE s.company_name = ?
|
||||
ORDER BY s.created_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`, [companyName, parseInt(limit.toString()), parseInt(offset.toString())]);
|
||||
const monthlyStatsMap = new Map<string, number>();
|
||||
|
||||
const stats = await this.dbService.all<{ month: string; count: number }>(`
|
||||
SELECT strftime('%Y-%m', created_at) as month,
|
||||
COUNT(*) as count
|
||||
FROM serials
|
||||
WHERE company_name = ?
|
||||
GROUP BY strftime('%Y-%m', created_at)
|
||||
ORDER BY month DESC
|
||||
LIMIT 12
|
||||
`, [companyName]);
|
||||
for (let i = 11; i >= 0; i--) {
|
||||
const date = new Date(now.getFullYear(), now.getMonth() - i, 1);
|
||||
const monthKey = date.toISOString().slice(0, 7);
|
||||
const count = company.serials.filter((s) => {
|
||||
const createdAt = new Date(s.createdAt);
|
||||
return (
|
||||
createdAt.getFullYear() === date.getFullYear() &&
|
||||
createdAt.getMonth() === date.getMonth()
|
||||
);
|
||||
}).length;
|
||||
|
||||
if (count > 0) {
|
||||
monthlyStatsMap.set(monthKey, count);
|
||||
}
|
||||
}
|
||||
|
||||
const paginatedSerials = company.serials.slice(offset, offset + limit);
|
||||
|
||||
return {
|
||||
message: '获取企业详情成功',
|
||||
message: "获取企业详情成功",
|
||||
data: {
|
||||
companyName: companyName,
|
||||
serialCount: serialStats?.serial_count || 0,
|
||||
activeCount: serialStats?.active_count || 0,
|
||||
disabledCount: serialStats?.disabled_count || 0,
|
||||
expiredCount: serialStats?.expired_count || 0,
|
||||
firstCreated: (companyInfo as any).created_at,
|
||||
lastCreated: (companyInfo as any).updated_at,
|
||||
status: (companyInfo as any).is_active ? 'active' : 'disabled',
|
||||
serials: serials.map((s: any) => ({
|
||||
serialNumber: s.serial_number,
|
||||
validUntil: s.valid_until,
|
||||
isActive: s.is_active,
|
||||
createdAt: s.created_at,
|
||||
createdBy: s.created_by_name
|
||||
serialCount,
|
||||
activeCount,
|
||||
disabledCount,
|
||||
expiredCount,
|
||||
firstCreated: company.createdAt,
|
||||
lastCreated: company.updatedAt,
|
||||
status: company.isActive ? "active" : "disabled",
|
||||
serials: paginatedSerials.map((s) => ({
|
||||
serialNumber: s.serialNumber,
|
||||
validUntil: s.validUntil,
|
||||
isActive: s.isActive,
|
||||
createdAt: s.createdAt,
|
||||
createdBy: s.user?.name,
|
||||
})),
|
||||
monthlyStats: stats.map(stat => ({
|
||||
month: stat.month,
|
||||
count: stat.count
|
||||
}))
|
||||
}
|
||||
monthlyStats: Array.from(monthlyStatsMap.entries()).map(
|
||||
([month, count]) => ({ month, count }),
|
||||
),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async update(companyName: string, newCompanyName: string) {
|
||||
const existingCompany = await this.dbService.get(
|
||||
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
||||
[companyName]
|
||||
);
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const existingCompany = await prisma.serial.count({
|
||||
where: { companyName },
|
||||
});
|
||||
|
||||
if (!existingCompany || (existingCompany as any).count === 0) {
|
||||
throw new Error('企业不存在');
|
||||
if (existingCompany === 0) {
|
||||
throw new Error("企业不存在");
|
||||
}
|
||||
|
||||
const duplicateCompany = await this.dbService.get(
|
||||
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
||||
[newCompanyName]
|
||||
);
|
||||
const duplicateCompany = await prisma.serial.count({
|
||||
where: { companyName: newCompanyName },
|
||||
});
|
||||
|
||||
if (duplicateCompany && (duplicateCompany as any).count > 0) {
|
||||
throw new Error('企业名称已存在');
|
||||
if (duplicateCompany > 0) {
|
||||
throw new Error("企业名称已存在");
|
||||
}
|
||||
|
||||
this.dbService.run(
|
||||
'UPDATE serials SET company_name = ?, updated_at = CURRENT_TIMESTAMP WHERE company_name = ?',
|
||||
[newCompanyName, companyName]
|
||||
);
|
||||
await prisma.serial.updateMany({
|
||||
where: { companyName },
|
||||
data: { companyName: newCompanyName },
|
||||
});
|
||||
|
||||
return {
|
||||
message: '企业名称更新成功',
|
||||
message: "企业名称更新成功",
|
||||
data: {
|
||||
oldCompanyName: companyName,
|
||||
newCompanyName
|
||||
}
|
||||
newCompanyName,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async delete(companyName: string) {
|
||||
const existingCompany = await this.dbService.get(
|
||||
'SELECT * FROM companies WHERE company_name = ?',
|
||||
[companyName]
|
||||
);
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const existingCompany = await prisma.company.findUnique({
|
||||
where: { companyName },
|
||||
});
|
||||
|
||||
if (!existingCompany) {
|
||||
throw new Error('企业不存在');
|
||||
throw new Error("企业不存在");
|
||||
}
|
||||
|
||||
this.dbService.run('BEGIN TRANSACTION');
|
||||
const deleteResult = await prisma.$transaction(async (tx) => {
|
||||
const serialDeleteCount = await tx.serial.deleteMany({
|
||||
where: { companyName },
|
||||
});
|
||||
|
||||
try {
|
||||
const serialDeleteResult = this.dbService.run(
|
||||
'DELETE FROM serials WHERE company_name = ?',
|
||||
[companyName]
|
||||
);
|
||||
await tx.company.delete({
|
||||
where: { companyName },
|
||||
});
|
||||
|
||||
const companyDeleteResult = this.dbService.run(
|
||||
'DELETE FROM companies WHERE company_name = ?',
|
||||
[companyName]
|
||||
);
|
||||
return serialDeleteCount.count;
|
||||
});
|
||||
|
||||
if (companyDeleteResult.changes === 0) {
|
||||
this.dbService.run('ROLLBACK');
|
||||
throw new Error('企业不存在');
|
||||
}
|
||||
|
||||
this.dbService.run('COMMIT');
|
||||
|
||||
return {
|
||||
message: '企业已完全删除,所有相关序列号已删除',
|
||||
data: {
|
||||
companyName: companyName,
|
||||
deletedSerialCount: serialDeleteResult.changes,
|
||||
deletedCompanyCount: companyDeleteResult.changes
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
this.dbService.run('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
return {
|
||||
message: "企业已完全删除,所有相关序列号已删除",
|
||||
data: {
|
||||
companyName: companyName,
|
||||
deletedSerialCount: deleteResult,
|
||||
deletedCompanyCount: 1,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async deleteSerial(companyName: string, serialNumber: string) {
|
||||
const serial = await this.dbService.get(
|
||||
'SELECT * FROM serials WHERE serial_number = ? AND company_name = ?',
|
||||
[serialNumber.toUpperCase(), companyName]
|
||||
);
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const serial = await prisma.serial.findFirst({
|
||||
where: {
|
||||
serialNumber: serialNumber.toUpperCase(),
|
||||
companyName,
|
||||
},
|
||||
});
|
||||
|
||||
if (!serial) {
|
||||
throw new Error('序列号不存在或不属于该企业');
|
||||
throw new Error("序列号不存在或不属于该企业");
|
||||
}
|
||||
|
||||
await this.dbService.run(
|
||||
'DELETE FROM serials WHERE serial_number = ? AND company_name = ?',
|
||||
[serialNumber.toUpperCase(), companyName]
|
||||
);
|
||||
await prisma.serial.delete({
|
||||
where: { serialNumber: serialNumber.toUpperCase() },
|
||||
});
|
||||
|
||||
return {
|
||||
message: '序列号已成功删除',
|
||||
message: "序列号已成功删除",
|
||||
data: {
|
||||
serialNumber: serialNumber.toUpperCase(),
|
||||
companyName
|
||||
}
|
||||
companyName,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async revoke(companyName: string) {
|
||||
const existingCompany = await this.dbService.get(
|
||||
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
||||
[companyName]
|
||||
);
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const existingCompany = await prisma.serial.count({
|
||||
where: { companyName },
|
||||
});
|
||||
|
||||
if (!existingCompany || (existingCompany as any).count === 0) {
|
||||
throw new Error('企业不存在');
|
||||
if (existingCompany === 0) {
|
||||
throw new Error("企业不存在");
|
||||
}
|
||||
|
||||
await this.dbService.run(
|
||||
'UPDATE serials SET is_active = 0, updated_at = CURRENT_TIMESTAMP WHERE company_name = ?',
|
||||
[companyName]
|
||||
);
|
||||
await prisma.serial.updateMany({
|
||||
where: { companyName },
|
||||
data: { isActive: false },
|
||||
});
|
||||
|
||||
return {
|
||||
message: '企业已吊销,所有序列号已失效',
|
||||
message: "企业已吊销,所有序列号已失效",
|
||||
data: {
|
||||
companyName: companyName
|
||||
}
|
||||
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
|
||||
WHERE is_active = 1 AND (valid_until IS NULL OR valid_until > datetime('now'))
|
||||
`);
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const now = new Date();
|
||||
|
||||
const monthlyStats = await this.dbService.all<{ month: string; company_count: number; serial_count: number }>(`
|
||||
SELECT strftime('%Y-%m', created_at) as month,
|
||||
COUNT(DISTINCT company_name) as company_count,
|
||||
COUNT(*) as serial_count
|
||||
FROM serials
|
||||
WHERE created_at >= strftime('%Y-%m-%d', datetime('now', '-12 months'))
|
||||
GROUP BY strftime('%Y-%m', created_at)
|
||||
ORDER BY month ASC
|
||||
`);
|
||||
const [companies, serials, recentCompanies, recentSerials] =
|
||||
await Promise.all([
|
||||
prisma.company.findMany(),
|
||||
prisma.serial.findMany({
|
||||
include: {
|
||||
company: true,
|
||||
},
|
||||
}),
|
||||
prisma.company.findMany({
|
||||
orderBy: { updatedAt: "desc" },
|
||||
take: 10,
|
||||
}),
|
||||
prisma.serial.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 10,
|
||||
}),
|
||||
]);
|
||||
|
||||
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
|
||||
FROM companies c
|
||||
ORDER BY c.updated_at DESC
|
||||
LIMIT 10
|
||||
`);
|
||||
const companyCount = companies.length;
|
||||
const serialCount = serials.length;
|
||||
const activeCount = serials.filter(
|
||||
(s) => s.isActive && (!s.validUntil || s.validUntil > now),
|
||||
).length;
|
||||
const inactiveCount = serialCount - activeCount;
|
||||
|
||||
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
|
||||
FROM serials s
|
||||
ORDER BY s.created_at DESC
|
||||
LIMIT 10
|
||||
`);
|
||||
const monthlyStats: Array<{
|
||||
month: string;
|
||||
company_count: number;
|
||||
serial_count: number;
|
||||
}> = [];
|
||||
const nowYear = now.getFullYear();
|
||||
const nowMonth = now.getMonth();
|
||||
|
||||
let finalMonthlyStats = monthlyStats;
|
||||
if (monthlyStats.length === 0) {
|
||||
finalMonthlyStats = [];
|
||||
const now = new Date();
|
||||
for (let i = 11; i >= 0; i--) {
|
||||
const date = new Date(now.getFullYear(), now.getMonth() - i, 1);
|
||||
const month = date.toISOString().substr(0, 7);
|
||||
finalMonthlyStats.push({
|
||||
month,
|
||||
company_count: 0,
|
||||
serial_count: 0
|
||||
for (let i = 11; i >= 0; i--) {
|
||||
const date = new Date(nowYear, nowMonth - i, 1);
|
||||
const monthStr = date.toISOString().slice(0, 7);
|
||||
const monthSerials = serials.filter((s) => {
|
||||
const createdAt = new Date(s.createdAt);
|
||||
return (
|
||||
createdAt.getFullYear() === date.getFullYear() &&
|
||||
createdAt.getMonth() === date.getMonth()
|
||||
);
|
||||
});
|
||||
const uniqueCompanies = new Set(monthSerials.map((s) => s.companyName));
|
||||
|
||||
if (monthSerials.length > 0) {
|
||||
monthlyStats.push({
|
||||
month: monthStr,
|
||||
company_count: uniqueCompanies.size,
|
||||
serial_count: monthSerials.length,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
message: '获取统计数据成功',
|
||||
message: "获取统计数据成功",
|
||||
data: {
|
||||
overview: {
|
||||
totalCompanies: companyCount?.count || 0,
|
||||
totalSerials: serialCount?.count || 0,
|
||||
activeSerials: activeCount?.count || 0,
|
||||
inactiveSerials: (serialCount?.count || 0) - (activeCount?.count || 0)
|
||||
totalCompanies: companyCount,
|
||||
totalSerials: serialCount,
|
||||
activeSerials: activeCount,
|
||||
inactiveSerials: inactiveCount,
|
||||
},
|
||||
monthlyStats: finalMonthlyStats.map(stat => ({
|
||||
month: stat.month,
|
||||
company_count: stat.company_count,
|
||||
serial_count: stat.serial_count
|
||||
monthlyStats,
|
||||
recentCompanies: recentCompanies.map((c) => ({
|
||||
companyName: c.companyName,
|
||||
lastCreated: c.updatedAt,
|
||||
status: c.isActive ? "active" : "disabled",
|
||||
})),
|
||||
recentCompanies: recentCompanies.map(c => ({
|
||||
companyName: c.company_name,
|
||||
lastCreated: c.last_created,
|
||||
status: c.is_active ? 'active' : 'disabled'
|
||||
recentSerials: recentSerials.map((s) => ({
|
||||
serialNumber: s.serialNumber,
|
||||
companyName: s.companyName,
|
||||
isActive: s.isActive,
|
||||
createdAt: s.createdAt,
|
||||
})),
|
||||
recentSerials: recentSerials.map(s => ({
|
||||
serialNumber: s.serial_number,
|
||||
companyName: s.company_name,
|
||||
isActive: !!s.is_active,
|
||||
createdAt: s.created_at
|
||||
}))
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,59 +1,36 @@
|
||||
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';
|
||||
import { Injectable, OnModuleInit, OnModuleDestroy } from "@nestjs/common";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import path from "path";
|
||||
import { PrismaBetterSqlite3 } from "@prisma/adapter-better-sqlite3";
|
||||
|
||||
@Injectable()
|
||||
export class DatabaseService implements OnModuleInit, OnModuleDestroy {
|
||||
private db: Database.Database;
|
||||
private dbPath: string;
|
||||
private prisma: PrismaClient;
|
||||
|
||||
constructor(private configService: ConfigService) {}
|
||||
constructor() {
|
||||
const url =
|
||||
process.env.DATABASE_URL ||
|
||||
"file:" + path.join(process.cwd(), "data/database.sqlite");
|
||||
|
||||
const adapter = new PrismaBetterSqlite3({
|
||||
url,
|
||||
});
|
||||
|
||||
this.prisma = new PrismaClient({
|
||||
log: ["query", "error", "warn"],
|
||||
adapter,
|
||||
});
|
||||
}
|
||||
|
||||
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 });
|
||||
this.prisma.$connect();
|
||||
}
|
||||
|
||||
onModuleDestroy() {
|
||||
this.db.close();
|
||||
this.prisma.$disconnect();
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
getPrisma() {
|
||||
return this.prisma;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
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();
|
||||
38
src/main.ts
38
src/main.ts
@@ -1,34 +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';
|
||||
import { NestFactory } from "@nestjs/core";
|
||||
import { AppModule } from "./app.module";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { join } from "path";
|
||||
import { NestExpressApplication } from "@nestjs/platform-express";
|
||||
import { ZodValidationPipe } from "nestjs-zod";
|
||||
|
||||
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');
|
||||
|
||||
app.useGlobalPipes(new ZodValidationPipe());
|
||||
app.setGlobalPrefix("api");
|
||||
|
||||
// 静态文件服务
|
||||
const frontendPath = join(__dirname, '..', 'frontend');
|
||||
const distPath = join(frontendPath, 'dist');
|
||||
const publicPath = join(frontendPath, 'public');
|
||||
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
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);
|
||||
|
||||
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'}`);
|
||||
console.log(`环境: ${process.env.NODE_ENV || "development"}`);
|
||||
}
|
||||
bootstrap();
|
||||
|
||||
@@ -1,46 +1,24 @@
|
||||
import { IsString, IsNotEmpty, IsNumber, IsOptional, IsBoolean, Min, Max } from 'class-validator';
|
||||
import { z } from "zod";
|
||||
|
||||
export class GenerateSerialDto {
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: '企业名称不能为空' })
|
||||
companyName: string;
|
||||
export const GenerateSerialDto = z.object({
|
||||
companyName: z.string().min(1, "企业名称不能为空"),
|
||||
quantity: z.number().min(1).max(100).optional(),
|
||||
validDays: z.number().optional(),
|
||||
});
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(1)
|
||||
@Max(100)
|
||||
quantity?: number;
|
||||
export const GenerateWithPrefixDto = GenerateSerialDto.extend({
|
||||
serialPrefix: z.string().min(1, "自定义前缀不能为空"),
|
||||
});
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
validDays?: number;
|
||||
}
|
||||
export const QRCodeDto = z.object({
|
||||
baseUrl: z.string().optional(),
|
||||
});
|
||||
|
||||
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 const UpdateSerialDto = z.object({
|
||||
companyName: z.string().optional(),
|
||||
validUntil: z.string().optional(),
|
||||
isActive: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export interface Serial {
|
||||
id: number;
|
||||
|
||||
@@ -1,18 +1,38 @@
|
||||
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';
|
||||
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')
|
||||
@Controller("serials")
|
||||
export class SerialsController {
|
||||
constructor(private readonly serialsService: SerialsService) {}
|
||||
|
||||
@Post('generate')
|
||||
@Post("generate")
|
||||
@UseGuards(AuthGuard, AdminGuard)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async generate(@Body() generateDto: GenerateSerialDto, @Req() req: Request) {
|
||||
async generate(
|
||||
@Body(GenerateSerialDto) generateDto: any,
|
||||
@Req() req: Request,
|
||||
) {
|
||||
const serials = await this.serialsService.generate(
|
||||
generateDto.companyName,
|
||||
generateDto.quantity || 1,
|
||||
@@ -25,10 +45,13 @@ export class SerialsController {
|
||||
};
|
||||
}
|
||||
|
||||
@Post('generate-with-prefix')
|
||||
@Post("generate-with-prefix")
|
||||
@UseGuards(AuthGuard, AdminGuard)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async generateWithPrefix(@Body() generateDto: GenerateWithPrefixDto, @Req() req: Request) {
|
||||
async generateWithPrefix(
|
||||
@Body(GenerateWithPrefixDto) generateDto: any,
|
||||
@Req() req: Request,
|
||||
) {
|
||||
const serials = await this.serialsService.generate(
|
||||
generateDto.companyName,
|
||||
generateDto.quantity || 1,
|
||||
@@ -42,44 +65,44 @@ export class SerialsController {
|
||||
};
|
||||
}
|
||||
|
||||
@Post(':serialNumber/qrcode')
|
||||
@Post(":serialNumber/qrcode")
|
||||
@UseGuards(AuthGuard)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async generateQRCode(
|
||||
@Param('serialNumber') serialNumber: string,
|
||||
@Body() qrCodeDto: QRCodeDto,
|
||||
@Param("serialNumber") serialNumber: string,
|
||||
@Body(QRCodeDto) qrCodeDto: any,
|
||||
@Req() req: Request,
|
||||
) {
|
||||
return this.serialsService.generateQRCode(
|
||||
serialNumber,
|
||||
qrCodeDto.baseUrl,
|
||||
req.get('host'),
|
||||
req.get("host"),
|
||||
req.protocol,
|
||||
);
|
||||
}
|
||||
|
||||
@Get(':serialNumber/query')
|
||||
@Get(":serialNumber/query")
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async query(@Param('serialNumber') serialNumber: string) {
|
||||
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 = '',
|
||||
@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')
|
||||
@Patch(":serialNumber")
|
||||
@UseGuards(AuthGuard, AdminGuard)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async update(
|
||||
@Param('serialNumber') serialNumber: string,
|
||||
@Body() updateDto: UpdateSerialDto,
|
||||
@Param("serialNumber") serialNumber: string,
|
||||
@Body(UpdateSerialDto) updateDto: any,
|
||||
) {
|
||||
return this.serialsService.update(serialNumber, {
|
||||
companyName: updateDto.companyName,
|
||||
@@ -88,10 +111,10 @@ export class SerialsController {
|
||||
});
|
||||
}
|
||||
|
||||
@Post(':serialNumber/revoke')
|
||||
@Post(":serialNumber/revoke")
|
||||
@UseGuards(AuthGuard, AdminGuard)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async revoke(@Param('serialNumber') serialNumber: string) {
|
||||
async revoke(@Param("serialNumber") serialNumber: string) {
|
||||
return this.serialsService.revoke(serialNumber);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,235 +1,281 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import * as QRCode from 'qrcode';
|
||||
import { Serial, SerialListItem } from './dto';
|
||||
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[]> {
|
||||
async generate(
|
||||
companyName: string,
|
||||
quantity: number,
|
||||
validDays: number,
|
||||
userId: number,
|
||||
serialPrefix?: string,
|
||||
): Promise<SerialListItem[]> {
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const validUntil = new Date();
|
||||
validUntil.setDate(validUntil.getDate() + validDays);
|
||||
|
||||
const existingCompany = await this.dbService.get('SELECT * FROM companies WHERE company_name = ?', [companyName]);
|
||||
const existingCompany = await prisma.company.findUnique({
|
||||
where: { companyName },
|
||||
});
|
||||
if (!existingCompany) {
|
||||
await this.dbService.run('INSERT INTO companies (company_name, is_active) VALUES (?, 1)', [companyName]);
|
||||
await prisma.company.create({
|
||||
data: { companyName, isActive: true },
|
||||
});
|
||||
}
|
||||
|
||||
const serials: SerialListItem[] = [];
|
||||
const prefix = serialPrefix ? serialPrefix.toUpperCase().replace(/[^A-Z0-9]/g, '') : 'BF' + new Date().getFullYear().toString().substr(2);
|
||||
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 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]
|
||||
);
|
||||
|
||||
await prisma.serial.create({
|
||||
data: {
|
||||
serialNumber,
|
||||
companyName,
|
||||
validUntil,
|
||||
createdBy: userId,
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
|
||||
serials.push({
|
||||
serialNumber,
|
||||
companyName,
|
||||
validUntil: validUntil.toISOString(),
|
||||
isActive: true,
|
||||
createdAt: new Date().toISOString()
|
||||
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()]
|
||||
);
|
||||
async generateQRCode(
|
||||
serialNumber: string,
|
||||
baseUrl?: string,
|
||||
requestHost?: string,
|
||||
protocol?: string,
|
||||
) {
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const serial = await prisma.serial.findUnique({
|
||||
where: { serialNumber: serialNumber.toUpperCase() },
|
||||
include: {
|
||||
user: {
|
||||
select: { name: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!serial) {
|
||||
throw new Error('序列号不存在');
|
||||
throw new Error("序列号不存在");
|
||||
}
|
||||
|
||||
if (!serial.is_active) {
|
||||
throw new Error('序列号已被禁用');
|
||||
if (!serial.isActive) {
|
||||
throw new Error("序列号已被禁用");
|
||||
}
|
||||
|
||||
if (serial.valid_until && new Date(serial.valid_until) < new Date()) {
|
||||
throw new Error('序列号已过期');
|
||||
if (serial.validUntil && new Date(serial.validUntil) < 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 queryUrl = baseUrl.includes("?")
|
||||
? `${baseUrl}&serial=${serial.serialNumber}`
|
||||
: `${baseUrl}?serial=${serial.serialNumber}`;
|
||||
|
||||
const qrCodeData = await QRCode.toDataURL(queryUrl, {
|
||||
width: 200,
|
||||
color: {
|
||||
dark: '#165DFF',
|
||||
light: '#ffffff'
|
||||
}
|
||||
dark: "#165DFF",
|
||||
light: "#ffffff",
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
message: '二维码生成成功',
|
||||
message: "二维码生成成功",
|
||||
qrCodeData,
|
||||
queryUrl,
|
||||
serialNumber: serial.serial_number,
|
||||
companyName: serial.company_name,
|
||||
validUntil: serial.valid_until
|
||||
serialNumber: serial.serialNumber,
|
||||
companyName: serial.companyName,
|
||||
validUntil: serial.validUntil,
|
||||
};
|
||||
}
|
||||
|
||||
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()]
|
||||
);
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const serial = await prisma.serial.findUnique({
|
||||
where: { serialNumber: serialNumber.toUpperCase() },
|
||||
include: {
|
||||
user: {
|
||||
select: { name: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!serial) {
|
||||
throw new Error('序列号不存在');
|
||||
throw new Error("序列号不存在");
|
||||
}
|
||||
|
||||
if (serial.valid_until && new Date(serial.valid_until) < new Date()) {
|
||||
throw new Error('序列号已过期');
|
||||
if (serial.validUntil && new Date(serial.validUntil) < new Date()) {
|
||||
throw new Error("序列号已过期");
|
||||
}
|
||||
|
||||
return {
|
||||
message: '查询成功',
|
||||
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
|
||||
}
|
||||
serialNumber: serial.serialNumber,
|
||||
companyName: serial.companyName,
|
||||
validUntil: serial.validUntil,
|
||||
status: serial.isActive ? "active" : "disabled",
|
||||
isActive: serial.isActive,
|
||||
createdAt: serial.createdAt,
|
||||
createdBy: serial.user?.name,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async findAll(page: number, limit: number, search: string) {
|
||||
const prisma = this.dbService.getPrisma();
|
||||
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[] = [];
|
||||
const where = search
|
||||
? {
|
||||
OR: [
|
||||
{ serialNumber: { contains: search } },
|
||||
{ companyName: { contains: search } },
|
||||
],
|
||||
}
|
||||
: undefined;
|
||||
|
||||
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 [serials, total] = await Promise.all([
|
||||
prisma.serial.findMany({
|
||||
where,
|
||||
include: {
|
||||
user: {
|
||||
select: { name: true },
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
skip: offset,
|
||||
take: limit,
|
||||
}),
|
||||
prisma.serial.count({ where }),
|
||||
]);
|
||||
|
||||
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
|
||||
message: "获取序列号列表成功",
|
||||
data: serials.map((s) => ({
|
||||
serialNumber: s.serialNumber,
|
||||
companyName: s.companyName,
|
||||
validUntil: s.validUntil,
|
||||
isActive: s.isActive,
|
||||
createdAt: s.createdAt,
|
||||
createdBy: s.user?.name,
|
||||
})),
|
||||
pagination: {
|
||||
page: parseInt(page.toString()),
|
||||
limit: parseInt(limit.toString()),
|
||||
total,
|
||||
totalPages
|
||||
}
|
||||
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()]);
|
||||
async update(
|
||||
serialNumber: string,
|
||||
updateData: {
|
||||
companyName?: string;
|
||||
validUntil?: string;
|
||||
isActive?: boolean;
|
||||
},
|
||||
) {
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const existingSerial = await prisma.serial.findUnique({
|
||||
where: { serialNumber: serialNumber.toUpperCase() },
|
||||
});
|
||||
|
||||
if (!existingSerial) {
|
||||
throw new Error('序列号不存在');
|
||||
throw new Error("序列号不存在");
|
||||
}
|
||||
|
||||
const updateFields: string[] = [];
|
||||
const params: any[] = [];
|
||||
|
||||
const updateFields: any = {};
|
||||
if (updateData.companyName !== undefined) {
|
||||
updateFields.push('company_name = ?');
|
||||
params.push(updateData.companyName);
|
||||
updateFields.companyName = updateData.companyName;
|
||||
}
|
||||
|
||||
if (updateData.validUntil !== undefined) {
|
||||
updateFields.push('valid_until = ?');
|
||||
params.push(updateData.validUntil);
|
||||
updateFields.validUntil = new Date(updateData.validUntil);
|
||||
}
|
||||
|
||||
if (updateData.isActive !== undefined) {
|
||||
updateFields.push('is_active = ?');
|
||||
params.push(updateData.isActive ? 1 : 0);
|
||||
updateFields.isActive = updateData.isActive;
|
||||
}
|
||||
|
||||
if (updateFields.length === 0) {
|
||||
throw new Error('没有提供更新字段');
|
||||
if (Object.keys(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()]);
|
||||
const updatedSerial = await prisma.serial.update({
|
||||
where: { serialNumber: serialNumber.toUpperCase() },
|
||||
data: updateFields,
|
||||
include: {
|
||||
user: {
|
||||
select: { name: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
message: '序列号更新成功',
|
||||
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
|
||||
}
|
||||
serialNumber: updatedSerial.serialNumber,
|
||||
companyName: updatedSerial.companyName,
|
||||
validUntil: updatedSerial.validUntil,
|
||||
isActive: updatedSerial.isActive,
|
||||
createdAt: updatedSerial.createdAt,
|
||||
updatedAt: updatedSerial.updatedAt,
|
||||
createdBy: updatedSerial.user?.name,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async revoke(serialNumber: string) {
|
||||
const existingSerial = await this.dbService.get<{ is_active: number }>('SELECT * FROM serials WHERE serial_number = ?', [serialNumber.toUpperCase()]);
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const existingSerial = await prisma.serial.findUnique({
|
||||
where: { serialNumber: serialNumber.toUpperCase() },
|
||||
});
|
||||
|
||||
if (!existingSerial) {
|
||||
throw new Error('序列号不存在');
|
||||
throw new Error("序列号不存在");
|
||||
}
|
||||
|
||||
if (!existingSerial.is_active) {
|
||||
throw new Error('序列号已被吊销');
|
||||
if (!existingSerial.isActive) {
|
||||
throw new Error("序列号已被吊销");
|
||||
}
|
||||
|
||||
await this.dbService.run(
|
||||
'UPDATE serials SET is_active = 0, updated_at = CURRENT_TIMESTAMP WHERE serial_number = ?',
|
||||
[serialNumber.toUpperCase()]
|
||||
);
|
||||
await prisma.serial.update({
|
||||
where: { serialNumber: serialNumber.toUpperCase() },
|
||||
data: { isActive: false },
|
||||
});
|
||||
|
||||
return {
|
||||
message: '序列号已吊销',
|
||||
message: "序列号已吊销",
|
||||
data: {
|
||||
serialNumber: serialNumber.toUpperCase()
|
||||
}
|
||||
serialNumber: serialNumber.toUpperCase(),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
59
src/types/index.d.ts
vendored
59
src/types/index.d.ts
vendored
@@ -4,42 +4,42 @@ export interface User {
|
||||
password: string;
|
||||
name: string;
|
||||
email: string | null;
|
||||
role: 'admin' | 'user';
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
role: "admin" | "user";
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface Company {
|
||||
id: number;
|
||||
company_name: string;
|
||||
is_active: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
companyName: string;
|
||||
isActive: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
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;
|
||||
serialNumber: string;
|
||||
companyName: string;
|
||||
validUntil: Date | null;
|
||||
isActive: boolean;
|
||||
createdBy: number | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
createdByName?: string;
|
||||
}
|
||||
|
||||
export interface AuthUser {
|
||||
id: number;
|
||||
username: string;
|
||||
name: string;
|
||||
role: 'admin' | 'user';
|
||||
role: "admin" | "user";
|
||||
}
|
||||
|
||||
export interface JWTPayload {
|
||||
userId: number;
|
||||
username: string;
|
||||
role: 'admin' | 'user';
|
||||
role: "admin" | "user";
|
||||
}
|
||||
|
||||
export interface LoginRequest {
|
||||
@@ -105,7 +105,7 @@ export interface LoginResponse {
|
||||
username: string;
|
||||
name: string;
|
||||
email: string | null;
|
||||
role: 'admin' | 'user';
|
||||
role: "admin" | "user";
|
||||
};
|
||||
}
|
||||
|
||||
@@ -124,7 +124,7 @@ export interface CompanyListItem {
|
||||
lastCreated: string;
|
||||
serialCount: number;
|
||||
activeCount: number;
|
||||
status: 'active' | 'disabled';
|
||||
status: "active" | "disabled";
|
||||
}
|
||||
|
||||
export interface CompanyDetail {
|
||||
@@ -135,7 +135,7 @@ export interface CompanyDetail {
|
||||
expiredCount: number;
|
||||
firstCreated: string;
|
||||
lastCreated: string;
|
||||
status: 'active' | 'disabled';
|
||||
status: "active" | "disabled";
|
||||
serials: SerialListItem[];
|
||||
monthlyStats: MonthlyStat[];
|
||||
}
|
||||
@@ -154,7 +154,20 @@ export interface StatsOverview {
|
||||
|
||||
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 }>;
|
||||
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;
|
||||
}>;
|
||||
}
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
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();
|
||||
Reference in New Issue
Block a user