import { Injectable, NotFoundException } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository, Not } from 'typeorm'; import { Tenant } from '../entities/tenant.entity'; import { CreateTenantDto, UpdateTenantDto } from './dto/tenant.dto'; // 预设色板(避开红绿盲敏感色,保证差异度) const COLOR_PALETTE = [ '#ff7875', '#ffa940', '#ffc53d', '#73d13d', '#36cfc9', '#40a9ff', '#597ef7', '#9254de', '#f759ab', '#8c8c8c', ]; @Injectable() export class TenantsService { constructor(@InjectRepository(Tenant) private repo: Repository) {} async findAll(query?: { includeArchived?: boolean }) { const where: any = {}; if (!query?.includeArchived) where.status = Not('archived'); return this.repo.find({ where, order: { createdAt: 'DESC' } }); } async findOne(id: number) { const tenant = await this.repo.findOne({ where: { id } }); if (!tenant) throw new NotFoundException('租赁方不存在'); return tenant; } async create(dto: CreateTenantDto) { // 颜色未指定则自动分配(按当前租赁方数量取模) let color = dto.color; if (!color) { const total = await this.repo.count(); color = COLOR_PALETTE[total % COLOR_PALETTE.length]; } return this.repo.save(this.repo.create({ ...dto, color })); } async update(id: number, dto: UpdateTenantDto) { await this.findOne(id); await this.repo.update(id, dto); return this.repo.findOne({ where: { id } }); } async remove(id: number) { await this.findOne(id); await this.repo.update(id, { status: 'archived' }); return { message: '已归档' }; } }