From fe9b6438e8987518a60231d08ffab1a90545b1b2 Mon Sep 17 00:00:00 2001 From: Jeremiah Samuel Date: Tue, 24 Nov 2026 23:49:38 +0100 Subject: [PATCH] feat(mobile): build gift-share flow for passing a subscription to another user (#2005) --- mobile/src/screens/gift/GiftShareScreen.tsx | 216 ++++++- mobile/src/screens/gift/README.md | 45 +- .../gift/__tests__/GiftShareScreen.test.tsx | 42 +- .../src/screens/gift/__tests__/hooks.test.ts | 579 ++++++++++++++++++ mobile/src/screens/gift/hooks.ts | 65 +- mobile/src/screens/gift/index.ts | 2 + mobile/src/screens/gift/types.ts | 33 + 7 files changed, 932 insertions(+), 50 deletions(-) create mode 100644 mobile/src/screens/gift/__tests__/hooks.test.ts diff --git a/mobile/src/screens/gift/GiftShareScreen.tsx b/mobile/src/screens/gift/GiftShareScreen.tsx index b2cd2daa..d8c9e550 100644 --- a/mobile/src/screens/gift/GiftShareScreen.tsx +++ b/mobile/src/screens/gift/GiftShareScreen.tsx @@ -2,8 +2,8 @@ * mobile/src/screens/gift/GiftShareScreen.tsx * * Production-ready subscription gift-share screen for SubTrackr mobile. - * Enables users to transfer/pass a subscription to another user via email - * or Stellar public address with shareable link generation and telemetry. + * Enables users to transfer/pass an active subscription to another user via email + * or Stellar public address with shareable link generation, error retry, and telemetry. */ import React, { useEffect } from 'react'; @@ -42,12 +42,16 @@ export const GiftShareScreen: React.FC = ({ setPersonalMessage, expiresInDays, setExpiresInDays, + allowSenderRevoke, + setAllowSenderRevoke, recipientValidation, error, giftResult, isCopied, handleSelectSubscription, handleProceed, + handleRetry, + handleEditDetails, handleBack, handleCopyLink, handleShareLink, @@ -72,7 +76,9 @@ export const GiftShareScreen: React.FC = ({ ✓ - Gift Share Ready! + + Gift Share Ready! + Your subscription to {giftResult.subscriptionName} can now be claimed by{' '} {giftResult.recipient}. @@ -158,6 +164,59 @@ export const GiftShareScreen: React.FC = ({ ); } + // Dedicated Error State with Retry & Edit Support + if (step === 'error') { + return ( + + + ✕ + + + Gift Share Failed + + + We encountered an issue creating your subscription transfer link. + + + + Error Details + + {error || 'An unexpected failure occurred while creating your gift share ticket.'} + + + + + + ↻ Retry Send + + + + Edit Details + + + + + Cancel + + + ); + } + const isNextDisabled = (step === 'select' && !selectedSubscription) || (step === 'recipient' && !recipientValidation.isValid); @@ -223,7 +282,11 @@ export const GiftShareScreen: React.FC = ({ {/* STEP 1: Select Subscription */} {step === 'select' && ( - + 1. Select Subscription Choose an active subscription to transfer or share. @@ -353,13 +416,18 @@ export const GiftShareScreen: React.FC = ({ {/* Expiry Options */} Claim Expiration Window - + {[3, 7, 14, 30].map((days) => ( setExpiresInDays(days)} - accessibilityRole="button" + accessibilityRole="radio" + accessibilityState={{ selected: expiresInDays === days }} + accessibilityLabel={`${days} days expiration`} testID={`expiry-chip-${days}`}> = ({ ))} + {/* Revocation Safeguard Toggle */} + setAllowSenderRevoke(!allowSenderRevoke)} + accessibilityRole="switch" + accessibilityState={{ checked: allowSenderRevoke }} + accessibilityLabel="Allow sender revocation" + accessibilityHint="Allows you to cancel this gift if recipient does not claim it" + testID="allow-sender-revoke-toggle"> + + Allow Sender Revocation + + Retain ability to cancel this gift if unclaimed before expiration. + + + + + + + {/* Personal Message */} Personal Message (Optional) @@ -438,6 +526,12 @@ export const GiftShareScreen: React.FC = ({ Valid For {expiresInDays} Days + + Revocation Policy + + {allowSenderRevoke ? 'Revocable until claimed' : 'Non-revocable'} + + {personalMessage.length > 0 && ( Note Attached: @@ -781,6 +875,53 @@ const styles = StyleSheet.create({ color: '#38BDF8', fontWeight: '700', }, + toggleCard: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + backgroundColor: '#1E293B', + borderWidth: 1, + borderColor: '#334155', + borderRadius: 8, + padding: 12, + marginVertical: 10, + minHeight: 48, + }, + toggleInfo: { + flex: 1, + marginRight: 12, + }, + toggleTitle: { + fontSize: 13, + fontWeight: '600', + color: '#F8FAFC', + marginBottom: 2, + }, + toggleDescription: { + fontSize: 11, + color: '#94A3B8', + lineHeight: 16, + }, + switchTrack: { + width: 44, + height: 24, + borderRadius: 12, + backgroundColor: '#334155', + padding: 2, + justifyContent: 'center', + }, + switchTrackActive: { + backgroundColor: '#3B82F6', + }, + switchThumb: { + width: 20, + height: 20, + borderRadius: 10, + backgroundColor: '#FFFFFF', + }, + switchThumbActive: { + alignSelf: 'flex-end', + }, messageLabelRow: { flexDirection: 'row', justifyContent: 'space-between', @@ -878,6 +1019,69 @@ const styles = StyleSheet.create({ color: '#10B981', fontWeight: '800', }, + errorBadge: { + width: 64, + height: 64, + borderRadius: 32, + backgroundColor: '#7F1D1D', + borderWidth: 2, + borderColor: '#EF4444', + justifyContent: 'center', + alignItems: 'center', + marginBottom: 16, + }, + errorBadgeIcon: { + fontSize: 28, + color: '#EF4444', + fontWeight: '800', + }, + errorCard: { + backgroundColor: '#1E293B', + borderWidth: 1, + borderColor: '#EF4444', + borderRadius: 10, + padding: 16, + width: '100%', + marginVertical: 16, + }, + errorCardLabel: { + fontSize: 11, + fontWeight: '700', + color: '#F87171', + textTransform: 'uppercase', + letterSpacing: 1, + marginBottom: 6, + }, + errorCardText: { + fontSize: 13, + color: '#FCA5A5', + lineHeight: 20, + }, + errorActionRow: { + flexDirection: 'row', + width: '100%', + marginBottom: 12, + }, + retryButton: { + flex: 1, + backgroundColor: '#2563EB', + marginRight: 8, + }, + editButton: { + flex: 1, + backgroundColor: '#334155', + borderRadius: 10, + paddingVertical: 14, + alignItems: 'center', + justifyContent: 'center', + minHeight: 48, + marginLeft: 8, + }, + editButtonText: { + color: '#F8FAFC', + fontSize: 14, + fontWeight: '600', + }, claimCodeCard: { backgroundColor: '#1E293B', borderWidth: 1.5, diff --git a/mobile/src/screens/gift/README.md b/mobile/src/screens/gift/README.md index d088be2f..26b18e9b 100644 --- a/mobile/src/screens/gift/README.md +++ b/mobile/src/screens/gift/README.md @@ -4,7 +4,7 @@ A production-ready, accessible, and self-contained gift-sharing and transfer sur ## Overview -Enables users to gift or transfer active software subscriptions to friends, colleagues, or team members via email or native Stellar blockchain addresses (`G...`), generating verifiable claim codes and shareable deep links. +Enables users to gift or transfer active software subscriptions to friends, colleagues, or team members via email or native Stellar blockchain addresses (`G...`), generating verifiable claim codes and shareable deep links with error recovery and sender revocation safeguards. ## Key Capabilities @@ -14,18 +14,23 @@ Enables users to gift or transfer active software subscriptions to friends, coll 2. **Deterministic Code & Deep-Link Generation**: - Secure uppercase alphanumeric claim codes (`SUB-XXXX-XXXX`). - Deep-link claim URL construction (`https://subtrackr.app/gift/claim?code=...`). -3. **Configurable Expiry & Revocation**: +3. **Configurable Expiry & Revocation Safeguards**: - Customizable claim window (3, 7, 14, or 30 days) with deterministic expiry calculation. - Revocation safeguards: sender billing continues until the recipient claims the gift, allowing the sender to revoke unclaimed links. + - Sender revocation toggle (`allowSenderRevoke`) persisted in transfer state. 4. **Multi-Delivery Methods**: - `share_link`: Copy link to clipboard or trigger native OS share sheet. - `direct_email`: Sends claim notification email to recipient. - `in_app`: Prepares in-app account transfer ticket. -5. **Observability & Telemetry**: - - Structured metrics hooks: `onView`, `onSelectSubscription`, `onStepChange`, `onGiftShareStart`, `onGiftShareSuccess`, `onGiftShareFailure`, `onCopyLink`, `onShareLink`, `onReset`. +5. **Resilient Error Recovery & Retry**: + - Dedicated `error` state view with structured error messaging. + - One-tap `Retry Send` re-attempts transaction without losing form context. + - `Edit Details` action navigates back to recipient inputs to fix validation or addressing issues. +6. **Observability & Telemetry**: + - Structured metrics hooks: `onView`, `onSelectSubscription`, `onStepChange`, `onGiftShareStart`, `onGiftShareSuccess`, `onGiftShareFailure`, `onRetry`, `onCopyLink`, `onShareLink`, `onReset`. - Pluggable logger interface (`info`, `warn`, `error`). -6. **Accessibility (WCAG 2.1 AA Compliant)**: - - Proper `accessibilityRole` (`radio`, `tab`, `button`, `alert`, `progressbar`, `header`). +7. **Accessibility (WCAG 2.1 AA Compliant)**: + - Proper `accessibilityRole` (`radio`, `radiogroup`, `switch`, `tab`, `tablist`, `button`, `alert`, `progressbar`, `header`). - High-contrast visual cues (#0F172A background, #1E293B surface, #3B82F6 primary, #10B981 success, #EF4444 error). - Minimum touch target dimensions (>= 48x48dp) across buttons, tabs, chips, and radio cards. @@ -35,16 +40,19 @@ Enables users to gift or transfer active software subscriptions to friends, coll ``` [select] ──> [recipient] ──> [confirm] ──> [processing] ──> [success] - │ │ │ - └─────────────┴───────────────┴─────────────────────────> [error] + │ │ │ │ + │ │ │ v + └─────────────┴───────────────┴───────> [error] + │ + (Retry / Edit Details) ``` 1. `select`: User chooses an eligible subscription from their active list. Ineligible subscriptions (paused/canceled) are disabled with clear status notes. -2. `recipient`: User inputs recipient email or Stellar address (with instant validation), delivery method, expiry window, and optional personal note (up to 250 chars). -3. `confirm`: Summary review card highlighting subscription value, recipient details, and transfer conditions. +2. `recipient`: User inputs recipient email or Stellar address (with instant validation), delivery method, expiry window, sender revocation toggle, and optional personal note (up to 250 chars). +3. `confirm`: Summary review card highlighting subscription value, recipient details, expiration, revocation policy, and transfer conditions. 4. `processing`: Accessible spinner while registering the claim ticket. 5. `success`: Claim code, copyable link with clipboard feedback, native share sheet trigger, and done action. -6. `error`: Alert banner with retry support. +6. `error`: Accessible failure card with error details, one-tap `Retry Send`, and `Edit Details` navigation. --- @@ -64,12 +72,16 @@ import { GiftShareScreen } from './screens/gift'; deliveryMethod: formState.deliveryMethod, personalMessage: formState.personalMessage, expiresInDays: formState.expiresInDays, + allowSenderRevoke: formState.allowSenderRevoke, }); }} onBack={() => navigation.goBack()} metrics={{ onGiftShareSuccess: (result) => analytics.track('gift_created', result), + onGiftShareFailure: (error) => analytics.track('gift_failed', { error }), + onRetry: () => analytics.track('gift_retry'), }} + logger={console} /> ``` @@ -77,10 +89,7 @@ import { GiftShareScreen } from './screens/gift'; ## Test Coverage -Unit tests in `__tests__/giftShareLogic.test.ts` and `__tests__/GiftShareScreen.test.tsx` cover: -- Stellar public key and email regex validation. -- Recipient auto-detection and error messages. -- Expiration calculations and clamping. -- Unique claim code formatting and URL building. -- Personal message character length limits. -- Screen rendering, step transitions, input updates, clipboard copying, native sharing, error handling, and telemetry firing. +Unit and integration tests cover: +- **`__tests__/giftShareLogic.test.ts`**: Stellar public key and email regex validation, recipient auto-detection, expiry calculations and clamping, claim code formatting, eligibility checks, and URL building. +- **`__tests__/hooks.test.ts`**: Complete state machine lifecycle (`select` -> `recipient` -> `confirm` -> `processing` -> `success` / `error`), validation guards, error recovery and retry, clipboard copying, native share sheet invocation, state resets, and full telemetry firing. +- **`__tests__/GiftShareScreen.test.tsx`**: Component mounting, error views, processing indicators, props forwarding, and accessibility labels. diff --git a/mobile/src/screens/gift/__tests__/GiftShareScreen.test.tsx b/mobile/src/screens/gift/__tests__/GiftShareScreen.test.tsx index ca06af60..aa447cac 100644 --- a/mobile/src/screens/gift/__tests__/GiftShareScreen.test.tsx +++ b/mobile/src/screens/gift/__tests__/GiftShareScreen.test.tsx @@ -11,7 +11,11 @@ import { useGiftShareFlow } from '../hooks'; import { DEFAULT_SAMPLE_SUBSCRIPTIONS } from '../giftShareLogic'; import type { GiftShareMetrics, GiftShareScreenProps } from '../types'; -// Mock react-native components and modules to prevent React Native native module execution in Node/Jest +beforeAll(() => { + (global as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; +}); + +// Mock react-native components and modules to prevent native module execution in Jest jest.mock('react-native', () => { const ReactActual = jest.requireActual('react'); return { @@ -84,6 +88,7 @@ describe('GiftShareScreen', () => { onGiftShareStart: jest.fn(), onGiftShareSuccess: jest.fn(), onGiftShareFailure: jest.fn(), + onRetry: jest.fn(), onCopyLink: jest.fn(), onShareLink: jest.fn(), onReset: jest.fn(), @@ -107,10 +112,14 @@ describe('GiftShareScreen', () => { logger, }; - const screen = ; - expect(screen).toBeDefined(); - expect(screen.props.initialSubscriptionId).toBe('sub_netflix_4k'); - expect(screen.props.subscriptions).toHaveLength(DEFAULT_SAMPLE_SUBSCRIPTIONS.length); + let tree: renderer.ReactTestRenderer | undefined; + act(() => { + tree = renderer.create(); + }); + + expect(tree).toBeDefined(); + expect(metrics.onView).toHaveBeenCalledTimes(1); + expect(logger.info).toHaveBeenCalledWith('GiftShareScreen mounted'); }); it('supports custom onSendGift callback', () => { @@ -128,18 +137,23 @@ describe('GiftShareScreen', () => { status: 'pending', }); - const screen = ( - - ); + let tree: renderer.ReactTestRenderer | undefined; + act(() => { + tree = renderer.create( + + ); + }); - expect(screen.props.onSendGift).toBe(onSendGift); + expect(tree).toBeDefined(); + expect(metrics.onView).toHaveBeenCalled(); }); - describe('useGiftShareFlow state machine', () => { + describe('useGiftShareFlow state machine integration', () => { it('initializes with default subscription and step select', () => { let stepValue = ''; function TestComponent() { diff --git a/mobile/src/screens/gift/__tests__/hooks.test.ts b/mobile/src/screens/gift/__tests__/hooks.test.ts new file mode 100644 index 00000000..1b33e6ab --- /dev/null +++ b/mobile/src/screens/gift/__tests__/hooks.test.ts @@ -0,0 +1,579 @@ +/** + * mobile/src/screens/gift/__tests__/hooks.test.ts + * + * Pure TypeScript unit tests for `useGiftShareFlow` state machine, + * input validation, step progression, error recovery, clipboard, native share, + * and observability integration. + */ + +import { renderHook, act } from '@testing-library/react-hooks'; +import { useGiftShareFlow } from '../hooks'; +import { DEFAULT_SAMPLE_SUBSCRIPTIONS } from '../giftShareLogic'; +import type { GiftShareMetrics, GiftShareResult } from '../types'; + +beforeAll(() => { + (global as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; +}); + +// Mock react-native Share +jest.mock('react-native', () => ({ + Share: { + share: jest.fn().mockResolvedValue({ action: 'sharedAction' }), + }, +})); + +// Mock expo-clipboard +jest.mock('expo-clipboard', () => ({ + setStringAsync: jest.fn().mockResolvedValue(true), +})); + +describe('useGiftShareFlow hook', () => { + const metrics: Required = { + onView: jest.fn(), + onSelectSubscription: jest.fn(), + onStepChange: jest.fn(), + onGiftShareStart: jest.fn(), + onGiftShareSuccess: jest.fn(), + onGiftShareFailure: jest.fn(), + onRetry: jest.fn(), + onCopyLink: jest.fn(), + onShareLink: jest.fn(), + onReset: jest.fn(), + }; + + const logger = { + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + }; + + beforeEach(() => { + jest.clearAllMocks(); + }); + + describe('Initialization', () => { + it('initializes with default eligible subscription and select step', () => { + const { result } = renderHook(() => + useGiftShareFlow({ + subscriptions: DEFAULT_SAMPLE_SUBSCRIPTIONS, + metrics, + logger, + }) + ); + + expect(result.current.step).toBe('select'); + expect(result.current.selectedSubId).toBe(DEFAULT_SAMPLE_SUBSCRIPTIONS[0].id); + expect(result.current.selectedSubscription).toBeDefined(); + expect(result.current.recipientInput).toBe(''); + expect(result.current.deliveryMethod).toBe('share_link'); + expect(result.current.expiresInDays).toBe(7); + expect(result.current.allowSenderRevoke).toBe(true); + expect(result.current.error).toBeNull(); + }); + + it('falls back to first eligible subscription if initialSubscriptionId is ineligible', () => { + const { result } = renderHook(() => + useGiftShareFlow({ + subscriptions: DEFAULT_SAMPLE_SUBSCRIPTIONS, + initialSubscriptionId: 'sub_gym_paused', // paused sub in sample + metrics, + logger, + }) + ); + + expect(result.current.selectedSubId).toBe(DEFAULT_SAMPLE_SUBSCRIPTIONS[0].id); + expect(result.current.selectedSubscription?.status).toBe('active'); + }); + + it('honors eligible initialSubscriptionId', () => { + const { result } = renderHook(() => + useGiftShareFlow({ + subscriptions: DEFAULT_SAMPLE_SUBSCRIPTIONS, + initialSubscriptionId: 'sub_spotify_duo', + metrics, + logger, + }) + ); + + expect(result.current.selectedSubId).toBe('sub_spotify_duo'); + expect(result.current.selectedSubscription?.name).toBe('Spotify Premium Duo'); + }); + }); + + describe('Subscription Selection', () => { + it('selects valid subscription and triggers telemetry', () => { + const { result } = renderHook(() => + useGiftShareFlow({ + subscriptions: DEFAULT_SAMPLE_SUBSCRIPTIONS, + metrics, + logger, + }) + ); + + act(() => { + result.current.handleSelectSubscription('sub_chatgpt_plus'); + }); + + expect(result.current.selectedSubId).toBe('sub_chatgpt_plus'); + expect(metrics.onSelectSubscription).toHaveBeenCalledWith('sub_chatgpt_plus'); + expect(logger.info).toHaveBeenCalledWith( + 'Selected subscription to gift', + expect.objectContaining({ subId: 'sub_chatgpt_plus' }) + ); + }); + + it('rejects paused or ineligible subscription and sets error', () => { + const { result } = renderHook(() => + useGiftShareFlow({ + subscriptions: DEFAULT_SAMPLE_SUBSCRIPTIONS, + metrics, + logger, + }) + ); + + act(() => { + result.current.handleSelectSubscription('sub_gym_paused'); + }); + + expect(result.current.selectedSubId).toBe(DEFAULT_SAMPLE_SUBSCRIPTIONS[0].id); + expect(result.current.error).toContain('Paused'); + expect(logger.warn).toHaveBeenCalledWith( + 'Ineligible subscription selected', + expect.objectContaining({ subId: 'sub_gym_paused' }) + ); + }); + }); + + describe('Step Transitions and Validations', () => { + it('proceeds from select to recipient when eligible subscription is selected', async () => { + const { result } = renderHook(() => + useGiftShareFlow({ + subscriptions: DEFAULT_SAMPLE_SUBSCRIPTIONS, + metrics, + logger, + }) + ); + + await act(async () => { + await result.current.handleProceed(); + }); + + expect(result.current.step).toBe('recipient'); + expect(metrics.onStepChange).toHaveBeenCalledWith('select', 'recipient'); + }); + + it('validates recipient before advancing from recipient to confirm', async () => { + const { result } = renderHook(() => + useGiftShareFlow({ + subscriptions: DEFAULT_SAMPLE_SUBSCRIPTIONS, + metrics, + logger, + }) + ); + + // Advance to recipient + await act(async () => { + await result.current.handleProceed(); + }); + expect(result.current.step).toBe('recipient'); + + // Attempt proceed with empty recipient + await act(async () => { + await result.current.handleProceed(); + }); + expect(result.current.step).toBe('recipient'); + expect(result.current.error).toContain('required'); + + // Attempt with invalid email + act(() => { + result.current.setRecipientInput('invalid-email-address'); + }); + await act(async () => { + await result.current.handleProceed(); + }); + expect(result.current.step).toBe('recipient'); + expect(result.current.error).toContain('valid email address or Stellar G-address'); + + // Provide valid email + act(() => { + result.current.setRecipientInput('friend@example.com'); + }); + await act(async () => { + await result.current.handleProceed(); + }); + expect(result.current.step).toBe('confirm'); + expect(result.current.error).toBeNull(); + expect(metrics.onStepChange).toHaveBeenCalledWith('recipient', 'confirm'); + }); + + it('validates personal message character length limit', async () => { + const { result } = renderHook(() => + useGiftShareFlow({ + subscriptions: DEFAULT_SAMPLE_SUBSCRIPTIONS, + metrics, + logger, + }) + ); + + // Move to recipient step + await act(async () => { + await result.current.handleProceed(); + }); + + act(() => { + result.current.setRecipientInput('friend@example.com'); + result.current.setPersonalMessage('x'.repeat(251)); // over 250 + }); + + await act(async () => { + await result.current.handleProceed(); + }); + + expect(result.current.step).toBe('recipient'); + expect(result.current.error).toContain('must not exceed 250 characters'); + }); + + it('navigates back across steps correctly with handleBack', async () => { + const { result } = renderHook(() => + useGiftShareFlow({ + subscriptions: DEFAULT_SAMPLE_SUBSCRIPTIONS, + metrics, + logger, + }) + ); + + // Step select -> recipient + await act(async () => { + await result.current.handleProceed(); + }); + expect(result.current.step).toBe('recipient'); + + // Step recipient -> confirm + act(() => { + result.current.setRecipientInput('friend@example.com'); + }); + await act(async () => { + await result.current.handleProceed(); + }); + expect(result.current.step).toBe('confirm'); + + // Back to recipient + act(() => { + result.current.handleBack(); + }); + expect(result.current.step).toBe('recipient'); + + // Back to select + act(() => { + result.current.handleBack(); + }); + expect(result.current.step).toBe('select'); + }); + }); + + describe('Gift Confirmation and Result Generation', () => { + it('creates gift result with default mock generator and triggers success metrics', async () => { + const { result } = renderHook(() => + useGiftShareFlow({ + subscriptions: DEFAULT_SAMPLE_SUBSCRIPTIONS, + metrics, + logger, + }) + ); + + // Advance to recipient + await act(async () => { + await result.current.handleProceed(); + }); + + // Fill recipient and options + act(() => { + result.current.setRecipientInput( + 'GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5' + ); + result.current.setDeliveryMethod('share_link'); + result.current.setExpiresInDays(14); + result.current.setAllowSenderRevoke(true); + result.current.setPersonalMessage('Happy Birthday!'); + }); + + // Advance to confirm + await act(async () => { + await result.current.handleProceed(); + }); + expect(result.current.step).toBe('confirm'); + + // Confirm send + await act(async () => { + await result.current.handleProceed(); + }); + + expect(result.current.step).toBe('success'); + expect(result.current.giftResult).toBeDefined(); + expect(result.current.giftResult?.claimCode).toMatch(/^SUB-/); + expect(result.current.giftResult?.recipientType).toBe('stellar_address'); + expect(result.current.giftResult?.personalMessage).toBe('Happy Birthday!'); + expect(metrics.onGiftShareStart).toHaveBeenCalled(); + expect(metrics.onGiftShareSuccess).toHaveBeenCalledWith(result.current.giftResult); + }); + + it('supports custom onSendGift handler', async () => { + const mockCustomResult: GiftShareResult = { + giftId: 'gift_custom_999', + subscriptionId: 'sub_netflix_4k', + subscriptionName: 'Netflix Premium (4K HDR)', + claimCode: 'SUB-CUST-9999', + shareableUrl: 'https://subtrackr.app/gift/claim?code=SUB-CUST-9999', + recipient: 'colleague@corp.com', + recipientType: 'email', + deliveryMethod: 'direct_email', + createdAt: '2026-11-24T12:00:00.000Z', + expiresAt: '2026-12-01T12:00:00.000Z', + status: 'pending', + }; + + const customOnSendGift = jest.fn().mockResolvedValue(mockCustomResult); + + const { result } = renderHook(() => + useGiftShareFlow({ + subscriptions: DEFAULT_SAMPLE_SUBSCRIPTIONS, + onSendGift: customOnSendGift, + metrics, + logger, + }) + ); + + // select -> recipient + await act(async () => { + await result.current.handleProceed(); + }); + + act(() => { + result.current.setRecipientInput('colleague@corp.com'); + result.current.setDeliveryMethod('direct_email'); + }); + + // recipient -> confirm + await act(async () => { + await result.current.handleProceed(); + }); + + // confirm -> success + await act(async () => { + await result.current.handleProceed(); + }); + + expect(customOnSendGift).toHaveBeenCalledWith( + expect.objectContaining({ + subscriptionId: 'sub_netflix_4k', + recipientInput: 'colleague@corp.com', + deliveryMethod: 'direct_email', + }) + ); + expect(result.current.step).toBe('success'); + expect(result.current.giftResult?.giftId).toBe('gift_custom_999'); + expect(metrics.onGiftShareSuccess).toHaveBeenCalledWith(mockCustomResult); + }); + + it('handles onSendGift failure, transitions to error, and supports retry', async () => { + const failingSendGift = jest + .fn() + .mockRejectedValueOnce(new Error('Network payment timeout')) + .mockResolvedValueOnce({ + giftId: 'gift_retry_success', + subscriptionId: 'sub_netflix_4k', + subscriptionName: 'Netflix Premium (4K HDR)', + claimCode: 'SUB-RETR-1111', + shareableUrl: 'https://subtrackr.app/gift/claim?code=SUB-RETR-1111', + recipient: 'friend@test.com', + recipientType: 'email' as const, + deliveryMethod: 'share_link' as const, + createdAt: '2026-11-24T12:00:00.000Z', + expiresAt: '2026-12-01T12:00:00.000Z', + status: 'pending' as const, + }); + + const { result } = renderHook(() => + useGiftShareFlow({ + subscriptions: DEFAULT_SAMPLE_SUBSCRIPTIONS, + onSendGift: failingSendGift, + metrics, + logger, + }) + ); + + // select -> recipient + await act(async () => { + await result.current.handleProceed(); + }); + + act(() => { + result.current.setRecipientInput('friend@test.com'); + }); + + // recipient -> confirm + await act(async () => { + await result.current.handleProceed(); + }); + + // confirm -> error + await act(async () => { + await result.current.handleProceed(); + }); + + expect(result.current.step).toBe('error'); + expect(result.current.error).toBe('Network payment timeout'); + expect(metrics.onGiftShareFailure).toHaveBeenCalledWith('Network payment timeout'); + expect(logger.error).toHaveBeenCalled(); + + // Retry send + await act(async () => { + await result.current.handleRetry(); + }); + + expect(metrics.onRetry).toHaveBeenCalled(); + expect(result.current.step).toBe('success'); + expect(result.current.giftResult?.giftId).toBe('gift_retry_success'); + }); + + it('allows editing recipient details from error step', async () => { + const failingSend = jest.fn().mockRejectedValue(new Error('Account not found')); + const { result } = renderHook(() => + useGiftShareFlow({ + subscriptions: DEFAULT_SAMPLE_SUBSCRIPTIONS, + onSendGift: failingSend, + metrics, + logger, + }) + ); + + // Navigate to confirm + await act(async () => { + await result.current.handleProceed(); + }); + act(() => { + result.current.setRecipientInput('bad@email.com'); + }); + await act(async () => { + await result.current.handleProceed(); + }); + + // Trigger error + await act(async () => { + await result.current.handleProceed(); + }); + expect(result.current.step).toBe('error'); + + // Click Edit Details + act(() => { + result.current.handleEditDetails(); + }); + + expect(result.current.step).toBe('recipient'); + expect(result.current.error).toBeNull(); + }); + }); + + describe('Clipboard, Sharing, and Reset', () => { + it('copies claim URL to clipboard and logs metrics', async () => { + const { result } = renderHook(() => + useGiftShareFlow({ + subscriptions: DEFAULT_SAMPLE_SUBSCRIPTIONS, + metrics, + logger, + }) + ); + + // Advance through to success + await act(async () => { + await result.current.handleProceed(); + }); + act(() => { + result.current.setRecipientInput('user@subtrackr.com'); + }); + await act(async () => { + await result.current.handleProceed(); + }); + await act(async () => { + await result.current.handleProceed(); + }); + expect(result.current.step).toBe('success'); + + // Copy link + await act(async () => { + await result.current.handleCopyLink(); + }); + + expect(result.current.isCopied).toBe(true); + expect(metrics.onCopyLink).toHaveBeenCalledWith(result.current.giftResult?.giftId); + }); + + it('triggers native share dialog and logs telemetry', async () => { + const { result } = renderHook(() => + useGiftShareFlow({ + subscriptions: DEFAULT_SAMPLE_SUBSCRIPTIONS, + metrics, + logger, + }) + ); + + // Advance to success + await act(async () => { + await result.current.handleProceed(); + }); + act(() => { + result.current.setRecipientInput('user@subtrackr.com'); + }); + await act(async () => { + await result.current.handleProceed(); + }); + await act(async () => { + await result.current.handleProceed(); + }); + + // Share link + await act(async () => { + await result.current.handleShareLink(); + }); + + expect(metrics.onShareLink).toHaveBeenCalledWith(result.current.giftResult?.giftId); + }); + + it('resets flow state back to select step with handleReset', async () => { + const { result } = renderHook(() => + useGiftShareFlow({ + subscriptions: DEFAULT_SAMPLE_SUBSCRIPTIONS, + metrics, + logger, + }) + ); + + // Advance to success + await act(async () => { + await result.current.handleProceed(); + }); + act(() => { + result.current.setRecipientInput('user@subtrackr.com'); + result.current.setPersonalMessage('Enjoy!'); + }); + await act(async () => { + await result.current.handleProceed(); + }); + await act(async () => { + await result.current.handleProceed(); + }); + expect(result.current.step).toBe('success'); + + // Reset + act(() => { + result.current.handleReset(); + }); + + expect(result.current.step).toBe('select'); + expect(result.current.recipientInput).toBe(''); + expect(result.current.personalMessage).toBe(''); + expect(result.current.giftResult).toBeNull(); + expect(metrics.onReset).toHaveBeenCalled(); + }); + }); +}); diff --git a/mobile/src/screens/gift/hooks.ts b/mobile/src/screens/gift/hooks.ts index deff19cc..5879668b 100644 --- a/mobile/src/screens/gift/hooks.ts +++ b/mobile/src/screens/gift/hooks.ts @@ -2,10 +2,10 @@ * mobile/src/screens/gift/hooks.ts * * State machine hook for managing the gift-share flow, step transitions, - * input validation, link sharing, and observability integration. + * input validation, link sharing, error retry, and observability integration. */ -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { Share } from 'react-native'; import * as Clipboard from 'expo-clipboard'; import { @@ -25,6 +25,7 @@ import type { GiftShareMetrics, GiftShareResult, GiftShareStep, + UseGiftShareFlowReturn, } from './types'; export interface UseGiftShareFlowOptions { @@ -41,11 +42,19 @@ export function useGiftShareFlow({ onSendGift, metrics, logger, -}: UseGiftShareFlowOptions = {}) { - const [selectedSubId, setSelectedSubId] = useState( - initialSubscriptionId || (subscriptions[0]?.isGiftable !== false ? subscriptions[0]?.id : null) - ); +}: UseGiftShareFlowOptions = {}): UseGiftShareFlowReturn { + const initialSubId = useMemo(() => { + if (initialSubscriptionId) { + const match = subscriptions.find((s) => s.id === initialSubscriptionId); + if (match && validateGiftEligibility(match).isEligible) { + return match.id; + } + } + const firstEligible = subscriptions.find((s) => validateGiftEligibility(s).isEligible); + return firstEligible ? firstEligible.id : subscriptions[0]?.id || null; + }, [subscriptions, initialSubscriptionId]); + const [selectedSubId, setSelectedSubId] = useState(initialSubId); const [step, setStep] = useState('select'); const [recipientInput, setRecipientInput] = useState(''); const [deliveryMethod, setDeliveryMethod] = useState('share_link'); @@ -56,6 +65,15 @@ export function useGiftShareFlow({ const [error, setError] = useState(null); const [giftResult, setGiftResult] = useState(null); const [isCopied, setIsCopied] = useState(false); + const copyTimeoutRef = useRef | null>(null); + + useEffect(() => { + return () => { + if (copyTimeoutRef.current) { + clearTimeout(copyTimeoutRef.current); + } + }; + }, []); const selectedSubscription = useMemo( () => subscriptions.find((sub) => sub.id === selectedSubId) || null, @@ -153,8 +171,8 @@ export function useGiftShareFlow({ return; } - // Step 3: Confirm -> Processing -> Success / Error - if (step === 'confirm') { + // Step 3 / Error Retry: Confirm -> Processing -> Success / Error + if (step === 'confirm' || step === 'error') { if (!selectedSubscription) { setError('Missing subscription details.'); return; @@ -176,7 +194,6 @@ export function useGiftShareFlow({ if (onSendGift) { result = await onSendGift(formState); } else { - // Default mock handler for demo / tests result = createMockGiftResult(formState, selectedSubscription); } @@ -210,6 +227,18 @@ export function useGiftShareFlow({ logger, ]); + const handleRetry = useCallback(async () => { + metrics?.onRetry?.(); + logger?.info?.('Retrying gift share creation from error step'); + await handleProceed(); + }, [handleProceed, metrics, logger]); + + const handleEditDetails = useCallback(() => { + setError(null); + transitionStep('recipient'); + logger?.info?.('Editing gift details from error state'); + }, [transitionStep, logger]); + const handleBack = useCallback(() => { setError(null); if (step === 'recipient') { @@ -228,7 +257,12 @@ export function useGiftShareFlow({ setIsCopied(true); metrics?.onCopyLink?.(giftResult.giftId); logger?.info?.('Copied gift share URL to clipboard', { giftId: giftResult.giftId }); - setTimeout(() => setIsCopied(false), 3000); + if (copyTimeoutRef.current) clearTimeout(copyTimeoutRef.current); + copyTimeoutRef.current = setTimeout(() => setIsCopied(false), 3000); + const timer = copyTimeoutRef.current as unknown as { unref?: () => void } | null; + if (timer && typeof timer.unref === 'function') { + timer.unref(); + } } catch (err: unknown) { const errorMsg = err instanceof Error ? err.message : String(err); logger?.warn?.('Clipboard copy failed', { error: errorMsg }); @@ -253,18 +287,23 @@ export function useGiftShareFlow({ }, [giftResult, metrics, logger]); const handleReset = useCallback(() => { - setSelectedSubId(subscriptions[0]?.id || null); + setSelectedSubId(initialSubId); setRecipientInput(''); setDeliveryMethod('share_link'); setPersonalMessage(''); setExpiresInDays(DEFAULT_EXPIRY_DAYS); + setAllowSenderRevoke(true); setError(null); setGiftResult(null); setIsCopied(false); + if (copyTimeoutRef.current) { + clearTimeout(copyTimeoutRef.current); + copyTimeoutRef.current = null; + } transitionStep('select'); metrics?.onReset?.(); logger?.info?.('Gift share state reset to default'); - }, [subscriptions, transitionStep, metrics, logger]); + }, [initialSubId, transitionStep, metrics, logger]); return { step, @@ -290,6 +329,8 @@ export function useGiftShareFlow({ isCopied, handleSelectSubscription, handleProceed, + handleRetry, + handleEditDetails, handleBack, handleCopyLink, handleShareLink, diff --git a/mobile/src/screens/gift/index.ts b/mobile/src/screens/gift/index.ts index d912b070..93bfd12a 100644 --- a/mobile/src/screens/gift/index.ts +++ b/mobile/src/screens/gift/index.ts @@ -6,6 +6,7 @@ export { GiftShareScreen } from './GiftShareScreen'; export { useGiftShareFlow } from './hooks'; +export type { UseGiftShareFlowOptions } from './hooks'; export { BASE_CLAIM_URL, DEFAULT_EXPIRY_DAYS, @@ -35,4 +36,5 @@ export type { GiftableSubscription, RecipientType, SubscriptionStatus, + UseGiftShareFlowReturn, } from './types'; diff --git a/mobile/src/screens/gift/types.ts b/mobile/src/screens/gift/types.ts index a819a4a1..98d19d6b 100644 --- a/mobile/src/screens/gift/types.ts +++ b/mobile/src/screens/gift/types.ts @@ -64,6 +64,7 @@ export interface GiftShareMetrics { }) => void; onGiftShareSuccess?: (result: GiftShareResult) => void; onGiftShareFailure?: (error: string) => void; + onRetry?: () => void; onCopyLink?: (giftId: string) => void; onShareLink?: (giftId: string) => void; onReset?: () => void; @@ -84,3 +85,35 @@ export interface GiftShareScreenProps { logger?: GiftShareLogger; testID?: string; } + +export interface UseGiftShareFlowReturn { + step: GiftShareStep; + subscriptions: GiftableSubscription[]; + selectedSubscription: GiftableSubscription | null; + selectedSubId: string | null; + recipientInput: string; + setRecipientInput: (val: string) => void; + deliveryMethod: GiftDeliveryMethod; + setDeliveryMethod: (val: GiftDeliveryMethod) => void; + personalMessage: string; + setPersonalMessage: (val: string) => void; + expiresInDays: number; + setExpiresInDays: (val: number) => void; + allowSenderRevoke: boolean; + setAllowSenderRevoke: (val: boolean) => void; + recipientValidation: { isValid: boolean; type?: RecipientType; error?: string }; + messageValidation: { isValid: boolean; error?: string }; + formState: GiftShareFormState; + error: string | null; + setError: (err: string | null) => void; + giftResult: GiftShareResult | null; + isCopied: boolean; + handleSelectSubscription: (subId: string) => void; + handleProceed: () => Promise; + handleRetry: () => Promise; + handleEditDetails: () => void; + handleBack: () => void; + handleCopyLink: () => Promise; + handleShareLink: () => Promise; + handleReset: () => void; +}