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
18 changed files with 10795 additions and 8778 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/launch.json
!.vscode/extensions.json !.vscode/extensions.json
postgres-data/
.env

View File

@ -1,5 +0,0 @@
{
"recommendations": [
"cweijan.dbclient-jdbc"
]
}

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 \ RUN wget https://download.oracle.com/otn_software/linux/instantclient/instantclient-basic-linuxx64.zip -O /opt/oracle/client.zip && \
apt-transport-https \ unzip /opt/oracle/client.zip -d /opt/oracle && \
ca-certificates \ rm /opt/oracle/client.zip && \
libaio1 \ ln -s /opt/oracle/instantclient_* /opt/oracle/instantclient
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
ENV LD_LIBRARY_PATH=/opt/oracle/instantclient
WORKDIR /app 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 ./ EXPOSE 8068
RUN npm install --legacy-peer-deps
COPY . .
CMD ["npm", "run", "start:prod"] CMD ["npm", "run", "start:prod"]

View File

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

16599
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -2,17 +2,17 @@ import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { ConnectionOptions } from 'typeorm'; import { ConnectionOptions } from 'typeorm';
export const typeOrmConfig: TypeOrmModuleOptions = { export const typeOrmConfig: TypeOrmModuleOptions = {
type: 'oracle', type: "oracle",
// host: "192.168.100.40", // host: "192.168.100.40",
// username: "LIVIA", // username: "LIVIA",
// password: "LIVIA", // password: "LIVIA",
host: '10.1.1.241', host: "10.1.1.241",
username: 'SEVEN', username: "teste",
password: 'USR54SEV', password: "teste",
// username: "API", // username: "API",
// password: "E05H5KIEQV3YKDJR", // password: "E05H5KIEQV3YKDJR",
port: 1521, port: 1521,
serviceName: 'WINT', sid: "BDTESTE",
synchronize: false, synchronize: false,
logging: false, logging: false,
entities: [__dirname + '/../**/*.entity.{js,ts}'], entities: [__dirname + '/../**/*.entity.{js,ts}'],
@ -20,13 +20,14 @@ export const typeOrmConfig: TypeOrmModuleOptions = {
}; };
export const connectionOptions: ConnectionOptions = { export const connectionOptions: ConnectionOptions = {
type: 'oracle', type: "oracle",
host: '10.1.1.241', host: "10.1.1.241",
username: 'SEVEN', username: "teste",
password: 'USR54SEV', password: "teste",
port: 1521, port: 1521,
serviceName: 'WINT', sid: "BDTESTE",
synchronize: false, synchronize: false,
logging: false, logging: false,
entities: [__dirname + '/../**/*.entity.{js,ts}'], entities: [__dirname + '/../**/*.entity.{js,ts}'],
}; }

View File

@ -36,7 +36,7 @@ export class Shopping {
@Column({ name: 'VLDESCONTO' }) @Column({ name: 'VLDESCONTO' })
vldesconto: number; vldesconto: number;
@Column({ name: 'VLCUSTOFIN' }) @Column({name: 'VLCUSTOFIN'})
vlcustofin: number; vlcustofin: number;
@Column({ name: 'CODFUNCAUTOR' }) @Column({ name: 'CODFUNCAUTOR' })
@ -60,7 +60,4 @@ export class Shopping {
@Column({ name: 'CODTABELAFRETE' }) @Column({ name: 'CODTABELAFRETE' })
codtabelafrete: number; codtabelafrete: number;
@Column({ name: 'CODPRACA' })
codpraca: number;
} }

View File

@ -1,24 +0,0 @@
export class CartUpdate {
constructor(
public id: string,
public idCustomer: number,
public idAddress: number,
public saleStore: string,
public userId: number,
public idSeller: number,
public idProfessional: number,
public idPaymentPlan: number,
public idBilling: string,
public shippingValue: number,
public scheduleDelivery: boolean,
public shippingDate: Date,
public shippingPriority: string,
public idStorePlace: number,
public notation1: string,
public notation2: string,
public deliveryNote1: string,
public deliveryNote2: string,
public deliveryNote3: string,
public carrierId: number,
) { }
}

View File

@ -20,6 +20,6 @@ async function bootstrap() {
.build(); .build();
const document = SwaggerModule.createDocument(app, options); const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup("docs", app, document); 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(); bootstrap();

View File

@ -145,4 +145,4 @@ export class CustomerController {
); );
} }
} }
} }

View File

@ -360,8 +360,9 @@ export class CustomerService {
newCustomer.longitude = customer.longitude; newCustomer.longitude = customer.longitude;
newCustomer.tipoendereco = customer.addressType; newCustomer.tipoendereco = customer.addressType;
const oldCustomer = await this.findCustomerByCpf(newCustomer.cgcent); const oldCustomers = await this.findCustomerByCpf(newCustomer.cgcent);
if (oldCustomer) { if (oldCustomers && oldCustomers.length > 0) {
const oldCustomer = oldCustomers[0];
console.log('Cliente localizado: ' + oldCustomer.customerId); console.log('Cliente localizado: ' + oldCustomer.customerId);
newCustomer.codcli = oldCustomer.customerId; newCustomer.codcli = oldCustomer.customerId;
await this.updateCustomer(newCustomer); await this.updateCustomer(newCustomer);
@ -709,4 +710,4 @@ export class CustomerService {
await connectionDb.close(); await connectionDb.close();
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,28 +1,29 @@
import { HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common'; import { Injectable, HttpException, HttpStatus, Inject, CACHE_MANAGER } from '@nestjs/common';
import { Connection } from 'typeorm';
import { connectionOptions } from '../../configs/typeorm.config';
import { Estavisoestoque } from '../../domain/entity/tables/estavisoestoque.entity';
import { Estruptura } from '../../domain/entity/tables/estruptura.entity';
import { Pcclient } from '../../domain/entity/tables/pcclient.entity'; import { Pcclient } from '../../domain/entity/tables/pcclient.entity';
import { Esvanalisevendarca } from '../../domain/entity/views/esvanalisevendarca.entity';
import { Esvdepartamento } from '../../domain/entity/views/esvdepartamento.entity';
import { Esvparcelamentovenda } from '../../domain/entity/views/esvparcelamentovenda.entity';
import { SalesProduct } from '../../domain/entity/views/esvprodutosvenda.entity'; import { SalesProduct } from '../../domain/entity/views/esvprodutosvenda.entity';
import { Esvsecao } from '../../domain/entity/views/esvsecao.entity'; import { Connection, getConnection } from 'typeorm';
import { Esvsituacaopedido } from '../../domain/entity/views/esvsituacaopedido.entity'; import { Esvsituacaopedido } from '../../domain/entity/views/esvsituacaopedido.entity';
import { Stock } from '../../domain/entity/views/esvestoquevenda.entity';
import { FilterProduct } from '../../domain/models/filter-product.model'; import { FilterProduct } from '../../domain/models/filter-product.model';
import { Notify } from '../../domain/models/notify.model'; import { Notify } from '../../domain/models/notify.model';
import { Estavisoestoque } from '../../domain/entity/tables/estavisoestoque.entity';
import { Esvparcelamentovenda } from '../../domain/entity/views/esvparcelamentovenda.entity';
import { Rupture } from '../../domain/models/rupture.model'; import { Rupture } from '../../domain/models/rupture.model';
import { Estruptura } from '../../domain/entity/tables/estruptura.entity';
import { Esvsecao } from '../../domain/entity/views/esvsecao.entity';
import { Esvdepartamento } from '../../domain/entity/views/esvdepartamento.entity';
import { Esvanalisevendarca } from '../../domain/entity/views/esvanalisevendarca.entity';
import { connectionOptions } from '../../configs/typeorm.config';
import { CustomerService } from '../customer/customer.service'; import { CustomerService } from '../customer/customer.service';
import Redis = require('ioredis'); import Redis = require('ioredis');
@Injectable() @Injectable()
export class SalesService { export class SalesService {
constructor( constructor(
@Inject('REDIS_CLIENT') private readonly redisClient: Redis.Redis, @Inject('REDIS_CLIENT') private readonly redisClient: Redis.Redis,
private readonly customerService: CustomerService private readonly customerService: CustomerService
) { } ) {}
async GetProducts2(store: string, pageSize: number, pageNumber: number, filter: FilterProduct = null,) { async GetProducts2(store: string, pageSize: number, pageNumber: number, filter: FilterProduct = null,) {
@ -85,7 +86,7 @@ export class SalesService {
if (filter && filter.text.length > 0) { if (filter && filter.text.length > 0) {
const description = filter.text.toUpperCase(); const description = filter.text.toUpperCase();
console.log('consultando por codigo de fabrica'); console.log('consultando por codigo de fabrica');
let products = await queryRunner.manager let products = await queryRunner.manager
.getRepository(SalesProduct) .getRepository(SalesProduct)
.createQueryBuilder('esvlistaprodutos') .createQueryBuilder('esvlistaprodutos')
@ -366,92 +367,92 @@ export class SalesService {
pageSize: number, pageSize: number,
pageNumber: number, pageNumber: number,
urlDepartment: string urlDepartment: string
): Promise<any> { ): Promise<any> {
const cacheKey = const cacheKey =
'searchByDepartment:' + 'searchByDepartment:' +
store + store +
'_' + '_' +
pageSize + pageSize +
'_' + '_' +
pageNumber + pageNumber +
'_' + '_' +
urlDepartment; urlDepartment;
const lockKey = 'lock:' + cacheKey; const lockKey = 'lock:' + cacheKey;
const lockTimeout = 30; // lock expira em 30 segundos const lockTimeout = 30; // lock expira em 30 segundos
try { try {
const cachedResult = await this.redisClient.get(cacheKey); const cachedResult = await this.redisClient.get(cacheKey);
if (cachedResult) { if (cachedResult) {
console.log('Retornando resultado do cache (searchByDepartment)'); console.log('Retornando resultado do cache (searchByDepartment)');
return JSON.parse(cachedResult); return JSON.parse(cachedResult);
} }
} catch (err) { } catch (err) {
console.error('Erro ao acessar o Redis no searchByDepartment:', err?.message || err); console.error('Erro ao acessar o Redis no searchByDepartment:', err?.message || err);
} }
const lockValue = Date.now() + lockTimeout * 1000 + 1; const lockValue = Date.now() + lockTimeout * 1000 + 1;
let acquiredLock: string | null = null; let acquiredLock: string | null = null;
try { try {
acquiredLock = await this.redisClient.set(lockKey, lockValue, 'NX', 'EX', lockTimeout); acquiredLock = await this.redisClient.set(lockKey, lockValue, 'NX', 'EX', lockTimeout);
} catch (err) { } catch (err) {
console.error('Erro ao adquirir lock no Redis (searchByDepartment):', err?.message || err); console.error('Erro ao adquirir lock no Redis (searchByDepartment):', err?.message || err);
} }
if (acquiredLock === 'OK') { if (acquiredLock === 'OK') {
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 {
if (pageSize === 0) pageSize = 50;
if (pageNumber === 0) pageNumber = 1;
const offSet = (pageNumber - 1) * pageSize;
let products = await queryRunner.manager
.getRepository(SalesProduct)
.createQueryBuilder('esvlistaprodutos')
.where('"esvlistaprodutos".urldepartamento = :urlDepartment', { urlDepartment })
.andWhere('("esvlistaprodutos".codfilial = :codfilial OR :codfilial = \'99\')', { codfilial: store })
.limit(pageSize)
.offset(offSet)
.orderBy('"esvlistaprodutos".DESCRICAO', 'ASC')
.getMany();
products = this.createListImages(products);
try { try {
if (pageSize === 0) pageSize = 50; await this.redisClient.set(cacheKey, JSON.stringify(products), 'EX', 3600);
if (pageNumber === 0) pageNumber = 1; } catch (cacheErr) {
const offSet = (pageNumber - 1) * pageSize; console.error('Erro ao salvar o resultado no cache (searchByDepartment):', cacheErr?.message || cacheErr);
let products = await queryRunner.manager
.getRepository(SalesProduct)
.createQueryBuilder('esvlistaprodutos')
.where('"esvlistaprodutos".urldepartamento = :urlDepartment', { urlDepartment })
.andWhere('("esvlistaprodutos".codfilial = :codfilial OR :codfilial = \'99\')', { codfilial: store })
.limit(pageSize)
.offset(offSet)
.orderBy('"esvlistaprodutos".DESCRICAO', 'ASC')
.getMany();
products = this.createListImages(products);
try {
await this.redisClient.set(cacheKey, JSON.stringify(products), 'EX', 3600);
} catch (cacheErr) {
console.error('Erro ao salvar o resultado no cache (searchByDepartment):', cacheErr?.message || cacheErr);
}
return products;
} catch (error) {
console.error('Erro ao executar a query no searchByDepartment:', error?.message || error);
throw error;
} finally {
await queryRunner.release();
await connectionDb.close();
try {
const currentLockValue = await this.redisClient.get(lockKey);
if (currentLockValue === lockValue.toString()) {
await this.redisClient.del(lockKey);
}
} catch (lockErr) {
console.error('Erro ao liberar o lock do Redis (searchByDepartment):', lockErr?.message || lockErr);
}
} }
return products;
} catch (error) {
console.error('Erro ao executar a query no searchByDepartment:', error?.message || error);
throw error;
} finally {
await queryRunner.release();
await connectionDb.close();
try {
const currentLockValue = await this.redisClient.get(lockKey);
if (currentLockValue === lockValue.toString()) {
await this.redisClient.del(lockKey);
}
} catch (lockErr) {
console.error('Erro ao liberar o lock do Redis (searchByDepartment):', lockErr?.message || lockErr);
}
}
} else { } else {
console.log('Lock não adquirido (searchByDepartment), aguardando e tentando novamente...'); console.log('Lock não adquirido (searchByDepartment), aguardando e tentando novamente...');
await this.sleep(1000); await this.sleep(1000);
return this.searchByDepartment(store, pageSize, pageNumber, urlDepartment); return this.searchByDepartment(store, pageSize, pageNumber, urlDepartment);
} }
} }
async searchBySection(store: string, pageSize: number, pageNumber: number, urlDepartment: string, urlSection: string): Promise<any> { async searchBySection(store: string, pageSize: number, pageNumber: number, urlDepartment: string, urlSection: string): Promise<any> {
const connectionDb = new Connection(connectionOptions); const connectionDb = new Connection(connectionOptions);
@ -619,7 +620,7 @@ export class SalesService {
.addSelect("\"esvlistaprodutos\".PRODUTO_COM_REDUCAO_PRECO", "downPrice") .addSelect("\"esvlistaprodutos\".PRODUTO_COM_REDUCAO_PRECO", "downPrice")
.addSelect("\"esvlistaprodutos\".PRODUTO_EM_CAMPANHA", "compaing") .addSelect("\"esvlistaprodutos\".PRODUTO_EM_CAMPANHA", "compaing")
.addSelect("\"esvlistaprodutos\".BASETINTOMETRICO", "base") .addSelect("\"esvlistaprodutos\".BASETINTOMETRICO", "base")
.addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock") .addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock")
.addSelect("\"esvlistaprodutos\".TEM_PRODUTO_SIMILAR", "similar") .addSelect("\"esvlistaprodutos\".TEM_PRODUTO_SIMILAR", "similar")
.addSelect("\"esvlistaprodutos\".TIPO_CAMPANHA", "type_campaing") .addSelect("\"esvlistaprodutos\".TIPO_CAMPANHA", "type_campaing")
.where("esvlistaprodutos.CODAUXILIAR = :id", { id: numbers }) .where("esvlistaprodutos.CODAUXILIAR = :id", { id: numbers })
@ -670,7 +671,7 @@ export class SalesService {
.addSelect("\"esvlistaprodutos\".PRODUTO_COM_REDUCAO_PRECO", "downPrice") .addSelect("\"esvlistaprodutos\".PRODUTO_COM_REDUCAO_PRECO", "downPrice")
.addSelect("\"esvlistaprodutos\".PRODUTO_EM_CAMPANHA", "compaing") .addSelect("\"esvlistaprodutos\".PRODUTO_EM_CAMPANHA", "compaing")
.addSelect("\"esvlistaprodutos\".BASETINTOMETRICO", "base") .addSelect("\"esvlistaprodutos\".BASETINTOMETRICO", "base")
.addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock") .addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock")
.addSelect("\"esvlistaprodutos\".TEM_PRODUTO_SIMILAR", "similar") .addSelect("\"esvlistaprodutos\".TEM_PRODUTO_SIMILAR", "similar")
.addSelect("\"esvlistaprodutos\".TIPO_CAMPANHA", "type_campaing") .addSelect("\"esvlistaprodutos\".TIPO_CAMPANHA", "type_campaing")
.where("UPPER(esvlistaprodutos.CODFAB) like REPLACE(:description, '@', '%')", { description }) .where("UPPER(esvlistaprodutos.CODFAB) like REPLACE(:description, '@', '%')", { description })
@ -718,7 +719,7 @@ export class SalesService {
.addSelect("\"esvlistaprodutos\".PRODUTO_COM_REDUCAO_PRECO", "downPrice") .addSelect("\"esvlistaprodutos\".PRODUTO_COM_REDUCAO_PRECO", "downPrice")
.addSelect("\"esvlistaprodutos\".PRODUTO_EM_CAMPANHA", "compaing") .addSelect("\"esvlistaprodutos\".PRODUTO_EM_CAMPANHA", "compaing")
.addSelect("\"esvlistaprodutos\".BASETINTOMETRICO", "base") .addSelect("\"esvlistaprodutos\".BASETINTOMETRICO", "base")
.addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock") .addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock")
.addSelect("\"esvlistaprodutos\".TEM_PRODUTO_SIMILAR", "similar") .addSelect("\"esvlistaprodutos\".TEM_PRODUTO_SIMILAR", "similar")
.addSelect("\"esvlistaprodutos\".TIPO_CAMPANHA", "type_campaing") .addSelect("\"esvlistaprodutos\".TIPO_CAMPANHA", "type_campaing")
.where("UPPER(esvlistaprodutos.DESCRICAO) like REPLACE(:description, '@', '%')", { description }) .where("UPPER(esvlistaprodutos.DESCRICAO) like REPLACE(:description, '@', '%')", { description })
@ -789,7 +790,7 @@ export class SalesService {
.addSelect("\"esvlistaprodutos\".PRODUTO_COM_REDUCAO_PRECO", "downPrice") .addSelect("\"esvlistaprodutos\".PRODUTO_COM_REDUCAO_PRECO", "downPrice")
.addSelect("\"esvlistaprodutos\".PRODUTO_EM_CAMPANHA", "compaing") .addSelect("\"esvlistaprodutos\".PRODUTO_EM_CAMPANHA", "compaing")
.addSelect("\"esvlistaprodutos\".BASETINTOMETRICO", "base") .addSelect("\"esvlistaprodutos\".BASETINTOMETRICO", "base")
.addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock") .addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock")
.addSelect("\"esvlistaprodutos\".TEM_PRODUTO_SIMILAR", "similar") .addSelect("\"esvlistaprodutos\".TEM_PRODUTO_SIMILAR", "similar")
.addSelect("\"esvlistaprodutos\".TIPO_CAMPANHA", "type_campaing") .addSelect("\"esvlistaprodutos\".TIPO_CAMPANHA", "type_campaing")
.where("esvlistaprodutos.idProduct = :id", { id: id }) .where("esvlistaprodutos.idProduct = :id", { id: id })
@ -952,17 +953,14 @@ export class SalesService {
,(CASE WHEN (SELECT COUNT(1) FROM PCFILIALRETIRA ,(CASE WHEN (SELECT COUNT(1) FROM PCFILIALRETIRA
WHERE PCFILIALRETIRA.CODFILIALVENDA = '${storeId}' WHERE PCFILIALRETIRA.CODFILIALVENDA = '${storeId}'
AND PCFILIALRETIRA.CODFILIALRETIRA = ESVESTOQUEVENDA.CODFILIAL ) > 0 THEN 1 AND PCFILIALRETIRA.CODFILIALRETIRA = ESVESTOQUEVENDA.CODFILIAL ) > 0 THEN 1
ELSE 0 END ) as "allowDelivery" ELSE 0 END ) as "allowDelivery"
, NVL(PCEST.QTEXPOSICAO,0) as "exhibition" FROM ESVESTOQUEVENDA, PCFILIAL
FROM ESVESTOQUEVENDA, PCFILIAL, PCEST
WHERE ESVESTOQUEVENDA.CODPROD = ${id} WHERE ESVESTOQUEVENDA.CODPROD = ${id}
AND ESVESTOQUEVENDA.CODFILIAL = PCFILIAL.CODIGO AND ESVESTOQUEVENDA.CODFILIAL = PCFILIAL.CODIGO
AND ESVESTOQUEVENDA.CODFILIAL = PCEST.CODFILIAL ORDER BY TO_NUMBER(ESVESTOQUEVENDA.CODFILIAL) `;
AND ESVESTOQUEVENDA.CODPROD = PCEST.CODPROD
ORDER BY TO_NUMBER(ESVESTOQUEVENDA.CODFILIAL)`; const stock = await queryRunner.query(sql);
const stock = await queryRunner.query(sql);
// return await queryRunner.manager // return await queryRunner.manager
// .getRepository(Stock) // .getRepository(Stock)
// .createQueryBuilder('esvestoquevenda') // .createQueryBuilder('esvestoquevenda')
@ -1212,71 +1210,71 @@ export class SalesService {
const cacheKey = 'departments'; const cacheKey = 'departments';
const lockKey = 'departments_lock'; const lockKey = 'departments_lock';
const lockTimeout = 30; const lockTimeout = 30;
try { try {
const cachedDepartments = await this.redisClient.get(cacheKey); const cachedDepartments = await this.redisClient.get(cacheKey);
if (cachedDepartments) { if (cachedDepartments) {
console.log('Buscando departamentos no Redis'); console.log('Buscando departamentos no Redis');
return JSON.parse(cachedDepartments); return JSON.parse(cachedDepartments);
} }
} catch (err) { } catch (err) {
console.error('Erro ao acessar o Redis (cache):', err); console.error('Erro ao acessar o Redis (cache):', err);
} }
const lockValue = Date.now() + lockTimeout * 1000 + 1; const lockValue = Date.now() + lockTimeout * 1000 + 1;
const acquiredLock = await this.redisClient.set(lockKey, lockValue, 'NX', 'EX', lockTimeout); const acquiredLock = await this.redisClient.set(lockKey, lockValue, 'NX', 'EX', lockTimeout);
if (acquiredLock === 'OK') { if (acquiredLock === 'OK') {
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 {
const departments = await queryRunner.manager
.getRepository(Esvdepartamento)
.createQueryBuilder('Esvdepartamento')
.innerJoinAndSelect('Esvdepartamento.secoes', 'secoes')
.innerJoinAndSelect('secoes.categorias', 'categorias')
.where('"Esvdepartamento".tituloecommerce is not null')
.orderBy('"Esvdepartamento".tituloecommerce, "secoes".tituloecommerce, "categorias".tituloecommerce')
.getMany();
try { try {
const departments = await queryRunner.manager await this.redisClient.set(cacheKey, JSON.stringify(departments), 'EX', 3600);
.getRepository(Esvdepartamento) } catch (cacheErr) {
.createQueryBuilder('Esvdepartamento') console.error('Erro ao armazenar dados no Redis:', cacheErr);
.innerJoinAndSelect('Esvdepartamento.secoes', 'secoes')
.innerJoinAndSelect('secoes.categorias', 'categorias')
.where('"Esvdepartamento".tituloecommerce is not null')
.orderBy('"Esvdepartamento".tituloecommerce, "secoes".tituloecommerce, "categorias".tituloecommerce')
.getMany();
try {
await this.redisClient.set(cacheKey, JSON.stringify(departments), 'EX', 3600);
} catch (cacheErr) {
console.error('Erro ao armazenar dados no Redis:', cacheErr);
}
return departments;
} catch (dbErr) {
console.error('Erro na consulta ao banco de dados:', dbErr);
throw dbErr;
} finally {
await queryRunner.release();
await connectionDb.close();
// Libera o lock somente se ainda for o proprietário
try {
const currentLockValue = await this.redisClient.get(lockKey);
if (currentLockValue === lockValue.toString()) {
await this.redisClient.del(lockKey);
}
} catch (lockErr) {
console.error('Erro ao liberar o lock do Redis:', lockErr);
}
} }
return departments;
} catch (dbErr) {
console.error('Erro na consulta ao banco de dados:', dbErr);
throw dbErr;
} finally {
await queryRunner.release();
await connectionDb.close();
// Libera o lock somente se ainda for o proprietário
try {
const currentLockValue = await this.redisClient.get(lockKey);
if (currentLockValue === lockValue.toString()) {
await this.redisClient.del(lockKey);
}
} catch (lockErr) {
console.error('Erro ao liberar o lock do Redis:', lockErr);
}
}
} else { } else {
console.log('Lock não adquirido, aguardando a liberação...'); console.log('Lock não adquirido, aguardando a liberação...');
await this.sleep(1000); // aguarda 1 segundo await this.sleep(1000); // aguarda 1 segundo
return this.getDepartments(); return this.getDepartments();
} }
} }
private sleep(ms: number): Promise<void> { private sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms)); return new Promise(resolve => setTimeout(resolve, ms));
} }
async getCategory() { async getCategory() {
@ -1303,15 +1301,15 @@ export class SalesService {
async searchProduct2(store: string, pageSize: number, pageNumber: number, filter: FilterProduct) { async searchProduct2(store: string, pageSize: number, pageNumber: number, filter: FilterProduct) {
console.log('searchProduct2'); console.log('searchProduct2');
const cacheKey = `searchProduct2:${store}:${pageSize}:${pageNumber}:${JSON.stringify(filter)}`; const cacheKey = `searchProduct2:${store}:${pageSize}:${pageNumber}:${JSON.stringify(filter)}`;
const cachedProducts = await this.redisClient.get(cacheKey); const cachedProducts = await this.redisClient.get(cacheKey);
if (cachedProducts) { if (cachedProducts) {
console.log('Retornando produtos do cache'); console.log('Retornando produtos do cache');
return JSON.parse(cachedProducts); return JSON.parse(cachedProducts);
} }
const sql = 'SELECT esvlistaprodutos.CODPROD "idProduct" ' + const sql = 'SELECT esvlistaprodutos.CODPROD "idProduct" ' +
` ,esvlistaprodutos.SEQ "seq" ` + ` ,esvlistaprodutos.SEQ "seq" ` +
' ,esvlistaprodutos.DESCRICAO "smallDescription" ' + ' ,esvlistaprodutos.DESCRICAO "smallDescription" ' +
@ -1354,8 +1352,8 @@ export class SalesService {
' ,esvlistaprodutos.TEM_PRODUTO_SIMILAR "similar" ' + ' ,esvlistaprodutos.TEM_PRODUTO_SIMILAR "similar" ' +
' ,esvlistaprodutos.TIPO_CAMPANHA "type_campaing" ' + ' ,esvlistaprodutos.TIPO_CAMPANHA "type_campaing" ' +
' FROM esvlistaprodutos ' + ' FROM esvlistaprodutos ' +
' WHERE 1 = 1 '; ' WHERE 1 = 1 ';
let where = ""; let where = "";
if (filter.text != null) { if (filter.text != null) {
where += ` AND ( ESF_REMOVE_ACENTUACAO(UPPER(esvlistaprodutos.descricao)) LIKE ` + where += ` AND ( ESF_REMOVE_ACENTUACAO(UPPER(esvlistaprodutos.descricao)) LIKE ` +
@ -1375,7 +1373,7 @@ export class SalesService {
where += ` AND (esvlistaprodutos.produto_em_campanha = '${(filter.offers ? 'D' : 'N')}' OR '${(filter.offers ? 'S' : 'N')}' = 'N') `; where += ` AND (esvlistaprodutos.produto_em_campanha = '${(filter.offers ? 'D' : 'N')}' OR '${(filter.offers ? 'S' : 'N')}' = 'N') `;
where += ` AND (esvlistaprodutos.produto_em_campanha = '${(filter.oportunity ? 'O' : 'N')}' OR '${(filter.oportunity ? 'O' : 'N')}' = 'N') `; where += ` AND (esvlistaprodutos.produto_em_campanha = '${(filter.oportunity ? 'O' : 'N')}' OR '${(filter.oportunity ? 'O' : 'N')}' = 'N') `;
where += ` AND (esvlistaprodutos.produto_em_promocao = '${(filter.promotion ? 'S' : 'N')}' OR '${(filter.promotion ? 'S' : 'N')}' = 'N') `; where += ` AND (esvlistaprodutos.produto_em_promocao = '${(filter.promotion ? 'S' : 'N')}' OR '${(filter.promotion ? 'S' : 'N')}' = 'N') `;
if (filter.onlyWithStock) { if (filter.onlyWithStock) {
if (filter.storeStock == '' || filter.storeStock == null) { if (filter.storeStock == '' || filter.storeStock == null) {
where += ` AND EXISTS( SELECT P.CODPROD FROM ESVLISTAPRODUTOS P ` + where += ` AND EXISTS( SELECT P.CODPROD FROM ESVLISTAPRODUTOS P ` +
@ -1387,15 +1385,15 @@ export class SalesService {
` AND P.ESTOQUE_DISP_LOJA > 0 ) `; ` AND P.ESTOQUE_DISP_LOJA > 0 ) `;
} }
} }
if (filter.percentOffMin > 0) { if (filter.percentOffMin > 0) {
where += ` AND esvlistaprodutos.PERCENTUALDESCONTO >= ${filter.percentOffMin}`; where += ` AND esvlistaprodutos.PERCENTUALDESCONTO >= ${filter.percentOffMin}`;
} }
if (filter.percentOffMax > 0) { if (filter.percentOffMax > 0) {
where += ` AND esvlistaprodutos.PERCENTUALDESCONTO <= ${filter.percentOffMax}`; where += ` AND esvlistaprodutos.PERCENTUALDESCONTO <= ${filter.percentOffMax}`;
} }
let xbrands = ''; let xbrands = '';
if (filter && filter.brands && filter.brands.length > 0) { if (filter && filter.brands && filter.brands.length > 0) {
const brands = filter.brands; const brands = filter.brands;
@ -1408,24 +1406,24 @@ export class SalesService {
}); });
where += ` AND esvlistaprodutos.nomemarca in ( ${xbrands} )`; where += ` AND esvlistaprodutos.nomemarca in ( ${xbrands} )`;
} }
const orderBy = `ORDER BY esvlistaprodutos.${(filter.orderBy == null) ? 'DESCRICAO' : filter.orderBy}`; const orderBy = `ORDER BY esvlistaprodutos.${(filter.orderBy == null) ? 'DESCRICAO' : filter.orderBy}`;
const skipReg = ((pageNumber - 1) * pageSize); const skipReg = ((pageNumber - 1) * pageSize);
const pagination = ` OFFSET ${skipReg} ROWS FETCH NEXT ${pageSize} ROWS ONLY`; const pagination = ` OFFSET ${skipReg} ROWS FETCH NEXT ${pageSize} ROWS ONLY`;
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 {
let products = await queryRunner.manager.query(sql + where + orderBy + pagination) as SalesProduct[]; let products = await queryRunner.manager.query(sql + where + orderBy + pagination) as SalesProduct[];
products = this.createListImages(products); products = this.createListImages(products);
console.log("Total de produtos: " + products.length); console.log("Total de produtos: " + products.length);
await this.redisClient.set(cacheKey, JSON.stringify(products), 'EX', 3600); await this.redisClient.set(cacheKey, JSON.stringify(products), 'EX', 3600);
return products; return products;
} catch (err) { } catch (err) {
console.log(err); console.log(err);
@ -1435,7 +1433,7 @@ export class SalesService {
await connectionDb.close(); await connectionDb.close();
} }
} }
async calculateDeliveryTax(cartId: string, ibgeCode: string) { async calculateDeliveryTax(cartId: string, ibgeCode: string) {
@ -1470,7 +1468,6 @@ export class SalesService {
.query(sql, [cityId, cartId]); .query(sql, [cityId, cartId]);
return deliveryTaxTable; return deliveryTaxTable;
} catch (err) { } catch (err) {
console.log(err);
throw err; throw err;
} finally { } finally {
await queryRunner.release(); await queryRunner.release();
@ -1491,7 +1488,7 @@ export class SalesService {
WHERE ID = '${cartId}'`; WHERE ID = '${cartId}'`;
await queryRunner.manager await queryRunner.manager
.query(sql); .query(sql);
await queryRunner.commitTransaction(); await queryRunner.commitTransaction();
} catch (err) { } catch (err) {
await queryRunner.rollbackTransaction(); await queryRunner.rollbackTransaction();
@ -1505,20 +1502,8 @@ export class SalesService {
} }
async calculateDeliveryTaxOrder(dataDeliveryTax: any) { async calculateDeliveryTaxOrder(dataDeliveryTax: any) {
console.log("json dataDeliveryTax", dataDeliveryTax); let cityId = await this.customerService.findCity(dataDeliveryTax.ibgeCode);
/*const dataDeliveryTax = {
cartId: cartId,
cityId: cityId,
ibgeCode: ibgeCode,
priorityDelivery: priorityDelivery,
};*/
let cityId = 0;
if (dataDeliveryTax.ibgeCode) {
cityId = await this.customerService.findCity(dataDeliveryTax.ibgeCode);
} else {
cityId = dataDeliveryTax.cityId;
}
await this.updatePriorityDelivery(dataDeliveryTax.cartId, dataDeliveryTax.priorityDelivery); await this.updatePriorityDelivery(dataDeliveryTax.cartId, dataDeliveryTax.priorityDelivery);
if (cityId == 0) { if (cityId == 0) {
@ -1559,26 +1544,26 @@ export class SalesService {
await queryRunner.release(); await queryRunner.release();
await connectionDb.close(); await connectionDb.close();
} }
} }
async getPlacesInterior() { async getPlacesInterior() {
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 {
const sql = ` const sql = `
SELECT DISTINCT ESTPREVENTREGAPRACA.CODPRACA, PCPRACA.PRACA SELECT DISTINCT ESTPREVENTREGAPRACA.CODPRACA, PCPRACA.PRACA
FROM ESTPREVENTREGAPRACA, PCPRACA FROM ESTPREVENTREGAPRACA, PCPRACA
WHERE ESTPREVENTREGAPRACA.CODPRACA = PCPRACA.CODPRACA WHERE ESTPREVENTREGAPRACA.CODPRACA = PCPRACA.CODPRACA
`; `;
const places = await queryRunner.query(sql); const places = await queryRunner.query(sql);
return places; return places;
} catch (err) { } catch (err) {
throw err; throw err;
@ -1587,7 +1572,7 @@ export class SalesService {
await connectionDb.close(); await connectionDb.close();
} }
} }
async getDeliveryTime(saleDate: string, invoiceStoreId: string, placeId: string, cartId: string) { async getDeliveryTime(saleDate: string, invoiceStoreId: string, placeId: string, cartId: string) {
const connection = new Connection(connectionOptions); const connection = new Connection(connectionOptions);
@ -1596,7 +1581,7 @@ export class SalesService {
await queryRunner.connect(); await queryRunner.connect();
try { try {
const sql = `SELECT ESF_CALCULAR_PRAZO_ENTREGA_PROGRAMADA(TO_DATE('${saleDate}', 'DD-MM-YYYY'), ${invoiceStoreId}, ${placeId}, '${cartId}') AS "days" FROM DUAL`; const sql = `SELECT ESF_CALCULAR_PRAZO_ENTREGA_PROGRAMADA(TO_DATE('${saleDate}', 'DD-MM-YYYY'), ${invoiceStoreId}, ${placeId}, '${cartId}') AS "days" FROM DUAL`;
// const sql = `SELECT ESF_CALCULAR_PRAZO_ENTREGA(TO_DATE('${saleDate}', 'DD-MM-YYYY')) AS "days" FROM DUAL`; // const sql = `SELECT ESF_CALCULAR_PRAZO_ENTREGA(TO_DATE('${saleDate}', 'DD-MM-YYYY')) AS "days" FROM DUAL`;
const timeDays = await queryRunner.query(sql); const timeDays = await queryRunner.query(sql);
const sqlRetiraPosterior = `SELECT ( PROXIMO_DIA_UTIL(TO_DATE('${saleDate}', 'DD-MM-YYYY'), '4') - TRUNC(SYSDATE) ) AS "days" FROM DUAL`; const sqlRetiraPosterior = `SELECT ( PROXIMO_DIA_UTIL(TO_DATE('${saleDate}', 'DD-MM-YYYY'), '4') - TRUNC(SYSDATE) ) AS "days" FROM DUAL`;

View File

@ -6,132 +6,117 @@ import { OrderDiscount } from 'src/domain/models/order-discount.model';
import { OrderTaxDelivery } from 'src/domain/models/order-taxdelivery.model'; import { OrderTaxDelivery } from 'src/domain/models/order-taxdelivery.model';
import { LogOrder } from 'src/domain/models/log-order.model'; import { LogOrder } from 'src/domain/models/log-order.model';
import { ApiTags } from '@nestjs/swagger'; import { ApiTags } from '@nestjs/swagger';
import { Cart } from 'src/domain/models/cart.model';
import { CartUpdate } from 'src/domain/models/cart-update.model';
@ApiTags('Shopping') @ApiTags('Shopping')
@Controller('api/v1/shopping') @Controller('api/v1/shopping')
export class ShoppingController { export class ShoppingController {
constructor(private shoppingService: ShoppingService) { } constructor(private shoppingService: ShoppingService){}
@Get('cart/:id') @Get('cart/:id')
async getCart(@Param('id') id: string) { async getCart(@Param('id') id: string){
try { try {
const cart = await this.shoppingService.GetItensCart(id); const cart = await this.shoppingService.GetItensCart(id);
if (cart == null || cart.length == 0) if (cart == null || cart.length == 0)
throw new HttpException("Carrinho de compras não encontrado", HttpStatus.NOT_FOUND); throw new HttpException("Carrinho de compras não encontrado", HttpStatus.NOT_FOUND);
return cart; return cart;
} catch (error) { } catch (error) {
const status = error.status == 404 ? error.status : HttpStatus.INTERNAL_SERVER_ERROR; const status = error.status == 404 ? error.status : HttpStatus.INTERNAL_SERVER_ERROR;
throw new HttpException(error.message, status); throw new HttpException(error.message, status);
} }
} }
@Get(':id') @Get(':id')
async getPreVenda(@Param('id') id: string) { async getPreVenda(@Param('id') id: string ){
try { try {
const cart = await this.shoppingService.getShopping(id); const cart = await this.shoppingService.getShopping(id);
if (cart == null) if (cart == null )
throw new HttpException("Carrinho de compras não encontrado", HttpStatus.NOT_FOUND); throw new HttpException("Carrinho de compras não encontrado", HttpStatus.NOT_FOUND);
return cart; return cart;
} catch (error) { } catch (error) {
const status = error.status == 404 ? error.status : HttpStatus.INTERNAL_SERVER_ERROR; const status = error.status == 404 ? error.status : HttpStatus.INTERNAL_SERVER_ERROR;
throw new HttpException(error.message, status); throw new HttpException(error.message, status);
} }
} }
@Get('cart/:idcart/item/:idProduct/tipoentrega/:deliveryType') @Get('cart/:idcart/item/:idProduct/tipoentrega/:deliveryType')
async getItemCart(@Req() request, @Param('idCart') idCart: string, async getItemCart(@Req() request, @Param('idCart') idCart: string,
@Param('idProduct') idProduct: string, @Param('deliveryType') deliveryType: string) { @Param('idProduct') idProduct: string, @Param('deliveryType') deliveryType: string){
let store = '99'; let store = '99';
try { try {
if (request.headers['x-store']) if (request.headers['x-store'])
store = request.headers['x-store']; store = request.headers['x-store'];
const cart = await this.shoppingService.getItemCart(idCart, idProduct, store, deliveryType); const cart = await this.shoppingService.getItemCart(idCart, idProduct, store, deliveryType);
if (cart == null) if (cart == null )
throw new HttpException("Item não foi encontrado no carrinho de compras.", HttpStatus.NOT_FOUND); throw new HttpException("Item não foi encontrado no carrinho de compras.", HttpStatus.NOT_FOUND);
return cart; return cart;
} catch (error) { } catch (error) {
const status = error.status == 404 ? error.status : HttpStatus.INTERNAL_SERVER_ERROR; const status = error.status == 404 ? error.status : HttpStatus.INTERNAL_SERVER_ERROR;
throw new HttpException(error.message, status); throw new HttpException(error.message, status);
} }
} }
@Get('cart/lot/:productId/:customerId') @Get('cart/lot/:productId/:customerId')
async getLotProduct(@Req() request, @Param('productId') productId: number, async getLotProduct( @Req() request, @Param('productId') productId: number,
@Param('customerId') customerId: number) { @Param('customerId') customerId: number ) {
let store = '99'; let store = '99';
try { try {
if (request.headers['x-store']) if (request.headers['x-store'])
store = request.headers['x-store']; store = request.headers['x-store'];
const lotsProduct = await this.shoppingService.getLotProduct(productId, customerId); const lotsProduct = await this.shoppingService.getLotProduct(productId, customerId);
return lotsProduct; return lotsProduct;
} catch (error) { } catch (error) {
const status = error.status == 404 ? error.status : HttpStatus.INTERNAL_SERVER_ERROR; const status = error.status == 404 ? error.status : HttpStatus.INTERNAL_SERVER_ERROR;
throw new HttpException(error.message, status); throw new HttpException(error.message, status);
} }
} }
@Post('item') @Post('item')
async createItemShopping(@Body() item: ShoppingItem) { async createItemShopping(@Body() item: ShoppingItem){
console.log('createItemShopping') console.log('createItemShopping')
try { try {
return await this.shoppingService.createItemCart(item); return await this.shoppingService.createItemCart(item);
} catch (error) { } catch (error) {
throw new HttpException(error.message, HttpStatus.BAD_REQUEST); throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
}
}
@Put('cart')
async updateCart(@Body() cart: CartUpdate) {
try {
if (cart.id == null) {
throw new HttpException('Cart sem Id informado, faça a inclusão do item no carrinho.', HttpStatus.BAD_REQUEST);
}
const updateCart = await this.shoppingService.updateShopping(cart);
return updateCart;
} catch (error) {
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
} }
} }
@Post('log') @Post('log')
async logOrderShopping(@Body() logOrder: LogOrder) { async logOrderShopping(@Body() logOrder: LogOrder){
try { try {
console.log('logOrderShopping') console.log('logOrderShopping')
return await this.shoppingService.createLogShopping(logOrder); return await this.shoppingService.createLogShopping(logOrder);
} catch (error) { } catch (error) {
throw new HttpException(error.message, HttpStatus.BAD_REQUEST); throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
} }
} }
@Put('item') @Put('item')
async updateQuantityItem(@Body() item: ShoppingItem) { async updateQuantityItem(@Body() item: ShoppingItem){
console.log(item); console.log(item);
try { try {
if (item.id == null) { if (item.id == null){
throw new HttpException('Item sem Id informado, faça a inclusão do item no carrinho.', HttpStatus.BAD_REQUEST); throw new HttpException('Item sem Id informado, faça a inclusão do item no carrinho.', HttpStatus.BAD_REQUEST);
} }
const itemCreate = await this.shoppingService.updateItem(item); const itemCreate = await this.shoppingService.updateItem(item);
return itemCreate; return itemCreate;
} catch (error) { } catch (error) {
throw new HttpException(error.message, HttpStatus.BAD_REQUEST); throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
} }
} }
@Put('item/discount') @Put('item/discount')
async updatePriceItem(@Body() item: ShoppingItem) { async updatePriceItem(@Body() item: ShoppingItem){
console.log(item); console.log(item);
try { try {
if (item.id == null) { if (item.id == null){
throw new HttpException('Item sem Id informado, faça a inclusão do item no carrinho.', HttpStatus.BAD_REQUEST); throw new HttpException('Item sem Id informado, faça a inclusão do item no carrinho.', HttpStatus.BAD_REQUEST);
} }
const itemCreate = await this.shoppingService.updatePrice(item); const itemCreate = await this.shoppingService.updatePrice(item);
return itemCreate; return itemCreate;
} catch (error) { } catch (error) {
throw new HttpException(error.message, HttpStatus.BAD_REQUEST); throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
} }
} }
@ -141,7 +126,7 @@ export class ShoppingController {
const itensOrder = await this.shoppingService.applyDiscountOrder(order); const itensOrder = await this.shoppingService.applyDiscountOrder(order);
return itensOrder; return itensOrder;
} catch (error) { } catch (error) {
throw new HttpException(error.message, HttpStatus.BAD_REQUEST); throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
} }
} }
@ -152,17 +137,17 @@ export class ShoppingController {
return orderTax; return orderTax;
} catch (error) { } catch (error) {
console.log(error); console.log(error);
throw new HttpException(error.message, HttpStatus.BAD_REQUEST); throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
} }
} }
@Delete('item/delete/:id') @Delete('item/delete/:id')
async deleteItem(@Param('id') id: string) { async deleteItem(@Param('id') id: string){
try { try {
await this.shoppingService.deleteItem(id); await this.shoppingService.deleteItem(id);
return new ResultModel(true, 'Item excluído com sucesso!', id, null,); return new ResultModel(true, 'Item excluído com sucesso!', id, null,);
} catch (error) { } catch (error) {
throw new HttpException(error.message, HttpStatus.BAD_REQUEST); throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
} }
} }
@ -180,4 +165,4 @@ export class ShoppingController {
} }
} }

View File

@ -8,8 +8,6 @@ import { Shopping } from 'src/domain/entity/tables/estprevendac.entity';
import { OrderTaxDelivery } from 'src/domain/models/order-taxdelivery.model'; import { OrderTaxDelivery } from 'src/domain/models/order-taxdelivery.model';
import { connectionOptions } from 'src/configs/typeorm.config'; import { connectionOptions } from 'src/configs/typeorm.config';
import { LogOrder } from 'src/domain/models/log-order.model'; import { LogOrder } from 'src/domain/models/log-order.model';
import { Cart } from 'src/domain/models/cart.model';
import { CartUpdate } from 'src/domain/models/cart-update.model';
@Injectable() @Injectable()
export class ShoppingService { export class ShoppingService {
@ -167,11 +165,11 @@ export class ShoppingService {
const dataStockItem = await queryRunner.query(`SELECT E.estoque_disp_loja as "quantityStock" const dataStockItem = await queryRunner.query(`SELECT E.estoque_disp_loja as "quantityStock"
FROM ESVLISTAPRODUTOS E WHERE E.CODPROD = ${itemShopping.idProduct} FROM ESVLISTAPRODUTOS E WHERE E.CODPROD = ${itemShopping.idProduct}
AND E.CODFILIAL = '${itemShopping.stockStore}'`); AND E.CODFILIAL = '${itemShopping.stockStore}'`);
let quantityStock = 0; let quantityStock = 0;
if (dataStockItem.length > 0) { if ( dataStockItem.length > 0 ) {
quantityStock = dataStockItem[0].quantityStock; quantityStock = dataStockItem[0].quantityStock;
} }
const sqlInsertitem = 'INSERT INTO ESTPREVENDAI ( ID, IDCART, NUMSEQ, CODPROD, QT, PVENDA, DTINCLUSAO, NOMEECOMMERCE, URLIMAGEM, TIPOPRODUTO, CODFILIALRETIRA, TIPOENTREGA, ' + const sqlInsertitem = 'INSERT INTO ESTPREVENDAI ( ID, IDCART, NUMSEQ, CODPROD, QT, PVENDA, DTINCLUSAO, NOMEECOMMERCE, URLIMAGEM, TIPOPRODUTO, CODFILIALRETIRA, TIPOENTREGA, ' +
@ -301,58 +299,6 @@ export class ShoppingService {
} }
async updateShopping(cart: CartUpdate) {
const connectionDb = new Connection(connectionOptions);
await connectionDb.connect();
const queryRunner = connectionDb.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const sqlUpdate = `UPDATE ESTPREVENDAC SET
CODFILIAL = :1,
CODUSUR = :2,
CODCLI = :3,
CODENDENTCLI = :4,
VLPEDIDO = :5,
VLDESCONTO = :6,
VLTAXAENTREGA = :7,
TIPOPRIORIDADEENTREGA = :8
WHERE ID = :9
`;
const total = await queryRunner.query('SELECT SUM(ESTPREVENDAI.PTABELA * ESTPREVENDAI.QT) as "vltabela" ' +
' ,SUM(ESTPREVENDAI.PVENDA * ESTPREVENDAI.QT) as "vlatend" ' +
' ,SUM(ESTPREVENDAI.VLDESCONTO * ESTPREVENDAI.QT) as "vldesconto" ' +
' ,SUM(PCPRODUT.PESOBRUTO * ESTPREVENDAI.QT) as "totpeso" ' +
' FROM ESTPREVENDAI, PCPRODUT ' +
' WHERE ESTPREVENDAI.CODPROD = PCPRODUT.CODPROD ' +
' AND ESTPREVENDAI.IDCART = :1', [cart.id]);
await queryRunner.query(sqlUpdate, [
cart.saleStore,
cart.userId,
cart.idCustomer,
cart.idAddress,
total[0].vlatend,
total[0].vldesconto,
cart.shippingValue,
cart.shippingPriority,
cart.id
]);
await queryRunner.commitTransaction();
return cart;
} catch (error) {
await queryRunner.rollbackTransaction();
throw error;
} finally {
await queryRunner.release();
await connectionDb.close();
}
}
async updateTotalShopping(idCart: string) { async updateTotalShopping(idCart: string) {
const connection = new Connection(connectionOptions); const connection = new Connection(connectionOptions);
await connection.connect(); await connection.connect();

View File

@ -13,9 +13,7 @@
"paths": { "paths": {
"src/*": ["./src/*"] "src/*": ["./src/*"]
}, },
"incremental": true, "incremental": true
"skipLibCheck": true,
"strict": false
}, },
"exclude": ["node_modules", "dist"] "exclude": ["node_modules", "dist"]
} }