729 lines
31 KiB
TypeScript
729 lines
31 KiB
TypeScript
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
|
|
import { ShoppingItens } from 'src/domain/entity/tables/estprevendai.entity';
|
|
import { OrderDiscount } from 'src/domain/models/order-discount.model';
|
|
import { ShoppingItem } from 'src/domain/models/shopping-item.model';
|
|
import { Connection, QueryRunner } from 'typeorm';
|
|
import { UserService } from 'src/Auth/services/user.service';
|
|
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';
|
|
|
|
@Injectable()
|
|
export class ShoppingService {
|
|
|
|
|
|
constructor(private userService: UserService
|
|
) { }
|
|
|
|
async GetItensCart(idcart: string) {
|
|
const connection = new Connection(connectionOptions);
|
|
await connection.connect();
|
|
const queryRunner = connection.createQueryRunner();
|
|
await queryRunner.connect();
|
|
try {
|
|
const product = await queryRunner.manager
|
|
.getRepository(ShoppingItens)
|
|
.createQueryBuilder('estprevendai')
|
|
.where("\"estprevendai\".idcart = :idcart", { idcart: idcart })
|
|
.andWhere("\"estprevendai\".dtcancel is null")
|
|
.orderBy("\"estprevendai\".dtinclusao")
|
|
.getMany();
|
|
return product;
|
|
} catch (error) {
|
|
console.log(error);
|
|
throw error;
|
|
} finally {
|
|
await queryRunner.release();
|
|
await connection.close();
|
|
}
|
|
}
|
|
|
|
/* async createSale(cart: Cart){
|
|
try
|
|
{
|
|
let sale = new Sale();
|
|
sale.id = cart.idShopping;
|
|
sale.codcli = cart.idCustomer;
|
|
sale.codusur = cart.idSeller;
|
|
sale.codcob = cart.billingCode;
|
|
sale.codendcli = 0;
|
|
sale.codplpag = cart.idPayment;
|
|
sale.vlfrete = cart.valueShipping;
|
|
|
|
await getConnection()
|
|
.createQueryBuilder()
|
|
.insert()
|
|
.into(Shopping)
|
|
.values(createShopping)
|
|
.execute();
|
|
|
|
return createShopping;
|
|
|
|
} catch ( erro ) {
|
|
console.log(erro);
|
|
throw new HttpException("Erro ao criar item no carrinho de compras", HttpStatus.INTERNAL_SERVER_ERROR);
|
|
}
|
|
}*/
|
|
|
|
async getItemCart(idCart: string, idProduct: string, store: string, deliveryType: string) {
|
|
const connection = new Connection(connectionOptions);
|
|
await connection.connect();
|
|
const queryRunner = connection.createQueryRunner();
|
|
await queryRunner.connect();
|
|
try {
|
|
const item = await queryRunner.manager
|
|
.getRepository(ShoppingItens)
|
|
.createQueryBuilder('estprevendai')
|
|
.where("\"estprevendai\".idcart = :idcart", { idcart: idCart })
|
|
.andWhere("\"estprevendai\".codprod = :idProduct", { idProduct: idProduct })
|
|
.andWhere("\"estprevendai\".tipoentrega = :tipoentrega", { tipoentrega: deliveryType })
|
|
.andWhere("( \"estprevendai\".codfilialretira = :store OR :store = '99' )", { store: store })
|
|
.andWhere("\"estprevendai\".dtcancel is null")
|
|
.getOne();
|
|
console.log(item);
|
|
return item;
|
|
} catch (error) {
|
|
console.log(error);
|
|
throw error;
|
|
} finally {
|
|
await queryRunner.release();
|
|
await connection.close();
|
|
}
|
|
|
|
}
|
|
|
|
async getItemCartById(idCart: string, id: string) {
|
|
const connection = new Connection(connectionOptions);
|
|
await connection.connect();
|
|
const queryRunner = connection.createQueryRunner();
|
|
await queryRunner.connect();
|
|
try {
|
|
const item = await queryRunner.manager
|
|
.getRepository(ShoppingItens)
|
|
.createQueryBuilder('estprevendai')
|
|
.where("\"estprevendai\".idcart = :idcart", { idcart: idCart })
|
|
.andWhere("\"estprevendai\".id = :id", { id: id })
|
|
.andWhere("\"estprevendai\".dtcancel is null")
|
|
.getOne();
|
|
console.log(item);
|
|
return item;
|
|
} catch (error) {
|
|
console.log(error);
|
|
throw error;
|
|
} finally {
|
|
await queryRunner.release();
|
|
await connection.close();
|
|
}
|
|
|
|
}
|
|
|
|
async createItemCart(itemShopping: ShoppingItem) {
|
|
console.log(JSON.stringify(itemShopping));
|
|
const connectionDb = new Connection(connectionOptions);
|
|
await connectionDb.connect();
|
|
//const connection = getConnection();
|
|
const queryRunner = connectionDb.createQueryRunner();
|
|
await queryRunner.connect();
|
|
console.log('Incluindo item 01 - ' + Date.now().toString());
|
|
await queryRunner.startTransaction();
|
|
|
|
try {
|
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
const uuid = require('uuid');
|
|
const idItem = uuid.v4();
|
|
let idCart = "";
|
|
if (itemShopping.idCart == null || itemShopping.idCart == '')
|
|
idCart = uuid.v4();
|
|
else
|
|
idCart = itemShopping.idCart;
|
|
console.log('Incluindo item 02 - ' + Date.now().toString());
|
|
const cart = await queryRunner.manager
|
|
.getRepository(Shopping)
|
|
.createQueryBuilder('estprevendac')
|
|
.where("\"estprevendac\".id = :id", { id: idCart })
|
|
.getOne();
|
|
console.log('Incluindo item 03 - ' + Date.now().toString());
|
|
if (cart == null) {
|
|
await this.createShopping(idCart, itemShopping.invoiceStore, itemShopping.seller, queryRunner);
|
|
}
|
|
console.log('Incluindo item 04 - ' + Date.now().toString());
|
|
const item = await this.getItemCartById(itemShopping.idCart, itemShopping.id);
|
|
console.log('Incluindo item 05 - ' + Date.now().toString());
|
|
if (item) {
|
|
itemShopping.id = item.id;
|
|
this.updateItem(itemShopping);
|
|
return await this.getItemCartById(itemShopping.idCart, itemShopping.id);
|
|
}
|
|
|
|
console.log('Incluindo item 06 - ' + Date.now().toString());
|
|
const recordItens = await queryRunner.query(`SELECT COUNT(1) as "recordNo" FROM ESTPREVENDAI WHERE IDCART = '${itemShopping.idCart}'`);
|
|
let numSeq = 1;
|
|
if (recordItens != null && recordItens.length > 0) {
|
|
numSeq = recordItens[0].recordNo + 1;
|
|
}
|
|
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 ) {
|
|
quantityStock = dataStockItem[0].quantityStock;
|
|
}
|
|
|
|
|
|
const sqlInsertitem = 'INSERT INTO ESTPREVENDAI ( ID, IDCART, NUMSEQ, CODPROD, QT, PVENDA, DTINCLUSAO, NOMEECOMMERCE, URLIMAGEM, TIPOPRODUTO, CODFILIALRETIRA, TIPOENTREGA, ' +
|
|
' CODUSUR, PERCDESC, CODFUNCDESC, PTABELA, VLDESCONTO, PRECOPROMOCIONAL, MULTIPLO, DESCRICAOAUXILIAR, DESCRICAO, MARCA, ' +
|
|
' PRECOPROMOCAO, CODAUXILIAR, VLCUSTOFIN, VLCUSTOREAL, VLCUSTOREP, PERCACRESCIMO, QTACRESCIMO, BASETINTOMETRICO, ' +
|
|
' LINHATINTOMETRICO, CORTINTOMETRICO, LITRAGEM, LETRATINTOMETRICO, AMBIENTE, PRODUTOCOMPREJUNTO, QTESTOQUEDISP ) ' +
|
|
' VALUES ( :ID, :IDCART, :NUMSEQ, :CODPROD, :QT, :PVENDA, SYSDATE, :NOMEECOMMERCE, :URLIMAGEM, :TIPOPRODUTO, :CODFILIALRETIRA, :TIPOENTREGA, ' +
|
|
' :CODUSUR, :PERCDESC, :CODFUNCDESC, :PTABELA, :VLDESCONTO, :PRECOPROMOCIONAL, :MULTIPLO, :DESCRICAOAUXILIAR, :DESCRICAO, :MARCA, ' +
|
|
' :PRECOPROMOCAO, :CODAUXILIAR, :VLCUSTOFIN, :VLCUSTOREAL, :VLCUSTOREP, :PERCACRESCIMO, :QTACRESCIMO, :BASETINTOMETRICO, ' +
|
|
' :LINHATINTOMETRICO, :CORTINTOMETRICO, :LITRAGEM, :LETRATINTOMETRICO, :AMBIENTE, :PRODUTOCOMPREJUNTO, :QTESTOQUEDISP )';
|
|
let listPrice = 0;
|
|
if (itemShopping.base === 'S') {
|
|
listPrice = itemShopping.price;
|
|
} else {
|
|
listPrice = (itemShopping.promotion > 0) ? itemShopping.promotion : itemShopping.listPrice;
|
|
}
|
|
|
|
await queryRunner.query(sqlInsertitem, [
|
|
idItem, //ID
|
|
idCart, //IDCART
|
|
numSeq, //NUMSEQ
|
|
itemShopping.idProduct, //CODPROD
|
|
itemShopping.quantity, //QT
|
|
itemShopping.price, //PVENDA
|
|
itemShopping.description, //NOMEECOMMERCE
|
|
itemShopping.image, //URLIMAGE
|
|
itemShopping.productType, //TIPOPRODUTO
|
|
itemShopping.stockStore, //CODFILIALRETIRA
|
|
itemShopping.deliveryType, //TIPOENTREGA
|
|
itemShopping.seller, //CODUSUR
|
|
itemShopping.discount, //PERCDESC
|
|
itemShopping.userDiscount, //CODFUNCDESC
|
|
listPrice, //PTABELA
|
|
itemShopping.discountValue, //VALORDESCONTO
|
|
(itemShopping.promotion > 0) ? 'S' : 'N', //PRECOPROMOCIONAL
|
|
itemShopping.mutiple, //MULTIPLO
|
|
itemShopping.auxDescription, //DESCRICAOAUXILIAR
|
|
itemShopping.smallDescription, //DESCRICAO
|
|
itemShopping.brand, //MARCA
|
|
itemShopping.promotion, //PRECOPROMOCAO
|
|
itemShopping.ean, //CODAUXILIAR
|
|
0, //VLCUSTOFIN
|
|
0, //VLCUSTOREAL
|
|
0, //VLCUSTOREP
|
|
itemShopping.percentUpQuantity, //PERCARESCIMO
|
|
itemShopping.upQuantity, //QTACRESCIMO
|
|
itemShopping.base, //BASEINTOMETRICO
|
|
itemShopping.line, //LINHATINTOMETRICO
|
|
(itemShopping.base == 'S') ? itemShopping.auxDescription : null, //CORTINTOMETRICO
|
|
itemShopping.can, //LITRAGEM
|
|
itemShopping.letter, //LETRATINTOMETRICO
|
|
itemShopping.environment, //AMBIENTE
|
|
itemShopping.productTogether, //PRODUTOCOMPREJUNTO
|
|
quantityStock, //QTESTOQUEDISP
|
|
]);
|
|
|
|
const createItemShopping = new ShoppingItens();
|
|
createItemShopping.id = idItem;
|
|
createItemShopping.description = itemShopping.description;
|
|
createItemShopping.smallDescription = itemShopping.smallDescription;
|
|
createItemShopping.image = itemShopping.image;
|
|
createItemShopping.productType = itemShopping.productType;
|
|
createItemShopping.idCart = idCart;
|
|
createItemShopping.idProduct = itemShopping.idProduct;
|
|
if (itemShopping.base === 'S') {
|
|
createItemShopping.listPrice = itemShopping.price;
|
|
} else {
|
|
createItemShopping.listPrice = (itemShopping.promotion > 0) ? itemShopping.promotion : itemShopping.listPrice;
|
|
}
|
|
createItemShopping.price = itemShopping.price;
|
|
createItemShopping.quantity = itemShopping.quantity;
|
|
createItemShopping.deliveryType = itemShopping.deliveryType;
|
|
createItemShopping.stockStore = itemShopping.stockStore;
|
|
createItemShopping.seller = itemShopping.seller;
|
|
createItemShopping.discount = itemShopping.discount;
|
|
createItemShopping.discountValue = (itemShopping.listPrice * itemShopping.discount / 100);
|
|
createItemShopping.promotion = itemShopping.promotion;
|
|
createItemShopping.mutiple = itemShopping.mutiple;
|
|
createItemShopping.auxDescription = itemShopping.auxDescription;
|
|
createItemShopping.brand = itemShopping.brand;
|
|
createItemShopping.ean = itemShopping.ean;
|
|
createItemShopping.percentUpQuantity = itemShopping.percentUpQuantity;
|
|
createItemShopping.upQuantity = itemShopping.upQuantity;
|
|
createItemShopping.base = itemShopping.base;
|
|
createItemShopping.line = itemShopping.line;
|
|
createItemShopping.can = itemShopping.can;
|
|
createItemShopping.letter = itemShopping.letter;
|
|
createItemShopping.color = (itemShopping.base == 'S') ? itemShopping.auxDescription : null;
|
|
createItemShopping.productTogether = itemShopping.productTogether;
|
|
|
|
createItemShopping.createDate = new Date();
|
|
|
|
console.log('Incluindo item 07 - ' + Date.now().toString());
|
|
// await queryRunner.manager.save(createItemShopping);
|
|
console.log('Incluindo item 08 - ' + Date.now().toString());
|
|
await queryRunner.commitTransaction();
|
|
console.log('Incluindo item 09 - ' + Date.now().toString());
|
|
await this.calculateProfitShoppping(idCart, queryRunner);
|
|
await this.updateTotalShopping(idCart);
|
|
|
|
return createItemShopping;
|
|
|
|
} catch (erro) {
|
|
console.log(erro);
|
|
await queryRunner.rollbackTransaction();
|
|
throw new HttpException("Erro ao criar item no carrinho de compras", HttpStatus.INTERNAL_SERVER_ERROR);
|
|
} finally {
|
|
await queryRunner.release();
|
|
await connectionDb.close();
|
|
}
|
|
|
|
}
|
|
|
|
async createShopping(idCart: string, storeId: string, sellerId: number, queryRunner: QueryRunner) {
|
|
const sql = 'INSERT INTO ESTPREVENDAC ( ID, CODFILIAL, DATA, CODUSUR, VLPEDIDO, VLDESCONTO, VLTAXAENTREGA, TIPOPRIORIDADEENTREGA ) ' +
|
|
' VALUES ( :1, :2, TRUNC(SYSDATE), :3, :4, :5, :6, :7 )';
|
|
|
|
await queryRunner.query(sql, [
|
|
idCart,
|
|
storeId,
|
|
sellerId,
|
|
0,
|
|
0,
|
|
0,
|
|
'B'
|
|
]);
|
|
|
|
}
|
|
|
|
async updateTotalShopping(idCart: string) {
|
|
const connection = new Connection(connectionOptions);
|
|
await connection.connect();
|
|
const queryRunner = connection.createQueryRunner();
|
|
await queryRunner.connect();
|
|
await queryRunner.startTransaction();
|
|
try {
|
|
const prevenda = 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', [idCart]);
|
|
if (prevenda != null) {
|
|
const sql = ` UPDATE ESTPREVENDAC SET ` +
|
|
` VLPEDIDO = :1 ` +
|
|
` ,VLDESCONTO = :2 ` +
|
|
` ,TOTPESO = :3 ` +
|
|
` ,VLTABELA = :4 ` +
|
|
` WHERE ID = :5 `;
|
|
await queryRunner.query(sql, [
|
|
prevenda[0].vlatend,
|
|
prevenda[0].vldesconto,
|
|
prevenda[0].totpeso,
|
|
prevenda[0].vltabela,
|
|
idCart
|
|
]);
|
|
}
|
|
await queryRunner.commitTransaction();
|
|
|
|
} catch (error) {
|
|
await queryRunner.rollbackTransaction();
|
|
throw error;
|
|
} finally {
|
|
await queryRunner.release();
|
|
await connection.close();
|
|
}
|
|
|
|
}
|
|
|
|
async updateItem(itemShopping: ShoppingItem) {
|
|
const connection = new Connection(connectionOptions);
|
|
await connection.connect();
|
|
const queryRunner = connection.createQueryRunner();
|
|
await queryRunner.connect();
|
|
await queryRunner.startTransaction();
|
|
try {
|
|
|
|
const sql = ' UPDATE ESTPREVENDAI SET ' +
|
|
' PVENDA = :1 ' +
|
|
' ,PTABELA = :2 ' +
|
|
' ,QT = :3 ' +
|
|
' ,TIPOENTREGA = :4 ' +
|
|
' ,CODFILIALRETIRA = :5 ' +
|
|
' ,DESCRICAOAUXILIAR = :6 ' +
|
|
' ,AMBIENTE = :7 ' +
|
|
' WHERE ID = :8 ';
|
|
|
|
await queryRunner.query(sql, [
|
|
itemShopping.price,
|
|
itemShopping.listPrice,
|
|
itemShopping.quantity,
|
|
itemShopping.deliveryType,
|
|
itemShopping.stockStore,
|
|
itemShopping.auxDescription,
|
|
itemShopping.environment,
|
|
itemShopping.id
|
|
]);
|
|
|
|
await queryRunner.commitTransaction();
|
|
|
|
await this.updateTotalShopping(itemShopping.idCart);
|
|
await this.calculateProfitShoppping(itemShopping.idCart, queryRunner);
|
|
|
|
} catch (erro) {
|
|
await queryRunner.rollbackTransaction();
|
|
throw erro;
|
|
} finally {
|
|
await queryRunner.release();
|
|
await connection.close();
|
|
}
|
|
}
|
|
|
|
async updatePrice(itemShopping: ShoppingItem) {
|
|
console.log(itemShopping);
|
|
const connection = new Connection(connectionOptions);
|
|
await connection.connect();
|
|
const queryRunner = connection.createQueryRunner();
|
|
await queryRunner.connect();
|
|
await queryRunner.startTransaction();
|
|
try {
|
|
|
|
const sql = 'UPDATE ESTPREVENDAI SET ' +
|
|
' PVENDA = :1 ' +
|
|
' ,PERCDESC = :2 ' +
|
|
' ,VLDESCONTO = :3 ' +
|
|
' ,CODFUNCDESC = :4 ' +
|
|
' WHERE ID = :5 ';
|
|
await queryRunner.query(sql, [
|
|
itemShopping.price,
|
|
itemShopping.discount,
|
|
Number.parseFloat((itemShopping.listPrice * itemShopping.discount / 100).toFixed(2)),
|
|
itemShopping.userDiscount,
|
|
itemShopping.id
|
|
]);
|
|
|
|
// await queryRunner.manager
|
|
// .createQueryBuilder()
|
|
// .update(ShoppingItens)
|
|
// .set({
|
|
// price: itemShopping.price,
|
|
// discount: itemShopping.discount,
|
|
// discountValue: Number.parseFloat((itemShopping.listPrice * itemShopping.discount / 100).toFixed(2)),
|
|
// userDiscount: itemShopping.userDiscount
|
|
// })
|
|
// .where("\"ESTPREVENDAI\".id = :id", { id: itemShopping.id })
|
|
// .execute();
|
|
await queryRunner.commitTransaction();
|
|
await this.calculateProfitShoppping(itemShopping.idCart, queryRunner);
|
|
await this.updateTotalShopping(itemShopping.idCart);
|
|
return itemShopping;
|
|
} catch (erro) {
|
|
await queryRunner.rollbackTransaction();
|
|
throw erro;
|
|
} finally {
|
|
await queryRunner.release();
|
|
await connection.close();
|
|
}
|
|
}
|
|
|
|
async deleteItem(id: string) {
|
|
const connection = new Connection(connectionOptions);
|
|
await connection.connect();
|
|
const queryRunner = connection.createQueryRunner();
|
|
await queryRunner.connect();
|
|
await queryRunner.startTransaction();
|
|
try {
|
|
const item = await queryRunner.manager
|
|
.getRepository(ShoppingItens)
|
|
.createQueryBuilder('estprevendai')
|
|
.where("\"estprevendai\".id = :id", { id })
|
|
.getOne();
|
|
if (item != null) {
|
|
const sql = 'DELETE FROM ESTPREVENDAI WHERE ID = :1';
|
|
await queryRunner.query(sql, [
|
|
id
|
|
]);
|
|
}
|
|
await queryRunner.commitTransaction();
|
|
await this.updateTotalShopping(item.idCart);
|
|
await this.calculateProfitShoppping(item.idCart, queryRunner);
|
|
} catch (erro) {
|
|
await queryRunner.rollbackTransaction();
|
|
throw erro;
|
|
} finally {
|
|
await queryRunner.release();
|
|
await connection.close();
|
|
}
|
|
}
|
|
|
|
async applyDiscountOrder(order: OrderDiscount) {
|
|
console.log('Desconto pedido: ' + JSON.stringify(order));
|
|
const items = await this.GetItensCart(order.id);
|
|
const discountAuthUser = await this.userService.discountUser(order.idUserAuth);
|
|
console.log(discountAuthUser);
|
|
if (discountAuthUser < order.percentDiscount) {
|
|
return new HttpException('Percentual de desconto acima do permido para o usuário.', HttpStatus.FORBIDDEN);
|
|
}
|
|
const connection = new Connection(connectionOptions);
|
|
await connection.connect();
|
|
const queryRunner = connection.createQueryRunner();
|
|
await queryRunner.connect();
|
|
await queryRunner.startTransaction();
|
|
try {
|
|
let listPriceTotal = 0;
|
|
let discountTotal = 0;
|
|
const sql = 'UPDATE ESTPREVENDAI SET ' +
|
|
' PVENDA = :1 ' +
|
|
' ,PERCDESC = :2 ' +
|
|
' ,VLDESCONTO = :3 ' +
|
|
' ,CODFUNCDESC = :4 ' +
|
|
' WHERE ID = :5 ';
|
|
items.filter(item => item.promotion == null || item.promotion == 0)
|
|
.forEach(async (item) => {
|
|
const price = (item.listPrice * (1 - (order.percentDiscount / 100))).toFixed(2);
|
|
listPriceTotal += (item.listPrice * item.quantity);
|
|
discountTotal += ((Number.parseFloat(item.listPrice.toFixed(2)) - Number.parseFloat(price)) * item.quantity);
|
|
await queryRunner.query(sql, [
|
|
Number.parseFloat(price),
|
|
order.percentDiscount,
|
|
(item.listPrice - Number.parseFloat(price)),
|
|
order.idUserAuth,
|
|
item.id
|
|
]);
|
|
// await queryRunner.manager
|
|
// .createQueryBuilder()
|
|
// .update(ShoppingItens)
|
|
// .set({
|
|
// price: Number.parseFloat(price),
|
|
// discount: order.percentDiscount,
|
|
// discountValue: (item.listPrice - Number.parseFloat(price)),
|
|
// userDiscount: order.idUserAuth
|
|
// })
|
|
// .where("\"ESTPREVENDAI\".id = :id", { id: item.id })
|
|
// .execute();
|
|
});
|
|
console.log('total de desconto: ' + discountTotal);
|
|
const sqlOrder = 'UPDATE ESTPREVENDAC SET ' +
|
|
' VLPEDIDO = :1 ' +
|
|
' ,VLDESCONTO = :2 ' +
|
|
' WHERE ID = :3 ';
|
|
|
|
await queryRunner.query(sqlOrder, [
|
|
listPriceTotal,
|
|
discountTotal,
|
|
order.id
|
|
]);
|
|
|
|
// await queryRunner.manager
|
|
// .createQueryBuilder()
|
|
// .update(Shopping)
|
|
// .set({
|
|
// vlpedido: listPriceTotal,
|
|
// vldesconto: discountTotal,
|
|
// })
|
|
// .where("\"ESTPREVENDAC\".id = :id", { id: order.id })
|
|
// .execute();
|
|
await queryRunner.commitTransaction();
|
|
await this.calculateProfitShoppping(order.id, queryRunner);
|
|
await this.updateTotalShopping(order.id);
|
|
} catch (err) {
|
|
console.log(err);
|
|
await queryRunner.rollbackTransaction();
|
|
throw err;
|
|
}
|
|
finally {
|
|
await queryRunner.release();
|
|
await connection.close();
|
|
}
|
|
|
|
return await this.GetItensCart(order.id);
|
|
|
|
}
|
|
|
|
async applyTaxDelivery(order: OrderTaxDelivery) {
|
|
|
|
|
|
/* const connection = new Connection(connectionOptions);
|
|
await connection.connect();
|
|
const queryRunner = connection.createQueryRunner();
|
|
await queryRunner.connect();
|
|
// await queryRunner.startTransaction();
|
|
try {
|
|
|
|
// const sql = ' UPDATE ESTPREVENDAC SET ' +
|
|
// ' VLTAXAENTREGA = :1 ' +
|
|
// ' ,CODFORNECFRETE = :2 ' +
|
|
// ' ,CODTABELAFRETE = :3 ' +
|
|
// ' WHERE ID = :4';
|
|
|
|
const sql = 'BEGIN ESK_VENDA.ATULIZAR_DADOS_PREVENDA(:1, :2, :3, :4); END;'
|
|
|
|
await queryRunner.query(sql, [
|
|
order.taxValue,
|
|
order.carrierId,
|
|
order.deliveryTaxId,
|
|
order.id
|
|
]);
|
|
// await queryRunner.commitTransaction();
|
|
} catch (err) {
|
|
// await queryRunner.rollbackTransaction();
|
|
// console.log(err);
|
|
|
|
throw err;
|
|
}
|
|
finally {
|
|
await queryRunner.release();
|
|
await connection.close();
|
|
} */
|
|
|
|
return await this.GetItensCart(order.id.toString());
|
|
}
|
|
|
|
|
|
async getShopping(id: string) {
|
|
const connection = new Connection(connectionOptions);
|
|
await connection.connect();
|
|
const queryRunner = connection.createQueryRunner();
|
|
await queryRunner.connect();
|
|
try {
|
|
const shopping = await queryRunner.manager
|
|
.getRepository(Shopping)
|
|
.createQueryBuilder('estprevendac')
|
|
.where("\"estprevendac\".id = :id", { id })
|
|
.getOne();
|
|
return shopping;
|
|
} catch (error) {
|
|
throw error;
|
|
} finally {
|
|
await queryRunner.release();
|
|
await connection.close();
|
|
}
|
|
}
|
|
|
|
async updatePriceShopping(idCart: string, idPaymentPlan: number) {
|
|
const connection = new Connection(connectionOptions);
|
|
await connection.connect();
|
|
const queryRunner = connection.createQueryRunner();
|
|
await queryRunner.connect();
|
|
await queryRunner.startTransaction();
|
|
try {
|
|
console.log('atualizando preços.');
|
|
await queryRunner
|
|
.query("BEGIN ESK_VENDA.ATUALIZAR_PRECO_VENDA(:idCart, :idPaymentPlan); END;", [idCart, idPaymentPlan]);
|
|
await this.calculateProfitShoppping(idCart, queryRunner);
|
|
await queryRunner.commitTransaction();
|
|
return true;
|
|
} catch (err) {
|
|
await queryRunner.rollbackTransaction();
|
|
console.log(err);
|
|
throw err;
|
|
// since we have errors let's rollback changes we made
|
|
} finally {
|
|
// you need to release query runner which is manually created:
|
|
await queryRunner.release();
|
|
await connection.close();
|
|
}
|
|
}
|
|
|
|
async calculateProfitShoppping(id: string, queryRunner: QueryRunner) {
|
|
try {
|
|
console.log('Calculando margem da prevenda - id: ' + id);
|
|
await queryRunner.query('BEGIN ESK_VENDA.calcular_cmv_prevenda(:1); END;', [id]).catch(err => console.log(err));
|
|
} catch (erro) {
|
|
throw erro;
|
|
}
|
|
}
|
|
|
|
async createLogShopping(logOrder: LogOrder) {
|
|
const connection = new Connection(connectionOptions);
|
|
await connection.connect();
|
|
const queryRunner = connection.createQueryRunner();
|
|
await queryRunner.connect();
|
|
await queryRunner.startTransaction();
|
|
try {
|
|
const sqlInsert = "INSERT INTO ESTLOGPEDIDOWEB ( IDCART, DATA, CODFUNCLOGADO, ACAO, CODFUNCAUTOR, OBSERVACAO ) " +
|
|
" VALUES ( :IDCART, SYSDATE, :CODFUNCAUTOR, :ACAO, :CODFUNCAUTOR, :OBSERVACAO )";
|
|
|
|
await queryRunner
|
|
.query(sqlInsert, [
|
|
logOrder.idCart,
|
|
logOrder.idUser,
|
|
logOrder.action,
|
|
logOrder.iduserAuth,
|
|
logOrder.notation
|
|
]);
|
|
await queryRunner.commitTransaction();
|
|
return true;
|
|
} catch (err) {
|
|
console.log(err);
|
|
await queryRunner.rollbackTransaction();
|
|
throw err;
|
|
} finally {
|
|
await queryRunner.release();
|
|
await connection.close();
|
|
}
|
|
}
|
|
|
|
async getLotProduct(productId: number, customerId: number) {
|
|
|
|
const sqlQueryLot = `SELECT LOTES_WMS.CODFILIAL as "storeId",
|
|
LOTES_WMS.CODPROD as "customerId",
|
|
LOTES_WMS.NUMLOTE as "lotProduct",
|
|
SUM(LOTES_WMS.QT) as "quantitySale",
|
|
MAX(ESTOQUE_WMS.QT) as "quantityStock"
|
|
FROM LOTES_WMS, ESTOQUE_WMS, PCPEDC
|
|
WHERE LOTES_WMS.NUMPED = PCPEDC.NUMPED
|
|
AND PCPEDC.DATA = ( SELECT MAX(P.DATA) FROM PCPEDC P, PCPEDI I
|
|
WHERE P.CODCLI = PCPEDC.CODCLI
|
|
AND P.NUMPED = I.NUMPED
|
|
AND I.CODPROD = LOTES_WMS.CODPROD )
|
|
AND ESTOQUE_WMS.EMPRESA_ERP = LOTES_WMS.CODFILIAL
|
|
AND ESTOQUE_WMS.PRODUTO_ERP = LOTES_WMS.CODPROD
|
|
AND ESTOQUE_WMS.LOTE = LOTES_WMS.NUMLOTE
|
|
AND PCPEDC.CODCLI = ${customerId}
|
|
AND ESTOQUE_WMS.PRODUTO_ERP = ${productId}
|
|
GROUP BY LOTES_WMS.CODFILIAL, LOTES_WMS.CODPROD, LOTES_WMS.NUMLOTE
|
|
|
|
UNION ALL
|
|
|
|
SELECT ESTOQUE_WMS.empresa_erp as "storeId",
|
|
ESTOQUE_WMS.produto_erp as "customerId",
|
|
ESTOQUE_WMS.LOTE as "lotProduct",
|
|
NULL as "quantitySale",
|
|
ESTOQUE_WMS.QT as "quantityStock"
|
|
FROM ESTOQUE_WMS
|
|
WHERE NOT EXISTS(SELECT LOTES_WMS.NUMPED FROM LOTES_WMS, PCPEDC
|
|
WHERE ESTOQUE_WMS.EMPRESA_ERP = LOTES_WMS.CODFILIAL
|
|
AND ESTOQUE_WMS.PRODUTO_ERP = LOTES_WMS.CODPROD
|
|
AND ESTOQUE_WMS.LOTE = LOTES_WMS.NUMLOTE
|
|
AND LOTES_WMS.NUMPED = PCPEDC.NUMPED
|
|
AND PCPEDC.CODCLI = ${customerId} )
|
|
AND ESTOQUE_WMS.PRODUTO_ERP = ${productId} `;
|
|
|
|
const connection = new Connection(connectionOptions);
|
|
await connection.connect();
|
|
const queryRunner = connection.createQueryRunner();
|
|
await queryRunner.connect();
|
|
try {
|
|
|
|
const lotsProduct = await queryRunner
|
|
.query(sqlQueryLot);
|
|
|
|
return lotsProduct;
|
|
} catch (err) {
|
|
console.log(err);
|
|
throw err;
|
|
} finally {
|
|
await queryRunner.release();
|
|
await connection.close();
|
|
}
|
|
|
|
}
|
|
|
|
}
|