juice-shop

Форк
0
/
payment.component.ts 
254 строки · 9.9 Кб
1
/*
2
 * Copyright (c) 2014-2024 Bjoern Kimminich & the OWASP Juice Shop contributors.
3
 * SPDX-License-Identifier: MIT
4
 */
5

6
import { UntypedFormControl, Validators } from '@angular/forms'
7
import { Component, NgZone, type OnInit } from '@angular/core'
8
import { ConfigurationService } from '../Services/configuration.service'
9
import { BasketService } from '../Services/basket.service'
10
import { TranslateService } from '@ngx-translate/core'
11
import { library } from '@fortawesome/fontawesome-svg-core'
12
import {
13
  faCartArrowDown,
14
  faCoffee,
15
  faGift,
16
  faHandHoldingUsd,
17
  faHeart,
18
  faStickyNote,
19
  faThumbsUp,
20
  faTimes,
21
  faTshirt,
22
  faPalette
23
} from '@fortawesome/free-solid-svg-icons'
24
import { faLeanpub, faStripe } from '@fortawesome/free-brands-svg-icons'
25
import { QrCodeComponent } from '../qr-code/qr-code.component'
26
import { MatDialog } from '@angular/material/dialog'
27
import { ActivatedRoute, type ParamMap, Router } from '@angular/router'
28
import { WalletService } from '../Services/wallet.service'
29
import { DeliveryService } from '../Services/delivery.service'
30
import { UserService } from '../Services/user.service'
31
import { CookieService } from 'ngx-cookie'
32
import { Location } from '@angular/common'
33
import { SnackBarHelperService } from '../Services/snack-bar-helper.service'
34

35
library.add(faCartArrowDown, faGift, faHeart, faLeanpub, faThumbsUp, faTshirt, faStickyNote, faHandHoldingUsd, faCoffee, faTimes, faStripe, faPalette)
36

37
@Component({
38
  selector: 'app-payment',
39
  templateUrl: './payment.component.html',
40
  styleUrls: ['./payment.component.scss']
41
})
42
export class PaymentComponent implements OnInit {
43
  public couponConfirmation: any
44
  public couponError: any
45
  public card: any = {}
46
  public twitterUrl = null
47
  public facebookUrl = null
48
  public applicationName = 'OWASP Juice Shop'
49
  private campaignCoupon: string
50
  public couponControl: UntypedFormControl = new UntypedFormControl('', [Validators.required, Validators.minLength(10), Validators.maxLength(10)])
51
  public clientDate: any
52
  public paymentId: any = undefined
53
  public couponPanelExpanded: boolean = false
54
  public paymentPanelExpanded: boolean = false
55
  public mode: any
56
  public walletBalance: number = 0
57
  public walletBalanceStr: string
58
  public totalPrice: any = 0
59
  public paymentMode: string = 'card'
60
  private readonly campaigns = {
61
    WMNSDY2019: { validOn: 1551999600000, discount: 75 },
62
    WMNSDY2020: { validOn: 1583622000000, discount: 60 },
63
    WMNSDY2021: { validOn: 1615158000000, discount: 60 },
64
    WMNSDY2022: { validOn: 1646694000000, discount: 60 },
65
    WMNSDY2023: { validOn: 1678230000000, discount: 60 },
66
    ORANGE2020: { validOn: 1588546800000, discount: 50 },
67
    ORANGE2021: { validOn: 1620082800000, discount: 40 },
68
    ORANGE2022: { validOn: 1651618800000, discount: 40 },
69
    ORANGE2023: { validOn: 1683154800000, discount: 40 }
70
  }
71

72
  constructor (private readonly location: Location, private readonly cookieService: CookieService,
73
    private readonly userService: UserService, private readonly deliveryService: DeliveryService, private readonly walletService: WalletService,
74
    private readonly router: Router, private readonly dialog: MatDialog, private readonly configurationService: ConfigurationService,
75
    private readonly basketService: BasketService, private readonly translate: TranslateService,
76
    private readonly activatedRoute: ActivatedRoute, private readonly ngZone: NgZone,
77
    private readonly snackBarHelperService: SnackBarHelperService) { }
78

79
  ngOnInit () {
80
    this.initTotal()
81
    this.walletService.get().subscribe((balance) => {
82
      this.walletBalance = balance
83
      this.walletBalanceStr = parseFloat(balance).toFixed(2)
84
    }, (err) => { console.log(err) })
85
    this.couponPanelExpanded = localStorage.getItem('couponPanelExpanded') ? JSON.parse(localStorage.getItem('couponPanelExpanded')) : false
86
    this.paymentPanelExpanded = localStorage.getItem('paymentPanelExpanded') ? JSON.parse(localStorage.getItem('paymentPanelExpanded')) : false
87

88
    this.configurationService.getApplicationConfiguration().subscribe((config) => {
89
      if (config?.application?.social) {
90
        if (config.application.social.twitterUrl) {
91
          this.twitterUrl = config.application.social.twitterUrl
92
        }
93
        if (config.application.social.facebookUrl) {
94
          this.facebookUrl = config.application.social.facebookUrl
95
        }
96
        if (config.application.name) {
97
          this.applicationName = config.application.name
98
        }
99
      }
100
    }, (err) => { console.log(err) })
101
  }
102

103
  initTotal () {
104
    this.activatedRoute.paramMap.subscribe((paramMap: ParamMap) => {
105
      this.mode = paramMap.get('entity')
106
      if (this.mode === 'wallet') {
107
        this.totalPrice = parseFloat(sessionStorage.getItem('walletTotal'))
108
      } else if (this.mode === 'deluxe') {
109
        this.userService.deluxeStatus().subscribe((res) => {
110
          this.totalPrice = res.membershipCost
111
        }, (err) => { console.log(err) })
112
      } else {
113
        const itemTotal = parseFloat(sessionStorage.getItem('itemTotal'))
114
        const promotionalDiscount = sessionStorage.getItem('couponDiscount') ? (parseFloat(sessionStorage.getItem('couponDiscount')) / 100) * itemTotal : 0
115
        this.deliveryService.getById(sessionStorage.getItem('deliveryMethodId')).subscribe((method) => {
116
          const deliveryPrice = method.price
117
          this.totalPrice = itemTotal + deliveryPrice - promotionalDiscount
118
        })
119
      }
120
    }, (err) => { console.log(err) })
121
  }
122

123
  applyCoupon () {
124
    this.campaignCoupon = this.couponControl.value
125
    this.clientDate = new Date()
126
    // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
127
    const offsetTimeZone = (this.clientDate.getTimezoneOffset() + 60) * 60 * 1000
128
    this.clientDate.setHours(0, 0, 0, 0)
129
    this.clientDate = this.clientDate.getTime() - offsetTimeZone
130
    // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
131
    sessionStorage.setItem('couponDetails', `${this.campaignCoupon}-${this.clientDate}`)
132
    const campaign = this.campaigns[this.couponControl.value]
133
    if (campaign) {
134
      if (this.clientDate === campaign.validOn) {
135
        this.showConfirmation(campaign.discount)
136
      } else {
137
        this.couponConfirmation = undefined
138
        this.translate.get('INVALID_COUPON').subscribe((invalidCoupon) => {
139
          this.couponError = { error: invalidCoupon }
140
        }, (translationId) => {
141
          this.couponError = { error: translationId }
142
        })
143
        this.resetCouponForm()
144
      }
145
    } else {
146
      this.basketService.applyCoupon(Number(sessionStorage.getItem('bid')), encodeURIComponent(this.couponControl.value)).subscribe((discount: any) => {
147
        this.showConfirmation(discount)
148
      }, (err) => {
149
        this.couponConfirmation = undefined
150
        this.couponError = err
151
        this.resetCouponForm()
152
      })
153
    }
154
  }
155

156
  showConfirmation (discount) {
157
    this.resetCouponForm()
158
    this.couponError = undefined
159
    sessionStorage.setItem('couponDiscount', discount)
160
    this.translate.get('DISCOUNT_APPLIED', { discount }).subscribe((discountApplied) => {
161
      this.couponConfirmation = discountApplied
162
    }, (translationId) => {
163
      this.couponConfirmation = translationId
164
    })
165
    this.initTotal()
166
  }
167

168
  getMessage (id) {
169
    this.paymentId = id
170
    this.paymentMode = 'card'
171
  }
172

173
  routeToPreviousUrl () {
174
    this.location.back()
175
  }
176

177
  choosePayment () {
178
    sessionStorage.removeItem('itemTotal')
179
    if (this.mode === 'wallet') {
180
      this.walletService.put({ balance: this.totalPrice, paymentId: this.paymentId }).subscribe(() => {
181
        sessionStorage.removeItem('walletTotal')
182
        this.ngZone.run(async () => await this.router.navigate(['/wallet']))
183
        this.snackBarHelperService.open('CHARGED_WALLET', 'confirmBar')
184
      }, (err) => {
185
        console.log(err)
186
        this.snackBarHelperService.open(err.error?.message, 'errorBar')
187
      })
188
    } else if (this.mode === 'deluxe') {
189
      this.userService.upgradeToDeluxe(this.paymentMode, this.paymentId).subscribe((data) => {
190
        localStorage.setItem('token', data.token)
191
        this.cookieService.put('token', data.token)
192
        this.ngZone.run(async () => await this.router.navigate(['/deluxe-membership']))
193
      }, (err) => { console.log(err) })
194
    } else {
195
      if (this.paymentMode === 'wallet') {
196
        if (this.walletBalance < this.totalPrice) {
197
          this.snackBarHelperService.open('INSUFFICIENT_WALLET_BALANCE', 'errorBar')
198
          return
199
        }
200
        sessionStorage.setItem('paymentId', 'wallet')
201
      } else {
202
        sessionStorage.setItem('paymentId', this.paymentId)
203
      }
204
      this.ngZone.run(async () => await this.router.navigate(['/order-summary']))
205
    }
206
  }
207

208
  // eslint-disable-next-line no-empty,@typescript-eslint/no-empty-function
209
  noop () { }
210

211
  showBitcoinQrCode () {
212
    this.dialog.open(QrCodeComponent, {
213
      data: {
214
        data: 'bitcoin:1AbKfgvw9psQ41NbLi8kufDQTezwG8DRZm',
215
        url: './redirect?to=https://blockchain.info/address/1AbKfgvw9psQ41NbLi8kufDQTezwG8DRZm',
216
        address: '1AbKfgvw9psQ41NbLi8kufDQTezwG8DRZm',
217
        title: 'TITLE_BITCOIN_ADDRESS'
218
      }
219
    })
220
  }
221

222
  showDashQrCode () {
223
    this.dialog.open(QrCodeComponent, {
224
      data: {
225
        data: 'dash:Xr556RzuwX6hg5EGpkybbv5RanJoZN17kW',
226
        url: './redirect?to=https://explorer.dash.org/address/Xr556RzuwX6hg5EGpkybbv5RanJoZN17kW',
227
        address: 'Xr556RzuwX6hg5EGpkybbv5RanJoZN17kW',
228
        title: 'TITLE_DASH_ADDRESS'
229
      }
230
    })
231
  }
232

233
  showEtherQrCode () {
234
    this.dialog.open(QrCodeComponent, {
235
      data: {
236
        data: '0x0f933ab9fCAAA782D0279C300D73750e1311EAE6',
237
        url: './redirect?to=https://etherscan.io/address/0x0f933ab9fcaaa782d0279c300d73750e1311eae6',
238
        address: '0x0f933ab9fCAAA782D0279C300D73750e1311EAE6',
239
        title: 'TITLE_ETHER_ADDRESS'
240
      }
241
    })
242
  }
243

244
  useWallet () {
245
    this.paymentMode = 'wallet'
246
    this.choosePayment()
247
  }
248

249
  resetCouponForm () {
250
    this.couponControl.setValue('')
251
    this.couponControl.markAsPristine()
252
    this.couponControl.markAsUntouched()
253
  }
254
}
255

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.