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, ResponseError } from '../interface/data'; import { lvlPeriods } from 'src/app/app.constants'; import moment, { Moment } from 'moment-timezone'; import { Router } from '@angular/router'; 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, ) { 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; this.wpJsonService .getCustomerInfo( environment.systemId, token, environment.icardProxy, ) .subscribe({ next: (value) => { if (value && value.customer_info && value.customer_info.errorCode === 'Customer_CustomerNotFound') { this.wpJsonService.newCustomer( environment.systemId, token, environment.icardProxy, ) .subscribe({ next: () => { this.getUserInfo(); } }) } else if (value && value.error && value.error.code > 1) { this.messageService.add({ severity: 'error', summary: 'Произошла ошибка! Попробуйте позже', }); } else if (value && value.customer_info) { this.userInfo = value.customer_info; this.cookiesService.setCookie('phone-number', this.userInfo!.phone?.slice(2)); this.getLastPurchase(); } }, error: (e) => { this.error = e; }, complete: () => { this.loading = false; }, }); } logout() { this.userInfo = undefined; this.cookiesService.logout(); this.router.navigate(['/login']); } sendVerifyByPhone(phone: string) { if (this.timeLeft) { 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.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, name: string) { this.loading = true; this.jsonrpc .rpc( { method: 'getTokenByPhone', params: [phone, code], }, RpcService.authService, false ) .subscribe({ next: (result) => { if (result.code === 0) { this.cookiesService.setCookie('token', result?.data?.token); this.jsonrpc.rpc( { method: 'updateAdditionalInfo', params: [ { first_name: name, birth_day: '01.01.1999' }, ], }, RpcService.authService, true ).subscribe({ next: () => { this.router.navigate(['/']); this.getUserInfo(); }, error: (err) => { console.error(err); }, }) } else if (result.code === 230) { this.messageService.add({ severity: 'error', summary: 'Неверный код!', }); } }, error: (error) => { console.error(error); }, complete: () => { 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) => { if (currentValue.wallet.name !== 'Федеральная программа лояльности') { return accumulator } return accumulator + currentValue.balance; }, 0); } }