Line data Source code
1 : import type { HostedTopupCheckout } from '@comfyorg/ingest-types'
2 :
3 : export type TopupCheckoutBanner =
4 : | { kind: 'failed'; sessionId: string; paymentAmountCents: number | null }
5 : | { kind: 'creditsApplying'; sessionId: string }
6 : | { kind: 'processing'; sessionId: string }
7 :
8 : export interface TopupCheckoutSnapshot {
9 : newestSessionId: string | null
10 : checkouts: readonly HostedTopupCheckout[]
11 : }
12 :
13 5 : const RANKED_KINDS = [
14 : 'failed',
15 : 'creditsApplying',
16 : 'processing'
17 : ] as const satisfies readonly TopupCheckoutBanner['kind'][]
18 :
19 0 : function servedPaymentAmount(cents: number | null): number | null {
20 0 : return cents !== null && Number.isSafeInteger(cents) && cents >= 0
21 : ? cents
22 : : null
23 : }
24 :
25 0 : function bannerForCheckout(
26 : checkout: HostedTopupCheckout,
27 : newestSessionId: string | null
28 : ): TopupCheckoutBanner | null {
29 0 : const sessionId = checkout.session_id
30 0 : switch (checkout.state) {
31 : case 'failed':
32 0 : return sessionId === newestSessionId
33 : ? {
34 : kind: 'failed',
35 : sessionId,
36 : paymentAmountCents: servedPaymentAmount(
37 : checkout.payment_amount_cents
38 : )
39 : }
40 : : null
41 : case 'credits_applying':
42 0 : return { kind: 'creditsApplying', sessionId }
43 : case 'payment_processing':
44 0 : return { kind: 'processing', sessionId }
45 : default:
46 0 : return null
47 : }
48 : }
49 :
50 0 : export function topupCheckoutBannerKey(banner: TopupCheckoutBanner): string {
51 0 : return `${banner.sessionId}:${banner.kind}`
52 : }
53 :
54 : /** The hosted top-up banner to show; a failed one only while newest. */
55 0 : export function selectTopupCheckoutBanner(
56 : snapshot: TopupCheckoutSnapshot,
57 : dismissed: ReadonlySet<string>
58 : ): TopupCheckoutBanner | null {
59 0 : const banners = snapshot.checkouts
60 : .map((checkout) => bannerForCheckout(checkout, snapshot.newestSessionId))
61 : .filter(
62 : (banner): banner is TopupCheckoutBanner =>
63 : banner !== null && !dismissed.has(topupCheckoutBannerKey(banner))
64 : )
65 0 : for (const kind of RANKED_KINDS) {
66 0 : const banner = banners.find((candidate) => candidate.kind === kind)
67 0 : if (banner) return banner
68 : }
69 0 : return null
70 : }
|