Line data Source code
1 : import type {
2 : BillingDeclineReason,
3 : BillingOperationState,
4 : EmbeddedChallenge,
5 : PendingBillingOperation
6 : } from './operationState'
7 :
8 : export type PaymentFrictionSignal =
9 : | { readonly stage: 'challenge_required' }
10 : | { readonly stage: 'challenge_completed' }
11 : | {
12 : readonly stage: 'challenge_failed'
13 : readonly declineReason?: BillingDeclineReason
14 : }
15 :
16 : /**
17 : * What one transition of a pending operation put in the customer's way: a
18 : * challenge first required under a client secret, this tab's verdict on it,
19 : * or a retryable decline with a reason the operation did not hold before.
20 : * The first decline the server reports for a challenge this tab already saw
21 : * fail is the same failure, so it is not reported twice.
22 : */
23 0 : export function paymentFrictionBetween(
24 : before: BillingOperationState | undefined,
25 : after: BillingOperationState
26 : ): readonly PaymentFrictionSignal[] {
27 0 : if (after.phase !== 'pending') return []
28 0 : const earlier = before?.phase === 'pending' ? before : undefined
29 0 : return [
30 : ...challengeSignals(earlier?.challenge, after.challenge),
31 : ...declineSignals(earlier, after)
32 : ]
33 : }
34 :
35 0 : function challengeSignals(
36 : before: EmbeddedChallenge | undefined,
37 : after: EmbeddedChallenge | undefined
38 : ): readonly PaymentFrictionSignal[] {
39 0 : if (after === undefined) return []
40 0 : if (after.clientSecret !== before?.clientSecret) {
41 0 : return after.status === 'required' ? [{ stage: 'challenge_required' }] : []
42 : }
43 0 : if (after.status === before.status) return []
44 0 : if (after.status === 'completed') return [{ stage: 'challenge_completed' }]
45 0 : if (after.status === 'failed') return [{ stage: 'challenge_failed' }]
46 0 : return []
47 : }
48 :
49 0 : function declineSignals(
50 : before: PendingBillingOperation | undefined,
51 : after: PendingBillingOperation
52 : ): readonly PaymentFrictionSignal[] {
53 0 : const reason = after.declineReason
54 0 : if (reason === undefined || reason === before?.declineReason) return []
55 : const echoesFailedChallenge =
56 : after.presentation === 'embedded' &&
57 : after.challenge?.status === 'failed' &&
58 : before?.declineReason === undefined
59 0 : return echoesFailedChallenge
60 : ? []
61 : : [{ stage: 'challenge_failed', declineReason: reason }]
62 : }
|