forked from likecoin/3ook-com
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckout.vue
More file actions
406 lines (366 loc) · 11.9 KB
/
Copy pathcheckout.vue
File metadata and controls
406 lines (366 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
<template>
<main class="items-center px-4 laptop:px-12 pb-[100px]">
<template v-if="isLoading">
<BookLoadingScreen
v-if="cartItems.length === 1"
:book-cover-src="cartItems[0]?.bookInfo?.coverSrc"
:book-name="cartItems[0]?.bookInfo?.name"
icon="i-material-symbols-shopping-cart"
:icon-label="$t('checkout_preparing_title')"
:loading-label="$t('checkout_loading_cart_items')"
:loading-progress="loadingProgress"
/>
<div
v-else
class="flex flex-col items-center justify-center py-[56px]"
>
<UIcon
class="text-theme-cyan text-[40px] mb-4"
name="i-material-symbols-shopping-cart"
/>
<h1
class="text-theme-cyan text-xl font-bold mb-4"
v-text="$t('checkout_preparing_title')"
/>
<UProgress
class="mt-2 max-w-[160px]"
size="sm"
:value="loadingProgress"
/>
</div>
</template>
<template v-else-if="cartItems.length > 0">
<section class="flex flex-col w-full max-w-[800px] mt-8">
<h1
class="text-[32px] font-bold text-highlighted mb-8"
v-text="$t('checkout_page_title')"
/>
<div class="bg-white p-6 rounded-lg shadow-[0px_10px_20px_0px_rgba(0,0,0,0.04)] mb-6">
<h2
class="text-lg font-semibold mb-4"
v-text="$t('checkout_cart_items_title', { count: cartItems.length })"
/>
<ul class="space-y-4">
<li
v-for="item in cartLineItems"
:key="`${item.classId}-${item.priceIndex}`"
class="flex gap-4 p-4 border border-gray-200 rounded-lg"
>
<BookCover
class="w-[80px] shrink-0"
:src="item.bookInfo?.coverSrc"
:alt="item.bookInfo?.name"
:has-shadow="true"
/>
<div class="flex-1">
<h3
class="font-semibold text-highlighted mb-1"
v-text="item.bookInfo?.name"
/>
<p
v-if="item.bookInfo?.authorName"
class="text-sm text-muted mb-2"
v-text="$t('checkout_by_author', { author: item.bookInfo.authorName })"
/>
<div class="flex items-center justify-between">
<span
class="text-sm text-gray-500"
v-text="localeString(item.pricingItem?.name || '')"
/>
<div class="flex items-center gap-2">
<span
class="text-xs text-gray-500"
v-text="$t('checkout_quantity_label', { quantity: item.quantity })"
/>
<span
class="text-green-600 font-semibold"
v-text="formatConvertedPrice(item.convertedLineTotal)"
/>
</div>
</div>
</div>
</li>
</ul>
</div>
<div
v-if="couponCode"
class="bg-green-50 border border-green-200 p-4 rounded-lg mb-6"
>
<div class="flex items-center gap-2">
<UIcon
name="i-material-symbols-local-offer"
class="text-green-600"
/>
<span
class="font-semibold text-green-800"
v-text="$t('checkout_coupon_applied', { code: couponCode })"
/>
</div>
</div>
<div class="bg-gray-50 p-6 rounded-lg mb-6">
<div class="flex justify-between items-center text-xl font-bold">
<span v-text="$t('checkout_total_label')" />
<span
class="text-green-600"
v-text="formatConvertedPrice(totalPriceConverted)"
/>
</div>
</div>
<UButton
class="cursor-pointer self-center max-w-[400px]"
color="primary"
size="xl"
:loading="isPurchasing"
:disabled="isPurchasing || cartItems.length === 0"
block
@click="handleCheckout"
>
<template v-if="isPurchasing">
{{ $t('checkout_processing_button') }}
</template>
<template v-else>
{{ $t('checkout_complete_purchase_button') }}
</template>
</UButton>
</section>
</template>
<template v-else>
<div class="flex flex-col items-center justify-center py-[100px]">
<UIcon
class="text-gray-400 text-[64px] mb-4"
name="i-material-symbols-shopping-cart-off"
/>
<h1
class="text-muted text-xl font-bold mb-2"
v-text="$t('checkout_cart_empty_title')"
/>
<p
class="text-gray-500 mb-6"
v-text="$t('checkout_cart_empty_description')"
/>
<UButton
:to="$localeRoute({ name: 'store' })"
color="primary"
size="lg"
:label="$t('checkout_cart_empty_browse_button')"
/>
</div>
</template>
</main>
</template>
<script setup lang="ts">
interface CheckoutItem {
classId: string
priceIndex: number
quantity: number
bookInfo?: {
name: string
authorName: string
coverSrc: string
}
pricingItem?: BookstorePrice
}
const likeCoinSessionAPI = useLikeCoinSessionAPI()
const getRouteQuery = useRouteQuery()
const { user } = useUserSession()
const nftStore = useNFTStore()
const bookstoreStore = useBookstoreStore()
const { convertPrice, formatConvertedPrice } = useCurrency()
const { getCheckoutCurrency } = usePaymentCurrency()
const { handleError } = useErrorHandler()
const { getAnalyticsParameters } = useAnalytics()
const { getResizedNormalizedImageURL } = useImageResize()
const { t: $t, locale } = useI18n()
const localeString = useLocaleString()
// Parse products from query string
// Format: products=12345-0%3A3%2C23456%3A1 (URL encoded: products=12345-0:3,23456:1)
const productsQuery = getRouteQuery('products', '')
const couponCode = getRouteQuery('coupon', '')
const products = computed(() => parseProducts(productsQuery))
const cartItems = computed<CheckoutItem[]>(() => {
return products.value.map((product) => {
const nftClass = nftStore.getNFTClassMetadataById(product.classId)
const bookstoreInfo = bookstoreStore.getBookstoreInfoByNFTClassId(product.classId)
if (!nftClass || !bookstoreInfo) {
return null
}
let authorName = ''
if (typeof bookstoreInfo.author === 'object' && bookstoreInfo.author.name) {
authorName = bookstoreInfo.author.name
}
else if (typeof nftClass.author === 'string') {
authorName = nftClass.author
}
else if (typeof nftClass.author === 'object' && nftClass.author.name) {
authorName = nftClass.author.name
}
const bookInfo = {
name: localeString(bookstoreInfo.name || nftClass.name) || '',
authorName,
coverSrc: getResizedNormalizedImageURL(nftClass.image, { size: 600 }),
}
const pricingItem = bookstoreInfo.prices.find(p => p.index === product.priceIndex)
return {
classId: product.classId,
priceIndex: product.priceIndex,
quantity: product.quantity,
bookInfo,
pricingItem,
}
}).filter(Boolean) as CheckoutItem[]
})
const isLoading = ref(true)
const isPurchasing = ref(false)
const loadingProgress = ref(0)
onMounted(async () => {
if (products.value.length > 0) {
isLoading.value = true
loadingProgress.value = 10
await Promise.all(
products.value.map(async (product) => {
if (!product) return
try {
await nftStore.lazyFetchNFTClassAggregatedMetadataById(product.classId)
loadingProgress.value += (90 / products.value.length)
}
catch (error) {
console.error(`Failed to load metadata for ${product.classId}:`, error)
}
}),
)
loadingProgress.value = 100
if (cartItems.value.length > 0) {
useLogEvent('add_to_cart', eventPayload.value)
}
setTimeout(() => {
isLoading.value = false
if (cartItems.value.length > 0) {
handleCheckout()
}
}, 1000)
}
else {
isLoading.value = false
}
})
const totalPrice = computed(() => {
return cartItems.value.reduce((total, item) => {
return total + (item.pricingItem?.price || 0) * item.quantity
}, 0)
})
// Per-line totals resolved once in the buyer's currency (honouring any
// per-tier override), so the line rows and the grand total cannot diverge.
// `totalPrice` (USD) is kept for analytics where currency is reported as USD.
const cartLineItems = computed(() => cartItems.value.map(item => ({
...item,
convertedLineTotal: convertPrice(
item.pricingItem?.price || 0,
item.pricingItem?.priceInDecimalByCurrency,
) * item.quantity,
})))
const totalPriceConverted = computed(() => cartLineItems.value.reduce(
(total, item) => total + item.convertedLineTotal,
0,
))
const eventPayload = computed(() => {
const payload = {
currency: 'USD',
value: totalPrice.value,
promotion_id: couponCode || (user.value?.isLikerPlus ? 'plus' : undefined),
promotion_name: couponCode || (user.value?.isLikerPlus ? 'plus' : undefined),
items: cartItems.value.map(item => ({
id: `${item.classId}-${item.priceIndex}`,
name: item.bookInfo?.name || '',
price: item.pricingItem?.price || 0,
currency: 'USD',
quantity: item.quantity,
google_business_vertical: 'retail',
})),
}
return payload
})
function parseProducts(productsString: string): Array<{ classId: string, priceIndex: number, quantity: number }> {
if (!productsString) return []
try {
const decoded = decodeURIComponent(productsString)
return decoded.split(',').map((productString) => {
const [productId, quantityStr] = productString.split(':')
const quantity = quantityStr ? parseInt(quantityStr, 10) || 1 : 1
if (!productId) {
throw createError({
statusCode: 400,
message: `Invalid product format: "${productString}"`,
})
}
const lastDashIndex = productId.lastIndexOf('-')
let classId: string
let priceIndex: number = 0
if (lastDashIndex === -1) {
classId = productId
priceIndex = 0
}
else {
const potentialPriceIndex = productId.substring(lastDashIndex + 1)
const parsedPriceIndex = parseInt(potentialPriceIndex, 10)
if (isNaN(parsedPriceIndex)) {
classId = productId
priceIndex = 0
}
else {
classId = productId.substring(0, lastDashIndex)
priceIndex = parsedPriceIndex
}
}
return {
classId: classId,
priceIndex,
quantity,
}
})
}
catch (error) {
handleError(error)
return []
}
}
async function handleCheckout() {
if (!cartItems.value.length) return
try {
isPurchasing.value = true
const { url, paymentId } = await likeCoinSessionAPI.createNFTBookCartPurchase(
cartItems.value.map(item => ({
nftClassId: item.classId,
priceIndex: item.priceIndex,
quantity: item.quantity,
})),
{
email: user.value?.email || undefined,
coupon: couponCode || undefined,
cancelPage: 'checkout',
language: locale.value.split('-')[0],
currency: getCheckoutCurrency(),
...getAnalyticsParameters({ utmSource: 'checkout' }),
},
)
useLogEvent('begin_checkout', {
...eventPayload.value,
transaction_id: paymentId,
})
await navigateTo(url, { external: true })
}
catch (error) {
useLogEvent('checkout_error', {
...eventPayload.value,
error_message: getErrorMessage(error),
})
isPurchasing.value = false
await handleError(error)
}
}
useHead(() => ({
title: [$t('checkout_page_title'), $t('app_title')].join(' - '),
meta: [
{ name: 'robots', content: 'noindex, nofollow' },
],
}))
</script>