File

src/client/client.service.ts

Index

Methods

Constructor

constructor(clientRepository: Repository<Client>, entityManager: EntityManager, applicationClientRepository: Repository<ApplicationClient>, applicationRepository: Repository<Application>, observationRepository: Repository<Observation>, keycloakApiService: KeycloakApiService, authApiService: AuthApiService, httpService: HttpService)
Parameters :
Name Type Optional
clientRepository Repository<Client> No
entityManager EntityManager No
applicationClientRepository Repository<ApplicationClient> No
applicationRepository Repository<Application> No
observationRepository Repository<Observation> No
keycloakApiService KeycloakApiService No
authApiService AuthApiService No
httpService HttpService No

Methods

Async addApplication
addApplication(clientId: number, body: AddApplicationClientBody)
Parameters :
Name Type Optional
clientId number No
body AddApplicationClientBody No
Returns : unknown
Async addApplicationForBulkRegistration
addApplicationForBulkRegistration(clientId: number, body: AddApplicationClientBody)
Parameters :
Name Type Optional
clientId number No
body AddApplicationClientBody No
Returns : unknown
Async addConversionType
addConversionType(body: AddConversionTypeBody, token: string)
Parameters :
Name Type Optional
body AddConversionTypeBody No
token string No
Returns : unknown
Async addObservation
addObservation(observation: ObservationDto, session: any)
Parameters :
Name Type Optional
observation ObservationDto No
session any No
Returns : unknown
Async createLevel
createLevel(body: AddLevelBody, token: string)
Parameters :
Name Type Optional
body AddLevelBody No
token string No
Returns : unknown
Async createLevelOption
createLevelOption(body: AddLevelOptionBody, token: string)
Parameters :
Name Type Optional
body AddLevelOptionBody No
token string No
Returns : unknown
Async createSecret
createSecret(name: string, clientId: number, token: string)
Parameters :
Name Type Optional
name string No
clientId number No
token string No
Returns : any
Async deleteApplication
deleteApplication(applicationId: number, clientId: number)
Parameters :
Name Type Optional
applicationId number No
clientId number No
Returns : unknown
Async deleteConversionType
deleteConversionType(body: DeleteConversionTypeBody, token: string)
Parameters :
Name Type Optional
body DeleteConversionTypeBody No
token string No
Returns : unknown
Async deleteCredential
deleteCredential(credentialId: string, clientId: number, token: string)
Parameters :
Name Type Optional
credentialId string No
clientId number No
token string No
Returns : any
Async deleteLevel
deleteLevel(body: DeleteLevelBody, token: string)
Parameters :
Name Type Optional
body DeleteLevelBody No
token string No
Returns : unknown
Async deleteLevelOption
deleteLevelOption(body: DeleteLevelOptionBody, token: string)
Parameters :
Name Type Optional
body DeleteLevelOptionBody No
token string No
Returns : unknown
Async disabledApplication
disabledApplication(applicationId: number, clientId: number)
Parameters :
Name Type Optional
applicationId number No
clientId number No
Returns : unknown
Async enabledApplication
enabledApplication(applicationId: number, clientId: number)
Parameters :
Name Type Optional
applicationId number No
clientId number No
Returns : unknown
Async enabledClient
enabledClient(id: number, client: ClientEnableDto)
Parameters :
Name Type Optional
id number No
client ClientEnableDto No
Returns : any
Async findClientByMtrixCode
findClientByMtrixCode(query: FindClientByMtrixCodeQueryDTO)
Parameters :
Name Type Optional
query FindClientByMtrixCodeQueryDTO No
Returns : unknown
Async findPaginate
findPaginate(filter: PaginateClientQueryDTO)
Parameters :
Name Type Optional
filter PaginateClientQueryDTO No
Returns : unknown
Async getApplicationsAvailableClient
getApplicationsAvailableClient(clientId: number)
Parameters :
Name Type Optional
clientId number No
Returns : unknown
getApplicationsByClientId
getApplicationsByClientId(clientId: number)
Parameters :
Name Type Optional
clientId number No
Returns : any
Async getClient
getClient()
Returns : unknown
Async getClientByName
getClientByName(name: string)
Parameters :
Name Type Optional
name string No
Returns : unknown
Async getClientCNPJ
getClientCNPJ(cnpj: string)
Parameters :
Name Type Optional
cnpj string No
Returns : unknown
Async getClientId
getClientId(id: number)
Parameters :
Name Type Optional
id number No
Returns : unknown
Async getClientIdSalesForceLevel
getClientIdSalesForceLevel(id: number)
Parameters :
Name Type Optional
id number No
Returns : unknown
Async getCompanyByClientName
getCompanyByClientName(name: string)
Parameters :
Name Type Optional
name string No
Returns : unknown
Async getConversionTypes
getConversionTypes(token: string)
Parameters :
Name Type Optional
token string No
Returns : unknown
Async getConversionTypesByClient
getConversionTypesByClient(clientId: number, token: string)
Parameters :
Name Type Optional
clientId number No
token string No
Returns : unknown
Async getCredentials
getCredentials(undefined: GetCredentials)
Parameters :
Name Type Optional
GetCredentials No
Returns : unknown
Async getLevelOptionsByCode
getLevelOptionsByCode(clientId: number, levelCode: number, token: string)
Parameters :
Name Type Optional
clientId number No
levelCode number No
token string No
Returns : unknown
Async getLevels
getLevels(clientId: number, token: string)
Parameters :
Name Type Optional
clientId number No
token string No
Returns : unknown
Async postClient
postClient(client: ClientPostDto, session: any)
Parameters :
Name Type Optional
client ClientPostDto No
session any No
Returns : unknown
Async putClient
putClient(id: number, client: ClientDto, session: any)
Parameters :
Name Type Optional
id number No
client ClientDto No
session any No
Returns : unknown
import { HttpService } from "@nestjs/axios";
import {
  BadRequestException,
  Injectable,
  NotFoundException,
} from "@nestjs/common";
import { InjectEntityManager, InjectRepository } from "@nestjs/typeorm";
import { EntityManager, ILike, IsNull, Repository } from "typeorm";
import { configENV } from '../../config-env';
import { Application } from "../entities/application";
import { ApplicationClient } from "../entities/applicationClient";
import { Client } from "../entities/client";
import { Observation } from "../entities/observation";
import { AuthApiService } from "../outbound/auth-api/auth-api.service";
import { KeycloakApiService } from "../provider/keycloak-apii/keycloak-api.service";
import { ExceptionError, GeneralException, formatName } from "../util";
import {
  AddApplicationClientBody,
  AddConversionTypeBody,
  AddLevelBody,
  AddLevelOptionBody,
  ClientDto,
  ClientEnableDto,
  ClientPostDto,
  DeleteConversionTypeBody,
  DeleteLevelBody,
  DeleteLevelOptionBody,
  FindClientByMtrixCodeQueryDTO,
  ObservationDto,
  PaginateClientQueryDTO,
} from "./dto/client.dto";
import { statusDeployment } from "src/types/statusDeployment";
const { url_product_source } = configENV;

const STATUS_ENABLE_APPLICATIONS: statusDeployment[] = [
  statusDeployment.POC,
  statusDeployment.CONTRATADO,
];

interface GetCredentials {
  clientId: number;
  realmUser: string;
  rolesUser: string[];
}

@Injectable()
export class ClientService {
  constructor(
    @InjectRepository(Client)
    private readonly clientRepository: Repository<Client>,
    @InjectEntityManager()
    private readonly entityManager: EntityManager,
    @InjectRepository(ApplicationClient)
    private applicationClientRepository: Repository<ApplicationClient>,
    @InjectRepository(Application)
    private applicationRepository: Repository<Application>,
    @InjectRepository(Observation)
    private observationRepository: Repository<Observation>,
    private readonly keycloakApiService: KeycloakApiService,
    private readonly authApiService: AuthApiService,
    private readonly httpService: HttpService
    ) {}

  async postClient(client: ClientPostDto, session: any) {
    try {
      const { observation, name, cnpj, enabled, internalCode, company ,useChannel} =
        client;

      delete client.observation;

      const clientSave = await this.clientRepository.save({
        name,
        company,
        cnpj,
        enabled,
        internalCode,
        mtrixCode: client.mtrixCode,
        type: client.type,
        useChannel,
        statusDeploymentId: client.statusDeploymentId,
      });

      const observationSave = observation
        ? await this.observationRepository.save({
            observation,
            userId: session.usuarioId,
            username: session.username,
            clientId: clientSave.id,
          })
        : undefined;
      return {
        client: {
          ...clientSave,
          observation: observationSave ? [observationSave] : [],
        },
      };
    } catch (error) {
      throw new BadRequestException(error.message);
    }
  }

  async getApplicationsAvailableClient(clientId: number) {
    const query = this.applicationRepository
      .createQueryBuilder("app")
      .where({
        exclusiveClientId: clientId,
      })
      .orWhere({
        exclusiveClientId: IsNull(),
      })
      .leftJoinAndSelect("app.translations", "translations")
      .orderBy("app.id", "ASC");

    return query.getMany();
  }

  async addApplication(clientId: number, body: AddApplicationClientBody) {
    const { applicationId } = body;

    const application = await this.applicationRepository.countBy({
      id: applicationId,
    });

    if (!application) {
      throw new NotFoundException({ messageKey: 'application_not_found' });
    }

    const client = await this.clientRepository.findOne({
      select: ['id', 'statusDeploymentId'],
      where: { id: clientId },
    });

    if (!client) {
      throw new NotFoundException({ messageKey: 'client_not_found' });
    }
    if (STATUS_ENABLE_APPLICATIONS.indexOf(client.statusDeploymentId) == -1) {
      throw new GeneralException('status_deployment_not_allows_update_apps');
    }

    const applicationClientExists =
      await this.applicationClientRepository.countBy({
        applicationId,
        clientId,
      });

    if (applicationClientExists) {
      throw new GeneralException("application_client_already_exists");
    }

    return await this.applicationClientRepository.save({
      clientId,
      applicationId,
      url: body.url,
      enabled: false,
    });
  }

  async addApplicationForBulkRegistration(clientId: number, body: AddApplicationClientBody) {
    const { applicationId } = body;

    if (!await this.applicationRepository.countBy({ id: applicationId })) {
      throw new NotFoundException({ messageKey: "application_not_found" });
    }

    if (!await this.clientRepository.countBy({ id: clientId })) {
      throw new NotFoundException({ messageKey: "client_not_found" });
    }

    const applicationClient = await this.applicationClientRepository.findOneBy({
      applicationId,
      clientId,
    });

    if (applicationClient) {
      return applicationClient
    }

    const result = await this.applicationClientRepository.save({
      clientId,
      applicationId,
      url: body.url,
      enabled: true,
    });

    await new Promise((resolv) => setTimeout(() => resolv({}), 1000))

    return result
  }

  getApplicationsByClientId(clientId: number) {
    return this.applicationClientRepository
      .createQueryBuilder("appClient")
      .where({
        clientId,
      })
      .innerJoinAndSelect("appClient.application", "application")
      .innerJoinAndSelect("application.translations", "appTranslation")
      .orderBy("appClient.id", "ASC")
      .getMany();
  }

  async enabledApplication(applicationId: number, clientId: number) {
    const client = await this.clientRepository.findOne({
      select: ['id', 'statusDeploymentId'],
      where: { id: clientId },
    });

    if (!client) {
      throw new NotFoundException({ messageKey: 'client_not_found' });
    }
    if (STATUS_ENABLE_APPLICATIONS.indexOf(client.statusDeploymentId) == -1) {
      throw new GeneralException('status_deployment_not_allows_update_apps');
    }

    const applicationClient = await this.applicationClientRepository.findOneBy({
      clientId,
      applicationId,
    });
    applicationClient.enabled = true;
    applicationClient.enabledAt = new Date();
    return await this.applicationClientRepository.save(applicationClient);
  }

  async disabledApplication(applicationId: number, clientId: number) {
    const client = await this.clientRepository.findOne({
      select: ['id', 'statusDeploymentId'],
      where: { id: clientId },
    });

    if (!client) {
      throw new NotFoundException({ messageKey: 'client_not_found' });
    }
    if (STATUS_ENABLE_APPLICATIONS.indexOf(client.statusDeploymentId) == -1) {
      throw new GeneralException('status_deployment_not_allows_update_apps');
    }

    const applicationClient = await this.applicationClientRepository.findOneBy({
      clientId,
      applicationId,
    });
    applicationClient.enabled = false;
    return await this.applicationClientRepository.save(applicationClient);
  }
  async deleteApplication(applicationId: number, clientId: number) {
    const client = await this.clientRepository.findOne({
      select: ['id', 'statusDeploymentId'],
      where: { id: clientId },
    });

    if (!client) {
      throw new NotFoundException({ messageKey: 'client_not_found' });
    }
    if (STATUS_ENABLE_APPLICATIONS.indexOf(client.statusDeploymentId) == -1) {
      throw new GeneralException('status_deployment_not_allows_update_apps');
    }

    const applicationClient = await this.applicationClientRepository.findOneBy({
      clientId,
      applicationId,
    });
    return await this.applicationClientRepository.delete(applicationClient.id);
  }
  async addObservation(observation: ObservationDto, session: any) {
    const clientExists = await this.clientRepository.countBy({
      id: observation.clientId,
    });
    if (!clientExists) {
      throw new GeneralException('client_not_found');
    }
    const appClientExists = await this.applicationClientRepository.countBy({
      clientId: observation.clientId,
      applicationId: observation.applicationId,
    });
    if (!appClientExists) {
      throw new GeneralException('application_client_not_found');
    }

    return await this.observationRepository.save({
      ...(observation as ObservationDto),
      userId: session.usuarioId,
      username: session.username,
    });
  }

  async getClient() {
    return await this.clientRepository.find({
      relations: ["application.application", "observation.application"],
    });
  }

  async getCompanyByClientName(name: string) {
    const client = await this.clientRepository.findOne({
      where: {
        name: ILike(`%${name}%`),
      },
    });

    return { name: client?.company || "" };
  }

  async getClientByName(name: string) {
    const client = await this.clientRepository.findOne({
      where: {
        name: ILike(`%${name}%`),
      },
    });

    return client;
  }

  async findPaginate(filter: PaginateClientQueryDTO) {
    const { size = 10, name } = filter;
    const page = +filter.page || 0;
    const skip = page * size;

    const queryBuilder = this.entityManager
      .createQueryBuilder(Client, "client")
      .take(size)
      .skip(skip)
      .orderBy("id");

    if (filter.name) {
      queryBuilder.where({ name: ILike("%" + name + "%") });
    }

    queryBuilder.relation("application.application");
    queryBuilder.relation("observation.application");

    const [content, total] = await queryBuilder.getManyAndCount();
    const lastPage = Math.ceil(total / size);
    const prevPage = page < 1 ? null : page;

    return {
      content,
      size: +size,
      totalElements: total,
      totalPages: lastPage,
      first: !prevPage,
      last: lastPage === page + 1,
      number: page + 1,
      numberOfElements: content.length,
    };
  }

  async getClientCNPJ(cnpj: string) {
    return await this.clientRepository.findOne({
      where: { cnpj: cnpj },
      relations: ["application.application", "observation.application"],
    });
  }

  async getClientIdSalesForceLevel(id: number) {
    const client = await this.clientRepository.findOne({
      where: { id },
      relations: [
        "salesForceLevel",
      ],
    });

    return {client, countSalesForceLevel: client.salesForceLevel.length}
  }

  async getClientId(id: number) {
    return await this.clientRepository.findOne({
      where: { id },
      relations: [
        "application.application",
        "observation.application",
        "cnpjClient",
      ],
    });
  }

  async findClientByMtrixCode(query: FindClientByMtrixCodeQueryDTO) {
    return await this.clientRepository.findOne({
      where: { mtrixCode: query.mtrixCode, type: query.clientType },
      relations: [
        "application.application",
        "observation.application",
        "cnpjClient",
      ],
    });
  }

  async putClient(id: number, client: ClientDto, session: any) {
    const clientFind = await this.clientRepository.findOne({
      where: { id },
      relations: ["observation"],
    });
    if (!clientFind) {
      throw new NotFoundException({ messageKey: "client_not_found" });
    }

    clientFind.name = client.name;
    clientFind.company = client.company;
    clientFind.enabled = client.enabled;
    clientFind.cnpj = client.cnpj;
    clientFind.internalCode = client.internalCode;
    clientFind.type = client.type;
    clientFind.mtrixCode = client.mtrixCode;
    clientFind.useChannel = client.useChannel;
    clientFind.statusDeploymentId = client.statusDeploymentId;
    await this.clientRepository.save(clientFind);
    return clientFind;
  }
  async enabledClient(id: number, client: ClientEnableDto) {
    const up = await this.clientRepository.update(id, client);
    if (!up?.affected) {
      throw new NotFoundException({ messageKey: "client_not_found" });
    }
  }

  async getCredentials({ clientId, realmUser, rolesUser }: GetCredentials) {
    const client = await this.clientRepository.findOneBy({ id: clientId });

    if (!rolesUser.map((role) => role.toUpperCase()).includes("ADMIN")) {
      throw ExceptionError("Permissão negada", 401);
    }

    const {
      data: { access_token },
    } = await this.keycloakApiService.loginWithUserMaster();

    const realmClient = formatName(client.name);

    const { data } = await this.keycloakApiService.getCredentialsByRealm(
      realmClient,
      access_token
    );

    const credentials = data
      .filter(
        (credential) =>
          credential.secret && credential.clientId.includes("-app")
      )
      .map((credential) => ({
        id: credential.id,
        name: credential.clientId,
        secret: credential.secret,
      }));

    return credentials;
  }

  async createSecret(name: string, clientId: number, token: string) {
    const client = await this.clientRepository.findOneBy({ id: clientId });

    const realmClient = formatName(client.name);

    await this.authApiService.createSecret(name, realmClient, token);
  }

  async deleteCredential(
    credentialId: string,
    clientId: number,
    token: string
  ) {
    const client = await this.clientRepository.findOneBy({ id: clientId });

    const realmClient = formatName(client.name);

    await this.authApiService.deleteCredential(
      credentialId,
      realmClient,
      token
    );
  }

  async getLevels(clientId: number, token: string) {
    const client = await this.clientRepository.findOneBy({ id: clientId });
    if (!client) throw new NotFoundException({ messageKey: "client_not_found" });
    if (!client.mtrixCode || !client.type) throw new NotFoundException({ messageKey: "invalid_client" });

    const response = await this.httpService.axiosRef.get(`${url_product_source}/source/personCode/${client.type}/${client.mtrixCode}`, {
      headers: {
        Authorization: `Bearer ${token}`
      },
    })

    return response.data
  }

  async createLevel(body: AddLevelBody, token: string) {
    const client = await this.clientRepository.findOneBy({ id: body.clientId });
    if (!client) throw new NotFoundException({ messageKey: "client_not_found" });
    if (!client.mtrixCode || !client.type) throw new NotFoundException({ messageKey: "invalid_client" });

    const response = await this.httpService.axiosRef.post(`${url_product_source}/product/sourceCode/productSourceLevelType`, {
      levelName: body.levelName,
      typePerson: client.type,
      typePersonCode: client.mtrixCode
    }, {
      headers: {
        Authorization: `Bearer ${token}`
      },
    })

    return response.data
  }

  async deleteLevel(body: DeleteLevelBody, token: string) {
    const client = await this.clientRepository.findOneBy({ id: body.clientId });
    if (!client) throw new NotFoundException({ messageKey: "client_not_found" });
    if (!client.mtrixCode || !client.type) throw new NotFoundException({ messageKey: "invalid_client" });

    const response = await this.httpService.axiosRef.delete(`${url_product_source}/product/sourceCode/productSourceLevelType`, {
      headers: {
        Authorization: `Bearer ${token}`
      },
      data: {
        levelCode: body.levelCode,
        typePerson: client.type,
        typePersonCode: client.mtrixCode
      }
    })

    return response.data
  }

  async deleteLevelOption(body: DeleteLevelOptionBody, token: string) {
    const client = await this.clientRepository.findOneBy({ id: body.clientId });
    if (!client) throw new NotFoundException({ messageKey: "client_not_found" });
    if (!client.mtrixCode || !client.type) throw new NotFoundException({ messageKey: "invalid_client" });

    const response = await this.httpService.axiosRef.delete(`${url_product_source}/product/sourceCode/productSourceLevel`, {
      headers: {
        Authorization: `Bearer ${token}`
      },
      data: {
        levelCode: body.levelCode,
        productSourceLevelCode: body.levelOptionCode,
        typePerson: client.type,
        typePersonCode: client.mtrixCode
      }
    })

    return response.data
  }

  async createLevelOption(body: AddLevelOptionBody, token: string) {
    const client = await this.clientRepository.findOneBy({ id: body.clientId });
    if (!client) throw new NotFoundException({ messageKey: "client_not_found" });
    if (!client.mtrixCode || !client.type) throw new NotFoundException({ messageKey: "invalid_client" });

    const response = await this.httpService.axiosRef.post(`${url_product_source}/product/sourceCode/productSourceLevel`, {
      levelCode: body.levelCode,
      productLevelName: body.levelName,
      typePersonCode: client.mtrixCode,
      typePerson: client.type
    }, {
      headers: {
        Authorization: `Bearer ${token}`
      },
    })

    return response.data
  }

  async getLevelOptionsByCode(clientId: number, levelCode: number, token: string) {
    const client = await this.clientRepository.findOneBy({ id: clientId });
    if (!client) throw new NotFoundException({ messageKey: "client_not_found" });
    if (!client.mtrixCode || !client.type) throw new NotFoundException({ messageKey: "invalid_client" });

    const response = await this.httpService.axiosRef.get(`${url_product_source}/product/productSourceLevel`, {
      headers: {
        Authorization: `Bearer ${token}`
      },
      params: {
        typePerson: client.type,
        typePersonCode: client.mtrixCode,
        levelCode,
      }
    })

    return response.data
  }

  async getConversionTypes(token: string) {
    const conversionTypes = await this.httpService.axiosRef.get(`${url_product_source}/conversionType`, {
      headers: {
        Authorization: `Bearer ${token}`
      },
    })

    return conversionTypes.data
  }

  async addConversionType(body: AddConversionTypeBody, token: string) {
    const client = await this.clientRepository.findOneBy({ id: body.clientId });
    if (!client) throw new NotFoundException({ messageKey: "client_not_found" });
    if (!client.mtrixCode || !client.type) throw new NotFoundException({ messageKey: "invalid_client" });

    const response = await this.httpService.axiosRef.post(`${url_product_source}/conversionType/source`, {
      typePersonCode: client.mtrixCode,
      typePerson: client.type,
      conversionTypeId: body.conversionTypeId,
      conversionTypeName: body.conversionTypeName,
      conversaoFactor: body.conversaoFactor,
    }, {
      headers: {
        Authorization: `Bearer ${token}`
      },
    })

    return response.data
  }

  async deleteConversionType(body: DeleteConversionTypeBody, token: string) {
    const client = await this.clientRepository.findOneBy({ id: body.clientId });
    if (!client) throw new NotFoundException({ messageKey: "client_not_found" });
    if (!client.mtrixCode || !client.type) throw new NotFoundException({ messageKey: "invalid_client" });

    const response = await this.httpService.axiosRef.delete(`${url_product_source}/conversionType/source`, {
      headers: {
        Authorization: `Bearer ${token}`
      },
      params: {
        typePersonCode: client.mtrixCode,
        typePerson: client.type,
        conversionTypeId: body.conversionTypeId,
      }
    })

    return response.data
  }

  async getConversionTypesByClient(clientId: number, token: string) {
    const client = await this.clientRepository.findOneBy({ id: clientId });
    if (!client) throw new NotFoundException({ messageKey: "client_not_found" });
    if (!client.mtrixCode || !client.type) throw new NotFoundException({ messageKey: "invalid_client" });

    const response = await this.httpService.axiosRef.get(`${url_product_source}/conversionType/typePerson`, {
      headers: {
        Authorization: `Bearer ${token}`
      },
      params: {
        typePersonCode: client.mtrixCode,
        typePerson: client.type
      }
    })

    return response.data
  }
}

results matching ""

    No results matching ""