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, lvlPeriod, UserInfoWalletBalance, Moment } from '../interface/data'; import { lvlPeriods } from 'src/app/app.constants'; import moment from 'moment-timezone'; import { Router } from '@angular/router'; @Injectable({ providedIn: 'root', }) export class AuthService { lastPeriod: Moment[] = []; currentPeriod: Moment[] = []; userInfo?: UserInfo; loading: boolean = false; error: any; timeLeft: number = 0; get currentLvlPeriod(): lvlPeriod { return lvlPeriods[ this.userInfo?.current_level_and_cashback ? this.userInfo?.current_level_and_cashback.current_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.clear(); 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)); } }, 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.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, 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.clear(); 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.lastPeriod = quarters[i - 1]; this.currentPeriod = quarters[i]; } } } getNextLevel(): lvlPeriod { if (this.userInfo?.next_level.next_level) { return lvlPeriods[this.userInfo.next_level.next_level]; } return lvlPeriods[0]; } getBalanceAmount(loyaltyPrograms: UserInfoWalletBalance[]) { return (loyaltyPrograms || []).reduce((accumulator, currentValue) => { if (currentValue.wallet.name !== 'Федеральная программа лояльности') { return accumulator } return accumulator + currentValue.balance; }, 0); } }