All files / src/domains/hr/organization department.service.ts

0% Statements 0/60
0% Branches 0/39
0% Functions 0/9
0% Lines 0/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163                                                                                                                                                                                                                                                                                                                                     
import {
  Injectable,
  NotFoundException,
  BadRequestException,
  ConflictException,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Department } from './schemas/department.schema';
import { AuditLogService } from '../../../platform/audit/audit-log.service';
import { EventBusService } from '../../../platform/events/event-bus.service';
 
@Injectable()
export class DepartmentService {
  constructor(
    @InjectModel(Department.name)
    private readonly departmentModel: Model<Department>,
    private readonly auditLog: AuditLogService,
    private readonly eventBus: EventBusService,
  ) {}
 
  async create(tenantId: string, data: any, userId: string) {
    const existing = await this.departmentModel
      .findOne({ tenantId, departmentCode: data.departmentCode })
      .exec();
    if (existing)
      throw new ConflictException(
        `Department code ${data.departmentCode} already exists.`,
      );
 
    if (data.parentDepartmentId) {
      const parent = await this.departmentModel
        .findOne({ tenantId, _id: data.parentDepartmentId })
        .exec();
      if (!parent)
        throw new BadRequestException(
          'Parent department not found in this tenant.',
        );
      // Circular hierarchy check
      await this.validateNoCycle(tenantId, data.parentDepartmentId, null);
    }
 
    const dept = await this.departmentModel.create({
      ...data,
      tenantId,
      createdBy: userId,
    });
 
    await this.auditLog.log({
      tenantId,
      userId,
      action: 'CREATE',
      resource: 'Department',
      resourceId: dept.id,
      newValues: data,
      moduleName: 'HR',
    });
    await this.eventBus.publish(
      'hr.department.created.v1',
      { tenantId, departmentId: dept.id },
      tenantId,
    );
    return dept;
  }
 
  async findAll(tenantId: string) {
    return this.departmentModel
      .find({ tenantId, deletedAt: null })
      .sort({ departmentName: 1 })
      .lean()
      .exec();
  }
 
  async findOne(tenantId: string, id: string) {
    const dept = await this.departmentModel
      .findOne({ tenantId, _id: id, deletedAt: null })
      .lean()
      .exec();
    if (!dept) throw new NotFoundException('Department not found');
    return dept;
  }
 
  async update(tenantId: string, id: string, data: any, userId: string) {
    const dept = await this.departmentModel
      .findOne({ tenantId, _id: id, deletedAt: null })
      .exec();
    if (!dept) throw new NotFoundException('Department not found');
 
    if (data.parentDepartmentId) {
      if (data.parentDepartmentId === id)
        throw new BadRequestException('Department cannot be its own parent.');
      await this.validateNoCycle(tenantId, data.parentDepartmentId, id);
    }
 
    const oldValues = dept.toObject();
    Object.assign(dept, data, { updatedBy: userId });
    await dept.save();
 
    await this.auditLog.log({
      tenantId,
      userId,
      action: 'UPDATE',
      resource: 'Department',
      resourceId: dept.id,
      oldValues,
      newValues: data,
      moduleName: 'HR',
    });
    await this.eventBus.publish(
      'hr.department.updated.v1',
      { tenantId, departmentId: dept.id },
      tenantId,
    );
    return dept;
  }
 
  async getTree(tenantId: string) {
    const departments = await this.findAll(tenantId);
    const tree: any[] = [];
    const lookup = new Map<string, any>();
 
    departments.forEach((dept: any) => {
      lookup.set(dept._id.toString(), { ...dept, children: [] });
    });
 
    departments.forEach((dept: any) => {
      const node = lookup.get(dept._id.toString());
      if (dept.parentDepartmentId && lookup.has(dept.parentDepartmentId)) {
        lookup.get(dept.parentDepartmentId).children.push(node);
      } else {
        tree.push(node);
      }
    });
 
    return tree;
  }
 
  /** Walk up the parent chain to ensure no cycle would be created */
  private async validateNoCycle(
    tenantId: string,
    parentId: string,
    selfId: string | null,
    depth = 0,
  ) {
    if (depth > 20)
      throw new BadRequestException('Department hierarchy too deep.');
    if (parentId === selfId)
      throw new BadRequestException('Circular department hierarchy detected.');
    const parent = await this.departmentModel
      .findOne({ tenantId, _id: parentId })
      .lean()
      .exec();
    if (parent && (parent as any).parentDepartmentId) {
      await this.validateNoCycle(
        tenantId,
        (parent as any).parentDepartmentId,
        selfId,
        depth + 1,
      );
    }
  }
}