commit
This commit is contained in:
168
src/sales/shopping/shopping.controller.ts
Normal file
168
src/sales/shopping/shopping.controller.ts
Normal file
@@ -0,0 +1,168 @@
|
||||
import { Body, Controller, Delete, Get, HttpException, HttpStatus, Param, Post, Put, Req } from '@nestjs/common';
|
||||
import { ShoppingItem } from 'src/domain/models/shopping-item.model';
|
||||
import { ShoppingService } from './shopping.service';
|
||||
import { ResultModel } from '../../domain/models/result.model';
|
||||
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';
|
||||
|
||||
@ApiTags('Shopping')
|
||||
@Controller('api/v1/shopping')
|
||||
export class ShoppingController {
|
||||
|
||||
constructor(private shoppingService: ShoppingService){}
|
||||
|
||||
@Get('cart/:id')
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
async getPreVenda(@Param('id') id: string ){
|
||||
try {
|
||||
const cart = await this.shoppingService.getShopping(id);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@Get('cart/:idcart/item/:idProduct/tipoentrega/:deliveryType')
|
||||
async getItemCart(@Req() request, @Param('idCart') idCart: string,
|
||||
@Param('idProduct') idProduct: string, @Param('deliveryType') deliveryType: string){
|
||||
let store = '99';
|
||||
try {
|
||||
if (request.headers['x-store'])
|
||||
store = request.headers['x-store'];
|
||||
const cart = await this.shoppingService.getItemCart(idCart, idProduct, store, deliveryType);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@Get('cart/lot/:productId/:customerId')
|
||||
async getLotProduct( @Req() request, @Param('productId') productId: number,
|
||||
@Param('customerId') customerId: number ) {
|
||||
let store = '99';
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Post('item')
|
||||
async createItemShopping(@Body() item: ShoppingItem){
|
||||
console.log('createItemShopping')
|
||||
try {
|
||||
return await this.shoppingService.createItemCart(item);
|
||||
} catch (error) {
|
||||
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
@Post('log')
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@Put('item')
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@Put('item/discount')
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@Put('order/discount')
|
||||
async applyDiscountOrder(@Body() order: OrderDiscount) {
|
||||
try {
|
||||
const itensOrder = await this.shoppingService.applyDiscountOrder(order);
|
||||
return itensOrder;
|
||||
} catch (error) {
|
||||
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
@Put('order/tax')
|
||||
async applyTaxDeOrder(@Body() order: OrderTaxDelivery) {
|
||||
try {
|
||||
const orderTax = await this.shoppingService.applyTaxDelivery(order);
|
||||
return orderTax;
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
@Delete('item/delete/:id')
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@Put('update/payment/:id')
|
||||
async updateItemsShopping(@Param('id') id: string, @Body() payment: any) {
|
||||
try {
|
||||
console.log('Atualizando preços (controller).')
|
||||
const idPaymentPlan = payment.idPaymentPlan;
|
||||
await this.shoppingService.updatePriceShopping(id, idPaymentPlan);
|
||||
return new ResultModel(true, 'Preços atualizados com sucesso!', {}, null);
|
||||
} catch (err) {
|
||||
throw new HttpException(new ResultModel(false, err.errors.message, {}, err),
|
||||
HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
17
src/sales/shopping/shopping.module.ts
Normal file
17
src/sales/shopping/shopping.module.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { ShoppingService } from './shopping.service';
|
||||
import { ShoppingController } from './shopping.controller';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { UserService } from 'src/Auth/services/user.service';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
UserService,
|
||||
],
|
||||
controllers: [
|
||||
ShoppingController,],
|
||||
providers: [
|
||||
ShoppingService,
|
||||
UserService
|
||||
],
|
||||
})
|
||||
export class ShoppingModule { }
|
||||
717
src/sales/shopping/shopping.service.ts
Normal file
717
src/sales/shopping/shopping.service.ts
Normal file
@@ -0,0 +1,717 @@
|
||||
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 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 ) ' +
|
||||
' 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 )';
|
||||
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
|
||||
]);
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user