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
|
# NestJS
|
||||||
.nest-cli.json
|
.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。
|
浙江贝凡溯源管理平台的后端服务,基于 NestJS + TypeScript + SQLite。
|
||||||
|
|
||||||
@@ -6,9 +6,13 @@
|
|||||||
|
|
||||||
- **NestJS**: 渐进式 Node.js 框架
|
- **NestJS**: 渐进式 Node.js 框架
|
||||||
- **TypeScript**: 类型安全
|
- **TypeScript**: 类型安全
|
||||||
|
- **Prisma**: 现代化 ORM(使用 better-sqlite3 适配器)
|
||||||
- **SQLite**: 轻量级数据库
|
- **SQLite**: 轻量级数据库
|
||||||
- **JWT**: 身份认证
|
- **better-sqlite3**: 高性能 SQLite 驱动
|
||||||
|
- **@nestjs/jwt**: JWT 身份认证
|
||||||
- **bcryptjs**: 密码加密
|
- **bcryptjs**: 密码加密
|
||||||
|
- **Zod**: 运行时类型验证
|
||||||
|
- **nestjs-zod**: NestJS 与 Zod 集成
|
||||||
|
|
||||||
## 项目结构
|
## 项目结构
|
||||||
|
|
||||||
@@ -49,10 +53,20 @@ backend/
|
|||||||
|
|
||||||
## 安装
|
## 安装
|
||||||
|
|
||||||
|
1. 安装依赖:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pnpm install
|
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
|
- 用户名: admin
|
||||||
- 密码: Beifan@2026
|
- 密码: Beifan@2026
|
||||||
|
|
||||||
|
|||||||
26
package.json
26
package.json
@@ -5,6 +5,7 @@
|
|||||||
"author": "",
|
"author": "",
|
||||||
"private": true,
|
"private": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"packageManager": "pnpm@10.27.0",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "nest build",
|
"build": "nest build",
|
||||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
@@ -28,26 +29,26 @@
|
|||||||
"@nestjs/passport": "^11.0.5",
|
"@nestjs/passport": "^11.0.5",
|
||||||
"@nestjs/platform-express": "^11.1.13",
|
"@nestjs/platform-express": "^11.1.13",
|
||||||
"@nestjs/serve-static": "^5.0.4",
|
"@nestjs/serve-static": "^5.0.4",
|
||||||
|
"@prisma/adapter-better-sqlite3": "^7.3.0",
|
||||||
|
"@prisma/client": "^7.3.0",
|
||||||
"bcryptjs": "^3.0.3",
|
"bcryptjs": "^3.0.3",
|
||||||
"better-sqlite3": "^12.6.2",
|
"better-sqlite3": "^12.6.2",
|
||||||
"class-transformer": "^0.5.1",
|
|
||||||
"class-validator": "^0.14.3",
|
|
||||||
"dotenv": "^17.2.3",
|
"dotenv": "^17.2.3",
|
||||||
"jsonwebtoken": "^9.0.2",
|
"nestjs-zod": "^5.1.1",
|
||||||
"passport": "^0.7.0",
|
"passport": "^0.7.0",
|
||||||
"passport-jwt": "^4.0.1",
|
"passport-jwt": "^4.0.1",
|
||||||
|
"prisma": "^7.3.0",
|
||||||
"qrcode": "^1.5.4",
|
"qrcode": "^1.5.4",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
"rxjs": "^7.8.2"
|
"rxjs": "^7.8.2",
|
||||||
|
"zod": "^4.3.6"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@nestjs/cli": "^11.0.0",
|
"@nestjs/cli": "^11.0.16",
|
||||||
"@nestjs/schematics": "^11.0.0",
|
"@nestjs/schematics": "^11.0.9",
|
||||||
"@nestjs/testing": "^11.1.13",
|
"@nestjs/testing": "^11.1.13",
|
||||||
"@types/better-sqlite3": "^7.6.13",
|
|
||||||
"@types/express": "^5.0.6",
|
"@types/express": "^5.0.6",
|
||||||
"@types/jest": "^30.0.0",
|
"@types/jest": "^30.0.0",
|
||||||
"@types/jsonwebtoken": "^9.0.10",
|
|
||||||
"@types/node": "^25.2.1",
|
"@types/node": "^25.2.1",
|
||||||
"@types/passport-jwt": "^4.0.1",
|
"@types/passport-jwt": "^4.0.1",
|
||||||
"@types/qrcode": "^1.5.6",
|
"@types/qrcode": "^1.5.6",
|
||||||
@@ -63,6 +64,15 @@
|
|||||||
"tsx": "^4.21.0",
|
"tsx": "^4.21.0",
|
||||||
"typescript": "^5.9.3"
|
"typescript": "^5.9.3"
|
||||||
},
|
},
|
||||||
|
"pnpm": {
|
||||||
|
"onlyBuiltDependencies": [
|
||||||
|
"@nestjs/core",
|
||||||
|
"@prisma/engines",
|
||||||
|
"better-sqlite3",
|
||||||
|
"esbuild",
|
||||||
|
"unrs-resolver"
|
||||||
|
]
|
||||||
|
},
|
||||||
"jest": {
|
"jest": {
|
||||||
"moduleFileExtensions": [
|
"moduleFileExtensions": [
|
||||||
"js",
|
"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 { PrismaClient } from "@prisma/client";
|
||||||
import bcrypt from 'bcryptjs';
|
import bcrypt from "bcryptjs";
|
||||||
import path from 'path';
|
import path from "path";
|
||||||
import fs from 'fs';
|
import { PrismaBetterSqlite3 } from "@prisma/adapter-better-sqlite3";
|
||||||
|
|
||||||
const dbPath = path.join(process.cwd(), 'data/database.sqlite');
|
const url =
|
||||||
const dbDir = path.dirname(dbPath);
|
process.env.DATABASE_URL ||
|
||||||
|
"file:" + path.join(process.cwd(), "data/database.sqlite");
|
||||||
|
|
||||||
if (!fs.existsSync(dbDir)) {
|
const adapter = new PrismaBetterSqlite3({
|
||||||
fs.mkdirSync(dbDir, { recursive: true });
|
url,
|
||||||
}
|
});
|
||||||
|
|
||||||
const db = new Database(dbPath, { verbose: console.log });
|
const prisma = new PrismaClient({
|
||||||
|
log: ["query", "error", "warn"],
|
||||||
const createTables = (): void => {
|
adapter,
|
||||||
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 createDefaultUser = async (): Promise<void> => {
|
const createDefaultUser = async (): Promise<void> => {
|
||||||
const username = 'admin';
|
const username = "admin";
|
||||||
const password = 'Beifan@2026';
|
const password = "Beifan@2026";
|
||||||
const name = '系统管理员';
|
const name = "系统管理员";
|
||||||
|
|
||||||
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
|
const user = await prisma.user.findUnique({
|
||||||
|
where: { username },
|
||||||
|
});
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
const hashedPassword = await bcrypt.hash(password, 10);
|
const hashedPassword = await bcrypt.hash(password, 10);
|
||||||
|
|
||||||
db.prepare(
|
await prisma.user.create({
|
||||||
'INSERT INTO users (username, password, name, email, role) VALUES (?, ?, ?, ?, ?)'
|
data: {
|
||||||
).run(username, hashedPassword, name, 'admin@example.com', 'admin');
|
username,
|
||||||
|
password: hashedPassword,
|
||||||
|
name,
|
||||||
|
email: "admin@example.com",
|
||||||
|
role: "admin",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
console.log('默认管理员用户创建完成:');
|
console.log("默认管理员用户创建完成:");
|
||||||
console.log('用户名:', username);
|
console.log("用户名:", username);
|
||||||
console.log('密码:', password);
|
console.log("密码:", password);
|
||||||
} else {
|
} else {
|
||||||
console.log('默认管理员用户已存在');
|
console.log("默认管理员用户已存在");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const initDatabase = async (): Promise<void> => {
|
const initDatabase = async (): Promise<void> => {
|
||||||
createTables();
|
|
||||||
await createDefaultUser();
|
await createDefaultUser();
|
||||||
db.close();
|
await prisma.$disconnect();
|
||||||
console.log('数据库连接已关闭');
|
console.log("数据库连接已关闭");
|
||||||
};
|
};
|
||||||
|
|
||||||
initDatabase();
|
initDatabase();
|
||||||
|
|||||||
@@ -1,29 +1,45 @@
|
|||||||
import { Controller, Post, Get, Put, Body, UseGuards, Request, HttpCode, HttpStatus } from '@nestjs/common';
|
import {
|
||||||
import { AuthService } from './auth.service';
|
Controller,
|
||||||
import { AuthGuard } from './auth.guard';
|
Post,
|
||||||
import { LoginDto, ChangePasswordDto, UpdateProfileDto } from './dto';
|
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 {
|
export class AuthController {
|
||||||
constructor(private authService: AuthService) {}
|
constructor(private authService: AuthService) {}
|
||||||
|
|
||||||
@Post('login')
|
@Post("login")
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
async login(@Body() loginDto: LoginDto) {
|
async login(@Body(LoginDto) loginDto: any) {
|
||||||
const user = await this.authService.validateUser(loginDto.username, loginDto.password);
|
const user = await this.authService.validateUser(
|
||||||
|
loginDto.username,
|
||||||
|
loginDto.password,
|
||||||
|
);
|
||||||
return this.authService.login(user);
|
return this.authService.login(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('profile')
|
@Get("profile")
|
||||||
@UseGuards(AuthGuard)
|
@UseGuards(AuthGuard)
|
||||||
async getProfile(@Request() req) {
|
async getProfile(@Request() req) {
|
||||||
return this.authService.getProfile(req.user.id);
|
return this.authService.getProfile(req.user.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post('change-password')
|
@Post("change-password")
|
||||||
@UseGuards(AuthGuard)
|
@UseGuards(AuthGuard)
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
async changePassword(@Request() req, @Body() changePasswordDto: ChangePasswordDto) {
|
async changePassword(
|
||||||
|
@Request() req,
|
||||||
|
@Body(ChangePasswordDto) changePasswordDto: any,
|
||||||
|
) {
|
||||||
return this.authService.changePassword(
|
return this.authService.changePassword(
|
||||||
req.user.id,
|
req.user.id,
|
||||||
changePasswordDto.currentPassword,
|
changePasswordDto.currentPassword,
|
||||||
@@ -31,10 +47,17 @@ export class AuthController {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Put('profile')
|
@Put("profile")
|
||||||
@UseGuards(AuthGuard)
|
@UseGuards(AuthGuard)
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
async updateProfile(@Request() req, @Body() updateProfileDto: UpdateProfileDto) {
|
async updateProfile(
|
||||||
return this.authService.updateProfile(req.user.id, updateProfileDto.name, updateProfileDto.email);
|
@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 {
|
||||||
import { JwtService } from '@nestjs/jwt';
|
Injectable,
|
||||||
import { DatabaseService } from '../database/database.service';
|
CanActivate,
|
||||||
import { AuthUser } from '../types';
|
ExecutionContext,
|
||||||
|
UnauthorizedException,
|
||||||
|
} from "@nestjs/common";
|
||||||
|
import { JwtService } from "@nestjs/jwt";
|
||||||
|
import { DatabaseService } from "../database/database.service";
|
||||||
|
import { AuthUser } from "../types";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AuthGuard implements CanActivate {
|
export class AuthGuard implements CanActivate {
|
||||||
@@ -12,32 +17,42 @@ export class AuthGuard implements CanActivate {
|
|||||||
|
|
||||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||||
const request = context.switchToHttp().getRequest();
|
const request = context.switchToHttp().getRequest();
|
||||||
const authHeader = request.headers['authorization'];
|
const authHeader = request.headers["authorization"];
|
||||||
const token = authHeader && authHeader.split(' ')[1];
|
const token = authHeader && authHeader.split(" ")[1];
|
||||||
|
|
||||||
if (!token) {
|
if (!token) {
|
||||||
throw new UnauthorizedException('访问令牌缺失');
|
throw new UnauthorizedException("访问令牌缺失");
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const decoded = this.jwtService.verify(token) as { userId: number; username: string; role: string };
|
const decoded = this.jwtService.verify(token) as {
|
||||||
|
userId: number;
|
||||||
const user = await this.dbService.get<AuthUser>(
|
username: string;
|
||||||
'SELECT id, username, name, role FROM users WHERE id = ?',
|
role: string;
|
||||||
[decoded.userId]
|
};
|
||||||
);
|
|
||||||
|
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) {
|
if (!user) {
|
||||||
throw new UnauthorizedException('用户不存在');
|
throw new UnauthorizedException("用户不存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
request.user = user;
|
request.user = user as AuthUser;
|
||||||
return true;
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error.name === 'TokenExpiredError') {
|
if (error.name === "TokenExpiredError") {
|
||||||
throw new UnauthorizedException('令牌已过期');
|
throw new UnauthorizedException("令牌已过期");
|
||||||
}
|
}
|
||||||
throw new UnauthorizedException('无效的令牌');
|
throw new UnauthorizedException("无效的令牌");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
import { Injectable, UnauthorizedException } from "@nestjs/common";
|
||||||
import { JwtService } from '@nestjs/jwt';
|
import { JwtService } from "@nestjs/jwt";
|
||||||
import * as bcrypt from 'bcryptjs';
|
import * as bcrypt from "bcryptjs";
|
||||||
import { DatabaseService } from '../database/database.service';
|
import { DatabaseService } from "../database/database.service";
|
||||||
import { User, AuthUser } from '../types';
|
import { User, AuthUser } from "../types";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AuthService {
|
export class AuthService {
|
||||||
@@ -12,23 +12,30 @@ export class AuthService {
|
|||||||
) {}
|
) {}
|
||||||
|
|
||||||
async validateUser(username: string, password: string) {
|
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) {
|
if (!user) {
|
||||||
throw new UnauthorizedException('用户名或密码错误');
|
throw new UnauthorizedException("用户名或密码错误");
|
||||||
}
|
}
|
||||||
|
|
||||||
const isValidPassword = await bcrypt.compare(password, user.password);
|
const isValidPassword = await bcrypt.compare(password, user.password);
|
||||||
|
|
||||||
if (!isValidPassword) {
|
if (!isValidPassword) {
|
||||||
throw new UnauthorizedException('用户名或密码错误');
|
throw new UnauthorizedException("用户名或密码错误");
|
||||||
}
|
}
|
||||||
|
|
||||||
return user;
|
return user as User;
|
||||||
}
|
}
|
||||||
|
|
||||||
async login(user: 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);
|
const token = this.jwtService.sign(payload);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -39,74 +46,81 @@ export class AuthService {
|
|||||||
name: user.name,
|
name: user.name,
|
||||||
email: user.email,
|
email: user.email,
|
||||||
role: user.role,
|
role: user.role,
|
||||||
createdAt: user.created_at,
|
createdAt: user.createdAt,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async getProfile(userId: number) {
|
async getProfile(userId: number) {
|
||||||
const user = await this.dbService.get<User>(
|
const prisma = this.dbService.getPrisma();
|
||||||
'SELECT id, username, name, email, role, created_at FROM users WHERE id = ?',
|
const user = await prisma.user.findUnique({
|
||||||
[userId],
|
where: { id: userId },
|
||||||
);
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
name: true,
|
||||||
|
email: true,
|
||||||
|
role: true,
|
||||||
|
createdAt: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
throw new UnauthorizedException('用户不存在');
|
throw new UnauthorizedException("用户不存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return user;
|
||||||
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) {
|
async changePassword(
|
||||||
const user = await this.dbService.get<Pick<User, 'password'>>('SELECT password FROM users WHERE id = ?', [
|
userId: number,
|
||||||
userId,
|
currentPassword: string,
|
||||||
]);
|
newPassword: string,
|
||||||
|
) {
|
||||||
|
const prisma = this.dbService.getPrisma();
|
||||||
|
const user = await prisma.user.findUnique({
|
||||||
|
where: { id: userId },
|
||||||
|
select: { password: true },
|
||||||
|
});
|
||||||
|
|
||||||
if (!user) {
|
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) {
|
if (!isValidPassword) {
|
||||||
throw new UnauthorizedException('当前密码错误');
|
throw new UnauthorizedException("当前密码错误");
|
||||||
}
|
}
|
||||||
|
|
||||||
const hashedPassword = await bcrypt.hash(newPassword, 10);
|
const hashedPassword = await bcrypt.hash(newPassword, 10);
|
||||||
|
|
||||||
await this.dbService.run('UPDATE users SET password = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', [
|
await prisma.user.update({
|
||||||
hashedPassword,
|
where: { id: userId },
|
||||||
userId,
|
data: { password: hashedPassword },
|
||||||
]);
|
});
|
||||||
|
|
||||||
return { message: '密码修改成功' };
|
return { message: "密码修改成功" };
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateProfile(userId: number, name: string, email: string | null) {
|
async updateProfile(userId: number, name: string, email: string | null) {
|
||||||
await this.dbService.run(
|
const prisma = this.dbService.getPrisma();
|
||||||
'UPDATE users SET name = ?, email = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
|
const updatedUser = await prisma.user.update({
|
||||||
[name, email, userId],
|
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>(
|
return updatedUser;
|
||||||
'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,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,31 +1,16 @@
|
|||||||
import { IsString, IsNotEmpty, MinLength, IsEmail, IsOptional } from 'class-validator';
|
import { z } from "zod";
|
||||||
|
|
||||||
export class LoginDto {
|
export const LoginDto = z.object({
|
||||||
@IsString()
|
username: z.string().min(1, "用户名不能为空"),
|
||||||
@IsNotEmpty({ message: '用户名不能为空' })
|
password: z.string().min(1, "密码不能为空"),
|
||||||
username: string;
|
});
|
||||||
|
|
||||||
@IsString()
|
export const ChangePasswordDto = z.object({
|
||||||
@IsNotEmpty({ message: '密码不能为空' })
|
currentPassword: z.string().min(1, "当前密码不能为空"),
|
||||||
password: string;
|
newPassword: z.string().min(6, "新密码长度至少为6位"),
|
||||||
}
|
});
|
||||||
|
|
||||||
export class ChangePasswordDto {
|
export const UpdateProfileDto = z.object({
|
||||||
@IsString()
|
name: z.string().min(1, "姓名不能为空"),
|
||||||
@IsNotEmpty({ message: '当前密码不能为空' })
|
email: z.string().email("邮箱格式不正确").optional(),
|
||||||
currentPassword: string;
|
});
|
||||||
|
|
||||||
@IsString()
|
|
||||||
@MinLength(6, { message: '新密码长度至少为6位' })
|
|
||||||
newPassword: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class UpdateProfileDto {
|
|
||||||
@IsString()
|
|
||||||
@IsNotEmpty({ message: '姓名不能为空' })
|
|
||||||
name: string;
|
|
||||||
|
|
||||||
@IsOptional()
|
|
||||||
@IsEmail({}, { message: '邮箱格式不正确' })
|
|
||||||
email?: string;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,313 +1,324 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from "@nestjs/common";
|
||||||
import { DatabaseService } from '../database/database.service';
|
import { DatabaseService } from "../database/database.service";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class CompaniesService {
|
export class CompaniesService {
|
||||||
constructor(private dbService: DatabaseService) {}
|
constructor(private dbService: DatabaseService) {}
|
||||||
|
|
||||||
async findAll(page: number, limit: number, search: string) {
|
async findAll(page: number, limit: number, search: string) {
|
||||||
|
const prisma = this.dbService.getPrisma();
|
||||||
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`;
|
const where = search
|
||||||
let countQuery = 'SELECT COUNT(*) as total FROM companies';
|
? {
|
||||||
let params: any[] = [];
|
companyName: { contains: search },
|
||||||
|
}
|
||||||
|
: undefined;
|
||||||
|
|
||||||
if (search) {
|
const [companies, total] = await Promise.all([
|
||||||
query += ' WHERE c.company_name LIKE ?';
|
prisma.company.findMany({
|
||||||
countQuery += ' WHERE company_name LIKE ?';
|
where,
|
||||||
params.push(`%${search}%`);
|
include: {
|
||||||
}
|
serials: true,
|
||||||
|
},
|
||||||
query += ' ORDER BY c.updated_at DESC LIMIT ? OFFSET ?';
|
orderBy: { updatedAt: "desc" },
|
||||||
params.push(parseInt(limit.toString()), parseInt(offset.toString()));
|
skip: offset,
|
||||||
|
take: limit,
|
||||||
const [companies, countResult] = await Promise.all([
|
}),
|
||||||
this.dbService.all(query, params),
|
prisma.company.count({ where }),
|
||||||
this.dbService.get<{ total: number }>(countQuery, params.slice(0, -2))
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const total = countResult?.total || 0;
|
|
||||||
const totalPages = Math.ceil(total / limit);
|
const totalPages = Math.ceil(total / limit);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: '获取企业列表成功',
|
message: "获取企业列表成功",
|
||||||
data: companies.map((company: any) => ({
|
data: companies.map((company: any) => ({
|
||||||
companyName: company.company_name,
|
companyName: company.companyName,
|
||||||
firstCreated: company.first_created,
|
firstCreated: company.createdAt,
|
||||||
lastCreated: company.last_created,
|
lastCreated: company.updatedAt,
|
||||||
serialCount: company.serial_count,
|
serialCount: company.serials.length,
|
||||||
activeCount: company.active_count,
|
activeCount: company.serials.filter((s: any) => s.isActive).length,
|
||||||
status: company.is_active ? 'active' : 'disabled'
|
status: company.isActive ? "active" : "disabled",
|
||||||
})),
|
})),
|
||||||
pagination: {
|
pagination: {
|
||||||
page: parseInt(page.toString()),
|
page: parseInt(page.toString()),
|
||||||
limit: parseInt(limit.toString()),
|
limit: parseInt(limit.toString()),
|
||||||
total,
|
total,
|
||||||
totalPages
|
totalPages,
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async findOne(companyName: string, page: number, limit: number) {
|
async findOne(companyName: string, page: number, limit: number) {
|
||||||
|
const prisma = this.dbService.getPrisma();
|
||||||
const offset = (page - 1) * limit;
|
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) {
|
if (!company) {
|
||||||
throw new Error('企业不存在');
|
throw new Error("企业不存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
const serialStats = await this.dbService.get(`
|
const now = new Date();
|
||||||
SELECT COUNT(*) as serial_count,
|
const serialCount = company.serials.length;
|
||||||
SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active_count,
|
const activeCount = company.serials.filter(
|
||||||
SUM(CASE WHEN is_active = 0 THEN 1 ELSE 0 END) as disabled_count,
|
(s) => s.isActive && (!s.validUntil || s.validUntil > now),
|
||||||
SUM(CASE WHEN valid_until IS NOT NULL AND valid_until <= datetime('now') THEN 1 ELSE 0 END) as expired_count
|
).length;
|
||||||
FROM serials
|
const disabledCount = company.serials.filter((s) => !s.isActive).length;
|
||||||
WHERE company_name = ?
|
const expiredCount = company.serials.filter(
|
||||||
`, [companyName]);
|
(s) => s.validUntil && s.validUntil <= now,
|
||||||
|
).length;
|
||||||
|
|
||||||
const serials = await this.dbService.all(`
|
const monthlyStatsMap = new Map<string, number>();
|
||||||
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 stats = await this.dbService.all<{ month: string; count: number }>(`
|
for (let i = 11; i >= 0; i--) {
|
||||||
SELECT strftime('%Y-%m', created_at) as month,
|
const date = new Date(now.getFullYear(), now.getMonth() - i, 1);
|
||||||
COUNT(*) as count
|
const monthKey = date.toISOString().slice(0, 7);
|
||||||
FROM serials
|
const count = company.serials.filter((s) => {
|
||||||
WHERE company_name = ?
|
const createdAt = new Date(s.createdAt);
|
||||||
GROUP BY strftime('%Y-%m', created_at)
|
return (
|
||||||
ORDER BY month DESC
|
createdAt.getFullYear() === date.getFullYear() &&
|
||||||
LIMIT 12
|
createdAt.getMonth() === date.getMonth()
|
||||||
`, [companyName]);
|
);
|
||||||
|
}).length;
|
||||||
|
|
||||||
|
if (count > 0) {
|
||||||
|
monthlyStatsMap.set(monthKey, count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const paginatedSerials = company.serials.slice(offset, offset + limit);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: '获取企业详情成功',
|
message: "获取企业详情成功",
|
||||||
data: {
|
data: {
|
||||||
companyName: companyName,
|
companyName: companyName,
|
||||||
serialCount: serialStats?.serial_count || 0,
|
serialCount,
|
||||||
activeCount: serialStats?.active_count || 0,
|
activeCount,
|
||||||
disabledCount: serialStats?.disabled_count || 0,
|
disabledCount,
|
||||||
expiredCount: serialStats?.expired_count || 0,
|
expiredCount,
|
||||||
firstCreated: (companyInfo as any).created_at,
|
firstCreated: company.createdAt,
|
||||||
lastCreated: (companyInfo as any).updated_at,
|
lastCreated: company.updatedAt,
|
||||||
status: (companyInfo as any).is_active ? 'active' : 'disabled',
|
status: company.isActive ? "active" : "disabled",
|
||||||
serials: serials.map((s: any) => ({
|
serials: paginatedSerials.map((s) => ({
|
||||||
serialNumber: s.serial_number,
|
serialNumber: s.serialNumber,
|
||||||
validUntil: s.valid_until,
|
validUntil: s.validUntil,
|
||||||
isActive: s.is_active,
|
isActive: s.isActive,
|
||||||
createdAt: s.created_at,
|
createdAt: s.createdAt,
|
||||||
createdBy: s.created_by_name
|
createdBy: s.user?.name,
|
||||||
})),
|
})),
|
||||||
monthlyStats: stats.map(stat => ({
|
monthlyStats: Array.from(monthlyStatsMap.entries()).map(
|
||||||
month: stat.month,
|
([month, count]) => ({ month, count }),
|
||||||
count: stat.count
|
),
|
||||||
}))
|
},
|
||||||
}
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async update(companyName: string, newCompanyName: string) {
|
async update(companyName: string, newCompanyName: string) {
|
||||||
const existingCompany = await this.dbService.get(
|
const prisma = this.dbService.getPrisma();
|
||||||
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
const existingCompany = await prisma.serial.count({
|
||||||
[companyName]
|
where: { companyName },
|
||||||
);
|
});
|
||||||
|
|
||||||
if (!existingCompany || (existingCompany as any).count === 0) {
|
if (existingCompany === 0) {
|
||||||
throw new Error('企业不存在');
|
throw new Error("企业不存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
const duplicateCompany = await this.dbService.get(
|
const duplicateCompany = await prisma.serial.count({
|
||||||
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
where: { companyName: newCompanyName },
|
||||||
[newCompanyName]
|
});
|
||||||
);
|
|
||||||
|
|
||||||
if (duplicateCompany && (duplicateCompany as any).count > 0) {
|
if (duplicateCompany > 0) {
|
||||||
throw new Error('企业名称已存在');
|
throw new Error("企业名称已存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
this.dbService.run(
|
await prisma.serial.updateMany({
|
||||||
'UPDATE serials SET company_name = ?, updated_at = CURRENT_TIMESTAMP WHERE company_name = ?',
|
where: { companyName },
|
||||||
[newCompanyName, companyName]
|
data: { companyName: newCompanyName },
|
||||||
);
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: '企业名称更新成功',
|
message: "企业名称更新成功",
|
||||||
data: {
|
data: {
|
||||||
oldCompanyName: companyName,
|
oldCompanyName: companyName,
|
||||||
newCompanyName
|
newCompanyName,
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async delete(companyName: string) {
|
async delete(companyName: string) {
|
||||||
const existingCompany = await this.dbService.get(
|
const prisma = this.dbService.getPrisma();
|
||||||
'SELECT * FROM companies WHERE company_name = ?',
|
const existingCompany = await prisma.company.findUnique({
|
||||||
[companyName]
|
where: { companyName },
|
||||||
);
|
});
|
||||||
|
|
||||||
if (!existingCompany) {
|
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 {
|
await tx.company.delete({
|
||||||
const serialDeleteResult = this.dbService.run(
|
where: { companyName },
|
||||||
'DELETE FROM serials WHERE company_name = ?',
|
});
|
||||||
[companyName]
|
|
||||||
);
|
|
||||||
|
|
||||||
const companyDeleteResult = this.dbService.run(
|
return serialDeleteCount.count;
|
||||||
'DELETE FROM companies WHERE company_name = ?',
|
});
|
||||||
[companyName]
|
|
||||||
);
|
|
||||||
|
|
||||||
if (companyDeleteResult.changes === 0) {
|
return {
|
||||||
this.dbService.run('ROLLBACK');
|
message: "企业已完全删除,所有相关序列号已删除",
|
||||||
throw new Error('企业不存在');
|
data: {
|
||||||
}
|
companyName: companyName,
|
||||||
|
deletedSerialCount: deleteResult,
|
||||||
this.dbService.run('COMMIT');
|
deletedCompanyCount: 1,
|
||||||
|
},
|
||||||
return {
|
};
|
||||||
message: '企业已完全删除,所有相关序列号已删除',
|
|
||||||
data: {
|
|
||||||
companyName: companyName,
|
|
||||||
deletedSerialCount: serialDeleteResult.changes,
|
|
||||||
deletedCompanyCount: companyDeleteResult.changes
|
|
||||||
}
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
this.dbService.run('ROLLBACK');
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteSerial(companyName: string, serialNumber: string) {
|
async deleteSerial(companyName: string, serialNumber: string) {
|
||||||
const serial = await this.dbService.get(
|
const prisma = this.dbService.getPrisma();
|
||||||
'SELECT * FROM serials WHERE serial_number = ? AND company_name = ?',
|
const serial = await prisma.serial.findFirst({
|
||||||
[serialNumber.toUpperCase(), companyName]
|
where: {
|
||||||
);
|
serialNumber: serialNumber.toUpperCase(),
|
||||||
|
companyName,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
if (!serial) {
|
if (!serial) {
|
||||||
throw new Error('序列号不存在或不属于该企业');
|
throw new Error("序列号不存在或不属于该企业");
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.dbService.run(
|
await prisma.serial.delete({
|
||||||
'DELETE FROM serials WHERE serial_number = ? AND company_name = ?',
|
where: { serialNumber: serialNumber.toUpperCase() },
|
||||||
[serialNumber.toUpperCase(), companyName]
|
});
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: '序列号已成功删除',
|
message: "序列号已成功删除",
|
||||||
data: {
|
data: {
|
||||||
serialNumber: serialNumber.toUpperCase(),
|
serialNumber: serialNumber.toUpperCase(),
|
||||||
companyName
|
companyName,
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async revoke(companyName: string) {
|
async revoke(companyName: string) {
|
||||||
const existingCompany = await this.dbService.get(
|
const prisma = this.dbService.getPrisma();
|
||||||
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
const existingCompany = await prisma.serial.count({
|
||||||
[companyName]
|
where: { companyName },
|
||||||
);
|
});
|
||||||
|
|
||||||
if (!existingCompany || (existingCompany as any).count === 0) {
|
if (existingCompany === 0) {
|
||||||
throw new Error('企业不存在');
|
throw new Error("企业不存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.dbService.run(
|
await prisma.serial.updateMany({
|
||||||
'UPDATE serials SET is_active = 0, updated_at = CURRENT_TIMESTAMP WHERE company_name = ?',
|
where: { companyName },
|
||||||
[companyName]
|
data: { isActive: false },
|
||||||
);
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: '企业已吊销,所有序列号已失效',
|
message: "企业已吊销,所有序列号已失效",
|
||||||
data: {
|
data: {
|
||||||
companyName: companyName
|
companyName: companyName,
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async getStats() {
|
async getStats() {
|
||||||
const companyCount = await this.dbService.get<{ count: number }>('SELECT COUNT(*) as count FROM companies');
|
const prisma = this.dbService.getPrisma();
|
||||||
const serialCount = await this.dbService.get<{ count: number }>('SELECT COUNT(*) as count FROM serials');
|
const now = new Date();
|
||||||
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 monthlyStats = await this.dbService.all<{ month: string; company_count: number; serial_count: number }>(`
|
const [companies, serials, recentCompanies, recentSerials] =
|
||||||
SELECT strftime('%Y-%m', created_at) as month,
|
await Promise.all([
|
||||||
COUNT(DISTINCT company_name) as company_count,
|
prisma.company.findMany(),
|
||||||
COUNT(*) as serial_count
|
prisma.serial.findMany({
|
||||||
FROM serials
|
include: {
|
||||||
WHERE created_at >= strftime('%Y-%m-%d', datetime('now', '-12 months'))
|
company: true,
|
||||||
GROUP BY strftime('%Y-%m', created_at)
|
},
|
||||||
ORDER BY month ASC
|
}),
|
||||||
`);
|
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 }>(`
|
const companyCount = companies.length;
|
||||||
SELECT c.company_name, c.created_at as last_created, c.is_active
|
const serialCount = serials.length;
|
||||||
FROM companies c
|
const activeCount = serials.filter(
|
||||||
ORDER BY c.updated_at DESC
|
(s) => s.isActive && (!s.validUntil || s.validUntil > now),
|
||||||
LIMIT 10
|
).length;
|
||||||
`);
|
const inactiveCount = serialCount - activeCount;
|
||||||
|
|
||||||
const recentSerials = await this.dbService.all<{ serial_number: string; company_name: string; is_active: number; created_at: string }>(`
|
const monthlyStats: Array<{
|
||||||
SELECT s.serial_number, s.company_name, s.is_active, s.created_at
|
month: string;
|
||||||
FROM serials s
|
company_count: number;
|
||||||
ORDER BY s.created_at DESC
|
serial_count: number;
|
||||||
LIMIT 10
|
}> = [];
|
||||||
`);
|
const nowYear = now.getFullYear();
|
||||||
|
const nowMonth = now.getMonth();
|
||||||
|
|
||||||
let finalMonthlyStats = monthlyStats;
|
for (let i = 11; i >= 0; i--) {
|
||||||
if (monthlyStats.length === 0) {
|
const date = new Date(nowYear, nowMonth - i, 1);
|
||||||
finalMonthlyStats = [];
|
const monthStr = date.toISOString().slice(0, 7);
|
||||||
const now = new Date();
|
const monthSerials = serials.filter((s) => {
|
||||||
for (let i = 11; i >= 0; i--) {
|
const createdAt = new Date(s.createdAt);
|
||||||
const date = new Date(now.getFullYear(), now.getMonth() - i, 1);
|
return (
|
||||||
const month = date.toISOString().substr(0, 7);
|
createdAt.getFullYear() === date.getFullYear() &&
|
||||||
finalMonthlyStats.push({
|
createdAt.getMonth() === date.getMonth()
|
||||||
month,
|
);
|
||||||
company_count: 0,
|
});
|
||||||
serial_count: 0
|
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 {
|
return {
|
||||||
message: '获取统计数据成功',
|
message: "获取统计数据成功",
|
||||||
data: {
|
data: {
|
||||||
overview: {
|
overview: {
|
||||||
totalCompanies: companyCount?.count || 0,
|
totalCompanies: companyCount,
|
||||||
totalSerials: serialCount?.count || 0,
|
totalSerials: serialCount,
|
||||||
activeSerials: activeCount?.count || 0,
|
activeSerials: activeCount,
|
||||||
inactiveSerials: (serialCount?.count || 0) - (activeCount?.count || 0)
|
inactiveSerials: inactiveCount,
|
||||||
},
|
},
|
||||||
monthlyStats: finalMonthlyStats.map(stat => ({
|
monthlyStats,
|
||||||
month: stat.month,
|
recentCompanies: recentCompanies.map((c) => ({
|
||||||
company_count: stat.company_count,
|
companyName: c.companyName,
|
||||||
serial_count: stat.serial_count
|
lastCreated: c.updatedAt,
|
||||||
|
status: c.isActive ? "active" : "disabled",
|
||||||
})),
|
})),
|
||||||
recentCompanies: recentCompanies.map(c => ({
|
recentSerials: recentSerials.map((s) => ({
|
||||||
companyName: c.company_name,
|
serialNumber: s.serialNumber,
|
||||||
lastCreated: c.last_created,
|
companyName: s.companyName,
|
||||||
status: c.is_active ? 'active' : 'disabled'
|
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 { Injectable, OnModuleInit, OnModuleDestroy } from "@nestjs/common";
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { PrismaClient } from "@prisma/client";
|
||||||
import Database from 'better-sqlite3';
|
import path from "path";
|
||||||
import * as path from 'path';
|
import { PrismaBetterSqlite3 } from "@prisma/adapter-better-sqlite3";
|
||||||
import * as fs from 'fs';
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class DatabaseService implements OnModuleInit, OnModuleDestroy {
|
export class DatabaseService implements OnModuleInit, OnModuleDestroy {
|
||||||
private db: Database.Database;
|
private prisma: PrismaClient;
|
||||||
private dbPath: string;
|
|
||||||
|
|
||||||
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() {
|
onModuleInit() {
|
||||||
this.dbPath = this.configService.get<string>('DB_PATH', path.join(process.cwd(), 'data/database.sqlite'));
|
this.prisma.$connect();
|
||||||
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() {
|
onModuleDestroy() {
|
||||||
this.db.close();
|
this.prisma.$disconnect();
|
||||||
}
|
}
|
||||||
|
|
||||||
get<T = any>(sql: string, params: any[] = []): T | undefined {
|
getPrisma() {
|
||||||
try {
|
return this.prisma;
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 { NestFactory } from "@nestjs/core";
|
||||||
import { AppModule } from './app.module';
|
import { AppModule } from "./app.module";
|
||||||
import { ValidationPipe } from '@nestjs/common';
|
import { ConfigService } from "@nestjs/config";
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { join } from "path";
|
||||||
import { join } from 'path';
|
import { NestExpressApplication } from "@nestjs/platform-express";
|
||||||
import { NestExpressApplication } from '@nestjs/platform-express';
|
import { ZodValidationPipe } from "nestjs-zod";
|
||||||
|
|
||||||
async function bootstrap() {
|
async function bootstrap() {
|
||||||
const app = await NestFactory.create<NestExpressApplication>(AppModule);
|
const app = await NestFactory.create<NestExpressApplication>(AppModule);
|
||||||
const configService = app.get(ConfigService);
|
const configService = app.get(ConfigService);
|
||||||
|
|
||||||
app.enableCors();
|
app.enableCors();
|
||||||
app.useGlobalPipes(new ValidationPipe({ transform: true }));
|
app.useGlobalPipes(new ZodValidationPipe());
|
||||||
app.setGlobalPrefix('api');
|
app.setGlobalPrefix("api");
|
||||||
|
|
||||||
// 静态文件服务
|
// 静态文件服务
|
||||||
const frontendPath = join(__dirname, '..', 'frontend');
|
const frontendPath = join(__dirname, "..", "frontend");
|
||||||
const distPath = join(frontendPath, 'dist');
|
const distPath = join(frontendPath, "dist");
|
||||||
const publicPath = join(frontendPath, 'public');
|
const publicPath = join(frontendPath, "public");
|
||||||
|
|
||||||
if (process.env.NODE_ENV === 'production') {
|
if (process.env.NODE_ENV === "production") {
|
||||||
app.useStaticAssets(distPath);
|
app.useStaticAssets(distPath);
|
||||||
} else {
|
} else {
|
||||||
app.useStaticAssets(publicPath);
|
app.useStaticAssets(publicPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
const port = configService.get<number>('PORT', 3000);
|
const port = configService.get<number>("PORT", 3000);
|
||||||
await app.listen(port);
|
await app.listen(port);
|
||||||
|
|
||||||
console.log(`服务器运行在 http://localhost:${port}`);
|
console.log(`服务器运行在 http://localhost:${port}`);
|
||||||
console.log(`API文档: http://localhost:${port}/api/health`);
|
console.log(`API文档: http://localhost:${port}/api/health`);
|
||||||
console.log(`环境: ${process.env.NODE_ENV || 'development'}`);
|
console.log(`环境: ${process.env.NODE_ENV || "development"}`);
|
||||||
}
|
}
|
||||||
bootstrap();
|
bootstrap();
|
||||||
|
|||||||
@@ -1,46 +1,24 @@
|
|||||||
import { IsString, IsNotEmpty, IsNumber, IsOptional, IsBoolean, Min, Max } from 'class-validator';
|
import { z } from "zod";
|
||||||
|
|
||||||
export class GenerateSerialDto {
|
export const GenerateSerialDto = z.object({
|
||||||
@IsString()
|
companyName: z.string().min(1, "企业名称不能为空"),
|
||||||
@IsNotEmpty({ message: '企业名称不能为空' })
|
quantity: z.number().min(1).max(100).optional(),
|
||||||
companyName: string;
|
validDays: z.number().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
@IsOptional()
|
export const GenerateWithPrefixDto = GenerateSerialDto.extend({
|
||||||
@IsNumber()
|
serialPrefix: z.string().min(1, "自定义前缀不能为空"),
|
||||||
@Min(1)
|
});
|
||||||
@Max(100)
|
|
||||||
quantity?: number;
|
|
||||||
|
|
||||||
@IsOptional()
|
export const QRCodeDto = z.object({
|
||||||
@IsNumber()
|
baseUrl: z.string().optional(),
|
||||||
validDays?: number;
|
});
|
||||||
}
|
|
||||||
|
|
||||||
export class GenerateWithPrefixDto extends GenerateSerialDto {
|
export const UpdateSerialDto = z.object({
|
||||||
@IsString()
|
companyName: z.string().optional(),
|
||||||
@IsNotEmpty({ message: '自定义前缀不能为空' })
|
validUntil: z.string().optional(),
|
||||||
serialPrefix: string;
|
isActive: z.boolean().optional(),
|
||||||
}
|
});
|
||||||
|
|
||||||
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 {
|
export interface Serial {
|
||||||
id: number;
|
id: number;
|
||||||
|
|||||||
@@ -1,18 +1,38 @@
|
|||||||
import { Controller, Get, Post, Patch, Body, Param, Query, UseGuards, Req, HttpCode, HttpStatus } from '@nestjs/common';
|
import {
|
||||||
import { Request } from 'express';
|
Controller,
|
||||||
import { SerialsService } from './serials.service';
|
Get,
|
||||||
import { AuthGuard } from '../auth/auth.guard';
|
Post,
|
||||||
import { AdminGuard } from '../auth/admin.guard';
|
Patch,
|
||||||
import { GenerateSerialDto, GenerateWithPrefixDto, QRCodeDto, UpdateSerialDto } from './dto';
|
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 {
|
export class SerialsController {
|
||||||
constructor(private readonly serialsService: SerialsService) {}
|
constructor(private readonly serialsService: SerialsService) {}
|
||||||
|
|
||||||
@Post('generate')
|
@Post("generate")
|
||||||
@UseGuards(AuthGuard, AdminGuard)
|
@UseGuards(AuthGuard, AdminGuard)
|
||||||
@HttpCode(HttpStatus.OK)
|
@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(
|
const serials = await this.serialsService.generate(
|
||||||
generateDto.companyName,
|
generateDto.companyName,
|
||||||
generateDto.quantity || 1,
|
generateDto.quantity || 1,
|
||||||
@@ -25,10 +45,13 @@ export class SerialsController {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post('generate-with-prefix')
|
@Post("generate-with-prefix")
|
||||||
@UseGuards(AuthGuard, AdminGuard)
|
@UseGuards(AuthGuard, AdminGuard)
|
||||||
@HttpCode(HttpStatus.OK)
|
@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(
|
const serials = await this.serialsService.generate(
|
||||||
generateDto.companyName,
|
generateDto.companyName,
|
||||||
generateDto.quantity || 1,
|
generateDto.quantity || 1,
|
||||||
@@ -42,44 +65,44 @@ export class SerialsController {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post(':serialNumber/qrcode')
|
@Post(":serialNumber/qrcode")
|
||||||
@UseGuards(AuthGuard)
|
@UseGuards(AuthGuard)
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
async generateQRCode(
|
async generateQRCode(
|
||||||
@Param('serialNumber') serialNumber: string,
|
@Param("serialNumber") serialNumber: string,
|
||||||
@Body() qrCodeDto: QRCodeDto,
|
@Body(QRCodeDto) qrCodeDto: any,
|
||||||
@Req() req: Request,
|
@Req() req: Request,
|
||||||
) {
|
) {
|
||||||
return this.serialsService.generateQRCode(
|
return this.serialsService.generateQRCode(
|
||||||
serialNumber,
|
serialNumber,
|
||||||
qrCodeDto.baseUrl,
|
qrCodeDto.baseUrl,
|
||||||
req.get('host'),
|
req.get("host"),
|
||||||
req.protocol,
|
req.protocol,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':serialNumber/query')
|
@Get(":serialNumber/query")
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
async query(@Param('serialNumber') serialNumber: string) {
|
async query(@Param("serialNumber") serialNumber: string) {
|
||||||
return this.serialsService.query(serialNumber);
|
return this.serialsService.query(serialNumber);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@UseGuards(AuthGuard)
|
@UseGuards(AuthGuard)
|
||||||
async findAll(
|
async findAll(
|
||||||
@Query('page') page: string = '1',
|
@Query("page") page: string = "1",
|
||||||
@Query('limit') limit: string = '20',
|
@Query("limit") limit: string = "20",
|
||||||
@Query('search') search: string = '',
|
@Query("search") search: string = "",
|
||||||
) {
|
) {
|
||||||
return this.serialsService.findAll(parseInt(page), parseInt(limit), search);
|
return this.serialsService.findAll(parseInt(page), parseInt(limit), search);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Patch(':serialNumber')
|
@Patch(":serialNumber")
|
||||||
@UseGuards(AuthGuard, AdminGuard)
|
@UseGuards(AuthGuard, AdminGuard)
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
async update(
|
async update(
|
||||||
@Param('serialNumber') serialNumber: string,
|
@Param("serialNumber") serialNumber: string,
|
||||||
@Body() updateDto: UpdateSerialDto,
|
@Body(UpdateSerialDto) updateDto: any,
|
||||||
) {
|
) {
|
||||||
return this.serialsService.update(serialNumber, {
|
return this.serialsService.update(serialNumber, {
|
||||||
companyName: updateDto.companyName,
|
companyName: updateDto.companyName,
|
||||||
@@ -88,10 +111,10 @@ export class SerialsController {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post(':serialNumber/revoke')
|
@Post(":serialNumber/revoke")
|
||||||
@UseGuards(AuthGuard, AdminGuard)
|
@UseGuards(AuthGuard, AdminGuard)
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
async revoke(@Param('serialNumber') serialNumber: string) {
|
async revoke(@Param("serialNumber") serialNumber: string) {
|
||||||
return this.serialsService.revoke(serialNumber);
|
return this.serialsService.revoke(serialNumber);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,235 +1,281 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from "@nestjs/common";
|
||||||
import { DatabaseService } from '../database/database.service';
|
import { DatabaseService } from "../database/database.service";
|
||||||
import * as QRCode from 'qrcode';
|
import * as QRCode from "qrcode";
|
||||||
import { Serial, SerialListItem } from './dto';
|
import { Serial, SerialListItem } from "./dto";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class SerialsService {
|
export class SerialsService {
|
||||||
constructor(private dbService: DatabaseService) {}
|
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();
|
const validUntil = new Date();
|
||||||
validUntil.setDate(validUntil.getDate() + validDays);
|
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) {
|
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 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++) {
|
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}`;
|
const serialNumber = `${prefix}${randomPart}`;
|
||||||
|
|
||||||
await this.dbService.run(
|
await prisma.serial.create({
|
||||||
'INSERT INTO serials (serial_number, company_name, valid_until, created_by) VALUES (?, ?, ?, ?)',
|
data: {
|
||||||
[serialNumber, companyName, validUntil.toISOString().slice(0, 19).replace('T', ' '), userId]
|
serialNumber,
|
||||||
);
|
companyName,
|
||||||
|
validUntil,
|
||||||
|
createdBy: userId,
|
||||||
|
isActive: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
serials.push({
|
serials.push({
|
||||||
serialNumber,
|
serialNumber,
|
||||||
companyName,
|
companyName,
|
||||||
validUntil: validUntil.toISOString(),
|
validUntil: validUntil.toISOString(),
|
||||||
isActive: true,
|
isActive: true,
|
||||||
createdAt: new Date().toISOString()
|
createdAt: new Date().toISOString(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return serials;
|
return serials;
|
||||||
}
|
}
|
||||||
|
|
||||||
async generateQRCode(serialNumber: string, baseUrl?: string, requestHost?: string, protocol?: string) {
|
async generateQRCode(
|
||||||
const serial = await this.dbService.get<{ serial_number: string; company_name: string; is_active: number; valid_until: string | null }>(
|
serialNumber: 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 = ?',
|
baseUrl?: string,
|
||||||
[serialNumber.toUpperCase()]
|
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) {
|
if (!serial) {
|
||||||
throw new Error('序列号不存在');
|
throw new Error("序列号不存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!serial.is_active) {
|
if (!serial.isActive) {
|
||||||
throw new Error('序列号已被禁用');
|
throw new Error("序列号已被禁用");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (serial.valid_until && new Date(serial.valid_until) < new Date()) {
|
if (serial.validUntil && new Date(serial.validUntil) < new Date()) {
|
||||||
throw new Error('序列号已过期');
|
throw new Error("序列号已过期");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!baseUrl) {
|
if (!baseUrl) {
|
||||||
baseUrl = `${protocol}://${requestHost}/query.html`;
|
baseUrl = `${protocol}://${requestHost}/query.html`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const queryUrl = baseUrl.includes('?')
|
const queryUrl = baseUrl.includes("?")
|
||||||
? `${baseUrl}&serial=${serial.serial_number}`
|
? `${baseUrl}&serial=${serial.serialNumber}`
|
||||||
: `${baseUrl}?serial=${serial.serial_number}`;
|
: `${baseUrl}?serial=${serial.serialNumber}`;
|
||||||
|
|
||||||
const qrCodeData = await QRCode.toDataURL(queryUrl, {
|
const qrCodeData = await QRCode.toDataURL(queryUrl, {
|
||||||
width: 200,
|
width: 200,
|
||||||
color: {
|
color: {
|
||||||
dark: '#165DFF',
|
dark: "#165DFF",
|
||||||
light: '#ffffff'
|
light: "#ffffff",
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: '二维码生成成功',
|
message: "二维码生成成功",
|
||||||
qrCodeData,
|
qrCodeData,
|
||||||
queryUrl,
|
queryUrl,
|
||||||
serialNumber: serial.serial_number,
|
serialNumber: serial.serialNumber,
|
||||||
companyName: serial.company_name,
|
companyName: serial.companyName,
|
||||||
validUntil: serial.valid_until
|
validUntil: serial.validUntil,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async query(serialNumber: string) {
|
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 }>(
|
const prisma = this.dbService.getPrisma();
|
||||||
'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 = ?',
|
const serial = await prisma.serial.findUnique({
|
||||||
[serialNumber.toUpperCase()]
|
where: { serialNumber: serialNumber.toUpperCase() },
|
||||||
);
|
include: {
|
||||||
|
user: {
|
||||||
|
select: { name: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
if (!serial) {
|
if (!serial) {
|
||||||
throw new Error('序列号不存在');
|
throw new Error("序列号不存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (serial.valid_until && new Date(serial.valid_until) < new Date()) {
|
if (serial.validUntil && new Date(serial.validUntil) < new Date()) {
|
||||||
throw new Error('序列号已过期');
|
throw new Error("序列号已过期");
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: '查询成功',
|
message: "查询成功",
|
||||||
serial: {
|
serial: {
|
||||||
serialNumber: serial.serial_number,
|
serialNumber: serial.serialNumber,
|
||||||
companyName: serial.company_name,
|
companyName: serial.companyName,
|
||||||
validUntil: serial.valid_until,
|
validUntil: serial.validUntil,
|
||||||
status: serial.is_active ? 'active' : 'disabled',
|
status: serial.isActive ? "active" : "disabled",
|
||||||
isActive: !!serial.is_active,
|
isActive: serial.isActive,
|
||||||
createdAt: serial.created_at,
|
createdAt: serial.createdAt,
|
||||||
createdBy: serial.created_by_name
|
createdBy: serial.user?.name,
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async findAll(page: number, limit: number, search: string) {
|
async findAll(page: number, limit: number, search: string) {
|
||||||
|
const prisma = this.dbService.getPrisma();
|
||||||
const offset = (page - 1) * limit;
|
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';
|
const where = search
|
||||||
let countQuery = 'SELECT COUNT(*) as total FROM serials s';
|
? {
|
||||||
let params: any[] = [];
|
OR: [
|
||||||
|
{ serialNumber: { contains: search } },
|
||||||
|
{ companyName: { contains: search } },
|
||||||
|
],
|
||||||
|
}
|
||||||
|
: undefined;
|
||||||
|
|
||||||
if (search) {
|
const [serials, total] = await Promise.all([
|
||||||
query += ' WHERE s.serial_number LIKE ? OR s.company_name LIKE ?';
|
prisma.serial.findMany({
|
||||||
countQuery += ' WHERE s.serial_number LIKE ? OR s.company_name LIKE ?';
|
where,
|
||||||
const searchParam = `%${search}%`;
|
include: {
|
||||||
params.push(searchParam, searchParam);
|
user: {
|
||||||
}
|
select: { name: true },
|
||||||
|
},
|
||||||
query += ' ORDER BY s.created_at DESC LIMIT ? OFFSET ?';
|
},
|
||||||
params.push(parseInt(limit.toString()), parseInt(offset.toString()));
|
orderBy: { createdAt: "desc" },
|
||||||
|
skip: offset,
|
||||||
const [serials, countResult] = await Promise.all([
|
take: limit,
|
||||||
this.dbService.all(query, params),
|
}),
|
||||||
this.dbService.get<{ total: number }>(countQuery, params.slice(0, -2))
|
prisma.serial.count({ where }),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const total = countResult?.total || 0;
|
|
||||||
const totalPages = Math.ceil(total / limit);
|
const totalPages = Math.ceil(total / limit);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: '获取序列号列表成功',
|
message: "获取序列号列表成功",
|
||||||
data: serials.map((s: any) => ({
|
data: serials.map((s) => ({
|
||||||
serialNumber: s.serial_number,
|
serialNumber: s.serialNumber,
|
||||||
companyName: s.company_name,
|
companyName: s.companyName,
|
||||||
validUntil: s.valid_until,
|
validUntil: s.validUntil,
|
||||||
isActive: s.is_active,
|
isActive: s.isActive,
|
||||||
createdAt: s.created_at,
|
createdAt: s.createdAt,
|
||||||
createdBy: s.created_by_name
|
createdBy: s.user?.name,
|
||||||
})),
|
})),
|
||||||
pagination: {
|
pagination: {
|
||||||
page: parseInt(page.toString()),
|
page: parseInt(page.toString()),
|
||||||
limit: parseInt(limit.toString()),
|
limit: parseInt(limit.toString()),
|
||||||
total,
|
total,
|
||||||
totalPages
|
totalPages,
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async update(serialNumber: string, updateData: { companyName?: string; validUntil?: string; isActive?: boolean }) {
|
async update(
|
||||||
const existingSerial = await this.dbService.get<{ is_active: number }>('SELECT * FROM serials WHERE serial_number = ?', [serialNumber.toUpperCase()]);
|
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) {
|
if (!existingSerial) {
|
||||||
throw new Error('序列号不存在');
|
throw new Error("序列号不存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
const updateFields: string[] = [];
|
const updateFields: any = {};
|
||||||
const params: any[] = [];
|
|
||||||
|
|
||||||
if (updateData.companyName !== undefined) {
|
if (updateData.companyName !== undefined) {
|
||||||
updateFields.push('company_name = ?');
|
updateFields.companyName = updateData.companyName;
|
||||||
params.push(updateData.companyName);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (updateData.validUntil !== undefined) {
|
if (updateData.validUntil !== undefined) {
|
||||||
updateFields.push('valid_until = ?');
|
updateFields.validUntil = new Date(updateData.validUntil);
|
||||||
params.push(updateData.validUntil);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (updateData.isActive !== undefined) {
|
if (updateData.isActive !== undefined) {
|
||||||
updateFields.push('is_active = ?');
|
updateFields.isActive = updateData.isActive;
|
||||||
params.push(updateData.isActive ? 1 : 0);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (updateFields.length === 0) {
|
if (Object.keys(updateFields).length === 0) {
|
||||||
throw new Error('没有提供更新字段');
|
throw new Error("没有提供更新字段");
|
||||||
}
|
}
|
||||||
|
|
||||||
updateFields.push('updated_at = CURRENT_TIMESTAMP');
|
const updatedSerial = await prisma.serial.update({
|
||||||
params.push(serialNumber.toUpperCase());
|
where: { serialNumber: serialNumber.toUpperCase() },
|
||||||
|
data: updateFields,
|
||||||
await this.dbService.run(
|
include: {
|
||||||
`UPDATE serials SET ${updateFields.join(', ')} WHERE serial_number = ?`,
|
user: {
|
||||||
params
|
select: { name: true },
|
||||||
);
|
},
|
||||||
|
},
|
||||||
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 {
|
return {
|
||||||
message: '序列号更新成功',
|
message: "序列号更新成功",
|
||||||
serial: {
|
serial: {
|
||||||
serialNumber: (updatedSerial as any).serial_number,
|
serialNumber: updatedSerial.serialNumber,
|
||||||
companyName: (updatedSerial as any).company_name,
|
companyName: updatedSerial.companyName,
|
||||||
validUntil: (updatedSerial as any).valid_until,
|
validUntil: updatedSerial.validUntil,
|
||||||
isActive: (updatedSerial as any).is_active,
|
isActive: updatedSerial.isActive,
|
||||||
createdAt: (updatedSerial as any).created_at,
|
createdAt: updatedSerial.createdAt,
|
||||||
updatedAt: (updatedSerial as any).updated_at,
|
updatedAt: updatedSerial.updatedAt,
|
||||||
createdBy: (updatedSerial as any).created_by_name
|
createdBy: updatedSerial.user?.name,
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async revoke(serialNumber: string) {
|
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) {
|
if (!existingSerial) {
|
||||||
throw new Error('序列号不存在');
|
throw new Error("序列号不存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!existingSerial.is_active) {
|
if (!existingSerial.isActive) {
|
||||||
throw new Error('序列号已被吊销');
|
throw new Error("序列号已被吊销");
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.dbService.run(
|
await prisma.serial.update({
|
||||||
'UPDATE serials SET is_active = 0, updated_at = CURRENT_TIMESTAMP WHERE serial_number = ?',
|
where: { serialNumber: serialNumber.toUpperCase() },
|
||||||
[serialNumber.toUpperCase()]
|
data: { isActive: false },
|
||||||
);
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: '序列号已吊销',
|
message: "序列号已吊销",
|
||||||
data: {
|
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;
|
password: string;
|
||||||
name: string;
|
name: string;
|
||||||
email: string | null;
|
email: string | null;
|
||||||
role: 'admin' | 'user';
|
role: "admin" | "user";
|
||||||
created_at: string;
|
createdAt: Date;
|
||||||
updated_at: string;
|
updatedAt: Date;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Company {
|
export interface Company {
|
||||||
id: number;
|
id: number;
|
||||||
company_name: string;
|
companyName: string;
|
||||||
is_active: boolean;
|
isActive: boolean;
|
||||||
created_at: string;
|
createdAt: Date;
|
||||||
updated_at: string;
|
updatedAt: Date;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Serial {
|
export interface Serial {
|
||||||
id: number;
|
id: number;
|
||||||
serial_number: string;
|
serialNumber: string;
|
||||||
company_name: string;
|
companyName: string;
|
||||||
valid_until: string | null;
|
validUntil: Date | null;
|
||||||
is_active: boolean;
|
isActive: boolean;
|
||||||
created_by: number | null;
|
createdBy: number | null;
|
||||||
created_at: string;
|
createdAt: Date;
|
||||||
updated_at: string;
|
updatedAt: Date;
|
||||||
created_by_name?: string;
|
createdByName?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AuthUser {
|
export interface AuthUser {
|
||||||
id: number;
|
id: number;
|
||||||
username: string;
|
username: string;
|
||||||
name: string;
|
name: string;
|
||||||
role: 'admin' | 'user';
|
role: "admin" | "user";
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface JWTPayload {
|
export interface JWTPayload {
|
||||||
userId: number;
|
userId: number;
|
||||||
username: string;
|
username: string;
|
||||||
role: 'admin' | 'user';
|
role: "admin" | "user";
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface LoginRequest {
|
export interface LoginRequest {
|
||||||
@@ -105,7 +105,7 @@ export interface LoginResponse {
|
|||||||
username: string;
|
username: string;
|
||||||
name: string;
|
name: string;
|
||||||
email: string | null;
|
email: string | null;
|
||||||
role: 'admin' | 'user';
|
role: "admin" | "user";
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -124,7 +124,7 @@ export interface CompanyListItem {
|
|||||||
lastCreated: string;
|
lastCreated: string;
|
||||||
serialCount: number;
|
serialCount: number;
|
||||||
activeCount: number;
|
activeCount: number;
|
||||||
status: 'active' | 'disabled';
|
status: "active" | "disabled";
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CompanyDetail {
|
export interface CompanyDetail {
|
||||||
@@ -135,7 +135,7 @@ export interface CompanyDetail {
|
|||||||
expiredCount: number;
|
expiredCount: number;
|
||||||
firstCreated: string;
|
firstCreated: string;
|
||||||
lastCreated: string;
|
lastCreated: string;
|
||||||
status: 'active' | 'disabled';
|
status: "active" | "disabled";
|
||||||
serials: SerialListItem[];
|
serials: SerialListItem[];
|
||||||
monthlyStats: MonthlyStat[];
|
monthlyStats: MonthlyStat[];
|
||||||
}
|
}
|
||||||
@@ -154,7 +154,20 @@ export interface StatsOverview {
|
|||||||
|
|
||||||
export interface StatsResponse {
|
export interface StatsResponse {
|
||||||
overview: StatsOverview;
|
overview: StatsOverview;
|
||||||
monthlyStats: Array<{ month: string; company_count: number; serial_count: number }>;
|
monthlyStats: Array<{
|
||||||
recentCompanies: Array<{ companyName: string; lastCreated: string; status: 'active' | 'disabled' }>;
|
month: string;
|
||||||
recentSerials: Array<{ serialNumber: string; companyName: string; isActive: boolean; createdAt: 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