File: /var/www/vhost/disk-apps/pwa.sports-crowd.com/src/app/pages/confirm-order/confirm-order.ts
import { LealService } from './../../services/leal.service';
import { Component, OnInit } from "@angular/core";
import { CurrencyPipe } from "@angular/common";
import { TranslateService } from "@ngx-translate/core";
import { AlertController, ModalController, IonRouterOutlet } from "@ionic/angular";
import { StorageService } from "../../services/storage.service";
import { NavigationStart, Router } from "@angular/router";
import { ModalUpdateProfilePage } from "../modal-update-profile/modal-update-profile.page";
import { UserService } from "../../services/user.service";
import { CartService } from "../../services/cart.service";
import { UtilsService } from "../../services/utils.service";
import { AnalyticsFacebookService } from "../../services/analytics-facebook.service";
@Component({
selector: "page-confirm-order",
templateUrl: "confirm-order.html",
styleUrls: ["./confirm-order.scss"],
})
export class ConfirmOrderPage implements OnInit {
listAddressUser: any;
addressUserLastUsed: any;
infoUser: any;
infoConfirmOrder: any = {
address: "",
wayPay: "",
cellphone: "",
observations: "",
point_sale_id: "",
};
messageText: any;
orderInfo: any;
effectivePaymentWayPay: any;
effectivePayment: any;
statusSendCreateOrder: boolean = false;
pointSale: boolean = false;
hourInitial: any;
hourEnd: any;
listCard: any;
paymentTdc: any;
discountList: any = [];
discountDelivery: any = [];
couponList: any = [];
campaignList: any = [];
categoryList: any = [];
percentageList: any = [];
pointSalesList: any = [];
old_price_domicile: any = 0;
pco_value: any = 0.15;
pco_quantity: any = 0;
pco_quantity_max: any = 1000;
price_using_pco: any;
params: any;
sucursalSelected: any = null;
selectablePaymentTypes: any = [];
constructor(
private storage: StorageService,
public cartProvider: CartService,
public alertCtrl: AlertController,
private translateService: TranslateService,
private currencyPipe: CurrencyPipe,
public modalCtrl: ModalController,
public userProvider: UserService,
public utilsService: UtilsService,
private router: Router,
private routerOutlet: IonRouterOutlet,
private analyticsFacebookService: AnalyticsFacebookService,
private lealService: LealService,
) {
// traduccion textos
this.translateService
.get([
"TITLE_ALERT_CONFIRM_ORDER",
"TEXT_ALERT_CONFIRM_ORDER_ADDRESS",
"TEXT_ALERT_CONFIRM_ORDER_WAYPAY",
"TEXT_ALERT_CONFIRM_ORDER_CELLPHONE",
"TEXT_ALERT_CONFIRM_ORDER_EFFECTIVE_PAYMENT",
"TEXT_ALERT_CONFIRM_ORDER_PAYMENT_TDC",
"TEXT_ALERT_CONFIRM_ORDER_PAYMENT_TDC2",
"TEXT_TOAST_OUT_OF_TIME",
"TEXT1_ALERT_COUPON",
"TEXT2_ALERT_COUPON",
"TEXT3_ALERT_COUPON",
"TEXT4_ALERT_COUPON",
"TEXT5_ALERT_COUPON",
"TEXT6_ALERT_COUPON",
"TEXT7_ALERT_COUPON",
"OTP_ALERT_MESSAGE"
])
.subscribe((values) => {
this.messageText = {
titleAlertConfirmOrder: values.TITLE_ALERT_CONFIRM_ORDER,
textAlertConfirmOrderAddress: values.TEXT_ALERT_CONFIRM_ORDER_ADDRESS,
textAlertConfirmOrderWayPay: values.TEXT_ALERT_CONFIRM_ORDER_WAYPAY,
textAlertConfirmOrderCellPhone:
values.TEXT_ALERT_CONFIRM_ORDER_CELLPHONE,
textAlertConfirmOrderEffevtivePayment:
values.TEXT_ALERT_CONFIRM_ORDER_EFFECTIVE_PAYMENT,
textAlertConfirmOrderPaymentTdc:
values.TEXT_ALERT_CONFIRM_ORDER_PAYMENT_TDC,
textAlertConfirmOrderPaymentTdc2:
values.TEXT_ALERT_CONFIRM_ORDER_PAYMENT_TDC2,
textToastOutofTime: values.TEXT_TOAST_OUT_OF_TIME,
text1AlertCoupon: values.TEXT1_ALERT_COUPON,
text2AlertCoupon: values.TEXT2_ALERT_COUPON,
text3AlertCoupon: values.TEXT3_ALERT_COUPON,
text4AlertCoupon: values.TEXT4_ALERT_COUPON,
text5AlertCoupon: values.TEXT5_ALERT_COUPON,
text6AlertCoupon: values.TEXT6_ALERT_COUPON,
text7AlertCoupon: values.TEXT7_ALERT_COUPON,
OTP_ALERT_MESSAGE: values.OTP_ALERT_MESSAGE
};
});
router.events.subscribe((event: NavigationStart) => {
if (event.navigationTrigger === 'popstate' && event.url.includes('confirm-order')) {
setTimeout(() => {
this.getInfoAddressLastUsed();
}, 500);
}
});
}
ngOnInit() {
var params = {};
params["CONTENT"] = this.cartProvider.productsCart;
params["NUM_ITEMS"] = this.cartProvider.productsCart.length;
params["CURRENCY"] = "COP";
this.analyticsFacebookService.createLogEvent(
"EVENT_NAME_INITIATED_CHECKOUT",
params,
this.cartProvider._total
);
this.price_using_pco = this.cartProvider._subtotal;
this.pco_quantity_max = this.price_using_pco * this.pco_value;
this.selectablePaymentTypes = this.cartProvider._paymentTypes;
// this.selectablePaymentTypes = this.cartProvider._paymentTypes.filter(paymentType => paymentType.id != 6 || (paymentType == 6 && this.pco_quantity_max >= this.cartProvider._total))
}
ionViewDidLoad() { }
ionViewWillEnter() {
this.infoUser = this.userProvider._infoUser;
this.infoConfirmOrder.cellphone = this.infoUser.phone;
this.getInfoAddressLastUsed();
this.storage.get("parameters").then((parameters) => {
if (parameters) {
this.params = parameters;
if (this.validateServiceHour(parameters)) {
this.utilsService.presentToast(
4000,
"warning",
"top",
this.messageText.textToastOutofTime +
this.hourInitial +
" y " +
this.hourEnd
);
}
}
});
this.storage.get("sucursalSelected").then((sucursalSelected) => {
if (sucursalSelected) {
this.sucursalSelected = sucursalSelected.id;
}
});
if (this.paymentTdc || this.infoConfirmOrder.wayPay == 4) {
this.changeTypePayment(4);
}
this.cartProvider.calculatePrice();
this.resetDiscount();
}
ionViewWillLeave() {
if (this.pointSale) {
this.cartProvider.getPriceDomicile();
} else {
this.cartProvider.calculatePrice();
}
}
resetDiscount() {
this.cartProvider._activeDiscount = false;
this.cartProvider._discountDelivery = 0;
this.cartProvider._discount = 0;
this.cartProvider._discountsApplied = [];
this.cartProvider._listShowToast = [];
this.couponList = [];
this.campaignList = [];
this.discountDelivery = [];
this.categoryList = [];
this.getDiscounts();
}
rangeChange(event: any) {
this.pco_quantity = event.detail.value;
let equivalence =
(this.cartProvider._subtotal * this.pco_quantity) / this.pco_quantity_max;
this.price_using_pco = this.cartProvider._subtotal - equivalence;
}
pointSaleChange() {
if (this.pointSale) {
this.cartProvider._priceDomicile = 0;
this.cartProvider.calculatePrice();
this.getPointsSale();
} else {
this.cartProvider.getPriceDomicile();
}
setTimeout(() => {
this.resetDiscount();
}, 500);
}
getPointsSale() {
this.storage.get("token").then(async (token) => {
if (token) {
(await this.userProvider.getPointsSale(token.access_token)).subscribe(
(resp: any) => {
if (resp["status"] == "success") {
this.pointSalesList = resp["d"];
}
},
(error) => {
console.log("error getPointsSale: ", error);
}
);
}
});
}
addNewAddress() {
this.router.navigate(["/address/confirmOrder/true"]);
}
addNewCard() {
this.router.navigate(["/app/tabs/settings/card-add"]);
}
validateServiceHour(parameters) {
let outOfRange = true;
let date = new Date();
let dayNumber = date.getDay();
if (dayNumber > 0) {
if (dayNumber == 6) {
this.hourInitial = this.formartHour(parameters.holiday_start_time);
this.hourEnd = this.formartHour(parameters.holiday_final_time);
} else {
this.hourInitial = this.formartHour(parameters.business_start_time);
this.hourEnd = this.formartHour(parameters.business_final_time);
}
let hourStart = parameters.business_start_time.split(":")[0];
let minuteStart = parameters.business_start_time.split(":")[1];
let hourEnd = parameters.business_final_time.split(":")[0];
let minuteEnd = parameters.business_final_time.split(":")[1];
if (
date.getHours() > Number(hourStart) &&
date.getHours() < Number(hourEnd)
) {
outOfRange = false;
}
if (
date.getHours() == Number(hourStart) &&
date.getMinutes() >= Number(minuteStart)
) {
outOfRange = false;
}
if (
date.getHours() == Number(hourEnd) &&
date.getMinutes() <= Number(minuteEnd)
) {
outOfRange = false;
}
return outOfRange;
} else {
this.hourInitial = this.formartHour(parameters.business_start_time);
this.hourEnd = this.formartHour(parameters.business_final_time);
let hourStart = parameters.holiday_start_time.split(":")[0];
let minuteStart = parameters.holiday_start_time.split(":")[1];
let hourEnd = parameters.holiday_final_time.split(":")[0];
let minuteEnd = parameters.holiday_final_time.split(":")[1];
if (
date.getHours() > Number(hourStart) &&
date.getHours() < Number(hourEnd)
) {
outOfRange = false;
}
if (
date.getHours() == Number(hourStart) &&
date.getMinutes() >= Number(minuteStart)
) {
outOfRange = false;
}
if (
date.getHours() == Number(hourEnd) &&
date.getMinutes() <= Number(minuteEnd)
) {
outOfRange = false;
}
return outOfRange;
}
}
formartHour(hour) {
var newHour = hour.split(":");
newHour[0] = Number(newHour[0]);
if (newHour[0] > 12) {
newHour[0] -= 12;
}
var textAmPm = "AM";
if (hour.split(":")[0] > 11) {
textAmPm = "PM";
}
return newHour[0] + ":" + newHour[1] + " " + textAmPm;
}
getCurrency(amount: number) {
return this.currencyPipe.transform(amount, "USD", "symbol", "1.0-0");
}
onPriceUp(evt) {
this.effectivePayment = evt.replace(/[^0-9.]/g, "");
this.effectivePaymentWayPay = this.getCurrency(this.effectivePayment);
}
changeAddress(address_id) {
for (let i = 0; i < this.listAddressUser.length; i++) {
if (this.listAddressUser[i].id === address_id) {
this.addressUserLastUsed = this.listAddressUser[i];
this.cartProvider.updateAddressPrice(this.addressUserLastUsed);
}
}
}
changeTypePayment(id) {
if (id == 4) {
this.listCard = [];
this.storage.get("token").then((token) => {
if (token) {
this.utilsService
.presentLoading(this.translateService.instant("all.loading"))
.then(async () => {
(await this.userProvider.listCreditCard(token.access_token)).subscribe(
(resp: any) => {
this.utilsService.dismissLoading();
for (let i = 0; i < resp.length; i++) {
if (resp[i].verified) {
resp[i].obfuscated_number = resp[
i
].obfuscated_number.substring(10, 19);
this.listCard.push(resp[i]);
if (resp[i].current) {
this.paymentTdc = resp[i].id;
}
}
}
},
(error) => {
this.utilsService.dismissLoading();
}
);
});
}
});
}
if (id != 6) {
this.price_using_pco = this.cartProvider._subtotal;
this.pco_quantity = 0;
}
}
changeDefaultCard(id) {
if (id && id != 0 && this.listCard.length > 1) {
this.storage.get("token").then((token) => {
if (token) {
this.utilsService.presentLoading(
this.translateService.instant("all.loading")
);
this.userProvider.selectDefaultCard(id, token.access_token).subscribe(
(resp) => {
this.utilsService.dismissLoading();
this.changeTypePayment(4);
},
(error) => {
this.utilsService.dismissLoading();
}
);
}
});
}
}
async alertsValidations(title, message) {
const alert = await this.alertCtrl.create({
header: title,
message: message,
buttons: ["OK"],
});
await alert.present();
}
async presentModalUpdateProfile() {
const modal = await this.modalCtrl.create({
component: ModalUpdateProfilePage,
swipeToClose: true,
presentingElement: this.routerOutlet.nativeEl,
componentProps: { accountUser: this.userProvider._infoUser },
});
await modal.present();
await modal.onWillDismiss().then((resp) => {
this.infoUser = this.userProvider._infoUser;
this.infoConfirmOrder.cellphone = this.infoUser.phone;
});
}
validatedConfirmOrder(formConfirmOrder) {
if (!this.pointSale && !formConfirmOrder.controls.address.valid) {
this.alertsValidations(
this.messageText.titleAlertConfirmOrder,
this.messageText.textAlertConfirmOrderAddress
);
return;
}
if (this.pointSale && !formConfirmOrder.controls.point_sale_id.valid) {
this.alertsValidations(
this.messageText.titleAlertConfirmOrder,
this.translateService.instant("TEXT_ALERT_CONFIRM_ORDER_POINT")
);
return;
}
if (!formConfirmOrder.controls.wayPay.valid) {
this.alertsValidations(
this.messageText.titleAlertConfirmOrder,
this.messageText.textAlertConfirmOrderWayPay
);
return;
}
if (
!this.userProvider._infoUser.document ||
this.userProvider._infoUser.document == "" ||
this.userProvider._infoUser.document == " "
) {
this.presentModalUpdateProfile();
return;
}
if (
!this.userProvider._infoUser.user_info.dob ||
this.userProvider._infoUser.user_info.dob == "" ||
this.userProvider._infoUser.user_info.dob == " "
) {
this.presentModalUpdateProfile();
return;
}
if (!formConfirmOrder.controls.cellphone.valid) {
this.alertsValidations(
this.messageText.titleAlertConfirmOrder,
this.messageText.textAlertConfirmOrderCellPhone
);
return;
}
if (
formConfirmOrder.controls.effectivePayment &&
!formConfirmOrder.controls.effectivePayment.valid
) {
this.alertsValidations(
this.messageText.titleAlertConfirmOrder,
this.messageText.textAlertConfirmOrderEffevtivePayment
);
return;
}
if (
formConfirmOrder.value.effectivePayment &&
!Number.isInteger(formConfirmOrder.value.effectivePayment)
) {
let replace1 = formConfirmOrder.value.effectivePayment.replace(/,/g, "");
let replace2 = parseInt(replace1.replace("$", ""));
formConfirmOrder.value.effectivePayment = replace2;
}
if (formConfirmOrder.value.wayPay === 4 && !this.paymentTdc) {
this.alertsValidations(
this.messageText.titleAlertConfirmOrder,
this.messageText.textAlertConfirmOrderPaymentTdc
);
return;
}
this.storage.get("infoEndVersion").then((infoEndVersion) => {
if (
infoEndVersion &&
infoEndVersion.end_version_home &&
infoEndVersion.end_version_home != null
) {
this.modalEndVersion(infoEndVersion);
} else {
this.storage.get("token").then(async (token) => {
if (token) {
this.statusSendCreateOrder = true;
this.utilsService.presentLoading(
this.translateService.instant("all.loading")
);
if (formConfirmOrder.value.wayPay === 4 && this.paymentTdc) {
(await this.userProvider.generateOrderPaymentTDC(this.cartProvider._total, token.access_token)).subscribe(
(result) => {
// console.log("result: ", result);
if (result["r"]) {
this.generateOrder(formConfirmOrder, token, result["d"]);
}
},
(error) => {
// console.log("error generateOrderPayment: ", error);
this.statusSendCreateOrder = false;
this.utilsService.dismissLoading();
this.utilsService.presentToast(
3000,
"danger",
"top",
this.messageText.textAlertConfirmOrderPaymentTdc2
);
}
);
} else if (formConfirmOrder.value.wayPay === 6) {
this.generateOrderPaymentCoins(formConfirmOrder, token);
} else {
this.generateOrder(formConfirmOrder, token);
}
}
});
}
});
}
async modalEndVersion(infoEndVersion) {
let params = {
image_end_version: infoEndVersion.image_end_version,
text_end_version: infoEndVersion.text_end_version,
link_end_version: infoEndVersion.link_end_version,
};
let addModalEndVersion = await this.modalCtrl.create({
component: "EndVersionPage",
swipeToClose: true,
presentingElement: this.routerOutlet.nativeEl,
componentProps: params,
});
await addModalEndVersion.present();
}
generateOrder(formConfirmOrder, token, paymentHistory_id?) {
var wayPay = formConfirmOrder.value.wayPay;
this.storage.get("productsNotFound").then(async (productsNotFound) => {
let dataProductsNotFound = null;
if (productsNotFound) {
dataProductsNotFound = productsNotFound;
} else {
dataProductsNotFound = null;
}
this.orderInfo = {
products: this.cartProvider.productsCart,
confirmOrder: formConfirmOrder.value,
subtotal: this.cartProvider._subtotal,
serviceCharge: this.cartProvider._serviceCharge,
priceDomicile: this.cartProvider._priceDomicile,
total: this.cartProvider._total,
discount: this.cartProvider._discount,
discountDelivery: this.cartProvider._discountDelivery,
productsNotFound: dataProductsNotFound,
order_type_id: 5,
activeDiscount: this.cartProvider._activeDiscount,
discountsApplied: this.cartProvider._discountsApplied,
paymentHistory_id: paymentHistory_id,
sucursal: this.sucursalSelected,
storeType: this.cartProvider.storeType,
currentAcademyUserId: this.cartProvider.currentAcademyUserId
};
let data = {
data: this.orderInfo,
};
(await this.cartProvider.generateOrder(data, token.access_token)).subscribe(
(resp) => {
this.statusSendCreateOrder = false;
this.utilsService.dismissLoading();
if (resp["status"] == "success") {
var params = {};
params["CONTENT"] = this.cartProvider.productsCart;
params["NUM_ITEMS"] = this.cartProvider.productsCart.length;
params["CURRENCY"] = "COP";
this.analyticsFacebookService.createLogEvent("EVENT_NAME_PURCHASED", params, this.cartProvider._total);
this.storage.remove("productsNotFound");
if (this.cartProvider.storeType != 'main') {
this.router.navigate(["/shop/" + this.cartProvider.storeType]);
} else {
this.router.navigate(["/shop"]);
}
setTimeout(() => {
this.cartProvider.deleteAllProductsCart();
// Gateway
if (wayPay == 5) {
this.utilsService.presentToast(6000, "success", "top", this.translateService.instant("order.msg_order_confirm", { code: resp['order']['code'] }), true);
this.router.navigate(["/payment-gateway-selection"], { state: { orderId: resp["order_id"] } });
} else {
this.router.navigate(["/app/tabs/settings/order/" + resp["order_id"] + "/confirmOrder",]);
}
}, 500);
} else {
this.utilsService.presentToast(5000, "danger", "top", resp["m"]);
}
},
(error) => {
this.utilsService.presentToast(2000, "danger", "top", "Hubo un error, intenta mas tarde.");
console.log("error generateOrder", error);
this.utilsService.dismissLoading();
this.statusSendCreateOrder = false;
}
);
});
}
generateOrderPaymentCoins(formConfirmOrder, token, paymentHistory_id?) {
this.storage.get("productsNotFound").then((productsNotFound) => {
let dataProductsNotFound = null;
if (productsNotFound) {
dataProductsNotFound = productsNotFound;
} else {
dataProductsNotFound = null;
}
this.orderInfo = {
products: this.cartProvider.productsCart,
confirmOrder: formConfirmOrder.value,
subtotal: this.cartProvider._subtotal,
priceDomicile: this.cartProvider._priceDomicile,
total: this.cartProvider._total,
discount: this.cartProvider._discount,
discountDelivery: this.cartProvider._discountDelivery,
productsNotFound: dataProductsNotFound,
order_type_id: 6,
activeDiscount: this.cartProvider._activeDiscount,
discountsApplied: this.cartProvider._discountsApplied,
paymentHistory_id: paymentHistory_id,
sucursal: this.sucursalSelected,
storeType: this.cartProvider.storeType
};
this.storage.get("infoUser").then(async (infoUser) => {
if (infoUser) {
let data = {
userInfo: this.infoUser,
order: {
data: this.orderInfo,
},
}
; (await this.lealService.generateOrderPaymentCoins(token.access_token, data)).subscribe(
(resp) => {
this.statusSendCreateOrder = false;
this.utilsService.dismissLoading();
if (resp["status"] == "success") {
var params = {};
params["CONTENT"] = this.cartProvider.productsCart;
params["NUM_ITEMS"] = this.cartProvider.productsCart.length;
params["CURRENCY"] = "COP";
this.analyticsFacebookService.createLogEvent(
"EVENT_NAME_PURCHASED",
params,
this.cartProvider._total
);
this.storage.remove("productsNotFound");
this.router.navigate(["/app/tabs/shop"]);
setTimeout(() => {
this.cartProvider.deleteAllProductsCart();
this.router.navigate(["/app/tabs/settings/order/" + resp["order_id"] + "/confirmOrder"]);
}, 500);
} else {
this.utilsService.presentToast(5000, "danger", "top", resp["m"] != null ? resp["m"] : resp["message"]);
}
},
(error) => {
this.utilsService.presentToast(2000, "danger", "top", "Hubo un error, intenta mas tarde.");
console.log("error generateOrder", error);
this.utilsService.dismissLoading();
this.statusSendCreateOrder = false;
}
);
}
});
});
}
getDiscounts() {
this.utilsService.presentLoading(
this.translateService.instant("all.loading")
);
this.storage.get("token").then(async (token) => {
if (token) {
(await this.cartProvider.getDiscounts(token.access_token)).subscribe(
(discountList) => {
this.utilsService.dismissLoading();
if (discountList["status"] == "success") {
this.discountList = discountList["discountList"];
for (let i = 0; i < this.discountList.length; i++) {
if (this.discountList[i].discount_type_id == 4) {
this.couponList.push(this.discountList[i]);
} else if (this.discountList[i].discount_type_id == 3) {
this.campaignList.push(this.discountList[i]);
} else if (this.discountList[i].discount_type_id == 1) {
this.discountDelivery.push(this.discountList[i]);
} else if (this.discountList[i].discount_type_id == 10) {
this.categoryList.push(this.discountList[i]);
} else if (this.discountList[i].discount_type_id == 7) {
this.percentageList.push(this.discountList[i]);
}
}
this.validateDiscount();
}
},
(error) => {
console.log("error generateOrder", error);
this.utilsService.dismissLoading();
this.discountList = [];
}
);
}
});
}
async validateCoupon() {
const prompt = await this.alertCtrl.create({
header: this.messageText.text1AlertCoupon,
inputs: [
{
name: "couponUser",
placeholder: this.messageText.text2AlertCoupon,
},
],
buttons: [
{
text: "Cancelar",
handler: (data) => { },
},
{
text: this.messageText.text3AlertCoupon,
handler: (data) => {
if (data.couponUser.trim() != "") {
let couponValid = false;
for (let i = 0; i < this.couponList.length; i++) {
if (this.couponList[i].code_coupon === data.couponUser.trim()) {
couponValid = true;
if (
this.couponList[i].discountOrderUsers &&
!this.couponList[i].is_multiple_redeem
) {
this.utilsService.presentToast(
4000,
"warning",
"top",
this.messageText.text4AlertCoupon
);
} else if (
this.cartProvider._subtotal >=
this.couponList[i].value_for_win
) {
this.cartProvider.applyDiscount(this.couponList[i]);
} else {
let message =
this.messageText.text6AlertCoupon +
this.couponList[i].name +
this.messageText.text6AlertCoupon +
this.couponList[i].value_for_win;
this.utilsService.presentToast(
4000,
"warning",
"top",
message
);
}
break;
}
}
if (!couponValid) {
this.utilsService.presentToast(
4000,
"warning",
"top",
this.messageText.text5AlertCoupon
);
}
}
},
},
],
});
await prompt.present();
}
async showOTPCodeAlert() {
const prompt = await this.alertCtrl.create({
message: this.messageText.OTP_ALERT_MESSAGE,
inputs: [
{
name: "couponUser",
placeholder: this.messageText.text2AlertCoupon,
},
],
buttons: [
{
text: "Cancelar",
handler: (data) => { },
},
{
text: "Reenviar",
handler: (data) => { },
},
{
text: this.messageText.text3AlertCoupon,
handler: (data) => {
if (data.couponUser.trim() != "") {
let couponValid = false;
for (let i = 0; i < this.couponList.length; i++) {
if (this.couponList[i].code_coupon === data.couponUser.trim()) {
couponValid = true;
if (this.couponList[i].discountOrderUsers && !this.couponList[i].is_multiple_redeem) {
this.utilsService.presentToast(4000, "warning", "top", this.messageText.text4AlertCoupon);
} else if (this.cartProvider._subtotal >= this.couponList[i].value_for_win) {
this.cartProvider.applyDiscount(this.couponList[i]);
} else {
let message =
this.messageText.text6AlertCoupon +
this.couponList[i].name +
this.messageText.text6AlertCoupon +
this.couponList[i].value_for_win;
this.utilsService.presentToast(4000, "warning", "top", message);
}
break;
}
}
if (!couponValid) {
this.utilsService.presentToast(4000, "warning", "top", this.messageText.text5AlertCoupon);
}
}
},
},
],
});
await prompt.present();
}
async validateOTPCode() {
this.storage.get("infoUser").then((infoUser) => {
if (infoUser) {
this.storage.get("token").then(async (token) => {
if (token) {
this.utilsService.presentLoading(this.translateService.instant("all.loading"));
let data = {
uid: this.infoUser.coin_uid,
valor: this.cartProvider._subtotal,
}
; (await this.lealService.generateOTP(token.access_token, data)).subscribe(
(resp) => {
console.log(resp); // PRESENTAR DATOS
},
(error) => {
console.log("Error coins", error);
this.utilsService.dismissLoading();
}
);
}
});
}
});
}
validateDiscount() {
if (this.discountDelivery.length) {
for (let i = 0; i < this.discountDelivery.length; i++) {
if (this.discountDelivery[i].discount_global_shipping) {
let currentDiscountDelivery =
(this.cartProvider._priceDomicile *
this.discountDelivery[i].discount_global_shipping) /
100;
this.cartProvider._discountDelivery = currentDiscountDelivery;
this.cartProvider._priceDomicile -= currentDiscountDelivery;
this.cartProvider._total -= currentDiscountDelivery;
let newDiscount = {
discount_id: this.discountDelivery[i].id,
discount_type_id: this.discountDelivery[i].discount_type_id,
};
this.cartProvider._discountsApplied.push(newDiscount);
this.cartProvider._activeDiscount = true;
} else if (
this.discountDelivery[i].discountOrderUsers &&
this.discountDelivery[i].discountOrderUsers.limit_discount
) {
if (this.discountDelivery[i].price_discount) {
this.cartProvider._discountDelivery =
this.discountDelivery[i].price_discount;
this.cartProvider._priceDomicile -=
this.discountDelivery[i].price_discount;
this.cartProvider._total -= this.discountDelivery[i].price_discount;
} else {
let currentDiscountDelivery =
(this.cartProvider._priceDomicile *
this.discountDelivery[i].percentage_discount) /
100;
this.cartProvider._discountDelivery = currentDiscountDelivery;
this.cartProvider._priceDomicile -= currentDiscountDelivery;
this.cartProvider._total -= currentDiscountDelivery;
}
let newDiscount = {
discount_id: this.discountDelivery[i].id,
discount_type_id: this.discountDelivery[i].discount_type_id,
};
this.cartProvider._discountsApplied.push(newDiscount);
this.cartProvider._activeDiscount = true;
}
}
}
if (this.campaignList.length) {
for (let i = 0; i < this.campaignList.length; i++) {
if (this.cartProvider._subtotal >= this.campaignList[i].value_for_win) {
this.cartProvider.applyDiscount(this.campaignList[i]);
} else if (
this.cartProvider.validateDateDiscount(this.campaignList[i])
) {
this.cartProvider.toatDiscountApply(
this.messageText.text6AlertCoupon +
this.campaignList[i].name +
this.messageText.text7AlertCoupon +
this.campaignList[i].value_for_win
);
}
}
}
if (this.categoryList.length) {
this.storage.get("productsCart").then((productsCart) => {
if (productsCart) {
for (let i = 0; i < this.categoryList.length; i++) {
let sumTotalProductsCategory = 0;
let sumDiscountApplyProduct = 0;
let sumDiscountApplyDelivery = 0;
for (let j = 0; j < productsCart.length; j++) {
if (
this.categoryList[i].category_id === productsCart[j].category.id
) {
sumTotalProductsCategory +=
productsCart[j].price * productsCart[j].quantity;
if (this.categoryList[i].apply_value) {
if (this.categoryList[i].percentage_discount) {
sumDiscountApplyProduct +=
(productsCart[j].price *
productsCart[j].quantity *
this.categoryList[i].percentage_discount) /
100;
} else {
sumDiscountApplyProduct +=
this.categoryList[i].price_discount *
productsCart[j].quantity;
}
} else if (
!this.categoryList[i].apply_value &&
sumDiscountApplyDelivery === 0
) {
if (this.categoryList[i].percentage_discount) {
sumDiscountApplyDelivery +=
(this.cartProvider._priceDomicile *
this.categoryList[i].percentage_discount) /
100;
} else {
sumDiscountApplyDelivery +=
this.categoryList[i].price_discount;
}
}
}
}
if (
sumTotalProductsCategory >= this.categoryList[i].value_for_win
) {
if (sumDiscountApplyProduct) {
this.cartProvider._discount += sumDiscountApplyProduct;
this.cartProvider._total -= sumDiscountApplyProduct;
let newDiscount = {
discount_id: this.categoryList[i].id,
discount_type_id: this.categoryList[i].discount_type_id,
};
this.cartProvider._activeDiscount = true;
this.cartProvider._discountsApplied.push(newDiscount);
this.cartProvider.toatDiscountApply(
this.categoryList[i].message_to_user
);
} else if (sumDiscountApplyDelivery) {
this.cartProvider._discountDelivery = sumDiscountApplyDelivery;
this.cartProvider._priceDomicile -= sumDiscountApplyDelivery;
this.cartProvider._total -= sumDiscountApplyDelivery;
let newDiscount = {
discount_id: this.categoryList[i].id,
discount_type_id: this.categoryList[i].discount_type_id,
};
this.cartProvider._activeDiscount = true;
this.cartProvider._discountsApplied.push(newDiscount);
this.cartProvider.toatDiscountApply(
this.categoryList[i].message_to_user
);
}
}
}
}
});
}
setTimeout(() => {
this.cartProvider.showListToast();
}, 1000);
}
getInfoAddressLastUsed() {
this.userProvider.getInfoUser().then((resp: any) => {
this.listAddressUser = resp["addresses"];
this.addressUserLastUsed = this.listAddressUser.find(
(addressLastUsed) => addressLastUsed.last_used === 1
);
this.infoConfirmOrder.address = this.addressUserLastUsed.id;
});
}
}