refactor: migrate backend framework from Express to NestJS
This commit is contained in:
22
src/app.module.ts
Normal file
22
src/app.module.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { SerialsModule } from './serials/serials.module';
|
||||
import { CompaniesModule } from './companies/companies.module';
|
||||
import { DatabaseModule } from './database/database.module';
|
||||
import { HealthController } from './health.controller';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
envFilePath: '.env',
|
||||
}),
|
||||
DatabaseModule,
|
||||
AuthModule,
|
||||
SerialsModule,
|
||||
CompaniesModule,
|
||||
],
|
||||
controllers: [HealthController],
|
||||
})
|
||||
export class AppModule {}
|
||||
14
src/auth/admin.guard.ts
Normal file
14
src/auth/admin.guard.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class AdminGuard implements CanActivate {
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const user = request.user;
|
||||
|
||||
if (user?.role !== 'admin') {
|
||||
throw new ForbiddenException('需要管理员权限');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
40
src/auth/auth.controller.ts
Normal file
40
src/auth/auth.controller.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { Controller, Post, Get, Put, Body, UseGuards, Request, HttpCode, HttpStatus } from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { AuthGuard } from './auth.guard';
|
||||
import { LoginDto, ChangePasswordDto, UpdateProfileDto } from './dto';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private authService: AuthService) {}
|
||||
|
||||
@Post('login')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async login(@Body() loginDto: LoginDto) {
|
||||
const user = await this.authService.validateUser(loginDto.username, loginDto.password);
|
||||
return this.authService.login(user);
|
||||
}
|
||||
|
||||
@Get('profile')
|
||||
@UseGuards(AuthGuard)
|
||||
async getProfile(@Request() req) {
|
||||
return this.authService.getProfile(req.user.id);
|
||||
}
|
||||
|
||||
@Post('change-password')
|
||||
@UseGuards(AuthGuard)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async changePassword(@Request() req, @Body() changePasswordDto: ChangePasswordDto) {
|
||||
return this.authService.changePassword(
|
||||
req.user.id,
|
||||
changePasswordDto.currentPassword,
|
||||
changePasswordDto.newPassword,
|
||||
);
|
||||
}
|
||||
|
||||
@Put('profile')
|
||||
@UseGuards(AuthGuard)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async updateProfile(@Request() req, @Body() updateProfileDto: UpdateProfileDto) {
|
||||
return this.authService.updateProfile(req.user.id, updateProfileDto.name, updateProfileDto.email);
|
||||
}
|
||||
}
|
||||
43
src/auth/auth.guard.ts
Normal file
43
src/auth/auth.guard.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { AuthUser } from '../types';
|
||||
|
||||
@Injectable()
|
||||
export class AuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private jwtService: JwtService,
|
||||
private dbService: DatabaseService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const authHeader = request.headers['authorization'];
|
||||
const token = authHeader && authHeader.split(' ')[1];
|
||||
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('访问令牌缺失');
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = this.jwtService.verify(token) as { userId: number; username: string; role: string };
|
||||
|
||||
const user = await this.dbService.get<AuthUser>(
|
||||
'SELECT id, username, name, role FROM users WHERE id = ?',
|
||||
[decoded.userId]
|
||||
);
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('用户不存在');
|
||||
}
|
||||
|
||||
request.user = user;
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error.name === 'TokenExpiredError') {
|
||||
throw new UnauthorizedException('令牌已过期');
|
||||
}
|
||||
throw new UnauthorizedException('无效的令牌');
|
||||
}
|
||||
}
|
||||
}
|
||||
25
src/auth/auth.module.ts
Normal file
25
src/auth/auth.module.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { Module, Global } from '@nestjs/common';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { AuthService } from './auth.service';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthGuard } from './auth.guard';
|
||||
import { AdminGuard } from './admin.guard';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [
|
||||
JwtModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
useFactory: async (configService: ConfigService) => ({
|
||||
secret: configService.get<string>('JWT_SECRET'),
|
||||
signOptions: { expiresIn: '24h' },
|
||||
}),
|
||||
inject: [ConfigService],
|
||||
}),
|
||||
],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, AuthGuard, AdminGuard],
|
||||
exports: [AuthGuard, AdminGuard, JwtModule],
|
||||
})
|
||||
export class AuthModule {}
|
||||
112
src/auth/auth.service.ts
Normal file
112
src/auth/auth.service.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { User, AuthUser } from '../types';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private dbService: DatabaseService,
|
||||
private jwtService: JwtService,
|
||||
) {}
|
||||
|
||||
async validateUser(username: string, password: string) {
|
||||
const user = await this.dbService.get<User>('SELECT * FROM users WHERE username = ?', [username]);
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('用户名或密码错误');
|
||||
}
|
||||
|
||||
const isValidPassword = await bcrypt.compare(password, user.password);
|
||||
|
||||
if (!isValidPassword) {
|
||||
throw new UnauthorizedException('用户名或密码错误');
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
async login(user: User) {
|
||||
const payload = { userId: user.id, username: user.username, role: user.role };
|
||||
const token = this.jwtService.sign(payload);
|
||||
|
||||
return {
|
||||
accessToken: token,
|
||||
user: {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
createdAt: user.created_at,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async getProfile(userId: number) {
|
||||
const user = await this.dbService.get<User>(
|
||||
'SELECT id, username, name, email, role, created_at FROM users WHERE id = ?',
|
||||
[userId],
|
||||
);
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('用户不存在');
|
||||
}
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
createdAt: user.created_at,
|
||||
};
|
||||
}
|
||||
|
||||
async changePassword(userId: number, currentPassword: string, newPassword: string) {
|
||||
const user = await this.dbService.get<Pick<User, 'password'>>('SELECT password FROM users WHERE id = ?', [
|
||||
userId,
|
||||
]);
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('用户不存在');
|
||||
}
|
||||
|
||||
const isValidPassword = await bcrypt.compare(currentPassword, user.password);
|
||||
|
||||
if (!isValidPassword) {
|
||||
throw new UnauthorizedException('当前密码错误');
|
||||
}
|
||||
|
||||
const hashedPassword = await bcrypt.hash(newPassword, 10);
|
||||
|
||||
await this.dbService.run('UPDATE users SET password = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', [
|
||||
hashedPassword,
|
||||
userId,
|
||||
]);
|
||||
|
||||
return { message: '密码修改成功' };
|
||||
}
|
||||
|
||||
async updateProfile(userId: number, name: string, email: string | null) {
|
||||
await this.dbService.run(
|
||||
'UPDATE users SET name = ?, email = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
|
||||
[name, email, userId],
|
||||
);
|
||||
|
||||
const updatedUser = await this.dbService.get<User>(
|
||||
'SELECT id, username, name, email, role, created_at FROM users WHERE id = ?',
|
||||
[userId],
|
||||
);
|
||||
|
||||
return {
|
||||
id: updatedUser!.id,
|
||||
username: updatedUser!.username,
|
||||
name: updatedUser!.name,
|
||||
email: updatedUser!.email,
|
||||
role: updatedUser!.role,
|
||||
createdAt: updatedUser!.created_at,
|
||||
};
|
||||
}
|
||||
}
|
||||
31
src/auth/dto/index.ts
Normal file
31
src/auth/dto/index.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { IsString, IsNotEmpty, MinLength, IsEmail, IsOptional } from 'class-validator';
|
||||
|
||||
export class LoginDto {
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: '用户名不能为空' })
|
||||
username: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: '密码不能为空' })
|
||||
password: string;
|
||||
}
|
||||
|
||||
export class ChangePasswordDto {
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: '当前密码不能为空' })
|
||||
currentPassword: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(6, { message: '新密码长度至少为6位' })
|
||||
newPassword: string;
|
||||
}
|
||||
|
||||
export class UpdateProfileDto {
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: '姓名不能为空' })
|
||||
name: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEmail({}, { message: '邮箱格式不正确' })
|
||||
email?: string;
|
||||
}
|
||||
68
src/companies/companies.controller.ts
Normal file
68
src/companies/companies.controller.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { Controller, Get, Post, Patch, Delete, Body, Param, Query, UseGuards, Req, HttpCode, HttpStatus } from '@nestjs/common';
|
||||
import { Request } from 'express';
|
||||
import { CompaniesService } from './companies.service';
|
||||
import { AuthGuard } from '../auth/auth.guard';
|
||||
import { AdminGuard } from '../auth/admin.guard';
|
||||
|
||||
@Controller('companies')
|
||||
export class CompaniesController {
|
||||
constructor(private readonly companiesService: CompaniesService) {}
|
||||
|
||||
@Get()
|
||||
@UseGuards(AuthGuard, AdminGuard)
|
||||
async findAll(
|
||||
@Query('page') page: string = '1',
|
||||
@Query('limit') limit: string = '20',
|
||||
@Query('search') search: string = '',
|
||||
) {
|
||||
return this.companiesService.findAll(parseInt(page), parseInt(limit), search);
|
||||
}
|
||||
|
||||
@Get('stats/overview')
|
||||
@UseGuards(AuthGuard, AdminGuard)
|
||||
async getStats() {
|
||||
return this.companiesService.getStats();
|
||||
}
|
||||
|
||||
@Get(':companyName')
|
||||
@UseGuards(AuthGuard, AdminGuard)
|
||||
async findOne(
|
||||
@Param('companyName') companyName: string,
|
||||
@Query('page') page: string = '1',
|
||||
@Query('limit') limit: string = '20',
|
||||
) {
|
||||
return this.companiesService.findOne(decodeURIComponent(companyName), parseInt(page), parseInt(limit));
|
||||
}
|
||||
|
||||
@Patch(':companyName')
|
||||
@UseGuards(AuthGuard, AdminGuard)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async update(
|
||||
@Param('companyName') companyName: string,
|
||||
@Body('newCompanyName') newCompanyName: string,
|
||||
) {
|
||||
return this.companiesService.update(decodeURIComponent(companyName), newCompanyName);
|
||||
}
|
||||
|
||||
@Delete(':companyName')
|
||||
@UseGuards(AuthGuard, AdminGuard)
|
||||
async delete(@Param('companyName') companyName: string) {
|
||||
return this.companiesService.delete(decodeURIComponent(companyName));
|
||||
}
|
||||
|
||||
@Delete(':companyName/serials/:serialNumber')
|
||||
@UseGuards(AuthGuard, AdminGuard)
|
||||
async deleteSerial(
|
||||
@Param('companyName') companyName: string,
|
||||
@Param('serialNumber') serialNumber: string,
|
||||
) {
|
||||
return this.companiesService.deleteSerial(decodeURIComponent(companyName), serialNumber);
|
||||
}
|
||||
|
||||
@Post(':companyName/revoke')
|
||||
@UseGuards(AuthGuard, AdminGuard)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async revoke(@Param('companyName') companyName: string) {
|
||||
return this.companiesService.revoke(decodeURIComponent(companyName));
|
||||
}
|
||||
}
|
||||
9
src/companies/companies.module.ts
Normal file
9
src/companies/companies.module.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CompaniesService } from './companies.service';
|
||||
import { CompaniesController } from './companies.controller';
|
||||
|
||||
@Module({
|
||||
controllers: [CompaniesController],
|
||||
providers: [CompaniesService],
|
||||
})
|
||||
export class CompaniesModule {}
|
||||
313
src/companies/companies.service.ts
Normal file
313
src/companies/companies.service.ts
Normal file
@@ -0,0 +1,313 @@
|
||||
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 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[] = [];
|
||||
|
||||
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 total = countResult?.total || 0;
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
|
||||
return {
|
||||
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'
|
||||
})),
|
||||
pagination: {
|
||||
page: parseInt(page.toString()),
|
||||
limit: parseInt(limit.toString()),
|
||||
total,
|
||||
totalPages
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async findOne(companyName: string, page: number, limit: number) {
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const companyInfo = await this.dbService.get('SELECT * FROM companies WHERE company_name = ?', [companyName]);
|
||||
|
||||
if (!companyInfo) {
|
||||
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 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 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]);
|
||||
|
||||
return {
|
||||
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
|
||||
})),
|
||||
monthlyStats: stats.map(stat => ({
|
||||
month: stat.month,
|
||||
count: stat.count
|
||||
}))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async update(companyName: string, newCompanyName: string) {
|
||||
const existingCompany = await this.dbService.get(
|
||||
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
||||
[companyName]
|
||||
);
|
||||
|
||||
if (!existingCompany || (existingCompany as any).count === 0) {
|
||||
throw new Error('企业不存在');
|
||||
}
|
||||
|
||||
const duplicateCompany = await this.dbService.get(
|
||||
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
||||
[newCompanyName]
|
||||
);
|
||||
|
||||
if (duplicateCompany && (duplicateCompany as any).count > 0) {
|
||||
throw new Error('企业名称已存在');
|
||||
}
|
||||
|
||||
this.dbService.run(
|
||||
'UPDATE serials SET company_name = ?, updated_at = CURRENT_TIMESTAMP WHERE company_name = ?',
|
||||
[newCompanyName, companyName]
|
||||
);
|
||||
|
||||
return {
|
||||
message: '企业名称更新成功',
|
||||
data: {
|
||||
oldCompanyName: companyName,
|
||||
newCompanyName
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async delete(companyName: string) {
|
||||
const existingCompany = await this.dbService.get(
|
||||
'SELECT * FROM companies WHERE company_name = ?',
|
||||
[companyName]
|
||||
);
|
||||
|
||||
if (!existingCompany) {
|
||||
throw new Error('企业不存在');
|
||||
}
|
||||
|
||||
this.dbService.run('BEGIN TRANSACTION');
|
||||
|
||||
try {
|
||||
const serialDeleteResult = this.dbService.run(
|
||||
'DELETE FROM serials WHERE company_name = ?',
|
||||
[companyName]
|
||||
);
|
||||
|
||||
const companyDeleteResult = this.dbService.run(
|
||||
'DELETE FROM companies WHERE company_name = ?',
|
||||
[companyName]
|
||||
);
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
async deleteSerial(companyName: string, serialNumber: string) {
|
||||
const serial = await this.dbService.get(
|
||||
'SELECT * FROM serials WHERE serial_number = ? AND company_name = ?',
|
||||
[serialNumber.toUpperCase(), companyName]
|
||||
);
|
||||
|
||||
if (!serial) {
|
||||
throw new Error('序列号不存在或不属于该企业');
|
||||
}
|
||||
|
||||
await this.dbService.run(
|
||||
'DELETE FROM serials WHERE serial_number = ? AND company_name = ?',
|
||||
[serialNumber.toUpperCase(), companyName]
|
||||
);
|
||||
|
||||
return {
|
||||
message: '序列号已成功删除',
|
||||
data: {
|
||||
serialNumber: serialNumber.toUpperCase(),
|
||||
companyName
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async revoke(companyName: string) {
|
||||
const existingCompany = await this.dbService.get(
|
||||
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
||||
[companyName]
|
||||
);
|
||||
|
||||
if (!existingCompany || (existingCompany as any).count === 0) {
|
||||
throw new Error('企业不存在');
|
||||
}
|
||||
|
||||
await this.dbService.run(
|
||||
'UPDATE serials SET is_active = 0, updated_at = CURRENT_TIMESTAMP WHERE company_name = ?',
|
||||
[companyName]
|
||||
);
|
||||
|
||||
return {
|
||||
message: '企业已吊销,所有序列号已失效',
|
||||
data: {
|
||||
companyName: companyName
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async getStats() {
|
||||
const companyCount = await this.dbService.get<{ count: number }>('SELECT COUNT(*) as count FROM companies');
|
||||
const serialCount = await this.dbService.get<{ count: number }>('SELECT COUNT(*) as count FROM serials');
|
||||
const activeCount = await this.dbService.get<{ count: number }>(`
|
||||
SELECT COUNT(*) as count FROM serials
|
||||
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 }>(`
|
||||
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 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 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
|
||||
`);
|
||||
|
||||
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
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
message: '获取统计数据成功',
|
||||
data: {
|
||||
overview: {
|
||||
totalCompanies: companyCount?.count || 0,
|
||||
totalSerials: serialCount?.count || 0,
|
||||
activeSerials: activeCount?.count || 0,
|
||||
inactiveSerials: (serialCount?.count || 0) - (activeCount?.count || 0)
|
||||
},
|
||||
monthlyStats: finalMonthlyStats.map(stat => ({
|
||||
month: stat.month,
|
||||
company_count: stat.company_count,
|
||||
serial_count: stat.serial_count
|
||||
})),
|
||||
recentCompanies: recentCompanies.map(c => ({
|
||||
companyName: c.company_name,
|
||||
lastCreated: c.last_created,
|
||||
status: c.is_active ? 'active' : 'disabled'
|
||||
})),
|
||||
recentSerials: recentSerials.map(s => ({
|
||||
serialNumber: s.serial_number,
|
||||
companyName: s.company_name,
|
||||
isActive: !!s.is_active,
|
||||
createdAt: s.created_at
|
||||
}))
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
9
src/database/database.module.ts
Normal file
9
src/database/database.module.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Module, Global } from '@nestjs/common';
|
||||
import { DatabaseService } from './database.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [DatabaseService],
|
||||
exports: [DatabaseService],
|
||||
})
|
||||
export class DatabaseModule {}
|
||||
59
src/database/database.service.ts
Normal file
59
src/database/database.service.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import Database from 'better-sqlite3';
|
||||
import * as path from 'path';
|
||||
import * as fs from 'fs';
|
||||
|
||||
@Injectable()
|
||||
export class DatabaseService implements OnModuleInit, OnModuleDestroy {
|
||||
private db: Database.Database;
|
||||
private dbPath: string;
|
||||
|
||||
constructor(private configService: ConfigService) {}
|
||||
|
||||
onModuleInit() {
|
||||
this.dbPath = this.configService.get<string>('DB_PATH', path.join(process.cwd(), 'data/database.sqlite'));
|
||||
const dbDir = path.dirname(this.dbPath);
|
||||
|
||||
if (!fs.existsSync(dbDir)) {
|
||||
fs.mkdirSync(dbDir, { recursive: true });
|
||||
}
|
||||
|
||||
this.db = new Database(this.dbPath, { verbose: console.log });
|
||||
}
|
||||
|
||||
onModuleDestroy() {
|
||||
this.db.close();
|
||||
}
|
||||
|
||||
get<T = any>(sql: string, params: any[] = []): T | undefined {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
return stmt.get(params) as T | undefined;
|
||||
} catch (error) {
|
||||
console.error('数据库查询错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
all<T = any>(sql: string, params: any[] = []): T[] {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
return stmt.all(params) as T[];
|
||||
} catch (error) {
|
||||
console.error('数据库查询错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
run(sql: string, params: any[] = []): { id: number; changes: number } {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
const result = stmt.run(params);
|
||||
return { id: result.lastInsertRowid as number, changes: result.changes };
|
||||
} catch (error) {
|
||||
console.error('数据库操作错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
56
src/database/database.ts
Normal file
56
src/database/database.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
class DatabaseWrapper {
|
||||
private db: Database.Database;
|
||||
private dbPath: string;
|
||||
|
||||
constructor() {
|
||||
this.dbPath = process.env.DB_PATH || path.join(process.cwd(), 'data/database.sqlite');
|
||||
const dbDir = path.dirname(this.dbPath);
|
||||
|
||||
if (!fs.existsSync(dbDir)) {
|
||||
fs.mkdirSync(dbDir, { recursive: true });
|
||||
}
|
||||
|
||||
this.db = new Database(this.dbPath, { verbose: console.log });
|
||||
}
|
||||
|
||||
get<T = any>(sql: string, params: any[] = []): T | undefined {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
return stmt.get(params) as T | undefined;
|
||||
} catch (error) {
|
||||
console.error('数据库查询错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
all<T = any>(sql: string, params: any[] = []): T[] {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
return stmt.all(params) as T[];
|
||||
} catch (error) {
|
||||
console.error('数据库查询错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
run(sql: string, params: any[] = []): { id: number; changes: number } {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
const result = stmt.run(params);
|
||||
return { id: result.lastInsertRowid as number, changes: result.changes };
|
||||
} catch (error) {
|
||||
console.error('数据库操作错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
}
|
||||
}
|
||||
|
||||
export default new DatabaseWrapper();
|
||||
9
src/health.controller.ts
Normal file
9
src/health.controller.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
|
||||
@Controller('health')
|
||||
export class HealthController {
|
||||
@Get()
|
||||
check() {
|
||||
return { status: 'ok', message: '服务器运行正常' };
|
||||
}
|
||||
}
|
||||
34
src/main.ts
Normal file
34
src/main.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { join } from 'path';
|
||||
import { NestExpressApplication } from '@nestjs/platform-express';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create<NestExpressApplication>(AppModule);
|
||||
const configService = app.get(ConfigService);
|
||||
|
||||
app.enableCors();
|
||||
app.useGlobalPipes(new ValidationPipe({ transform: true }));
|
||||
app.setGlobalPrefix('api');
|
||||
|
||||
// 静态文件服务
|
||||
const frontendPath = join(__dirname, '..', 'frontend');
|
||||
const distPath = join(frontendPath, 'dist');
|
||||
const publicPath = join(frontendPath, 'public');
|
||||
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
app.useStaticAssets(distPath);
|
||||
} else {
|
||||
app.useStaticAssets(publicPath);
|
||||
}
|
||||
|
||||
const port = configService.get<number>('PORT', 3000);
|
||||
await app.listen(port);
|
||||
|
||||
console.log(`服务器运行在 http://localhost:${port}`);
|
||||
console.log(`API文档: http://localhost:${port}/api/health`);
|
||||
console.log(`环境: ${process.env.NODE_ENV || 'development'}`);
|
||||
}
|
||||
bootstrap();
|
||||
63
src/serials/dto/index.ts
Normal file
63
src/serials/dto/index.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { IsString, IsNotEmpty, IsNumber, IsOptional, IsBoolean, Min, Max } from 'class-validator';
|
||||
|
||||
export class GenerateSerialDto {
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: '企业名称不能为空' })
|
||||
companyName: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(1)
|
||||
@Max(100)
|
||||
quantity?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
validDays?: number;
|
||||
}
|
||||
|
||||
export class GenerateWithPrefixDto extends GenerateSerialDto {
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: '自定义前缀不能为空' })
|
||||
serialPrefix: string;
|
||||
}
|
||||
|
||||
export class QRCodeDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
baseUrl?: string;
|
||||
}
|
||||
|
||||
export class UpdateSerialDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
companyName?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
validUntil?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
isActive?: boolean;
|
||||
}
|
||||
|
||||
export interface Serial {
|
||||
id: number;
|
||||
serial_number: string;
|
||||
company_name: string;
|
||||
valid_until: string | null;
|
||||
is_active: boolean;
|
||||
created_by: number | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface SerialListItem {
|
||||
serialNumber: string;
|
||||
companyName: string;
|
||||
validUntil: string | null;
|
||||
isActive: boolean;
|
||||
createdAt: string;
|
||||
createdBy?: string;
|
||||
}
|
||||
97
src/serials/serials.controller.ts
Normal file
97
src/serials/serials.controller.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import { Controller, Get, Post, Patch, Body, Param, Query, UseGuards, Req, HttpCode, HttpStatus } from '@nestjs/common';
|
||||
import { Request } from 'express';
|
||||
import { SerialsService } from './serials.service';
|
||||
import { AuthGuard } from '../auth/auth.guard';
|
||||
import { AdminGuard } from '../auth/admin.guard';
|
||||
import { GenerateSerialDto, GenerateWithPrefixDto, QRCodeDto, UpdateSerialDto } from './dto';
|
||||
|
||||
@Controller('serials')
|
||||
export class SerialsController {
|
||||
constructor(private readonly serialsService: SerialsService) {}
|
||||
|
||||
@Post('generate')
|
||||
@UseGuards(AuthGuard, AdminGuard)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async generate(@Body() generateDto: GenerateSerialDto, @Req() req: Request) {
|
||||
const serials = await this.serialsService.generate(
|
||||
generateDto.companyName,
|
||||
generateDto.quantity || 1,
|
||||
generateDto.validDays || 365,
|
||||
(req as any).user.id,
|
||||
);
|
||||
return {
|
||||
message: `成功生成${serials.length}个序列号`,
|
||||
serials,
|
||||
};
|
||||
}
|
||||
|
||||
@Post('generate-with-prefix')
|
||||
@UseGuards(AuthGuard, AdminGuard)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async generateWithPrefix(@Body() generateDto: GenerateWithPrefixDto, @Req() req: Request) {
|
||||
const serials = await this.serialsService.generate(
|
||||
generateDto.companyName,
|
||||
generateDto.quantity || 1,
|
||||
generateDto.validDays || 365,
|
||||
(req as any).user.id,
|
||||
generateDto.serialPrefix,
|
||||
);
|
||||
return {
|
||||
message: `成功生成${serials.length}个序列号`,
|
||||
serials,
|
||||
};
|
||||
}
|
||||
|
||||
@Post(':serialNumber/qrcode')
|
||||
@UseGuards(AuthGuard)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async generateQRCode(
|
||||
@Param('serialNumber') serialNumber: string,
|
||||
@Body() qrCodeDto: QRCodeDto,
|
||||
@Req() req: Request,
|
||||
) {
|
||||
return this.serialsService.generateQRCode(
|
||||
serialNumber,
|
||||
qrCodeDto.baseUrl,
|
||||
req.get('host'),
|
||||
req.protocol,
|
||||
);
|
||||
}
|
||||
|
||||
@Get(':serialNumber/query')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async query(@Param('serialNumber') serialNumber: string) {
|
||||
return this.serialsService.query(serialNumber);
|
||||
}
|
||||
|
||||
@Get()
|
||||
@UseGuards(AuthGuard)
|
||||
async findAll(
|
||||
@Query('page') page: string = '1',
|
||||
@Query('limit') limit: string = '20',
|
||||
@Query('search') search: string = '',
|
||||
) {
|
||||
return this.serialsService.findAll(parseInt(page), parseInt(limit), search);
|
||||
}
|
||||
|
||||
@Patch(':serialNumber')
|
||||
@UseGuards(AuthGuard, AdminGuard)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async update(
|
||||
@Param('serialNumber') serialNumber: string,
|
||||
@Body() updateDto: UpdateSerialDto,
|
||||
) {
|
||||
return this.serialsService.update(serialNumber, {
|
||||
companyName: updateDto.companyName,
|
||||
validUntil: updateDto.validUntil,
|
||||
isActive: updateDto.isActive,
|
||||
});
|
||||
}
|
||||
|
||||
@Post(':serialNumber/revoke')
|
||||
@UseGuards(AuthGuard, AdminGuard)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async revoke(@Param('serialNumber') serialNumber: string) {
|
||||
return this.serialsService.revoke(serialNumber);
|
||||
}
|
||||
}
|
||||
9
src/serials/serials.module.ts
Normal file
9
src/serials/serials.module.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { SerialsService } from './serials.service';
|
||||
import { SerialsController } from './serials.controller';
|
||||
|
||||
@Module({
|
||||
controllers: [SerialsController],
|
||||
providers: [SerialsService],
|
||||
})
|
||||
export class SerialsModule {}
|
||||
235
src/serials/serials.service.ts
Normal file
235
src/serials/serials.service.ts
Normal file
@@ -0,0 +1,235 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import * as QRCode from 'qrcode';
|
||||
import { Serial, SerialListItem } from './dto';
|
||||
|
||||
@Injectable()
|
||||
export class SerialsService {
|
||||
constructor(private dbService: DatabaseService) {}
|
||||
|
||||
async generate(companyName: string, quantity: number, validDays: number, userId: number, serialPrefix?: string): Promise<SerialListItem[]> {
|
||||
const validUntil = new Date();
|
||||
validUntil.setDate(validUntil.getDate() + validDays);
|
||||
|
||||
const existingCompany = await this.dbService.get('SELECT * FROM companies WHERE company_name = ?', [companyName]);
|
||||
if (!existingCompany) {
|
||||
await this.dbService.run('INSERT INTO companies (company_name, is_active) VALUES (?, 1)', [companyName]);
|
||||
}
|
||||
|
||||
const serials: SerialListItem[] = [];
|
||||
const prefix = serialPrefix ? serialPrefix.toUpperCase().replace(/[^A-Z0-9]/g, '') : 'BF' + new Date().getFullYear().toString().substr(2);
|
||||
|
||||
for (let i = 0; i < quantity; i++) {
|
||||
const randomPart = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
|
||||
const serialNumber = `${prefix}${randomPart}`;
|
||||
|
||||
await this.dbService.run(
|
||||
'INSERT INTO serials (serial_number, company_name, valid_until, created_by) VALUES (?, ?, ?, ?)',
|
||||
[serialNumber, companyName, validUntil.toISOString().slice(0, 19).replace('T', ' '), userId]
|
||||
);
|
||||
|
||||
serials.push({
|
||||
serialNumber,
|
||||
companyName,
|
||||
validUntil: validUntil.toISOString(),
|
||||
isActive: true,
|
||||
createdAt: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
|
||||
return serials;
|
||||
}
|
||||
|
||||
async generateQRCode(serialNumber: string, baseUrl?: string, requestHost?: string, protocol?: string) {
|
||||
const serial = await this.dbService.get<{ serial_number: string; company_name: string; is_active: number; valid_until: string | null }>(
|
||||
'SELECT s.*, u.name as created_by_name FROM serials s LEFT JOIN users u ON s.created_by = u.id WHERE s.serial_number = ?',
|
||||
[serialNumber.toUpperCase()]
|
||||
);
|
||||
|
||||
if (!serial) {
|
||||
throw new Error('序列号不存在');
|
||||
}
|
||||
|
||||
if (!serial.is_active) {
|
||||
throw new Error('序列号已被禁用');
|
||||
}
|
||||
|
||||
if (serial.valid_until && new Date(serial.valid_until) < new Date()) {
|
||||
throw new Error('序列号已过期');
|
||||
}
|
||||
|
||||
if (!baseUrl) {
|
||||
baseUrl = `${protocol}://${requestHost}/query.html`;
|
||||
}
|
||||
|
||||
const queryUrl = baseUrl.includes('?')
|
||||
? `${baseUrl}&serial=${serial.serial_number}`
|
||||
: `${baseUrl}?serial=${serial.serial_number}`;
|
||||
|
||||
const qrCodeData = await QRCode.toDataURL(queryUrl, {
|
||||
width: 200,
|
||||
color: {
|
||||
dark: '#165DFF',
|
||||
light: '#ffffff'
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
message: '二维码生成成功',
|
||||
qrCodeData,
|
||||
queryUrl,
|
||||
serialNumber: serial.serial_number,
|
||||
companyName: serial.company_name,
|
||||
validUntil: serial.valid_until
|
||||
};
|
||||
}
|
||||
|
||||
async query(serialNumber: string) {
|
||||
const serial = await this.dbService.get<{ serial_number: string; company_name: string; valid_until: string | null; is_active: number; created_at: string; created_by_name: string }>(
|
||||
'SELECT s.*, u.name as created_by_name FROM serials s LEFT JOIN users u ON s.created_by = u.id WHERE s.serial_number = ?',
|
||||
[serialNumber.toUpperCase()]
|
||||
);
|
||||
|
||||
if (!serial) {
|
||||
throw new Error('序列号不存在');
|
||||
}
|
||||
|
||||
if (serial.valid_until && new Date(serial.valid_until) < new Date()) {
|
||||
throw new Error('序列号已过期');
|
||||
}
|
||||
|
||||
return {
|
||||
message: '查询成功',
|
||||
serial: {
|
||||
serialNumber: serial.serial_number,
|
||||
companyName: serial.company_name,
|
||||
validUntil: serial.valid_until,
|
||||
status: serial.is_active ? 'active' : 'disabled',
|
||||
isActive: !!serial.is_active,
|
||||
createdAt: serial.created_at,
|
||||
createdBy: serial.created_by_name
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async findAll(page: number, limit: number, search: string) {
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
let query = 'SELECT s.*, u.name as created_by_name FROM serials s LEFT JOIN users u ON s.created_by = u.id';
|
||||
let countQuery = 'SELECT COUNT(*) as total FROM serials s';
|
||||
let params: any[] = [];
|
||||
|
||||
if (search) {
|
||||
query += ' WHERE s.serial_number LIKE ? OR s.company_name LIKE ?';
|
||||
countQuery += ' WHERE s.serial_number LIKE ? OR s.company_name LIKE ?';
|
||||
const searchParam = `%${search}%`;
|
||||
params.push(searchParam, searchParam);
|
||||
}
|
||||
|
||||
query += ' ORDER BY s.created_at DESC LIMIT ? OFFSET ?';
|
||||
params.push(parseInt(limit.toString()), parseInt(offset.toString()));
|
||||
|
||||
const [serials, countResult] = await Promise.all([
|
||||
this.dbService.all(query, params),
|
||||
this.dbService.get<{ total: number }>(countQuery, params.slice(0, -2))
|
||||
]);
|
||||
|
||||
const total = countResult?.total || 0;
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
|
||||
return {
|
||||
message: '获取序列号列表成功',
|
||||
data: serials.map((s: any) => ({
|
||||
serialNumber: s.serial_number,
|
||||
companyName: s.company_name,
|
||||
validUntil: s.valid_until,
|
||||
isActive: s.is_active,
|
||||
createdAt: s.created_at,
|
||||
createdBy: s.created_by_name
|
||||
})),
|
||||
pagination: {
|
||||
page: parseInt(page.toString()),
|
||||
limit: parseInt(limit.toString()),
|
||||
total,
|
||||
totalPages
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async update(serialNumber: string, updateData: { companyName?: string; validUntil?: string; isActive?: boolean }) {
|
||||
const existingSerial = await this.dbService.get<{ is_active: number }>('SELECT * FROM serials WHERE serial_number = ?', [serialNumber.toUpperCase()]);
|
||||
|
||||
if (!existingSerial) {
|
||||
throw new Error('序列号不存在');
|
||||
}
|
||||
|
||||
const updateFields: string[] = [];
|
||||
const params: any[] = [];
|
||||
|
||||
if (updateData.companyName !== undefined) {
|
||||
updateFields.push('company_name = ?');
|
||||
params.push(updateData.companyName);
|
||||
}
|
||||
|
||||
if (updateData.validUntil !== undefined) {
|
||||
updateFields.push('valid_until = ?');
|
||||
params.push(updateData.validUntil);
|
||||
}
|
||||
|
||||
if (updateData.isActive !== undefined) {
|
||||
updateFields.push('is_active = ?');
|
||||
params.push(updateData.isActive ? 1 : 0);
|
||||
}
|
||||
|
||||
if (updateFields.length === 0) {
|
||||
throw new Error('没有提供更新字段');
|
||||
}
|
||||
|
||||
updateFields.push('updated_at = CURRENT_TIMESTAMP');
|
||||
params.push(serialNumber.toUpperCase());
|
||||
|
||||
await this.dbService.run(
|
||||
`UPDATE serials SET ${updateFields.join(', ')} WHERE serial_number = ?`,
|
||||
params
|
||||
);
|
||||
|
||||
const updatedSerial = await this.dbService.get('SELECT s.*, u.name as created_by_name FROM serials s LEFT JOIN users u ON s.created_by = u.id WHERE s.serial_number = ?', [serialNumber.toUpperCase()]);
|
||||
|
||||
return {
|
||||
message: '序列号更新成功',
|
||||
serial: {
|
||||
serialNumber: (updatedSerial as any).serial_number,
|
||||
companyName: (updatedSerial as any).company_name,
|
||||
validUntil: (updatedSerial as any).valid_until,
|
||||
isActive: (updatedSerial as any).is_active,
|
||||
createdAt: (updatedSerial as any).created_at,
|
||||
updatedAt: (updatedSerial as any).updated_at,
|
||||
createdBy: (updatedSerial as any).created_by_name
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async revoke(serialNumber: string) {
|
||||
const existingSerial = await this.dbService.get<{ is_active: number }>('SELECT * FROM serials WHERE serial_number = ?', [serialNumber.toUpperCase()]);
|
||||
|
||||
if (!existingSerial) {
|
||||
throw new Error('序列号不存在');
|
||||
}
|
||||
|
||||
if (!existingSerial.is_active) {
|
||||
throw new Error('序列号已被吊销');
|
||||
}
|
||||
|
||||
await this.dbService.run(
|
||||
'UPDATE serials SET is_active = 0, updated_at = CURRENT_TIMESTAMP WHERE serial_number = ?',
|
||||
[serialNumber.toUpperCase()]
|
||||
);
|
||||
|
||||
return {
|
||||
message: '序列号已吊销',
|
||||
data: {
|
||||
serialNumber: serialNumber.toUpperCase()
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
160
src/types/index.d.ts
vendored
Normal file
160
src/types/index.d.ts
vendored
Normal file
@@ -0,0 +1,160 @@
|
||||
export interface User {
|
||||
id: number;
|
||||
username: string;
|
||||
password: string;
|
||||
name: string;
|
||||
email: string | null;
|
||||
role: 'admin' | 'user';
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface Company {
|
||||
id: number;
|
||||
company_name: string;
|
||||
is_active: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface Serial {
|
||||
id: number;
|
||||
serial_number: string;
|
||||
company_name: string;
|
||||
valid_until: string | null;
|
||||
is_active: boolean;
|
||||
created_by: number | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
created_by_name?: string;
|
||||
}
|
||||
|
||||
export interface AuthUser {
|
||||
id: number;
|
||||
username: string;
|
||||
name: string;
|
||||
role: 'admin' | 'user';
|
||||
}
|
||||
|
||||
export interface JWTPayload {
|
||||
userId: number;
|
||||
username: string;
|
||||
role: 'admin' | 'user';
|
||||
}
|
||||
|
||||
export interface LoginRequest {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface ChangePasswordRequest {
|
||||
currentPassword: string;
|
||||
newPassword: string;
|
||||
}
|
||||
|
||||
export interface GenerateSerialRequest {
|
||||
companyName: string;
|
||||
quantity?: number;
|
||||
validDays?: number;
|
||||
}
|
||||
|
||||
export interface GenerateSerialWithPrefixRequest {
|
||||
companyName: string;
|
||||
quantity?: number;
|
||||
validDays?: number;
|
||||
serialPrefix: string;
|
||||
}
|
||||
|
||||
export interface QRCodeRequest {
|
||||
baseUrl?: string;
|
||||
}
|
||||
|
||||
export interface UpdateSerialRequest {
|
||||
companyName?: string;
|
||||
validUntil?: string;
|
||||
isActive?: boolean;
|
||||
}
|
||||
|
||||
export interface UpdateCompanyRequest {
|
||||
newCompanyName: string;
|
||||
}
|
||||
|
||||
export interface PaginationQuery {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
}
|
||||
|
||||
export interface PaginationResponse {
|
||||
page: number;
|
||||
limit: number;
|
||||
total: number;
|
||||
totalPages: number;
|
||||
}
|
||||
|
||||
export interface ApiResponse<T = any> {
|
||||
message: string;
|
||||
data?: T;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
accessToken: string;
|
||||
user: {
|
||||
id: number;
|
||||
username: string;
|
||||
name: string;
|
||||
email: string | null;
|
||||
role: 'admin' | 'user';
|
||||
};
|
||||
}
|
||||
|
||||
export interface SerialListItem {
|
||||
serialNumber: string;
|
||||
companyName: string;
|
||||
validUntil: string | null;
|
||||
isActive: boolean;
|
||||
createdAt: string;
|
||||
createdBy?: string;
|
||||
}
|
||||
|
||||
export interface CompanyListItem {
|
||||
companyName: string;
|
||||
firstCreated: string;
|
||||
lastCreated: string;
|
||||
serialCount: number;
|
||||
activeCount: number;
|
||||
status: 'active' | 'disabled';
|
||||
}
|
||||
|
||||
export interface CompanyDetail {
|
||||
companyName: string;
|
||||
serialCount: number;
|
||||
activeCount: number;
|
||||
disabledCount: number;
|
||||
expiredCount: number;
|
||||
firstCreated: string;
|
||||
lastCreated: string;
|
||||
status: 'active' | 'disabled';
|
||||
serials: SerialListItem[];
|
||||
monthlyStats: MonthlyStat[];
|
||||
}
|
||||
|
||||
export interface MonthlyStat {
|
||||
month: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface StatsOverview {
|
||||
totalCompanies: number;
|
||||
totalSerials: number;
|
||||
activeSerials: number;
|
||||
inactiveSerials: number;
|
||||
}
|
||||
|
||||
export interface StatsResponse {
|
||||
overview: StatsOverview;
|
||||
monthlyStats: Array<{ month: string; company_count: number; serial_count: number }>;
|
||||
recentCompanies: Array<{ companyName: string; lastCreated: string; status: 'active' | 'disabled' }>;
|
||||
recentSerials: Array<{ serialNumber: string; companyName: string; isActive: boolean; createdAt: string }>;
|
||||
}
|
||||
56
src/utils/database.ts
Normal file
56
src/utils/database.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
class DatabaseWrapper {
|
||||
private db: Database.Database;
|
||||
private dbPath: string;
|
||||
|
||||
constructor() {
|
||||
this.dbPath = process.env.DB_PATH || path.join(process.cwd(), 'data/database.sqlite');
|
||||
const dbDir = path.dirname(this.dbPath);
|
||||
|
||||
if (!fs.existsSync(dbDir)) {
|
||||
fs.mkdirSync(dbDir, { recursive: true });
|
||||
}
|
||||
|
||||
this.db = new Database(this.dbPath, { verbose: console.log });
|
||||
}
|
||||
|
||||
get<T = any>(sql: string, params: any[] = []): T | undefined {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
return stmt.get(params) as T | undefined;
|
||||
} catch (error) {
|
||||
console.error('数据库查询错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
all<T = any>(sql: string, params: any[] = []): T[] {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
return stmt.all(params) as T[];
|
||||
} catch (error) {
|
||||
console.error('数据库查询错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
run(sql: string, params: any[] = []): { id: number; changes: number } {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
const result = stmt.run(params);
|
||||
return { id: result.lastInsertRowid as number, changes: result.changes };
|
||||
} catch (error) {
|
||||
console.error('数据库操作错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
}
|
||||
}
|
||||
|
||||
export default new DatabaseWrapper();
|
||||
Reference in New Issue
Block a user