From 94f9208ee4a88ac147767dd6c30f478d349420a8 Mon Sep 17 00:00:00 2001 From: joelson Date: Thu, 8 Jan 2026 18:43:22 -0300 Subject: [PATCH] Refactor code structure for improved readability and maintainability --- src/sales/customer/customer.controller.ts | 219 ++-- src/sales/customer/customer.service.ts | 1288 +++++++++++---------- 2 files changed, 802 insertions(+), 705 deletions(-) diff --git a/src/sales/customer/customer.controller.ts b/src/sales/customer/customer.controller.ts index adad69c..ce499da 100644 --- a/src/sales/customer/customer.controller.ts +++ b/src/sales/customer/customer.controller.ts @@ -1,109 +1,148 @@ -import { Body, Controller, Get, HttpException, HttpStatus, Param, Post, Query } from '@nestjs/common'; -import { CustomerService } from './customer.service'; -import { ResultModel } from '../../domain/models/result.model'; +import { + Body, + Controller, + Get, + HttpException, + HttpStatus, + Param, + Post, + Query, +} from '@nestjs/common'; +import { ApiTags } from '@nestjs/swagger'; import { error } from 'console'; 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') @Controller('api/v1/customer') -export class CustomerController { +export class CustomerController { + constructor(private readonly customerService: CustomerService) {} - constructor(private readonly customerService: CustomerService){} + @Get(':name') + async getCustomerByName(@Param('name') name: string) { + try { + const customers = await this.customerService.findCustomerByName(name); + return new ResultModel(true, null, customers, null); + } catch (err) { + throw new HttpException( + new ResultModel( + false, + 'Não foi possível consultar o cadastro de clientes.', + {}, + error, + ), + HttpStatus.INTERNAL_SERVER_ERROR, + ); + } + } - @Get(':name') - async getCustomerByName(@Param('name') name: string){ - try{ - const customers = await this.customerService.findCustomerByName(name); - return new ResultModel(true, null, customers, null); - } catch(err){ - throw new HttpException(new ResultModel(false, 'Não foi possível consultar o cadastro de clientes.', {}, error), - HttpStatus.INTERNAL_SERVER_ERROR); - } + @Get('categories/fechAll') + async getCategories() { + try { + const categories = await this.customerService.getCategory(); + return categories; + } catch (err) { + throw new HttpException( + new ResultModel(false, err.message, {}, error), + HttpStatus.INTERNAL_SERVER_ERROR, + ); } + } - @Get('categories/fechAll') - async getCategories(){ - try{ - const categories = await this.customerService.getCategory(); - return categories; - } catch(err){ - throw new HttpException(new ResultModel(false, err.message, {}, error), - HttpStatus.INTERNAL_SERVER_ERROR); - } + @Get('subcategories/fechAll') + async getSubCategories() { + try { + const subCategories = await this.customerService.getSubCategory(); + return subCategories; + } catch (err) { + throw new HttpException( + new ResultModel(false, err.message, {}, error), + HttpStatus.INTERNAL_SERVER_ERROR, + ); } + } - @Get('subcategories/fechAll') - async getSubCategories(){ - try{ - const subCategories = await this.customerService.getSubCategory(); - return subCategories; - } catch(err){ - throw new HttpException(new ResultModel(false, err.message, {}, error), - HttpStatus.INTERNAL_SERVER_ERROR); - } + @Get() + async getCustomer(@Query() query) { + try { + const field = query['field']; + const textSearch = query['textsearch']; + const customers = await this.customerService.findCustomerByQuery( + field, + textSearch, + ); + return new ResultModel(true, null, customers, null); + } catch (err) { + // 'Não foi possível consultar o cadastro de clientes.' + throw new HttpException( + new ResultModel(false, err.message, {}, error), + HttpStatus.INTERNAL_SERVER_ERROR, + ); } + } - - @Get() - async getCustomer(@Query() query){ - try{ - const field = query['field']; - const textSearch = query['textsearch']; - const customers = await this.customerService.findCustomerByQuery(field, textSearch); - return new ResultModel(true, null, customers, null); - } catch(err){ - // 'Não foi possível consultar o cadastro de clientes.' - throw new HttpException(new ResultModel(false, err.message, {}, error), - HttpStatus.INTERNAL_SERVER_ERROR); - } + @Get(':id') + async getCustomerById(@Param('id') id: number) { + try { + const customers = await this.customerService.findCustomerById(id); + return new ResultModel(true, null, customers, null); + } catch (err) { + throw new HttpException( + new ResultModel( + false, + 'Não foi possível consultar o cadastro de clientes.', + {}, + error, + ), + HttpStatus.INTERNAL_SERVER_ERROR, + ); } + } - @Get(':id') - async getCustomerById(@Param('id') id: number){ - try{ - const customers = await this.customerService.findCustomerById(id); - return new ResultModel(true, null, customers, null); - } catch(err){ - throw new HttpException(new ResultModel(false, 'Não foi possível consultar o cadastro de clientes.', {}, error), - HttpStatus.INTERNAL_SERVER_ERROR); - } + @Get('cpf/:cpf') + async getCustomerByCpf(@Param('cpf') cpf: string) { + try { + console.log('pesquisando por cpf'); + const customer = await this.customerService.findCustomerByCpf(cpf); + if (!customer) + return new ResultModel(false, 'Cliente não cadastrado', null, null); + return new ResultModel(true, null, customer, null); + } catch (err) { + throw new HttpException( + new ResultModel( + false, + 'Não foi possível consultar o cadastro de clientes.', + {}, + error, + ), + HttpStatus.INTERNAL_SERVER_ERROR, + ); } - - @Get('cpf/:cpf') - async getCustomerByCpf(@Param('cpf') cpf: string){ - try{ - console.log("pesquisando por cpf"); - const customer = await this.customerService.findCustomerByCpf(cpf); - if (!customer) return new ResultModel(false, 'Cliente não cadastrado', null, null); - return new ResultModel(true, null, customer, null); - } catch(err){ - throw new HttpException(new ResultModel(false, 'Não foi possível consultar o cadastro de clientes.', {}, error), - HttpStatus.INTERNAL_SERVER_ERROR); - } - } - @Get('create/proxnumcli') - async IdCustomer(){ - try{ - console.log('proxnumcli'); - const id = await this.customerService.generateIdCustomer(); - return new ResultModel(true, null, id, null); - } catch(err){ - throw err; - } + } + @Get('create/proxnumcli') + async IdCustomer() { + try { + console.log('proxnumcli'); + const id = await this.customerService.generateIdCustomer(); + return new ResultModel(true, null, id, null); + } catch (err) { + throw err; } + } - - @Post('create') - async createCustomer(@Body() customer: Customer){ - try{ - console.log(customer); - const result = await this.customerService.createCustomer(customer); - return new ResultModel(true, null, result, null); - //return new ResultModel(true, null, id, null); - } catch(err){ - throw new HttpException(new ResultModel(false, 'Erro ao cadastrar cliente.', {}, err), - HttpStatus.INTERNAL_SERVER_ERROR); - } + @Post('create') + async createCustomer(@Body() customer: Customer) { + try { + console.log(customer); + const result = await this.customerService.createCustomer(customer); + return new ResultModel(true, null, result, null); + //return new ResultModel(true, null, id, null); + } catch (err) { + throw new HttpException( + new ResultModel(false, 'Erro ao cadastrar cliente.', {}, err), + HttpStatus.INTERNAL_SERVER_ERROR, + ); } -} + } +} \ No newline at end of file diff --git a/src/sales/customer/customer.service.ts b/src/sales/customer/customer.service.ts index 60d5f7d..b7ed1ba 100644 --- a/src/sales/customer/customer.service.ts +++ b/src/sales/customer/customer.service.ts @@ -1,654 +1,712 @@ -import { HttpStatus } from '@nestjs/common'; -import { Injectable, HttpException } from '@nestjs/common'; +import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; +import { Connection } from 'typeorm'; import { connectionOptions } from '../../configs/typeorm.config'; import { Customer } from '../../domain/models/customer.model'; -import { Connection } 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 { Estsubcategoriacliente } from '../../domain/entity/tables/estsubcategoriacliente.entity'; +import { Pcclient } from '../../domain/entity/tables/pcclient.entity'; @Injectable() export class CustomerService { - - async findCustomerByName(name: string) { - let auxName = ''; - for (let i = 0; i < name.length; i++) { - auxName += name[i].replace("@", "%"); - } - const connection = new Connection(connectionOptions); - await connection.connect(); - const queryRunner = connection.createQueryRunner(); - await queryRunner.connect(); - try { - const sql = ' SELECT pcclient.cliente as "name" ' + - ' ,pcclient.codcli as "customerId" ' + - ' ,pcclient.emailnfe as "email" ' + - ' ,pcclient.cgcent as "cpfCnpj" ' + - ' ,pcclient.sexo as "gender" ' + - ' ,pcclient.enderent as "address" ' + - ' ,pcclient.numeroent as "addressNumber" ' + - ' ,pcclient.complementoent as "complement" ' + - ' ,pcclient.bairroent as "neigborhood" ' + - ' ,pcclient.municent as "city" ' + - ' ,pcclient.estent as "state" ' + - ' ,pcclient.cepent as "zipCode" ' + - ' ,pcclient.telent as "phone" ' + - ' ,pcclient.telcelent as "cellPhone" ' + - ' ,pcclient.ieent as "numberState" ' + - ' ,pcclient.codcategoria as "categoryId" ' + - ' ,pcclient.codsubcategoria as "subCategoryId" ' + - ' ,pcclient.codpraca as "placeId" ' + - ' ,pcclient.codusur1 as "sellerId" ' + - ' ,pccidade.codibge as "ibgeCode" ' + - ' ,pcclient.dtnasc as "birthdate" ' + - ' ,pcclient.codatv1 as "ramoId" ' + - ' ,pcclient.meiocomunicacao as "communicate" ' + - ' ,pcclient.latitude as "latitude" ' + - ' ,pcclient.longitude as "longitude" ' + - ' ,pcclient.codmunicipio as "ibgeCode" ' + - ' ,pcclient.codcidade as "cityId" ' + - ' ,pcclient.tipoendereco as "addressType" ' + - ' FROM pcclient, pccidade ' + - ' WHERE pcclient.codcidade = pccidade.codcidade (+)'; - let where = ` AND ( pcclient.cliente like '%'||'${auxName.replace('@', '%')}'||'%' OR ` + - ` REGEXP_REPLACE(pcclient.cgcent, '[^0-9]', '') = REGEXP_REPLACE('${name}', '[^0-9]') OR ` + - ` pcclient.codcli = REGEXP_REPLACE('${name}', '[^0-9]') )`; - where += ` AND pcclient.codcli NOT IN (2) AND pcclient.DTEXCLUSAO IS NULL `; - const orderBy = ` ORDER BY pcclient.cliente `; - const pagination = ` OFFSET 0 ROWS FETCH NEXT 100 ROWS ONLY`; - const customers = await queryRunner.manager - .query(sql + where + orderBy + pagination) as Customer[]; - let customerList: Customer[] = []; - for (let i = 0; i < customers.length; i++) { - let customer = customers[i]; - const place = await queryRunner.query(`SELECT PCPRACA.CODPRACA as "placeId" + async findCustomerByName(name: string) { + let auxName = ''; + for (let i = 0; i < name.length; i++) { + auxName += name[i].replace('@', '%'); + } + const connection = new Connection(connectionOptions); + await connection.connect(); + const queryRunner = connection.createQueryRunner(); + await queryRunner.connect(); + try { + const sql = + ' SELECT pcclient.cliente as "name" ' + + ' ,pcclient.codcli as "customerId" ' + + ' ,pcclient.emailnfe as "email" ' + + ' ,pcclient.cgcent as "cpfCnpj" ' + + ' ,pcclient.sexo as "gender" ' + + ' ,pcclient.enderent as "address" ' + + ' ,pcclient.numeroent as "addressNumber" ' + + ' ,pcclient.complementoent as "complement" ' + + ' ,pcclient.bairroent as "neigborhood" ' + + ' ,pcclient.municent as "city" ' + + ' ,pcclient.estent as "state" ' + + ' ,pcclient.cepent as "zipCode" ' + + ' ,pcclient.telent as "phone" ' + + ' ,pcclient.telcelent as "cellPhone" ' + + ' ,pcclient.ieent as "numberState" ' + + ' ,pcclient.codcategoria as "categoryId" ' + + ' ,pcclient.codsubcategoria as "subCategoryId" ' + + ' ,pcclient.codpraca as "placeId" ' + + ' ,pcclient.codusur1 as "sellerId" ' + + ' ,pccidade.codibge as "ibgeCode" ' + + ' ,pcclient.dtnasc as "birthdate" ' + + ' ,pcclient.codatv1 as "ramoId" ' + + ' ,pcclient.meiocomunicacao as "communicate" ' + + ' ,pcclient.latitude as "latitude" ' + + ' ,pcclient.longitude as "longitude" ' + + ' ,pcclient.codmunicipio as "ibgeCode" ' + + ' ,pcclient.codcidade as "cityId" ' + + ' ,pcclient.tipoendereco as "addressType" ' + + ' FROM pcclient, pccidade ' + + ' WHERE pcclient.codcidade = pccidade.codcidade (+)'; + let where = + ` AND ( pcclient.cliente like '%'||'${auxName.replace( + '@', + '%', + )}'||'%' OR ` + + ` REGEXP_REPLACE(pcclient.cgcent, '[^0-9]', '') = REGEXP_REPLACE('${name}', '[^0-9]') OR ` + + ` pcclient.codcli = REGEXP_REPLACE('${name}', '[^0-9]') )`; + where += ` AND pcclient.codcli NOT IN (2) AND pcclient.DTEXCLUSAO IS NULL `; + const orderBy = ` ORDER BY pcclient.cliente `; + const pagination = ` OFFSET 0 ROWS FETCH NEXT 100 ROWS ONLY`; + const customers = (await queryRunner.manager.query( + sql + where + orderBy + pagination, + )) as Customer[]; + const customerList: Customer[] = []; + for (let i = 0; i < customers.length; i++) { + const customer = customers[i]; + const place = await queryRunner.query(`SELECT PCPRACA.CODPRACA as "placeId" ,PCPRACA.PRACA as "name" FROM PCPRACA WHERE PCPRACA.CODPRACA = ${customer.placeId}`); - customer.place = place[0]; - customerList.push(customer); - } - return customerList; - } catch (error) { - console.log(error); - throw error; - } finally { - await queryRunner.release(); - await connection.close(); - } + customer.place = place[0]; + customerList.push(customer); + } + return customerList; + } catch (error) { + console.log(error); + throw error; + } finally { + await queryRunner.release(); + await connection.close(); } + } - async findCustomerByCpf(cpf: string) { - const connection = new Connection(connectionOptions); - await connection.connect(); - const queryRunner = connection.createQueryRunner(); - await queryRunner.connect(); - try { - const sql = ' SELECT pcclient.cliente as "name" ' + - ' ,pcclient.codcli as "customerId" ' + - ' ,pcclient.emailnfe as "email" ' + - ' ,pcclient.cgcent as "cpfCnpj" ' + - ' ,pcclient.sexo as "gender" ' + - ' ,pcclient.enderent as "address" ' + - ' ,pcclient.numeroent as "addressNumber" ' + - ' ,pcclient.complementoent as "complement" ' + - ' ,pcclient.bairroent as "neighborhood" ' + - ' ,pcclient.municent as "city" ' + - ' ,pcclient.estent as "state" ' + - ' ,pcclient.cepent as "zipCode" ' + - ' ,pcclient.telent as "phone" ' + - ' ,pcclient.telcelent as "cellPhone" ' + - ' ,pcclient.ieent as "numberState" ' + - ' ,pcclient.codcategoria as "categoryId" ' + - ' ,pcclient.codsubcategoria as "subCategoryId" ' + - ' ,pcclient.codpraca as "placeId" ' + - ' ,pcclient.codusur1 as "sellerId" ' + - ' ,pccidade.codibge as "ibgeCode" ' + - ' ,pcclient.dtnasc as "birthdate" ' + - ' ,pcclient.codatv1 as "ramoId" ' + - ' ,pcclient.meiocomunicacao as "communicate" ' + - ' ,pcclient.latitude as "latitude" ' + - ' ,pcclient.longitude as "longitude" ' + - ' ,pcclient.codmunicipio as "ibgeCode" ' + - ' ,pcclient.codcidade as "cityId" ' + - ' ,pcclient.tipoendereco as "addressType" ' + - ' FROM pcclient, pccidade ' + - ' WHERE pcclient.codcidade = pccidade.codcidade (+)'; - const where = ` AND REGEXP_REPLACE(pcclient.cgcent, '[^0-9]', '') =REGEXP_REPLACE('${cpf}', '[^0-9]', '')`; - const customer = await queryRunner.query(sql + where); - return customer[0]; - } catch (error) { - console.log(error); - throw error; - } finally { - await queryRunner.release(); - await connection.close(); - } + async findCustomerByCpf(cpf: string) { + const connection = new Connection(connectionOptions); + await connection.connect(); + const queryRunner = connection.createQueryRunner(); + await queryRunner.connect(); + try { + const sql = + ' SELECT pcclient.cliente as "name" ' + + ' ,pcclient.codcli as "customerId" ' + + ' ,pcclient.emailnfe as "email" ' + + ' ,pcclient.cgcent as "cpfCnpj" ' + + ' ,pcclient.sexo as "gender" ' + + ' ,pcclient.enderent as "address" ' + + ' ,pcclient.numeroent as "addressNumber" ' + + ' ,pcclient.complementoent as "complement" ' + + ' ,pcclient.bairroent as "neighborhood" ' + + ' ,pcclient.municent as "city" ' + + ' ,pcclient.estent as "state" ' + + ' ,pcclient.cepent as "zipCode" ' + + ' ,pcclient.telent as "phone" ' + + ' ,pcclient.telcelent as "cellPhone" ' + + ' ,pcclient.ieent as "numberState" ' + + ' ,pcclient.codcategoria as "categoryId" ' + + ' ,pcclient.codsubcategoria as "subCategoryId" ' + + ' ,pcclient.codpraca as "placeId" ' + + ' ,pcclient.codusur1 as "sellerId" ' + + ' ,pccidade.codibge as "ibgeCode" ' + + ' ,pcclient.dtnasc as "birthdate" ' + + ' ,pcclient.codatv1 as "ramoId" ' + + ' ,pcclient.meiocomunicacao as "communicate" ' + + ' ,pcclient.latitude as "latitude" ' + + ' ,pcclient.longitude as "longitude" ' + + ' ,pcclient.codmunicipio as "ibgeCode" ' + + ' ,pcclient.codcidade as "cityId" ' + + ' ,pcclient.tipoendereco as "addressType" ' + + ' ,DECODE(pcclient.dtexclusao, NULL, 1, 0) as "deletedCustomer" ' + + ' FROM pcclient, pccidade ' + + ' WHERE pcclient.codcidade = pccidade.codcidade (+)'; + const where = ` AND REGEXP_REPLACE(pcclient.cgcent, '[^0-9]', '') =REGEXP_REPLACE('${cpf}', '[^0-9]', '')`; + const customer = await queryRunner.query(sql + where); + return customer as Customer[]; + } catch (error) { + console.log(error); + throw error; + } finally { + await queryRunner.release(); + await connection.close(); } + } - async findCustomerById(idCustomer: number) { - const connection = new Connection(connectionOptions); - await connection.connect(); - const queryRunner = connection.createQueryRunner(); - await queryRunner.connect(); - try { - - const sql = ' SELECT pcclient.cliente as "name" ' + - ' ,pcclient.codcli as "customerId" ' + - ' ,pcclient.emailnfe as "email" ' + - ' ,pcclient.cgcent as "cpfCnpj" ' + - ' ,pcclient.sexo as "gender" ' + - ' ,pcclient.enderent as "address" ' + - ' ,pcclient.numeroent as "addressNumber" ' + - ' ,pcclient.complementoent as "complement" ' + - ' ,pcclient.bairroent as "neighborhood" ' + - ' ,pcclient.municent as "city" ' + - ' ,pcclient.estent as "state" ' + - ' ,pcclient.cepent as "zipCode" ' + - ' ,pcclient.telent as "phone" ' + - ' ,pcclient.telcelent as "cellPhone" ' + - ' ,pcclient.ieent as "numberState" ' + - ' ,pcclient.codcategoria as "categoryId" ' + - ' ,pcclient.codsubcategoria as "subCategoryId" ' + - ' ,pcclient.codpraca as "placeId" ' + - ' ,pcclient.codusur1 as "sellerId" ' + - ' ,pccidade.codibge as "ibgeCode" ' + - ' ,pcclient.dtnasc as "birthdate" ' + - ' ,pcclient.codatv1 as "ramoId" ' + - ' ,pcclient.meiocomunicacao as "communicate" ' + - ' ,pcclient.latitude as "latitude" ' + - ' ,pcclient.longitude as "longitude" ' + - ' ,pcclient.codmunicipio as "ibgeCode" ' + - ' ,pcclient.codcidade as "cityId" ' + - ' ,pcclient.tipoendereco as "addressType" ' + - ' FROM pcclient, pccidade ' + - ' WHERE pcclient.codcidade = pccidade.codcidade (+)'; - const where = ` AND pcclient.codcli = ${idCustomer}`; - const customer = await queryRunner.query(sql + where); - const place = await queryRunner.query(`SELECT PCPRACA.CODPRACA as "placeId" + async findCustomerById(idCustomer: number) { + const connection = new Connection(connectionOptions); + await connection.connect(); + const queryRunner = connection.createQueryRunner(); + await queryRunner.connect(); + try { + const sql = + ' SELECT pcclient.cliente as "name" ' + + ' ,pcclient.codcli as "customerId" ' + + ' ,pcclient.emailnfe as "email" ' + + ' ,pcclient.cgcent as "cpfCnpj" ' + + ' ,pcclient.sexo as "gender" ' + + ' ,pcclient.enderent as "address" ' + + ' ,pcclient.numeroent as "addressNumber" ' + + ' ,pcclient.complementoent as "complement" ' + + ' ,pcclient.bairroent as "neighborhood" ' + + ' ,pcclient.municent as "city" ' + + ' ,pcclient.estent as "state" ' + + ' ,pcclient.cepent as "zipCode" ' + + ' ,pcclient.telent as "phone" ' + + ' ,pcclient.telcelent as "cellPhone" ' + + ' ,pcclient.ieent as "numberState" ' + + ' ,pcclient.codcategoria as "categoryId" ' + + ' ,pcclient.codsubcategoria as "subCategoryId" ' + + ' ,pcclient.codpraca as "placeId" ' + + ' ,pcclient.codusur1 as "sellerId" ' + + ' ,pccidade.codibge as "ibgeCode" ' + + ' ,pcclient.dtnasc as "birthdate" ' + + ' ,pcclient.codatv1 as "ramoId" ' + + ' ,pcclient.meiocomunicacao as "communicate" ' + + ' ,pcclient.latitude as "latitude" ' + + ' ,pcclient.longitude as "longitude" ' + + ' ,pcclient.codmunicipio as "ibgeCode" ' + + ' ,pcclient.codcidade as "cityId" ' + + ' ,pcclient.tipoendereco as "addressType" ' + + ' FROM pcclient, pccidade ' + + ' WHERE pcclient.codcidade = pccidade.codcidade (+)'; + const where = ` AND pcclient.codcli = ${idCustomer}`; + const customer = await queryRunner.query(sql + where); + const place = await queryRunner.query(`SELECT PCPRACA.CODPRACA as "placeId" ,PCPRACA.PRACA as "name" FROM PCPRACA WHERE PCPRACA.CODPRACA = ${customer[0].placeId}`); - return {...customer[0], place: place[0]}; - } catch (error) { - console.log(error); - throw error; - } finally { - await queryRunner.release(); - await connection.close(); - } + return { ...customer[0], place: place[0] }; + } catch (error) { + console.log(error); + throw error; + } finally { + await queryRunner.release(); + await connection.close(); + } + } + + async findCustomerByQuery(field: string, textSearch: string) { + let where = ''; + switch (field) { + case 'name': + where += '"pcclient".cliente like \'' + textSearch + "%'"; + break; + case 'document': + where += + "REGEXP_REPLACE(\"pcclient\".cgcent, '[^0-9]', '') = REGEXP_REPLACE('" + + textSearch + + "', '[^0-9]', '')"; + break; + case 'phone': + where += + "REGEXP_REPLACE(\"pcclient\".telent, '[^0-9]', '') = REGEXP_REPLACE('" + + textSearch + + "', '[^0-9]', '')"; + break; + case 'cellphone': + where += + "REGEXP_REPLACE(\"pcclient\".telcelent, '[^0-9]', '') = REGEXP_REPLACE('" + + textSearch + + "', '[^0-9]', '')"; + break; + case 'customerId': + where += '"pcclient".codcli = ' + textSearch; + break; + default: + throw new HttpException( + 'Não foi informado um campo válido para pesquisa.', + HttpStatus.BAD_REQUEST, + ); } - async findCustomerByQuery(field: string, textSearch: string) { - let where = ""; - switch (field) { - case "name": - where += "\"pcclient\".cliente like '" + textSearch + "%'"; - break; - case "document": - where += "REGEXP_REPLACE(\"pcclient\".cgcent, '[^0-9]', '') = REGEXP_REPLACE('" + textSearch + "', '[^0-9]', '')"; - break; - case "phone": - where += "REGEXP_REPLACE(\"pcclient\".telent, '[^0-9]', '') = REGEXP_REPLACE('" + textSearch + "', '[^0-9]', '')"; - break; - case "cellphone": - where += "REGEXP_REPLACE(\"pcclient\".telcelent, '[^0-9]', '') = REGEXP_REPLACE('" + textSearch + "', '[^0-9]', '')"; - break; - case "customerId": - where += "\"pcclient\".codcli = " + textSearch; - break; - default: - throw new HttpException('Não foi informado um campo válido para pesquisa.', HttpStatus.BAD_REQUEST); - } - - const connection = new Connection(connectionOptions); - await connection.connect(); - const queryRunner = connection.createQueryRunner(); - await queryRunner.connect(); - try { - const customers = await queryRunner.manager - .getRepository(Pcclient) - .createQueryBuilder('pcclient') - .select("\"pcclient\".codcli as \"customerId\"") - .addSelect("\"pcclient\".cliente as \"name\"") - .addSelect("\"pcclient\".emailnfe as \"email\"") - .addSelect("\"pcclient\".cgcent as \"cpfCnpj\"") - .addSelect("\"pcclient\".sexo as \"gender\"") - .addSelect("\"pcclient\".enderent as \"address\"") - .addSelect("\"pcclient\".numeroent as \"addressNumber\"") - .addSelect("\"pcclient\".bairroent as \"neighborhood\"") - .addSelect("\"pcclient\".complementoent as \"complement\"") - .addSelect("\"pcclient\".municent as \"city\"") - .addSelect("\"pcclient\".estent as \"state\"") - .addSelect("\"pcclient\".cepent as \"zipCode\"") - .addSelect("\"pcclient\".telent as \"phone\"") - .addSelect("\"pcclient\".telcelent as \"cellPhone\"") - .addSelect("\"pcclient\".codcategoria as \"categoryId\"") - .addSelect("\"pcclient\".codsubcategoria as \"subCategoryId\"") - .addSelect("\"pcclient\".codpraca as \"placeId\"") - .addSelect("\"pcclient\".ieent as \"numberState\"") - .addSelect("\"pcclient\".latitude as \"latitude\"") - .addSelect("\"pcclient\".longitude as \"longitude\"") - .addSelect("\"pcclient\".codmunicipio as \"ibgeCode\"") - .addSelect("\"pcclient\".codcidade as \"cityId\"") - .addSelect("\"pcclient\".esc_tipoeclieente as \"addressType\"") - .where(where) - .andWhere("\"pcclient\".CODCLI NOT IN (2) AND \"pcclient\".DTEXCLUSAO IS NULL") - .getRawMany(); - return customers; - } catch (error) { - console.log(error); - throw error; - } finally { - await queryRunner.release(); - await connection.close(); - } + const connection = new Connection(connectionOptions); + await connection.connect(); + const queryRunner = connection.createQueryRunner(); + await queryRunner.connect(); + try { + const customers = await queryRunner.manager + .getRepository(Pcclient) + .createQueryBuilder('pcclient') + .select('"pcclient".codcli as "customerId"') + .addSelect('"pcclient".cliente as "name"') + .addSelect('"pcclient".emailnfe as "email"') + .addSelect('"pcclient".cgcent as "cpfCnpj"') + .addSelect('"pcclient".sexo as "gender"') + .addSelect('"pcclient".enderent as "address"') + .addSelect('"pcclient".numeroent as "addressNumber"') + .addSelect('"pcclient".bairroent as "neighborhood"') + .addSelect('"pcclient".complementoent as "complement"') + .addSelect('"pcclient".municent as "city"') + .addSelect('"pcclient".estent as "state"') + .addSelect('"pcclient".cepent as "zipCode"') + .addSelect('"pcclient".telent as "phone"') + .addSelect('"pcclient".telcelent as "cellPhone"') + .addSelect('"pcclient".codcategoria as "categoryId"') + .addSelect('"pcclient".codsubcategoria as "subCategoryId"') + .addSelect('"pcclient".codpraca as "placeId"') + .addSelect('"pcclient".ieent as "numberState"') + .addSelect('"pcclient".latitude as "latitude"') + .addSelect('"pcclient".longitude as "longitude"') + .addSelect('"pcclient".codmunicipio as "ibgeCode"') + .addSelect('"pcclient".codcidade as "cityId"') + .addSelect('"pcclient".esc_tipoeclieente as "addressType"') + .where(where) + .andWhere( + '"pcclient".CODCLI NOT IN (2) AND "pcclient".DTEXCLUSAO IS NULL', + ) + .getRawMany(); + return customers; + } catch (error) { + console.log(error); + throw error; + } finally { + await queryRunner.release(); + await connection.close(); } + } - async createCustomer(customer: Customer) { - try { - console.log("Dados consumer: " + JSON.stringify(customer)); - const newCustomer = await this.InitializeCustomer(); - newCustomer.tipofj = (customer.company == 'true' ? "J" : "F"); - newCustomer.ieent = (customer.company == 'true' ? customer.numberState : "ISENTO"); - newCustomer.inscestadual = newCustomer.ieent; - newCustomer.cgcent = customer.cpfCnpj; - newCustomer.sexo = customer.gender; - newCustomer.cgcentrega = customer.cpfCnpj; - newCustomer.cliente = customer.name.toUpperCase(); - newCustomer.fantasia = newCustomer.cliente; - newCustomer.email = customer.email.toLowerCase(); - newCustomer.emailnfe = customer.email.toLowerCase(); - newCustomer.telent = customer.cellPhone; - newCustomer.telcelent = customer.cellPhone; - newCustomer.celularwhatsapp = customer.cellPhone; - newCustomer.codusur1 = customer.sellerId; - newCustomer.codatv1 = ( customer.ramo != null && customer.ramo.id > 0 ) ? customer.ramo.id : newCustomer.codatv1; - //Endereço de entrega - newCustomer.cepent = customer.zipCode; - newCustomer.enderent = customer.address.toUpperCase(); - newCustomer.numeroent = customer.addressNumber; - if ( customer.complement !== null && customer.complement.length > 80 ) { - newCustomer.complementoent = customer.complement.substring(0, 80 ).toUpperCase(); - } else { - if ( customer.complement != null ) { - newCustomer.complementoent = customer.complement.toUpperCase(); - } - } - newCustomer.bairroent = customer.neighborhood.toUpperCase(); - newCustomer.municent = customer.city.toUpperCase(); - newCustomer.estent = customer.state.toUpperCase(); - //Endereço de comercial - newCustomer.cepcom = customer.zipCode; - newCustomer.endercom = customer.address.toUpperCase(); - newCustomer.numerocom = customer.addressNumber.toUpperCase(); - if ( customer.complement !== null && customer.complement.length > 80 ) { - newCustomer.complementocom = customer.complement.substring(0, 80 ).toUpperCase(); - } else { - if ( customer.complement != null ) { - newCustomer.complementocom = customer.complement.toUpperCase(); - } - } - newCustomer.bairrocom = customer.neighborhood.toUpperCase(); - newCustomer.municcom = customer.city.toUpperCase(); - newCustomer.estcom = customer.state.toUpperCase(); - //Endereço de cobrança - newCustomer.cepcob = customer.zipCode; - newCustomer.endercob = customer.address.toUpperCase(); - newCustomer.numerocob = customer.addressNumber; - if ( customer.complement !== null && customer.complement.length > 80 ) { - newCustomer.complementocob = customer.complement.substring(0, 80 ).toUpperCase(); - } else { - if ( customer.complement ) { - newCustomer.complementocob = customer.complement.toUpperCase(); - } - } - newCustomer.bairrocob = customer.neighborhood.toUpperCase(); - newCustomer.municcob = customer.city.toUpperCase(); - newCustomer.estcob = customer.state.toUpperCase(); - newCustomer.codcategoria = (customer.category != null) ? customer.category.id : null; - newCustomer.codsubcategoria = (customer.subCategory != null) ? customer.subCategory.id : null; - newCustomer.codpraca = customer.place.id; - newCustomer.codcidade = customer.ibgeCode != null ? await this.findCity(customer.ibgeCode) : null; - newCustomer.codmunicipio = Number.parseInt(customer.ibgeCode); - newCustomer.codcidadecom = newCustomer.codcidade; - newCustomer.dtnasc = customer.birthdate; - newCustomer.meiocomunicacao = customer.communicate; - newCustomer.codfunccad = customer.idUser; - newCustomer.codfunccadastro = customer.idUser; - newCustomer.codfuncultalter = customer.idUser; - newCustomer.dtultalter = new Date(); - newCustomer.latitude = customer.latitude; - newCustomer.longitude = customer.longitude; - newCustomer.tipoendereco = customer.addressType; - - const oldCustomer = await this.findCustomerByCpf(newCustomer.cgcent); - if (oldCustomer) { - console.log('Cliente localizado: ' + oldCustomer.customerId); - newCustomer.codcli = oldCustomer.customerId; - await this.updateCustomer(newCustomer); - return { - customerId: oldCustomer.customerId, - company: customer.company, name: customer.name, sexo: customer.gender, - cpfCnpj: customer.cpfCnpj, numberState: customer.numberState, - email: customer.email, zipCode: customer.zipCode, address: customer.address, - addressNumber: customer.addressNumber, complement: customer.complement, - neighborhood: customer.neighborhood, - city: customer.city, state: customer.state, - allowMessage: customer.allowMessage, cellPhone: customer.cellPhone, - 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, - }; - } else { - const idCustomer = await this.generateIdCustomer(); - if (idCustomer == -1) - return new HttpException("Erro ao gerar númeração de cliente.", HttpStatus.INTERNAL_SERVER_ERROR); - newCustomer.codcli = idCustomer; - await this.insertCustomer(newCustomer); - return { - customerId: idCustomer, - company: customer.company, name: customer.name, - cpfCnpj: customer.cpfCnpj, gender: customer.gender, numberState: customer.numberState, - email: customer.email, zipCode: customer.zipCode, address: customer.address, - addressNumber: customer.addressNumber, complement: customer.complement, - neighborhood: customer.neighborhood, - city: customer.city, state: customer.state, - allowMessage: customer.allowMessage, cellPhone: customer.cellPhone, - category: customer.category, 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) { - throw error; + async createCustomer(customer: Customer) { + try { + console.log('Dados consumer: ' + JSON.stringify(customer)); + const newCustomer = await this.InitializeCustomer(); + newCustomer.tipofj = customer.company == 'true' ? 'J' : 'F'; + newCustomer.ieent = + customer.company == 'true' ? customer.numberState : 'ISENTO'; + newCustomer.inscestadual = newCustomer.ieent; + newCustomer.cgcent = customer.cpfCnpj; + newCustomer.sexo = customer.gender; + newCustomer.cgcentrega = customer.cpfCnpj; + newCustomer.cliente = customer.name.toUpperCase(); + newCustomer.fantasia = newCustomer.cliente; + newCustomer.email = customer.email.toLowerCase(); + newCustomer.emailnfe = customer.email.toLowerCase(); + newCustomer.telent = customer.cellPhone; + newCustomer.telcelent = customer.cellPhone; + newCustomer.celularwhatsapp = customer.cellPhone; + newCustomer.codusur1 = customer.sellerId; + newCustomer.codatv1 = + customer.ramo != null && customer.ramo.id > 0 + ? customer.ramo.id + : newCustomer.codatv1; + //Endereço de entrega + newCustomer.cepent = customer.zipCode; + newCustomer.enderent = customer.address.toUpperCase(); + newCustomer.numeroent = customer.addressNumber; + if (customer.complement !== null && customer.complement.length > 80) { + newCustomer.complementoent = customer.complement + .substring(0, 80) + .toUpperCase(); + } else { + if (customer.complement != null) { + newCustomer.complementoent = customer.complement.toUpperCase(); } - } - - async updateCustomer(client: Pcclient) { - const connection = new Connection(connectionOptions); - await connection.connect(); - const queryRunner = connection.createQueryRunner(); - await queryRunner.connect(); - await queryRunner.startTransaction(); - try { - console.log("MEIO DE COMUNICACAO: " + client.meiocomunicacao); - await queryRunner.manager - .createQueryBuilder() - .update(Pcclient) - .set({ - cliente: client.cliente, - fantasia: client.cliente, - telcelent: client.telcelent, - sexo: client.sexo, - telent: client.telent, - email: client.email, - emailnfe: client.email, - cepent: client.cepent, - enderent: client.enderent, - numeroent: client.numeroent, - complementoent: client.complementoent, - bairroent: client.bairroent, - municent: client.municent, - estent: client.estent, - cepcob: client.cepent, - endercob: client.enderent, - numerocob: client.numeroent, - complementocob: client.complementoent, - bairrocob: client.bairroent, - municcob: client.municent, - estcob: client.estent, - cepcom: client.cepent, - endercom: client.enderent, - numerocom: client.numeroent, - complementocom: client.complementoent, - bairrocom: client.bairroent, - municcom: client.municent, - estcom: client.estent, - codcategoria: client.codcategoria, - codsubcategoria: client.codsubcategoria, - codpraca: client.codpraca, - codcidade: client.codcidade, - codmunicipio: client.codmunicipio, - codcidadecom: client.codcidade, - dtnasc: client.dtnasc, - codatv1: client.codatv1, - meiocomunicacao: client.meiocomunicacao, - codfuncultalter: client.codfuncultalter, - dtultalter: client.dtultalter, - latitude: client.latitude, - longitude: client.longitude, - tipoendereco: client.tipoendereco - }) - .where({ codcli: client.codcli }) - .execute(); - await queryRunner.commitTransaction(); - return client; - } catch (err) { - await queryRunner.rollbackTransaction(); - throw err; - } finally { - if ( queryRunner.isTransactionActive) { - await queryRunner.rollbackTransaction(); - } - await queryRunner.release(); - await connection.close(); + } + newCustomer.bairroent = customer.neighborhood.toUpperCase(); + newCustomer.municent = customer.city.toUpperCase(); + newCustomer.estent = customer.state.toUpperCase(); + //Endereço de comercial + newCustomer.cepcom = customer.zipCode; + newCustomer.endercom = customer.address.toUpperCase(); + newCustomer.numerocom = customer.addressNumber.toUpperCase(); + if (customer.complement !== null && customer.complement.length > 80) { + newCustomer.complementocom = customer.complement + .substring(0, 80) + .toUpperCase(); + } else { + if (customer.complement != null) { + newCustomer.complementocom = customer.complement.toUpperCase(); } - - } - - async findCity(ibgeCode: string) { - if (ibgeCode == null) { - return 0; - } - const connection = new Connection(connectionOptions); - await connection.connect(); - const queryRunner = connection.createQueryRunner(); - await queryRunner.connect(); - try { - const city = await queryRunner.query('SELECT PCCIDADE.CODCIDADE as "codigoCidade" FROM PCCIDADE WHERE PCCIDADE.codibge = :1', [ibgeCode]); - let cityId = 0; - if (city.length > 0) { - cityId = city[0].codigoCidade; - } - return cityId; - } catch (err) { - throw err; - } finally { - await queryRunner.release(); - await connection.close(); + } + newCustomer.bairrocom = customer.neighborhood.toUpperCase(); + newCustomer.municcom = customer.city.toUpperCase(); + newCustomer.estcom = customer.state.toUpperCase(); + //Endereço de cobrança + newCustomer.cepcob = customer.zipCode; + newCustomer.endercob = customer.address.toUpperCase(); + newCustomer.numerocob = customer.addressNumber; + if (customer.complement !== null && customer.complement.length > 80) { + newCustomer.complementocob = customer.complement + .substring(0, 80) + .toUpperCase(); + } else { + if (customer.complement) { + newCustomer.complementocob = customer.complement.toUpperCase(); } + } + newCustomer.bairrocob = customer.neighborhood.toUpperCase(); + newCustomer.municcob = customer.city.toUpperCase(); + newCustomer.estcob = customer.state.toUpperCase(); + newCustomer.codcategoria = + customer.category != null ? customer.category.id : null; + newCustomer.codsubcategoria = + customer.subCategory != null ? customer.subCategory.id : null; + newCustomer.codpraca = customer.place.id; + newCustomer.codcidade = + customer.ibgeCode != null + ? await this.findCity(customer.ibgeCode) + : null; + newCustomer.codmunicipio = Number.parseInt(customer.ibgeCode); + newCustomer.codcidadecom = newCustomer.codcidade; + newCustomer.dtnasc = customer.birthdate; + newCustomer.meiocomunicacao = customer.communicate; + newCustomer.codfunccad = customer.idUser; + newCustomer.codfunccadastro = customer.idUser; + newCustomer.codfuncultalter = customer.idUser; + newCustomer.dtultalter = new Date(); + newCustomer.latitude = customer.latitude; + newCustomer.longitude = customer.longitude; + newCustomer.tipoendereco = customer.addressType; + + const oldCustomer = await this.findCustomerByCpf(newCustomer.cgcent); + if (oldCustomer) { + console.log('Cliente localizado: ' + oldCustomer.customerId); + newCustomer.codcli = oldCustomer.customerId; + await this.updateCustomer(newCustomer); + return { + customerId: oldCustomer.customerId, + company: customer.company, + name: customer.name, + sexo: customer.gender, + cpfCnpj: customer.cpfCnpj, + numberState: customer.numberState, + email: customer.email, + zipCode: customer.zipCode, + address: customer.address, + addressNumber: customer.addressNumber, + complement: customer.complement, + neighborhood: customer.neighborhood, + city: customer.city, + state: customer.state, + allowMessage: customer.allowMessage, + cellPhone: customer.cellPhone, + 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, + }; + } else { + const idCustomer = await this.generateIdCustomer(); + if (idCustomer == -1) + return new HttpException( + 'Erro ao gerar númeração de cliente.', + HttpStatus.INTERNAL_SERVER_ERROR, + ); + newCustomer.codcli = idCustomer; + await this.insertCustomer(newCustomer); + return { + customerId: idCustomer, + company: customer.company, + name: customer.name, + cpfCnpj: customer.cpfCnpj, + gender: customer.gender, + numberState: customer.numberState, + email: customer.email, + zipCode: customer.zipCode, + address: customer.address, + addressNumber: customer.addressNumber, + complement: customer.complement, + neighborhood: customer.neighborhood, + city: customer.city, + state: customer.state, + allowMessage: customer.allowMessage, + cellPhone: customer.cellPhone, + category: customer.category, + 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) { + throw error; } + } - async InitializeCustomer() { - const cliente = new Pcclient(); - cliente.codusur1 = 1; - cliente.codplpag = 10; - cliente.codpraca = 119; - cliente.codcob = "D"; - cliente.dtcadastro = new Date(); - cliente.codcontab = "1"; - cliente.aceitavendafracao = "N"; - //cliente.Meiocomunicacao = "N"; - cliente.bloqueio = "N"; - cliente.bloqueiosefaz = "N"; - cliente.bloqueiosefazped = "N"; - cliente.bloqvendapf = "N"; - cliente.condvenda1 = "S"; - cliente.condvenda5 = "S"; - cliente.condvenda7 = "S"; - cliente.condvenda8 = "S"; - cliente.contribuinte = "N"; - cliente.validarmultiplovenda = "N"; - cliente.codfunccad = 1; - cliente.codfunccadastro = 1; - cliente.horacadastro = new Date(); - cliente.dtcadastro = new Date(); - cliente.dtultvisita = new Date(); - cliente.codatv1 = 7; - cliente.aceitatrocanegativa = "N"; - cliente.consumidorfinal = "S"; - cliente.aplicadescnf = "S"; - cliente.simplesnacional = "N"; - cliente.sexo = "M"; - cliente.isencaosuframa = "T"; - cliente.clicrm = "N"; - cliente.tv10usacustoproduto = "N"; - cliente.inscestadual = "ISENTO"; - cliente.codpais = 1058; //Brasil - cliente.observacao = "Importado do E-Commerce"; - cliente.aceitachterceiros = "S"; - cliente.agregarvalorstdescfin = "N"; - cliente.anvisa = "N"; - cliente.aplicredbaseicmstransp = "N"; - cliente.atendedomingo = "N"; - cliente.atendequarta = "N"; - cliente.atendequinta = "N"; - cliente.atendesabado = "N"; - cliente.atendesegunda = "N"; - cliente.atendesexta = "N"; - cliente.atendeterca = "N"; - cliente.atualizasaldoccdescfin = "N"; - cliente.bloqremcob = "N"; - cliente.clientedan = "N"; - cliente.clientefontest = "N"; - cliente.clientemonitorado = "N"; - cliente.clientprotesto = "S"; - cliente.fretedespacho = "0"; - cliente.aceitavendafracao = "S"; - cliente.validarmultiplovenda = "S"; - - return cliente; + async updateCustomer(client: Pcclient) { + const connection = new Connection(connectionOptions); + await connection.connect(); + const queryRunner = connection.createQueryRunner(); + await queryRunner.connect(); + await queryRunner.startTransaction(); + try { + console.log('MEIO DE COMUNICACAO: ' + client.meiocomunicacao); + await queryRunner.manager + .createQueryBuilder() + .update(Pcclient) + .set({ + cliente: client.cliente, + fantasia: client.cliente, + telcelent: client.telcelent, + sexo: client.sexo, + telent: client.telent, + email: client.email, + emailnfe: client.email, + cepent: client.cepent, + enderent: client.enderent, + numeroent: client.numeroent, + complementoent: client.complementoent, + bairroent: client.bairroent, + municent: client.municent, + estent: client.estent, + cepcob: client.cepent, + endercob: client.enderent, + numerocob: client.numeroent, + complementocob: client.complementoent, + bairrocob: client.bairroent, + municcob: client.municent, + estcob: client.estent, + cepcom: client.cepent, + endercom: client.enderent, + numerocom: client.numeroent, + complementocom: client.complementoent, + bairrocom: client.bairroent, + municcom: client.municent, + estcom: client.estent, + codcategoria: client.codcategoria, + codsubcategoria: client.codsubcategoria, + codpraca: client.codpraca, + codcidade: client.codcidade, + codmunicipio: client.codmunicipio, + codcidadecom: client.codcidade, + dtnasc: client.dtnasc, + codatv1: client.codatv1, + meiocomunicacao: client.meiocomunicacao, + codfuncultalter: client.codfuncultalter, + dtultalter: client.dtultalter, + latitude: client.latitude, + longitude: client.longitude, + tipoendereco: client.tipoendereco, + }) + .where({ codcli: client.codcli }) + .execute(); + await queryRunner.commitTransaction(); + return client; + } catch (err) { + await queryRunner.rollbackTransaction(); + throw err; + } finally { + if (queryRunner.isTransactionActive) { + await queryRunner.rollbackTransaction(); + } + await queryRunner.release(); + await connection.close(); } + } - async generateIdCustomer() { - console.log("Gerando idcustomer"); - const connection = new Connection(connectionOptions); - const queryRunner = connection.createQueryRunner(); - try { - - await connection.connect(); - - await queryRunner.connect(); - - // lets now open a new transaction: - await queryRunner.startTransaction(); - - - let sql = `SELECT PROXNUMCLI as "proxnumcli" FROM PCCONSUM WHERE 1 = 1 FOR UPDATE`; - let param = await queryRunner.query(sql); - - // const param = await queryRunner.manager - // .getRepository(Pcconsum) - // .createQueryBuilder('pcconsum') - // .setLock("dirty_read") - // .getOne(); - - const idCustomer = param[0].proxnumcli; - console.log(idCustomer); - sql = `UPDATE PCCONSUM SET PROXNUMCLI = NVL(PROXNUMCLI,0) + 1`; - param = await queryRunner.query(sql); - // await queryRunner.manager - // .createQueryBuilder() - // .update(Pcconsum) - // .set({ proxnumcli: idCustomer + 1 }) - // .execute(); - - // commit transaction now: - await queryRunner.commitTransaction(); - return idCustomer; - - } catch (err) { - // since we have errors let's rollback changes we made - if ( queryRunner.isTransactionActive) { - await queryRunner.rollbackTransaction(); - } - console.log(err); - return -1; - - } finally { - if ( queryRunner.isTransactionActive) { - await queryRunner.rollbackTransaction(); - } - // you need to release query runner which is manually created: - await queryRunner.release(); - await connection.close(); - } + async findCity(ibgeCode: string) { + if (ibgeCode == null) { + return 0; } - - async insertCustomer(client: Pcclient) { - console.log(client); - const connection = new Connection(connectionOptions); - await connection.connect(); - const queryRunner = connection.createQueryRunner(); - await queryRunner.connect(); - await queryRunner.startTransaction(); - try { - await queryRunner.manager - .createQueryBuilder() - .insert() - .into(Pcclient) - .values(client) - .execute(); - await queryRunner.commitTransaction(); - return client; - } catch (err) { - await queryRunner.rollbackTransaction(); - console.log(err); - throw err; - } finally { - if ( queryRunner.isTransactionActive) { - await queryRunner.rollbackTransaction(); - } - await queryRunner.release(); - await connection.close(); - } + const connection = new Connection(connectionOptions); + await connection.connect(); + const queryRunner = connection.createQueryRunner(); + await queryRunner.connect(); + try { + const city = await queryRunner.query( + 'SELECT PCCIDADE.CODCIDADE as "codigoCidade" FROM PCCIDADE WHERE PCCIDADE.codibge = :1', + [ibgeCode], + ); + let cityId = 0; + if (city.length > 0) { + cityId = city[0].codigoCidade; + } + return cityId; + } catch (err) { + throw err; + } finally { + await queryRunner.release(); + await connection.close(); } + } - async getCategory() { - const connectionDb = new Connection(connectionOptions) - await connectionDb.connect(); - const queryRunner = connectionDb.createQueryRunner(); - await queryRunner.connect(); - try { - return await queryRunner.manager - .getRepository(Estcategoriacliente) - .createQueryBuilder("estcategoriacliente") - .getMany(); + async InitializeCustomer() { + const cliente = new Pcclient(); + cliente.codusur1 = 1; + cliente.codplpag = 10; + cliente.codpraca = 119; + cliente.codcob = 'D'; + cliente.dtcadastro = new Date(); + cliente.codcontab = '1'; + cliente.aceitavendafracao = 'N'; + //cliente.Meiocomunicacao = "N"; + cliente.bloqueio = 'N'; + cliente.bloqueiosefaz = 'N'; + cliente.bloqueiosefazped = 'N'; + cliente.bloqvendapf = 'N'; + cliente.condvenda1 = 'S'; + cliente.condvenda5 = 'S'; + cliente.condvenda7 = 'S'; + cliente.condvenda8 = 'S'; + cliente.contribuinte = 'N'; + cliente.validarmultiplovenda = 'N'; + cliente.codfunccad = 1; + cliente.codfunccadastro = 1; + cliente.horacadastro = new Date(); + cliente.dtcadastro = new Date(); + cliente.dtultvisita = new Date(); + cliente.codatv1 = 7; + cliente.aceitatrocanegativa = 'N'; + cliente.consumidorfinal = 'S'; + cliente.aplicadescnf = 'S'; + cliente.simplesnacional = 'N'; + cliente.sexo = 'M'; + cliente.isencaosuframa = 'T'; + cliente.clicrm = 'N'; + cliente.tv10usacustoproduto = 'N'; + cliente.inscestadual = 'ISENTO'; + cliente.codpais = 1058; //Brasil + cliente.observacao = 'Importado do E-Commerce'; + cliente.aceitachterceiros = 'S'; + cliente.agregarvalorstdescfin = 'N'; + cliente.anvisa = 'N'; + cliente.aplicredbaseicmstransp = 'N'; + cliente.atendedomingo = 'N'; + cliente.atendequarta = 'N'; + cliente.atendequinta = 'N'; + cliente.atendesabado = 'N'; + cliente.atendesegunda = 'N'; + cliente.atendesexta = 'N'; + cliente.atendeterca = 'N'; + cliente.atualizasaldoccdescfin = 'N'; + cliente.bloqremcob = 'N'; + cliente.clientedan = 'N'; + cliente.clientefontest = 'N'; + cliente.clientemonitorado = 'N'; + cliente.clientprotesto = 'S'; + cliente.fretedespacho = '0'; + cliente.aceitavendafracao = 'S'; + cliente.validarmultiplovenda = 'S'; - } catch (err) { - console.log(err); - throw err; - } finally { - await queryRunner.release(); - await connectionDb.close(); - } + return cliente; + } + + async generateIdCustomer() { + console.log('Gerando idcustomer'); + const connection = new Connection(connectionOptions); + const queryRunner = connection.createQueryRunner(); + try { + await connection.connect(); + + await queryRunner.connect(); + + // lets now open a new transaction: + await queryRunner.startTransaction(); + + let sql = `SELECT PROXNUMCLI as "proxnumcli" FROM PCCONSUM WHERE 1 = 1 FOR UPDATE`; + let param = await queryRunner.query(sql); + + // const param = await queryRunner.manager + // .getRepository(Pcconsum) + // .createQueryBuilder('pcconsum') + // .setLock("dirty_read") + // .getOne(); + + const idCustomer = param[0].proxnumcli; + console.log(idCustomer); + sql = `UPDATE PCCONSUM SET PROXNUMCLI = NVL(PROXNUMCLI,0) + 1`; + param = await queryRunner.query(sql); + // await queryRunner.manager + // .createQueryBuilder() + // .update(Pcconsum) + // .set({ proxnumcli: idCustomer + 1 }) + // .execute(); + + // commit transaction now: + await queryRunner.commitTransaction(); + return idCustomer; + } catch (err) { + // since we have errors let's rollback changes we made + if (queryRunner.isTransactionActive) { + await queryRunner.rollbackTransaction(); + } + console.log(err); + return -1; + } finally { + if (queryRunner.isTransactionActive) { + await queryRunner.rollbackTransaction(); + } + // you need to release query runner which is manually created: + await queryRunner.release(); + await connection.close(); } + } - async getSubCategory() { - const connectionDb = new Connection(connectionOptions) - await connectionDb.connect(); - const queryRunner = connectionDb.createQueryRunner(); - await queryRunner.connect(); - try { - return await queryRunner.manager - .getRepository(Estsubcategoriacliente) - .createQueryBuilder("estsubcategoriacliente") - .getMany(); - - } catch (err) { - console.log(err); - throw err; - } finally { - await queryRunner.release(); - await connectionDb.close(); - } + async insertCustomer(client: Pcclient) { + console.log(client); + const connection = new Connection(connectionOptions); + await connection.connect(); + const queryRunner = connection.createQueryRunner(); + await queryRunner.connect(); + await queryRunner.startTransaction(); + try { + await queryRunner.manager + .createQueryBuilder() + .insert() + .into(Pcclient) + .values(client) + .execute(); + await queryRunner.commitTransaction(); + return client; + } catch (err) { + await queryRunner.rollbackTransaction(); + console.log(err); + throw err; + } finally { + if (queryRunner.isTransactionActive) { + await queryRunner.rollbackTransaction(); + } + await queryRunner.release(); + await connection.close(); } + } -} + async getCategory() { + const connectionDb = new Connection(connectionOptions); + await connectionDb.connect(); + const queryRunner = connectionDb.createQueryRunner(); + await queryRunner.connect(); + try { + return await queryRunner.manager + .getRepository(Estcategoriacliente) + .createQueryBuilder('estcategoriacliente') + .getMany(); + } catch (err) { + console.log(err); + throw err; + } finally { + await queryRunner.release(); + await connectionDb.close(); + } + } + + async getSubCategory() { + const connectionDb = new Connection(connectionOptions); + await connectionDb.connect(); + const queryRunner = connectionDb.createQueryRunner(); + await queryRunner.connect(); + try { + return await queryRunner.manager + .getRepository(Estsubcategoriacliente) + .createQueryBuilder('estsubcategoriacliente') + .getMany(); + } catch (err) { + console.log(err); + throw err; + } finally { + await queryRunner.release(); + await connectionDb.close(); + } + } +} \ No newline at end of file