Skip to content
Snippets Groups Projects
admin.controller.ts 7.44 KiB
import { ApiOperation, ApiParam } from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import {
  Body,
  Delete,
  Param,
  Controller,
  Get,
  Post,
  UseGuards,
  HttpStatus,
  HttpException,
  Logger,
} from '@nestjs/common';
import { NewsletterSubscription } from '../newsletter/newsletter-subscription.schema';
import { NewsletterService } from '../newsletter/newsletter.service';
import { StructuresService } from '../structures/services/structures.service';
import { Roles } from '../users/decorators/roles.decorator';
import { RolesGuard } from '../users/guards/roles.guard';
import { UsersService } from '../users/users.service';
import { PendingStructureDto } from './dto/pending-structure.dto';
import { validate } from 'class-validator';
import { Structure } from '../structures/schemas/structure.schema';

@Controller('admin')
export class AdminController {
  private readonly logger = new Logger(AdminController.name);
  constructor(
    private usersService: UsersService,
    private structuresService: StructuresService,
    private newsletterService: NewsletterService
  ) {}

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles('admin')
  @Get('pendingStructures')
  @ApiOperation({ description: 'Get pending structre for validation' })
  public async getPendingAttachments(): Promise<PendingStructureDto[]> {
    const pendingStructure = await this.usersService.getPendingStructures();
    return Promise.all(
      pendingStructure.map(async (structure) => {
        structure.structureName = (await this.structuresService.findOne(structure.structureId)).structureName;
        return structure;
      })
    );
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles('admin')
  @Get('adminStructuresList')
  @ApiOperation({ description: 'Get pending structre for validation' })
  public async getAdminStructuresList(): Promise<any> {
    const structuresList = { claimed: [], inClaim: [], toClaim: [], incomplete: [] };
    structuresList.inClaim = await this.getPendingAttachments();
    structuresList.toClaim = (await this.structuresService.findAllUnclaimed()).filter(
      (demand) => !structuresList.inClaim.find((elem) => elem.structureId == demand.structureId)
    );
    const allStructures = await this.structuresService.findAll();
    structuresList.claimed = allStructures
      .filter(
        (demand) =>
          !structuresList.inClaim.find((elem) => elem.structureId == demand.id) &&
          !structuresList.toClaim.find((elem) => elem.structureId == demand.id)
      )
      .map((structure) => {
        return { structureId: structure.id, structureName: structure.structureName };
      });
    structuresList.incomplete = await Promise.all(
      allStructures.map(async (struct) => {
        const validity = await validate(new Structure(struct));
        if (validity.length > 0) {
          this.logger.debug(`getAdminStructuresList - validation failed. errors: ${validity.toString()}`);
          return { structureId: struct.id, structureName: struct.structureName };
        } else {
          this.logger.debug('getAdminStructuresList - validation succeed');
          return null;
        }
      })
    );
    structuresList.incomplete = structuresList.incomplete.filter((structure) => structure);
    structuresList.claimed.sort((a, b) => a.structureName.localeCompare(b.structureName));
    structuresList.inClaim.sort((a, b) => a.structureName.localeCompare(b.structureName));
    structuresList.toClaim.sort((a, b) => a.structureName.localeCompare(b.structureName));
    structuresList.incomplete.sort((a, b) => a.structureName.localeCompare(b.structureName));
    return structuresList;
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles('admin')
  @Post('validatePendingStructure')
  @ApiOperation({ description: 'Validate structure ownership' })
  public async validatePendingStructure(@Body() pendingStructureDto: PendingStructureDto) {
    const structure = await this.structuresService.findOne(pendingStructureDto.structureId);
    if (!structure || structure.deletedAt) {
      throw new HttpException('Structure does not exist', HttpStatus.NOT_FOUND);
    }
    await this.usersService.validatePendingStructure(
      pendingStructureDto.userEmail,
      pendingStructureDto.structureId,
      structure.structureName,
      true
    );
    const pendingStructure = await this.usersService.getPendingStructures();
    return Promise.all(
      pendingStructure.map(async (pendingStructureData) => {
        pendingStructureData.structureName = (
          await this.structuresService.findOne(pendingStructureData.structureId)
        ).structureName;
        return pendingStructureData;
      })
    );
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles('admin')
  @Post('rejectPendingStructure')
  @ApiOperation({ description: 'Refuse structure ownership' })
  public async refusePendingStructure(@Body() pendingStructureDto: PendingStructureDto) {
    const structure = await this.structuresService.findOne(pendingStructureDto.structureId);
    if (!structure || structure.deletedAt) {
      throw new HttpException('Structure does not exist', HttpStatus.NOT_FOUND);
    }
    await this.usersService.validatePendingStructure(
      pendingStructureDto.userEmail,
      pendingStructureDto.structureId,
      structure.structureName,
      false
    );
    const pendingStructure = await this.usersService.getPendingStructures();
    return Promise.all(
      pendingStructure.map(async (pendingStructureData) => {
        pendingStructureData.structureName = (
          await this.structuresService.findOne(pendingStructureData.structureId)
        ).structureName;
        return pendingStructureData;
      })
    );
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles('admin')
  @Delete('user/:id')
  @ApiParam({ name: 'id', type: String, required: true })
  public async deleteUser(@Param() params) {
    const user = await this.usersService.deleteOneId(params.id);
    user.structuresLink.forEach((structureId) => {
      this.usersService.isStructureClaimed(structureId.toString()).then((userFound) => {
        if (!userFound) {
          this.structuresService.deleteOne(structureId.toString());
        }
      });
    });
    return user;
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles('admin')
  @Post('searchUsers')
  public async searchUsers(@Body() searchString: { searchString: string }) {
    if (searchString && searchString.searchString && searchString.searchString.length > 0)
      return this.usersService.searchUsers(searchString.searchString);
    else return this.usersService.findAll();
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles('admin')
  @Post('searchNewsletterSubscriptions')
  public async getNewsletterSubscriptions(@Body() searchString: { searchString: string }) {
    if (searchString && searchString.searchString && searchString.searchString.length > 0)
      return this.newsletterService.searchNewsletterSubscription(searchString.searchString);
    else return this.newsletterService.findAll();
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles('admin')
  @Get('countNewsletterSubscriptions')
  public async countNewsletterSubscriptions(): Promise<number> {
    return this.newsletterService.countNewsletterSubscriptions();
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles('admin')
  @Delete('newsletterSubscription/:email')
  @ApiParam({ name: 'email', type: String, required: true })
  public async unsubscribeUserFromNewsletter(@Param() params): Promise<NewsletterSubscription> {
    return this.newsletterService.deleteOneEmail(params.email);
  }
}