Line data Source code
1 : /** The dollar presets the Add credits dialog offers, in cents. */
2 2356 : export const ADD_CREDITS_PRESETS_CENTS: readonly number[] = [
3 : 1000, 2500, 5000, 10000
4 : ]
5 :
6 2356 : export const ADD_CREDITS_DEFAULT_CENTS = 5000
7 :
8 : /** Used only while the balance response omits `min_topup_cents` / `max_topup_cents`. */
9 2356 : export const ADD_CREDITS_FALLBACK_BOUNDS: AddCreditsBounds = {
10 : minCents: 500,
11 : maxCents: 250_000
12 : }
13 :
14 : export interface AddCreditsBounds {
15 : readonly minCents: number
16 : readonly maxCents: number
17 : }
18 :
19 : export type AddCreditsAmount =
20 : | { readonly kind: 'preset'; readonly cents: number }
21 : | { readonly kind: 'custom'; readonly input: string }
22 :
23 : export type AddCreditsAmountError = 'below_min' | 'above_max' | 'whole_dollars'
24 :
25 : export type AddCreditsAmountCheck =
26 : | { readonly status: 'empty' }
27 : | { readonly status: 'valid'; readonly cents: number }
28 : | { readonly status: 'invalid'; readonly error: AddCreditsAmountError }
29 :
30 2356 : const WHOLE_DOLLARS = /^(\d+)(?:\.0*)?$/
31 2356 : const DECIMAL = /^\d*\.?\d*$/
32 :
33 8 : function checkCents(
34 : cents: number,
35 : bounds: AddCreditsBounds
36 : ): AddCreditsAmountCheck {
37 8 : if (cents < bounds.minCents) return { status: 'invalid', error: 'below_min' }
38 8 : if (cents > bounds.maxCents) return { status: 'invalid', error: 'above_max' }
39 8 : return { status: 'valid', cents }
40 : }
41 :
42 : /** Whole dollars only: `12`, `12.` and `12.00` are $12; anything else is an error, never rewritten. */
43 8 : export function checkAddCreditsAmount(
44 : amount: AddCreditsAmount,
45 : bounds: AddCreditsBounds
46 : ): AddCreditsAmountCheck {
47 8 : if (amount.kind === 'preset') return checkCents(amount.cents, bounds)
48 0 : const input = amount.input.trim()
49 0 : if (input === '') return { status: 'empty' }
50 0 : const whole = WHOLE_DOLLARS.exec(input)
51 0 : if (whole) return checkCents(Number(whole[1]) * 100, bounds)
52 8 : if (!DECIMAL.test(input) || input === '.') {
53 0 : return { status: 'invalid', error: 'whole_dollars' }
54 : }
55 : const cents = Math.round(Number(input) * 100)
56 8 : return cents < bounds.minCents
57 : ? { status: 'invalid', error: 'below_min' }
58 : : { status: 'invalid', error: 'whole_dollars' }
59 : }
60 :
61 : /**
62 : * The amount the dialog opens with: the served `suggested_topup_amount_cents`
63 : * as a typed amount when it is above the $50 default, else the $50 preset.
64 : */
65 4 : export function initialAddCreditsAmount(
66 : suggestedTopupCents: number | null | undefined
67 : ): AddCreditsAmount {
68 4 : if (
69 : suggestedTopupCents != null &&
70 : suggestedTopupCents > ADD_CREDITS_DEFAULT_CENTS &&
71 : suggestedTopupCents % 100 === 0
72 : ) {
73 0 : return { kind: 'custom', input: String(suggestedTopupCents / 100) }
74 : }
75 4 : return { kind: 'preset', cents: ADD_CREDITS_DEFAULT_CENTS }
76 : }
|