refactor: migrate database layer to Prisma ORM
This commit is contained in:
@@ -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
|
||||
}))
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user