import { Injectable, HttpException, HttpStatus, Inject, CACHE_MANAGER } from '@nestjs/common'; import { Pcclient } from '../../domain/entity/tables/pcclient.entity'; import { SalesProduct } from '../../domain/entity/views/esvprodutosvenda.entity'; import { Connection, getConnection } from 'typeorm'; 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 { 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 { 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 Redis = require('ioredis'); @Injectable() export class SalesService { constructor( @Inject('REDIS_CLIENT') private readonly redisClient: Redis.Redis, private readonly customerService: CustomerService ) {} async GetProducts2(store: string, pageSize: number, pageNumber: number, filter: FilterProduct = null,) { const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); try { if (pageSize == 0) pageSize = 500; if (pageNumber == 0) pageNumber = 1; const offSet = (pageNumber - 1) * pageSize; const sqlProduto = `SELECT esvlistaprodutos.CODPROD as "idProduct", esvlistaprodutos.SEQ as "seq", esvlistaprodutos.DESCRICAO as "smallDescription", esvlistaprodutos.NOMEECOMMERCE as "title", esvlistaprodutos.CODFAB as "idProvider", esvlistaprodutos.CODAUXILIAR as "ean", esvlistaprodutos.TIPOPRODUTO as "productType", esvlistaprodutos.DADOSTECNICOS as "technicalData", esvlistaprodutos.INFORMACOESTECNICAS as "description", esvlistaprodutos.URLIMAGEM as "urlImage", esvlistaprodutos.NOMEMARCA as "brand", esvlistaprodutos.NOMEDEPARTAMENTO as "department", esvlistaprodutos.NOMESECAO as "section", esvlistaprodutos.NOMECATEGORIA as "category", esvlistaprodutos.NOMEFORNECEDOR as "supplier", esvlistaprodutos.CODIGOFILIAL as "store", esvlistaprodutos.CLASSEVENDA as "saleAbc", esvlistaprodutos.CLASSEESTOQUE as "stockAbc", esvlistaprodutos.FORALINHA as "outLine", esvlistaprodutos.PRECOVENDA as "listPrice", esvlistaprodutos.PRECOPROMOCIONAL as "salePrice", esvlistaprodutos.PRECOPROMOCIONAL as "salePromotion", esvlistaprodutos.PRECOPROMOCIONAL_AVISTA as "salePromotion_cash", esvlistaprodutos.PERCENTUALDESCONTO as "offPercent", esvlistaprodutos.QTESTOQUE_DISPONIVEL as "stock", esvlistaprodutos.QTCAIXAS as "boxStock", esvlistaprodutos.ESTOQUE_DISP_LOJA as "store_stock", esvlistaprodutos.ESTOQUE_DISP_CAIXA_LOJA as "store_boxStock", esvlistaprodutos.MULTIPLO as "mutiple", esvlistaprodutos.UNIDADE as "unity", esvlistaprodutos.URLDEPARTAMENTO as "urlDepartment", esvlistaprodutos.URLSECAO as "urlSection", esvlistaprodutos.PRODUTO_COM_REDUCAO_PRECO as "downPrice", esvlistaprodutos.PRODUTO_EM_CAMPANHA as "compaing", esvlistaprodutos.BASETINTOMETRICO as "base", esvlistaprodutos.LETRABASETINTOMETRICO as "letter", esvlistaprodutos.LINHATINTOMETRICO as "line", esvlistaprodutos.LITRAGEM as "can", esvlistaprodutos.QUANTIDADE_ESTOQUE_GERAL as "full_stock", esvlistaprodutos.TEM_PRODUTO_SIMILAR as "similar", NVL(esvlistaprodutos.TIPO, 'SEM') as "type_campaing" FROM ESVLISTAPRODUTOS WHERE 1 = 1 `; if (filter && filter.text.length > 0) { const description = filter.text.toUpperCase(); console.log('consultando por codigo de fabrica'); let products = await queryRunner.manager .getRepository(SalesProduct) .createQueryBuilder('esvlistaprodutos') .select("\"esvlistaprodutos\".CODPROD", "idProduct") .addSelect("\"esvlistaprodutos\".SEQ", "seq") .addSelect("\"esvlistaprodutos\".DESCRICAO", "smallDescription") .addSelect("\"esvlistaprodutos\".NOMEECOMMERCE", "title") .addSelect("\"esvlistaprodutos\".CODFAB", "idProvider") .addSelect("\"esvlistaprodutos\".CODAUXILIAR", "ean") .addSelect("\"esvlistaprodutos\".TIPOPRODUTO", "productType") .addSelect("\"esvlistaprodutos\".DADOSTECNICOS", "technicalData") .addSelect("\"esvlistaprodutos\".INFORMACOESTECNICAS", "description") .addSelect("\"esvlistaprodutos\".URLIMAGEM", "urlImage") .addSelect("\"esvlistaprodutos\".NOMEMARCA", "brand") .addSelect("\"esvlistaprodutos\".NOMEDEPARTAMENTO", "department") .addSelect("\"esvlistaprodutos\".NOMESECAO", "section") .addSelect("\"esvlistaprodutos\".NOMECATEGORIA", "category") .addSelect("\"esvlistaprodutos\".NOMEFORNECEDOR", "supplier") .addSelect("\"esvlistaprodutos\".CODIGOFILIAL", "store") .addSelect("\"esvlistaprodutos\".CLASSEVENDA", "saleAbc") .addSelect("\"esvlistaprodutos\".CLASSEESTOQUE", "stockAbc") .addSelect("\"esvlistaprodutos\".FORALINHA", "outLine") .addSelect("\"esvlistaprodutos\".PRECOVENDA", "listPrice") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL", "salePrice") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL", "salePromotion") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL_AVISTA", "salePromotion_cash") .addSelect("\"esvlistaprodutos\".PERCENTUALDESCONTO", "offPercent") .addSelect("\"esvlistaprodutos\".QTESTOQUE_DISPONIVEL", "stock") .addSelect("\"esvlistaprodutos\".QTCAIXAS", "boxStock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_LOJA", "store_stock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_CAIXA_LOJA", "store_boxStock") .addSelect("\"esvlistaprodutos\".MULTIPLO", "mutiple") .addSelect("\"esvlistaprodutos\".UNIDADE", "unity") .addSelect("\"esvlistaprodutos\".URLDEPARTAMENTO", "urlDepartment") .addSelect("\"esvlistaprodutos\".URLSECAO", "urlSection") .addSelect("\"esvlistaprodutos\".PRODUTO_COM_REDUCAO_PRECO", "downPrice") .addSelect("\"esvlistaprodutos\".PRODUTO_EM_CAMPANHA", "compaing") .addSelect("\"esvlistaprodutos\".BASETINTOMETRICO", "base") .addSelect("\"esvlistaprodutos\".LETRATINTOMETRICO", "letter") .addSelect("\"esvlistaprodutos\".LINHATINTOMETRICO", "line") .addSelect("\"esvlistaprodutos\".LITRAGEM", "can") .addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock") .addSelect("\"esvlistaprodutos\".TEM_PRODUTO_SIMILAR", "similar") .addSelect("\"esvlistaprodutos\".TIPO_CAMPANHA", "type_campaing") .where("UPPER(\"esvlistaprodutos\".CODFAB) LIKE '%'||REPLACE(:description, '@', '%')||'%'", { description }) .andWhere("(\"esvlistaprodutos\".codfilial = :codfilial OR :codfilial = '99')", { codfilial: store }) .andWhere("(\"esvlistaprodutos\".produto_com_reducao_preco = :produtoComReducaoPreco OR :produtoComReducaoPreco = 'N')", { produtoComReducaoPreco: (filter.markdown) ? 'S' : 'N' }) .andWhere("(\"esvlistaprodutos\".produto_em_campanha = :campaign OR :campaign = 'N')", { campaign: (filter.campaign) ? 'I' : 'N' }) .andWhere("(\"esvlistaprodutos\".produto_em_campanha = :oportunity OR :oportunity = 'N')", { oportunity: (filter.oportunity) ? 'O' : 'N' }) .andWhere("(\"esvlistaprodutos\".produto_em_promocao = :produtoEmPromocao OR :produtoEmPromocao = 'N')", { produtoEmPromocao: (filter.promotion) ? 'S' : 'N' }) .limit(pageSize) .offset(offSet) .orderBy("\"esvlistaprodutos\".DESCRICAO", "ASC") .getRawMany(); if (products.length == 0) { products = await queryRunner.manager .getRepository(SalesProduct) .createQueryBuilder('esvlistaprodutos') .select("\"esvlistaprodutos\".CODPROD", "idProduct") .addSelect("\"esvlistaprodutos\".SEQ", "seq") .addSelect("\"esvlistaprodutos\".DESCRICAO", "smallDescription") .addSelect("\"esvlistaprodutos\".NOMEECOMMERCE", "title") .addSelect("\"esvlistaprodutos\".CODFAB", "idProvider") .addSelect("\"esvlistaprodutos\".CODAUXILIAR", "ean") .addSelect("\"esvlistaprodutos\".TIPOPRODUTO", "productType") .addSelect("\"esvlistaprodutos\".DADOSTECNICOS", "technicalData") .addSelect("\"esvlistaprodutos\".INFORMACOESTECNICAS", "description") .addSelect("\"esvlistaprodutos\".URLIMAGEM", "urlImage") .addSelect("\"esvlistaprodutos\".NOMEMARCA", "brand") .addSelect("\"esvlistaprodutos\".NOMEDEPARTAMENTO", "department") .addSelect("\"esvlistaprodutos\".NOMESECAO", "section") .addSelect("\"esvlistaprodutos\".NOMECATEGORIA", "category") .addSelect("\"esvlistaprodutos\".NOMEFORNECEDOR", "supplier") .addSelect("\"esvlistaprodutos\".CODIGOFILIAL", "store") .addSelect("\"esvlistaprodutos\".CLASSEVENDA", "saleAbc") .addSelect("\"esvlistaprodutos\".CLASSEESTOQUE", "stockAbc") .addSelect("\"esvlistaprodutos\".FORALINHA", "outLine") .addSelect("\"esvlistaprodutos\".PRECOVENDA", "listPrice") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL", "salePrice") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL", "salePromotion") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL_AVISTA", "salePromotion_cash") .addSelect("\"esvlistaprodutos\".PERCENTUALDESCONTO", "offPercent") .addSelect("\"esvlistaprodutos\".QTESTOQUE_DISPONIVEL", "stock") .addSelect("\"esvlistaprodutos\".QTCAIXAS", "boxStock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_LOJA", "store_stock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_CAIXA_LOJA", "store_boxStock") .addSelect("\"esvlistaprodutos\".MULTIPLO", "mutiple") .addSelect("\"esvlistaprodutos\".UNIDADE", "unity") .addSelect("\"esvlistaprodutos\".URLDEPARTAMENTO", "urlDepartment") .addSelect("\"esvlistaprodutos\".URLSECAO", "urlSection") .addSelect("\"esvlistaprodutos\".PRODUTO_COM_REDUCAO_PRECO", "downPrice") .addSelect("\"esvlistaprodutos\".PRODUTO_EM_CAMPANHA", "compaing") .addSelect("\"esvlistaprodutos\".BASETINTOMETRICO", "base") .addSelect("\"esvlistaprodutos\".LETRATINTOMETRICO", "letter") .addSelect("\"esvlistaprodutos\".LINHATINTOMETRICO", "line") .addSelect("\"esvlistaprodutos\".LITRAGEM", "can") .addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock") .addSelect("\"esvlistaprodutos\".TEM_PRODUTO_SIMILAR", "similar") .addSelect("\"esvlistaprodutos\".TIPO_CAMPANHA", "type_campaing") .where("UPPER(\"esvlistaprodutos\".descricao) LIKE '%'||REPLACE(:description, '@', '%')||'%'", { description }) .andWhere("(\"esvlistaprodutos\".codfilial = :codfilial OR :codfilial = '99')", { codfilial: store }) .andWhere("(\"esvlistaprodutos\".produto_com_reducao_preco = :produtoComReducaoPreco OR :produtoComReducaoPreco = 'N')", { produtoComReducaoPreco: (filter.markdown) ? 'S' : 'N' }) .andWhere("(\"esvlistaprodutos\".produto_em_campanha = :campaign OR :campaign = 'N')", { campaign: (filter.campaign) ? 'I' : 'N' }) .andWhere("(\"esvlistaprodutos\".produto_oportunidade = :oportunity OR :oportunity = 'N')", { oportunity: (filter.oportunity) ? 'O' : 'N' }) .andWhere("(\"esvlistaprodutos\".produto_em_promocao = :produtoEmPromocao OR :produtoEmPromocao = 'N')", { produtoEmPromocao: (filter.promotion) ? 'S' : 'N' }) .orderBy("\"esvlistaprodutos\".CLASSEVENDA") .limit(pageSize) .offset(offSet) .orderBy("\"esvlistaprodutos\".DESCRICAO", "ASC") .getRawMany(); } products = this.createListImages(products); console.log(products.length + ' produtos'); return products; } if (filter && filter.brands && filter.brands.length > 0) { const brands = filter.brands; let xbrands = ''; brands.forEach(b => { if (xbrands.length > 0) { xbrands += ', ' + '\'' + b + '\'' } else { xbrands = '\'' + b + '\''; } }); console.log("String: " + xbrands); console.log("String: " + filter.urlCategory); let products = await queryRunner.manager .getRepository(SalesProduct) .createQueryBuilder('esvlistaprodutos') .select("\"esvlistaprodutos\".CODPROD", "idProduct") .addSelect("\"esvlistaprodutos\".SEQ", "seq") .addSelect("\"esvlistaprodutos\".DESCRICAO", "smallDescription") .addSelect("\"esvlistaprodutos\".NOMEECOMMERCE", "title") .addSelect("\"esvlistaprodutos\".CODFAB", "idProvider") .addSelect("\"esvlistaprodutos\".CODAUXILIAR", "ean") .addSelect("\"esvlistaprodutos\".TIPOPRODUTO", "productType") .addSelect("\"esvlistaprodutos\".DADOSTECNICOS", "technicalData") .addSelect("\"esvlistaprodutos\".INFORMACOESTECNICAS", "description") .addSelect("\"esvlistaprodutos\".URLIMAGEM", "urlImage") .addSelect("\"esvlistaprodutos\".NOMEMARCA", "brand") .addSelect("\"esvlistaprodutos\".NOMEDEPARTAMENTO", "department") .addSelect("\"esvlistaprodutos\".NOMESECAO", "section") .addSelect("\"esvlistaprodutos\".NOMECATEGORIA", "category") .addSelect("\"esvlistaprodutos\".NOMEFORNECEDOR", "supplier") .addSelect("\"esvlistaprodutos\".CODIGOFILIAL", "store") .addSelect("\"esvlistaprodutos\".CLASSEVENDA", "saleAbc") .addSelect("\"esvlistaprodutos\".CLASSEESTOQUE", "stockAbc") .addSelect("\"esvlistaprodutos\".FORALINHA", "outLine") .addSelect("\"esvlistaprodutos\".PRECOVENDA", "listPrice") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL", "salePrice") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL", "salePromotion") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL_AVISTA", "salePromotion_cash") .addSelect("\"esvlistaprodutos\".PERCENTUALDESCONTO", "offPercent") .addSelect("\"esvlistaprodutos\".QTESTOQUE_DISPONIVEL", "stock") .addSelect("\"esvlistaprodutos\".QTCAIXAS", "boxStock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_LOJA", "store_stock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_CAIXA_LOJA", "store_boxStock") .addSelect("\"esvlistaprodutos\".MULTIPLO", "mutiple") .addSelect("\"esvlistaprodutos\".UNIDADE", "unity") .addSelect("\"esvlistaprodutos\".URLDEPARTAMENTO", "urlDepartment") .addSelect("\"esvlistaprodutos\".URLSECAO", "urlSection") .addSelect("\"esvlistaprodutos\".PRODUTO_COM_REDUCAO_PRECO", "downPrice") .addSelect("\"esvlistaprodutos\".PRODUTO_EM_CAMPANHA", "compaing") .addSelect("\"esvlistaprodutos\".BASETINTOMETRICO", "base") .addSelect("\"esvlistaprodutos\".LETRATINTOMETRICO", "letter") .addSelect("\"esvlistaprodutos\".LINHATINTOMETRICO", "line") .addSelect("\"esvlistaprodutos\".LITRAGEM", "can") .addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock") .addSelect("\"esvlistaprodutos\".TEM_PRODUTO_SIMILAR", "similar") .addSelect("\"esvlistaprodutos\".TIPO_CAMPANHA", "type_campaing") .where("esvlistaprodutos.brand in (" + xbrands + ")") .andWhere("\"esvlistaprodutos\".URLCATEGORIA LIKE :urlCategoria||'%'", { urlCategoria: filter.urlCategory }) .andWhere("(\"esvlistaprodutos\".codfilial = :codfilial OR :codfilial = '99')", { codfilial: store }) .andWhere("(\"esvlistaprodutos\".produto_com_reducao_preco = :produtoComReducaoPreco OR :produtoComReducaoPreco = 'N')", { produtoComReducaoPreco: (filter.markdown) ? 'S' : 'N' }) .andWhere("(\"esvlistaprodutos\".produto_em_campanha = :campaign OR :campaign = 'N')", { campaign: (filter.campaign) ? 'I' : 'N' }) .andWhere("(\"esvlistaprodutos\".produto_oportunidade = :oportunity OR :oportunity = 'N')", { oportunity: (filter.oportunity) ? 'O' : 'N' }) .andWhere("(\"esvlistaprodutos\".produto_em_promocao = :produtoEmPromocao OR :produtoEmPromocao = 'N')", { produtoEmPromocao: (filter.promotion) ? 'S' : 'N' }) .limit(pageSize) .offset(offSet) .orderBy("\"esvlistaprodutos\".DESCRICAO", "ASC") .getRawMany(); products = this.createListImages(products); console.log(products.length + ' produtos'); return products; } else { if (filter.markdown.toString() == 'true') console.log('Produto em redução de preço - 2'); let products = await queryRunner.manager .getRepository(SalesProduct) .createQueryBuilder("esvlistaprodutos") .select("\"esvlistaprodutos\".CODPROD", "idProduct") .addSelect("\"esvlistaprodutos\".SEQ", "seq") .addSelect("\"esvlistaprodutos\".DESCRICAO", "smallDescription") .addSelect("\"esvlistaprodutos\".NOMEECOMMERCE", "title") .addSelect("\"esvlistaprodutos\".CODFAB", "idProvider") .addSelect("\"esvlistaprodutos\".CODAUXILIAR", "ean") .addSelect("\"esvlistaprodutos\".TIPOPRODUTO", "productType") .addSelect("\"esvlistaprodutos\".DADOSTECNICOS", "technicalData") .addSelect("\"esvlistaprodutos\".INFORMACOESTECNICAS", "description") .addSelect("\"esvlistaprodutos\".URLIMAGEM", "urlImage") .addSelect("\"esvlistaprodutos\".NOMEMARCA", "brand") .addSelect("\"esvlistaprodutos\".NOMEDEPARTAMENTO", "department") .addSelect("\"esvlistaprodutos\".NOMESECAO", "section") .addSelect("\"esvlistaprodutos\".NOMECATEGORIA", "category") .addSelect("\"esvlistaprodutos\".NOMEFORNECEDOR", "supplier") .addSelect("\"esvlistaprodutos\".CODIGOFILIAL", "store") .addSelect("\"esvlistaprodutos\".CLASSEVENDA", "saleAbc") .addSelect("\"esvlistaprodutos\".CLASSEESTOQUE", "stockAbc") .addSelect("\"esvlistaprodutos\".FORALINHA", "outLine") .addSelect("\"esvlistaprodutos\".PRECOVENDA", "listPrice") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL", "salePrice") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL", "salePromotion") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL_AVISTA", "salePromotion_cash") .addSelect("\"esvlistaprodutos\".PERCENTUALDESCONTO", "offPercent") .addSelect("\"esvlistaprodutos\".QTESTOQUE_DISPONIVEL", "stock") .addSelect("\"esvlistaprodutos\".QTCAIXAS", "boxStock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_LOJA", "store_stock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_CAIXA_LOJA", "store_boxStock") .addSelect("\"esvlistaprodutos\".MULTIPLO", "mutiple") .addSelect("\"esvlistaprodutos\".UNIDADE", "unity") .addSelect("\"esvlistaprodutos\".URLDEPARTAMENTO", "urlDepartment") .addSelect("\"esvlistaprodutos\".URLSECAO", "urlSection") .addSelect("\"esvlistaprodutos\".PRODUTO_COM_REDUCAO_PRECO", "downPrice") .addSelect("\"esvlistaprodutos\".PRODUTO_EM_CAMPANHA", "compaing") .addSelect("\"esvlistaprodutos\".BASETINTOMETRICO", "base") .addSelect("\"esvlistaprodutos\".LETRATINTOMETRICO", "letter") .addSelect("\"esvlistaprodutos\".LINHATINTOMETRICO", "line") .addSelect("\"esvlistaprodutos\".LITRAGEM", "can") .addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock") .addSelect("\"esvlistaprodutos\".TEM_PRODUTO_SIMILAR", "similar") .addSelect("\"esvlistaprodutos\".TIPO_CAMPANHA", "type_campaing") .where("(\"esvlistaprodutos\".codfilial = :codfilial OR :codfilial = '99')", { codfilial: store }) .andWhere("(\"esvlistaprodutos\".produto_com_reducao_preco = :produtoComReducaoPreco OR :produtoComReducaoPreco = 'N')", { produtoComReducaoPreco: (filter.markdown.toString() == 'true') ? 'S' : 'N' }) // .andWhere("(\"esvlistaprodutos\".produto_em_campanha = :campaign OR :campaign = 'N')", // { campaign: (filter && filter.campaign) ? 'I' : 'N' }) .andWhere("(\"esvlistaprodutos\".produto_oportunidade = :oportunity OR :oportunity = 'N')", { oportunity: (filter.oportunity.toString() == 'true') ? 'O' : 'N' }) .andWhere("(\"esvlistaprodutos\".produto_em_promocao = :produtoEmPromocao OR :produtoEmPromocao = 'N')", { produtoEmPromocao: (filter.promotion.toString() == 'true') ? 'S' : 'N' }) .limit(pageSize) .offset(offSet) .orderBy("\"esvlistaprodutos\".DESCRICAO", "ASC") .getRawMany(); products = this.createListImages(products); console.log(products.length + ' produtos'); return products; } } catch (error) { console.log(error); throw error; } finally { await queryRunner.release(); await connectionDb.close(); } } async searchByDepartment( store: string, pageSize: number, pageNumber: number, urlDepartment: string ): Promise { const cacheKey = 'searchByDepartment:' + store + '_' + pageSize + '_' + pageNumber + '_' + urlDepartment; const lockKey = 'lock:' + cacheKey; const lockTimeout = 30; // lock expira em 30 segundos try { const cachedResult = await this.redisClient.get(cacheKey); if (cachedResult) { console.log('Retornando resultado do cache (searchByDepartment)'); return JSON.parse(cachedResult); } } catch (err) { console.error('Erro ao acessar o Redis no searchByDepartment:', err?.message || err); } const lockValue = Date.now() + lockTimeout * 1000 + 1; let acquiredLock: string | null = null; try { acquiredLock = await this.redisClient.set(lockKey, lockValue, 'NX', 'EX', lockTimeout); } catch (err) { console.error('Erro ao adquirir lock no Redis (searchByDepartment):', err?.message || err); } if (acquiredLock === 'OK') { const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); 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 { 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); } } } else { console.log('Lock não adquirido (searchByDepartment), aguardando e tentando novamente...'); await this.sleep(1000); return this.searchByDepartment(store, pageSize, pageNumber, urlDepartment); } } async searchBySection(store: string, pageSize: number, pageNumber: number, urlDepartment: string, urlSection: string): Promise { const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); const url = urlDepartment + '/' + urlSection; 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\".urlsecao = :url', { url }) .andWhere("(\"esvlistaprodutos\".codfilial = :codfilial OR :codfilial = '99')", { codfilial: store }) .limit(pageSize) .offset(offSet) .orderBy("\"esvlistaprodutos\".DESCRICAO", "ASC") .getMany(); products = this.createListImages(products); return products; } catch (error) { console.log(error); throw error; } finally { await queryRunner.release(); await connectionDb.close(); } } async searchByCategory(store: string, pageSize: number, pageNumber: number, urlDepartment: string, urlSection: string, urlCategory: string): Promise { const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); const url = urlDepartment + '/' + urlSection + '/' + urlCategory; 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\".urlcategoria = :url', { url }) .andWhere("(\"esvlistaprodutos\".codfilial = :codfilial OR :codfilial = '99')", { codfilial: store }) .limit(pageSize) .offset(offSet) .orderBy("\"esvlistaprodutos\".DESCRICAO", "ASC") .getMany(); products = this.createListImages(products); return products; } catch (error) { console.log(error); throw error; } finally { await queryRunner.release(); await connectionDb.close(); } } async searchProduct(store: string, search: string, pageSize: number, pageNumber: number) { const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); try { if (pageSize == 0) pageSize = 50; if (pageNumber == 0) pageNumber = 1; const offSet = (pageNumber - 1) * pageSize; const numbers = search.replace(/[^0-9]/g, ''); let products: SalesProduct[] = []; if (numbers === search) { products = await queryRunner.manager .getRepository(SalesProduct) .createQueryBuilder('esvlistaprodutos') .select("\"esvlistaprodutos\".CODPROD", "idProduct") .addSelect("\"esvlistaprodutos\".SEQ", "seq") .addSelect("\"esvlistaprodutos\".DESCRICAO", "smallDescription") .addSelect("\"esvlistaprodutos\".NOMEECOMMERCE", "title") .addSelect("\"esvlistaprodutos\".CODFAB", "idProvider") .addSelect("\"esvlistaprodutos\".CODAUXILIAR", "ean") .addSelect("\"esvlistaprodutos\".TIPOPRODUTO", "productType") .addSelect("\"esvlistaprodutos\".DADOSTECNICOS", "technicalData") .addSelect("\"esvlistaprodutos\".INFORMACOESTECNICAS", "description") .addSelect("\"esvlistaprodutos\".URLIMAGEM", "urlImage") .addSelect("\"esvlistaprodutos\".NOMEMARCA", "brand") .addSelect("\"esvlistaprodutos\".NOMEDEPARTAMENTO", "department") .addSelect("\"esvlistaprodutos\".NOMESECAO", "section") .addSelect("\"esvlistaprodutos\".NOMECATEGORIA", "category") .addSelect("\"esvlistaprodutos\".NOMEFORNECEDOR", "supplier") .addSelect("\"esvlistaprodutos\".CODIGOFILIAL", "store") .addSelect("\"esvlistaprodutos\".CLASSEVENDA", "saleAbc") .addSelect("\"esvlistaprodutos\".CLASSEESTOQUE", "stockAbc") .addSelect("\"esvlistaprodutos\".FORALINHA", "outLine") .addSelect("\"esvlistaprodutos\".PRECOVENDA", "listPrice") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL", "salePrice") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL", "salePromotion") .addSelect("\"esvlistaprodutos\".PERCENTUALDESCONTO", "offPercent") .addSelect("\"esvlistaprodutos\".QTESTOQUE_DISPONIVEL", "stock") .addSelect("\"esvlistaprodutos\".QTCAIXAS", "boxStock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_LOJA", "store_stock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_CAIXA_LOJA", "store_boxStock") .addSelect("\"esvlistaprodutos\".MULTIPLO", "mutiple") .addSelect("\"esvlistaprodutos\".UNIDADE", "unity") .addSelect("\"esvlistaprodutos\".URLDEPARTAMENTO", "urlDepartment") .addSelect("\"esvlistaprodutos\".URLSECAO", "urlSection") .addSelect("\"esvlistaprodutos\".PRODUTO_COM_REDUCAO_PRECO", "downPrice") .addSelect("\"esvlistaprodutos\".PRODUTO_EM_CAMPANHA", "compaing") .addSelect("\"esvlistaprodutos\".BASETINTOMETRICO", "base") .addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock") .addSelect("\"esvlistaprodutos\".TEM_PRODUTO_SIMILAR", "similar") .addSelect("\"esvlistaprodutos\".TIPO_CAMPANHA", "type_campaing") .where("esvlistaprodutos.idProduct = :id", { id: numbers }) .andWhere("\"esvlistaprodutos\".codfilial = :codfilial OR :codfilial = '99'", { codfilial: store }) .limit(pageSize) .offset(offSet) .orderBy("REPLACE(\"esvlistaprodutos\".DESCRICAO,'#', '')", "ASC") .getRawMany(); if (products.length === 0) { console.log('pesquisando por ean'); products = await queryRunner.manager .getRepository(SalesProduct) .createQueryBuilder('esvlistaprodutos') .select("\"esvlistaprodutos\".CODPROD", "idProduct") .addSelect("\"esvlistaprodutos\".SEQ", "seq") .addSelect("\"esvlistaprodutos\".DESCRICAO", "smallDescription") .addSelect("\"esvlistaprodutos\".NOMEECOMMERCE", "title") .addSelect("\"esvlistaprodutos\".CODFAB", "idProvider") .addSelect("\"esvlistaprodutos\".CODAUXILIAR", "ean") .addSelect("\"esvlistaprodutos\".TIPOPRODUTO", "productType") .addSelect("\"esvlistaprodutos\".DADOSTECNICOS", "technicalData") .addSelect("\"esvlistaprodutos\".INFORMACOESTECNICAS", "description") .addSelect("\"esvlistaprodutos\".URLIMAGEM", "urlImage") .addSelect("\"esvlistaprodutos\".NOMEMARCA", "brand") .addSelect("\"esvlistaprodutos\".NOMEDEPARTAMENTO", "department") .addSelect("\"esvlistaprodutos\".NOMESECAO", "section") .addSelect("\"esvlistaprodutos\".NOMECATEGORIA", "category") .addSelect("\"esvlistaprodutos\".NOMEFORNECEDOR", "supplier") .addSelect("\"esvlistaprodutos\".CODIGOFILIAL", "store") .addSelect("\"esvlistaprodutos\".CLASSEVENDA", "saleAbc") .addSelect("\"esvlistaprodutos\".CLASSEESTOQUE", "stockAbc") .addSelect("\"esvlistaprodutos\".FORALINHA", "outLine") .addSelect("\"esvlistaprodutos\".PRECOVENDA", "listPrice") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL", "salePrice") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL", "salePromotion") .addSelect("\"esvlistaprodutos\".PERCENTUALDESCONTO", "offPercent") .addSelect("\"esvlistaprodutos\".QTESTOQUE_DISPONIVEL", "stock") .addSelect("\"esvlistaprodutos\".QTCAIXAS", "boxStock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_LOJA", "store_stock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_CAIXA_LOJA", "store_boxStock") .addSelect("\"esvlistaprodutos\".MULTIPLO", "mutiple") .addSelect("\"esvlistaprodutos\".UNIDADE", "unity") .addSelect("\"esvlistaprodutos\".URLDEPARTAMENTO", "urlDepartment") .addSelect("\"esvlistaprodutos\".URLSECAO", "urlSection") .addSelect("\"esvlistaprodutos\".PRODUTO_COM_REDUCAO_PRECO", "downPrice") .addSelect("\"esvlistaprodutos\".PRODUTO_EM_CAMPANHA", "compaing") .addSelect("\"esvlistaprodutos\".BASETINTOMETRICO", "base") .addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock") .addSelect("\"esvlistaprodutos\".TEM_PRODUTO_SIMILAR", "similar") .addSelect("\"esvlistaprodutos\".TIPO_CAMPANHA", "type_campaing") .where("esvlistaprodutos.CODAUXILIAR = :id", { id: numbers }) .andWhere("(\"esvlistaprodutos\".codfilial = :codfilial OR :codfilial = '99')", { codfilial: store }) .limit(pageSize) .offset(offSet) .orderBy("REPLACE(\"esvlistaprodutos\".DESCRICAO,'#', '')", "ASC") .getRawMany(); } } else { const description = '%' + search.toUpperCase() + '%'; console.log('consultando por codigo de fabrica'); products = await queryRunner.manager .getRepository(SalesProduct) .createQueryBuilder('esvlistaprodutos') .select("\"esvlistaprodutos\".CODPROD", "idProduct") .addSelect("\"esvlistaprodutos\".SEQ", "seq") .addSelect("\"esvlistaprodutos\".DESCRICAO", "smallDescription") .addSelect("\"esvlistaprodutos\".NOMEECOMMERCE", "title") .addSelect("\"esvlistaprodutos\".CODFAB", "idProvider") .addSelect("\"esvlistaprodutos\".CODAUXILIAR", "ean") .addSelect("\"esvlistaprodutos\".TIPOPRODUTO", "productType") .addSelect("\"esvlistaprodutos\".DADOSTECNICOS", "technicalData") .addSelect("\"esvlistaprodutos\".INFORMACOESTECNICAS", "description") .addSelect("\"esvlistaprodutos\".URLIMAGEM", "urlImage") .addSelect("\"esvlistaprodutos\".NOMEMARCA", "brand") .addSelect("\"esvlistaprodutos\".NOMEDEPARTAMENTO", "department") .addSelect("\"esvlistaprodutos\".NOMESECAO", "section") .addSelect("\"esvlistaprodutos\".NOMECATEGORIA", "category") .addSelect("\"esvlistaprodutos\".NOMEFORNECEDOR", "supplier") .addSelect("\"esvlistaprodutos\".CODIGOFILIAL", "store") .addSelect("\"esvlistaprodutos\".CLASSEVENDA", "saleAbc") .addSelect("\"esvlistaprodutos\".CLASSEESTOQUE", "stockAbc") .addSelect("\"esvlistaprodutos\".FORALINHA", "outLine") .addSelect("\"esvlistaprodutos\".PRECOVENDA", "listPrice") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL", "salePrice") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL", "salePromotion") .addSelect("\"esvlistaprodutos\".PERCENTUALDESCONTO", "offPercent") .addSelect("\"esvlistaprodutos\".QTESTOQUE_DISPONIVEL", "stock") .addSelect("\"esvlistaprodutos\".QTCAIXAS", "boxStock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_LOJA", "store_stock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_CAIXA_LOJA", "store_boxStock") .addSelect("\"esvlistaprodutos\".MULTIPLO", "mutiple") .addSelect("\"esvlistaprodutos\".UNIDADE", "unity") .addSelect("\"esvlistaprodutos\".URLDEPARTAMENTO", "urlDepartment") .addSelect("\"esvlistaprodutos\".URLSECAO", "urlSection") .addSelect("\"esvlistaprodutos\".PRODUTO_COM_REDUCAO_PRECO", "downPrice") .addSelect("\"esvlistaprodutos\".PRODUTO_EM_CAMPANHA", "compaing") .addSelect("\"esvlistaprodutos\".BASETINTOMETRICO", "base") .addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock") .addSelect("\"esvlistaprodutos\".TEM_PRODUTO_SIMILAR", "similar") .addSelect("\"esvlistaprodutos\".TIPO_CAMPANHA", "type_campaing") .where("UPPER(esvlistaprodutos.CODFAB) like REPLACE(:description, '@', '%')", { description }) .andWhere("\"esvlistaprodutos\".codfilial = :codfilial OR :codfilial = '99'", { codfilial: store }) .limit(pageSize) .offset(offSet) .orderBy("REPLACE(\"esvlistaprodutos\".DESCRICAO,'#', '')", "ASC") .getRawMany(); if (products.length == 0) { products = await queryRunner.manager .getRepository(SalesProduct) .createQueryBuilder('esvlistaprodutos') .select("\"esvlistaprodutos\".CODPROD", "idProduct") .addSelect("\"esvlistaprodutos\".SEQ", "seq") .addSelect("\"esvlistaprodutos\".DESCRICAO", "smallDescription") .addSelect("\"esvlistaprodutos\".NOMEECOMMERCE", "title") .addSelect("\"esvlistaprodutos\".CODFAB", "idProvider") .addSelect("\"esvlistaprodutos\".CODAUXILIAR", "ean") .addSelect("\"esvlistaprodutos\".TIPOPRODUTO", "productType") .addSelect("\"esvlistaprodutos\".DADOSTECNICOS", "technicalData") .addSelect("\"esvlistaprodutos\".INFORMACOESTECNICAS", "description") .addSelect("\"esvlistaprodutos\".URLIMAGEM", "urlImage") .addSelect("\"esvlistaprodutos\".NOMEMARCA", "brand") .addSelect("\"esvlistaprodutos\".NOMEDEPARTAMENTO", "department") .addSelect("\"esvlistaprodutos\".NOMESECAO", "section") .addSelect("\"esvlistaprodutos\".NOMECATEGORIA", "category") .addSelect("\"esvlistaprodutos\".NOMEFORNECEDOR", "supplier") .addSelect("\"esvlistaprodutos\".CODIGOFILIAL", "store") .addSelect("\"esvlistaprodutos\".CLASSEVENDA", "saleAbc") .addSelect("\"esvlistaprodutos\".CLASSEESTOQUE", "stockAbc") .addSelect("\"esvlistaprodutos\".FORALINHA", "outLine") .addSelect("\"esvlistaprodutos\".PRECOVENDA", "listPrice") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL", "salePrice") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL", "salePromotion") .addSelect("\"esvlistaprodutos\".PERCENTUALDESCONTO", "offPercent") .addSelect("\"esvlistaprodutos\".QTESTOQUE_DISPONIVEL", "stock") .addSelect("\"esvlistaprodutos\".QTCAIXAS", "boxStock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_LOJA", "store_stock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_CAIXA_LOJA", "store_boxStock") .addSelect("\"esvlistaprodutos\".MULTIPLO", "mutiple") .addSelect("\"esvlistaprodutos\".UNIDADE", "unity") .addSelect("\"esvlistaprodutos\".URLDEPARTAMENTO", "urlDepartment") .addSelect("\"esvlistaprodutos\".URLSECAO", "urlSection") .addSelect("\"esvlistaprodutos\".PRODUTO_COM_REDUCAO_PRECO", "downPrice") .addSelect("\"esvlistaprodutos\".PRODUTO_EM_CAMPANHA", "compaing") .addSelect("\"esvlistaprodutos\".BASETINTOMETRICO", "base") .addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock") .addSelect("\"esvlistaprodutos\".TEM_PRODUTO_SIMILAR", "similar") .addSelect("\"esvlistaprodutos\".TIPO_CAMPANHA", "type_campaing") .where("UPPER(esvlistaprodutos.DESCRICAO) like REPLACE(:description, '@', '%')", { description }) .andWhere("\"esvlistaprodutos\".codfilial = :codfilial OR :codfilial = '99'", { codfilial: store }) .limit(pageSize) .offset(offSet) .orderBy("REPLACE(\"esvlistaprodutos\".DESCRICAO,'#', '')", "ASC") .getRawMany(); } } products = this.createListImages(products); console.log(products.length); return products; } catch (error) { console.log(error); throw error; } finally { await queryRunner.release(); await connectionDb.close(); } } async GetProduct(store: string, id: number) { const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); try { let products: SalesProduct[] = await queryRunner.manager .getRepository(SalesProduct) .createQueryBuilder('esvlistaprodutos') .select("\"esvlistaprodutos\".CODPROD", "idProduct") .addSelect("\"esvlistaprodutos\".SEQ", "seq") .addSelect("\"esvlistaprodutos\".DESCRICAO", "smallDescription") .addSelect("\"esvlistaprodutos\".NOMEECOMMERCE", "title") .addSelect("\"esvlistaprodutos\".CODFAB", "idProvider") .addSelect("\"esvlistaprodutos\".CODAUXILIAR", "ean") .addSelect("\"esvlistaprodutos\".TIPOPRODUTO", "productType") .addSelect("\"esvlistaprodutos\".DADOSTECNICOS", "technicalData") .addSelect("\"esvlistaprodutos\".INFORMACOESTECNICAS", "description") .addSelect("\"esvlistaprodutos\".URLIMAGEM", "urlImage") .addSelect("\"esvlistaprodutos\".NOMEMARCA", "brand") .addSelect("\"esvlistaprodutos\".NOMEDEPARTAMENTO", "department") .addSelect("\"esvlistaprodutos\".NOMESECAO", "section") .addSelect("\"esvlistaprodutos\".NOMECATEGORIA", "category") .addSelect("\"esvlistaprodutos\".NOMEFORNECEDOR", "supplier") .addSelect("\"esvlistaprodutos\".CODIGOFILIAL", "store") .addSelect("\"esvlistaprodutos\".CLASSEVENDA", "saleAbc") .addSelect("\"esvlistaprodutos\".CLASSEESTOQUE", "stockAbc") .addSelect("\"esvlistaprodutos\".FORALINHA", "outLine") .addSelect("\"esvlistaprodutos\".PRECOVENDA", "listPrice") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL", "salePrice") .addSelect("\"esvlistaprodutos\".PRECOPROMOCIONAL", "salePromotion") .addSelect("\"esvlistaprodutos\".PERCENTUALDESCONTO", "offPercent") .addSelect("\"esvlistaprodutos\".QTESTOQUE_DISPONIVEL", "stock") .addSelect("\"esvlistaprodutos\".QTCAIXAS", "boxStock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_LOJA", "store_stock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_CAIXA_LOJA", "store_boxStock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_LOJA", "store_stock") .addSelect("\"esvlistaprodutos\".ESTOQUE_DISP_CAIXA_LOJA", "store_boxStock") .addSelect("\"esvlistaprodutos\".MULTIPLO", "mutiple") .addSelect("\"esvlistaprodutos\".UNIDADE", "unity") .addSelect("\"esvlistaprodutos\".URLDEPARTAMENTO", "urlDepartment") .addSelect("\"esvlistaprodutos\".URLSECAO", "urlSection") .addSelect("\"esvlistaprodutos\".PRODUTO_COM_REDUCAO_PRECO", "downPrice") .addSelect("\"esvlistaprodutos\".PRODUTO_EM_CAMPANHA", "compaing") .addSelect("\"esvlistaprodutos\".BASETINTOMETRICO", "base") .addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock") .addSelect("\"esvlistaprodutos\".TEM_PRODUTO_SIMILAR", "similar") .addSelect("\"esvlistaprodutos\".TIPO_CAMPANHA", "type_campaing") .where("esvlistaprodutos.idProduct = :id", { id: id }) .andWhere("\"esvlistaprodutos\".codfilial = :codfilial", { codfilial: store }) .orderBy("REPLACE(\"esvlistaprodutos\".DESCRICAO,'#', '')", "ASC") .getRawMany(); products = this.createListImages(products); if (products.length == 0) { throw new HttpException('Produto não encontrado!', HttpStatus.NOT_FOUND); } const product = products[0]; return product; } catch (error) { throw error; } finally { await queryRunner.release(); await connectionDb.close(); } } async GetProductsBuyTogether(store: string, id: number) { const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); try { const sql = `SELECT esvlistaprodutos.CODPROD as "idProduct" ,esvlistaprodutos.SEQ as "seq" ,esvlistaprodutos.DESCRICAO as "smallDescription" ,esvlistaprodutos.NOMEECOMMERCE as "title" ,esvlistaprodutos.CODFAB as "idProvider" ,esvlistaprodutos.CODAUXILIAR as "ean" ,esvlistaprodutos.TIPOPRODUTO as "productType" ,esvlistaprodutos.DADOSTECNICOS as "technicalData" ,esvlistaprodutos.INFORMACOESTECNICAS as "description" ,esvlistaprodutos.URLIMAGEM as "urlImage" ,esvlistaprodutos.NOMEMARCA as "brand" ,esvlistaprodutos.NOMEDEPARTAMENTO as "department" ,esvlistaprodutos.NOMESECAO as "section" ,esvlistaprodutos.NOMECATEGORIA as "category" ,esvlistaprodutos.NOMEFORNECEDOR as "supplier" ,esvlistaprodutos.CODIGOFILIAL as "store" ,esvlistaprodutos.CLASSEVENDA as "saleAbc" ,esvlistaprodutos.CLASSEESTOQUE as "stockAbc" ,esvlistaprodutos.FORALINHA as "outLine" ,esvlistaprodutos.PRECOVENDA as "listPrice" ,esvlistaprodutos.PRECOPROMOCIONAL as "salePrice" ,esvlistaprodutos.PRECOPROMOCIONAL as "salePromotion" ,esvlistaprodutos.PERCENTUALDESCONTO as"offPercent" ,esvlistaprodutos.QTESTOQUE_DISPONIVEL as "stock" ,esvlistaprodutos.QTCAIXAS as "boxStock" ,esvlistaprodutos.ESTOQUE_DISP_LOJA as "store_stock" ,esvlistaprodutos.ESTOQUE_DISP_CAIXA_LOJA as "store_boxStock" ,esvlistaprodutos.ESTOQUE_DISP_LOJA as "store_stock" ,esvlistaprodutos.ESTOQUE_DISP_CAIXA_LOJA as "store_boxStock" ,esvlistaprodutos.MULTIPLO as "mutiple" ,esvlistaprodutos.UNIDADE as "unity" ,esvlistaprodutos.URLDEPARTAMENTO as "urlDepartment" ,esvlistaprodutos.URLSECAO as "urlSection" ,esvlistaprodutos.PRODUTO_COM_REDUCAO_PRECO as "downPrice" ,esvlistaprodutos.PRODUTO_EM_CAMPANHA as "compaing" ,esvlistaprodutos.BASETINTOMETRICO as "base" ,esvlistaprodutos.QUANTIDADE_ESTOQUE_GERAL as "full_stock" ,esvlistaprodutos.TEM_PRODUTO_SIMILAR as "similar" ,esvlistaprodutos.TIPO_CAMPANHA as "type_campaing" FROM ESVLISTAPRODUTOS, ESTCOMPREJUNTO WHERE ESVLISTAPRODUTOS.CODPROD = ESTCOMPREJUNTO.CODPROD AND ESTCOMPREJUNTO.CODPRODVENDA = ${id} AND ESVLISTAPRODUTOS.CODFILIAL = '${store}' ORDER BY REPLACE(esvlistaprodutos.DESCRICAO,'#', '')`; let products: SalesProduct[] = await queryRunner.query(sql); products = this.createListImages(products); return products; } catch (error) { throw error; } finally { await queryRunner.release(); await connectionDb.close(); } } async GetProductsSimil(store: string, id: number) { const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); try { const sql = `SELECT esvlistaprodutos.CODPROD as "idProduct" ,esvlistaprodutos.SEQ as "seq" ,esvlistaprodutos.DESCRICAO as "smallDescription" ,esvlistaprodutos.NOMEECOMMERCE as "title" ,esvlistaprodutos.CODFAB as "idProvider" ,esvlistaprodutos.CODAUXILIAR as "ean" ,esvlistaprodutos.TIPOPRODUTO as "productType" ,esvlistaprodutos.DADOSTECNICOS as "technicalData" ,esvlistaprodutos.INFORMACOESTECNICAS as "description" ,esvlistaprodutos.URLIMAGEM as "urlImage" ,esvlistaprodutos.NOMEMARCA as "brand" ,esvlistaprodutos.NOMEDEPARTAMENTO as "department" ,esvlistaprodutos.NOMESECAO as "section" ,esvlistaprodutos.NOMECATEGORIA as "category" ,esvlistaprodutos.NOMEFORNECEDOR as "supplier" ,esvlistaprodutos.CODIGOFILIAL as "store" ,esvlistaprodutos.CLASSEVENDA as "saleAbc" ,esvlistaprodutos.CLASSEESTOQUE as "stockAbc" ,esvlistaprodutos.FORALINHA as "outLine" ,esvlistaprodutos.PRECOVENDA as "listPrice" ,esvlistaprodutos.PRECOPROMOCIONAL as "salePrice" ,esvlistaprodutos.PRECOPROMOCIONAL as "salePromotion" ,esvlistaprodutos.PERCENTUALDESCONTO as"offPercent" ,esvlistaprodutos.QTESTOQUE_DISPONIVEL as "stock" ,esvlistaprodutos.QTCAIXAS as "boxStock" ,esvlistaprodutos.ESTOQUE_DISP_LOJA as "store_stock" ,esvlistaprodutos.ESTOQUE_DISP_CAIXA_LOJA as "store_boxStock" ,esvlistaprodutos.ESTOQUE_DISP_LOJA as "store_stock" ,esvlistaprodutos.ESTOQUE_DISP_CAIXA_LOJA as "store_boxStock" ,esvlistaprodutos.MULTIPLO as "mutiple" ,esvlistaprodutos.UNIDADE as "unity" ,esvlistaprodutos.URLDEPARTAMENTO as "urlDepartment" ,esvlistaprodutos.URLSECAO as "urlSection" ,esvlistaprodutos.PRODUTO_COM_REDUCAO_PRECO as "downPrice" ,esvlistaprodutos.PRODUTO_EM_CAMPANHA as "compaing" ,esvlistaprodutos.BASETINTOMETRICO as "base" ,esvlistaprodutos.QUANTIDADE_ESTOQUE_GERAL as "full_stock" ,esvlistaprodutos.TEM_PRODUTO_SIMILAR as "similar" ,esvlistaprodutos.TIPO_CAMPANHA as "type_campaing" FROM ESVLISTAPRODUTOS, PCPRODSIMIL WHERE ESVLISTAPRODUTOS.CODPROD = PCPRODSIMIL.CODSIMIL AND PCPRODSIMIL.CODPROD = ${id} AND ESVLISTAPRODUTOS.CODFILIAL = '${store}' ORDER BY REPLACE(esvlistaprodutos.DESCRICAO,'#', '')`; let products: SalesProduct[] = await queryRunner.query(sql); products = this.createListImages(products); return products; } catch (error) { throw error; } finally { await queryRunner.release(); await connectionDb.close(); } } async GetStocks(storeId: string, id: number) { const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); try { const sql = `SELECT ESVESTOQUEVENDA.CODFILIAL as "store" ,PCFILIAL.FANTASIA as "storeName" ,ESVESTOQUEVENDA.CODPROD as "idProduct" ,ESVESTOQUEVENDA.PERTENCE as "work" ,ESVESTOQUEVENDA.QUANTIDADEESTOQUEDISPONIVEL as "quantity" ,ESVESTOQUEVENDA.QUANTIDADEBLOQUEADA as "blocked" ,ESVESTOQUEVENDA.QUANTIDADEAVARIA as "breakdown" ,ESVESTOQUEVENDA.QUANTIDADETRANSITO as "transfer" ,(CASE WHEN (SELECT COUNT(1) FROM PCFILIALRETIRA WHERE PCFILIALRETIRA.CODFILIALVENDA = '${storeId}' AND PCFILIALRETIRA.CODFILIALRETIRA = ESVESTOQUEVENDA.CODFILIAL ) > 0 THEN 1 ELSE 0 END ) as "allowDelivery" FROM ESVESTOQUEVENDA, PCFILIAL WHERE ESVESTOQUEVENDA.CODPROD = ${id} AND ESVESTOQUEVENDA.CODFILIAL = PCFILIAL.CODIGO ORDER BY TO_NUMBER(ESVESTOQUEVENDA.CODFILIAL) `; const stock = await queryRunner.query(sql); // return await queryRunner.manager // .getRepository(Stock) // .createQueryBuilder('esvestoquevenda') // .where("esvestoquevenda.idProduct = :id", { id: id }) // .getMany(); return stock; } catch (error) { console.log(error); throw error; } finally { await queryRunner.release(); await connectionDb.close(); } } async GetSaleInstallment(store: string, id: number, quantity: number) { const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); try { const installments = await queryRunner.manager .getRepository(Esvparcelamentovenda) .createQueryBuilder('esvparcelamentovenda') .select('\"esvparcelamentovenda\".CODFILIAL', 'store') .addSelect('\"esvparcelamentovenda\".CODPROD', 'productId') .addSelect('\"esvparcelamentovenda\".NUMREGIAO', 'priceTable') .addSelect('\"esvparcelamentovenda\".PARCELAS', 'installment') .addSelect('\"esvparcelamentovenda\".PRECOVENDA', 'salePrice') .addSelect('\"esvparcelamentovenda\".VALORPARCELA', 'installmentValue') .where("esvparcelamentovenda.store = :store", { store: store }) .andWhere("esvparcelamentovenda.productId = :id", { id: id }) .getRawMany(); installments.forEach(i => { i.salePrice = i.salePrice * quantity; i.installmentValue = i.installmentValue * quantity; }) return installments; } catch (error) { console.log(error); throw error; } finally { await queryRunner.release(); await connectionDb.close(); } } async GetDelivery(cpf: string): Promise { const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); try { const customer = await queryRunner.manager .getRepository(Pcclient) .createQueryBuilder('pcclient') .where("regexp_replace(cgcent, '[^0-9]', '') = regexp_replace(:cpf, '[^0-9]', '') AND dtexclusao is null", { cpf }) .getOne(); if (customer == null) { throw new HttpException('CPF não localizado em nosso cadastro de clientes.', HttpStatus.NOT_FOUND); } const orders = await queryRunner.manager .getRepository(Esvsituacaopedido) .createQueryBuilder('esvsituacaopedido') .where("\"esvsituacaopedido\".codcli = :codcli", { codcli: customer.codcli }) .getMany(); return orders; } catch (error) { console.log(error); throw error; } finally { await queryRunner.release(); await connectionDb.close(); } } async GetAnaliseVenda(id: number): Promise { const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); try { const result = await queryRunner.manager .getRepository(Esvanalisevendarca) .createQueryBuilder('esvanalisevendarca') .where("\"esvanalisevendarca\".codusur = :codusur", { codusur: id }) .getOne(); return result; } catch (error) { throw error; } finally { await queryRunner.release(); await connectionDb.close(); } } async GetHistoricoVendas(id: number): Promise { const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); try { const sql = `SELECT PCDIASUTEIS.DATA as "saleDate", CASE WHEN TO_CHAR(PCDIASUTEIS.DATA, 'D') = 1 THEN 'DOMINGO' WHEN TO_CHAR(PCDIASUTEIS.DATA, 'D') = 2 THEN 'SEGUNDA' WHEN TO_CHAR(PCDIASUTEIS.DATA, 'D') = 3 THEN 'TERÇA' WHEN TO_CHAR(PCDIASUTEIS.DATA, 'D') = 4 THEN 'QUARTA' WHEN TO_CHAR(PCDIASUTEIS.DATA, 'D') = 5 THEN 'QUINTA' WHEN TO_CHAR(PCDIASUTEIS.DATA, 'D') = 6 THEN 'SEXTA' WHEN TO_CHAR(PCDIASUTEIS.DATA, 'D') = 7 THEN 'SABADO' END as "dayWeek", NVL(VENDAS.CODUSUR, ${id}) as "sellerId", NVL(VENDAS.VLVENDA,0) as "saleValue", NVL(DEVOLUCAO.VLDEVOLUCAO,0) as "devolucao", ( NVL(VENDAS.VLVENDA,0) - NVL(DEVOLUCAO.VLDEVOLUCAO,0) ) as "amount", ESVCOMISSAOVENDAS.VLCOMISSAO as "comissionValue" FROM PCDIASUTEIS, ESVCOMISSAOVENDAS, ( SELECT VENDAS.DTSAIDA ,VENDAS.CODUSUR ,SUM(VENDAS.VLVENDA) VLVENDA FROM VIEW_VENDAS_RESUMO_FATURAMENTO VENDAS WHERE VENDAS.CONDVENDA IN (1,7) AND VENDAS.DTCANCEL IS NULL AND VENDAS.DTSAIDA >= TRUNC(SYSDATE) - 90 AND VENDAS.CODUSUR = 15 GROUP BY VENDAS.DTSAIDA, VENDAS.CODUSUR ) VENDAS, ( SELECT DEVOLUCAO.DTENT ,DEVOLUCAO.CODUSUR ,SUM(DEVOLUCAO.VLDEVOLUCAO) VLDEVOLUCAO FROM VIEW_DEVOL_RESUMO_FATURAMENTO DEVOLUCAO WHERE DEVOLUCAO.DTCANCEL IS NULL AND DEVOLUCAO.DTENT >= TRUNC(SYSDATE) - 90 AND DEVOLUCAO.CODUSUR = 15 GROUP BY DEVOLUCAO.DTENT, DEVOLUCAO.CODUSUR ) DEVOLUCAO WHERE PCDIASUTEIS.DATA = VENDAS.DTSAIDA (+) AND PCDIASUTEIS.DATA = DEVOLUCAO.DTENT (+) AND ESVCOMISSAOVENDAS.CODUSUR = ${id} AND PCDIASUTEIS.DATA BETWEEN LAST_DAY(ADD_MONTHS(TRUNC(SYSDATE),-1)) + 1 AND TRUNC(SYSDATE) AND PCDIASUTEIS.CODFILIAL = 6 ORDER BY PCDIASUTEIS.DATA`; const result = await queryRunner.query(sql); return result; } finally { await queryRunner.release(); await connectionDb.close(); } } createListImages(products: SalesProduct[]): SalesProduct[] { products.forEach(product => { product.images = []; if (product.urlImage != null) { let urlImage = product.urlImage; if (urlImage.indexOf(";") == -1) { urlImage += ";"; } const images = product.urlImage.split(";"); product.images = images.map(i => i.trim()); } }); return products; } async createNotification(data: Notify) { const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); await queryRunner.startTransaction(); try { const notify: Estavisoestoque = new Estavisoestoque(); notify.id = null; notify.createDate = new Date(); notify.codusur = data.idSeller; notify.cpf = data.document; notify.name = data.name; notify.cellPhone = data.cellPhone; notify.email = data.email; notify.codprod = data.codprod; notify.obs = data.notification; await queryRunner.manager .createQueryBuilder() .insert() .into(Estavisoestoque) .values(notify) .execute(); await queryRunner.commitTransaction(); } catch (err) { await queryRunner.rollbackTransaction(); throw err; } finally { await queryRunner.release(); await connectionDb.close(); } } async createRuptura(data: Rupture) { const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); let customerId = 0; const customer = await queryRunner.manager .getRepository(Pcclient) .createQueryBuilder('pcclient') .where("regexp_replace(cgcent, '[^0-9]', '') = regexp_replace(:cpf, '[^0-9]', '') AND dtexclusao is null", { cpf: data.document }) .getOne(); if (customer) { customerId = customer.codcli; } await queryRunner.startTransaction(); try { const ruptura: Estruptura = new Estruptura(); ruptura.id = null; ruptura.date = new Date(); ruptura.store = data.store; ruptura.customerId = customerId; ruptura.sellerId = Number.parseFloat(data.seller); ruptura.document = data.document; ruptura.name = data.name; ruptura.cellPhone = data.cellPhone; ruptura.email = data.email; ruptura.productId = data.idProduct; ruptura.quantity = data.quantity; await queryRunner.manager .createQueryBuilder() .insert() .into(Estruptura) .values(ruptura) .execute(); await queryRunner.commitTransaction(); } catch (err) { await queryRunner.rollbackTransaction(); throw err; } finally { await queryRunner.release(); await connectionDb.close(); } } async getDepartments(): Promise { const cacheKey = 'departments'; const lockKey = 'departments_lock'; const lockTimeout = 30; try { const cachedDepartments = await this.redisClient.get(cacheKey); if (cachedDepartments) { console.log('Buscando departamentos no Redis'); return JSON.parse(cachedDepartments); } } catch (err) { console.error('Erro ao acessar o Redis (cache):', err); } const lockValue = Date.now() + lockTimeout * 1000 + 1; const acquiredLock = await this.redisClient.set(lockKey, lockValue, 'NX', 'EX', lockTimeout); if (acquiredLock === 'OK') { const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); 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 { 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); } } } else { console.log('Lock não adquirido, aguardando a liberação...'); await this.sleep(1000); // aguarda 1 segundo return this.getDepartments(); } } private sleep(ms: number): Promise { return new Promise(resolve => setTimeout(resolve, ms)); } async getCategory() { const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); try { const departments = await queryRunner.manager .getRepository(Esvsecao) .createQueryBuilder('esvsecao') .innerJoinAndSelect('esvsecao.departamento', 'departamento') .innerJoinAndSelect('esvsecao.categorias', 'categorias') .getMany(); return departments; } catch (err) { throw err; } finally { await queryRunner.release(); await connectionDb.close(); } } async searchProduct2(store: string, pageSize: number, pageNumber: number, filter: FilterProduct) { console.log('searchProduct2'); const cacheKey = `searchProduct2:${store}:${pageSize}:${pageNumber}:${JSON.stringify(filter)}`; const cachedProducts = await this.redisClient.get(cacheKey); if (cachedProducts) { console.log('Retornando produtos do cache'); return JSON.parse(cachedProducts); } const sql = 'SELECT esvlistaprodutos.CODPROD "idProduct" ' + ` ,esvlistaprodutos.SEQ "seq" ` + ' ,esvlistaprodutos.DESCRICAO "smallDescription" ' + ' ,esvlistaprodutos.NOMEECOMMERCE "title" ' + ' ,esvlistaprodutos.CODFAB "idProvider" ' + ' ,esvlistaprodutos.CODAUXILIAR "ean" ' + ' ,esvlistaprodutos.TIPOPRODUTO "productType" ' + ' ,esvlistaprodutos.DADOSTECNICOS "technicalData" ' + ' ,esvlistaprodutos.INFORMACOESTECNICAS "description" ' + ' ,esvlistaprodutos.URLIMAGEM "urlImage" ' + ' ,esvlistaprodutos.NOMEMARCA "brand" ' + ' ,esvlistaprodutos.NOMEDEPARTAMENTO "department" ' + ' ,esvlistaprodutos.NOMESECAO "section" ' + ' ,esvlistaprodutos.NOMECATEGORIA "category" ' + ' ,esvlistaprodutos.NOMEFORNECEDOR "supplier" ' + ' ,esvlistaprodutos.CODIGOFILIAL "store" ' + ' ,esvlistaprodutos.CLASSEVENDA "saleAbc" ' + ' ,esvlistaprodutos.CLASSEESTOQUE "stockAbc" ' + ' ,esvlistaprodutos.FORALINHA "outLine" ' + ' ,esvlistaprodutos.PRECOVENDA "listPrice" ' + ' ,esvlistaprodutos.PRECOPROMOCIONAL "salePrice" ' + ' ,esvlistaprodutos.PRECOPROMOCIONAL "salePromotion" ' + ' ,esvlistaprodutos.PRECOPROMOCIONAL_AVISTA "salePromotion_cash" ' + ' ,esvlistaprodutos.PERCENTUALDESCONTO "offPercent" ' + ' ,esvlistaprodutos.QTESTOQUE_DISPONIVEL "stock" ' + ' ,esvlistaprodutos.QTCAIXAS "boxStock" ' + ' ,esvlistaprodutos.ESTOQUE_DISP_LOJA "store_stock" ' + ' ,esvlistaprodutos.ESTOQUE_DISP_CAIXA_LOJA "store_boxStock" ' + ' ,esvlistaprodutos.MULTIPLO "mutiple" ' + ' ,esvlistaprodutos.UNIDADE "unity" ' + ' ,esvlistaprodutos.URLDEPARTAMENTO "urlDepartment" ' + ' ,esvlistaprodutos.URLSECAO "urlSection" ' + ' ,esvlistaprodutos.PRODUTO_COM_REDUCAO_PRECO "downPrice" ' + ' ,esvlistaprodutos.PRODUTO_EM_CAMPANHA "compaing" ' + ' ,esvlistaprodutos.BASETINTOMETRICO "base" ' + ' ,esvlistaprodutos.LETRABASETINTOMETRICO "letter" ' + ' ,esvlistaprodutos.LINHATINTOMETRICO "line" ' + ' ,esvlistaprodutos.LITRAGEM "can" ' + ' ,esvlistaprodutos.QUANTIDADE_ESTOQUE_GERAL "full_stock" ' + ' ,esvlistaprodutos.TEM_PRODUTO_SIMILAR "similar" ' + ' ,esvlistaprodutos.TIPO_CAMPANHA "type_campaing" ' + ' FROM esvlistaprodutos ' + ' WHERE 1 = 1 '; let where = ""; if (filter.text != null) { where += ` AND ( ESF_REMOVE_ACENTUACAO(UPPER(esvlistaprodutos.descricao)) LIKE ` + ` ESF_REMOVE_ACENTUACAO(REPLACE('${filter.text}', '@', '%'))||'%' ` + ` OR ESF_REMOVE_ACENTUACAO(UPPER(esvlistaprodutos.nomeecommerce)) LIKE ` + ` ESF_REMOVE_ACENTUACAO(REPLACE('${filter.text}', '@', '%'))||'%' ` + ` OR esvlistaprodutos.codprod = REGEXP_REPLACE('${filter.text}', '[^0-9]', '') ` + ` OR esvlistaprodutos.codauxiliar = REGEXP_REPLACE('${filter.text}', '[^0-9]', '') ` + ` OR esvlistaprodutos.nomemarca = REPLACE('${filter.text}', '@', '%') ` + ` OR esvlistaprodutos.codfab LIKE '${filter.text}%' )`; } if (filter.urlCategory != null) { where += ` AND esvlistaprodutos.urlcategoria like '${filter.urlCategory}%'`; } where += ` AND (esvlistaprodutos.codfilial = '${store}' OR '${store}' = '99') `; where += ` AND (esvlistaprodutos.produto_com_reducao_preco = '${(filter.markdown ? 'S' : 'N')}' OR '${(filter.markdown ? '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_promocao = '${(filter.promotion ? 'S' : 'N')}' OR '${(filter.promotion ? 'S' : 'N')}' = 'N') `; if (filter.onlyWithStock) { if (filter.storeStock == '' || filter.storeStock == null) { where += ` AND EXISTS( SELECT P.CODPROD FROM ESVLISTAPRODUTOS P ` + ` WHERE P.CODPROD = ESVLISTAPRODUTOS.CODPROD ` + ` AND P.QTESTOQUE_DISPONIVEL > 0 ) `; } else { where += ` AND EXISTS( SELECT P.CODPROD FROM ESVLISTAPRODUTOS P ` + ` WHERE P.CODPROD = ESVLISTAPRODUTOS.CODPROD AND P.CODFILIAL = '${filter.storeStock}' ` + ` AND P.ESTOQUE_DISP_LOJA > 0 ) `; } } if (filter.percentOffMin > 0) { where += ` AND esvlistaprodutos.PERCENTUALDESCONTO >= ${filter.percentOffMin}`; } if (filter.percentOffMax > 0) { where += ` AND esvlistaprodutos.PERCENTUALDESCONTO <= ${filter.percentOffMax}`; } let xbrands = ''; if (filter && filter.brands && filter.brands.length > 0) { const brands = filter.brands; brands.forEach(b => { if (xbrands.length > 0) { xbrands += ', ' + '\'' + b + '\''; } else { xbrands = '\'' + b + '\''; } }); where += ` AND esvlistaprodutos.nomemarca in ( ${xbrands} )`; } const orderBy = `ORDER BY esvlistaprodutos.${(filter.orderBy == null) ? 'DESCRICAO' : filter.orderBy}`; const skipReg = ((pageNumber - 1) * pageSize); const pagination = ` OFFSET ${skipReg} ROWS FETCH NEXT ${pageSize} ROWS ONLY`; const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); try { let products = await queryRunner.manager.query(sql + where + orderBy + pagination) as SalesProduct[]; products = this.createListImages(products); console.log("Total de produtos: " + products.length); await this.redisClient.set(cacheKey, JSON.stringify(products), 'EX', 3600); return products; } catch (err) { console.log(err); throw err; } finally { await queryRunner.release(); await connectionDb.close(); } } async calculateDeliveryTax(cartId: string, ibgeCode: string) { let cityId = await this.customerService.findCity(ibgeCode); if (cityId == 0) { cityId = Number.parseInt(ibgeCode); // throw new HttpException('Cidade não localiza para cálculo da taxa de entrega', HttpStatus.BAD_REQUEST); } const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); try { const sql = 'SELECT ESVCALCULOFRETE.CODTABELAFRETE as "id" ' + ' ,ESVCALCULOFRETE.CODFILIAL as "store" ' + ' ,ESVCALCULOFRETE.CODCIDADE as "cityId" ' + ' ,PCCIDADE.NOMECIDADE as "cityName" ' + ' ,ESVCALCULOFRETE.CODFORNEC as "carrierId" ' + ' ,PCFORNEC.FORNECEDOR as "carrierName" ' + ' ,ESVCALCULOFRETE.VLCOMPRAMIN as "minSale" ' + ' ,ESVCALCULOFRETE.VLFRETE as "deliveryValue" ' + ' ,ESVCALCULOFRETE.PRAZOENTREGA as "deliveryTime" ' + ' FROM ESVCALCULOFRETE, PCFORNEC, PCCIDADE ' + ' WHERE ESVCALCULOFRETE.CODFORNEC = PCFORNEC.CODFORNEC ' + ' AND ESVCALCULOFRETE.CODCIDADE = PCCIDADE.CODCIDADE ' + ' AND ESVCALCULOFRETE.CODCIDADE = :1 ' + ' AND ESVCALCULOFRETE.IDCART = :2 ' + ' ORDER BY VLFRETE'; const deliveryTaxTable = await queryRunner.manager .query(sql, [cityId, cartId]); return deliveryTaxTable; } catch (err) { throw err; } finally { await queryRunner.release(); await connectionDb.close(); } } async updatePriorityDelivery(cartId: string, priorityDelivery: string) { const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); await queryRunner.startTransaction(); try { const sql = `UPDATE ESTPREVENDAC SET TIPOPRIORIDADEENTREGA = '${priorityDelivery}' WHERE ID = '${cartId}'`; await queryRunner.manager .query(sql); await queryRunner.commitTransaction(); } catch (err) { await queryRunner.rollbackTransaction(); throw err; } finally { await queryRunner.release(); await connectionDb.close(); } } async calculateDeliveryTaxOrder(dataDeliveryTax: any) { let cityId = await this.customerService.findCity(dataDeliveryTax.ibgeCode); await this.updatePriorityDelivery(dataDeliveryTax.cartId, dataDeliveryTax.priorityDelivery); if (cityId == 0) { cityId = Number.parseInt(dataDeliveryTax.ibgeCode); // throw new HttpException('Cidade não localiza para cálculo da taxa de entrega', HttpStatus.BAD_REQUEST); } const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); try { const sql = 'SELECT ESVCALCULOFRETE.CODTABELAFRETE as "id" ' + ' ,ESVCALCULOFRETE.CODFILIAL as "store" ' + ' ,ESVCALCULOFRETE.CODCIDADE as "cityId" ' + ' ,PCCIDADE.NOMECIDADE as "cityName" ' + ' ,ESVCALCULOFRETE.CODFORNEC as "carrierId" ' + ' ,PCFORNEC.FORNECEDOR as "carrierName" ' + ' ,ESVCALCULOFRETE.VLCOMPRAMIN as "minSale" ' + ' ,ESVCALCULOFRETE.VLFRETE as "deliveryValue" ' + ' ,ESVCALCULOFRETE.PRAZOENTREGA as "deliveryTime" ' + ' FROM ESVCALCULOFRETE, PCFORNEC, PCCIDADE ' + ' WHERE ESVCALCULOFRETE.CODFORNEC = PCFORNEC.CODFORNEC ' + ' AND ESVCALCULOFRETE.CODCIDADE = PCCIDADE.CODCIDADE ' + ' AND ESVCALCULOFRETE.CODCIDADE = :1 ' + ' AND ESVCALCULOFRETE.IDCART = :2 ' + ' ORDER BY VLFRETE'; let deliveryTaxTable = await queryRunner.manager .query(sql, [dataDeliveryTax.cityId, dataDeliveryTax.cartId]); if (deliveryTaxTable == null || deliveryTaxTable.length == 0) { deliveryTaxTable = await queryRunner.manager .query(sql, [cityId, dataDeliveryTax.cartId]); } return deliveryTaxTable; } catch (err) { throw err; } finally { await queryRunner.release(); await connectionDb.close(); } } async getPlacesInterior() { const connectionDb = new Connection(connectionOptions); await connectionDb.connect(); const queryRunner = connectionDb.createQueryRunner(); await queryRunner.connect(); try { const sql = ` SELECT DISTINCT ESTPREVENTREGAPRACA.CODPRACA, PCPRACA.PRACA FROM ESTPREVENTREGAPRACA, PCPRACA WHERE ESTPREVENTREGAPRACA.CODPRACA = PCPRACA.CODPRACA `; const places = await queryRunner.query(sql); return places; } catch (err) { throw err; } finally { await queryRunner.release(); await connectionDb.close(); } } async getDeliveryTime(saleDate: string, invoiceStoreId: string, placeId: string, cartId: string) { const connection = new Connection(connectionOptions); await connection.connect(); const queryRunner = connection.createQueryRunner(); await queryRunner.connect(); 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(TO_DATE('${saleDate}', 'DD-MM-YYYY')) AS "days" FROM DUAL`; 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 timeDaysRetiraPosterior = await queryRunner.query(sqlRetiraPosterior); return { deliveryDays: timeDays[0].days, retiraPosteriorDays: timeDaysRetiraPosterior[0].days }; } catch (err) { console.log(err); throw err; } finally { await queryRunner.release(); await connection.close(); } } async allowShippingDelivery(placeId: string, cartId: string) { const connection = new Connection(connectionOptions); await connection.connect(); const queryRunner = connection.createQueryRunner(); await queryRunner.connect(); try { const sql = `SELECT ESF_PERMITE_ENTREGA_DELIVERY('${cartId}', ${placeId}) AS "allow" FROM DUAL`; const deliveryAllow = await queryRunner.query(sql); return { allowShippingDelivery: deliveryAllow[0].allow }; } catch (err) { console.log(err); throw err; } finally { await queryRunner.release(); await connection.close(); } } }