-
Notifications
You must be signed in to change notification settings - Fork 453
Expand file tree
/
Copy pathCheckoutForm.tsx
More file actions
524 lines (464 loc) · 16.4 KB
/
CheckoutForm.tsx
File metadata and controls
524 lines (464 loc) · 16.4 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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
import { __experimental_useCheckout as useCheckout } from '@clerk/shared/react';
import type { BillingPaymentMethodResource, ConfirmCheckoutParams, RemoveFunctions } from '@clerk/shared/types';
import { useMemo, useState } from 'react';
import { Card } from '@/ui/elements/Card';
import { useCardState, withCardStateProvider } from '@/ui/elements/contexts';
import { Drawer } from '@/ui/elements/Drawer';
import { LineItems } from '@/ui/elements/LineItems';
import { SegmentedControl } from '@/ui/elements/SegmentedControl';
import { Select, SelectButton, SelectOptionList } from '@/ui/elements/Select';
import { Tooltip } from '@/ui/elements/Tooltip';
import { handleError } from '@/ui/utils/errorHandler';
import { DevOnly } from '../../common/DevOnly';
import { useCheckoutContext, usePaymentMethods } from '../../contexts';
import { Box, Button, Col, descriptors, Flex, Form, localizationKeys, Spinner, Text } from '../../customizables';
import { ChevronUpDown, InformationCircle } from '../../icons';
import type { PropsOfComponent, ThemableCssProp } from '../../styledSystem';
import * as AddPaymentMethod from '../PaymentMethods/AddPaymentMethod';
import { PaymentMethodRow } from '../PaymentMethods/PaymentMethodRow';
import { SubscriptionBadge } from '../Subscriptions/badge';
type PaymentMethodSource = 'existing' | 'new';
const capitalize = (name: string) => name[0].toUpperCase() + name.slice(1);
const HIDDEN_INPUT_NAME = 'payment_method_id';
export const CheckoutForm = withCardStateProvider(() => {
const { checkout } = useCheckout();
const { plan, totals, isImmediatePlanChange, planPeriod, freeTrialEndsAt } = checkout;
if (!plan) {
return null;
}
const showProratedCredit = !!totals.credits?.proration?.amount && totals.credits.proration.amount.amount > 0;
const showAccountCredits = !!totals.credits?.payer?.appliedAmount && totals.credits.payer.appliedAmount.amount > 0;
const showPastDue = !!totals.pastDue?.amount && totals.pastDue.amount > 0;
const showDowngradeInfo = !isImmediatePlanChange;
const fee =
planPeriod === 'month'
? plan.fee!
: // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
plan.annualMonthlyFee!;
const descriptionElements = [];
if (planPeriod === 'annual') {
descriptionElements.push(localizationKeys('billing.billedAnnually'));
}
const seatUnitPrice = plan.unitPrices?.find(unitPrice => unitPrice.name.toLowerCase() === 'seats');
if (seatUnitPrice && seatUnitPrice.tiers.length === 1 && seatUnitPrice.tiers[0].feePerBlock.amount === 0) {
descriptionElements.push(
seatUnitPrice.tiers[0].endsAfterBlock
? localizationKeys('billing.pricingTable.seatCost.upToSeats', {
endsAfterBlock: seatUnitPrice.tiers[0].endsAfterBlock,
})
: localizationKeys('billing.pricingTable.seatCost.unlimitedSeats'),
);
}
return (
<Drawer.Body>
<Box
elementDescriptor={descriptors.checkoutFormLineItemsRoot}
sx={t => ({
padding: t.space.$4,
borderBottomWidth: t.borderWidths.$normal,
borderBottomStyle: t.borderStyles.$solid,
borderBottomColor: t.colors.$borderAlpha100,
})}
>
<LineItems.Root>
<LineItems.Group>
<LineItems.Title
title={plan.name}
description={descriptionElements}
badge={
plan.freeTrialEnabled && freeTrialEndsAt ? (
<SubscriptionBadge subscription={{ status: 'free_trial' }} />
) : null
}
/>
<LineItems.Description
prefix={planPeriod === 'annual' ? 'x12' : undefined}
text={`${fee.currencySymbol}${fee.amountFormatted}`}
suffix={localizationKeys('billing.checkout.perMonth')}
/>
</LineItems.Group>
<LineItems.Group
borderTop
variant='tertiary'
>
<LineItems.Title title={localizationKeys('billing.subtotal')} />
<LineItems.Description text={`${totals.subtotal.currencySymbol}${totals.subtotal.amountFormatted}`} />
</LineItems.Group>
{showProratedCredit && (
<LineItems.Group variant='tertiary'>
<LineItems.Title title={localizationKeys('billing.creditRemainder')} />
<LineItems.Description
text={`- ${totals.credits?.proration?.amount.currencySymbol}${totals.credits?.proration?.amount.amountFormatted}`}
/>
</LineItems.Group>
)}
{showAccountCredits && (
<LineItems.Group variant='tertiary'>
<LineItems.Title title={localizationKeys('billing.payerCreditRemainder')} />
<LineItems.Description
text={`- ${totals.credits?.payer?.appliedAmount?.currencySymbol}${totals.credits?.payer?.appliedAmount?.amountFormatted}`}
/>
</LineItems.Group>
)}
{showPastDue && (
<LineItems.Group variant='tertiary'>
<Tooltip.Root>
<Tooltip.Trigger>
<LineItems.Title
title={localizationKeys('billing.pastDue')}
icon={InformationCircle}
/>
</Tooltip.Trigger>
<Tooltip.Content text={localizationKeys('billing.checkout.pastDueNotice')} />
</Tooltip.Root>
<LineItems.Description text={`${totals.pastDue?.currencySymbol}${totals.pastDue?.amountFormatted}`} />
</LineItems.Group>
)}
{!!freeTrialEndsAt && !!plan.freeTrialDays && totals.totalDueAfterFreeTrial && (
<LineItems.Group variant='tertiary'>
<LineItems.Title
title={localizationKeys('billing.checkout.totalDueAfterTrial', {
days: plan.freeTrialDays,
})}
/>
<LineItems.Description
text={`${totals.totalDueAfterFreeTrial.currencySymbol}${totals.totalDueAfterFreeTrial.amountFormatted}`}
/>
</LineItems.Group>
)}
<LineItems.Group borderTop>
<LineItems.Title title={localizationKeys('billing.totalDueToday')} />
<LineItems.Description text={`${totals.totalDueNow.currencySymbol}${totals.totalDueNow.amountFormatted}`} />
</LineItems.Group>
</LineItems.Root>
</Box>
{showDowngradeInfo && (
<Box
elementDescriptor={descriptors.checkoutFormLineItemsRoot}
sx={t => ({
paddingBlockStart: t.space.$4,
paddingInline: t.space.$4,
})}
>
<Text
localizationKey={localizationKeys('billing.checkout.downgradeNotice')}
variant='caption'
colorScheme='secondary'
/>
</Box>
)}
<CheckoutFormElements />
</Drawer.Body>
);
});
const useCheckoutMutations = () => {
const { onSubscriptionComplete } = useCheckoutContext();
const { checkout } = useCheckout();
const card = useCardState();
if (checkout.status !== 'needs_confirmation') {
throw new Error('Checkout not found');
}
const confirmCheckout = async (params: ConfirmCheckoutParams) => {
card.setLoading();
card.setError(undefined);
const { error } = await checkout.confirm(params);
if (error) {
handleError(error, [], card.setError);
} else {
onSubscriptionComplete?.();
}
card.setIdle();
};
const payWithExistingPaymentMethod = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const data = new FormData(e.currentTarget);
const paymentMethodId = data.get(HIDDEN_INPUT_NAME) as string;
return confirmCheckout({
paymentMethodId,
});
};
const payWithoutPaymentMethod = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
return confirmCheckout({});
};
const addPaymentMethodAndPay = (ctx: { gateway: 'stripe'; paymentToken: string }) => confirmCheckout(ctx);
const payWithTestCard = () =>
confirmCheckout({
gateway: 'stripe',
useTestCard: true,
});
return {
payWithExistingPaymentMethod,
addPaymentMethodAndPay,
payWithTestCard,
payWithoutPaymentMethod,
};
};
const CheckoutFormElements = () => {
const { checkout } = useCheckout();
const { plan } = checkout;
const { isLoading } = usePaymentMethods();
if (!plan) {
return null;
}
if (isLoading) {
return (
<Spinner
sx={{
margin: 'auto',
}}
/>
);
}
return <CheckoutFormElementsInternal />;
};
const CheckoutFormElementsInternal = () => {
const { checkout } = useCheckout();
const { plan, isImmediatePlanChange, needsPaymentMethod } = checkout;
const { data: paymentMethods } = usePaymentMethods();
const [paymentMethodSource, setPaymentMethodSource] = useState<PaymentMethodSource>(() =>
paymentMethods.length > 0 || __BUILD_DISABLE_RHC__ ? 'existing' : 'new',
);
const showTabs = isImmediatePlanChange && needsPaymentMethod;
if (!plan) {
return null;
}
return (
<Col
elementDescriptor={descriptors.checkoutFormElementsRoot}
gap={4}
sx={t => ({ padding: t.space.$4 })}
>
{__BUILD_DISABLE_RHC__ ? null : (
<>
{paymentMethods.length > 0 && showTabs && (
<SegmentedControl.Root
aria-label='Payment method source'
value={paymentMethodSource}
onChange={value => setPaymentMethodSource(value as PaymentMethodSource)}
size='lg'
fullWidth
>
<SegmentedControl.Button
value='existing'
text={localizationKeys('billing.paymentMethods__label')}
/>
<SegmentedControl.Button
value='new'
text={localizationKeys('billing.addPaymentMethod__label')}
/>
</SegmentedControl.Root>
)}
</>
)}
{!needsPaymentMethod ? (
<FreeTrialButton />
) : paymentMethodSource === 'existing' ? (
<ExistingPaymentMethodForm paymentMethods={paymentMethods} />
) : (
!__BUILD_DISABLE_RHC__ && paymentMethodSource === 'new' && <AddPaymentMethodForCheckout />
)}
</Col>
);
};
export const PayWithTestPaymentMethod = () => {
const { isLoading } = useCardState();
const { payWithTestCard } = useCheckoutMutations();
return (
<Box
sx={t => ({
background: t.colors.$neutralAlpha50,
padding: t.space.$2x5,
borderRadius: t.radii.$md,
borderWidth: t.borderWidths.$normal,
borderStyle: t.borderStyles.$solid,
borderColor: t.colors.$borderAlpha100,
display: 'flex',
flexDirection: 'column',
rowGap: t.space.$2,
position: 'relative',
})}
>
<Box
sx={t => ({
position: 'absolute',
inset: 0,
background: `repeating-linear-gradient(-45deg,${t.colors.$warningAlpha100},${t.colors.$warningAlpha100} 6px,${t.colors.$warningAlpha150} 6px,${t.colors.$warningAlpha150} 12px)`,
maskImage: `linear-gradient(transparent 20%, black)`,
pointerEvents: 'none',
})}
/>
<Flex
sx={t => ({
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
rowGap: t.space.$2,
})}
>
<Text
sx={t => ({
color: t.colors.$warning500,
fontWeight: t.fontWeights.$semibold,
})}
localizationKey={localizationKeys('billing.paymentMethod.dev.developmentMode')}
/>
<Button
type='button'
block
variant='bordered'
localizationKey={localizationKeys('userProfile.billingPage.paymentMethodsSection.payWithTestCardButton')}
colorScheme='secondary'
isLoading={isLoading}
onClick={payWithTestCard}
/>
</Flex>
</Box>
);
};
const useSubmitLabel = () => {
const { checkout } = useCheckout();
const { status, freeTrialEndsAt, totals } = checkout;
if (status === 'needs_initialization') {
throw new Error('Clerk: Invalid state');
}
if (freeTrialEndsAt) {
return localizationKeys('billing.startFreeTrial');
}
if (totals.totalDueNow.amount > 0) {
return localizationKeys('billing.pay', {
amount: `${totals.totalDueNow.currencySymbol}${totals.totalDueNow.amountFormatted}`,
});
}
return localizationKeys('billing.subscribe');
};
const FreeTrialButton = withCardStateProvider(() => {
const { for: _for } = useCheckoutContext();
const { payWithoutPaymentMethod } = useCheckoutMutations();
const card = useCardState();
return (
<Form
onSubmit={payWithoutPaymentMethod}
sx={formProps}
>
<Card.Alert>{card.error}</Card.Alert>
<CheckoutSubmitButton />
</Form>
);
});
const AddPaymentMethodForCheckout = withCardStateProvider(() => {
const { addPaymentMethodAndPay } = useCheckoutMutations();
const submitLabel = useSubmitLabel();
const { checkout } = useCheckout();
return (
<AddPaymentMethod.Root
onSuccess={addPaymentMethodAndPay}
checkout={checkout}
>
<DevOnly>
<PayWithTestPaymentMethod />
</DevOnly>
<AddPaymentMethod.FormButton text={submitLabel} />
</AddPaymentMethod.Root>
);
});
const CheckoutSubmitButton = (props: PropsOfComponent<typeof Button>) => {
const card = useCardState();
const submitLabel = useSubmitLabel();
return (
<Button
type='submit'
colorScheme='primary'
size='sm'
textVariant={'buttonLarge'}
sx={{
width: '100%',
}}
isLoading={card.isLoading}
localizationKey={submitLabel}
{...props}
/>
);
};
const formProps: ThemableCssProp = t => ({
display: 'flex',
flexDirection: 'column',
rowGap: t.space.$4,
});
const ExistingPaymentMethodForm = withCardStateProvider(
({ paymentMethods }: { paymentMethods: BillingPaymentMethodResource[] }) => {
const { checkout } = useCheckout();
const { paymentMethod, isImmediatePlanChange, needsPaymentMethod } = checkout;
const { payWithExistingPaymentMethod } = useCheckoutMutations();
const card = useCardState();
const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<
RemoveFunctions<BillingPaymentMethodResource> | undefined
>(paymentMethod || paymentMethods.find(p => p.isDefault));
const options = useMemo(() => {
return paymentMethods.map(method => {
const label =
method.paymentType !== 'card'
? method.paymentType
? `${capitalize(method.paymentType)}`
: '–'
: method.cardType
? `${capitalize(method.cardType)} ⋯ ${method.last4}`
: '–';
return {
value: method.id,
label,
};
});
}, [paymentMethods]);
const showPaymentMethods = isImmediatePlanChange && needsPaymentMethod;
return (
<Form
onSubmit={payWithExistingPaymentMethod}
sx={formProps}
>
{showPaymentMethods ? (
<Select
elementId='paymentMethod'
options={options}
value={selectedPaymentMethod?.id || null}
onChange={option => {
const paymentMethod = paymentMethods.find(source => source.id === option.value);
setSelectedPaymentMethod(paymentMethod);
}}
portal
>
{/*Store value inside an input in order to be accessible as form data*/}
<input
name={HIDDEN_INPUT_NAME}
type='hidden'
value={selectedPaymentMethod?.id}
/>
<SelectButton
icon={ChevronUpDown}
sx={t => ({
justifyContent: 'space-between',
backgroundColor: t.colors.$colorBackground,
})}
>
{selectedPaymentMethod && <PaymentMethodRow paymentMethod={selectedPaymentMethod} />}
</SelectButton>
<SelectOptionList
sx={t => ({
paddingBlock: t.space.$1,
color: t.colors.$colorForeground,
})}
/>
</Select>
) : (
<input
name={HIDDEN_INPUT_NAME}
type='hidden'
value={selectedPaymentMethod?.id}
/>
)}
<Card.Alert>{card.error}</Card.Alert>
<CheckoutSubmitButton />
</Form>
);
},
);