Уровень {{ loyaltyProgram.currentLvl }}
-Кэшбек {{ loyaltyProgram.currentLvlPeriod.percent }}%
+Уровень {{ authService.userInfo.customer_level }}
+Кэшбек {{ authService.currentLvlPeriod.percent }}%
- {{ Math.floor(loyaltyProgram.getBalanceAmount(customerInfo?.walletBalances)) }} + {{ Math.floor(authService.getBalanceAmount(authService.userInfo.walletBalances)) }} бонусов
-
Данные недоступны, попробуйте позже
- Ваш текущий уровень {{ loyaltyProgram.currentLvl }}, - поэтому вам начисляется {{ loyaltyProgram.currentLvlPeriod.percent }}% от суммы покупки. + Ваш текущий уровень {{ authService.userInfo?.customer_level }}, + поэтому вам начисляется {{ authService.currentLvlPeriod.percent }}% от суммы покупки.
Смена уровня произойдет в начале следующего квартала, - {{ loyaltyProgram.purchaseData.currentPeriod[1] + {{ authService.purchaseData.currentPeriod[1] .locale("ru") .format("DD.MM.YY") }}.
diff --git a/angular/src/app/presentation-options/default-option/pages/loyality-program/loyality-program.component.ts b/angular/src/app/presentation-options/default-option/pages/loyality-program/loyality-program.component.ts index da1dd10..516feba 100644 --- a/angular/src/app/presentation-options/default-option/pages/loyality-program/loyality-program.component.ts +++ b/angular/src/app/presentation-options/default-option/pages/loyality-program/loyality-program.component.ts @@ -1,18 +1,18 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; import { Location } from '@angular/common'; import { lvlPeriod } from 'src/app/interface/data'; import { lvlPeriods } from 'src/app/app.constants'; -import { LoyaltyProgramService } from 'src/app/services/loyalty-program.service'; +import { AuthService } from 'src/app/services/auth.service'; @Component({ selector: 'loyality-program', templateUrl: './loyality-program.component.html', styleUrls: ['./loyality-program.component.scss'], }) -export class LoyalityProgramComponent implements OnInit { +export class LoyalityProgramComponent { constructor( private _location: Location, - public loyaltyProgram: LoyaltyProgramService, + public authService: AuthService, ) { } public lvlPeriods: lvlPeriod[] = lvlPeriods; @@ -20,10 +20,4 @@ export class LoyalityProgramComponent implements OnInit { goBack = () => { this._location.back(); } - - ngOnInit(): void { - if (this.loyaltyProgram.currentLvlPeriod == null) { - this._location.back(); - } - } } diff --git a/angular/src/app/services/auth.service.ts b/angular/src/app/services/auth.service.ts new file mode 100644 index 0000000..6697b58 --- /dev/null +++ b/angular/src/app/services/auth.service.ts @@ -0,0 +1,258 @@ +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'; + +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)); + } + }, + error: (e) => { + this.error = e; + }, + complete: () => { + this.loading = false; + }, + }); + } + + 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: (value) => { + this.router.navigate(['/']); + this.getUserInfo(); + }, + error: (err) => { + console.error(err); + + }, + complete: () => { + this.loading = false; + } + }) + } else if (result.code === 230) { + this.messageService.add({ + severity: 'error', + summary: 'Неверный код!', + }); + } + }, + error: (error) => { + console.error(error); + }, + }); + } + + 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(userInfo: UserInfo) { + this.wpJsonService.getLastPurchase(environment.systemId, this.token!).subscribe({ + next: (res) => { + this.purchaseData.lastPurchase = res[userInfo.id][0]; + }, + }); + } + + getBalanceAmount(loyaltyPrograms: UserInfoWalletBalance[]) { + return (loyaltyPrograms || []).reduce((accumulator, currentValue) => { + if (currentValue.wallet.name !== 'Федеральная программа лояльности') { + return accumulator + } + return accumulator + currentValue.balance; + }, 0); + } +} diff --git a/angular/src/app/services/loyalty-program.service.ts b/angular/src/app/services/loyalty-program.service.ts deleted file mode 100644 index 5781650..0000000 --- a/angular/src/app/services/loyalty-program.service.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { Injectable } from '@angular/core'; -import moment from 'moment'; -import { Moment, Purchase, lvlPeriod } from '../interface/data'; -import { lvlPeriods } from '../app.constants'; -import { WpJsonService } from './wp-json.service'; -import { Observable } from 'rxjs'; - -export interface IPurchaseData { - currentPeriod: Moment[]; - lastPeriod: Moment[]; - currentAmount?: number; - $loading: boolean; - lastPurchase?: Purchase; -} - -@Injectable({ - providedIn: 'root', -}) -export class LoyaltyProgramService { - public purchaseData: IPurchaseData = { - currentPeriod: [], - lastPeriod: [], - $loading: false, - lastPurchase: undefined, - }; - - public currentLvl: number = 1; - public currentLvlPeriod!: lvlPeriod; - public lvlPeriods: lvlPeriod[] = lvlPeriods; - - constructor( - private wpJsonService: WpJsonService, - ) { - this.getCurrentQuarterOfYear(); - } - - 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]; - } - } - } - - getBalanceAmount(loyaltyPrograms: any[]) { - return (loyaltyPrograms || []).reduce((accumulator, currentValue) => { - if (currentValue.wallet.name !== 'Федеральная программа лояльности') { - return accumulator - } - return accumulator + currentValue.balance; - }, 0); - } - - setCurrentLvl(currentAmount: number) { - const index = this.lvlPeriods.findIndex( - (item) => - item.start <= currentAmount && currentAmount <= (item.end || Infinity) - )!; - if (index != -1) { - this.currentLvlPeriod = this.lvlPeriods[index]; - this.currentLvl = index + 1; - } - } - - getNextLevel(): lvlPeriod { - if(this.currentLvl == this.lvlPeriods.length) { - return lvlPeriods[this.currentLvl - 1]; - } - return lvlPeriods[this.currentLvl]; - } - - getLastPurchase(systemId: string, token: string, customerId: string) { - this.purchaseData.$loading = true; - this.wpJsonService.getLastPurchase(systemId, token).subscribe({ - next: (res) => { - this.purchaseData.lastPurchase = res[customerId][0]; - }, - complete: () => { - this.purchaseData.$loading = false; - } - }); - } -} diff --git a/angular/src/app/services/wp-json.service.ts b/angular/src/app/services/wp-json.service.ts index 09e2f10..c05b001 100644 --- a/angular/src/app/services/wp-json.service.ts +++ b/angular/src/app/services/wp-json.service.ts @@ -4,8 +4,7 @@ import { HttpClient, HttpHeaders } from "@angular/common/http"; import { CookiesService } from "./cookies.service"; import { Observable, of, switchMap } from "rxjs"; import { JsonRpcBody } from "./jsonrpc.service"; -import { DeliveryType, AcceptedOrder, Product, Purchase } from "../interface/data"; -import { ActivatedRoute } from "@angular/router"; +import { DeliveryType, AcceptedOrder, Product } from "../interface/data"; export enum Method { @@ -22,7 +21,6 @@ export class WpJsonService { constructor( private http: HttpClient, private cookiesService: CookiesService, - private route: ActivatedRoute, ) { } getDeliveryTypes(): Observable