src/client/client.service.ts
Methods |
|
constructor(clientRepository: Repository<Client>, entityManager: EntityManager, applicationClientRepository: Repository<ApplicationClient>, applicationRepository: Repository<Application>, observationRepository: Repository<Observation>, keycloakApiService: KeycloakApiService, authApiService: AuthApiService, httpService: HttpService)
|
|||||||||||||||||||||||||||
Defined in src/client/client.service.ts:47
|
|||||||||||||||||||||||||||
Parameters :
|
Async addApplication | |||||||||
addApplication(clientId: number, body: AddApplicationClientBody)
|
|||||||||
Defined in src/client/client.service.ts:117
|
|||||||||
Parameters :
Returns :
unknown
|
Async addApplicationForBulkRegistration | |||||||||
addApplicationForBulkRegistration(clientId: number, body: AddApplicationClientBody)
|
|||||||||
Defined in src/client/client.service.ts:158
|
|||||||||
Parameters :
Returns :
unknown
|
Async addConversionType | |||||||||
addConversionType(body: AddConversionTypeBody, token: string)
|
|||||||||
Defined in src/client/client.service.ts:588
|
|||||||||
Parameters :
Returns :
unknown
|
Async addObservation | |||||||||
addObservation(observation: ObservationDto, session: any)
|
|||||||||
Defined in src/client/client.service.ts:263
|
|||||||||
Parameters :
Returns :
unknown
|
Async createLevel | |||||||||
createLevel(body: AddLevelBody, token: string)
|
|||||||||
Defined in src/client/client.service.ts:483
|
|||||||||
Parameters :
Returns :
unknown
|
Async createLevelOption | |||||||||
createLevelOption(body: AddLevelOptionBody, token: string)
|
|||||||||
Defined in src/client/client.service.ts:540
|
|||||||||
Parameters :
Returns :
unknown
|
Async createSecret |
createSecret(name: string, clientId: number, token: string)
|
Defined in src/client/client.service.ts:445
|
Returns :
any
|
Async deleteApplication |
deleteApplication(applicationId: number, clientId: number)
|
Defined in src/client/client.service.ts:244
|
Returns :
unknown
|
Async deleteConversionType | |||||||||
deleteConversionType(body: DeleteConversionTypeBody, token: string)
|
|||||||||
Defined in src/client/client.service.ts:608
|
|||||||||
Parameters :
Returns :
unknown
|
Async deleteCredential |
deleteCredential(credentialId: string, clientId: number, token: string)
|
Defined in src/client/client.service.ts:453
|
Returns :
any
|
Async deleteLevel | |||||||||
deleteLevel(body: DeleteLevelBody, token: string)
|
|||||||||
Defined in src/client/client.service.ts:501
|
|||||||||
Parameters :
Returns :
unknown
|
Async deleteLevelOption | |||||||||
deleteLevelOption(body: DeleteLevelOptionBody, token: string)
|
|||||||||
Defined in src/client/client.service.ts:520
|
|||||||||
Parameters :
Returns :
unknown
|
Async disabledApplication |
disabledApplication(applicationId: number, clientId: number)
|
Defined in src/client/client.service.ts:224
|
Returns :
unknown
|
Async enabledApplication |
enabledApplication(applicationId: number, clientId: number)
|
Defined in src/client/client.service.ts:202
|
Returns :
unknown
|
Async enabledClient | |||||||||
enabledClient(id: number, client: ClientEnableDto)
|
|||||||||
Defined in src/client/client.service.ts:406
|
|||||||||
Parameters :
Returns :
any
|
Async findClientByMtrixCode | ||||||
findClientByMtrixCode(query: FindClientByMtrixCodeQueryDTO)
|
||||||
Defined in src/client/client.service.ts:374
|
||||||
Parameters :
Returns :
unknown
|
Async findPaginate | ||||||
findPaginate(filter: PaginateClientQueryDTO)
|
||||||
Defined in src/client/client.service.ts:311
|
||||||
Parameters :
Returns :
unknown
|
Async getApplicationsAvailableClient | ||||||
getApplicationsAvailableClient(clientId: number)
|
||||||
Defined in src/client/client.service.ts:102
|
||||||
Parameters :
Returns :
unknown
|
getApplicationsByClientId | ||||||
getApplicationsByClientId(clientId: number)
|
||||||
Defined in src/client/client.service.ts:190
|
||||||
Parameters :
Returns :
any
|
Async getClient |
getClient()
|
Defined in src/client/client.service.ts:285
|
Returns :
unknown
|
Async getClientByName | ||||||
getClientByName(name: string)
|
||||||
Defined in src/client/client.service.ts:301
|
||||||
Parameters :
Returns :
unknown
|
Async getClientCNPJ | ||||||
getClientCNPJ(cnpj: string)
|
||||||
Defined in src/client/client.service.ts:345
|
||||||
Parameters :
Returns :
unknown
|
Async getClientId | ||||||
getClientId(id: number)
|
||||||
Defined in src/client/client.service.ts:363
|
||||||
Parameters :
Returns :
unknown
|
Async getClientIdSalesForceLevel | ||||||
getClientIdSalesForceLevel(id: number)
|
||||||
Defined in src/client/client.service.ts:352
|
||||||
Parameters :
Returns :
unknown
|
Async getCompanyByClientName | ||||||
getCompanyByClientName(name: string)
|
||||||
Defined in src/client/client.service.ts:291
|
||||||
Parameters :
Returns :
unknown
|
Async getConversionTypes | ||||||
getConversionTypes(token: string)
|
||||||
Defined in src/client/client.service.ts:578
|
||||||
Parameters :
Returns :
unknown
|
Async getConversionTypesByClient |
getConversionTypesByClient(clientId: number, token: string)
|
Defined in src/client/client.service.ts:627
|
Returns :
unknown
|
Async getCredentials | |||||
getCredentials(undefined: GetCredentials)
|
|||||
Defined in src/client/client.service.ts:413
|
|||||
Parameters :
Returns :
unknown
|
Async getLevelOptionsByCode |
getLevelOptionsByCode(clientId: number, levelCode: number, token: string)
|
Defined in src/client/client.service.ts:559
|
Returns :
unknown
|
Async getLevels |
getLevels(clientId: number, token: string)
|
Defined in src/client/client.service.ts:469
|
Returns :
unknown
|
Async postClient | |||||||||
postClient(client: ClientPostDto, session: any)
|
|||||||||
Defined in src/client/client.service.ts:64
|
|||||||||
Parameters :
Returns :
unknown
|
Async putClient |
putClient(id: number, client: ClientDto, session: any)
|
Defined in src/client/client.service.ts:385
|
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
}
}