Compare commits

...

36 Commits

Author SHA1 Message Date
Felipe Batista 15d8fecf42 teste2
Deploy NestJS API / build-and-push-deploy (push) Successful in 41s Details
2026-01-10 11:52:42 -03:00
Felipe Batista c5f284023a teste
Deploy NestJS API / build-and-push-deploy (push) Has been cancelled Details
2026-01-10 11:49:31 -03:00
joelson df466ddaba fix: update server port from 8065 to 8068
Deploy NestJS API / build-and-push-deploy (push) Successful in 4m29s Details
2026-01-09 09:27:19 -03:00
joelson 6360675ebf teste
Deploy NestJS API / build-and-push-deploy (push) Successful in 4m41s Details
2026-01-08 19:41:28 -03:00
joelson cedcb43939 :ajuste na porta para 8065
Deploy NestJS API / build-and-push-deploy (push) Successful in 4m33s Details
2026-01-08 19:03:00 -03:00
joelson b330910fbf feat: ajustado a entidade cliente
Deploy NestJS API / build-and-push-deploy (push) Successful in 3m44s Details
2026-01-08 18:53:59 -03:00
joelson 94f9208ee4 Refactor code structure for improved readability and maintainability
Deploy NestJS API / build-and-push-deploy (push) Failing after 1m34s Details
2026-01-08 18:43:22 -03:00
joelson 4e926909b8 fix: update health check status message to 'TESTE COM ALESSANDRO'
Deploy NestJS API / build-and-push-deploy (push) Successful in 3m40s Details
2026-01-06 12:26:43 -03:00
joelson 70e88913f5 refactor: simplify image tagging and pushing in deployment workflow
Deploy NestJS API / build-and-push-deploy (push) Successful in 2m8s Details
2026-01-06 12:23:33 -03:00
joelson 217329adef Merge branch 'main' of https://git.jurunense.com/joelson/vendaweb-api
Deploy NestJS API / build-and-push-deploy (push) Has been cancelled Details
2026-01-06 12:22:29 -03:00
joelson f55d0da72d refactor: update port mappings to 8068, enhance deployment configurations, and modify health check response 2026-01-06 12:20:43 -03:00
JuruSysadmin 2b91449137 fix: update health check status message to 'JURUNENSE HOME CENTER BR V2'
Deploy NestJS API / build-and-push-deploy (push) Successful in 2m42s Details
2026-01-06 11:18:19 -03:00
JuruSysadmin 95850ea39b fix: update health check status message to 'JURUNENSE HOME CENTER BR'
Deploy NestJS API / build-and-push-deploy (push) Successful in 2m48s Details
2026-01-06 11:07:03 -03:00
JuruSysadmin 1760934db3 fix: update health check response status message to 'JURUNENSE HOME CENTER'
Deploy NestJS API / build-and-push-deploy (push) Successful in 2m42s Details
2026-01-06 10:59:26 -03:00
JuruSysadmin 7b2f13ab91 fix: update health check status response to ':ok 4'
Deploy NestJS API / build-and-push-deploy (push) Successful in 2m51s Details
2026-01-06 10:52:49 -03:00
joelson f66fd4271f :ok
Deploy NestJS API / build-and-push-deploy (push) Successful in 2m45s Details
2026-01-05 15:50:31 -03:00
joelson c60eabd804 feat: Configure host-mode port mapping and a stop-first deployment strategy with rollback, removing local build.
Deploy NestJS API / build-and-push-deploy (push) Successful in 3m1s Details
2026-01-05 15:39:49 -03:00
joelson 9176d65606 refactor: Update workflow name, SHA source, Docker image tagging, and Portainer webhook notification.
Deploy NestJS API / build-and-push-deploy (push) Successful in 30s Details
2026-01-05 15:23:32 -03:00
joelson 1fa2938128 fix: remove accidental '7' character from WEBHOOK_URL secret definition in deploy workflow 2026-01-05 15:11:25 -03:00
joelson efc7d738a9 refactor: streamline Docker build/push and add webhook secret validation to deployment workflow.
Deploy vendaweb-api / build-and-push-deploy (push) Successful in 29s Details
2026-01-05 15:09:22 -03:00
joelson bf246e2882 chore: update API startup console log message
Deploy vendaweb-api / build-and-push-deploy (push) Successful in 1m2s Details
2026-01-05 14:56:17 -03:00
joelson fb724067c8 style: adjust whitespace in getVersion method
Deploy vendaweb-api / build-and-push-deploy (push) Successful in 3m14s Details
2026-01-05 14:50:27 -03:00
joelson e9c7d8d282 chore: Update health check endpoint status message.
Deploy vendaweb-api / build-and-push-deploy (push) Successful in 3m7s Details
2026-01-05 14:43:23 -03:00
joelson a92fa77e37 feat: Configure `vendaweb-api` service to build locally and connect to an external `juru-network`.
Deploy vendaweb-api / build-and-push-deploy (push) Successful in 3m39s Details
2026-01-05 14:34:15 -03:00
joelson e6fd33a22e fix: remove unused networks section from docker-compose.yml
Deploy vendaweb-api / build-and-push-deploy (push) Successful in 30s Details
2026-01-05 14:23:33 -03:00
joelson c75f8ed9f4 fix: comment out networks section in docker-compose.yml
Deploy vendaweb-api / build-and-push-deploy (push) Successful in 32s Details
2026-01-05 14:21:22 -03:00
joelson b034330e34 fix: add console log to indicate API is running on port 8066
Deploy vendaweb-api / build-and-push-deploy (push) Successful in 2m44s Details
2026-01-05 14:05:40 -03:00
joelson 61cdae600c fix: ensure server listens on all network interfaces in main.ts 2026-01-05 14:05:14 -03:00
joelson 6fe94a4a7c refactor: clean up Dockerfile by removing unnecessary comments and consolidating commands
Deploy vendaweb-api / build-and-push-deploy (push) Successful in 2m46s Details
2026-01-05 14:00:11 -03:00
joelson 0084a162f7 fix: correct port mapping in docker-compose.yml for vendaweb-api
Deploy vendaweb-api / build-and-push-deploy (push) Successful in 46s Details
2026-01-05 13:55:49 -03:00
joelson d5fa17151f fix: update Dockerfile CMD and change server port in main.ts
Deploy vendaweb-api / build-and-push-deploy (push) Successful in 50s Details
2026-01-05 13:29:57 -03:00
joelson 937b3f37ab fix: update vendaweb-api configuration in docker-compose.yml 2026-01-05 13:29:49 -03:00
joelson 7022d491ce feat: add deployment workflow for vendaweb-api
Deploy vendaweb-api / build-and-push-deploy (push) Failing after 1m19s Details
2026-01-05 12:12:54 -03:00
joelson c4e8996a22 feat: add deployment workflow for vendaweb-api 2026-01-05 12:00:48 -03:00
juru 757d547755 chore: ignora pastas de dados e arquivos sensiveis 2026-01-05 11:46:41 -03:00
juru 79fb04fdb5 first commit 2026-01-05 11:45:17 -03:00
10 changed files with 879 additions and 752 deletions

View File

@ -0,0 +1,30 @@
name: Deploy NestJS API
on: [push]
jobs:
build-and-push-deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Login no Harbor
run: |
echo "${{ secrets.HARBOR_PASSWORD }}" | docker login 10.1.1.124:8082 -u ${{ secrets.HARBOR_USERNAME }} --password-stdin
- name: Build e Push
run: |
# Usando o short SHA para uma tag mais limpa
TAG=$(echo ${{ gitea.sha }} | cut -c1-7)
IMAGE_NAME="10.1.1.124:8082/library/vendaweb-api"
docker build -t $IMAGE_NAME:$TAG .
docker tag $IMAGE_NAME:$TAG $IMAGE_NAME:latest
docker push $IMAGE_NAME:$TAG
docker push $IMAGE_NAME:latest
- name: Notificar Portainer via Webhook
run: |
# O segredo PORTAINER_WEBHOOK_VENDAWEBAPI deve conter a URL completa gerada na Stack
curl -f -X POST "${{ secrets.PORTAINER_WEBHOOK_VENDAWEBAPI }}"

2
.gitignore vendored
View File

@ -33,3 +33,5 @@ lerna-debug.log*
!.vscode/launch.json
!.vscode/extensions.json
postgres-data/
.env

View File

@ -1,32 +1,24 @@
FROM node:16
FROM node:16-bullseye-slim AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install --legacy-peer-deps
COPY . .
RUN npm run build
FROM node:16-bullseye-slim
RUN apt-get update && apt-get install -y libaio1 unzip wget && mkdir -p /opt/oracle
RUN apt-get update && apt-get install -y \
apt-transport-https \
ca-certificates \
libaio1 \
unzip \
wget \
libc6 \
libncurses5 && \
mkdir -p /opt/oracle && \
wget https://download.oracle.com/otn_software/linux/instantclient/instantclient-basic-linuxx64.zip -O /opt/oracle/instantclient-basic-linuxx64.zip && \
unzip /opt/oracle/instantclient-basic-linuxx64.zip -d /opt/oracle && \
rm /opt/oracle/instantclient-basic-linuxx64.zip && \
ln -s /opt/oracle/instantclient_* /opt/oracle/instantclient && \
echo "/opt/oracle/instantclient" > /etc/ld.so.conf.d/oracle-instantclient.conf && \
ldconfig
RUN wget https://download.oracle.com/otn_software/linux/instantclient/instantclient-basic-linuxx64.zip -O /opt/oracle/client.zip && \
unzip /opt/oracle/client.zip -d /opt/oracle && \
rm /opt/oracle/client.zip && \
ln -s /opt/oracle/instantclient_* /opt/oracle/instantclient
ENV LD_LIBRARY_PATH=/opt/oracle/instantclient
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package*.json ./
COPY --from=builder /app/node_modules ./node_modules
COPY package*.json ./
RUN npm install --legacy-peer-deps
COPY . .
EXPOSE 8068
CMD ["npm", "run", "start:prod"]

View File

@ -1,14 +1,18 @@
version: '3.8'
services:
vendaweb:
image: link70/vendaweb
deploy:
replicas: 20
resources:
limits:
cpus: '0.5'
memory: 512M
vendaweb-api:
image: 10.1.1.124:8082/library/vendaweb-api:latest
ports:
- "8065:8065"
restart: always
- "8068:8068"
networks:
- simplifique-network
deploy:
replicas: 4
update_config:
order: start-first
parallelism: 1
networks:
simplifique-network:
external: true

View File

@ -1,5 +1,5 @@
import { Controller, Get } from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { APP_VERSION } from './version';
@ApiTags('Main')
@ -14,7 +14,7 @@ export class AppController {
@Get('health')
@ApiOperation({ summary: 'Health check' })
healthCheck() {
return { status: 'ok' };
return { status: 'TESTE COM Felipe2 ' };
}
}

View File

@ -7,12 +7,12 @@ export const typeOrmConfig: TypeOrmModuleOptions = {
// username: "LIVIA",
// password: "LIVIA",
host: "10.1.1.241",
username: "SEVEN",
password: "USR54SEV",
username: "teste",
password: "teste",
// username: "API",
// password: "E05H5KIEQV3YKDJR",
port: 1521,
sid: "WINT",
sid: "BDTESTE",
synchronize: false,
logging: false,
entities: [__dirname + '/../**/*.entity.{js,ts}'],
@ -22,10 +22,10 @@ export const typeOrmConfig: TypeOrmModuleOptions = {
export const connectionOptions: ConnectionOptions = {
type: "oracle",
host: "10.1.1.241",
username: "SEVEN",
password: "USR54SEV",
username: "teste",
password: "teste",
port: 1521,
sid: "WINT",
sid: "BDTESTE",
synchronize: false,
logging: false,
entities: [__dirname + '/../**/*.entity.{js,ts}'],

View File

@ -20,6 +20,6 @@ async function bootstrap() {
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup("docs", app, document);
await app.listen(8065);
}
await app.listen(8068, '0.0.0.0');}
console.log('API rodando na porta 8065 test 4');
bootstrap();

View File

@ -1,14 +1,22 @@
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 {
constructor(private readonly customerService: CustomerService) {}
@Get(':name')
@ -17,8 +25,15 @@ export class CustomerController {
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);
throw new HttpException(
new ResultModel(
false,
'Não foi possível consultar o cadastro de clientes.',
{},
error,
),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
@ -28,8 +43,10 @@ export class CustomerController {
const categories = await this.customerService.getCategory();
return categories;
} catch (err) {
throw new HttpException(new ResultModel(false, err.message, {}, error),
HttpStatus.INTERNAL_SERVER_ERROR);
throw new HttpException(
new ResultModel(false, err.message, {}, error),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
@ -39,23 +56,29 @@ export class CustomerController {
const subCategories = await this.customerService.getSubCategory();
return subCategories;
} catch (err) {
throw new HttpException(new ResultModel(false, err.message, {}, error),
HttpStatus.INTERNAL_SERVER_ERROR);
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);
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);
throw new HttpException(
new ResultModel(false, err.message, {}, error),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
@ -65,21 +88,36 @@ export class CustomerController {
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);
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");
console.log('pesquisando por 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);
} catch (err) {
throw new HttpException(new ResultModel(false, 'Não foi possível consultar o cadastro de clientes.', {}, error),
HttpStatus.INTERNAL_SERVER_ERROR);
throw new HttpException(
new ResultModel(
false,
'Não foi possível consultar o cadastro de clientes.',
{},
error,
),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
@Get('create/proxnumcli')
@ -93,7 +131,6 @@ export class CustomerController {
}
}
@Post('create')
async createCustomer(@Body() customer: Customer) {
try {
@ -102,8 +139,10 @@ export class CustomerController {
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);
throw new HttpException(
new ResultModel(false, 'Erro ao cadastrar cliente.', {}, err),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
}

View File

@ -1,28 +1,26 @@
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("@", "%");
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" ' +
const sql =
' SELECT pcclient.cliente as "name" ' +
' ,pcclient.codcli as "customerId" ' +
' ,pcclient.emailnfe as "email" ' +
' ,pcclient.cgcent as "cpfCnpj" ' +
@ -52,17 +50,22 @@ export class CustomerService {
' ,pcclient.tipoendereco as "addressType" ' +
' FROM pcclient, pccidade ' +
' 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 ` +
` 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[] = [];
const customers = (await queryRunner.manager.query(
sql + where + orderBy + pagination,
)) as Customer[];
const customerList: Customer[] = [];
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"
,PCPRACA.PRACA as "name"
FROM PCPRACA
@ -87,7 +90,8 @@ export class CustomerService {
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const sql = ' SELECT pcclient.cliente as "name" ' +
const sql =
' SELECT pcclient.cliente as "name" ' +
' ,pcclient.codcli as "customerId" ' +
' ,pcclient.emailnfe as "email" ' +
' ,pcclient.cgcent as "cpfCnpj" ' +
@ -115,11 +119,12 @@ export class CustomerService {
' ,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[0];
return customer as Customer[];
} catch (error) {
console.log(error);
throw error;
@ -135,8 +140,8 @@ export class CustomerService {
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const sql = ' SELECT pcclient.cliente as "name" ' +
const sql =
' SELECT pcclient.cliente as "name" ' +
' ,pcclient.codcli as "customerId" ' +
' ,pcclient.emailnfe as "email" ' +
' ,pcclient.cgcent as "cpfCnpj" ' +
@ -184,25 +189,37 @@ export class CustomerService {
}
async findCustomerByQuery(field: string, textSearch: string) {
let where = "";
let where = '';
switch (field) {
case "name":
where += "\"pcclient\".cliente like '" + textSearch + "%'";
case 'name':
where += '"pcclient".cliente like \'' + textSearch + "%'";
break;
case "document":
where += "REGEXP_REPLACE(\"pcclient\".cgcent, '[^0-9]', '') = REGEXP_REPLACE('" + textSearch + "', '[^0-9]', '')";
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]', '')";
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]', '')";
case 'cellphone':
where +=
"REGEXP_REPLACE(\"pcclient\".telcelent, '[^0-9]', '') = REGEXP_REPLACE('" +
textSearch +
"', '[^0-9]', '')";
break;
case "customerId":
where += "\"pcclient\".codcli = " + textSearch;
case 'customerId':
where += '"pcclient".codcli = ' + textSearch;
break;
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);
@ -213,31 +230,33 @@ export class CustomerService {
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\"")
.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")
.andWhere(
'"pcclient".CODCLI NOT IN (2) AND "pcclient".DTEXCLUSAO IS NULL',
)
.getRawMany();
return customers;
} catch (error) {
@ -251,10 +270,11 @@ export class CustomerService {
async createCustomer(customer: Customer) {
try {
console.log("Dados consumer: " + JSON.stringify(customer));
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.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;
@ -267,13 +287,18 @@ export class CustomerService {
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;
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();
newCustomer.complementoent = customer.complement
.substring(0, 80)
.toUpperCase();
} else {
if (customer.complement != null) {
newCustomer.complementoent = customer.complement.toUpperCase();
@ -287,7 +312,9 @@ export class CustomerService {
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();
newCustomer.complementocom = customer.complement
.substring(0, 80)
.toUpperCase();
} else {
if (customer.complement != null) {
newCustomer.complementocom = customer.complement.toUpperCase();
@ -301,7 +328,9 @@ export class CustomerService {
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();
newCustomer.complementocob = customer.complement
.substring(0, 80)
.toUpperCase();
} else {
if (customer.complement) {
newCustomer.complementocob = customer.complement.toUpperCase();
@ -310,10 +339,15 @@ export class CustomerService {
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.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.codcidade =
customer.ibgeCode != null
? await this.findCity(customer.ibgeCode)
: null;
newCustomer.codmunicipio = Number.parseInt(customer.ibgeCode);
newCustomer.codcidadecom = newCustomer.codcidade;
newCustomer.dtnasc = customer.birthdate;
@ -326,44 +360,74 @@ export class CustomerService {
newCustomer.longitude = customer.longitude;
newCustomer.tipoendereco = customer.addressType;
const oldCustomer = await this.findCustomerByCpf(newCustomer.cgcent);
if (oldCustomer) {
const oldCustomers = await this.findCustomerByCpf(newCustomer.cgcent);
if (oldCustomers && oldCustomers.length > 0) {
const oldCustomer = oldCustomers[0];
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,
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,
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);
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,
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,
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) {
@ -378,7 +442,7 @@ export class CustomerService {
await queryRunner.connect();
await queryRunner.startTransaction();
try {
console.log("MEIO DE COMUNICACAO: " + client.meiocomunicacao);
console.log('MEIO DE COMUNICACAO: ' + client.meiocomunicacao);
await queryRunner.manager
.createQueryBuilder()
.update(Pcclient)
@ -424,7 +488,7 @@ export class CustomerService {
dtultalter: client.dtultalter,
latitude: client.latitude,
longitude: client.longitude,
tipoendereco: client.tipoendereco
tipoendereco: client.tipoendereco,
})
.where({ codcli: client.codcli })
.execute();
@ -440,7 +504,6 @@ export class CustomerService {
await queryRunner.release();
await connection.close();
}
}
async findCity(ibgeCode: string) {
@ -452,7 +515,10 @@ export class CustomerService {
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]);
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;
@ -471,68 +537,67 @@ export class CustomerService {
cliente.codusur1 = 1;
cliente.codplpag = 10;
cliente.codpraca = 119;
cliente.codcob = "D";
cliente.codcob = 'D';
cliente.dtcadastro = new Date();
cliente.codcontab = "1";
cliente.aceitavendafracao = "N";
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.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.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";
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 generateIdCustomer() {
console.log("Gerando idcustomer");
console.log('Gerando idcustomer');
const connection = new Connection(connectionOptions);
const queryRunner = connection.createQueryRunner();
try {
await connection.connect();
await queryRunner.connect();
@ -540,7 +605,6 @@ export class CustomerService {
// 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);
@ -563,7 +627,6 @@ export class CustomerService {
// commit transaction now:
await queryRunner.commitTransaction();
return idCustomer;
} catch (err) {
// since we have errors let's rollback changes we made
if (queryRunner.isTransactionActive) {
@ -571,7 +634,6 @@ export class CustomerService {
}
console.log(err);
return -1;
} finally {
if (queryRunner.isTransactionActive) {
await queryRunner.rollbackTransaction();
@ -612,16 +674,15 @@ export class CustomerService {
}
async getCategory() {
const connectionDb = new Connection(connectionOptions)
const connectionDb = new Connection(connectionOptions);
await connectionDb.connect();
const queryRunner = connectionDb.createQueryRunner();
await queryRunner.connect();
try {
return await queryRunner.manager
.getRepository(Estcategoriacliente)
.createQueryBuilder("estcategoriacliente")
.createQueryBuilder('estcategoriacliente')
.getMany();
} catch (err) {
console.log(err);
throw err;
@ -632,16 +693,15 @@ export class CustomerService {
}
async getSubCategory() {
const connectionDb = new Connection(connectionOptions)
const connectionDb = new Connection(connectionOptions);
await connectionDb.connect();
const queryRunner = connectionDb.createQueryRunner();
await queryRunner.connect();
try {
return await queryRunner.manager
.getRepository(Estsubcategoriacliente)
.createQueryBuilder("estsubcategoriacliente")
.createQueryBuilder('estsubcategoriacliente')
.getMany();
} catch (err) {
console.log(err);
throw err;
@ -650,5 +710,4 @@ export class CustomerService {
await connectionDb.close();
}
}
}

View File

@ -1503,6 +1503,7 @@ export class SalesService {
async calculateDeliveryTaxOrder(dataDeliveryTax: any) {
let cityId = await this.customerService.findCity(dataDeliveryTax.ibgeCode);
await this.updatePriorityDelivery(dataDeliveryTax.cartId, dataDeliveryTax.priorityDelivery);
if (cityId == 0) {