Merge branch 'dev' into main
Deploy NestJS API / build-and-push-deploy (push) Failing after 1m36s Details

This commit is contained in:
JuruSysadmin 2026-01-13 12:33:19 -03:00
commit 73c460d87b
12 changed files with 8677 additions and 10692 deletions

5
.vscode/extensions.json vendored Normal file
View File

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

16399
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -7,12 +7,12 @@ export const typeOrmConfig: TypeOrmModuleOptions = {
// username: "LIVIA", // username: "LIVIA",
// password: "LIVIA", // password: "LIVIA",
host: "10.1.1.241", host: "10.1.1.241",
username: "teste", username: "SEVEN",
password: "teste", password: "USR54SEV",
// username: "API", // username: "API",
// password: "E05H5KIEQV3YKDJR", // password: "E05H5KIEQV3YKDJR",
port: 1521, port: 1521,
sid: "BDTESTE", sid: "WINT",
synchronize: false, synchronize: false,
logging: false, logging: false,
entities: [__dirname + '/../**/*.entity.{js,ts}'], entities: [__dirname + '/../**/*.entity.{js,ts}'],
@ -22,12 +22,11 @@ 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: "teste", username: "SEVEN",
password: "teste", password: "USR54SEV",
port: 1521, port: 1521,
sid: "BDTESTE", sid: "WINT",
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,4 +60,7 @@ export class Shopping {
@Column({ name: 'CODTABELAFRETE' }) @Column({ name: 'CODTABELAFRETE' })
codtabelafrete: number; codtabelafrete: number;
@Column({ name: 'CODPRACA' })
codpraca: number;
} }

View File

@ -0,0 +1,24 @@
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

@ -131,18 +131,16 @@ export class CustomerController {
} }
} }
@Post('create') @Post('create')
async createCustomer(@Body() customer: Customer) { async createCustomer(@Body() customer: Customer){
try { try{
console.log(customer); console.log(customer);
const result = await this.customerService.createCustomer(customer); const result = await this.customerService.createCustomer(customer);
return new ResultModel(true, null, result, null); return new ResultModel(true, null, result, null);
//return new ResultModel(true, null, id, null); //return new ResultModel(true, null, id, null);
} catch (err) { } catch(err){
throw new HttpException( throw new HttpException(new ResultModel(false, 'Erro ao cadastrar cliente.', {}, err),
new ResultModel(false, 'Erro ao cadastrar cliente.', {}, err), HttpStatus.INTERNAL_SERVER_ERROR);
HttpStatus.INTERNAL_SERVER_ERROR, }
);
} }
}
} }

View File

@ -360,80 +360,50 @@ export class CustomerService {
newCustomer.longitude = customer.longitude; newCustomer.longitude = customer.longitude;
newCustomer.tipoendereco = customer.addressType; newCustomer.tipoendereco = customer.addressType;
const oldCustomers = await this.findCustomerByCpf(newCustomer.cgcent); const oldCustomer = await this.findCustomerByCpf(newCustomer.cgcent);
if (oldCustomers && oldCustomers.length > 0) { if (oldCustomer) {
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); return {
return { customerId: oldCustomer.customerId,
customerId: oldCustomer.customerId, company: customer.company, name: customer.name, sexo: customer.gender,
company: customer.company, cpfCnpj: customer.cpfCnpj, numberState: customer.numberState,
name: customer.name, email: customer.email, zipCode: customer.zipCode, address: customer.address,
sexo: customer.gender, addressNumber: customer.addressNumber, complement: customer.complement,
cpfCnpj: customer.cpfCnpj, neighborhood: customer.neighborhood,
numberState: customer.numberState, city: customer.city, state: customer.state,
email: customer.email, allowMessage: customer.allowMessage, cellPhone: customer.cellPhone,
zipCode: customer.zipCode, category: customer.category, subCategory: customer.subCategory,
address: customer.address, place: customer.place, ramo: customer.ramo, meiocomunicacao: customer.communicate,
addressNumber: customer.addressNumber, latitude: customer.latitude, longitude: customer.longitude, ibgeCode: customer.ibgeCode,
complement: customer.complement, addressType: customer.addressType,
neighborhood: customer.neighborhood, };
city: customer.city, } else {
state: customer.state, const idCustomer = await this.generateIdCustomer();
allowMessage: customer.allowMessage, if (idCustomer == -1)
cellPhone: customer.cellPhone, return new HttpException("Erro ao gerar númeração de cliente.", HttpStatus.INTERNAL_SERVER_ERROR);
category: customer.category, newCustomer.codcli = idCustomer;
subCategory: customer.subCategory, await this.insertCustomer(newCustomer);
place: customer.place, return {
ramo: customer.ramo, customerId: idCustomer,
meiocomunicacao: customer.communicate, company: customer.company, name: customer.name,
latitude: customer.latitude, cpfCnpj: customer.cpfCnpj, gender: customer.gender, numberState: customer.numberState,
longitude: customer.longitude, email: customer.email, zipCode: customer.zipCode, address: customer.address,
ibgeCode: customer.ibgeCode, addressNumber: customer.addressNumber, complement: customer.complement,
addressType: customer.addressType, neighborhood: customer.neighborhood,
}; city: customer.city, state: customer.state,
} else { allowMessage: customer.allowMessage, cellPhone: customer.cellPhone,
const idCustomer = await this.generateIdCustomer(); category: customer.category, subCategory: customer.subCategory,
if (idCustomer == -1) place: customer.place, meiocomunicacao: customer.communicate,
return new HttpException( ramo: customer.ramo, latitude: customer.latitude, longitude: customer.longitude,
'Erro ao gerar númeração de cliente.', ibgeCode: customer.ibgeCode, addressType: customer.addressType,
HttpStatus.INTERNAL_SERVER_ERROR, };
); }
newCustomer.codcli = idCustomer; } catch (error) {
await this.insertCustomer(newCustomer); throw error;
return { }
customerId: idCustomer,
company: customer.company,
name: customer.name,
cpfCnpj: customer.cpfCnpj,
gender: customer.gender,
numberState: customer.numberState,
email: customer.email,
zipCode: customer.zipCode,
address: customer.address,
addressNumber: customer.addressNumber,
complement: customer.complement,
neighborhood: customer.neighborhood,
city: customer.city,
state: customer.state,
allowMessage: customer.allowMessage,
cellPhone: customer.cellPhone,
category: customer.category,
subCategory: customer.subCategory,
place: customer.place,
meiocomunicacao: customer.communicate,
ramo: customer.ramo,
latitude: customer.latitude,
longitude: customer.longitude,
ibgeCode: customer.ibgeCode,
addressType: customer.addressType,
};
}
} catch (error) {
throw error;
} }
}
async updateCustomer(client: Pcclient) { async updateCustomer(client: Pcclient) {
const connection = new Connection(connectionOptions); const connection = new Connection(connectionOptions);

File diff suppressed because it is too large Load Diff

View File

@ -1,29 +1,28 @@
import { Injectable, HttpException, HttpStatus, Inject, CACHE_MANAGER } from '@nestjs/common'; import { HttpException, HttpStatus, Inject, Injectable } 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 { Connection, getConnection } from 'typeorm'; import { Esvsecao } from '../../domain/entity/views/esvsecao.entity';
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,) {
@ -367,88 +366,88 @@ 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 {
await this.redisClient.set(cacheKey, JSON.stringify(products), 'EX', 3600); if (pageSize === 0) pageSize = 50;
} catch (cacheErr) { if (pageNumber === 0) pageNumber = 1;
console.error('Erro ao salvar o resultado no cache (searchByDepartment):', cacheErr?.message || cacheErr); const offSet = (pageNumber - 1) * pageSize;
}
return products; let products = await queryRunner.manager
} catch (error) { .getRepository(SalesProduct)
console.error('Erro ao executar a query no searchByDepartment:', error?.message || error); .createQueryBuilder('esvlistaprodutos')
throw error; .where('"esvlistaprodutos".urldepartamento = :urlDepartment', { urlDepartment })
} finally { .andWhere('("esvlistaprodutos".codfilial = :codfilial OR :codfilial = \'99\')', { codfilial: store })
await queryRunner.release(); .limit(pageSize)
await connectionDb.close(); .offset(offSet)
.orderBy('"esvlistaprodutos".DESCRICAO', 'ASC')
.getMany();
try { products = this.createListImages(products);
const currentLockValue = await this.redisClient.get(lockKey);
if (currentLockValue === lockValue.toString()) { try {
await this.redisClient.del(lockKey); await this.redisClient.set(cacheKey, JSON.stringify(products), 'EX', 3600);
} } catch (cacheErr) {
} catch (lockErr) { console.error('Erro ao salvar o resultado no cache (searchByDepartment):', cacheErr?.message || cacheErr);
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);
} }
} }
@ -954,10 +953,13 @@ export class SalesService {
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"
FROM ESVESTOQUEVENDA, PCFILIAL , NVL(PCEST.QTEXPOSICAO,0) as "exhibition"
FROM ESVESTOQUEVENDA, PCFILIAL, PCEST
WHERE ESVESTOQUEVENDA.CODPROD = ${id} WHERE ESVESTOQUEVENDA.CODPROD = ${id}
AND ESVESTOQUEVENDA.CODFILIAL = PCFILIAL.CODIGO AND ESVESTOQUEVENDA.CODFILIAL = PCFILIAL.CODIGO
ORDER BY TO_NUMBER(ESVESTOQUEVENDA.CODFILIAL) `; AND ESVESTOQUEVENDA.CODFILIAL = PCEST.CODFILIAL
AND ESVESTOQUEVENDA.CODPROD = PCEST.CODPROD
ORDER BY TO_NUMBER(ESVESTOQUEVENDA.CODFILIAL)`;
const stock = await queryRunner.query(sql); const stock = await queryRunner.query(sql);
@ -1212,66 +1214,66 @@ export class SalesService {
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 {
await this.redisClient.set(cacheKey, JSON.stringify(departments), 'EX', 3600); const departments = await queryRunner.manager
} catch (cacheErr) { .getRepository(Esvdepartamento)
console.error('Erro ao armazenar dados no Redis:', cacheErr); .createQueryBuilder('Esvdepartamento')
} .innerJoinAndSelect('Esvdepartamento.secoes', 'secoes')
.innerJoinAndSelect('secoes.categorias', 'categorias')
.where('"Esvdepartamento".tituloecommerce is not null')
.orderBy('"Esvdepartamento".tituloecommerce, "secoes".tituloecommerce, "categorias".tituloecommerce')
.getMany();
return departments; try {
} catch (dbErr) { await this.redisClient.set(cacheKey, JSON.stringify(departments), 'EX', 3600);
console.error('Erro na consulta ao banco de dados:', dbErr); } catch (cacheErr) {
throw dbErr; console.error('Erro ao armazenar dados no Redis:', cacheErr);
} finally { }
await queryRunner.release();
await connectionDb.close();
// Libera o lock somente se ainda for o proprietário return departments;
try { } catch (dbErr) {
const currentLockValue = await this.redisClient.get(lockKey); console.error('Erro na consulta ao banco de dados:', dbErr);
if (currentLockValue === lockValue.toString()) { throw dbErr;
await this.redisClient.del(lockKey); } finally {
} await queryRunner.release();
} catch (lockErr) { await connectionDb.close();
console.error('Erro ao liberar o lock do Redis:', lockErr);
// 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));
} }
@ -1468,6 +1470,7 @@ 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();
@ -1488,7 +1491,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();
@ -1502,8 +1505,25 @@ export class SalesService {
} }
async calculateDeliveryTaxOrder(dataDeliveryTax: any) { async calculateDeliveryTaxOrder(dataDeliveryTax: any) {
<<<<<<< HEAD
let cityId = await this.customerService.findCity(dataDeliveryTax.ibgeCode); let cityId = await this.customerService.findCity(dataDeliveryTax.ibgeCode);
=======
console.log("json dataDeliveryTax", dataDeliveryTax);
/*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;
}
>>>>>>> feat/painel-cliente
await this.updatePriorityDelivery(dataDeliveryTax.cartId, dataDeliveryTax.priorityDelivery); await this.updatePriorityDelivery(dataDeliveryTax.cartId, dataDeliveryTax.priorityDelivery);
if (cityId == 0) { if (cityId == 0) {
@ -1581,7 +1601,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,15 +6,17 @@ 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)
@ -27,10 +29,10 @@ export class ShoppingController {
} }
@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) {
@ -41,13 +43,13 @@ export class ShoppingController {
@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) {
@ -57,8 +59,8 @@ export class ShoppingController {
} }
@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'])
@ -73,7 +75,7 @@ export class ShoppingController {
@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);
@ -82,8 +84,21 @@ export class ShoppingController {
} }
} }
@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);
@ -93,10 +108,10 @@ export class ShoppingController {
} }
@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);
@ -107,10 +122,10 @@ export class ShoppingController {
} }
@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);
@ -142,7 +157,7 @@ export class ShoppingController {
} }
@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,);
@ -165,4 +180,4 @@ export class ShoppingController {
} }
} }

View File

@ -8,6 +8,8 @@ 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,7 +169,7 @@ export class ShoppingService {
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;
} }
@ -299,6 +301,58 @@ 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,7 +13,9 @@
"paths": { "paths": {
"src/*": ["./src/*"] "src/*": ["./src/*"]
}, },
"incremental": true "incremental": true,
"skipLibCheck": true,
"strict": false
}, },
"exclude": ["node_modules", "dist"] "exclude": ["node_modules", "dist"]
} }