Compare commits
2 Commits
1eb8abb447
...
86e41b479d
| Author | SHA1 | Date | |
|---|---|---|---|
|
86e41b479d
|
|||
|
2dc6bf16ec
|
2
.gitignore
vendored
2
.gitignore
vendored
@@ -75,3 +75,5 @@ dist/
|
|||||||
|
|
||||||
# NestJS
|
# NestJS
|
||||||
.nest-cli.json
|
.nest-cli.json
|
||||||
|
|
||||||
|
/generated/prisma
|
||||||
|
|||||||
1
.npmrc
1
.npmrc
@@ -1,4 +1,3 @@
|
|||||||
only-built-dependencies[]=better-sqlite3
|
|
||||||
only-built-dependencies[]=esbuild
|
only-built-dependencies[]=esbuild
|
||||||
only-built-dependencies[]=@nestjs/core
|
only-built-dependencies[]=@nestjs/core
|
||||||
only-built-dependencies[]=unrs-resolver
|
only-built-dependencies[]=unrs-resolver
|
||||||
@@ -28,23 +28,24 @@
|
|||||||
"@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-libsql": "^7.3.0",
|
||||||
|
"@prisma/client": "^7.3.0",
|
||||||
"bcryptjs": "^3.0.3",
|
"bcryptjs": "^3.0.3",
|
||||||
"better-sqlite3": "^12.6.2",
|
|
||||||
"class-transformer": "^0.5.1",
|
"class-transformer": "^0.5.1",
|
||||||
"class-validator": "^0.14.3",
|
"class-validator": "^0.14.3",
|
||||||
"dotenv": "^17.2.3",
|
"dotenv": "^17.2.3",
|
||||||
"jsonwebtoken": "^9.0.2",
|
"jsonwebtoken": "^9.0.2",
|
||||||
"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"
|
||||||
},
|
},
|
||||||
"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/jsonwebtoken": "^9.0.10",
|
||||||
|
|||||||
916
pnpm-lock.yaml
generated
916
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,53 @@
|
|||||||
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 { PrismaLibSql } from "@prisma/adapter-libsql";
|
||||||
|
|
||||||
const dbPath = path.join(process.cwd(), 'data/database.sqlite');
|
const adapter = new PrismaLibSql({
|
||||||
const dbDir = path.dirname(dbPath);
|
url:
|
||||||
|
process.env.DATABASE_URL ||
|
||||||
|
"file:" + path.join(process.cwd(), "data/database.sqlite"),
|
||||||
|
});
|
||||||
|
|
||||||
if (!fs.existsSync(dbDir)) {
|
const prisma = new PrismaClient({
|
||||||
fs.mkdirSync(dbDir, { recursive: true });
|
log: ["query", "error", "warn"],
|
||||||
}
|
adapter,
|
||||||
|
});
|
||||||
const db = new Database(dbPath, { verbose: console.log });
|
|
||||||
|
|
||||||
const createTables = (): void => {
|
|
||||||
db.exec(`
|
|
||||||
CREATE TABLE IF NOT EXISTS users (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
username TEXT UNIQUE NOT NULL,
|
|
||||||
password TEXT NOT NULL,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
email TEXT,
|
|
||||||
role TEXT DEFAULT 'user',
|
|
||||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
||||||
)
|
|
||||||
`);
|
|
||||||
|
|
||||||
db.exec(`
|
|
||||||
CREATE TABLE IF NOT EXISTS companies (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
company_name TEXT UNIQUE NOT NULL,
|
|
||||||
is_active BOOLEAN BOOLEAN DEFAULT 1,
|
|
||||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
||||||
)
|
|
||||||
`);
|
|
||||||
|
|
||||||
db.exec(`
|
|
||||||
CREATE TABLE IF NOT EXISTS serials (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
serial_number TEXT UNIQUE NOT NULL,
|
|
||||||
company_name TEXT NOT NULL,
|
|
||||||
valid_until DATETIME,
|
|
||||||
is_active BOOLEAN DEFAULT 1,
|
|
||||||
created_by INTEGER,
|
|
||||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
FOREIGN KEY (created_by) REFERENCES users (id),
|
|
||||||
FOREIGN KEY (company_name) REFERENCES companies (company_name)
|
|
||||||
)
|
|
||||||
`);
|
|
||||||
|
|
||||||
db.exec('CREATE INDEX IF NOT EXISTS idx_company_name_companies ON companies (company_name)');
|
|
||||||
db.exec('CREATE INDEX IF NOT EXISTS idx_serial_number ON serials (serial_number)');
|
|
||||||
db.exec('CREATE INDEX IF NOT EXISTS idx_company_name_serials ON serials (company_name)');
|
|
||||||
db.exec('CREATE INDEX IF NOT EXISTS idx_created_by ON serials (created_by)');
|
|
||||||
|
|
||||||
console.log('数据库表创建完成');
|
|
||||||
};
|
|
||||||
|
|
||||||
const 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,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;
|
||||||
|
username: string;
|
||||||
|
role: string;
|
||||||
|
};
|
||||||
|
|
||||||
const user = await this.dbService.get<AuthUser>(
|
const prisma = this.dbService.getPrisma();
|
||||||
'SELECT id, username, name, role FROM users WHERE id = ?',
|
const user = await prisma.user.findUnique({
|
||||||
[decoded.userId]
|
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) {
|
||||||
|
throw new UnauthorizedException("用户不存在");
|
||||||
|
}
|
||||||
|
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
async changePassword(
|
||||||
|
userId: number,
|
||||||
|
currentPassword: string,
|
||||||
|
newPassword: string,
|
||||||
|
) {
|
||||||
|
const prisma = this.dbService.getPrisma();
|
||||||
|
const user = await prisma.user.findUnique({
|
||||||
|
where: { id: userId },
|
||||||
|
select: { password: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
throw new UnauthorizedException("用户不存在");
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValidPassword = await bcrypt.compare(
|
||||||
|
currentPassword,
|
||||||
|
user.password,
|
||||||
);
|
);
|
||||||
|
|
||||||
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) {
|
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,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 },
|
||||||
|
|
||||||
if (search) {
|
|
||||||
query += ' WHERE c.company_name LIKE ?';
|
|
||||||
countQuery += ' WHERE company_name LIKE ?';
|
|
||||||
params.push(`%${search}%`);
|
|
||||||
}
|
}
|
||||||
|
: undefined;
|
||||||
|
|
||||||
query += ' ORDER BY c.updated_at DESC LIMIT ? OFFSET ?';
|
const [companies, total] = await Promise.all([
|
||||||
params.push(parseInt(limit.toString()), parseInt(offset.toString()));
|
prisma.company.findMany({
|
||||||
|
where,
|
||||||
const [companies, countResult] = await Promise.all([
|
include: {
|
||||||
this.dbService.all(query, params),
|
serials: true,
|
||||||
this.dbService.get<{ total: number }>(countQuery, params.slice(0, -2))
|
},
|
||||||
|
orderBy: { updatedAt: "desc" },
|
||||||
|
skip: offset,
|
||||||
|
take: limit,
|
||||||
|
}),
|
||||||
|
prisma.company.count({ where }),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
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) {
|
|
||||||
this.dbService.run('ROLLBACK');
|
|
||||||
throw new Error('企业不存在');
|
|
||||||
}
|
|
||||||
|
|
||||||
this.dbService.run('COMMIT');
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: '企业已完全删除,所有相关序列号已删除',
|
message: "企业已完全删除,所有相关序列号已删除",
|
||||||
data: {
|
data: {
|
||||||
companyName: companyName,
|
companyName: companyName,
|
||||||
deletedSerialCount: serialDeleteResult.changes,
|
deletedSerialCount: deleteResult,
|
||||||
deletedCompanyCount: companyDeleteResult.changes
|
deletedCompanyCount: 1,
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
} 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 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();
|
const now = new Date();
|
||||||
|
|
||||||
|
const [companies, serials, recentCompanies, recentSerials] =
|
||||||
|
await Promise.all([
|
||||||
|
prisma.company.findMany(),
|
||||||
|
prisma.serial.findMany({
|
||||||
|
include: {
|
||||||
|
company: true,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
prisma.company.findMany({
|
||||||
|
orderBy: { updatedAt: "desc" },
|
||||||
|
take: 10,
|
||||||
|
}),
|
||||||
|
prisma.serial.findMany({
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
take: 10,
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const companyCount = companies.length;
|
||||||
|
const serialCount = serials.length;
|
||||||
|
const activeCount = serials.filter(
|
||||||
|
(s) => s.isActive && (!s.validUntil || s.validUntil > now),
|
||||||
|
).length;
|
||||||
|
const inactiveCount = serialCount - activeCount;
|
||||||
|
|
||||||
|
const monthlyStats: Array<{
|
||||||
|
month: string;
|
||||||
|
company_count: number;
|
||||||
|
serial_count: number;
|
||||||
|
}> = [];
|
||||||
|
const nowYear = now.getFullYear();
|
||||||
|
const nowMonth = now.getMonth();
|
||||||
|
|
||||||
for (let i = 11; i >= 0; i--) {
|
for (let i = 11; i >= 0; i--) {
|
||||||
const date = new Date(now.getFullYear(), now.getMonth() - i, 1);
|
const date = new Date(nowYear, nowMonth - i, 1);
|
||||||
const month = date.toISOString().substr(0, 7);
|
const monthStr = date.toISOString().slice(0, 7);
|
||||||
finalMonthlyStats.push({
|
const monthSerials = serials.filter((s) => {
|
||||||
month,
|
const createdAt = new Date(s.createdAt);
|
||||||
company_count: 0,
|
return (
|
||||||
serial_count: 0
|
createdAt.getFullYear() === date.getFullYear() &&
|
||||||
|
createdAt.getMonth() === date.getMonth()
|
||||||
|
);
|
||||||
|
});
|
||||||
|
const uniqueCompanies = new Set(monthSerials.map((s) => s.companyName));
|
||||||
|
|
||||||
|
if (monthSerials.length > 0) {
|
||||||
|
monthlyStats.push({
|
||||||
|
month: monthStr,
|
||||||
|
company_count: uniqueCompanies.size,
|
||||||
|
serial_count: monthSerials.length,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
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,34 @@
|
|||||||
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 { PrismaLibSql } from "@prisma/adapter-libsql";
|
||||||
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 adapter = new PrismaLibSql({
|
||||||
|
url:
|
||||||
|
process.env.DATABASE_URL ||
|
||||||
|
"file:" + path.join(process.cwd(), "data/database.sqlite"),
|
||||||
|
});
|
||||||
|
|
||||||
onModuleInit() {
|
this.prisma = new PrismaClient({
|
||||||
this.dbPath = this.configService.get<string>('DB_PATH', path.join(process.cwd(), 'data/database.sqlite'));
|
log: ["query", "error", "warn"],
|
||||||
const dbDir = path.dirname(this.dbPath);
|
adapter,
|
||||||
|
});
|
||||||
if (!fs.existsSync(dbDir)) {
|
|
||||||
fs.mkdirSync(dbDir, { recursive: true });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.db = new Database(this.dbPath, { verbose: console.log });
|
onModuleInit() {
|
||||||
|
this.prisma.$connect();
|
||||||
}
|
}
|
||||||
|
|
||||||
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();
|
|
||||||
@@ -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 } },
|
||||||
if (search) {
|
{ companyName: { contains: 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);
|
|
||||||
}
|
}
|
||||||
|
: undefined;
|
||||||
|
|
||||||
query += ' ORDER BY s.created_at DESC LIMIT ? OFFSET ?';
|
const [serials, total] = await Promise.all([
|
||||||
params.push(parseInt(limit.toString()), parseInt(offset.toString()));
|
prisma.serial.findMany({
|
||||||
|
where,
|
||||||
const [serials, countResult] = await Promise.all([
|
include: {
|
||||||
this.dbService.all(query, params),
|
user: {
|
||||||
this.dbService.get<{ total: number }>(countQuery, params.slice(0, -2))
|
select: { name: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
skip: offset,
|
||||||
|
take: limit,
|
||||||
|
}),
|
||||||
|
prisma.serial.count({ where }),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const total = countResult?.total || 0;
|
|
||||||
const totalPages = Math.ceil(total / limit);
|
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