File: /var/www/vhost/disk-apps/pwa.sports-crowd.com/src/app/pages/cart/cart.ts
import { Component, OnInit } from "@angular/core";
import { TranslateService } from "@ngx-translate/core";
import {
NavController,
ModalController,
IonRouterOutlet,
AlertController,
} from "@ionic/angular";
import { StorageService } from '../../services/storage.service';
import { Router } from "@angular/router";
import { CartService } from "../../services/cart.service";
import { CityService } from "../../services/city.service";
import { UserService } from "../../services/user.service";
import { UtilsService } from "../../services/utils.service";
import { CorporateIdentityService } from "../../services/corporate-identity.service";
@Component({
selector: "page-cart",
templateUrl: "cart.html",
styleUrls: ["./cart.scss"],
})
export class CartPage implements OnInit {
private toastMessageText: any;
messageText: any;
emptySettingsSlide: any;
discountList: any = [];
discountDelivery: any = [];
couponList: any = [];
campaignList: any = [];
categoryList: any = [];
priceToDiscount: any;
discountpercentageCombo: any;
productGift: any = [];
productosDescuentoGift: any = [];
validConfirmPurchase: boolean = false;
currency: string;
constructor(
public navCtrl: NavController,
public modalCtrl: ModalController,
public alertCtrl: AlertController,
private translateService: TranslateService,
public cartProvider: CartService,
public cityProvider: CityService,
public userProvider: UserService,
public utilsService: UtilsService,
private storage: StorageService,
private routerOutlet: IonRouterOutlet,
private router: Router,
private corporateIdentityService: CorporateIdentityService
) {
// traduccion textos
this.translateService
.get([
"TITLE_DELETE_CART",
"TEXT_DELETE_CART",
"TITLE_VALIDATE_INVITED",
"TEXT_VALIDATE_INVITED",
])
.subscribe((values) => {
this.messageText = {
titleDeleteCart: values.TITLE_DELETE_CART,
textDeleteCart: values.TEXT_DELETE_CART,
titleValidateInvited: values.TITLE_VALIDATE_INVITED,
textValidateInvited: values.TEXT_VALIDATE_INVITED,
};
});
this.currency = this.corporateIdentityService.getCurrency();
}
ngOnInit() {
this.emptySettingsSlide = {
showImage: true,
urlImage: "../../assets/img/shopping_cart_sad.png",
showText: true,
text: this.translateService.instant("EMPTY_CART"),
};
if (this.userProvider._infoUser && ((this.userProvider._infoUser.user_info && this.userProvider._infoUser.user_info.is_initial) || !this.userProvider._infoUser.addresses.length)) {
this.router.navigate(["/address/confirmOrder/true"]);
}
}
ionViewDidLeave() {
if (this.cartProvider.productsCart && this.cartProvider.productsCart.length) {
for (let i = 0; i < this.cartProvider.productsCart.length; i++) {
this.cartProvider.productsCart[i].priceToDiscount = 0;
if (typeof (this.cartProvider.productsCart[i].discountpercentageCombo) !== "undefined") {
this.cartProvider.productsCart[i].discountpercentageCombo = 0;
this.cartProvider.productsCart[i].priceTotal = this.cartProvider.productsCart[i].price;
this.cartProvider.productsCart[i].priceWithDiscount = this.cartProvider.productsCart[i].price;
}
}
this.cartProvider.calculatePrice();
}
}
ionViewWillEnter() {
if (!this.cartProvider._paymentTypes) {
this.cartProvider.getPaymentTypesDomicile();
}
if (
!this.cartProvider._priceDomicile ||
this.cartProvider._discountDelivery
) {
this.cartProvider._discountDelivery = 0;
this.cartProvider.getPriceDomicile();
}
if (this.cartProvider.domicile_by_coverage) {
this.cartProvider
.priceDomicileByCoverage()
.then(() => {
this.getDiscounts();
this.validateShoppingCartProducts();
this.cartProvider.calculatePrice();
})
.catch((error) => {
console.log("error");
});
} else {
this.getDiscounts();
this.validateShoppingCartProducts();
this.cartProvider.calculatePrice();
}
}
async showConfirmDeleteCart() {
const confirm = await this.alertCtrl.create({
header: this.messageText.titleDeleteCart,
message: this.messageText.textDeleteCart,
buttons: [
{
text: "Cancelar",
handler: () => { },
},
{
text: "Vaciar",
handler: () => {
this.cartProvider.deleteAllProductsCart();
},
},
],
});
await confirm.present();
}
goToConfirmOrder() {
this.validateShoppingCartProducts(true);
}
async confirm() {
if (this.userProvider._infoUser.id == 2) {
const confirm = await this.alertCtrl.create({
header: this.messageText.titleValidateInvited,
message: this.messageText.textValidateInvited,
buttons: [
{
text: "Cancelar",
handler: () => {
console.log("Disagree clicked");
},
},
{
text: "Registrarme",
handler: () => {
this.storage.remove("token");
this.storage.remove("infoUser");
this.navCtrl.navigateRoot("/welcome");
},
},
],
});
await confirm.present();
} else if (this.userProvider._infoUser && ((this.userProvider._infoUser.user_info && this.userProvider._infoUser.user_info.is_initial) || !this.userProvider._infoUser.addresses.length)) {
this.router.navigate(["/address/confirmOrder/true"]);
} else {
if (this.cartProvider.storeType == 'main') {
this.router.navigate(["/app/tabs/shop/confirm-order"]);
} else {
this.router.navigate(["/shop/" + this.cartProvider.storeType + "/confirm-order"]);
}
}
}
getDiscounts() {
this.storage.get("token").then(async (token) => {
if (token) {
(await this.cartProvider.getDiscounts(token.access_token)).subscribe(
(discountList) => {
if (discountList["status"] == "success") {
this.discountList = discountList["discountList"];
this.cartProvider._serviceChargeEnabled = discountList['serviceChargeEnabled'];
this.cartProvider._serviceCharge = discountList['serviceCharge'];
if (this.cartProvider.productsCart.length <= 0) {
return;
}
let mainProduct, productsGift, productAdiscounting, productAdiscountingIndex, mainProductIndex, productAdiscountingIndexCombo, productWithDiscountValue;
for (let i = 0; i < this.discountList.length; i++) {
this.productGift = discountList["productGift"];
if (this.discountList[i].discount_type_id == 6) {
if (this.cartProvider.validateDateDiscount(this.discountList[i])) {
this.cartProvider.applyDiscount(this.discountList[i]);
//filtra los productos del descuento
let filterGiftProducts = this.productGift.filter((element) => element.discount_id == this.discountList[i].id);
for (let j = 0; j < filterGiftProducts.length; j++) {
// Me trae el producto con el que esta ligado el producto regalo
if (!filterGiftProducts[j].is_gift) {
mainProduct = this.cartProvider.productsCart.filter((element) => element.product_id == filterGiftProducts[j].product_id);
if (mainProduct) {
productsGift = filterGiftProducts.filter((element) => element.discount_id == filterGiftProducts[j].discount_id && element.is_gift == 1);
// Validamos que vengan el principal producto y el de regalo de this.cartProvider.productsCart
if (mainProduct.filter((element) => element.product_id == this.cartProvider.productsCart[j].product_id)) {
if (productsGift.filter((element) => element.product_id == this.cartProvider.productsCart[j].product_id)) {
for (let z = 0; z < mainProduct.length; z++) {
mainProductIndex = this.cartProvider.productsCart.findIndex((element) => element.product_id == mainProduct[z].product_id);
this.productosDescuentoGift.push(this.cartProvider.productsCart[mainProductIndex]);
}
for (let m = 0; m < productsGift.length; m++) {
productAdiscountingIndex = this.cartProvider.productsCart.findIndex((element) => element.product_id == productsGift[m].product_id);
this.productosDescuentoGift.push(this.cartProvider.productsCart[productAdiscountingIndex]);
}
//Elimina productos repetidos
for (let p = this.productosDescuentoGift.length - 1; p >= 0; p--) {
if (this.productosDescuentoGift.indexOf(this.productosDescuentoGift[p]) !== p) this.productosDescuentoGift.splice(p, 1);
}
// eliminar de la matriz si en realidad no está definido
this.productosDescuentoGift.forEach(function (val, i, arr) {
if (val === undefined) { arr.splice(i, 1) };
});
this.productosDescuentoGift.sort(function (a, b) { return a.price - b.price; });
let firstPosition = 0;
let equalPrices;
// let primerIndex = mainProduct.findIndex((element) =>element.price == this.productosDescuentoGift[firstPosition].price);
var ifIsUndefinedValue = this.productosDescuentoGift.filter(val => (val !== undefined) && (val !== null));
if (ifIsUndefinedValue.length != 0) {
// if(primerIndex != -1){}
equalPrices = this.productosDescuentoGift.every((element) => element.price == this.productosDescuentoGift[firstPosition].price);
if (equalPrices == true) {
let nonZeroDiscount = this.cartProvider.productsCart.map((element, index) => element.priceToDiscount && element.priceToDiscount != 0);
let checkProductList;
for (let t = 0; t < this.productosDescuentoGift.length; t++) {
checkProductList = this.cartProvider.productsCart.filter((element) => element.id == this.productosDescuentoGift[t].id);
}
if (this.productosDescuentoGift[j].quantity == 1 && this.productosDescuentoGift.length > 0) {
if (checkProductList.length == filterGiftProducts.length) {
if (nonZeroDiscount.indexOf(true) == -1) {
const randomIndex = Math.floor(Math.random() * this.productosDescuentoGift.length);
productAdiscounting = randomIndex;
let testIndex = this.cartProvider.productsCart.find((element) => element.id == this.productosDescuentoGift[productAdiscounting].id);
productWithDiscountValue = this.cartProvider.productsCart.findIndex((element) => element.product_id == testIndex.product_id);
let productGiftOrDiscount = this.cartProvider.productsCart[productWithDiscountValue].name;
let messageUser = this.discountList[i].message_to_user;
// setTimeout(() => {
// if(this.discountList[i].message_to_user != ""){
// this.toastMessageText = this.discountList[i].message_to_user;
// this.utilsService.presentToast(2500, "success", "top", this.toastMessageText);
// }
// }, 4500);
this.utilsService.presentAlertInfo(productGiftOrDiscount, '', messageUser);
// Aplicar el descuento
this.cartProvider.productsCart[productWithDiscountValue].priceToDiscount = testIndex.price; // Calcular para quitar el precio a una unidad en 0.
this.storage.set(
"priceToDiscount",
this.cartProvider.productsCart[productWithDiscountValue].priceToDiscount
);
this.cartProvider.calculatePrice();
}
}
} else {
if (this.productosDescuentoGift[j].quantity == 2 || this.productosDescuentoGift.length == 1) {
let soloDescuento = this.cartProvider.productsCart.every((element) => element.product_id == this.productosDescuentoGift[j].product_id);
if (soloDescuento == false) {
let verificar = this.productosDescuentoGift.every((element) => element.product_id == productsGift[j].product_id);
if (verificar = true) {
productAdiscountingIndex = this.productosDescuentoGift.findIndex((element) => element.product_id == productsGift[j].product_id);
this.cartProvider.productsCart[productAdiscountingIndex].priceToDiscount = this.cartProvider.productsCart[productAdiscountingIndex].price; // Calcular para quitar el precio a una unidad en 0.
this.storage.set(
"priceToDiscount",
this.cartProvider.productsCart[productAdiscountingIndex].priceToDiscount
);
this.cartProvider.calculatePrice();
}
} else {
this.cartProvider.calculatePrice();
}
} else {
this.cartProvider.calculatePrice();
}
}
} else {
// obtengo el menor precio de los productos que tiene descuento
let minimumPriceIndex = this.cartProvider.productsCart.find(e => e.price === Math.min(...this.productosDescuentoGift.map(f => f.price)));
let indexWithMinimumPrice = this.cartProvider.productsCart.findIndex((element) => element.id == minimumPriceIndex.id);
let minimumValueIndex = this.cartProvider.productsCart.findIndex((element) => element.price == this.cartProvider.productsCart[indexWithMinimumPrice].price);
this.cartProvider.productsCart[minimumValueIndex].priceToDiscount = this.cartProvider.productsCart[minimumValueIndex].price; // Calcular para quitar el precio a una unidad en 0.
this.storage.set(
"priceToDiscount",
this.cartProvider.productsCart[minimumValueIndex].priceToDiscount
);
this.cartProvider.calculatePrice();
}
}
}
}
}
}
}
}
} else if (this.discountList[i].discount_type_id == 5) {
if (this.cartProvider.validateDateDiscount(this.discountList[i])) {
this.cartProvider.applyDiscount(this.discountList[i]);
let filterCombosProducts = this.productGift.filter((element) => element.discount_id == this.discountList[i].id);
for (let j = 0; j < filterCombosProducts.length; j++) {
// Me trae el producto con el que esta ligado el producto regalo
if (!filterCombosProducts[j].is_gift) {
mainProduct = this.cartProvider.productsCart.find((element) => element.product_id == filterCombosProducts[j].product_id);
if (mainProduct) {
productsGift = filterCombosProducts.filter((element) => element.discount_id == filterCombosProducts[j].discount_id && element.is_gift == 1);
if (productsGift) {
//Flitro
let arrayFiltrado = filterCombosProducts.filter(element2 =>
!this.cartProvider.productsCart.some(element =>
element2.product_id == element.product_id
)
);
if (arrayFiltrado.length == 0) {
setTimeout(() => {
if (this.discountList[i].message_to_user != "") {
this.toastMessageText = this.discountList[i].message_to_user;
this.utilsService.presentToast(2500, "success", "top", this.toastMessageText);
}
}, 4500);
if (this.cartProvider.productsCart.find((element) => element.product_id == mainProduct.product_id) && this.cartProvider.productsCart.findIndex((element) => element.product_id == productsGift[j].product_id) != -1) {
this.productosDescuentoGift.push(mainProduct);
for (let k = 0; k < productsGift.length; k++) {
productAdiscountingIndexCombo = this.cartProvider.productsCart.findIndex((element) => element.product_id == productsGift[k].product_id);
this.productosDescuentoGift.push(this.cartProvider.productsCart[productAdiscountingIndexCombo]);
this.cartProvider.productsCart[productAdiscountingIndexCombo].discountpercentageCombo = this.discountList[i].percentage_discount;
}
//Validamos que si viene un producto con descuento se lo quite.
if (this.cartProvider.productsCart.find(element => element.priceToDiscount !== 0)) {
let RemoveDiscountValue = this.cartProvider.productsCart.findIndex(element => element.priceToDiscount !== 0);
this.cartProvider.productsCart[RemoveDiscountValue].priceToDiscount = 0
this.storage.set(
"priceToDiscount2",
this.cartProvider.productsCart[RemoveDiscountValue].priceToDiscount
);
}
// eliminar de la matriz si en realidad no está definido
this.productosDescuentoGift.forEach(function (val, i, arr) {
if (val === undefined) { arr.splice(i, 1) };
});
//Elimina productos repetidos
for (let p = this.productosDescuentoGift.length - 1; p >= 0; p--) {
if (this.productosDescuentoGift.indexOf(this.productosDescuentoGift[p]) !== p) this.productosDescuentoGift.splice(p, 1);
}
this.storage.set("productsCartCombo", this.productosDescuentoGift);
if (this.productosDescuentoGift.findIndex((element) => element.product_id == mainProduct.product_id) != -1) {
productAdiscounting = this.cartProvider.productsCart.findIndex((element) => element.product_id == mainProduct.product_id);
this.cartProvider.productsCart[productAdiscounting].pivotProduct = 1; // producto pivote.
this.cartProvider.productsCart[productAdiscounting].discountpercentageCombo = this.discountList[i].percentage_discount;
var obj = {
"pivotProduct":
this.cartProvider.productsCart[productAdiscounting].pivotProduct,
"discountpercentageCombo":
this.cartProvider.productsCart[productAdiscounting].discountpercentageCombo
}
this.storage.set(
"discountTypes", obj
);
this.cartProvider.calculatePrice();
}
} else {
this.cartProvider.calculatePrice();
}
} else {
productAdiscountingIndexCombo = this.cartProvider.productsCart.findIndex((element) => element.product_id != productsGift[j].product_id);
if (productAdiscountingIndexCombo != -1) {
this.cartProvider.productsCart[productAdiscountingIndexCombo].discountpercentageCombo = 0;
}
this.cartProvider.calculatePrice();
}
}
} else {
this.cartProvider.calculatePrice();
}
}
}
}
}
}
this.cartProvider.calculatePrice();
} else {
this.cartProvider.calculatePrice();
}
},
(error) => {
console.log("error getDiscounts", error);
this.discountList = [];
}
);
}
});
}
validateShoppingCartProducts(confirm: boolean = false) {
var me = this;
this.utilsService.presentLoading(this.translateService.instant("all.validating")).then(async () => {
let productsCart = [], productsAttributesCart = [];
for (let i = 0; i < this.cartProvider.productsCart.length; i++) {
let productDetail = {};
let product = this.cartProvider.productsCart[i];
if (product.product_attributes_selected && product.product_attributes_selected[0]) {
productDetail = {
product_id: product.product_attributes_selected[0].product_id,
attribute_id: product.product_attributes_selected[0].attribute_id,
value: product.product_attributes_selected[0].value,
quantity: product.quantity,
item: i,
oldPrice: product.priceTotal + product.product_attributes_selected[0].price_additional,
}
productsAttributesCart.push(productDetail);
} else {
productDetail = {
id: product.id,
quantity: product.quantity,
item: i,
oldPrice: product.priceTotal,
}
productsCart.push(productDetail);
}
}
let data = {
productsAttributesCart: productsAttributesCart,
productsCart: productsCart
};
me.validConfirmPurchase = true;
this.storage.get("token").then(async (token) => {
if (token) {
(await this.cartProvider.productValidationCart(data, token.access_token)).subscribe(
(resp: any) => {
resp.forEach(function (product: any) {
me.cartProvider.productsCart[product.item].availableStock = product.availableStock;
me.cartProvider.productsCart[product.item].availablePrice = product.availablePrice;
me.cartProvider.productsCart[product.item].validationMessage = product.validationMessage;
me.cartProvider.productsCart[product.item].newPriceAfterSpecialPriceTag = 0;
me.cartProvider.productsCart[product.item].newPriceAfterFlash = 0;
me.cartProvider.productsCart[product.item].newPriceAfterDiscount = 0;
me.cartProvider.productsCart[product.item].newPrice = 0;
if (product.priceAfterSpecialPriceTag)
me.cartProvider.productsCart[product.item].newPriceAfterSpecialPriceTag = product.priceAfterSpecialPriceTag;
else if (product.priceAfterFlash)
me.cartProvider.productsCart[product.item].newPriceAfterFlash = product.priceAfterFlash;
else if (product.priceAfterDiscount)
me.cartProvider.productsCart[product.item].newPriceAfterDiscount = product.priceAfterDiscount;
else
me.cartProvider.productsCart[product.item].newPrice = product.newPrice;
if (product.availableStock == false || product.availablePrice == false) {
me.validConfirmPurchase = false;
}
});
this.utilsService.dismissLoading();
if (!me.validConfirmPurchase) {
this.utilsService.presentAlertInfo(this.translateService.instant("TITLE_NOVELTY_BUY"), '', this.translateService.instant("MESSAGE_NOVELTY_BUY"));
} else if (confirm) {
this.confirm();
}
},
(error) => {
console.log("error productValidationCart", error);
me.validConfirmPurchase = false;
this.utilsService.dismissLoading();
this.utilsService.presentAlertInfo(this.translateService.instant("TITLE_NOVELTY_BUY"), '', this.translateService.instant("MESSAGE_NOVELTY_BUY"));
});
}
});
});
}
}