File: /var/www/vhost/disk-apps/pwa.sports-crowd.com/src/app/services/user.service.ts
import { Injectable } from "@angular/core";
import { StorageService } from './storage.service';
import { Platform, ModalController, AlertController, NavController } from "@ionic/angular";
import { Router } from "@angular/router";
import { UtilsService } from "./utils.service";
import { TranslateService } from "@ngx-translate/core";
import { SucursalConnectionPage } from "../pages/sucursal-connection/sucursal-connection";
import { ApiService } from "./api.service";
import { ApiMainService } from "./api-main.service";
import { AuthService } from "./auth.service";
import { SucursalService } from "./sucursal.service";
import { Location } from '@angular/common';
import OneSignal from 'onesignal-cordova-plugin';
import { Capacitor } from "@capacitor/core";
@Injectable({
providedIn: "root",
})
export class UserService {
_infoUser: any;
_documentType: any;
_sexType: any;
tagsUserOneSignal: any;
messageText: any;
sessionTime: number;
invitedUser = 'invitado@invitado';
testingUser = 'test@test';
constructor(
public api: ApiService,
public apiMainProvider: ApiMainService,
private storage: StorageService,
public auth: AuthService,
private utilsService: UtilsService,
private platform: Platform,
public sucursalProvider: SucursalService,
public modalCtrl: ModalController,
private translateService: TranslateService,
public alertController: AlertController,
private router: Router,
private navCtrl: NavController,
private location: Location,
) { }
signup(accountInfo: any, name_database) {
return new Promise((resolve, reject) => {
let info = {
accountInfo: accountInfo,
name_database: name_database,
};
this.apiMainProvider.postFree("user/signup", info).subscribe(
(signup: any) => {
if (signup.status == "success") {
// se consulta y almacena el token del usuario
this.auth
.getAccessToken(accountInfo.email, accountInfo.password)
.then((data) => {
this.storage.set("token", {
access_token: data["access_token"],
token_refresh: data["refresh_token"],
});
this.utilsService._HAS_LOGGED_IN = true;
this.storage.set("HAS_LOGGED_IN", true);
this.infoUser(accountInfo.email, accountInfo.password, data["access_token"]).then((res) => {
this.savePlayerOnesignal();
// se valida si esta activo descuento envios para usuarios nuevos
this.registerDiscountShipments(data["access_token"]);
this.utilsService._HAS_LOGGED_IN = true;
this.storage.set("HAS_LOGGED_IN", true);
// si guarda la sucursal en la informacion del usuario para la logica de productos por sucursal
this.storage.get("sucursalSelected").then((sucursalSelected) => {
if (sucursalSelected) {
this.sucursalProvider.updateSucursalUser(sucursalSelected.id, data["access_token"]).then((res) => {
resolve(res)
})
/* this.sucursalProvider.updateSucursalUser(sucursalSelected.id, data["access_token"]).subscribe(() => {
resolve(res);
}); */
} else {
resolve(res);
}
});
resolve(res);
});
})
.catch((error) => {
console.log("error getTokenUser: ", error);
reject(error);
});
} else {
reject(signup);
}
},
(err) => {
console.error("error provider signup: ", err);
reject(err);
}
);
});
}
isPreabonadoByEmail(email) {
return new Promise((resolve, reject) => {
this.api.postFree("tickets/isPreabonadoByEmail", { email }).subscribe(
(res: any) => {
resolve(res);
},
(err) => {
reject(err);
console.error("error provider isPreabonadoByEmail: ", err);
}
);
});
}
isPreabonadoByDocSuscription(data) {
return new Promise((resolve, reject) => {
this.api.postFree("tickets/isPreabonadoByDocSuscription", data).subscribe(
(res: any) => {
resolve(res);
},
(err) => {
reject(err);
console.error("error provider isPreabonadoByDocSuscription: ", err);
}
);
});
}
uploadProfilePhoto(formData: FormData, token_access) {
return new Promise(async (resolve, reject) => {
(await this.api.postFile("user/uploadImageProfile", formData, token_access)).subscribe(
(res: any) => {
resolve(res);
},
(err) => {
reject(err);
console.error("error provider uploadProfilePhoto: ", err);
}
);
});
}
infoUser(email, password, token_access) {
return new Promise(async (resolve, reject) => {
let data = {
email: email,
};
(await this.api.post("user/info", data, token_access)).subscribe(
(res: any) => {
if (res.status == "success") {
let accountInfo = res.user;
accountInfo.password = password;
// se guarda la informacion del usuario en el localstorage
this.storage.set("infoUser", accountInfo);
setTimeout(() => {
this.getInfoUser();
}, 300);
}
resolve(res);
},
(err) => {
reject(err);
console.error("error provider infoUser: ", err);
}
);
});
}
loginAuthMain(email, name_database) {
let info = {
email: email,
name_database: name_database,
};
return this.apiMainProvider.postFree("validate/login", info);
}
facebookAuthMain(tokenFb, name_database) {
let info = {
accessToken: tokenFb,
provider: "facebook",
name_database: name_database,
};
return this.apiMainProvider.postFree("loginSocial", info);
}
appleAuthMain(tokenFb, name_database) {
let info = {
accessToken: tokenFb,
provider: "apple",
name_database: name_database,
};
return this.apiMainProvider.postFree("loginSocial", info);
}
facebookAuth(tokenFb) {
let info = {
accessToken: tokenFb,
provider: "facebook",
};
return this.api.postFree("loginSocial", info);
}
appleAuth(tokenFb) {
let info = {
accessToken: tokenFb,
provider: "apple",
};
return this.api.postFree("loginSocial", info);
}
getDocumentType(token, data?) {
return new Promise(async (resolve, reject) => {
(await this.api.get("user/getDocumentTypes", token, data)).subscribe({
next: (res: any) => {
if (res.status == "success") {
this._documentType = res.documents_types;
}
resolve(res);
},
error: (err) => {
reject(err);
console.error("error provider infoUser: ", err);
},
});
});
}
getInfoUser() {
return new Promise((resolve, reject) => {
this.storage.get("infoUser").then((infoUser) => {
if (infoUser) {
this._infoUser = infoUser;
resolve(infoUser);
}
}, reject);
});
}
updateInfoUser(userInfo, password, token) {
return new Promise((resolve, reject) => {
this.api.put("user/update", userInfo, token).subscribe(
(res: any) => {
if (res.status == "success") {
let accountInfo = res.user;
accountInfo.password = password;
// se guarda la informacion del usuario en el localstorage
this.storage.set("infoUser", accountInfo);
setTimeout(() => {
resolve(res);
this.getInfoUser();
}, 300);
}
},
(err) => {
reject(err);
console.error("error provider infoUser: ", err);
}
);
});
}
async savePlayerOnesignal() {
if (Capacitor.isNativePlatform()) {
const token = await this.api.getAccessToken();
OneSignal.User.pushSubscription.getIdAsync().then((resp) => {
let info = {
playerId: resp,
};
this.api.put("user/saveOnesignalPlayerId", info, token).subscribe(
(resp: any) => {
console.log("updateOnesignalPnsId: ", resp);
},
(error) => {
console.error("updateOnesignalPnsIdError: ", error);
}
);
});
}
}
sendMailbox(mailbox, token) {
let info = {
mailbox: mailbox,
};
return this.api.post("user/mailbox", info, token);
}
getMessages(token) {
return this.api.get("user/messages", token);
}
newMessage(message, token) {
let info = {
message: message,
};
return this.api.post("user/newMessage", info, token);
}
rememberPassword(email) {
let info = {
email: email,
};
return this.apiMainProvider.postFree("recoverPassword", info);
}
getlastAddressUser() {
return new Promise((resolve, reject) => {
this.storage.get("infoUser").then((infoUser) => {
let address = null;
if (infoUser) {
address = infoUser.addresses.find((address) => address.last_used == 1);
}
resolve(address);
}, reject);
});
}
async updateLastUsedAddress(id) {
(await this.api.post(`users/addresses/${id}/set-default`, {})).subscribe(
(resp: any) => {
console.log("updateLastUsedAddress: ", resp);
},
(error) => {
console.error("error getting delivery price: ", error);
}
);
this.storage.get("infoUser").then((infoUser) => {
if (infoUser) {
for (let i = 0; i < infoUser.addresses.length; i++) {
if (infoUser.addresses[i].id == id) {
infoUser.addresses[i].last_used = 1;
} else {
infoUser.addresses[i].last_used = 0;
}
}
this._infoUser = infoUser;
this.storage.set("infoUser", this._infoUser);
}
});
}
changeCityUser(email, password) {
return new Promise((resolve, reject) => {
this.storage.get("infoHost").then((infoHost) => {
// console.log('infoHost changeCityUser:', infoHost);
if (infoHost) {
this.loginAuthMain(email, infoHost.name_database).subscribe(
(validate) => {
if (validate["status"] == "success") {
this.auth.getAccessToken(email, password).then((token) => {
if (token["m"] != null) {
this.utilsService.presentToast(3000, "warning", "top", token["m"]);
return;
}
this.storage.set("token", {
access_token: token["access_token"],
token_refresh: token["refresh_token"],
});
this.infoUser(email, password, token["access_token"]).then(
(res) => {
if (res["status"] == "success") {
this.savePlayerOnesignal();
// si guarda la sucursal en la informacion del usuario para la logica de productos por sucursal
if (infoHost.sucursal_products) {
this.storage.get("sucursalSelected").then((sucursalSelected) => {
this.openModalSucursalConnection(token["access_token"]);
});
}
}
},
(error) => {
console.log("error getInfoUser changeCityUser", error);
}
);
})
.catch((error) => {
console.log("getAccessToken error: ", error);
});
}
},
(error) => {
console.log("error loginAuthMain: ", error);
reject(error);
}
);
}
});
});
}
async openModalSucursalConnection(token) {
const modal = await this.modalCtrl.create({
component: SucursalConnectionPage,
componentProps: { buttonBack: false },
});
await modal.present();
const { data } = await modal.onWillDismiss();
if (data) {
this.sucursalProvider.updateSucursalUser(data.id, token);
}
}
changeCityUserFacebook(authResponse) {
return new Promise((resolve, reject) => {
this.storage.get("infoHost").then((infoHost) => {
if (infoHost) {
this.facebookAuthMain(authResponse.accessToken, infoHost.name_database).subscribe(
(resp) => {
this.facebookAuth(authResponse.accessToken).subscribe(
(respAuthHost) => {
// se guarda la informacion del usuario en el localstorage
let infoUser = respAuthHost["userInfo"];
this.storage.set("infoUser", infoUser);
setTimeout(() => {
this.getInfoUser();
}, 300);
// se guarda token del usuario en el localstorage
this.storage.set("token", {
access_token: respAuthHost["token"].access_token,
token_refresh: respAuthHost["token"].refresh_token,
});
this.savePlayerOnesignal();
this.storage.get("sucursalSelected").then((sucursalSelected) => {
if (sucursalSelected) {
this.sucursalProvider.updateSucursalUser(1, respAuthHost["token"].access_token);
}
});
resolve(respAuthHost);
},
(error) => {
console.log("error facebookAuth: ", error);
}
);
},
(error) => {
console.log("error facebookAuthMain", error);
reject(error);
}
);
}
});
});
}
saveCardCredit(dataCard, typeCardText, token) {
let valueDate = dataCard.date.split("/");
let info = {
name: dataCard.name,
expiryMonth: valueDate[0],
expiryYear: "20" + valueDate[1],
cardNumber: dataCard.numberCard.split(" ").join(""),
type: "Card",
cvc: dataCard.cvc,
paymentMethod: typeCardText,
};
return this.api.post("wpgw/cc/register", info, token);
}
listCreditCard(token) {
return this.api.get("wpgw/cc/all", token);
}
getPointsSale(token) {
return this.api.get("orders/getPointsSale", token);
}
deleteCreditCard(id, token) {
return this.api.delete("wpgw/cc/delete/" + id, token);
}
selectDefaultCard(id, token) {
return this.api.put("wpgw/cc/current/" + id, {}, token);
}
generateVerifyCard(id, token) {
return this.api.put("wpgw/cc/apply/verification/" + id, {}, token);
}
sendValueVerifyCard(id, amount, token) {
let info = {
amount: amount,
};
return this.api.put("wpgw/cc/verify/" + id, info, token);
}
generateOrderPaymentTDC(amount, token) {
let info = {
amount: amount,
};
return this.api.post("wpgw/cc/apply/charge", info, token);
}
async registerDiscountShipments(token) {
let seq = this.api.get("user/registerDiscountShipments", token);
(await seq).subscribe(
(res: any) => {
console.log("res registerDiscountShipments: ", res);
},
(err) => {
console.error("Error registerDiscountShipments", err);
}
);
}
async updateViewTutorial(token) {
let seq = this.api.get("user/updateViewTutorial", token);
(await seq).subscribe(
(res: any) => {
this._infoUser.user_info.is_tutorial_viewed = true;
},
(err) => {
console.error("Error updateViewTutorial", err);
}
);
}
updateLastSession() {
return new Promise((resolve, reject) => {
this.storage.get("token").then(async (token) => {
if (token) {
let seq = this.api.get("user/updateLastSession", token.access_token);
(await seq).subscribe(
(res: any) => {
resolve(res);
},
(err) => {
reject();
console.error("Error updateLastSession", err);
}
);
}
});
});
}
getCurrentCoinsUser() {
return new Promise((resolve, reject) => {
this.storage.get("token").then(async (token) => {
if (token) {
let seq = this.api.get(`coins/info`, token.access_token);
(await seq).subscribe(
(res: any) => {
resolve(res);
},
(err) => {
reject();
console.error("Error updateLastSession", err);
}
);
}
});
});
}
deleteAccount(userId) {
return new Promise((resolve, reject) => {
this.storage.get("token").then(async (token) => {
if (token) {
(await this.api.delete("user/deleteSystemUser/" + userId, token.access_token)).subscribe(
(res: any) => {
resolve(res);
},
(err) => {
reject(err);
console.error("error provider deleteAccount: ", err);
}
);
}
});
});
}
getSexType() {
this._sexType = [
{
'id': 'M',
'name': this.translateService.instant("MALE")
}, {
'id': 'F',
'name': this.translateService.instant("FEMALE")
}, {
'id': 'I',
'name': this.translateService.instant("NONBINARY")
}];
}
validateAlertsUseApp(optionalValidation: string = 'document', back: boolean = false) {
if (!this.messageText) {
this.loadTextAlerts();
}
if (!this._infoUser) {
return false;
}
if (this._infoUser.id == 2) {
this.alertUserInvited(back);
return false;
} else if (optionalValidation && optionalValidation == 'comingSoon') {
this.confirmationAlertWithGenericMessage(this.messageText.textFeatureComingSoon, back);
return false;
} else if (optionalValidation && optionalValidation == 'document' && !this._infoUser.document) {
this.alertUserInformationUpdate(back);
return false;
} else if (optionalValidation && optionalValidation == 'coins' && !this._infoUser.coin_uid) {
this.alertUserWalletRegistrationConfirmation(back);
return false;
} else if (optionalValidation && optionalValidation == 'isSubscriber' && !this._infoUser.is_subscriber) {
this.confirmationAlertWithGenericMessage(this.messageText.textValidateUserSubscriberCard, back);
return false;
}
return true;
}
async loadTextAlerts() {
// traducción textos
await this.translateService
.get([
"TITLE_VALIDATE_INVITED",
"TEXT_VALIDATE_INVITED",
"TEXT_VALIDATE_USER_INFORMATION",
"TEXT_VALIDATE_USER_SUBSCRIBER_CARD",
"TEXT_VALIDATE_REGISTER_API",
"TEXT_CANCEL_ACTION",
"TEXT_SIGN_UP",
"TEXT_UPDATE_PROFILE",
"BUTTON_OK",
"COMING_SOON",
])
.subscribe((values) => {
this.messageText = {
titleValidateUser: values.TITLE_VALIDATE_INVITED,
textValidateInvited: values.TEXT_VALIDATE_INVITED,
textValidateUserInformation: values.TEXT_VALIDATE_USER_INFORMATION,
textValidateUserSubscriberCard: values.TEXT_VALIDATE_USER_SUBSCRIBER_CARD,
textValidateUserWalletRegistrationConfirmation: values.TEXT_VALIDATE_REGISTER_API,
textCancel: values.TEXT_CANCEL_ACTION,
textSignup: values.TEXT_SIGN_UP,
textUpdateProfile: values.TEXT_UPDATE_PROFILE,
textOk: values.BUTTON_OK,
textFeatureComingSoon: values.COMING_SOON,
};
});
}
async alertUserInvited(back: boolean = false) {
const confirm = await this.alertController.create({
header: this.messageText.titleValidateUser,
message: this.messageText.textValidateInvited,
backdropDismiss: false,
buttons: [
{
text: this.messageText.textCancel,
handler: () => {
if (back) this.location.back();
},
},
{
text: this.messageText.textSignup,
handler: () => {
this.storage.remove("token");
this.storage.remove("infoUser");
this.navCtrl.navigateRoot("/city-connection");
},
},
],
});
await confirm.present();
}
async alertUserInformationUpdate(back: boolean = false) {
const confirm = await this.alertController.create({
header: this.messageText.titleValidateUser,
message: this.messageText.textValidateUserInformation,
backdropDismiss: false,
buttons: [
{
text: this.messageText.textCancel,
handler: () => {
if (back) this.location.back();
},
},
{
text: this.messageText.textUpdateProfile,
handler: () => {
this.router.navigate(["/user-profile"]);
},
},
],
});
await confirm.present();
}
async alertUserWalletRegistrationConfirmation(back: boolean = false) {
const confirm = await this.alertController.create({
header: this.messageText.titleValidateUser,
message: this.messageText.textValidateUserWalletRegistrationConfirmation,
backdropDismiss: false,
buttons: [
{
text: this.messageText.textCancel,
handler: () => {
if (back) this.location.back();
},
},
{
text: this.messageText.textUpdateProfile,
handler: () => {
this.router.navigate(["/user-profile"]);
},
},
],
});
await confirm.present();
}
async confirmationAlertWithGenericMessage(message: string, back: boolean = false) {
const confirm = await this.alertController.create({
header: this.messageText.titleValidateUser,
message: message,
backdropDismiss: false,
buttons: [
{
text: this.messageText.textOk,
handler: () => {
if (back) this.location.back();
},
},
],
});
await confirm.present();
}
async getUserCards(take: number, offset: number, show_in) {
return this.api.get(`user/cards/${take}/${offset}/${show_in}`, await this.utilsService.getAccessToken());
}
async getMemberships() {
return this.api.get(`users/memberships`);
}
isRestrictedUser() {
let isRestrictedUser = false;
if (this._infoUser && (this._infoUser.email.includes(this.invitedUser) || this._infoUser.email.includes(this.testingUser))) {
isRestrictedUser = true;
}
return isRestrictedUser;
}
}