h-usersite/angular/src/app/services/auth.service.ts
nikolay 7fe4b6de52 dev #14607 Море. Правки по сайту:
add agree information;
remove uncessary user update;
2023-07-04 15:03:57 +04:00

299 lines
7.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { Injectable } from '@angular/core';
import { CookiesService } from './cookies.service';
import { WpJsonService } from './wp-json.service';
import { environment } from 'src/environments/environment';
import { JsonrpcService, RpcService } from './jsonrpc.service';
import { MessageService } from 'primeng/api';
import { UserInfo, Purchase, lvlPeriod, UserInfoWalletBalance } from '../interface/data';
import { lvlPeriods } from 'src/app/app.constants';
import moment, { Moment } from 'moment-timezone';
import { Router } from '@angular/router';
import { AppleWalletService } from './apple-wallet.service';
import { getTypeDevice, DeviceType } from 'src/app/utils';
export interface IPurchaseData {
currentPeriod: Moment[];
lastPeriod: Moment[];
currentAmount?: number;
lastPurchase?: Purchase;
}
@Injectable({
providedIn: 'root',
})
export class AuthService {
public purchaseData: IPurchaseData = {
currentPeriod: [],
lastPeriod: [],
lastPurchase: undefined,
};
userInfo?: UserInfo;
loading: boolean = false;
error: any;
timeLeft: number = 0;
get currentLvlPeriod(): lvlPeriod {
return lvlPeriods[this.userInfo ? this.userInfo.customer_level - 1 : 0];
}
constructor(
private cookiesService: CookiesService,
private wpJsonService: WpJsonService,
private jsonrpc: JsonrpcService,
private messageService: MessageService,
private router: Router,
private appleWalletService: AppleWalletService,
) {
this.getCurrentQuarterOfYear();
}
get token(): string | undefined {
return this.cookiesService.getItem('token');
}
get authorized(): boolean {
return !!this.token;
}
getUserInfo() {
const token = this.cookiesService.getItem('token');
if (!token) {
return;
}
this.loading = true;
return new Promise((res, rej) => this.wpJsonService
.getCustomerInfo(
environment.systemId,
token,
environment.icardProxy,
)
.subscribe({
next: (value) => {
if (value && value.customer_info && value.customer_info.errorCode === 'Customer_CustomerNotFound'
|| !this.userHasData(value?.customer_info)) {
this.router.navigate(['create_user']);
return rej(null);
} else if (value && value.error && value.error.code > 1) {
this.messageService.clear();
this.messageService.add({
severity: 'error',
summary: 'Произошла ошибка! Попробуйте позже',
});
return rej(null);
} else if (value && value.customer_info) {
this.userInfo = value.customer_info;
this.cookiesService.setCookie('phone-number', this.userInfo!.phone?.slice(2));
}
res(null);
},
error: (e) => {
this.error = e;
rej(e);
},
complete: () => {
this.loading = false;
},
})
);
}
userHasData(user?: UserInfo) {
return user && (user.name || user.birthday);
}
logout() {
this.userInfo = undefined;
this.cookiesService.logout();
this.router.navigate(['/login']);
}
sendVerifyByPhone(phone: string) {
if (this.timeLeft) {
this.messageService.clear();
this.messageService.add({
severity: 'custom',
summary: `Отправить повторно можно через ${this.timeLeft}с`,
});
return;
}
this.loading = true;
this.jsonrpc
.rpc(
{
method: 'sendVerifyByPhone',
params: [phone],
},
RpcService.authService,
false
)
.subscribe({
next: (result) => {
if (result.code !== 0) {
this.messageService.clear();
this.messageService.add({
severity: 'error',
summary: 'Произошла ошибка! Попробуйте позже',
});
}
if (result.code === 0) {
this.timeLeft = 60;
const interval = setInterval(() => {
if (this.timeLeft > 0) {
this.timeLeft--;
} else {
clearInterval(interval);
}
}, 1000);
}
},
error: (error) => {
console.error('Error: ', error);
},
complete: () => {
this.loading = false;
},
});
}
submitCode(code: string, phone: string) {
this.loading = true;
this.jsonrpc
.rpc(
{
method: 'getTokenByPhone',
params: [phone, code],
},
RpcService.authService,
false
)
.subscribe({
next: async (result) => {
if (result.code === 0) {
this.cookiesService.setCookie('token', result?.data?.token);
this.router.navigate(['/']);
await this.getUserInfo();
if(getTypeDevice() === DeviceType.ios) {
this.appleWalletService.addCardToWallet();
}
} else if (result.code === 230) {
this.messageService.clear();
this.messageService.add({
severity: 'error',
summary: 'Неверный код!',
});
}
},
error: (error) => {
console.error(error);
this.loading = false;
},
});
}
getCurrentQuarterOfYear() {
const quarters = [
[
moment().subtract(1, 'years').endOf('year').subtract(3, 'months'),
moment().startOf('year').add(10, 'days'),
],
[
moment().startOf('year').add(10, 'days'),
moment().startOf('year').add(3, 'months'),
],
[
moment().startOf('year').add(3, 'months'),
moment().startOf('year').add(6, 'months'),
],
[
moment().startOf('year').add(6, 'months'),
moment().startOf('year').add(9, 'months'),
],
[
moment().startOf('year').add(9, 'months'),
moment().startOf('year').add(12, 'months'),
],
];
for (let i = 0; i < 4; i++) {
if (moment().isBetween(quarters[i][0], quarters[i][1])) {
this.purchaseData.lastPeriod = quarters[i - 1];
this.purchaseData.currentPeriod = quarters[i];
}
}
}
getNextLevel(): lvlPeriod {
if (this.userInfo?.customer_level === lvlPeriods.length) {
return lvlPeriods[lvlPeriods.length - 1];
}
return this.userInfo && lvlPeriods[this.userInfo?.customer_level] || lvlPeriods[0];
}
getLastPurchase() {
if (this.userInfo) {
this.wpJsonService.getLastPurchase(environment.systemId, this.token!).subscribe({
next: (res) => {
this.purchaseData.lastPurchase = res[this.userInfo!.id][0];
},
});
}
}
getBalanceAmount(loyaltyPrograms: UserInfoWalletBalance[]) {
return (loyaltyPrograms || []).reduce((accumulator, currentValue) => {
return accumulator + currentValue.balance;
}, 0);
}
register(name: string, sex: string, date: string) {
if (this.token) {
this.loading = true;
this.jsonrpc.rpc(
{
method: 'updateAdditionalInfo',
params: [
{
first_name: name,
birth_day: '01.01.1999'
},
],
},
RpcService.authService,
true
).subscribe({
next: () => {
this.wpJsonService.updateNewCustomer(environment.systemId, this.token!, {
name,
sex: sex,
birthday: date,
})
.subscribe({
next: async () => {
this.router.navigate(['/']);
await this.getUserInfo();
if(getTypeDevice() === DeviceType.ios) {
this.appleWalletService.addCardToWallet();
}
},
error: () => {
this.loading = false;
}
});
},
error: (err) => {
console.error(err);
this.loading = false;
},
})
}
}
}