HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux ip-172-31-4-197 6.8.0-1036-aws #38~22.04.1-Ubuntu SMP Fri Aug 22 15:44:33 UTC 2025 x86_64
User: ubuntu (1000)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/api-management/src/app/permisos/services/permiso.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Permiso } from '../schemas/permiso.schema';
import { CreatePermisoDto } from '../dto/create-permiso.dto';
import { UpdatePermisoDto } from '../dto/update-permiso.dto';
import { ModulosAreasDto } from '../dto/modulos-areas.dto';
import {
  handleMessageError,
  handleMessageSucces,
} from '../../../shared/utils/message-handler';
import { ResApiInterface } from '../../../shared/interfaces/res-api.interface';
import { handleValidationError } from '../../../shared/utils/error-handler';

@Injectable()
export class PermisoService {
  constructor(
    @InjectModel(Permiso.name) private permisoModel: Model<Permiso>,
  ) {}

  async create(
    createPermisoDto: CreatePermisoDto,
  ): Promise<ResApiInterface<CreatePermisoDto>> {
    try {
      const createdPermiso = new this.permisoModel(createPermisoDto);
      const savedPermiso = await createdPermiso.save();
      return handleMessageSucces(savedPermiso, 'create');
    } catch (error) {
      console.log(error);
      throw handleValidationError(error);
    }
  }

  async findAll(
    page: number,
    limit: number,
  ): Promise<ResApiInterface<CreatePermisoDto[]>> {
    try {
      const skip = (page - 1) * limit;

      const totalRecordsPromise = await this.permisoModel.countDocuments({
        deletedAt: { $in: null },
      });

      const permisosPromise = this.permisoModel
        .find({ deletedAt: { $in: null } }, '_id nombre slug descripcion')
        .skip(skip)
        .limit(limit)
        .exec();

      const [permisos, totalRecords] = await Promise.all([
        permisosPromise,
        totalRecordsPromise,
      ]);

      return handleMessageSucces(permisos, 'findAll', totalRecords);
    } catch (error) {
      throw handleValidationError(error);
    }
  }

  async findOne(id: string): Promise<ResApiInterface<CreatePermisoDto>> {
    try {
      const permiso = await this.permisoModel
        .findById(
          id,
          '_id nombre slug descripcion modulo._id modulo.codigo modulo.nombre modulo.icon.codigo modulo.posicion modulo.showMenu area.codigo area._id area.nombre area.icon.codigo area.posicion area.showMenu',
        )
        .exec();

      if (!permiso) {
        throw new NotFoundException(handleMessageError('notFound'));
      }

      return handleMessageSucces(permiso, 'findOne');
    } catch (error) {
      throw handleValidationError(error);
    }
  }

  async update(
    id: string,
    updatePermisoDto: UpdatePermisoDto,
  ): Promise<ResApiInterface<UpdatePermisoDto>> {
    try {
      const updatedPermiso = await this.permisoModel.findByIdAndUpdate(
        id,
        updatePermisoDto,
        { new: true },
      );
      if (!updatedPermiso) {
        throw new NotFoundException(handleMessageError('notFound'));
      }
      return handleMessageSucces(updatedPermiso, 'update');
    } catch (error) {
      throw handleValidationError(error);
    }
  }

  async delete(id: string): Promise<ResApiInterface<CreatePermisoDto>> {
    try {
      const deletedPermiso = await this.permisoModel.findByIdAndUpdate(id, {
        deletedAt: new Date(),
      });
      if (!deletedPermiso) {
        throw new NotFoundException(handleMessageError('notFound'));
      }
      return handleMessageSucces(deletedPermiso, 'delete');
    } catch (error) {
      throw handleValidationError(error);
    }
  }

  async findModulosAreasPermisos(ModulosAreas: ModulosAreasDto[]) {
    try {
      const modulosAreasPermisos = await Promise.all(
        ModulosAreas.map(async (modulo) => {
          const itemsWithPermisos = await Promise.all(
            modulo.items.map(async (area) => {
              const areaId = area._id;
              const permisos = await this.permisoModel
                .find(
                  { 'area._id': areaId, deletedAt: null },
                  '_id nombre slug descripcion createdAt',
                )
                .exec();
              return { ...area, permisos };
            }),
          );
          return { ...modulo, items: itemsWithPermisos };
        }),
      );
      return handleMessageSucces(modulosAreasPermisos, 'findAll');
    } catch (error) {
      throw handleValidationError(error);
    }
  }
}