refacor: 重构目录架构

This commit is contained in:
2026-09-16 22:43:21 +08:00
parent b37cdb0d54
commit 2754ed1e45
2762 changed files with 0 additions and 1529 deletions
@@ -0,0 +1,18 @@
import { Body, Controller, Post } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LoginDto } from './auth.dto';
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Post('login')
login(@Body() dto: LoginDto) {
return this.authService.login(dto);
}
@Post('logout')
logout() {
return { success: true };
}
}
@@ -0,0 +1,11 @@
import { IsNotEmpty, IsString } from 'class-validator';
export class LoginDto {
@IsString()
@IsNotEmpty()
username!: string;
@IsString()
@IsNotEmpty()
password!: string;
}
@@ -0,0 +1,23 @@
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { TypeOrmModule } from '@nestjs/typeorm';
import { LcAdmin } from '../../entities/lc-admin.entity';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
@Module({
imports: [
TypeOrmModule.forFeature([LcAdmin]),
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secret: process.env.JWT_SECRET || 'change-me-in-production',
signOptions: { expiresIn: process.env.JWT_EXPIRES_IN || '8h' },
}),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
exports: [JwtModule],
})
export class AuthModule {}
@@ -0,0 +1,38 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import * as bcrypt from 'bcrypt';
import { Repository } from 'typeorm';
import { LcAdmin } from '../../entities/lc-admin.entity';
import { LoginDto } from './auth.dto';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(LcAdmin)
private readonly adminRepo: Repository<LcAdmin>,
private readonly jwtService: JwtService,
) {}
async login(dto: LoginDto) {
const admin = await this.adminRepo.findOne({ where: { username: dto.username } });
if (!admin || admin.status !== 1) {
throw new UnauthorizedException('用户名或密码错误');
}
const ok = await bcrypt.compare(dto.password, admin.password);
if (!ok) {
throw new UnauthorizedException('用户名或密码错误');
}
const expiresIn = process.env.JWT_EXPIRES_IN || '8h';
const token = this.jwtService.sign(
{ sub: admin.id, username: admin.username },
{ expiresIn },
);
const decoded = this.jwtService.decode(token) as { exp?: number };
return {
token,
username: admin.username,
expiresAt: decoded?.exp ? new Date(decoded.exp * 1000).toISOString() : null,
};
}
}
@@ -0,0 +1,5 @@
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
@@ -0,0 +1,26 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
export interface AdminJwtPayload {
sub: number;
username: string;
}
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.JWT_SECRET || 'change-me-in-production',
});
}
validate(payload: AdminJwtPayload) {
if (!payload?.sub) {
throw new UnauthorizedException();
}
return { adminId: payload.sub, username: payload.username };
}
}
@@ -0,0 +1,55 @@
import {
Body,
Controller,
Delete,
Get,
Param,
ParseIntPipe,
Post,
Put,
Query,
UseGuards,
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { LicenseService } from '../license/license.service';
import { CreateCustomerDto, CustomerQueryDto, UpdateCustomerDto } from './customer.dto';
import { CustomerService } from './customer.service';
@Controller('customers')
@UseGuards(JwtAuthGuard)
export class CustomerController {
constructor(
private readonly customerService: CustomerService,
private readonly licenseService: LicenseService,
) {}
@Get()
list(@Query() query: CustomerQueryDto) {
return this.customerService.list(query);
}
@Post()
create(@Body() dto: CreateCustomerDto) {
return this.customerService.create(dto);
}
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
return this.customerService.findOne(id);
}
@Put(':id')
update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateCustomerDto) {
return this.customerService.update(id, dto);
}
@Delete(':id')
remove(@Param('id', ParseIntPipe) id: number) {
return this.customerService.remove(id);
}
@Get(':id/licenses')
licenses(@Param('id', ParseIntPipe) id: number) {
return this.licenseService.listByCustomer(id);
}
}
@@ -0,0 +1,68 @@
import { IsEmail, IsInt, IsNotEmpty, IsOptional, IsString, Min } from 'class-validator';
import { Type } from 'class-transformer';
export class CreateCustomerDto {
@IsString()
@IsOptional()
code?: string;
@IsString()
@IsNotEmpty()
name!: string;
@IsString()
@IsOptional()
contactName?: string;
@IsString()
@IsOptional()
contactPhone?: string;
@IsEmail()
@IsOptional()
contactEmail?: string;
@IsString()
@IsOptional()
remark?: string;
}
export class UpdateCustomerDto {
@IsString()
@IsOptional()
name?: string;
@IsString()
@IsOptional()
contactName?: string;
@IsString()
@IsOptional()
contactPhone?: string;
@IsEmail()
@IsOptional()
contactEmail?: string;
@IsInt()
@IsOptional()
status?: number;
@IsString()
@IsOptional()
remark?: string;
}
export class CustomerQueryDto {
@Type(() => Number)
@IsInt()
@Min(1)
@IsOptional()
page?: number = 1;
@Type(() => Number)
@IsInt()
@Min(1)
@IsOptional()
size?: number = 20;
}
@@ -0,0 +1,17 @@
import { Module, forwardRef } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { LcCustomer } from '../../entities/lc-customer.entity';
import { LicenseModule } from '../license/license.module';
import { CustomerController } from './customer.controller';
import { CustomerService } from './customer.service';
@Module({
imports: [
TypeOrmModule.forFeature([LcCustomer]),
forwardRef(() => LicenseModule),
],
controllers: [CustomerController],
providers: [CustomerService],
exports: [CustomerService],
})
export class CustomerModule {}
@@ -0,0 +1,67 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { LcCustomer } from '../../entities/lc-customer.entity';
import { CreateCustomerDto, CustomerQueryDto, UpdateCustomerDto } from './customer.dto';
@Injectable()
export class CustomerService {
constructor(
@InjectRepository(LcCustomer)
private readonly customerRepo: Repository<LcCustomer>,
) {}
async list(query: CustomerQueryDto) {
const page = query.page || 1;
const size = query.size || 20;
const [items, total] = await this.customerRepo.findAndCount({
order: { id: 'DESC' },
skip: (page - 1) * size,
take: size,
});
return { items, total, page, size };
}
async findOne(id: number) {
const customer = await this.customerRepo.findOne({ where: { id } });
if (!customer) throw new NotFoundException('客户不存在');
return customer;
}
async create(dto: CreateCustomerDto) {
const code = dto.code || (await this.generateCode());
const customer = this.customerRepo.create({
code,
name: dto.name,
contactName: dto.contactName ?? null,
contactPhone: dto.contactPhone ?? null,
contactEmail: dto.contactEmail ?? null,
remark: dto.remark ?? null,
status: 1,
});
return this.customerRepo.save(customer);
}
async update(id: number, dto: UpdateCustomerDto) {
const customer = await this.findOne(id);
Object.assign(customer, {
...dto,
contactName: dto.contactName ?? customer.contactName,
contactPhone: dto.contactPhone ?? customer.contactPhone,
contactEmail: dto.contactEmail ?? customer.contactEmail,
});
return this.customerRepo.save(customer);
}
async remove(id: number) {
const customer = await this.findOne(id);
await this.customerRepo.remove(customer);
return { success: true };
}
private async generateCode() {
const date = new Date().toISOString().slice(0, 10).replace(/-/g, '');
const count = await this.customerRepo.count();
return `CUST-${date}-${String(count + 1).padStart(3, '0')}`;
}
}
@@ -0,0 +1,14 @@
import { Controller, Get, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { DashboardService } from './dashboard.service';
@Controller('dashboard')
@UseGuards(JwtAuthGuard)
export class DashboardController {
constructor(private readonly dashboardService: DashboardService) {}
@Get('stats')
stats() {
return this.dashboardService.stats();
}
}
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { LcCustomer } from '../../entities/lc-customer.entity';
import { LcLicense } from '../../entities/lc-license.entity';
import { DashboardController } from './dashboard.controller';
import { DashboardService } from './dashboard.service';
@Module({
imports: [TypeOrmModule.forFeature([LcCustomer, LcLicense])],
controllers: [DashboardController],
providers: [DashboardService],
})
export class DashboardModule {}
@@ -0,0 +1,41 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, MoreThan } from 'typeorm';
import { LcCustomer } from '../../entities/lc-customer.entity';
import { LcLicense } from '../../entities/lc-license.entity';
@Injectable()
export class DashboardService {
constructor(
@InjectRepository(LcCustomer)
private readonly customerRepo: Repository<LcCustomer>,
@InjectRepository(LcLicense)
private readonly licenseRepo: Repository<LcLicense>,
) {}
async stats() {
const customerCount = await this.customerRepo.count();
const activeLicenseCount = await this.licenseRepo.count({ where: { status: 'active' } });
const thirtyDaysLater = new Date();
thirtyDaysLater.setDate(thirtyDaysLater.getDate() + 30);
const expiringSoonCount = await this.licenseRepo.count({
where: {
status: 'active',
expiresAt: MoreThan(new Date()),
},
});
const expiring = await this.licenseRepo
.createQueryBuilder('l')
.where('l.status = :status', { status: 'active' })
.andWhere('l.expires_at <= :date', { date: thirtyDaysLater })
.andWhere('l.expires_at > NOW()')
.getCount();
return {
customerCount,
activeLicenseCount,
expiringSoonCount: expiring,
totalLicenses: await this.licenseRepo.count(),
};
}
}
@@ -0,0 +1,59 @@
import {
Body,
Controller,
Get,
Param,
ParseIntPipe,
Post,
Query,
Res,
UseGuards,
} from '@nestjs/common';
import { Response } from 'express';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { GenerateLicenseDto, LicenseQueryDto } from './license.dto';
import { LicenseService } from './license.service';
@Controller('licenses')
export class LicenseController {
constructor(private readonly licenseService: LicenseService) {}
/** 在线吊销状态查询(主应用调用,无需管理员 JWT) */
@Get('status')
status(@Query('jti') jti: string) {
return this.licenseService.getStatusByJti(jti);
}
@Get()
@UseGuards(JwtAuthGuard)
list(@Query() query: LicenseQueryDto) {
return this.licenseService.list(query);
}
@Post('generate')
@UseGuards(JwtAuthGuard)
generate(@Body() dto: GenerateLicenseDto) {
return this.licenseService.generate(dto);
}
@Get(':id')
@UseGuards(JwtAuthGuard)
findOne(@Param('id', ParseIntPipe) id: number) {
return this.licenseService.findOne(id);
}
@Post(':id/revoke')
@UseGuards(JwtAuthGuard)
revoke(@Param('id', ParseIntPipe) id: number) {
return this.licenseService.revoke(id);
}
@Get(':id/download')
@UseGuards(JwtAuthGuard)
async download(@Param('id', ParseIntPipe) id: number, @Res() res: Response) {
const file = await this.licenseService.download(id);
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.setHeader('Content-Disposition', `attachment; filename="${file.filename}"`);
res.send(file.content);
}
}
@@ -0,0 +1,64 @@
import {
IsArray,
IsDateString,
IsInt,
IsNotEmpty,
IsOptional,
IsString,
Min,
} from 'class-validator';
import { Type } from 'class-transformer';
export class GenerateLicenseDto {
@Type(() => Number)
@IsInt()
customerId!: number;
@IsString()
@IsNotEmpty()
company!: string;
@IsString()
@IsNotEmpty()
machineFingerprint!: string;
@IsString()
@IsNotEmpty()
edition!: string;
@IsDateString()
expiresAt!: string;
@IsArray()
@IsString({ each: true })
features!: string[];
@Type(() => Number)
@IsInt()
@Min(1)
@IsOptional()
maxCompanies?: number;
}
export class LicenseQueryDto {
@Type(() => Number)
@IsInt()
@Min(1)
@IsOptional()
page?: number = 1;
@Type(() => Number)
@IsInt()
@Min(1)
@IsOptional()
size?: number = 20;
@Type(() => Number)
@IsInt()
@IsOptional()
customerId?: number;
@IsString()
@IsOptional()
status?: string;
}
@@ -0,0 +1,18 @@
import { Module, forwardRef } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { JwtSignerService } from '../../common/jwt-signer.service';
import { LcLicense } from '../../entities/lc-license.entity';
import { CustomerModule } from '../customer/customer.module';
import { LicenseController } from './license.controller';
import { LicenseService } from './license.service';
@Module({
imports: [
TypeOrmModule.forFeature([LcLicense]),
forwardRef(() => CustomerModule),
],
controllers: [LicenseController],
providers: [LicenseService, JwtSignerService],
exports: [LicenseService, JwtSignerService],
})
export class LicenseModule {}
@@ -0,0 +1,126 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { JwtSignerService } from '../../common/jwt-signer.service';
import { LcCustomer } from '../../entities/lc-customer.entity';
import { LcLicense } from '../../entities/lc-license.entity';
import { CustomerService } from '../customer/customer.service';
import { GenerateLicenseDto, LicenseQueryDto } from './license.dto';
@Injectable()
export class LicenseService {
constructor(
@InjectRepository(LcLicense)
private readonly licenseRepo: Repository<LcLicense>,
private readonly customerService: CustomerService,
private readonly jwtSigner: JwtSignerService,
) {}
async list(query: LicenseQueryDto) {
const page = query.page || 1;
const size = query.size || 20;
const qb = this.licenseRepo
.createQueryBuilder('l')
.leftJoinAndSelect('l.customer', 'c')
.orderBy('l.id', 'DESC')
.skip((page - 1) * size)
.take(size);
if (query.customerId) {
qb.andWhere('l.customer_id = :customerId', { customerId: query.customerId });
}
if (query.status) {
qb.andWhere('l.status = :status', { status: query.status });
}
const [items, total] = await qb.getManyAndCount();
return { items, total, page, size };
}
async findOne(id: number) {
const license = await this.licenseRepo.findOne({
where: { id },
relations: ['customer'],
});
if (!license) throw new NotFoundException('许可证不存在');
return license;
}
async listByCustomer(customerId: number) {
await this.customerService.findOne(customerId);
return this.licenseRepo.find({
where: { customerId },
order: { id: 'DESC' },
});
}
async generate(dto: GenerateLicenseDto) {
const customer = await this.customerService.findOne(dto.customerId);
const expiresAt = new Date(dto.expiresAt);
const signed = await this.jwtSigner.signLicense({
sub: customer.code,
company: dto.company,
machineFingerprint: dto.machineFingerprint,
edition: dto.edition,
features: dto.features,
expiresAt,
maxCompanies: dto.maxCompanies,
});
const license = this.licenseRepo.create({
customerId: customer.id,
licenseKey: signed.licenseKey,
jti: signed.jti,
edition: dto.edition,
machineFingerprint: dto.machineFingerprint,
features: dto.features,
status: 'active',
issuedAt: signed.issuedAt,
expiresAt: signed.expiresAt,
activationCount: 0,
maxCompanies: dto.maxCompanies ?? null,
});
const saved = await this.licenseRepo.save(license);
return {
id: saved.id,
licenseKey: saved.licenseKey,
jti: saved.jti,
edition: saved.edition,
machineFingerprint: saved.machineFingerprint,
maxCompanies: saved.maxCompanies,
expiresAt: saved.expiresAt,
status: saved.status,
};
}
async revoke(id: number) {
const license = await this.findOne(id);
license.status = 'revoked';
license.revokedAt = new Date();
await this.licenseRepo.save(license);
return { id: license.id, jti: license.jti, status: license.status, revokedAt: license.revokedAt };
}
/** 在线吊销查询(主应用可选同步) */
async getStatusByJti(jti: string) {
const license = await this.licenseRepo.findOne({ where: { jti } });
if (!license) {
throw new NotFoundException('许可证不存在');
}
// 过期自动标记
if (license.status === 'active' && license.expiresAt < new Date()) {
license.status = 'expired';
await this.licenseRepo.save(license);
}
return {
jti: license.jti,
status: license.status,
revokedAt: license.revokedAt,
};
}
async download(id: number) {
const license = await this.findOne(id);
return {
filename: `license-${license.jti}.key`,
content: license.licenseKey,
};
}
}