setup da configuracao do redis

This commit is contained in:
JurTI-BR
2025-03-13 22:27:19 -03:00
parent 80117a0df0
commit 0c517800e0
13 changed files with 844 additions and 432 deletions

View File

@@ -1,11 +1,11 @@
import { HttpStatus } from '@nestjs/common';
import { Injectable, HttpException } from '@nestjs/common';
import { connectionOptions } from 'src/configs/typeorm.config';
import { Customer } from 'src/domain/models/customer.model';
import { connectionOptions } from '../../configs/typeorm.config';
import { Customer } from '../../domain/models/customer.model';
import { Connection } from 'typeorm';
import { Pcclient } from '../../domain/entity/tables/pcclient.entity';
import { Estcategoriacliente } from '../../domain/entity/tables/estcategoriacliente.entity';
import { Estsubcategoriacliente } from 'src/domain/entity/tables/estsubcategoriacliente.entity';
import { Estsubcategoriacliente } from '../../domain/entity/tables/estsubcategoriacliente.entity';
@Injectable()
export class CustomerService {

View File

@@ -0,0 +1,49 @@
import { Test, TestingModule } from '@nestjs/testing';
import { SalesController } from './sales.controller';
import { SalesService } from './sales.service';
import { HttpException, HttpStatus } from '@nestjs/common';
describe('SalesController', () => {
let salesController: SalesController;
let salesService: SalesService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [SalesController],
providers: [
{
provide: SalesService,
useValue: {
getPlacesInterior: jest.fn(),
},
},
],
}).compile();
salesController = module.get<SalesController>(SalesController);
salesService = module.get<SalesService>(SalesService);
});
describe('getPlacesInterior', () => {
it('deve retornar a lista de cidades do interior', async () => {
const mockData = [{ name: 'Cidade1' }, { name: 'Cidade2' }];
jest.spyOn(salesService, 'getPlacesInterior').mockResolvedValue(mockData);
const result = await salesController.getPlacesInterior();
expect(result).toEqual(mockData);
});
it('deve lançar um HttpException em caso de erro', async () => {
jest
.spyOn(salesService, 'getPlacesInterior')
.mockRejectedValue(new Error('Erro ao buscar cidades'));
await expect(salesController.getPlacesInterior()).rejects.toThrow(
new HttpException('Erro ao buscar cidades', HttpStatus.BAD_REQUEST),
);
});
});
});

View File

@@ -1,37 +1,48 @@
import { Body, Controller, Get, HttpException, HttpStatus, Param, Post, Query, Req } from '@nestjs/common';
import { FilterProduct } from 'src/domain/models/filter-product.model';
import { Notify } from 'src/domain/models/notify.model';
import { Rupture } from 'src/domain/models/rupture.model';
import { Body, Controller, Get, HttpException, HttpStatus, Param, Post, Query, Req, Headers } from '@nestjs/common';
import { FilterProduct } from '../../domain/models/filter-product.model';
import { Notify } from '../../domain/models/notify.model';
import { Rupture } from '../../domain/models/rupture.model';
import { SalesService } from './sales.service';
import { ApiTags } from '@nestjs/swagger';
import { ApiTags, ApiHeader, ApiOperation, ApiParam, ApiQuery, ApiResponse } from '@nestjs/swagger';
interface PaginationParams {
pageNumber: number;
sizeCount: number;
store: string;
}
@ApiTags('Sales')
@Controller('api/v1/sales')
@ApiHeader({ name: 'x-page', description: 'Page number for pagination', required: false })
@ApiHeader({ name: 'x-size-count', description: 'Number of items per page', required: false })
@ApiHeader({ name: 'x-store', description: 'Store identifier', required: false })
export class SalesController {
constructor(private salesService: SalesService) { }
constructor(private readonly salesService: SalesService) { }
private extractPaginationParams(headers): PaginationParams {
return {
pageNumber: headers['x-page'] ? parseInt(headers['x-page'], 10) : 1,
sizeCount: headers['x-size-count'] ? parseInt(headers['x-size-count'], 10) : 500,
store: headers['x-store'] || '99'
};
}
@Get('products')
async get(@Req() request: any) {
let pageNumber = 1;
let sizeCount = 500;
let store = '99';
console.log(request.headers);
console.log(request.query);
@ApiOperation({ summary: 'Obter produtos com filtro' })
@ApiResponse({ status: 200, description: 'Retorna lista de produtos' })
@ApiResponse({ status: 400, description: 'Erro ao obter produtos' })
async getProducts(@Req() request: any) {
try {
if (request.headers['x-page'])
pageNumber = request.headers['x-page'];
if (request.headers['x-size-count'])
sizeCount = request.headers['x-size-count'];
if (request.headers['x-store'])
store = request.headers['x-store'];
const { pageNumber, sizeCount, store } = this.extractPaginationParams(request.headers);
return await this.salesService.GetProducts2(store, sizeCount, pageNumber, request.query);
} catch (e) {
throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
}
}
@Get('departments')
@ApiOperation({ summary: 'Get all departments' })
@ApiResponse({ status: 200, description: 'Returns department list' })
async getDepartments() {
try {
return await this.salesService.getDepartments();
@@ -41,6 +52,8 @@ export class SalesController {
}
@Get('category')
@ApiOperation({ summary: 'Get all categories' })
@ApiResponse({ status: 200, description: 'Returns category list' })
async getCategory() {
try {
return await this.salesService.getCategory();
@@ -49,8 +62,9 @@ export class SalesController {
}
}
@Get('placesinterior')
@ApiOperation({ summary: 'Lista de cidades do interior' })
@ApiResponse({ status: 200, description: 'Retorna lista de cidades do interior' })
async getPlacesInterior() {
try {
return await this.salesService.getPlacesInterior();
@@ -60,18 +74,12 @@ export class SalesController {
}
@Get('products/:search')
async searchProducts(@Param('search') search: string, @Req() request: any) {
console.log("pesquisando produtos...");
let pageNumber = 1;
let sizeCount = 500;
let store = '99';
@ApiOperation({ summary: 'Search products by term' })
@ApiParam({ name: 'search', description: 'Search term' })
@ApiResponse({ status: 200, description: 'Returns matching products' })
async searchProducts(@Param('search') search: string, @Headers() headers) {
try {
if (request.headers['x-page'])
pageNumber = request.headers['x-page'];
if (request.headers['x-size-count'])
sizeCount = request.headers['x-size-count'];
if (request.headers['x-store'])
store = request.headers['x-store'];
const { pageNumber, sizeCount, store } = this.extractPaginationParams(headers);
return await this.salesService.searchProduct(store, search, sizeCount, pageNumber);
} catch (e) {
throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
@@ -79,18 +87,11 @@ export class SalesController {
}
@Get('product/category/:url')
async searchByDepartment(@Param('url') urlDepartment: string, @Req() request: any) {
console.log("pesquisando produtos...");
let pageNumber = 1;
let sizeCount = 500;
let store = '99';
@ApiOperation({ summary: 'Search products by department' })
@ApiParam({ name: 'url', description: 'Department URL' })
async searchByDepartment(@Param('url') urlDepartment: string, @Headers() headers) {
try {
if (request.headers['x-page'])
pageNumber = request.headers['x-page'];
if (request.headers['x-size-count'])
sizeCount = request.headers['x-size-count'];
if (request.headers['x-store'])
store = request.headers['x-store'];
const { pageNumber, sizeCount, store } = this.extractPaginationParams(headers);
return await this.salesService.searchByDepartment(store, sizeCount, pageNumber, urlDepartment);
} catch (e) {
throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
@@ -98,17 +99,16 @@ export class SalesController {
}
@Get('product/category/:urlDepartament/:urlSection')
async searchBySection(@Param('urlDepartament') urlDepartment: string, @Param('urlSection') urlSection: string, @Req() request: any) {
let pageNumber = 1;
let sizeCount = 500;
let store = '99';
@ApiOperation({ summary: 'Search products by department and section' })
@ApiParam({ name: 'urlDepartament', description: 'Department URL' })
@ApiParam({ name: 'urlSection', description: 'Section URL' })
async searchBySection(
@Param('urlDepartament') urlDepartment: string,
@Param('urlSection') urlSection: string,
@Headers() headers
) {
try {
if (request.headers['x-page'])
pageNumber = request.headers['x-page'];
if (request.headers['x-size-count'])
sizeCount = request.headers['x-size-count'];
if (request.headers['x-store'])
store = request.headers['x-store'];
const { pageNumber, sizeCount, store } = this.extractPaginationParams(headers);
return await this.salesService.searchBySection(store, sizeCount, pageNumber, urlDepartment, urlSection);
} catch (e) {
throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
@@ -116,39 +116,36 @@ export class SalesController {
}
@Get('product/category/:urlDepartament/:urlSection/:urlCategory')
async searchByCategory(@Param('urlDepartament') urlDepartment: string, @Param('urlSection') urlSection: string,
@Param('urlCategory') urlCategory: string, @Req() request: any) {
let pageNumber = 1;
let sizeCount = 500;
let store = '99';
@ApiOperation({ summary: 'Search products by department, section and category' })
@ApiParam({ name: 'urlDepartament', description: 'Department URL' })
@ApiParam({ name: 'urlSection', description: 'Section URL' })
@ApiParam({ name: 'urlCategory', description: 'Category URL' })
async searchByCategory(
@Param('urlDepartament') urlDepartment: string,
@Param('urlSection') urlSection: string,
@Param('urlCategory') urlCategory: string,
@Headers() headers
) {
try {
if (request.headers['x-page'])
pageNumber = request.headers['x-page'];
if (request.headers['x-size-count'])
sizeCount = request.headers['x-size-count'];
if (request.headers['x-store'])
store = request.headers['x-store'];
return await this.salesService.searchByCategory(store, sizeCount, pageNumber, urlDepartment, urlSection, urlCategory);
const { pageNumber, sizeCount, store } = this.extractPaginationParams(headers);
return await this.salesService.searchByCategory(
store,
sizeCount,
pageNumber,
urlDepartment,
urlSection,
urlCategory
);
} catch (e) {
throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
}
}
@Post('products')
async getProductsByFilter(@Req() request: any, @Body() filter: FilterProduct) {
let pageNumber = 1;
let sizeCount = 500;
console.log(filter);
let store = '99';
@ApiOperation({ summary: 'Get products by filter criteria' })
async getProductsByFilter(@Headers() headers, @Body() filter: FilterProduct) {
try {
if (request.headers['x-page'])
pageNumber = request.headers['x-page'];
if (request.headers['x-size-count'])
sizeCount = request.headers['x-size-count'];
if (request.headers['x-store'])
store = request.headers['x-store'];
// return await this.salesService.GetProducts2(store, sizeCount, pageNumber, filter);
const { pageNumber, sizeCount, store } = this.extractPaginationParams(headers);
return await this.salesService.searchProduct2(store, sizeCount, pageNumber, filter);
} catch (e) {
throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
@@ -156,11 +153,11 @@ export class SalesController {
}
@Get('product/:id')
async getProduct(@Req() request: any, @Param('id') id: number) {
let store = '99';
@ApiOperation({ summary: 'Get product by ID' })
@ApiParam({ name: 'id', description: 'Product ID' })
async getProduct(@Headers() headers, @Param('id') id: number) {
try {
if (request.headers['x-store'])
store = request.headers['x-store'];
const { store } = this.extractPaginationParams(headers);
return await this.salesService.GetProduct(store, id);
} catch (e) {
throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
@@ -168,11 +165,11 @@ export class SalesController {
}
@Get('product/bytogether/:id')
async GetProductsBuyTogether(@Req() request: any, @Param('id') id: number) {
let store = '99';
@ApiOperation({ summary: 'Get products frequently bought together' })
@ApiParam({ name: 'id', description: 'Product ID' })
async getProductsBuyTogether(@Headers() headers, @Param('id') id: number) {
try {
if (request.headers['x-store'])
store = request.headers['x-store'];
const { store } = this.extractPaginationParams(headers);
return await this.salesService.GetProductsBuyTogether(store, id);
} catch (e) {
throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
@@ -180,6 +177,9 @@ export class SalesController {
}
@Get('stock/:storeid/:id')
@ApiOperation({ summary: 'Get product stock information' })
@ApiParam({ name: 'storeid', description: 'Store ID' })
@ApiParam({ name: 'id', description: 'Product ID' })
async getStock(@Param('storeid') storeId: string, @Param('id') id: number) {
try {
return await this.salesService.GetStocks(storeId, id);
@@ -189,23 +189,26 @@ export class SalesController {
}
@Get('installment/:id')
async getSaleIntallment(@Req() request: any, @Query() query, @Param('id') id: number) {
let store = '99';
let quantity = 1;
@ApiOperation({ summary: 'Get installment options for a product' })
@ApiParam({ name: 'id', description: 'Product ID' })
@ApiQuery({ name: 'quantity', description: 'Product quantity', required: false })
async getSaleInstallment(
@Headers() headers,
@Query('quantity') quantityParam: string,
@Param('id') id: number
) {
try {
if (request.headers['x-store'])
store = request.headers['x-store'];
if (query['quantity']) {
quantity = Number.parseFloat(query['quantity']);
}
const { store } = this.extractPaginationParams(headers);
const quantity = quantityParam ? parseFloat(quantityParam) : 1;
return await this.salesService.GetSaleInstallment(store, id, quantity);
} catch (e) {
throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
}
}
@Get('delivery/:cpf')
@ApiOperation({ summary: 'Get delivery options by CPF' })
@ApiParam({ name: 'cpf', description: 'Customer CPF' })
async getDelivery(@Param('cpf') cpf: string) {
try {
return await this.salesService.GetDelivery(cpf);
@@ -215,14 +218,26 @@ export class SalesController {
}
@Get('deliveryDays/:createDate/:invoiceStoreId/:placeId/:cartId')
async deliveryDays(@Param('createDate') createDate: string,
@Param('invoiceStoreId') invoiceStoreId: string,
@Param('placeId') placeId: string,
@Param('cartId') cartId: string) {
@ApiOperation({ summary: 'Get delivery days estimation' })
@ApiParam({ name: 'createDate', description: 'Order creation date' })
@ApiParam({ name: 'invoiceStoreId', description: 'Invoice store ID' })
@ApiParam({ name: 'placeId', description: 'Place ID' })
@ApiParam({ name: 'cartId', description: 'Cart ID' })
async deliveryDays(
@Param('createDate') createDate: string,
@Param('invoiceStoreId') invoiceStoreId: string,
@Param('placeId') placeId: string,
@Param('cartId') cartId: string
) {
try {
return this.salesService.getDeliveryTime(createDate, invoiceStoreId, placeId, cartId);
} catch (e) {
throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
}
}
@Post('notify')
@ApiOperation({ summary: 'Create product notification' })
async createNotification(@Body() data: Notify) {
try {
return await this.salesService.createNotification(data);
@@ -232,6 +247,7 @@ export class SalesController {
}
@Post('rupture')
@ApiOperation({ summary: 'Create rupture notification' })
async createRupture(@Body() data: Rupture) {
try {
return await this.salesService.createRuptura(data);
@@ -241,8 +257,8 @@ export class SalesController {
}
@Post('calculatedeliverytaxorder')
async calcDeliveryTaxOrder(
@Body() dataDeliveryOrder: any) {
@ApiOperation({ summary: 'Calculate delivery tax for an order' })
async calcDeliveryTaxOrder(@Body() dataDeliveryOrder: any) {
try {
return await this.salesService.calculateDeliveryTaxOrder(dataDeliveryOrder);
} catch (e) {
@@ -251,6 +267,8 @@ export class SalesController {
}
@Get('analisevenda/:id')
@ApiOperation({ summary: 'Get sale analysis' })
@ApiParam({ name: 'id', description: 'Sale ID' })
async analiseVendaRca(@Param('id') id: number) {
try {
return await this.salesService.GetAnaliseVenda(id);
@@ -260,6 +278,8 @@ export class SalesController {
}
@Get('historicovenda/:id')
@ApiOperation({ summary: 'Get sales history' })
@ApiParam({ name: 'id', description: 'Customer ID' })
async historicoVendaRca(@Param('id') id: number) {
try {
return await this.salesService.GetHistoricoVendas(id);
@@ -269,15 +289,17 @@ export class SalesController {
}
@Get('calculatedeliverytax/:cartid/:ibgeCode')
@ApiOperation({ summary: 'Calculate delivery tax by cart and location' })
@ApiParam({ name: 'cartid', description: 'Cart ID' })
@ApiParam({ name: 'ibgeCode', description: 'IBGE location code' })
async calculatedeliverytax(
@Param('cartid') cartId: string,
@Param('ibgeCode') ibgeCode: string) {
@Param('cartid') cartId: string,
@Param('ibgeCode') ibgeCode: string
) {
try {
return await this.salesService.calculateDeliveryTax(cartId, ibgeCode);
} catch (e) {
throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
}
}
}
}

View File

@@ -2,9 +2,10 @@ import { Module } from '@nestjs/common';
import { SalesController } from './sales.controller';
import { SalesService } from './sales.service';
import { CustomerService } from '../customer/customer.service';
import { RedisModule } from '../../redis/redis.module';
@Module({
imports: [],
imports: [RedisModule],
controllers: [SalesController],
providers: [SalesService, CustomerService],
})

View File

@@ -1,287 +1,29 @@
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { Pcclient } from 'src/domain/entity/tables/pcclient.entity';
import { SalesProduct } from 'src/domain/entity/views/esvprodutosvenda.entity';
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 'src/domain/models/filter-product.model';
import { Notify } from 'src/domain/models/notify.model';
import { Estavisoestoque } from 'src/domain/entity/tables/estavisoestoque.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 'src/domain/models/rupture.model';
import { Estruptura } from 'src/domain/entity/tables/estruptura.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 'src/domain/entity/views/esvdepartamento.entity';
import { Esvanalisevendarca } from 'src/domain/entity/views/esvanalisevendarca.entity';
import { connectionOptions } from 'src/configs/typeorm.config';
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(
private readonly customerService: CustomerService
) { }
async GetProducts(store: string, pageSize: number, pageNumber: number, filter: FilterProduct = null): Promise<any> {
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
if (pageSize == 0)
pageSize = 500;
if (pageNumber == 0)
pageNumber = 1;
const offSet = (pageNumber - 1) * pageSize;
if (filter && filter.text != null) {
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\".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\".BASETINTOMETRICO", "base")
.addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock")
.orderBy("\"esvlistaprodutos\".DESCRICAO")
.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) ? 'S' : 'N' })
.andWhere("(\"esvlistaprodutos\".produto_oportunidade = :oportunity OR :oportunity = 'N')",
{ oportunity: (filter.oportunity) ? 'S' : '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();
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\".BASETINTOMETRICO", "base")
.addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock")
.orderBy("\"esvlistaprodutos\".DESCRICAO")
.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) ? 'S' : 'N' })
.andWhere("(\"esvlistaprodutos\".produto_oportunidade = :oportunity OR :oportunity = 'N')",
{ oportunity: (filter.oportunity) ? 'S' : '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\".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\".BASETINTOMETRICO", "base")
.addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock")
.orderBy("\"esvlistaprodutos\".DESCRICAO")
.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) ? 'S' : 'N' })
.andWhere("(\"esvlistaprodutos\".produto_oportunidade = :oportunity OR :oportunity = 'N')",
{ oportunity: (filter.oportunity) ? 'S' : '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 && filter.markdown)
console.log('Produto em redução de preço - 1');
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\".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\".BASETINTOMETRICO", "base")
.addSelect("\"esvlistaprodutos\".QUANTIDADE_ESTOQUE_GERAL", "full_stock")
.where("(\"esvlistaprodutos\".codfilial = :codfilial OR :codfilial = '99')", { codfilial: store })
.andWhere("(\"esvlistaprodutos\".produto_com_reducao_preco = :produtoComReducaoPreco OR :produtoComReducaoPreco = 'N')",
{ produtoComReducaoPreco: (filter && filter.markdown) ? 'S' : 'N' })
.andWhere("(\"esvlistaprodutos\".produto_em_campanha = :campaign OR :campaign = 'N')",
{ campaign: (filter && filter.campaign) ? 'S' : 'N' })
.andWhere("(\"esvlistaprodutos\".produto_oportunidade = :oportunity OR :oportunity = 'N')",
{ oportunity: (filter && filter.oportunity) ? 'S' : 'N' })
.andWhere("(\"esvlistaprodutos\".produto_em_promocao = :produtoEmPromocao OR :produtoEmPromocao = 'N')",
{ produtoEmPromocao: (filter && filter.promotion) ? 'S' : 'N' })
.orderBy("\"esvlistaprodutos\".DESCRICAO")
.limit(pageSize)
.offset(offSet)
.getRawMany();
products = this.createListImages(products);
console.log(products.length + ' produtos');
return products;
}
} catch (error) {
console.log(error);
throw error;
} finally {
await queryRunner.release();
}
}
constructor(
@Inject('REDIS_CLIENT') private readonly redisClient: Redis.Redis,
private readonly customerService: CustomerService
) {}
async GetProducts2(store: string, pageSize: number, pageNumber: number, filter: FilterProduct = null,) {
@@ -1317,29 +1059,78 @@ export class SalesService {
}
async getDepartments() {
const connectionDb = new Connection(connectionOptions);
await connectionDb.connect();
const queryRunner = connectionDb.createQueryRunner();
await queryRunner.connect();
async getDepartments(): Promise<Esvdepartamento[]> {
const cacheKey = 'departments';
const lockKey = 'departments_lock';
const lockTimeout = 30; // lock expira em 30 segundos
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();
return departments;
// Tenta recuperar os departamentos do cache
const cachedDepartments = await this.redisClient.get(cacheKey);
if (cachedDepartments) {
console.log('Buscando departamentos no Redis');
return JSON.parse(cachedDepartments);
}
} catch (err) {
throw err;
} finally {
console.error('Erro ao acessar o Redis (cache):', err);
// Se o Redis falhar, a execução continua para consultar o banco
}
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<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
async getCategory() {
const connectionDb = new Connection(connectionOptions);
@@ -1365,6 +1156,18 @@ export class SalesService {
async searchProduct2(store: string, pageSize: number, pageNumber: number, filter: FilterProduct) {
console.log('searchProduct2');
// Cria uma chave única para o cache utilizando os parâmetros da função
const cacheKey = `searchProduct2:${store}:${pageSize}:${pageNumber}:${JSON.stringify(filter)}`;
// Tenta recuperar os produtos do cache
const cachedProducts = await this.redisClient.get(cacheKey);
if (cachedProducts) {
console.log('Retornando produtos do cache');
return JSON.parse(cachedProducts);
}
// Monta a consulta SQL
const sql = 'SELECT esvlistaprodutos.CODPROD "idProduct" ' +
` ,esvlistaprodutos.SEQ "seq" ` +
' ,esvlistaprodutos.DESCRICAO "smallDescription" ' +
@@ -1406,6 +1209,8 @@ export class SalesService {
' ,esvlistaprodutos.QUANTIDADE_ESTOQUE_GERAL "full_stock" ' +
' FROM esvlistaprodutos ' +
' WHERE 1 = 1';
// Concatena as condições WHERE baseadas nos filtros
let where = "";
if (filter.text != null) {
where += ` AND ( ESF_REMOVE_ACENTUACAO(UPPER(esvlistaprodutos.descricao)) LIKE ` +
@@ -1425,7 +1230,7 @@ export class SalesService {
where += ` AND (esvlistaprodutos.produto_em_campanha = '${(filter.offers ? 'D' : 'N')}' OR '${(filter.offers ? 'S' : 'N')}' = 'N') `;
where += ` AND (esvlistaprodutos.produto_em_campanha = '${(filter.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 ` +
@@ -1437,43 +1242,45 @@ export class SalesService {
` AND P.ESTOQUE_DISP_LOJA > 0 ) `;
}
}
if (filter.percentOffMin > 0) {
where += ` AND esvlistaprodutos.PERCENTUALDESCONTO >= ${filter.percentOffMin}`
where += ` AND esvlistaprodutos.PERCENTUALDESCONTO >= ${filter.percentOffMin}`;
}
if (filter.percentOffMax > 0) {
where += ` AND esvlistaprodutos.PERCENTUALDESCONTO <= ${filter.percentOffMax}`
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 + '\'';
} 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);
@@ -1482,8 +1289,8 @@ export class SalesService {
await queryRunner.release();
await connectionDb.close();
}
}
async calculateDeliveryTax(cartId: string, ibgeCode: string) {
@@ -1596,17 +1403,23 @@ export class SalesService {
}
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);
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;
@@ -1614,9 +1427,8 @@ export class SalesService {
await queryRunner.release();
await connectionDb.close();
}
}
async getDeliveryTime(saleDate: string, invoiceStoreId: string, placeId: string, cartId: string) {
const connection = new Connection(connectionOptions);