Compare commits
4 Commits
94fcbe9b39
...
8a0fd7699b
| Author | SHA1 | Date |
|---|---|---|
|
|
8a0fd7699b | |
|
|
7bd0d85386 | |
|
|
0b729ef6d4 | |
|
|
c062b65a35 |
|
|
@ -0,0 +1,5 @@
|
|||
{
|
||||
"recommendations": [
|
||||
"cweijan.dbclient-jdbc"
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -2,17 +2,17 @@ import { TypeOrmModuleOptions } from '@nestjs/typeorm';
|
|||
import { ConnectionOptions } from 'typeorm';
|
||||
|
||||
export const typeOrmConfig: TypeOrmModuleOptions = {
|
||||
type: "oracle",
|
||||
// host: "192.168.100.40",
|
||||
// username: "LIVIA",
|
||||
// password: "LIVIA",
|
||||
host: "10.1.1.241",
|
||||
username: "SEVEN",
|
||||
password: "USR54SEV",
|
||||
// username: "API",
|
||||
// password: "E05H5KIEQV3YKDJR",
|
||||
type: 'oracle',
|
||||
// host: "192.168.100.40",
|
||||
// username: "LIVIA",
|
||||
// password: "LIVIA",
|
||||
host: '10.1.1.241',
|
||||
username: 'SEVEN',
|
||||
password: 'USR54SEV',
|
||||
// username: "API",
|
||||
// password: "E05H5KIEQV3YKDJR",
|
||||
port: 1521,
|
||||
sid: "WINT",
|
||||
serviceName: 'WINT',
|
||||
synchronize: false,
|
||||
logging: false,
|
||||
entities: [__dirname + '/../**/*.entity.{js,ts}'],
|
||||
|
|
@ -20,14 +20,13 @@ export const typeOrmConfig: TypeOrmModuleOptions = {
|
|||
};
|
||||
|
||||
export const connectionOptions: ConnectionOptions = {
|
||||
type: "oracle",
|
||||
host: "10.1.1.241",
|
||||
username: "SEVEN",
|
||||
password: "USR54SEV",
|
||||
type: 'oracle',
|
||||
host: '10.1.1.241',
|
||||
username: 'SEVEN',
|
||||
password: 'USR54SEV',
|
||||
port: 1521,
|
||||
sid: "WINT",
|
||||
serviceName: 'WINT',
|
||||
synchronize: false,
|
||||
logging: false,
|
||||
entities: [__dirname + '/../**/*.entity.{js,ts}'],
|
||||
}
|
||||
|
||||
};
|
||||
|
|
|
|||
|
|
@ -36,7 +36,7 @@ export class Shopping {
|
|||
@Column({ name: 'VLDESCONTO' })
|
||||
vldesconto: number;
|
||||
|
||||
@Column({name: 'VLCUSTOFIN'})
|
||||
@Column({ name: 'VLCUSTOFIN' })
|
||||
vlcustofin: number;
|
||||
|
||||
@Column({ name: 'CODFUNCAUTOR' })
|
||||
|
|
@ -60,4 +60,7 @@ export class Shopping {
|
|||
@Column({ name: 'CODTABELAFRETE' })
|
||||
codtabelafrete: number;
|
||||
|
||||
@Column({ name: 'CODPRACA' })
|
||||
codpraca: number;
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,24 @@
|
|||
export class CartUpdate {
|
||||
constructor(
|
||||
public id: string,
|
||||
public idCustomer: number,
|
||||
public idAddress: number,
|
||||
public saleStore: string,
|
||||
public userId: number,
|
||||
public idSeller: number,
|
||||
public idProfessional: number,
|
||||
public idPaymentPlan: number,
|
||||
public idBilling: string,
|
||||
public shippingValue: number,
|
||||
public scheduleDelivery: boolean,
|
||||
public shippingDate: Date,
|
||||
public shippingPriority: string,
|
||||
public idStorePlace: number,
|
||||
public notation1: string,
|
||||
public notation2: string,
|
||||
public deliveryNote1: string,
|
||||
public deliveryNote2: string,
|
||||
public deliveryNote3: string,
|
||||
public carrierId: number,
|
||||
) { }
|
||||
}
|
||||
|
|
@ -1,109 +1,148 @@
|
|||
import { Body, Controller, Get, HttpException, HttpStatus, Param, Post, Query } from '@nestjs/common';
|
||||
import { CustomerService } from './customer.service';
|
||||
import { ResultModel } from '../../domain/models/result.model';
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { error } from 'console';
|
||||
import { Customer } from 'src/domain/models/customer.model';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { ResultModel } from '../../domain/models/result.model';
|
||||
import { CustomerService } from './customer.service';
|
||||
|
||||
@ApiTags('Customer')
|
||||
@Controller('api/v1/customer')
|
||||
export class CustomerController {
|
||||
export class CustomerController {
|
||||
constructor(private readonly customerService: CustomerService) {}
|
||||
|
||||
constructor(private readonly customerService: CustomerService){}
|
||||
@Get(':name')
|
||||
async getCustomerByName(@Param('name') name: string) {
|
||||
try {
|
||||
const customers = await this.customerService.findCustomerByName(name);
|
||||
return new ResultModel(true, null, customers, null);
|
||||
} catch (err) {
|
||||
throw new HttpException(
|
||||
new ResultModel(
|
||||
false,
|
||||
'Não foi possível consultar o cadastro de clientes.',
|
||||
{},
|
||||
error,
|
||||
),
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Get(':name')
|
||||
async getCustomerByName(@Param('name') name: string){
|
||||
try{
|
||||
const customers = await this.customerService.findCustomerByName(name);
|
||||
return new ResultModel(true, null, customers, null);
|
||||
} catch(err){
|
||||
throw new HttpException(new ResultModel(false, 'Não foi possível consultar o cadastro de clientes.', {}, error),
|
||||
HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
@Get('categories/fechAll')
|
||||
async getCategories() {
|
||||
try {
|
||||
const categories = await this.customerService.getCategory();
|
||||
return categories;
|
||||
} catch (err) {
|
||||
throw new HttpException(
|
||||
new ResultModel(false, err.message, {}, error),
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Get('categories/fechAll')
|
||||
async getCategories(){
|
||||
try{
|
||||
const categories = await this.customerService.getCategory();
|
||||
return categories;
|
||||
} catch(err){
|
||||
throw new HttpException(new ResultModel(false, err.message, {}, error),
|
||||
HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
@Get('subcategories/fechAll')
|
||||
async getSubCategories() {
|
||||
try {
|
||||
const subCategories = await this.customerService.getSubCategory();
|
||||
return subCategories;
|
||||
} catch (err) {
|
||||
throw new HttpException(
|
||||
new ResultModel(false, err.message, {}, error),
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Get('subcategories/fechAll')
|
||||
async getSubCategories(){
|
||||
try{
|
||||
const subCategories = await this.customerService.getSubCategory();
|
||||
return subCategories;
|
||||
} catch(err){
|
||||
throw new HttpException(new ResultModel(false, err.message, {}, error),
|
||||
HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
@Get()
|
||||
async getCustomer(@Query() query) {
|
||||
try {
|
||||
const field = query['field'];
|
||||
const textSearch = query['textsearch'];
|
||||
const customers = await this.customerService.findCustomerByQuery(
|
||||
field,
|
||||
textSearch,
|
||||
);
|
||||
return new ResultModel(true, null, customers, null);
|
||||
} catch (err) {
|
||||
// 'Não foi possível consultar o cadastro de clientes.'
|
||||
throw new HttpException(
|
||||
new ResultModel(false, err.message, {}, error),
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Get()
|
||||
async getCustomer(@Query() query){
|
||||
try{
|
||||
const field = query['field'];
|
||||
const textSearch = query['textsearch'];
|
||||
const customers = await this.customerService.findCustomerByQuery(field, textSearch);
|
||||
return new ResultModel(true, null, customers, null);
|
||||
} catch(err){
|
||||
// 'Não foi possível consultar o cadastro de clientes.'
|
||||
throw new HttpException(new ResultModel(false, err.message, {}, error),
|
||||
HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
@Get(':id')
|
||||
async getCustomerById(@Param('id') id: number) {
|
||||
try {
|
||||
const customers = await this.customerService.findCustomerById(id);
|
||||
return new ResultModel(true, null, customers, null);
|
||||
} catch (err) {
|
||||
throw new HttpException(
|
||||
new ResultModel(
|
||||
false,
|
||||
'Não foi possível consultar o cadastro de clientes.',
|
||||
{},
|
||||
error,
|
||||
),
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
async getCustomerById(@Param('id') id: number){
|
||||
try{
|
||||
const customers = await this.customerService.findCustomerById(id);
|
||||
return new ResultModel(true, null, customers, null);
|
||||
} catch(err){
|
||||
throw new HttpException(new ResultModel(false, 'Não foi possível consultar o cadastro de clientes.', {}, error),
|
||||
HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
@Get('cpf/:cpf')
|
||||
async getCustomerByCpf(@Param('cpf') cpf: string) {
|
||||
try {
|
||||
console.log('pesquisando por cpf');
|
||||
const customer = await this.customerService.findCustomerByCpf(cpf);
|
||||
if (!customer)
|
||||
return new ResultModel(false, 'Cliente não cadastrado', null, null);
|
||||
return new ResultModel(true, null, customer, null);
|
||||
} catch (err) {
|
||||
throw new HttpException(
|
||||
new ResultModel(
|
||||
false,
|
||||
'Não foi possível consultar o cadastro de clientes.',
|
||||
{},
|
||||
error,
|
||||
),
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
|
||||
@Get('cpf/:cpf')
|
||||
async getCustomerByCpf(@Param('cpf') cpf: string){
|
||||
try{
|
||||
console.log("pesquisando por cpf");
|
||||
const customer = await this.customerService.findCustomerByCpf(cpf);
|
||||
if (!customer) return new ResultModel(false, 'Cliente não cadastrado', null, null);
|
||||
return new ResultModel(true, null, customer, null);
|
||||
} catch(err){
|
||||
throw new HttpException(new ResultModel(false, 'Não foi possível consultar o cadastro de clientes.', {}, error),
|
||||
HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
@Get('create/proxnumcli')
|
||||
async IdCustomer(){
|
||||
try{
|
||||
console.log('proxnumcli');
|
||||
const id = await this.customerService.generateIdCustomer();
|
||||
return new ResultModel(true, null, id, null);
|
||||
} catch(err){
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@Get('create/proxnumcli')
|
||||
async IdCustomer() {
|
||||
try {
|
||||
console.log('proxnumcli');
|
||||
const id = await this.customerService.generateIdCustomer();
|
||||
return new ResultModel(true, null, id, null);
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Post('create')
|
||||
async createCustomer(@Body() customer: Customer){
|
||||
try{
|
||||
console.log(customer);
|
||||
const result = await this.customerService.createCustomer(customer);
|
||||
return new ResultModel(true, null, result, null);
|
||||
//return new ResultModel(true, null, id, null);
|
||||
} catch(err){
|
||||
throw new HttpException(new ResultModel(false, 'Erro ao cadastrar cliente.', {}, err),
|
||||
HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
@Post('create')
|
||||
async createCustomer(@Body() customer: Customer) {
|
||||
try {
|
||||
console.log(customer);
|
||||
const result = await this.customerService.createCustomer(customer);
|
||||
return new ResultModel(true, null, result, null);
|
||||
//return new ResultModel(true, null, id, null);
|
||||
} catch (err) {
|
||||
throw new HttpException(
|
||||
new ResultModel(false, 'Erro ao cadastrar cliente.', {}, err),
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
|
@ -1,29 +1,28 @@
|
|||
import { Injectable, HttpException, HttpStatus, Inject, CACHE_MANAGER } from '@nestjs/common';
|
||||
import { HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common';
|
||||
import { Connection } from 'typeorm';
|
||||
import { connectionOptions } from '../../configs/typeorm.config';
|
||||
import { Estavisoestoque } from '../../domain/entity/tables/estavisoestoque.entity';
|
||||
import { Estruptura } from '../../domain/entity/tables/estruptura.entity';
|
||||
import { Pcclient } from '../../domain/entity/tables/pcclient.entity';
|
||||
import { Esvanalisevendarca } from '../../domain/entity/views/esvanalisevendarca.entity';
|
||||
import { Esvdepartamento } from '../../domain/entity/views/esvdepartamento.entity';
|
||||
import { Esvparcelamentovenda } from '../../domain/entity/views/esvparcelamentovenda.entity';
|
||||
import { SalesProduct } from '../../domain/entity/views/esvprodutosvenda.entity';
|
||||
import { Connection, getConnection } from 'typeorm';
|
||||
import { Esvsecao } from '../../domain/entity/views/esvsecao.entity';
|
||||
import { Esvsituacaopedido } from '../../domain/entity/views/esvsituacaopedido.entity';
|
||||
import { Stock } from '../../domain/entity/views/esvestoquevenda.entity';
|
||||
import { FilterProduct } from '../../domain/models/filter-product.model';
|
||||
import { 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
|
||||
) {}
|
||||
constructor(
|
||||
@Inject('REDIS_CLIENT') private readonly redisClient: Redis.Redis,
|
||||
private readonly customerService: CustomerService
|
||||
) { }
|
||||
|
||||
|
||||
async GetProducts2(store: string, pageSize: number, pageNumber: number, filter: FilterProduct = null,) {
|
||||
|
|
@ -86,7 +85,7 @@ export class SalesService {
|
|||
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')
|
||||
|
|
@ -367,92 +366,92 @@ export class SalesService {
|
|||
pageSize: number,
|
||||
pageNumber: number,
|
||||
urlDepartment: string
|
||||
): Promise<any> {
|
||||
): Promise<any> {
|
||||
const cacheKey =
|
||||
'searchByDepartment:' +
|
||||
store +
|
||||
'_' +
|
||||
pageSize +
|
||||
'_' +
|
||||
pageNumber +
|
||||
'_' +
|
||||
urlDepartment;
|
||||
'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);
|
||||
}
|
||||
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);
|
||||
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);
|
||||
acquiredLock = await this.redisClient.set(lockKey, lockValue, 'NX', 'EX', lockTimeout);
|
||||
} catch (err) {
|
||||
console.error('Erro ao adquirir lock no Redis (searchByDepartment):', err?.message || err);
|
||||
console.error('Erro ao adquirir lock no Redis (searchByDepartment):', err?.message || err);
|
||||
}
|
||||
|
||||
|
||||
if (acquiredLock === 'OK') {
|
||||
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);
|
||||
|
||||
const connectionDb = new Connection(connectionOptions);
|
||||
await connectionDb.connect();
|
||||
const queryRunner = connectionDb.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
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<any> {
|
||||
const connectionDb = new Connection(connectionOptions);
|
||||
|
|
@ -620,7 +619,7 @@ export class SalesService {
|
|||
.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\".QUANTIDADE_ESTOQUE_GERAL", "full_stock")
|
||||
.addSelect("\"esvlistaprodutos\".TEM_PRODUTO_SIMILAR", "similar")
|
||||
.addSelect("\"esvlistaprodutos\".TIPO_CAMPANHA", "type_campaing")
|
||||
.where("esvlistaprodutos.CODAUXILIAR = :id", { id: numbers })
|
||||
|
|
@ -671,7 +670,7 @@ export class SalesService {
|
|||
.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\".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 })
|
||||
|
|
@ -719,7 +718,7 @@ export class SalesService {
|
|||
.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\".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 })
|
||||
|
|
@ -790,7 +789,7 @@ export class SalesService {
|
|||
.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\".QUANTIDADE_ESTOQUE_GERAL", "full_stock")
|
||||
.addSelect("\"esvlistaprodutos\".TEM_PRODUTO_SIMILAR", "similar")
|
||||
.addSelect("\"esvlistaprodutos\".TIPO_CAMPANHA", "type_campaing")
|
||||
.where("esvlistaprodutos.idProduct = :id", { id: id })
|
||||
|
|
@ -953,14 +952,17 @@ export class SalesService {
|
|||
,(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
|
||||
ELSE 0 END ) as "allowDelivery"
|
||||
, NVL(PCEST.QTEXPOSICAO,0) as "exhibition"
|
||||
FROM ESVESTOQUEVENDA, PCFILIAL, PCEST
|
||||
WHERE ESVESTOQUEVENDA.CODPROD = ${id}
|
||||
AND ESVESTOQUEVENDA.CODFILIAL = PCFILIAL.CODIGO
|
||||
ORDER BY TO_NUMBER(ESVESTOQUEVENDA.CODFILIAL) `;
|
||||
|
||||
const stock = await queryRunner.query(sql);
|
||||
|
||||
AND ESVESTOQUEVENDA.CODFILIAL = PCEST.CODFILIAL
|
||||
AND ESVESTOQUEVENDA.CODPROD = PCEST.CODPROD
|
||||
ORDER BY TO_NUMBER(ESVESTOQUEVENDA.CODFILIAL)`;
|
||||
|
||||
const stock = await queryRunner.query(sql);
|
||||
|
||||
// return await queryRunner.manager
|
||||
// .getRepository(Stock)
|
||||
// .createQueryBuilder('esvestoquevenda')
|
||||
|
|
@ -1210,71 +1212,71 @@ export class SalesService {
|
|||
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);
|
||||
}
|
||||
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);
|
||||
console.error('Erro ao acessar o Redis (cache):', err);
|
||||
}
|
||||
const lockValue = Date.now() + lockTimeout * 1000 + 1;
|
||||
const lockValue = Date.now() + lockTimeout * 1000 + 1;
|
||||
const acquiredLock = await this.redisClient.set(lockKey, lockValue, 'NX', 'EX', lockTimeout);
|
||||
|
||||
|
||||
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();
|
||||
|
||||
const connectionDb = new Connection(connectionOptions);
|
||||
await connectionDb.connect();
|
||||
const queryRunner = connectionDb.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
|
||||
try {
|
||||
await this.redisClient.set(cacheKey, JSON.stringify(departments), 'EX', 3600);
|
||||
} catch (cacheErr) {
|
||||
console.error('Erro ao armazenar dados no Redis:', cacheErr);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
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> {
|
||||
}
|
||||
private sleep(ms: number): Promise<void> {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
async getCategory() {
|
||||
|
|
@ -1301,15 +1303,15 @@ export class SalesService {
|
|||
|
||||
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" ' +
|
||||
|
|
@ -1352,8 +1354,8 @@ export class SalesService {
|
|||
' ,esvlistaprodutos.TEM_PRODUTO_SIMILAR "similar" ' +
|
||||
' ,esvlistaprodutos.TIPO_CAMPANHA "type_campaing" ' +
|
||||
' FROM esvlistaprodutos ' +
|
||||
' WHERE 1 = 1 ';
|
||||
|
||||
' WHERE 1 = 1 ';
|
||||
|
||||
let where = "";
|
||||
if (filter.text != null) {
|
||||
where += ` AND ( ESF_REMOVE_ACENTUACAO(UPPER(esvlistaprodutos.descricao)) LIKE ` +
|
||||
|
|
@ -1373,7 +1375,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 ` +
|
||||
|
|
@ -1385,15 +1387,15 @@ export class SalesService {
|
|||
` 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;
|
||||
|
|
@ -1406,24 +1408,24 @@ export class SalesService {
|
|||
});
|
||||
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);
|
||||
|
|
@ -1433,7 +1435,7 @@ export class SalesService {
|
|||
await connectionDb.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
async calculateDeliveryTax(cartId: string, ibgeCode: string) {
|
||||
|
|
@ -1468,6 +1470,7 @@ export class SalesService {
|
|||
.query(sql, [cityId, cartId]);
|
||||
return deliveryTaxTable;
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
throw err;
|
||||
} finally {
|
||||
await queryRunner.release();
|
||||
|
|
@ -1488,7 +1491,7 @@ export class SalesService {
|
|||
WHERE ID = '${cartId}'`;
|
||||
|
||||
await queryRunner.manager
|
||||
.query(sql);
|
||||
.query(sql);
|
||||
await queryRunner.commitTransaction();
|
||||
} catch (err) {
|
||||
await queryRunner.rollbackTransaction();
|
||||
|
|
@ -1502,7 +1505,20 @@ export class SalesService {
|
|||
}
|
||||
|
||||
async calculateDeliveryTaxOrder(dataDeliveryTax: any) {
|
||||
let cityId = await this.customerService.findCity(dataDeliveryTax.ibgeCode);
|
||||
console.log("json dataDeliveryTax", dataDeliveryTax);
|
||||
/*const dataDeliveryTax = {
|
||||
cartId: cartId,
|
||||
cityId: cityId,
|
||||
ibgeCode: ibgeCode,
|
||||
priorityDelivery: priorityDelivery,
|
||||
};*/
|
||||
|
||||
let cityId = 0;
|
||||
if (dataDeliveryTax.ibgeCode) {
|
||||
cityId = await this.customerService.findCity(dataDeliveryTax.ibgeCode);
|
||||
} else {
|
||||
cityId = dataDeliveryTax.cityId;
|
||||
}
|
||||
await this.updatePriorityDelivery(dataDeliveryTax.cartId, dataDeliveryTax.priorityDelivery);
|
||||
|
||||
if (cityId == 0) {
|
||||
|
|
@ -1543,26 +1559,26 @@ export class SalesService {
|
|||
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;
|
||||
|
|
@ -1571,7 +1587,7 @@ export class SalesService {
|
|||
await connectionDb.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
async getDeliveryTime(saleDate: string, invoiceStoreId: string, placeId: string, cartId: string) {
|
||||
const connection = new Connection(connectionOptions);
|
||||
|
|
@ -1580,7 +1596,7 @@ export class SalesService {
|
|||
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 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`;
|
||||
|
|
|
|||
|
|
@ -6,117 +6,132 @@ import { OrderDiscount } from 'src/domain/models/order-discount.model';
|
|||
import { OrderTaxDelivery } from 'src/domain/models/order-taxdelivery.model';
|
||||
import { LogOrder } from 'src/domain/models/log-order.model';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { Cart } from 'src/domain/models/cart.model';
|
||||
import { CartUpdate } from 'src/domain/models/cart-update.model';
|
||||
|
||||
@ApiTags('Shopping')
|
||||
@Controller('api/v1/shopping')
|
||||
export class ShoppingController {
|
||||
|
||||
constructor(private shoppingService: ShoppingService){}
|
||||
constructor(private shoppingService: ShoppingService) { }
|
||||
|
||||
@Get('cart/:id')
|
||||
async getCart(@Param('id') id: string){
|
||||
try {
|
||||
async getCart(@Param('id') id: string) {
|
||||
try {
|
||||
const cart = await this.shoppingService.GetItensCart(id);
|
||||
if (cart == null || cart.length == 0)
|
||||
throw new HttpException("Carrinho de compras não encontrado", HttpStatus.NOT_FOUND);
|
||||
return cart;
|
||||
} catch (error) {
|
||||
const status = error.status == 404 ? error.status : HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
throw new HttpException(error.message, status);
|
||||
throw new HttpException(error.message, status);
|
||||
}
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
async getPreVenda(@Param('id') id: string ){
|
||||
try {
|
||||
async getPreVenda(@Param('id') id: string) {
|
||||
try {
|
||||
const cart = await this.shoppingService.getShopping(id);
|
||||
if (cart == null )
|
||||
if (cart == null)
|
||||
throw new HttpException("Carrinho de compras não encontrado", HttpStatus.NOT_FOUND);
|
||||
return cart;
|
||||
} catch (error) {
|
||||
const status = error.status == 404 ? error.status : HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
throw new HttpException(error.message, status);
|
||||
throw new HttpException(error.message, status);
|
||||
}
|
||||
}
|
||||
|
||||
@Get('cart/:idcart/item/:idProduct/tipoentrega/:deliveryType')
|
||||
async getItemCart(@Req() request, @Param('idCart') idCart: string,
|
||||
@Param('idProduct') idProduct: string, @Param('deliveryType') deliveryType: string){
|
||||
async getItemCart(@Req() request, @Param('idCart') idCart: string,
|
||||
@Param('idProduct') idProduct: string, @Param('deliveryType') deliveryType: string) {
|
||||
let store = '99';
|
||||
try {
|
||||
try {
|
||||
if (request.headers['x-store'])
|
||||
store = request.headers['x-store'];
|
||||
const cart = await this.shoppingService.getItemCart(idCart, idProduct, store, deliveryType);
|
||||
if (cart == null )
|
||||
if (cart == null)
|
||||
throw new HttpException("Item não foi encontrado no carrinho de compras.", HttpStatus.NOT_FOUND);
|
||||
return cart;
|
||||
} catch (error) {
|
||||
const status = error.status == 404 ? error.status : HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
throw new HttpException(error.message, status);
|
||||
throw new HttpException(error.message, status);
|
||||
}
|
||||
}
|
||||
|
||||
@Get('cart/lot/:productId/:customerId')
|
||||
async getLotProduct( @Req() request, @Param('productId') productId: number,
|
||||
@Param('customerId') customerId: number ) {
|
||||
async getLotProduct(@Req() request, @Param('productId') productId: number,
|
||||
@Param('customerId') customerId: number) {
|
||||
let store = '99';
|
||||
try {
|
||||
try {
|
||||
if (request.headers['x-store'])
|
||||
store = request.headers['x-store'];
|
||||
const lotsProduct = await this.shoppingService.getLotProduct(productId, customerId);
|
||||
return lotsProduct;
|
||||
} catch (error) {
|
||||
const status = error.status == 404 ? error.status : HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
throw new HttpException(error.message, status);
|
||||
throw new HttpException(error.message, status);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Post('item')
|
||||
async createItemShopping(@Body() item: ShoppingItem){
|
||||
async createItemShopping(@Body() item: ShoppingItem) {
|
||||
console.log('createItemShopping')
|
||||
try {
|
||||
try {
|
||||
return await this.shoppingService.createItemCart(item);
|
||||
} catch (error) {
|
||||
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
|
||||
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
@Put('cart')
|
||||
async updateCart(@Body() cart: CartUpdate) {
|
||||
try {
|
||||
if (cart.id == null) {
|
||||
throw new HttpException('Cart sem Id informado, faça a inclusão do item no carrinho.', HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
const updateCart = await this.shoppingService.updateShopping(cart);
|
||||
return updateCart;
|
||||
} catch (error) {
|
||||
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
@Post('log')
|
||||
async logOrderShopping(@Body() logOrder: LogOrder){
|
||||
try {
|
||||
async logOrderShopping(@Body() logOrder: LogOrder) {
|
||||
try {
|
||||
console.log('logOrderShopping')
|
||||
return await this.shoppingService.createLogShopping(logOrder);
|
||||
} catch (error) {
|
||||
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
|
||||
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
@Put('item')
|
||||
async updateQuantityItem(@Body() item: ShoppingItem){
|
||||
console.log(item);
|
||||
try {
|
||||
if (item.id == null){
|
||||
async updateQuantityItem(@Body() item: ShoppingItem) {
|
||||
console.log(item);
|
||||
try {
|
||||
if (item.id == null) {
|
||||
throw new HttpException('Item sem Id informado, faça a inclusão do item no carrinho.', HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
const itemCreate = await this.shoppingService.updateItem(item);
|
||||
return itemCreate;
|
||||
} catch (error) {
|
||||
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
|
||||
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
@Put('item/discount')
|
||||
async updatePriceItem(@Body() item: ShoppingItem){
|
||||
console.log(item);
|
||||
try {
|
||||
if (item.id == null){
|
||||
async updatePriceItem(@Body() item: ShoppingItem) {
|
||||
console.log(item);
|
||||
try {
|
||||
if (item.id == null) {
|
||||
throw new HttpException('Item sem Id informado, faça a inclusão do item no carrinho.', HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
const itemCreate = await this.shoppingService.updatePrice(item);
|
||||
return itemCreate;
|
||||
} catch (error) {
|
||||
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
|
||||
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -126,7 +141,7 @@ export class ShoppingController {
|
|||
const itensOrder = await this.shoppingService.applyDiscountOrder(order);
|
||||
return itensOrder;
|
||||
} catch (error) {
|
||||
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
|
||||
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -137,17 +152,17 @@ export class ShoppingController {
|
|||
return orderTax;
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
|
||||
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
@Delete('item/delete/:id')
|
||||
async deleteItem(@Param('id') id: string){
|
||||
try {
|
||||
async deleteItem(@Param('id') id: string) {
|
||||
try {
|
||||
await this.shoppingService.deleteItem(id);
|
||||
return new ResultModel(true, 'Item excluído com sucesso!', id, null,);
|
||||
} catch (error) {
|
||||
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
|
||||
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -165,4 +180,4 @@ export class ShoppingController {
|
|||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,8 @@ import { Shopping } from 'src/domain/entity/tables/estprevendac.entity';
|
|||
import { OrderTaxDelivery } from 'src/domain/models/order-taxdelivery.model';
|
||||
import { connectionOptions } from 'src/configs/typeorm.config';
|
||||
import { LogOrder } from 'src/domain/models/log-order.model';
|
||||
import { Cart } from 'src/domain/models/cart.model';
|
||||
import { CartUpdate } from 'src/domain/models/cart-update.model';
|
||||
|
||||
@Injectable()
|
||||
export class ShoppingService {
|
||||
|
|
@ -165,11 +167,11 @@ export class ShoppingService {
|
|||
const dataStockItem = await queryRunner.query(`SELECT E.estoque_disp_loja as "quantityStock"
|
||||
FROM ESVLISTAPRODUTOS E WHERE E.CODPROD = ${itemShopping.idProduct}
|
||||
AND E.CODFILIAL = '${itemShopping.stockStore}'`);
|
||||
|
||||
|
||||
let quantityStock = 0;
|
||||
if ( dataStockItem.length > 0 ) {
|
||||
if (dataStockItem.length > 0) {
|
||||
quantityStock = dataStockItem[0].quantityStock;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const sqlInsertitem = 'INSERT INTO ESTPREVENDAI ( ID, IDCART, NUMSEQ, CODPROD, QT, PVENDA, DTINCLUSAO, NOMEECOMMERCE, URLIMAGEM, TIPOPRODUTO, CODFILIALRETIRA, TIPOENTREGA, ' +
|
||||
|
|
@ -299,6 +301,58 @@ export class ShoppingService {
|
|||
|
||||
}
|
||||
|
||||
async updateShopping(cart: CartUpdate) {
|
||||
const connectionDb = new Connection(connectionOptions);
|
||||
await connectionDb.connect();
|
||||
const queryRunner = connectionDb.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
|
||||
try {
|
||||
const sqlUpdate = `UPDATE ESTPREVENDAC SET
|
||||
CODFILIAL = :1,
|
||||
CODUSUR = :2,
|
||||
CODCLI = :3,
|
||||
CODENDENTCLI = :4,
|
||||
VLPEDIDO = :5,
|
||||
VLDESCONTO = :6,
|
||||
VLTAXAENTREGA = :7,
|
||||
TIPOPRIORIDADEENTREGA = :8
|
||||
WHERE ID = :9
|
||||
`;
|
||||
|
||||
const total = await queryRunner.query('SELECT SUM(ESTPREVENDAI.PTABELA * ESTPREVENDAI.QT) as "vltabela" ' +
|
||||
' ,SUM(ESTPREVENDAI.PVENDA * ESTPREVENDAI.QT) as "vlatend" ' +
|
||||
' ,SUM(ESTPREVENDAI.VLDESCONTO * ESTPREVENDAI.QT) as "vldesconto" ' +
|
||||
' ,SUM(PCPRODUT.PESOBRUTO * ESTPREVENDAI.QT) as "totpeso" ' +
|
||||
' FROM ESTPREVENDAI, PCPRODUT ' +
|
||||
' WHERE ESTPREVENDAI.CODPROD = PCPRODUT.CODPROD ' +
|
||||
' AND ESTPREVENDAI.IDCART = :1', [cart.id]);
|
||||
|
||||
await queryRunner.query(sqlUpdate, [
|
||||
cart.saleStore,
|
||||
cart.userId,
|
||||
cart.idCustomer,
|
||||
cart.idAddress,
|
||||
total[0].vlatend,
|
||||
total[0].vldesconto,
|
||||
cart.shippingValue,
|
||||
cart.shippingPriority,
|
||||
cart.id
|
||||
]);
|
||||
|
||||
await queryRunner.commitTransaction();
|
||||
|
||||
return cart;
|
||||
} catch (error) {
|
||||
await queryRunner.rollbackTransaction();
|
||||
throw error;
|
||||
} finally {
|
||||
await queryRunner.release();
|
||||
await connectionDb.close();
|
||||
}
|
||||
}
|
||||
|
||||
async updateTotalShopping(idCart: string) {
|
||||
const connection = new Connection(connectionOptions);
|
||||
await connection.connect();
|
||||
|
|
|
|||
|
|
@ -13,7 +13,9 @@
|
|||
"paths": {
|
||||
"src/*": ["./src/*"]
|
||||
},
|
||||
"incremental": true
|
||||
"incremental": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": false
|
||||
},
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue