template-saas-backend-v2/src/modules/mlm/services/structures.service.ts
Adrian Flores Cortes c683ab0353 [SAAS-021] feat: Implement MLM module backend
- 6 entities: structure, rank, node, commission, bonus, rank_history
- 4 DTOs with validation
- 4 services with tree operations (LTREE path queries)
- 4 controllers with full CRUD
- Commission calculation and rank evaluation logic
- My network endpoints for user dashboard

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 06:48:44 -06:00

80 lines
2.0 KiB
TypeScript

import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, ILike } from 'typeorm';
import { StructureEntity } from '../entities/structure.entity';
import {
CreateStructureDto,
UpdateStructureDto,
StructureFiltersDto,
} from '../dto/structure.dto';
@Injectable()
export class StructuresService {
constructor(
@InjectRepository(StructureEntity)
private readonly structureRepository: Repository<StructureEntity>,
) {}
async findAll(tenantId: string, filters?: StructureFiltersDto): Promise<StructureEntity[]> {
const where: any = { tenantId };
if (filters?.type) {
where.type = filters.type;
}
if (filters?.isActive !== undefined) {
where.isActive = filters.isActive;
}
if (filters?.search) {
where.name = ILike(`%${filters.search}%`);
}
return this.structureRepository.find({
where,
order: { createdAt: 'DESC' },
});
}
async findOne(tenantId: string, id: string): Promise<StructureEntity> {
const structure = await this.structureRepository.findOne({
where: { id, tenantId },
});
if (!structure) {
throw new NotFoundException(`Structure with ID ${id} not found`);
}
return structure;
}
async create(
tenantId: string,
userId: string,
dto: CreateStructureDto,
): Promise<StructureEntity> {
const structure = this.structureRepository.create({
...dto,
tenantId,
createdBy: userId,
});
return this.structureRepository.save(structure);
}
async update(
tenantId: string,
id: string,
dto: UpdateStructureDto,
): Promise<StructureEntity> {
const structure = await this.findOne(tenantId, id);
Object.assign(structure, dto);
return this.structureRepository.save(structure);
}
async remove(tenantId: string, id: string): Promise<void> {
const structure = await this.findOne(tenantId, id);
await this.structureRepository.remove(structure);
}
}