Compare commits
2 Commits
1eb8abb447
...
86e41b479d
| Author | SHA1 | Date | |
|---|---|---|---|
|
86e41b479d
|
|||
|
2dc6bf16ec
|
2
.gitignore
vendored
2
.gitignore
vendored
@@ -75,3 +75,5 @@ dist/
|
||||
|
||||
# NestJS
|
||||
.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[]=@nestjs/core
|
||||
only-built-dependencies[]=unrs-resolver
|
||||
@@ -28,23 +28,24 @@
|
||||
"@nestjs/passport": "^11.0.5",
|
||||
"@nestjs/platform-express": "^11.1.13",
|
||||
"@nestjs/serve-static": "^5.0.4",
|
||||
"@prisma/adapter-libsql": "^7.3.0",
|
||||
"@prisma/client": "^7.3.0",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"better-sqlite3": "^12.6.2",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.3",
|
||||
"dotenv": "^17.2.3",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"passport": "^0.7.0",
|
||||
"passport-jwt": "^4.0.1",
|
||||
"prisma": "^7.3.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^11.0.0",
|
||||
"@nestjs/schematics": "^11.0.0",
|
||||
"@nestjs/cli": "^11.0.16",
|
||||
"@nestjs/schematics": "^11.0.9",
|
||||
"@nestjs/testing": "^11.1.13",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/express": "^5.0.6",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
|
||||
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 bcrypt from 'bcryptjs';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import bcrypt from "bcryptjs";
|
||||
import path from "path";
|
||||
import { PrismaLibSql } from "@prisma/adapter-libsql";
|
||||
|
||||
const dbPath = path.join(process.cwd(), 'data/database.sqlite');
|
||||
const dbDir = path.dirname(dbPath);
|
||||
const adapter = new PrismaLibSql({
|
||||
url:
|
||||
process.env.DATABASE_URL ||
|
||||
"file:" + path.join(process.cwd(), "data/database.sqlite"),
|
||||
});
|
||||
|
||||
if (!fs.existsSync(dbDir)) {
|
||||
fs.mkdirSync(dbDir, { recursive: true });
|
||||
}
|
||||
|
||||
const db = new Database(dbPath, { verbose: console.log });
|
||||
|
||||
const createTables = (): void => {
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
email TEXT,
|
||||
role TEXT DEFAULT 'user',
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS companies (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
company_name TEXT UNIQUE NOT NULL,
|
||||
is_active BOOLEAN BOOLEAN DEFAULT 1,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS serials (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
serial_number TEXT UNIQUE NOT NULL,
|
||||
company_name TEXT NOT NULL,
|
||||
valid_until DATETIME,
|
||||
is_active BOOLEAN DEFAULT 1,
|
||||
created_by INTEGER,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (created_by) REFERENCES users (id),
|
||||
FOREIGN KEY (company_name) REFERENCES companies (company_name)
|
||||
)
|
||||
`);
|
||||
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_company_name_companies ON companies (company_name)');
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_serial_number ON serials (serial_number)');
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_company_name_serials ON serials (company_name)');
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_created_by ON serials (created_by)');
|
||||
|
||||
console.log('数据库表创建完成');
|
||||
};
|
||||
const prisma = new PrismaClient({
|
||||
log: ["query", "error", "warn"],
|
||||
adapter,
|
||||
});
|
||||
|
||||
const createDefaultUser = async (): Promise<void> => {
|
||||
const username = 'admin';
|
||||
const password = 'Beifan@2026';
|
||||
const name = '系统管理员';
|
||||
const username = "admin";
|
||||
const password = "Beifan@2026";
|
||||
const name = "系统管理员";
|
||||
|
||||
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { username },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
const hashedPassword = await bcrypt.hash(password, 10);
|
||||
|
||||
db.prepare(
|
||||
'INSERT INTO users (username, password, name, email, role) VALUES (?, ?, ?, ?, ?)'
|
||||
).run(username, hashedPassword, name, 'admin@example.com', 'admin');
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
username,
|
||||
password: hashedPassword,
|
||||
name,
|
||||
email: "admin@example.com",
|
||||
role: "admin",
|
||||
},
|
||||
});
|
||||
|
||||
console.log('默认管理员用户创建完成:');
|
||||
console.log('用户名:', username);
|
||||
console.log('密码:', password);
|
||||
console.log("默认管理员用户创建完成:");
|
||||
console.log("用户名:", username);
|
||||
console.log("密码:", password);
|
||||
} else {
|
||||
console.log('默认管理员用户已存在');
|
||||
console.log("默认管理员用户已存在");
|
||||
}
|
||||
};
|
||||
|
||||
const initDatabase = async (): Promise<void> => {
|
||||
createTables();
|
||||
await createDefaultUser();
|
||||
db.close();
|
||||
console.log('数据库连接已关闭');
|
||||
await prisma.$disconnect();
|
||||
console.log("数据库连接已关闭");
|
||||
};
|
||||
|
||||
initDatabase();
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { AuthUser } from '../types';
|
||||
import {
|
||||
Injectable,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
UnauthorizedException,
|
||||
} from "@nestjs/common";
|
||||
import { JwtService } from "@nestjs/jwt";
|
||||
import { DatabaseService } from "../database/database.service";
|
||||
import { AuthUser } from "../types";
|
||||
|
||||
@Injectable()
|
||||
export class AuthGuard implements CanActivate {
|
||||
@@ -12,32 +17,42 @@ export class AuthGuard implements CanActivate {
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const authHeader = request.headers['authorization'];
|
||||
const token = authHeader && authHeader.split(' ')[1];
|
||||
const authHeader = request.headers["authorization"];
|
||||
const token = authHeader && authHeader.split(" ")[1];
|
||||
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('访问令牌缺失');
|
||||
throw new UnauthorizedException("访问令牌缺失");
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = this.jwtService.verify(token) as { userId: number; username: string; role: string };
|
||||
|
||||
const user = await this.dbService.get<AuthUser>(
|
||||
'SELECT id, username, name, role FROM users WHERE id = ?',
|
||||
[decoded.userId]
|
||||
);
|
||||
|
||||
const decoded = this.jwtService.verify(token) as {
|
||||
userId: number;
|
||||
username: string;
|
||||
role: string;
|
||||
};
|
||||
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: decoded.userId },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
name: true,
|
||||
role: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('用户不存在');
|
||||
throw new UnauthorizedException("用户不存在");
|
||||
}
|
||||
|
||||
request.user = user;
|
||||
|
||||
request.user = user as AuthUser;
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error.name === 'TokenExpiredError') {
|
||||
throw new UnauthorizedException('令牌已过期');
|
||||
if (error.name === "TokenExpiredError") {
|
||||
throw new UnauthorizedException("令牌已过期");
|
||||
}
|
||||
throw new UnauthorizedException('无效的令牌');
|
||||
throw new UnauthorizedException("无效的令牌");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { User, AuthUser } from '../types';
|
||||
import { Injectable, UnauthorizedException } from "@nestjs/common";
|
||||
import { JwtService } from "@nestjs/jwt";
|
||||
import * as bcrypt from "bcryptjs";
|
||||
import { DatabaseService } from "../database/database.service";
|
||||
import { User, AuthUser } from "../types";
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
@@ -12,23 +12,30 @@ export class AuthService {
|
||||
) {}
|
||||
|
||||
async validateUser(username: string, password: string) {
|
||||
const user = await this.dbService.get<User>('SELECT * FROM users WHERE username = ?', [username]);
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { username },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('用户名或密码错误');
|
||||
throw new UnauthorizedException("用户名或密码错误");
|
||||
}
|
||||
|
||||
const isValidPassword = await bcrypt.compare(password, user.password);
|
||||
|
||||
if (!isValidPassword) {
|
||||
throw new UnauthorizedException('用户名或密码错误');
|
||||
throw new UnauthorizedException("用户名或密码错误");
|
||||
}
|
||||
|
||||
return user;
|
||||
return user as User;
|
||||
}
|
||||
|
||||
async login(user: User) {
|
||||
const payload = { userId: user.id, username: user.username, role: user.role };
|
||||
const payload = {
|
||||
userId: user.id,
|
||||
username: user.username,
|
||||
role: user.role,
|
||||
};
|
||||
const token = this.jwtService.sign(payload);
|
||||
|
||||
return {
|
||||
@@ -39,74 +46,81 @@ export class AuthService {
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
createdAt: user.created_at,
|
||||
createdAt: user.createdAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async getProfile(userId: number) {
|
||||
const user = await this.dbService.get<User>(
|
||||
'SELECT id, username, name, email, role, created_at FROM users WHERE id = ?',
|
||||
[userId],
|
||||
);
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
name: true,
|
||||
email: true,
|
||||
role: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('用户不存在');
|
||||
throw new UnauthorizedException("用户不存在");
|
||||
}
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
createdAt: user.created_at,
|
||||
};
|
||||
return user;
|
||||
}
|
||||
|
||||
async changePassword(userId: number, currentPassword: string, newPassword: string) {
|
||||
const user = await this.dbService.get<Pick<User, 'password'>>('SELECT password FROM users WHERE id = ?', [
|
||||
userId,
|
||||
]);
|
||||
async changePassword(
|
||||
userId: number,
|
||||
currentPassword: string,
|
||||
newPassword: string,
|
||||
) {
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { password: true },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('用户不存在');
|
||||
throw new UnauthorizedException("用户不存在");
|
||||
}
|
||||
|
||||
const isValidPassword = await bcrypt.compare(currentPassword, user.password);
|
||||
const isValidPassword = await bcrypt.compare(
|
||||
currentPassword,
|
||||
user.password,
|
||||
);
|
||||
|
||||
if (!isValidPassword) {
|
||||
throw new UnauthorizedException('当前密码错误');
|
||||
throw new UnauthorizedException("当前密码错误");
|
||||
}
|
||||
|
||||
const hashedPassword = await bcrypt.hash(newPassword, 10);
|
||||
|
||||
await this.dbService.run('UPDATE users SET password = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', [
|
||||
hashedPassword,
|
||||
userId,
|
||||
]);
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { password: hashedPassword },
|
||||
});
|
||||
|
||||
return { message: '密码修改成功' };
|
||||
return { message: "密码修改成功" };
|
||||
}
|
||||
|
||||
async updateProfile(userId: number, name: string, email: string | null) {
|
||||
await this.dbService.run(
|
||||
'UPDATE users SET name = ?, email = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
|
||||
[name, email, userId],
|
||||
);
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const updatedUser = await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { name, email },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
name: true,
|
||||
email: true,
|
||||
role: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
const updatedUser = await this.dbService.get<User>(
|
||||
'SELECT id, username, name, email, role, created_at FROM users WHERE id = ?',
|
||||
[userId],
|
||||
);
|
||||
|
||||
return {
|
||||
id: updatedUser!.id,
|
||||
username: updatedUser!.username,
|
||||
name: updatedUser!.name,
|
||||
email: updatedUser!.email,
|
||||
role: updatedUser!.role,
|
||||
createdAt: updatedUser!.created_at,
|
||||
};
|
||||
return updatedUser;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,313 +1,324 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { DatabaseService } from "../database/database.service";
|
||||
|
||||
@Injectable()
|
||||
export class CompaniesService {
|
||||
constructor(private dbService: DatabaseService) {}
|
||||
|
||||
async findAll(page: number, limit: number, search: string) {
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
let query = `SELECT c.company_name, c.created_at as first_created, c.updated_at as last_created, c.is_active, (SELECT COUNT(*) FROM serials s WHERE s.company_name = c.company_name) as serial_count, (SELECT COUNT(*) FROM serials s WHERE s.company_name = c.company_name AND s.is_active = 1) as active_count FROM companies c`;
|
||||
let countQuery = 'SELECT COUNT(*) as total FROM companies';
|
||||
let params: any[] = [];
|
||||
const where = search
|
||||
? {
|
||||
companyName: { contains: search },
|
||||
}
|
||||
: undefined;
|
||||
|
||||
if (search) {
|
||||
query += ' WHERE c.company_name LIKE ?';
|
||||
countQuery += ' WHERE company_name LIKE ?';
|
||||
params.push(`%${search}%`);
|
||||
}
|
||||
|
||||
query += ' ORDER BY c.updated_at DESC LIMIT ? OFFSET ?';
|
||||
params.push(parseInt(limit.toString()), parseInt(offset.toString()));
|
||||
|
||||
const [companies, countResult] = await Promise.all([
|
||||
this.dbService.all(query, params),
|
||||
this.dbService.get<{ total: number }>(countQuery, params.slice(0, -2))
|
||||
const [companies, total] = await Promise.all([
|
||||
prisma.company.findMany({
|
||||
where,
|
||||
include: {
|
||||
serials: true,
|
||||
},
|
||||
orderBy: { updatedAt: "desc" },
|
||||
skip: offset,
|
||||
take: limit,
|
||||
}),
|
||||
prisma.company.count({ where }),
|
||||
]);
|
||||
|
||||
const total = countResult?.total || 0;
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
|
||||
return {
|
||||
message: '获取企业列表成功',
|
||||
message: "获取企业列表成功",
|
||||
data: companies.map((company: any) => ({
|
||||
companyName: company.company_name,
|
||||
firstCreated: company.first_created,
|
||||
lastCreated: company.last_created,
|
||||
serialCount: company.serial_count,
|
||||
activeCount: company.active_count,
|
||||
status: company.is_active ? 'active' : 'disabled'
|
||||
companyName: company.companyName,
|
||||
firstCreated: company.createdAt,
|
||||
lastCreated: company.updatedAt,
|
||||
serialCount: company.serials.length,
|
||||
activeCount: company.serials.filter((s: any) => s.isActive).length,
|
||||
status: company.isActive ? "active" : "disabled",
|
||||
})),
|
||||
pagination: {
|
||||
page: parseInt(page.toString()),
|
||||
limit: parseInt(limit.toString()),
|
||||
total,
|
||||
totalPages
|
||||
}
|
||||
totalPages,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async findOne(companyName: string, page: number, limit: number) {
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const companyInfo = await this.dbService.get('SELECT * FROM companies WHERE company_name = ?', [companyName]);
|
||||
const company = await prisma.company.findUnique({
|
||||
where: { companyName },
|
||||
include: {
|
||||
serials: {
|
||||
include: {
|
||||
user: {
|
||||
select: { name: true },
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!companyInfo) {
|
||||
throw new Error('企业不存在');
|
||||
if (!company) {
|
||||
throw new Error("企业不存在");
|
||||
}
|
||||
|
||||
const serialStats = await this.dbService.get(`
|
||||
SELECT COUNT(*) as serial_count,
|
||||
SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active_count,
|
||||
SUM(CASE WHEN is_active = 0 THEN 1 ELSE 0 END) as disabled_count,
|
||||
SUM(CASE WHEN valid_until IS NOT NULL AND valid_until <= datetime('now') THEN 1 ELSE 0 END) as expired_count
|
||||
FROM serials
|
||||
WHERE company_name = ?
|
||||
`, [companyName]);
|
||||
const now = new Date();
|
||||
const serialCount = company.serials.length;
|
||||
const activeCount = company.serials.filter(
|
||||
(s) => s.isActive && (!s.validUntil || s.validUntil > now),
|
||||
).length;
|
||||
const disabledCount = company.serials.filter((s) => !s.isActive).length;
|
||||
const expiredCount = company.serials.filter(
|
||||
(s) => s.validUntil && s.validUntil <= now,
|
||||
).length;
|
||||
|
||||
const serials = await this.dbService.all(`
|
||||
SELECT s.*, u.name as created_by_name
|
||||
FROM serials s
|
||||
LEFT JOIN users u ON s.created_by = u.id
|
||||
WHERE s.company_name = ?
|
||||
ORDER BY s.created_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`, [companyName, parseInt(limit.toString()), parseInt(offset.toString())]);
|
||||
const monthlyStatsMap = new Map<string, number>();
|
||||
|
||||
const stats = await this.dbService.all<{ month: string; count: number }>(`
|
||||
SELECT strftime('%Y-%m', created_at) as month,
|
||||
COUNT(*) as count
|
||||
FROM serials
|
||||
WHERE company_name = ?
|
||||
GROUP BY strftime('%Y-%m', created_at)
|
||||
ORDER BY month DESC
|
||||
LIMIT 12
|
||||
`, [companyName]);
|
||||
for (let i = 11; i >= 0; i--) {
|
||||
const date = new Date(now.getFullYear(), now.getMonth() - i, 1);
|
||||
const monthKey = date.toISOString().slice(0, 7);
|
||||
const count = company.serials.filter((s) => {
|
||||
const createdAt = new Date(s.createdAt);
|
||||
return (
|
||||
createdAt.getFullYear() === date.getFullYear() &&
|
||||
createdAt.getMonth() === date.getMonth()
|
||||
);
|
||||
}).length;
|
||||
|
||||
if (count > 0) {
|
||||
monthlyStatsMap.set(monthKey, count);
|
||||
}
|
||||
}
|
||||
|
||||
const paginatedSerials = company.serials.slice(offset, offset + limit);
|
||||
|
||||
return {
|
||||
message: '获取企业详情成功',
|
||||
message: "获取企业详情成功",
|
||||
data: {
|
||||
companyName: companyName,
|
||||
serialCount: serialStats?.serial_count || 0,
|
||||
activeCount: serialStats?.active_count || 0,
|
||||
disabledCount: serialStats?.disabled_count || 0,
|
||||
expiredCount: serialStats?.expired_count || 0,
|
||||
firstCreated: (companyInfo as any).created_at,
|
||||
lastCreated: (companyInfo as any).updated_at,
|
||||
status: (companyInfo as any).is_active ? 'active' : 'disabled',
|
||||
serials: serials.map((s: any) => ({
|
||||
serialNumber: s.serial_number,
|
||||
validUntil: s.valid_until,
|
||||
isActive: s.is_active,
|
||||
createdAt: s.created_at,
|
||||
createdBy: s.created_by_name
|
||||
serialCount,
|
||||
activeCount,
|
||||
disabledCount,
|
||||
expiredCount,
|
||||
firstCreated: company.createdAt,
|
||||
lastCreated: company.updatedAt,
|
||||
status: company.isActive ? "active" : "disabled",
|
||||
serials: paginatedSerials.map((s) => ({
|
||||
serialNumber: s.serialNumber,
|
||||
validUntil: s.validUntil,
|
||||
isActive: s.isActive,
|
||||
createdAt: s.createdAt,
|
||||
createdBy: s.user?.name,
|
||||
})),
|
||||
monthlyStats: stats.map(stat => ({
|
||||
month: stat.month,
|
||||
count: stat.count
|
||||
}))
|
||||
}
|
||||
monthlyStats: Array.from(monthlyStatsMap.entries()).map(
|
||||
([month, count]) => ({ month, count }),
|
||||
),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async update(companyName: string, newCompanyName: string) {
|
||||
const existingCompany = await this.dbService.get(
|
||||
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
||||
[companyName]
|
||||
);
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const existingCompany = await prisma.serial.count({
|
||||
where: { companyName },
|
||||
});
|
||||
|
||||
if (!existingCompany || (existingCompany as any).count === 0) {
|
||||
throw new Error('企业不存在');
|
||||
if (existingCompany === 0) {
|
||||
throw new Error("企业不存在");
|
||||
}
|
||||
|
||||
const duplicateCompany = await this.dbService.get(
|
||||
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
||||
[newCompanyName]
|
||||
);
|
||||
const duplicateCompany = await prisma.serial.count({
|
||||
where: { companyName: newCompanyName },
|
||||
});
|
||||
|
||||
if (duplicateCompany && (duplicateCompany as any).count > 0) {
|
||||
throw new Error('企业名称已存在');
|
||||
if (duplicateCompany > 0) {
|
||||
throw new Error("企业名称已存在");
|
||||
}
|
||||
|
||||
this.dbService.run(
|
||||
'UPDATE serials SET company_name = ?, updated_at = CURRENT_TIMESTAMP WHERE company_name = ?',
|
||||
[newCompanyName, companyName]
|
||||
);
|
||||
await prisma.serial.updateMany({
|
||||
where: { companyName },
|
||||
data: { companyName: newCompanyName },
|
||||
});
|
||||
|
||||
return {
|
||||
message: '企业名称更新成功',
|
||||
message: "企业名称更新成功",
|
||||
data: {
|
||||
oldCompanyName: companyName,
|
||||
newCompanyName
|
||||
}
|
||||
newCompanyName,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async delete(companyName: string) {
|
||||
const existingCompany = await this.dbService.get(
|
||||
'SELECT * FROM companies WHERE company_name = ?',
|
||||
[companyName]
|
||||
);
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const existingCompany = await prisma.company.findUnique({
|
||||
where: { companyName },
|
||||
});
|
||||
|
||||
if (!existingCompany) {
|
||||
throw new Error('企业不存在');
|
||||
throw new Error("企业不存在");
|
||||
}
|
||||
|
||||
this.dbService.run('BEGIN TRANSACTION');
|
||||
const deleteResult = await prisma.$transaction(async (tx) => {
|
||||
const serialDeleteCount = await tx.serial.deleteMany({
|
||||
where: { companyName },
|
||||
});
|
||||
|
||||
try {
|
||||
const serialDeleteResult = this.dbService.run(
|
||||
'DELETE FROM serials WHERE company_name = ?',
|
||||
[companyName]
|
||||
);
|
||||
await tx.company.delete({
|
||||
where: { companyName },
|
||||
});
|
||||
|
||||
const companyDeleteResult = this.dbService.run(
|
||||
'DELETE FROM companies WHERE company_name = ?',
|
||||
[companyName]
|
||||
);
|
||||
return serialDeleteCount.count;
|
||||
});
|
||||
|
||||
if (companyDeleteResult.changes === 0) {
|
||||
this.dbService.run('ROLLBACK');
|
||||
throw new Error('企业不存在');
|
||||
}
|
||||
|
||||
this.dbService.run('COMMIT');
|
||||
|
||||
return {
|
||||
message: '企业已完全删除,所有相关序列号已删除',
|
||||
data: {
|
||||
companyName: companyName,
|
||||
deletedSerialCount: serialDeleteResult.changes,
|
||||
deletedCompanyCount: companyDeleteResult.changes
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
this.dbService.run('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
return {
|
||||
message: "企业已完全删除,所有相关序列号已删除",
|
||||
data: {
|
||||
companyName: companyName,
|
||||
deletedSerialCount: deleteResult,
|
||||
deletedCompanyCount: 1,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async deleteSerial(companyName: string, serialNumber: string) {
|
||||
const serial = await this.dbService.get(
|
||||
'SELECT * FROM serials WHERE serial_number = ? AND company_name = ?',
|
||||
[serialNumber.toUpperCase(), companyName]
|
||||
);
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const serial = await prisma.serial.findFirst({
|
||||
where: {
|
||||
serialNumber: serialNumber.toUpperCase(),
|
||||
companyName,
|
||||
},
|
||||
});
|
||||
|
||||
if (!serial) {
|
||||
throw new Error('序列号不存在或不属于该企业');
|
||||
throw new Error("序列号不存在或不属于该企业");
|
||||
}
|
||||
|
||||
await this.dbService.run(
|
||||
'DELETE FROM serials WHERE serial_number = ? AND company_name = ?',
|
||||
[serialNumber.toUpperCase(), companyName]
|
||||
);
|
||||
await prisma.serial.delete({
|
||||
where: { serialNumber: serialNumber.toUpperCase() },
|
||||
});
|
||||
|
||||
return {
|
||||
message: '序列号已成功删除',
|
||||
message: "序列号已成功删除",
|
||||
data: {
|
||||
serialNumber: serialNumber.toUpperCase(),
|
||||
companyName
|
||||
}
|
||||
companyName,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async revoke(companyName: string) {
|
||||
const existingCompany = await this.dbService.get(
|
||||
'SELECT COUNT(*) as count FROM serials WHERE company_name = ?',
|
||||
[companyName]
|
||||
);
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const existingCompany = await prisma.serial.count({
|
||||
where: { companyName },
|
||||
});
|
||||
|
||||
if (!existingCompany || (existingCompany as any).count === 0) {
|
||||
throw new Error('企业不存在');
|
||||
if (existingCompany === 0) {
|
||||
throw new Error("企业不存在");
|
||||
}
|
||||
|
||||
await this.dbService.run(
|
||||
'UPDATE serials SET is_active = 0, updated_at = CURRENT_TIMESTAMP WHERE company_name = ?',
|
||||
[companyName]
|
||||
);
|
||||
await prisma.serial.updateMany({
|
||||
where: { companyName },
|
||||
data: { isActive: false },
|
||||
});
|
||||
|
||||
return {
|
||||
message: '企业已吊销,所有序列号已失效',
|
||||
message: "企业已吊销,所有序列号已失效",
|
||||
data: {
|
||||
companyName: companyName
|
||||
}
|
||||
companyName: companyName,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async getStats() {
|
||||
const companyCount = await this.dbService.get<{ count: number }>('SELECT COUNT(*) as count FROM companies');
|
||||
const serialCount = await this.dbService.get<{ count: number }>('SELECT COUNT(*) as count FROM serials');
|
||||
const activeCount = await this.dbService.get<{ count: number }>(`
|
||||
SELECT COUNT(*) as count FROM serials
|
||||
WHERE is_active = 1 AND (valid_until IS NULL OR valid_until > datetime('now'))
|
||||
`);
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const now = new Date();
|
||||
|
||||
const monthlyStats = await this.dbService.all<{ month: string; company_count: number; serial_count: number }>(`
|
||||
SELECT strftime('%Y-%m', created_at) as month,
|
||||
COUNT(DISTINCT company_name) as company_count,
|
||||
COUNT(*) as serial_count
|
||||
FROM serials
|
||||
WHERE created_at >= strftime('%Y-%m-%d', datetime('now', '-12 months'))
|
||||
GROUP BY strftime('%Y-%m', created_at)
|
||||
ORDER BY month ASC
|
||||
`);
|
||||
const [companies, serials, recentCompanies, recentSerials] =
|
||||
await Promise.all([
|
||||
prisma.company.findMany(),
|
||||
prisma.serial.findMany({
|
||||
include: {
|
||||
company: true,
|
||||
},
|
||||
}),
|
||||
prisma.company.findMany({
|
||||
orderBy: { updatedAt: "desc" },
|
||||
take: 10,
|
||||
}),
|
||||
prisma.serial.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 10,
|
||||
}),
|
||||
]);
|
||||
|
||||
const recentCompanies = await this.dbService.all<{ company_name: string; last_created: string; is_active: number }>(`
|
||||
SELECT c.company_name, c.created_at as last_created, c.is_active
|
||||
FROM companies c
|
||||
ORDER BY c.updated_at DESC
|
||||
LIMIT 10
|
||||
`);
|
||||
const companyCount = companies.length;
|
||||
const serialCount = serials.length;
|
||||
const activeCount = serials.filter(
|
||||
(s) => s.isActive && (!s.validUntil || s.validUntil > now),
|
||||
).length;
|
||||
const inactiveCount = serialCount - activeCount;
|
||||
|
||||
const recentSerials = await this.dbService.all<{ serial_number: string; company_name: string; is_active: number; created_at: string }>(`
|
||||
SELECT s.serial_number, s.company_name, s.is_active, s.created_at
|
||||
FROM serials s
|
||||
ORDER BY s.created_at DESC
|
||||
LIMIT 10
|
||||
`);
|
||||
const monthlyStats: Array<{
|
||||
month: string;
|
||||
company_count: number;
|
||||
serial_count: number;
|
||||
}> = [];
|
||||
const nowYear = now.getFullYear();
|
||||
const nowMonth = now.getMonth();
|
||||
|
||||
let finalMonthlyStats = monthlyStats;
|
||||
if (monthlyStats.length === 0) {
|
||||
finalMonthlyStats = [];
|
||||
const now = new Date();
|
||||
for (let i = 11; i >= 0; i--) {
|
||||
const date = new Date(now.getFullYear(), now.getMonth() - i, 1);
|
||||
const month = date.toISOString().substr(0, 7);
|
||||
finalMonthlyStats.push({
|
||||
month,
|
||||
company_count: 0,
|
||||
serial_count: 0
|
||||
for (let i = 11; i >= 0; i--) {
|
||||
const date = new Date(nowYear, nowMonth - i, 1);
|
||||
const monthStr = date.toISOString().slice(0, 7);
|
||||
const monthSerials = serials.filter((s) => {
|
||||
const createdAt = new Date(s.createdAt);
|
||||
return (
|
||||
createdAt.getFullYear() === date.getFullYear() &&
|
||||
createdAt.getMonth() === date.getMonth()
|
||||
);
|
||||
});
|
||||
const uniqueCompanies = new Set(monthSerials.map((s) => s.companyName));
|
||||
|
||||
if (monthSerials.length > 0) {
|
||||
monthlyStats.push({
|
||||
month: monthStr,
|
||||
company_count: uniqueCompanies.size,
|
||||
serial_count: monthSerials.length,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
message: '获取统计数据成功',
|
||||
message: "获取统计数据成功",
|
||||
data: {
|
||||
overview: {
|
||||
totalCompanies: companyCount?.count || 0,
|
||||
totalSerials: serialCount?.count || 0,
|
||||
activeSerials: activeCount?.count || 0,
|
||||
inactiveSerials: (serialCount?.count || 0) - (activeCount?.count || 0)
|
||||
totalCompanies: companyCount,
|
||||
totalSerials: serialCount,
|
||||
activeSerials: activeCount,
|
||||
inactiveSerials: inactiveCount,
|
||||
},
|
||||
monthlyStats: finalMonthlyStats.map(stat => ({
|
||||
month: stat.month,
|
||||
company_count: stat.company_count,
|
||||
serial_count: stat.serial_count
|
||||
monthlyStats,
|
||||
recentCompanies: recentCompanies.map((c) => ({
|
||||
companyName: c.companyName,
|
||||
lastCreated: c.updatedAt,
|
||||
status: c.isActive ? "active" : "disabled",
|
||||
})),
|
||||
recentCompanies: recentCompanies.map(c => ({
|
||||
companyName: c.company_name,
|
||||
lastCreated: c.last_created,
|
||||
status: c.is_active ? 'active' : 'disabled'
|
||||
recentSerials: recentSerials.map((s) => ({
|
||||
serialNumber: s.serialNumber,
|
||||
companyName: s.companyName,
|
||||
isActive: s.isActive,
|
||||
createdAt: s.createdAt,
|
||||
})),
|
||||
recentSerials: recentSerials.map(s => ({
|
||||
serialNumber: s.serial_number,
|
||||
companyName: s.company_name,
|
||||
isActive: !!s.is_active,
|
||||
createdAt: s.created_at
|
||||
}))
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,59 +1,34 @@
|
||||
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import Database from 'better-sqlite3';
|
||||
import * as path from 'path';
|
||||
import * as fs from 'fs';
|
||||
import { Injectable, OnModuleInit, OnModuleDestroy } from "@nestjs/common";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import path from "path";
|
||||
import { PrismaLibSql } from "@prisma/adapter-libsql";
|
||||
|
||||
@Injectable()
|
||||
export class DatabaseService implements OnModuleInit, OnModuleDestroy {
|
||||
private db: Database.Database;
|
||||
private dbPath: string;
|
||||
private prisma: PrismaClient;
|
||||
|
||||
constructor(private configService: ConfigService) {}
|
||||
constructor() {
|
||||
const adapter = new PrismaLibSql({
|
||||
url:
|
||||
process.env.DATABASE_URL ||
|
||||
"file:" + path.join(process.cwd(), "data/database.sqlite"),
|
||||
});
|
||||
|
||||
this.prisma = new PrismaClient({
|
||||
log: ["query", "error", "warn"],
|
||||
adapter,
|
||||
});
|
||||
}
|
||||
|
||||
onModuleInit() {
|
||||
this.dbPath = this.configService.get<string>('DB_PATH', path.join(process.cwd(), 'data/database.sqlite'));
|
||||
const dbDir = path.dirname(this.dbPath);
|
||||
|
||||
if (!fs.existsSync(dbDir)) {
|
||||
fs.mkdirSync(dbDir, { recursive: true });
|
||||
}
|
||||
|
||||
this.db = new Database(this.dbPath, { verbose: console.log });
|
||||
this.prisma.$connect();
|
||||
}
|
||||
|
||||
onModuleDestroy() {
|
||||
this.db.close();
|
||||
this.prisma.$disconnect();
|
||||
}
|
||||
|
||||
get<T = any>(sql: string, params: any[] = []): T | undefined {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
return stmt.get(params) as T | undefined;
|
||||
} catch (error) {
|
||||
console.error('数据库查询错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
all<T = any>(sql: string, params: any[] = []): T[] {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
return stmt.all(params) as T[];
|
||||
} catch (error) {
|
||||
console.error('数据库查询错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
run(sql: string, params: any[] = []): { id: number; changes: number } {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
const result = stmt.run(params);
|
||||
return { id: result.lastInsertRowid as number, changes: result.changes };
|
||||
} catch (error) {
|
||||
console.error('数据库操作错误:', error);
|
||||
throw error;
|
||||
}
|
||||
getPrisma() {
|
||||
return this.prisma;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
class DatabaseWrapper {
|
||||
private db: Database.Database;
|
||||
private dbPath: string;
|
||||
|
||||
constructor() {
|
||||
this.dbPath = process.env.DB_PATH || path.join(process.cwd(), 'data/database.sqlite');
|
||||
const dbDir = path.dirname(this.dbPath);
|
||||
|
||||
if (!fs.existsSync(dbDir)) {
|
||||
fs.mkdirSync(dbDir, { recursive: true });
|
||||
}
|
||||
|
||||
this.db = new Database(this.dbPath, { verbose: console.log });
|
||||
}
|
||||
|
||||
get<T = any>(sql: string, params: any[] = []): T | undefined {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
return stmt.get(params) as T | undefined;
|
||||
} catch (error) {
|
||||
console.error('数据库查询错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
all<T = any>(sql: string, params: any[] = []): T[] {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
return stmt.all(params) as T[];
|
||||
} catch (error) {
|
||||
console.error('数据库查询错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
run(sql: string, params: any[] = []): { id: number; changes: number } {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
const result = stmt.run(params);
|
||||
return { id: result.lastInsertRowid as number, changes: result.changes };
|
||||
} catch (error) {
|
||||
console.error('数据库操作错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
}
|
||||
}
|
||||
|
||||
export default new DatabaseWrapper();
|
||||
@@ -1,235 +1,281 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import * as QRCode from 'qrcode';
|
||||
import { Serial, SerialListItem } from './dto';
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { DatabaseService } from "../database/database.service";
|
||||
import * as QRCode from "qrcode";
|
||||
import { Serial, SerialListItem } from "./dto";
|
||||
|
||||
@Injectable()
|
||||
export class SerialsService {
|
||||
constructor(private dbService: DatabaseService) {}
|
||||
|
||||
async generate(companyName: string, quantity: number, validDays: number, userId: number, serialPrefix?: string): Promise<SerialListItem[]> {
|
||||
async generate(
|
||||
companyName: string,
|
||||
quantity: number,
|
||||
validDays: number,
|
||||
userId: number,
|
||||
serialPrefix?: string,
|
||||
): Promise<SerialListItem[]> {
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const validUntil = new Date();
|
||||
validUntil.setDate(validUntil.getDate() + validDays);
|
||||
|
||||
const existingCompany = await this.dbService.get('SELECT * FROM companies WHERE company_name = ?', [companyName]);
|
||||
const existingCompany = await prisma.company.findUnique({
|
||||
where: { companyName },
|
||||
});
|
||||
if (!existingCompany) {
|
||||
await this.dbService.run('INSERT INTO companies (company_name, is_active) VALUES (?, 1)', [companyName]);
|
||||
await prisma.company.create({
|
||||
data: { companyName, isActive: true },
|
||||
});
|
||||
}
|
||||
|
||||
const serials: SerialListItem[] = [];
|
||||
const prefix = serialPrefix ? serialPrefix.toUpperCase().replace(/[^A-Z0-9]/g, '') : 'BF' + new Date().getFullYear().toString().substr(2);
|
||||
const prefix = serialPrefix
|
||||
? serialPrefix.toUpperCase().replace(/[^A-Z0-9]/g, "")
|
||||
: "BF" + new Date().getFullYear().toString().substr(2);
|
||||
|
||||
for (let i = 0; i < quantity; i++) {
|
||||
const randomPart = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
|
||||
const randomPart = Math.floor(Math.random() * 1000000)
|
||||
.toString()
|
||||
.padStart(6, "0");
|
||||
const serialNumber = `${prefix}${randomPart}`;
|
||||
|
||||
await this.dbService.run(
|
||||
'INSERT INTO serials (serial_number, company_name, valid_until, created_by) VALUES (?, ?, ?, ?)',
|
||||
[serialNumber, companyName, validUntil.toISOString().slice(0, 19).replace('T', ' '), userId]
|
||||
);
|
||||
|
||||
await prisma.serial.create({
|
||||
data: {
|
||||
serialNumber,
|
||||
companyName,
|
||||
validUntil,
|
||||
createdBy: userId,
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
|
||||
serials.push({
|
||||
serialNumber,
|
||||
companyName,
|
||||
validUntil: validUntil.toISOString(),
|
||||
isActive: true,
|
||||
createdAt: new Date().toISOString()
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
return serials;
|
||||
}
|
||||
|
||||
async generateQRCode(serialNumber: string, baseUrl?: string, requestHost?: string, protocol?: string) {
|
||||
const serial = await this.dbService.get<{ serial_number: string; company_name: string; is_active: number; valid_until: string | null }>(
|
||||
'SELECT s.*, u.name as created_by_name FROM serials s LEFT JOIN users u ON s.created_by = u.id WHERE s.serial_number = ?',
|
||||
[serialNumber.toUpperCase()]
|
||||
);
|
||||
async generateQRCode(
|
||||
serialNumber: string,
|
||||
baseUrl?: string,
|
||||
requestHost?: string,
|
||||
protocol?: string,
|
||||
) {
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const serial = await prisma.serial.findUnique({
|
||||
where: { serialNumber: serialNumber.toUpperCase() },
|
||||
include: {
|
||||
user: {
|
||||
select: { name: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!serial) {
|
||||
throw new Error('序列号不存在');
|
||||
throw new Error("序列号不存在");
|
||||
}
|
||||
|
||||
if (!serial.is_active) {
|
||||
throw new Error('序列号已被禁用');
|
||||
if (!serial.isActive) {
|
||||
throw new Error("序列号已被禁用");
|
||||
}
|
||||
|
||||
if (serial.valid_until && new Date(serial.valid_until) < new Date()) {
|
||||
throw new Error('序列号已过期');
|
||||
if (serial.validUntil && new Date(serial.validUntil) < new Date()) {
|
||||
throw new Error("序列号已过期");
|
||||
}
|
||||
|
||||
if (!baseUrl) {
|
||||
baseUrl = `${protocol}://${requestHost}/query.html`;
|
||||
}
|
||||
|
||||
const queryUrl = baseUrl.includes('?')
|
||||
? `${baseUrl}&serial=${serial.serial_number}`
|
||||
: `${baseUrl}?serial=${serial.serial_number}`;
|
||||
|
||||
const queryUrl = baseUrl.includes("?")
|
||||
? `${baseUrl}&serial=${serial.serialNumber}`
|
||||
: `${baseUrl}?serial=${serial.serialNumber}`;
|
||||
|
||||
const qrCodeData = await QRCode.toDataURL(queryUrl, {
|
||||
width: 200,
|
||||
color: {
|
||||
dark: '#165DFF',
|
||||
light: '#ffffff'
|
||||
}
|
||||
dark: "#165DFF",
|
||||
light: "#ffffff",
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
message: '二维码生成成功',
|
||||
message: "二维码生成成功",
|
||||
qrCodeData,
|
||||
queryUrl,
|
||||
serialNumber: serial.serial_number,
|
||||
companyName: serial.company_name,
|
||||
validUntil: serial.valid_until
|
||||
serialNumber: serial.serialNumber,
|
||||
companyName: serial.companyName,
|
||||
validUntil: serial.validUntil,
|
||||
};
|
||||
}
|
||||
|
||||
async query(serialNumber: string) {
|
||||
const serial = await this.dbService.get<{ serial_number: string; company_name: string; valid_until: string | null; is_active: number; created_at: string; created_by_name: string }>(
|
||||
'SELECT s.*, u.name as created_by_name FROM serials s LEFT JOIN users u ON s.created_by = u.id WHERE s.serial_number = ?',
|
||||
[serialNumber.toUpperCase()]
|
||||
);
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const serial = await prisma.serial.findUnique({
|
||||
where: { serialNumber: serialNumber.toUpperCase() },
|
||||
include: {
|
||||
user: {
|
||||
select: { name: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!serial) {
|
||||
throw new Error('序列号不存在');
|
||||
throw new Error("序列号不存在");
|
||||
}
|
||||
|
||||
if (serial.valid_until && new Date(serial.valid_until) < new Date()) {
|
||||
throw new Error('序列号已过期');
|
||||
if (serial.validUntil && new Date(serial.validUntil) < new Date()) {
|
||||
throw new Error("序列号已过期");
|
||||
}
|
||||
|
||||
return {
|
||||
message: '查询成功',
|
||||
message: "查询成功",
|
||||
serial: {
|
||||
serialNumber: serial.serial_number,
|
||||
companyName: serial.company_name,
|
||||
validUntil: serial.valid_until,
|
||||
status: serial.is_active ? 'active' : 'disabled',
|
||||
isActive: !!serial.is_active,
|
||||
createdAt: serial.created_at,
|
||||
createdBy: serial.created_by_name
|
||||
}
|
||||
serialNumber: serial.serialNumber,
|
||||
companyName: serial.companyName,
|
||||
validUntil: serial.validUntil,
|
||||
status: serial.isActive ? "active" : "disabled",
|
||||
isActive: serial.isActive,
|
||||
createdAt: serial.createdAt,
|
||||
createdBy: serial.user?.name,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async findAll(page: number, limit: number, search: string) {
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
let query = 'SELECT s.*, u.name as created_by_name FROM serials s LEFT JOIN users u ON s.created_by = u.id';
|
||||
let countQuery = 'SELECT COUNT(*) as total FROM serials s';
|
||||
let params: any[] = [];
|
||||
const where = search
|
||||
? {
|
||||
OR: [
|
||||
{ serialNumber: { contains: search } },
|
||||
{ companyName: { contains: search } },
|
||||
],
|
||||
}
|
||||
: undefined;
|
||||
|
||||
if (search) {
|
||||
query += ' WHERE s.serial_number LIKE ? OR s.company_name LIKE ?';
|
||||
countQuery += ' WHERE s.serial_number LIKE ? OR s.company_name LIKE ?';
|
||||
const searchParam = `%${search}%`;
|
||||
params.push(searchParam, searchParam);
|
||||
}
|
||||
|
||||
query += ' ORDER BY s.created_at DESC LIMIT ? OFFSET ?';
|
||||
params.push(parseInt(limit.toString()), parseInt(offset.toString()));
|
||||
|
||||
const [serials, countResult] = await Promise.all([
|
||||
this.dbService.all(query, params),
|
||||
this.dbService.get<{ total: number }>(countQuery, params.slice(0, -2))
|
||||
const [serials, total] = await Promise.all([
|
||||
prisma.serial.findMany({
|
||||
where,
|
||||
include: {
|
||||
user: {
|
||||
select: { name: true },
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
skip: offset,
|
||||
take: limit,
|
||||
}),
|
||||
prisma.serial.count({ where }),
|
||||
]);
|
||||
|
||||
const total = countResult?.total || 0;
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
|
||||
return {
|
||||
message: '获取序列号列表成功',
|
||||
data: serials.map((s: any) => ({
|
||||
serialNumber: s.serial_number,
|
||||
companyName: s.company_name,
|
||||
validUntil: s.valid_until,
|
||||
isActive: s.is_active,
|
||||
createdAt: s.created_at,
|
||||
createdBy: s.created_by_name
|
||||
message: "获取序列号列表成功",
|
||||
data: serials.map((s) => ({
|
||||
serialNumber: s.serialNumber,
|
||||
companyName: s.companyName,
|
||||
validUntil: s.validUntil,
|
||||
isActive: s.isActive,
|
||||
createdAt: s.createdAt,
|
||||
createdBy: s.user?.name,
|
||||
})),
|
||||
pagination: {
|
||||
page: parseInt(page.toString()),
|
||||
limit: parseInt(limit.toString()),
|
||||
total,
|
||||
totalPages
|
||||
}
|
||||
totalPages,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async update(serialNumber: string, updateData: { companyName?: string; validUntil?: string; isActive?: boolean }) {
|
||||
const existingSerial = await this.dbService.get<{ is_active: number }>('SELECT * FROM serials WHERE serial_number = ?', [serialNumber.toUpperCase()]);
|
||||
async update(
|
||||
serialNumber: string,
|
||||
updateData: {
|
||||
companyName?: string;
|
||||
validUntil?: string;
|
||||
isActive?: boolean;
|
||||
},
|
||||
) {
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const existingSerial = await prisma.serial.findUnique({
|
||||
where: { serialNumber: serialNumber.toUpperCase() },
|
||||
});
|
||||
|
||||
if (!existingSerial) {
|
||||
throw new Error('序列号不存在');
|
||||
throw new Error("序列号不存在");
|
||||
}
|
||||
|
||||
const updateFields: string[] = [];
|
||||
const params: any[] = [];
|
||||
|
||||
const updateFields: any = {};
|
||||
if (updateData.companyName !== undefined) {
|
||||
updateFields.push('company_name = ?');
|
||||
params.push(updateData.companyName);
|
||||
updateFields.companyName = updateData.companyName;
|
||||
}
|
||||
|
||||
if (updateData.validUntil !== undefined) {
|
||||
updateFields.push('valid_until = ?');
|
||||
params.push(updateData.validUntil);
|
||||
updateFields.validUntil = new Date(updateData.validUntil);
|
||||
}
|
||||
|
||||
if (updateData.isActive !== undefined) {
|
||||
updateFields.push('is_active = ?');
|
||||
params.push(updateData.isActive ? 1 : 0);
|
||||
updateFields.isActive = updateData.isActive;
|
||||
}
|
||||
|
||||
if (updateFields.length === 0) {
|
||||
throw new Error('没有提供更新字段');
|
||||
if (Object.keys(updateFields).length === 0) {
|
||||
throw new Error("没有提供更新字段");
|
||||
}
|
||||
|
||||
updateFields.push('updated_at = CURRENT_TIMESTAMP');
|
||||
params.push(serialNumber.toUpperCase());
|
||||
|
||||
await this.dbService.run(
|
||||
`UPDATE serials SET ${updateFields.join(', ')} WHERE serial_number = ?`,
|
||||
params
|
||||
);
|
||||
|
||||
const updatedSerial = await this.dbService.get('SELECT s.*, u.name as created_by_name FROM serials s LEFT JOIN users u ON s.created_by = u.id WHERE s.serial_number = ?', [serialNumber.toUpperCase()]);
|
||||
const updatedSerial = await prisma.serial.update({
|
||||
where: { serialNumber: serialNumber.toUpperCase() },
|
||||
data: updateFields,
|
||||
include: {
|
||||
user: {
|
||||
select: { name: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
message: '序列号更新成功',
|
||||
message: "序列号更新成功",
|
||||
serial: {
|
||||
serialNumber: (updatedSerial as any).serial_number,
|
||||
companyName: (updatedSerial as any).company_name,
|
||||
validUntil: (updatedSerial as any).valid_until,
|
||||
isActive: (updatedSerial as any).is_active,
|
||||
createdAt: (updatedSerial as any).created_at,
|
||||
updatedAt: (updatedSerial as any).updated_at,
|
||||
createdBy: (updatedSerial as any).created_by_name
|
||||
}
|
||||
serialNumber: updatedSerial.serialNumber,
|
||||
companyName: updatedSerial.companyName,
|
||||
validUntil: updatedSerial.validUntil,
|
||||
isActive: updatedSerial.isActive,
|
||||
createdAt: updatedSerial.createdAt,
|
||||
updatedAt: updatedSerial.updatedAt,
|
||||
createdBy: updatedSerial.user?.name,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async revoke(serialNumber: string) {
|
||||
const existingSerial = await this.dbService.get<{ is_active: number }>('SELECT * FROM serials WHERE serial_number = ?', [serialNumber.toUpperCase()]);
|
||||
const prisma = this.dbService.getPrisma();
|
||||
const existingSerial = await prisma.serial.findUnique({
|
||||
where: { serialNumber: serialNumber.toUpperCase() },
|
||||
});
|
||||
|
||||
if (!existingSerial) {
|
||||
throw new Error('序列号不存在');
|
||||
throw new Error("序列号不存在");
|
||||
}
|
||||
|
||||
if (!existingSerial.is_active) {
|
||||
throw new Error('序列号已被吊销');
|
||||
if (!existingSerial.isActive) {
|
||||
throw new Error("序列号已被吊销");
|
||||
}
|
||||
|
||||
await this.dbService.run(
|
||||
'UPDATE serials SET is_active = 0, updated_at = CURRENT_TIMESTAMP WHERE serial_number = ?',
|
||||
[serialNumber.toUpperCase()]
|
||||
);
|
||||
await prisma.serial.update({
|
||||
where: { serialNumber: serialNumber.toUpperCase() },
|
||||
data: { isActive: false },
|
||||
});
|
||||
|
||||
return {
|
||||
message: '序列号已吊销',
|
||||
message: "序列号已吊销",
|
||||
data: {
|
||||
serialNumber: serialNumber.toUpperCase()
|
||||
}
|
||||
serialNumber: serialNumber.toUpperCase(),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
59
src/types/index.d.ts
vendored
59
src/types/index.d.ts
vendored
@@ -4,42 +4,42 @@ export interface User {
|
||||
password: string;
|
||||
name: string;
|
||||
email: string | null;
|
||||
role: 'admin' | 'user';
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
role: "admin" | "user";
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface Company {
|
||||
id: number;
|
||||
company_name: string;
|
||||
is_active: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
companyName: string;
|
||||
isActive: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface Serial {
|
||||
id: number;
|
||||
serial_number: string;
|
||||
company_name: string;
|
||||
valid_until: string | null;
|
||||
is_active: boolean;
|
||||
created_by: number | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
created_by_name?: string;
|
||||
serialNumber: string;
|
||||
companyName: string;
|
||||
validUntil: Date | null;
|
||||
isActive: boolean;
|
||||
createdBy: number | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
createdByName?: string;
|
||||
}
|
||||
|
||||
export interface AuthUser {
|
||||
id: number;
|
||||
username: string;
|
||||
name: string;
|
||||
role: 'admin' | 'user';
|
||||
role: "admin" | "user";
|
||||
}
|
||||
|
||||
export interface JWTPayload {
|
||||
userId: number;
|
||||
username: string;
|
||||
role: 'admin' | 'user';
|
||||
role: "admin" | "user";
|
||||
}
|
||||
|
||||
export interface LoginRequest {
|
||||
@@ -105,7 +105,7 @@ export interface LoginResponse {
|
||||
username: string;
|
||||
name: string;
|
||||
email: string | null;
|
||||
role: 'admin' | 'user';
|
||||
role: "admin" | "user";
|
||||
};
|
||||
}
|
||||
|
||||
@@ -124,7 +124,7 @@ export interface CompanyListItem {
|
||||
lastCreated: string;
|
||||
serialCount: number;
|
||||
activeCount: number;
|
||||
status: 'active' | 'disabled';
|
||||
status: "active" | "disabled";
|
||||
}
|
||||
|
||||
export interface CompanyDetail {
|
||||
@@ -135,7 +135,7 @@ export interface CompanyDetail {
|
||||
expiredCount: number;
|
||||
firstCreated: string;
|
||||
lastCreated: string;
|
||||
status: 'active' | 'disabled';
|
||||
status: "active" | "disabled";
|
||||
serials: SerialListItem[];
|
||||
monthlyStats: MonthlyStat[];
|
||||
}
|
||||
@@ -154,7 +154,20 @@ export interface StatsOverview {
|
||||
|
||||
export interface StatsResponse {
|
||||
overview: StatsOverview;
|
||||
monthlyStats: Array<{ month: string; company_count: number; serial_count: number }>;
|
||||
recentCompanies: Array<{ companyName: string; lastCreated: string; status: 'active' | 'disabled' }>;
|
||||
recentSerials: Array<{ serialNumber: string; companyName: string; isActive: boolean; createdAt: string }>;
|
||||
monthlyStats: Array<{
|
||||
month: string;
|
||||
company_count: number;
|
||||
serial_count: number;
|
||||
}>;
|
||||
recentCompanies: Array<{
|
||||
companyName: string;
|
||||
lastCreated: string;
|
||||
status: "active" | "disabled";
|
||||
}>;
|
||||
recentSerials: Array<{
|
||||
serialNumber: string;
|
||||
companyName: string;
|
||||
isActive: boolean;
|
||||
createdAt: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
class DatabaseWrapper {
|
||||
private db: Database.Database;
|
||||
private dbPath: string;
|
||||
|
||||
constructor() {
|
||||
this.dbPath = process.env.DB_PATH || path.join(process.cwd(), 'data/database.sqlite');
|
||||
const dbDir = path.dirname(this.dbPath);
|
||||
|
||||
if (!fs.existsSync(dbDir)) {
|
||||
fs.mkdirSync(dbDir, { recursive: true });
|
||||
}
|
||||
|
||||
this.db = new Database(this.dbPath, { verbose: console.log });
|
||||
}
|
||||
|
||||
get<T = any>(sql: string, params: any[] = []): T | undefined {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
return stmt.get(params) as T | undefined;
|
||||
} catch (error) {
|
||||
console.error('数据库查询错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
all<T = any>(sql: string, params: any[] = []): T[] {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
return stmt.all(params) as T[];
|
||||
} catch (error) {
|
||||
console.error('数据库查询错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
run(sql: string, params: any[] = []): { id: number; changes: number } {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
const result = stmt.run(params);
|
||||
return { id: result.lastInsertRowid as number, changes: result.changes };
|
||||
} catch (error) {
|
||||
console.error('数据库操作错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
}
|
||||
}
|
||||
|
||||
export default new DatabaseWrapper();
|
||||
Reference in New Issue
Block a user