Refactor code structure for improved readability and maintainability
Deploy NestJS API / build-and-push-deploy (push) Failing after 1m34s Details

This commit is contained in:
joelson 2026-01-08 18:43:22 -03:00
parent 4e926909b8
commit 94f9208ee4
2 changed files with 802 additions and 705 deletions

View File

@ -1,109 +1,148 @@
import { Body, Controller, Get, HttpException, HttpStatus, Param, Post, Query } from '@nestjs/common'; import {
import { CustomerService } from './customer.service'; Body,
import { ResultModel } from '../../domain/models/result.model'; Controller,
Get,
HttpException,
HttpStatus,
Param,
Post,
Query,
} from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { error } from 'console'; import { error } from 'console';
import { Customer } from 'src/domain/models/customer.model'; import { Customer } from 'src/domain/models/customer.model';
import { ApiTags } from '@nestjs/swagger'; import { ResultModel } from '../../domain/models/result.model';
import { CustomerService } from './customer.service';
@ApiTags('Customer') @ApiTags('Customer')
@Controller('api/v1/customer') @Controller('api/v1/customer')
export class CustomerController { export class CustomerController {
constructor(private readonly customerService: CustomerService) {}
constructor(private readonly customerService: CustomerService){}
@Get(':name') @Get(':name')
async getCustomerByName(@Param('name') name: string){ async getCustomerByName(@Param('name') name: string) {
try{ try {
const customers = await this.customerService.findCustomerByName(name); const customers = await this.customerService.findCustomerByName(name);
return new ResultModel(true, null, customers, null); return new ResultModel(true, null, customers, null);
} catch(err){ } catch (err) {
throw new HttpException(new ResultModel(false, 'Não foi possível consultar o cadastro de clientes.', {}, error), throw new HttpException(
HttpStatus.INTERNAL_SERVER_ERROR); new ResultModel(
false,
'Não foi possível consultar o cadastro de clientes.',
{},
error,
),
HttpStatus.INTERNAL_SERVER_ERROR,
);
} }
} }
@Get('categories/fechAll') @Get('categories/fechAll')
async getCategories(){ async getCategories() {
try{ try {
const categories = await this.customerService.getCategory(); const categories = await this.customerService.getCategory();
return categories; return categories;
} catch(err){ } catch (err) {
throw new HttpException(new ResultModel(false, err.message, {}, error), throw new HttpException(
HttpStatus.INTERNAL_SERVER_ERROR); new ResultModel(false, err.message, {}, error),
HttpStatus.INTERNAL_SERVER_ERROR,
);
} }
} }
@Get('subcategories/fechAll') @Get('subcategories/fechAll')
async getSubCategories(){ async getSubCategories() {
try{ try {
const subCategories = await this.customerService.getSubCategory(); const subCategories = await this.customerService.getSubCategory();
return subCategories; return subCategories;
} catch(err){ } catch (err) {
throw new HttpException(new ResultModel(false, err.message, {}, error), throw new HttpException(
HttpStatus.INTERNAL_SERVER_ERROR); new ResultModel(false, err.message, {}, error),
HttpStatus.INTERNAL_SERVER_ERROR,
);
} }
} }
@Get() @Get()
async getCustomer(@Query() query){ async getCustomer(@Query() query) {
try{ try {
const field = query['field']; const field = query['field'];
const textSearch = query['textsearch']; const textSearch = query['textsearch'];
const customers = await this.customerService.findCustomerByQuery(field, textSearch); const customers = await this.customerService.findCustomerByQuery(
field,
textSearch,
);
return new ResultModel(true, null, customers, null); return new ResultModel(true, null, customers, null);
} catch(err){ } catch (err) {
// 'Não foi possível consultar o cadastro de clientes.' // 'Não foi possível consultar o cadastro de clientes.'
throw new HttpException(new ResultModel(false, err.message, {}, error), throw new HttpException(
HttpStatus.INTERNAL_SERVER_ERROR); new ResultModel(false, err.message, {}, error),
HttpStatus.INTERNAL_SERVER_ERROR,
);
} }
} }
@Get(':id') @Get(':id')
async getCustomerById(@Param('id') id: number){ async getCustomerById(@Param('id') id: number) {
try{ try {
const customers = await this.customerService.findCustomerById(id); const customers = await this.customerService.findCustomerById(id);
return new ResultModel(true, null, customers, null); return new ResultModel(true, null, customers, null);
} catch(err){ } catch (err) {
throw new HttpException(new ResultModel(false, 'Não foi possível consultar o cadastro de clientes.', {}, error), throw new HttpException(
HttpStatus.INTERNAL_SERVER_ERROR); new ResultModel(
false,
'Não foi possível consultar o cadastro de clientes.',
{},
error,
),
HttpStatus.INTERNAL_SERVER_ERROR,
);
} }
} }
@Get('cpf/:cpf') @Get('cpf/:cpf')
async getCustomerByCpf(@Param('cpf') cpf: string){ async getCustomerByCpf(@Param('cpf') cpf: string) {
try{ try {
console.log("pesquisando por cpf"); console.log('pesquisando por cpf');
const customer = await this.customerService.findCustomerByCpf(cpf); const customer = await this.customerService.findCustomerByCpf(cpf);
if (!customer) return new ResultModel(false, 'Cliente não cadastrado', null, null); if (!customer)
return new ResultModel(false, 'Cliente não cadastrado', null, null);
return new ResultModel(true, null, customer, null); return new ResultModel(true, null, customer, null);
} catch(err){ } catch (err) {
throw new HttpException(new ResultModel(false, 'Não foi possível consultar o cadastro de clientes.', {}, error), throw new HttpException(
HttpStatus.INTERNAL_SERVER_ERROR); new ResultModel(
false,
'Não foi possível consultar o cadastro de clientes.',
{},
error,
),
HttpStatus.INTERNAL_SERVER_ERROR,
);
} }
} }
@Get('create/proxnumcli') @Get('create/proxnumcli')
async IdCustomer(){ async IdCustomer() {
try{ try {
console.log('proxnumcli'); console.log('proxnumcli');
const id = await this.customerService.generateIdCustomer(); const id = await this.customerService.generateIdCustomer();
return new ResultModel(true, null, id, null); return new ResultModel(true, null, id, null);
} catch(err){ } catch (err) {
throw err; throw err;
} }
} }
@Post('create') @Post('create')
async createCustomer(@Body() customer: Customer){ async createCustomer(@Body() customer: Customer) {
try{ try {
console.log(customer); console.log(customer);
const result = await this.customerService.createCustomer(customer); const result = await this.customerService.createCustomer(customer);
return new ResultModel(true, null, result, null); return new ResultModel(true, null, result, null);
//return new ResultModel(true, null, id, null); //return new ResultModel(true, null, id, null);
} catch(err){ } catch (err) {
throw new HttpException(new ResultModel(false, 'Erro ao cadastrar cliente.', {}, err), throw new HttpException(
HttpStatus.INTERNAL_SERVER_ERROR); new ResultModel(false, 'Erro ao cadastrar cliente.', {}, err),
HttpStatus.INTERNAL_SERVER_ERROR,
);
} }
} }
} }

View File

@ -1,28 +1,26 @@
import { HttpStatus } from '@nestjs/common'; import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { Injectable, HttpException } from '@nestjs/common'; import { Connection } from 'typeorm';
import { connectionOptions } from '../../configs/typeorm.config'; import { connectionOptions } from '../../configs/typeorm.config';
import { Customer } from '../../domain/models/customer.model'; import { Customer } from '../../domain/models/customer.model';
import { Connection } from 'typeorm';
//import { DataSource } from 'typeorm'; //import { DataSource } from 'typeorm';
import { EntityManager } from 'typeorm';
import { Pcclient } from '../../domain/entity/tables/pcclient.entity';
import { Estcategoriacliente } from '../../domain/entity/tables/estcategoriacliente.entity'; import { Estcategoriacliente } from '../../domain/entity/tables/estcategoriacliente.entity';
import { Estsubcategoriacliente } from '../../domain/entity/tables/estsubcategoriacliente.entity'; import { Estsubcategoriacliente } from '../../domain/entity/tables/estsubcategoriacliente.entity';
import { Pcclient } from '../../domain/entity/tables/pcclient.entity';
@Injectable() @Injectable()
export class CustomerService { export class CustomerService {
async findCustomerByName(name: string) { async findCustomerByName(name: string) {
let auxName = ''; let auxName = '';
for (let i = 0; i < name.length; i++) { for (let i = 0; i < name.length; i++) {
auxName += name[i].replace("@", "%"); auxName += name[i].replace('@', '%');
} }
const connection = new Connection(connectionOptions); const connection = new Connection(connectionOptions);
await connection.connect(); await connection.connect();
const queryRunner = connection.createQueryRunner(); const queryRunner = connection.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
try { try {
const sql = ' SELECT pcclient.cliente as "name" ' + const sql =
' SELECT pcclient.cliente as "name" ' +
' ,pcclient.codcli as "customerId" ' + ' ,pcclient.codcli as "customerId" ' +
' ,pcclient.emailnfe as "email" ' + ' ,pcclient.emailnfe as "email" ' +
' ,pcclient.cgcent as "cpfCnpj" ' + ' ,pcclient.cgcent as "cpfCnpj" ' +
@ -52,17 +50,22 @@ export class CustomerService {
' ,pcclient.tipoendereco as "addressType" ' + ' ,pcclient.tipoendereco as "addressType" ' +
' FROM pcclient, pccidade ' + ' FROM pcclient, pccidade ' +
' WHERE pcclient.codcidade = pccidade.codcidade (+)'; ' WHERE pcclient.codcidade = pccidade.codcidade (+)';
let where = ` AND ( pcclient.cliente like '%'||'${auxName.replace('@', '%')}'||'%' OR ` + let where =
` AND ( pcclient.cliente like '%'||'${auxName.replace(
'@',
'%',
)}'||'%' OR ` +
` REGEXP_REPLACE(pcclient.cgcent, '[^0-9]', '') = REGEXP_REPLACE('${name}', '[^0-9]') OR ` + ` REGEXP_REPLACE(pcclient.cgcent, '[^0-9]', '') = REGEXP_REPLACE('${name}', '[^0-9]') OR ` +
` pcclient.codcli = REGEXP_REPLACE('${name}', '[^0-9]') )`; ` pcclient.codcli = REGEXP_REPLACE('${name}', '[^0-9]') )`;
where += ` AND pcclient.codcli NOT IN (2) AND pcclient.DTEXCLUSAO IS NULL `; where += ` AND pcclient.codcli NOT IN (2) AND pcclient.DTEXCLUSAO IS NULL `;
const orderBy = ` ORDER BY pcclient.cliente `; const orderBy = ` ORDER BY pcclient.cliente `;
const pagination = ` OFFSET 0 ROWS FETCH NEXT 100 ROWS ONLY`; const pagination = ` OFFSET 0 ROWS FETCH NEXT 100 ROWS ONLY`;
const customers = await queryRunner.manager const customers = (await queryRunner.manager.query(
.query(sql + where + orderBy + pagination) as Customer[]; sql + where + orderBy + pagination,
let customerList: Customer[] = []; )) as Customer[];
const customerList: Customer[] = [];
for (let i = 0; i < customers.length; i++) { for (let i = 0; i < customers.length; i++) {
let customer = customers[i]; const customer = customers[i];
const place = await queryRunner.query(`SELECT PCPRACA.CODPRACA as "placeId" const place = await queryRunner.query(`SELECT PCPRACA.CODPRACA as "placeId"
,PCPRACA.PRACA as "name" ,PCPRACA.PRACA as "name"
FROM PCPRACA FROM PCPRACA
@ -87,7 +90,8 @@ export class CustomerService {
const queryRunner = connection.createQueryRunner(); const queryRunner = connection.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
try { try {
const sql = ' SELECT pcclient.cliente as "name" ' + const sql =
' SELECT pcclient.cliente as "name" ' +
' ,pcclient.codcli as "customerId" ' + ' ,pcclient.codcli as "customerId" ' +
' ,pcclient.emailnfe as "email" ' + ' ,pcclient.emailnfe as "email" ' +
' ,pcclient.cgcent as "cpfCnpj" ' + ' ,pcclient.cgcent as "cpfCnpj" ' +
@ -115,11 +119,12 @@ export class CustomerService {
' ,pcclient.codmunicipio as "ibgeCode" ' + ' ,pcclient.codmunicipio as "ibgeCode" ' +
' ,pcclient.codcidade as "cityId" ' + ' ,pcclient.codcidade as "cityId" ' +
' ,pcclient.tipoendereco as "addressType" ' + ' ,pcclient.tipoendereco as "addressType" ' +
' ,DECODE(pcclient.dtexclusao, NULL, 1, 0) as "deletedCustomer" ' +
' FROM pcclient, pccidade ' + ' FROM pcclient, pccidade ' +
' WHERE pcclient.codcidade = pccidade.codcidade (+)'; ' WHERE pcclient.codcidade = pccidade.codcidade (+)';
const where = ` AND REGEXP_REPLACE(pcclient.cgcent, '[^0-9]', '') =REGEXP_REPLACE('${cpf}', '[^0-9]', '')`; const where = ` AND REGEXP_REPLACE(pcclient.cgcent, '[^0-9]', '') =REGEXP_REPLACE('${cpf}', '[^0-9]', '')`;
const customer = await queryRunner.query(sql + where); const customer = await queryRunner.query(sql + where);
return customer[0]; return customer as Customer[];
} catch (error) { } catch (error) {
console.log(error); console.log(error);
throw error; throw error;
@ -135,8 +140,8 @@ export class CustomerService {
const queryRunner = connection.createQueryRunner(); const queryRunner = connection.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
try { try {
const sql =
const sql = ' SELECT pcclient.cliente as "name" ' + ' SELECT pcclient.cliente as "name" ' +
' ,pcclient.codcli as "customerId" ' + ' ,pcclient.codcli as "customerId" ' +
' ,pcclient.emailnfe as "email" ' + ' ,pcclient.emailnfe as "email" ' +
' ,pcclient.cgcent as "cpfCnpj" ' + ' ,pcclient.cgcent as "cpfCnpj" ' +
@ -173,7 +178,7 @@ export class CustomerService {
FROM PCPRACA FROM PCPRACA
WHERE PCPRACA.CODPRACA = ${customer[0].placeId}`); WHERE PCPRACA.CODPRACA = ${customer[0].placeId}`);
return {...customer[0], place: place[0]}; return { ...customer[0], place: place[0] };
} catch (error) { } catch (error) {
console.log(error); console.log(error);
throw error; throw error;
@ -184,25 +189,37 @@ export class CustomerService {
} }
async findCustomerByQuery(field: string, textSearch: string) { async findCustomerByQuery(field: string, textSearch: string) {
let where = ""; let where = '';
switch (field) { switch (field) {
case "name": case 'name':
where += "\"pcclient\".cliente like '" + textSearch + "%'"; where += '"pcclient".cliente like \'' + textSearch + "%'";
break; break;
case "document": case 'document':
where += "REGEXP_REPLACE(\"pcclient\".cgcent, '[^0-9]', '') = REGEXP_REPLACE('" + textSearch + "', '[^0-9]', '')"; where +=
"REGEXP_REPLACE(\"pcclient\".cgcent, '[^0-9]', '') = REGEXP_REPLACE('" +
textSearch +
"', '[^0-9]', '')";
break; break;
case "phone": case 'phone':
where += "REGEXP_REPLACE(\"pcclient\".telent, '[^0-9]', '') = REGEXP_REPLACE('" + textSearch + "', '[^0-9]', '')"; where +=
"REGEXP_REPLACE(\"pcclient\".telent, '[^0-9]', '') = REGEXP_REPLACE('" +
textSearch +
"', '[^0-9]', '')";
break; break;
case "cellphone": case 'cellphone':
where += "REGEXP_REPLACE(\"pcclient\".telcelent, '[^0-9]', '') = REGEXP_REPLACE('" + textSearch + "', '[^0-9]', '')"; where +=
"REGEXP_REPLACE(\"pcclient\".telcelent, '[^0-9]', '') = REGEXP_REPLACE('" +
textSearch +
"', '[^0-9]', '')";
break; break;
case "customerId": case 'customerId':
where += "\"pcclient\".codcli = " + textSearch; where += '"pcclient".codcli = ' + textSearch;
break; break;
default: default:
throw new HttpException('Não foi informado um campo válido para pesquisa.', HttpStatus.BAD_REQUEST); throw new HttpException(
'Não foi informado um campo válido para pesquisa.',
HttpStatus.BAD_REQUEST,
);
} }
const connection = new Connection(connectionOptions); const connection = new Connection(connectionOptions);
@ -213,31 +230,33 @@ export class CustomerService {
const customers = await queryRunner.manager const customers = await queryRunner.manager
.getRepository(Pcclient) .getRepository(Pcclient)
.createQueryBuilder('pcclient') .createQueryBuilder('pcclient')
.select("\"pcclient\".codcli as \"customerId\"") .select('"pcclient".codcli as "customerId"')
.addSelect("\"pcclient\".cliente as \"name\"") .addSelect('"pcclient".cliente as "name"')
.addSelect("\"pcclient\".emailnfe as \"email\"") .addSelect('"pcclient".emailnfe as "email"')
.addSelect("\"pcclient\".cgcent as \"cpfCnpj\"") .addSelect('"pcclient".cgcent as "cpfCnpj"')
.addSelect("\"pcclient\".sexo as \"gender\"") .addSelect('"pcclient".sexo as "gender"')
.addSelect("\"pcclient\".enderent as \"address\"") .addSelect('"pcclient".enderent as "address"')
.addSelect("\"pcclient\".numeroent as \"addressNumber\"") .addSelect('"pcclient".numeroent as "addressNumber"')
.addSelect("\"pcclient\".bairroent as \"neighborhood\"") .addSelect('"pcclient".bairroent as "neighborhood"')
.addSelect("\"pcclient\".complementoent as \"complement\"") .addSelect('"pcclient".complementoent as "complement"')
.addSelect("\"pcclient\".municent as \"city\"") .addSelect('"pcclient".municent as "city"')
.addSelect("\"pcclient\".estent as \"state\"") .addSelect('"pcclient".estent as "state"')
.addSelect("\"pcclient\".cepent as \"zipCode\"") .addSelect('"pcclient".cepent as "zipCode"')
.addSelect("\"pcclient\".telent as \"phone\"") .addSelect('"pcclient".telent as "phone"')
.addSelect("\"pcclient\".telcelent as \"cellPhone\"") .addSelect('"pcclient".telcelent as "cellPhone"')
.addSelect("\"pcclient\".codcategoria as \"categoryId\"") .addSelect('"pcclient".codcategoria as "categoryId"')
.addSelect("\"pcclient\".codsubcategoria as \"subCategoryId\"") .addSelect('"pcclient".codsubcategoria as "subCategoryId"')
.addSelect("\"pcclient\".codpraca as \"placeId\"") .addSelect('"pcclient".codpraca as "placeId"')
.addSelect("\"pcclient\".ieent as \"numberState\"") .addSelect('"pcclient".ieent as "numberState"')
.addSelect("\"pcclient\".latitude as \"latitude\"") .addSelect('"pcclient".latitude as "latitude"')
.addSelect("\"pcclient\".longitude as \"longitude\"") .addSelect('"pcclient".longitude as "longitude"')
.addSelect("\"pcclient\".codmunicipio as \"ibgeCode\"") .addSelect('"pcclient".codmunicipio as "ibgeCode"')
.addSelect("\"pcclient\".codcidade as \"cityId\"") .addSelect('"pcclient".codcidade as "cityId"')
.addSelect("\"pcclient\".esc_tipoeclieente as \"addressType\"") .addSelect('"pcclient".esc_tipoeclieente as "addressType"')
.where(where) .where(where)
.andWhere("\"pcclient\".CODCLI NOT IN (2) AND \"pcclient\".DTEXCLUSAO IS NULL") .andWhere(
'"pcclient".CODCLI NOT IN (2) AND "pcclient".DTEXCLUSAO IS NULL',
)
.getRawMany(); .getRawMany();
return customers; return customers;
} catch (error) { } catch (error) {
@ -251,10 +270,11 @@ export class CustomerService {
async createCustomer(customer: Customer) { async createCustomer(customer: Customer) {
try { try {
console.log("Dados consumer: " + JSON.stringify(customer)); console.log('Dados consumer: ' + JSON.stringify(customer));
const newCustomer = await this.InitializeCustomer(); const newCustomer = await this.InitializeCustomer();
newCustomer.tipofj = (customer.company == 'true' ? "J" : "F"); newCustomer.tipofj = customer.company == 'true' ? 'J' : 'F';
newCustomer.ieent = (customer.company == 'true' ? customer.numberState : "ISENTO"); newCustomer.ieent =
customer.company == 'true' ? customer.numberState : 'ISENTO';
newCustomer.inscestadual = newCustomer.ieent; newCustomer.inscestadual = newCustomer.ieent;
newCustomer.cgcent = customer.cpfCnpj; newCustomer.cgcent = customer.cpfCnpj;
newCustomer.sexo = customer.gender; newCustomer.sexo = customer.gender;
@ -267,15 +287,20 @@ export class CustomerService {
newCustomer.telcelent = customer.cellPhone; newCustomer.telcelent = customer.cellPhone;
newCustomer.celularwhatsapp = customer.cellPhone; newCustomer.celularwhatsapp = customer.cellPhone;
newCustomer.codusur1 = customer.sellerId; newCustomer.codusur1 = customer.sellerId;
newCustomer.codatv1 = ( customer.ramo != null && customer.ramo.id > 0 ) ? customer.ramo.id : newCustomer.codatv1; newCustomer.codatv1 =
customer.ramo != null && customer.ramo.id > 0
? customer.ramo.id
: newCustomer.codatv1;
//Endereço de entrega //Endereço de entrega
newCustomer.cepent = customer.zipCode; newCustomer.cepent = customer.zipCode;
newCustomer.enderent = customer.address.toUpperCase(); newCustomer.enderent = customer.address.toUpperCase();
newCustomer.numeroent = customer.addressNumber; newCustomer.numeroent = customer.addressNumber;
if ( customer.complement !== null && customer.complement.length > 80 ) { if (customer.complement !== null && customer.complement.length > 80) {
newCustomer.complementoent = customer.complement.substring(0, 80 ).toUpperCase(); newCustomer.complementoent = customer.complement
.substring(0, 80)
.toUpperCase();
} else { } else {
if ( customer.complement != null ) { if (customer.complement != null) {
newCustomer.complementoent = customer.complement.toUpperCase(); newCustomer.complementoent = customer.complement.toUpperCase();
} }
} }
@ -286,10 +311,12 @@ export class CustomerService {
newCustomer.cepcom = customer.zipCode; newCustomer.cepcom = customer.zipCode;
newCustomer.endercom = customer.address.toUpperCase(); newCustomer.endercom = customer.address.toUpperCase();
newCustomer.numerocom = customer.addressNumber.toUpperCase(); newCustomer.numerocom = customer.addressNumber.toUpperCase();
if ( customer.complement !== null && customer.complement.length > 80 ) { if (customer.complement !== null && customer.complement.length > 80) {
newCustomer.complementocom = customer.complement.substring(0, 80 ).toUpperCase(); newCustomer.complementocom = customer.complement
.substring(0, 80)
.toUpperCase();
} else { } else {
if ( customer.complement != null ) { if (customer.complement != null) {
newCustomer.complementocom = customer.complement.toUpperCase(); newCustomer.complementocom = customer.complement.toUpperCase();
} }
} }
@ -300,20 +327,27 @@ export class CustomerService {
newCustomer.cepcob = customer.zipCode; newCustomer.cepcob = customer.zipCode;
newCustomer.endercob = customer.address.toUpperCase(); newCustomer.endercob = customer.address.toUpperCase();
newCustomer.numerocob = customer.addressNumber; newCustomer.numerocob = customer.addressNumber;
if ( customer.complement !== null && customer.complement.length > 80 ) { if (customer.complement !== null && customer.complement.length > 80) {
newCustomer.complementocob = customer.complement.substring(0, 80 ).toUpperCase(); newCustomer.complementocob = customer.complement
.substring(0, 80)
.toUpperCase();
} else { } else {
if ( customer.complement ) { if (customer.complement) {
newCustomer.complementocob = customer.complement.toUpperCase(); newCustomer.complementocob = customer.complement.toUpperCase();
} }
} }
newCustomer.bairrocob = customer.neighborhood.toUpperCase(); newCustomer.bairrocob = customer.neighborhood.toUpperCase();
newCustomer.municcob = customer.city.toUpperCase(); newCustomer.municcob = customer.city.toUpperCase();
newCustomer.estcob = customer.state.toUpperCase(); newCustomer.estcob = customer.state.toUpperCase();
newCustomer.codcategoria = (customer.category != null) ? customer.category.id : null; newCustomer.codcategoria =
newCustomer.codsubcategoria = (customer.subCategory != null) ? customer.subCategory.id : null; customer.category != null ? customer.category.id : null;
newCustomer.codsubcategoria =
customer.subCategory != null ? customer.subCategory.id : null;
newCustomer.codpraca = customer.place.id; newCustomer.codpraca = customer.place.id;
newCustomer.codcidade = customer.ibgeCode != null ? await this.findCity(customer.ibgeCode) : null; newCustomer.codcidade =
customer.ibgeCode != null
? await this.findCity(customer.ibgeCode)
: null;
newCustomer.codmunicipio = Number.parseInt(customer.ibgeCode); newCustomer.codmunicipio = Number.parseInt(customer.ibgeCode);
newCustomer.codcidadecom = newCustomer.codcidade; newCustomer.codcidadecom = newCustomer.codcidade;
newCustomer.dtnasc = customer.birthdate; newCustomer.dtnasc = customer.birthdate;
@ -333,37 +367,66 @@ export class CustomerService {
await this.updateCustomer(newCustomer); await this.updateCustomer(newCustomer);
return { return {
customerId: oldCustomer.customerId, customerId: oldCustomer.customerId,
company: customer.company, name: customer.name, sexo: customer.gender, company: customer.company,
cpfCnpj: customer.cpfCnpj, numberState: customer.numberState, name: customer.name,
email: customer.email, zipCode: customer.zipCode, address: customer.address, sexo: customer.gender,
addressNumber: customer.addressNumber, complement: customer.complement, cpfCnpj: customer.cpfCnpj,
numberState: customer.numberState,
email: customer.email,
zipCode: customer.zipCode,
address: customer.address,
addressNumber: customer.addressNumber,
complement: customer.complement,
neighborhood: customer.neighborhood, neighborhood: customer.neighborhood,
city: customer.city, state: customer.state, city: customer.city,
allowMessage: customer.allowMessage, cellPhone: customer.cellPhone, state: customer.state,
category: customer.category, subCategory: customer.subCategory, allowMessage: customer.allowMessage,
place: customer.place, ramo: customer.ramo, meiocomunicacao: customer.communicate, cellPhone: customer.cellPhone,
latitude: customer.latitude, longitude: customer.longitude, ibgeCode: customer.ibgeCode, category: customer.category,
subCategory: customer.subCategory,
place: customer.place,
ramo: customer.ramo,
meiocomunicacao: customer.communicate,
latitude: customer.latitude,
longitude: customer.longitude,
ibgeCode: customer.ibgeCode,
addressType: customer.addressType, addressType: customer.addressType,
}; };
} else { } else {
const idCustomer = await this.generateIdCustomer(); const idCustomer = await this.generateIdCustomer();
if (idCustomer == -1) if (idCustomer == -1)
return new HttpException("Erro ao gerar númeração de cliente.", HttpStatus.INTERNAL_SERVER_ERROR); return new HttpException(
'Erro ao gerar númeração de cliente.',
HttpStatus.INTERNAL_SERVER_ERROR,
);
newCustomer.codcli = idCustomer; newCustomer.codcli = idCustomer;
await this.insertCustomer(newCustomer); await this.insertCustomer(newCustomer);
return { return {
customerId: idCustomer, customerId: idCustomer,
company: customer.company, name: customer.name, company: customer.company,
cpfCnpj: customer.cpfCnpj, gender: customer.gender, numberState: customer.numberState, name: customer.name,
email: customer.email, zipCode: customer.zipCode, address: customer.address, cpfCnpj: customer.cpfCnpj,
addressNumber: customer.addressNumber, complement: customer.complement, gender: customer.gender,
numberState: customer.numberState,
email: customer.email,
zipCode: customer.zipCode,
address: customer.address,
addressNumber: customer.addressNumber,
complement: customer.complement,
neighborhood: customer.neighborhood, neighborhood: customer.neighborhood,
city: customer.city, state: customer.state, city: customer.city,
allowMessage: customer.allowMessage, cellPhone: customer.cellPhone, state: customer.state,
category: customer.category, subCategory: customer.subCategory, allowMessage: customer.allowMessage,
place: customer.place, meiocomunicacao: customer.communicate, cellPhone: customer.cellPhone,
ramo: customer.ramo, latitude: customer.latitude, longitude: customer.longitude, category: customer.category,
ibgeCode: customer.ibgeCode, addressType: customer.addressType, subCategory: customer.subCategory,
place: customer.place,
meiocomunicacao: customer.communicate,
ramo: customer.ramo,
latitude: customer.latitude,
longitude: customer.longitude,
ibgeCode: customer.ibgeCode,
addressType: customer.addressType,
}; };
} }
} catch (error) { } catch (error) {
@ -378,7 +441,7 @@ export class CustomerService {
await queryRunner.connect(); await queryRunner.connect();
await queryRunner.startTransaction(); await queryRunner.startTransaction();
try { try {
console.log("MEIO DE COMUNICACAO: " + client.meiocomunicacao); console.log('MEIO DE COMUNICACAO: ' + client.meiocomunicacao);
await queryRunner.manager await queryRunner.manager
.createQueryBuilder() .createQueryBuilder()
.update(Pcclient) .update(Pcclient)
@ -424,7 +487,7 @@ export class CustomerService {
dtultalter: client.dtultalter, dtultalter: client.dtultalter,
latitude: client.latitude, latitude: client.latitude,
longitude: client.longitude, longitude: client.longitude,
tipoendereco: client.tipoendereco tipoendereco: client.tipoendereco,
}) })
.where({ codcli: client.codcli }) .where({ codcli: client.codcli })
.execute(); .execute();
@ -434,13 +497,12 @@ export class CustomerService {
await queryRunner.rollbackTransaction(); await queryRunner.rollbackTransaction();
throw err; throw err;
} finally { } finally {
if ( queryRunner.isTransactionActive) { if (queryRunner.isTransactionActive) {
await queryRunner.rollbackTransaction(); await queryRunner.rollbackTransaction();
} }
await queryRunner.release(); await queryRunner.release();
await connection.close(); await connection.close();
} }
} }
async findCity(ibgeCode: string) { async findCity(ibgeCode: string) {
@ -452,7 +514,10 @@ export class CustomerService {
const queryRunner = connection.createQueryRunner(); const queryRunner = connection.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
try { try {
const city = await queryRunner.query('SELECT PCCIDADE.CODCIDADE as "codigoCidade" FROM PCCIDADE WHERE PCCIDADE.codibge = :1', [ibgeCode]); const city = await queryRunner.query(
'SELECT PCCIDADE.CODCIDADE as "codigoCidade" FROM PCCIDADE WHERE PCCIDADE.codibge = :1',
[ibgeCode],
);
let cityId = 0; let cityId = 0;
if (city.length > 0) { if (city.length > 0) {
cityId = city[0].codigoCidade; cityId = city[0].codigoCidade;
@ -471,68 +536,67 @@ export class CustomerService {
cliente.codusur1 = 1; cliente.codusur1 = 1;
cliente.codplpag = 10; cliente.codplpag = 10;
cliente.codpraca = 119; cliente.codpraca = 119;
cliente.codcob = "D"; cliente.codcob = 'D';
cliente.dtcadastro = new Date(); cliente.dtcadastro = new Date();
cliente.codcontab = "1"; cliente.codcontab = '1';
cliente.aceitavendafracao = "N"; cliente.aceitavendafracao = 'N';
//cliente.Meiocomunicacao = "N"; //cliente.Meiocomunicacao = "N";
cliente.bloqueio = "N"; cliente.bloqueio = 'N';
cliente.bloqueiosefaz = "N"; cliente.bloqueiosefaz = 'N';
cliente.bloqueiosefazped = "N"; cliente.bloqueiosefazped = 'N';
cliente.bloqvendapf = "N"; cliente.bloqvendapf = 'N';
cliente.condvenda1 = "S"; cliente.condvenda1 = 'S';
cliente.condvenda5 = "S"; cliente.condvenda5 = 'S';
cliente.condvenda7 = "S"; cliente.condvenda7 = 'S';
cliente.condvenda8 = "S"; cliente.condvenda8 = 'S';
cliente.contribuinte = "N"; cliente.contribuinte = 'N';
cliente.validarmultiplovenda = "N"; cliente.validarmultiplovenda = 'N';
cliente.codfunccad = 1; cliente.codfunccad = 1;
cliente.codfunccadastro = 1; cliente.codfunccadastro = 1;
cliente.horacadastro = new Date(); cliente.horacadastro = new Date();
cliente.dtcadastro = new Date(); cliente.dtcadastro = new Date();
cliente.dtultvisita = new Date(); cliente.dtultvisita = new Date();
cliente.codatv1 = 7; cliente.codatv1 = 7;
cliente.aceitatrocanegativa = "N"; cliente.aceitatrocanegativa = 'N';
cliente.consumidorfinal = "S"; cliente.consumidorfinal = 'S';
cliente.aplicadescnf = "S"; cliente.aplicadescnf = 'S';
cliente.simplesnacional = "N"; cliente.simplesnacional = 'N';
cliente.sexo = "M"; cliente.sexo = 'M';
cliente.isencaosuframa = "T"; cliente.isencaosuframa = 'T';
cliente.clicrm = "N"; cliente.clicrm = 'N';
cliente.tv10usacustoproduto = "N"; cliente.tv10usacustoproduto = 'N';
cliente.inscestadual = "ISENTO"; cliente.inscestadual = 'ISENTO';
cliente.codpais = 1058; //Brasil cliente.codpais = 1058; //Brasil
cliente.observacao = "Importado do E-Commerce"; cliente.observacao = 'Importado do E-Commerce';
cliente.aceitachterceiros = "S"; cliente.aceitachterceiros = 'S';
cliente.agregarvalorstdescfin = "N"; cliente.agregarvalorstdescfin = 'N';
cliente.anvisa = "N"; cliente.anvisa = 'N';
cliente.aplicredbaseicmstransp = "N"; cliente.aplicredbaseicmstransp = 'N';
cliente.atendedomingo = "N"; cliente.atendedomingo = 'N';
cliente.atendequarta = "N"; cliente.atendequarta = 'N';
cliente.atendequinta = "N"; cliente.atendequinta = 'N';
cliente.atendesabado = "N"; cliente.atendesabado = 'N';
cliente.atendesegunda = "N"; cliente.atendesegunda = 'N';
cliente.atendesexta = "N"; cliente.atendesexta = 'N';
cliente.atendeterca = "N"; cliente.atendeterca = 'N';
cliente.atualizasaldoccdescfin = "N"; cliente.atualizasaldoccdescfin = 'N';
cliente.bloqremcob = "N"; cliente.bloqremcob = 'N';
cliente.clientedan = "N"; cliente.clientedan = 'N';
cliente.clientefontest = "N"; cliente.clientefontest = 'N';
cliente.clientemonitorado = "N"; cliente.clientemonitorado = 'N';
cliente.clientprotesto = "S"; cliente.clientprotesto = 'S';
cliente.fretedespacho = "0"; cliente.fretedespacho = '0';
cliente.aceitavendafracao = "S"; cliente.aceitavendafracao = 'S';
cliente.validarmultiplovenda = "S"; cliente.validarmultiplovenda = 'S';
return cliente; return cliente;
} }
async generateIdCustomer() { async generateIdCustomer() {
console.log("Gerando idcustomer"); console.log('Gerando idcustomer');
const connection = new Connection(connectionOptions); const connection = new Connection(connectionOptions);
const queryRunner = connection.createQueryRunner(); const queryRunner = connection.createQueryRunner();
try { try {
await connection.connect(); await connection.connect();
await queryRunner.connect(); await queryRunner.connect();
@ -540,7 +604,6 @@ export class CustomerService {
// lets now open a new transaction: // lets now open a new transaction:
await queryRunner.startTransaction(); await queryRunner.startTransaction();
let sql = `SELECT PROXNUMCLI as "proxnumcli" FROM PCCONSUM WHERE 1 = 1 FOR UPDATE`; let sql = `SELECT PROXNUMCLI as "proxnumcli" FROM PCCONSUM WHERE 1 = 1 FOR UPDATE`;
let param = await queryRunner.query(sql); let param = await queryRunner.query(sql);
@ -563,17 +626,15 @@ export class CustomerService {
// commit transaction now: // commit transaction now:
await queryRunner.commitTransaction(); await queryRunner.commitTransaction();
return idCustomer; return idCustomer;
} catch (err) { } catch (err) {
// since we have errors let's rollback changes we made // since we have errors let's rollback changes we made
if ( queryRunner.isTransactionActive) { if (queryRunner.isTransactionActive) {
await queryRunner.rollbackTransaction(); await queryRunner.rollbackTransaction();
} }
console.log(err); console.log(err);
return -1; return -1;
} finally { } finally {
if ( queryRunner.isTransactionActive) { if (queryRunner.isTransactionActive) {
await queryRunner.rollbackTransaction(); await queryRunner.rollbackTransaction();
} }
// you need to release query runner which is manually created: // you need to release query runner which is manually created:
@ -603,7 +664,7 @@ export class CustomerService {
console.log(err); console.log(err);
throw err; throw err;
} finally { } finally {
if ( queryRunner.isTransactionActive) { if (queryRunner.isTransactionActive) {
await queryRunner.rollbackTransaction(); await queryRunner.rollbackTransaction();
} }
await queryRunner.release(); await queryRunner.release();
@ -612,16 +673,15 @@ export class CustomerService {
} }
async getCategory() { async getCategory() {
const connectionDb = new Connection(connectionOptions) const connectionDb = new Connection(connectionOptions);
await connectionDb.connect(); await connectionDb.connect();
const queryRunner = connectionDb.createQueryRunner(); const queryRunner = connectionDb.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
try { try {
return await queryRunner.manager return await queryRunner.manager
.getRepository(Estcategoriacliente) .getRepository(Estcategoriacliente)
.createQueryBuilder("estcategoriacliente") .createQueryBuilder('estcategoriacliente')
.getMany(); .getMany();
} catch (err) { } catch (err) {
console.log(err); console.log(err);
throw err; throw err;
@ -632,16 +692,15 @@ export class CustomerService {
} }
async getSubCategory() { async getSubCategory() {
const connectionDb = new Connection(connectionOptions) const connectionDb = new Connection(connectionOptions);
await connectionDb.connect(); await connectionDb.connect();
const queryRunner = connectionDb.createQueryRunner(); const queryRunner = connectionDb.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
try { try {
return await queryRunner.manager return await queryRunner.manager
.getRepository(Estsubcategoriacliente) .getRepository(Estsubcategoriacliente)
.createQueryBuilder("estsubcategoriacliente") .createQueryBuilder('estsubcategoriacliente')
.getMany(); .getMany();
} catch (err) { } catch (err) {
console.log(err); console.log(err);
throw err; throw err;
@ -650,5 +709,4 @@ export class CustomerService {
await connectionDb.close(); await connectionDb.close();
} }
} }
} }