@outerjoyn/react-native 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,10 +7,20 @@ Drop-in loyalty SDK for React Native. Let your customers pay with loyalty points
7
7
  ## Installation
8
8
 
9
9
  ```bash
10
- npm install @outerjoyn/react-native
10
+ npm install @outerjoyn/react-native \
11
+ @react-native-community/slider expo-web-browser
11
12
  ```
12
13
 
13
- That's it. No `pod install`, no Gradle changes, no Expo config plugins.
14
+ `@react-native-community/slider` (exchange amount slider) and
15
+ `expo-web-browser` (in-app OAuth for account linking) are peer dependencies.
16
+ All three are Expo Go compatible.
17
+
18
+ Optional peers, auto-detected if installed:
19
+ - `@react-native-async-storage/async-storage` — offline balance cache
20
+ - `react-native-sse` — live balance updates
21
+ - `react-native-webview` — legacy hosted-widget fallback
22
+
23
+ No `pod install`, no Gradle changes, no Expo config plugins.
14
24
 
15
25
  ## Quick Start
16
26
 
@@ -23,7 +33,7 @@ const outerjoyn = new OuterJoyn('oj_live_YOUR_API_KEY');
23
33
  app.post('/api/loyalty-session', async (req, res) => {
24
34
  const session = await outerjoyn.sessions.create({
25
35
  partner_member_id: req.user.id,
26
- scopes: ['link', 'balance:read', 'pay'],
36
+ scopes: ['link', 'balance:read', 'redeem'],
27
37
  });
28
38
  res.json({ token: session.token });
29
39
  });
@@ -108,7 +118,14 @@ Automatic based on API key prefix:
108
118
 
109
119
  ## Demo Mode
110
120
 
111
- If the API is unreachable, the SDK auto-falls back to demo mode with sample data. All mutation actions disabled. No crashes.
121
+ Demo mode shows sample data with all mutations disabled. It activates only when:
122
+
123
+ - no `sessionToken` is provided (showcase / storybook), or
124
+ - the API is unreachable when the provider first initializes (offline).
125
+
126
+ An authenticated session never silently falls back to demo data on a transient
127
+ API error — screens surface a visible error state (with retry) instead, so demo
128
+ data can't masquerade as a real balance, catalog, or account.
112
129
 
113
130
  ## Theming
114
131
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@outerjoyn/react-native",
3
- "version": "1.1.0",
3
+ "version": "1.3.0",
4
4
  "description": "Drop-in loyalty SDK for React Native. Works in Expo Go.",
5
5
  "main": "src/index.ts",
6
6
  "react-native": "src/index.ts",
@@ -28,6 +28,7 @@
28
28
  "react": ">=18.0.0",
29
29
  "react-native": ">=0.72.0",
30
30
  "@react-native-community/slider": ">=4.0.0",
31
+ "expo-web-browser": ">=12.0.0",
31
32
  "@react-native-async-storage/async-storage": ">=1.19.0"
32
33
  },
33
34
  "peerDependenciesMeta": {
@@ -51,6 +52,7 @@
51
52
  "react-native-webview": "^13.6.0",
52
53
  "@react-native-community/slider": "^4.5.0",
53
54
  "@react-native-async-storage/async-storage": "^1.23.0",
55
+ "expo-web-browser": "^13.0.0",
54
56
  "@types/react": "^18.2.0",
55
57
  "typescript": "^5.4.0"
56
58
  }
@@ -6,11 +6,30 @@ import {
6
6
  TouchableOpacity,
7
7
  Text,
8
8
  ActivityIndicator,
9
+ Linking,
9
10
  } from 'react-native';
10
11
  import { WebView } from 'react-native-webview';
11
12
  import type { WebViewMessage, SDKError } from './types';
12
13
  import { generateWidgetHTML } from './html';
13
14
 
15
+ /**
16
+ * True for a wallet-pass hand-off URL that must go to the OS, not the WebView.
17
+ * A WKWebView can't render a `.pkpass` (no PassKit hand-off) or a Google Wallet
18
+ * save page, so navigating to them in-WebView silently does nothing. We open
19
+ * them with Linking.openURL so iOS presents the "Add Pass" sheet / Google Wallet
20
+ * opens. Matched by URL (not OS) — the widget only surfaces the per-device button.
21
+ */
22
+ export function isWalletPassHandoffUrl(url: string): boolean {
23
+ if (!url) return false;
24
+ const u = url.toLowerCase();
25
+ return (
26
+ (u.includes('/api/wallet/pass/') && (u.endsWith('/apple') || u.endsWith('/google'))) ||
27
+ u.endsWith('.pkpass') ||
28
+ u.includes('pay.google.com') ||
29
+ u.includes('wallet.google')
30
+ );
31
+ }
32
+
14
33
  interface SheetProps {
15
34
  visible: boolean;
16
35
  sessionToken: string;
@@ -128,6 +147,14 @@ export function OuterJoynSheet({
128
147
  bounces={false}
129
148
  showsVerticalScrollIndicator={false}
130
149
  onShouldStartLoadWithRequest={(request) => {
150
+ // Wallet-pass hand-off must go to the OS, not the WebView —
151
+ // check BEFORE the api.outerjoyn.com whitelist (the pkpass URL
152
+ // is on that host, so it would otherwise load in-WebView and
153
+ // do nothing).
154
+ if (isWalletPassHandoffUrl(request.url)) {
155
+ Linking.openURL(request.url).catch(() => {});
156
+ return false;
157
+ }
131
158
  if (
132
159
  request.url === 'about:blank' ||
133
160
  request.url.includes('sdk.outerjoyn.com') ||
@@ -0,0 +1,80 @@
1
+ /**
2
+ * WalletPassButton — drop-in "Add to Wallet" button.
3
+ *
4
+ * The simplest way to let a member save their loyalty card to Apple Wallet or
5
+ * Google Wallet: render the button anywhere, tap opens the WalletPassSheet.
6
+ *
7
+ * ```tsx
8
+ * import { OuterJoynProvider, WalletPassButton } from '@outerjoyn/react-native';
9
+ *
10
+ * <OuterJoynProvider sessionToken={token}>
11
+ * <WalletPassButton />
12
+ * </OuterJoynProvider>
13
+ * ```
14
+ *
15
+ * `sessionToken`/`theme` are auto-read from <OuterJoynProvider> when present, so
16
+ * with a provider no props are required.
17
+ */
18
+
19
+ import React, { useState } from 'react';
20
+ import { Pressable, Text, StyleSheet } from 'react-native';
21
+ import { WalletPassSheet } from './widgets';
22
+ import type { WalletPassButtonProps } from './types';
23
+
24
+ export function WalletPassButton({
25
+ sessionToken,
26
+ apiBaseUrl,
27
+ theme,
28
+ label = 'Add to Wallet',
29
+ style,
30
+ textStyle,
31
+ onSuccess,
32
+ onError,
33
+ }: WalletPassButtonProps) {
34
+ const [open, setOpen] = useState(false);
35
+
36
+ return (
37
+ <>
38
+ <Pressable
39
+ accessibilityRole="button"
40
+ accessibilityLabel={label}
41
+ style={({ pressed }: { pressed: boolean }) => [styles.button, pressed && styles.pressed, style]}
42
+ onPress={() => setOpen(true)}
43
+ >
44
+ <Text style={[styles.label, textStyle]}>{label}</Text>
45
+ </Pressable>
46
+
47
+ <WalletPassSheet
48
+ visible={open}
49
+ sessionToken={sessionToken}
50
+ apiBaseUrl={apiBaseUrl}
51
+ theme={theme}
52
+ onSuccess={(result) => {
53
+ onSuccess?.(result);
54
+ setOpen(false);
55
+ }}
56
+ onError={onError}
57
+ onClose={() => setOpen(false)}
58
+ />
59
+ </>
60
+ );
61
+ }
62
+
63
+ const styles = StyleSheet.create({
64
+ button: {
65
+ backgroundColor: '#111827',
66
+ paddingVertical: 14,
67
+ paddingHorizontal: 20,
68
+ borderRadius: 12,
69
+ alignItems: 'center',
70
+ justifyContent: 'center',
71
+ },
72
+ pressed: {
73
+ opacity: 0.85,
74
+ },
75
+ label: {
76
+ color: '#ffffff',
77
+ fontSize: 16,
78
+ fontWeight: '600',
79
+ },
80
+ });
package/src/index.ts CHANGED
@@ -26,7 +26,10 @@ export { OuterJoynProvider } from './OuterJoynProvider';
26
26
  export { useOuterJoyn } from './useOuterJoyn';
27
27
 
28
28
  // Sheet components — modal bottom sheets (Phase 2)
29
- export { PaySheet, ConnectSheet, ExchangeSheet, RedeemSheet, AccountSheet } from './widgets';
29
+ export { PaySheet, ConnectSheet, ExchangeSheet, RedeemSheet, AccountSheet, WalletPassSheet } from './widgets';
30
+
31
+ // Wallet pass — optional Add-to-Wallet button + sheet (opt-in)
32
+ export { WalletPassButton } from './WalletPassButton';
30
33
 
31
34
  // Inline components — pure RN, no WebView (Phase 3)
32
35
  export {
@@ -93,6 +96,7 @@ export type {
93
96
  ConnectSheetProps,
94
97
  ExchangeSheetProps,
95
98
  RedeemSheetProps,
99
+ WalletPassSheetProps,
96
100
  WalletPassButtonProps,
97
101
  PromotionsViewProps,
98
102
  PayResult,
@@ -255,9 +255,21 @@ export function AccountScreen({
255
255
  }));
256
256
  setActivity([]);
257
257
  } else {
258
- setProfile(DEMO_PROFILE);
259
- setBrands(DEMO_BRANDS);
260
- setActivity(DEMO_ACTIVITY);
258
+ // Real session with zero linked programs — show a genuine empty
259
+ // account, not fabricated demo brands/activity. Previously this
260
+ // rendered "Alex Johnson" + fake SkyMiles for an authenticated user
261
+ // who simply hadn't linked anything yet.
262
+ setProfile({
263
+ member_id: '',
264
+ name: 'Member',
265
+ email: '',
266
+ tier: 'Standard',
267
+ points_balance: 0,
268
+ points_unit: 'Points',
269
+ linked_count: 0,
270
+ });
271
+ setBrands([]);
272
+ setActivity([]);
261
273
  }
262
274
  setLoading(false);
263
275
  }, [visible, isDemo, ctx.linkedPrograms]);
@@ -353,6 +365,13 @@ export function AccountScreen({
353
365
 
354
366
  {/* Connected brands */}
355
367
  <Text style={styles.sectionTitle}>{t('account.programs_linked', { count: String(brands.length) })}</Text>
368
+ {brands.length === 0 && (
369
+ <View style={styles.emptyBrands}>
370
+ <Text style={styles.emptyBrandsText}>
371
+ No loyalty programs linked yet.
372
+ </Text>
373
+ </View>
374
+ )}
356
375
  {brands.map((brand) => (
357
376
  <Pressable key={brand.brand_id} style={styles.brandRow} onPress={() => handleBrandPress(brand)}>
358
377
  <View style={[styles.brandIcon, { backgroundColor: COLORS.primary + '18' }]}>
@@ -588,6 +607,8 @@ const styles = StyleSheet.create({
588
607
 
589
608
  // Section
590
609
  sectionTitle: { fontSize: 14, fontWeight: '700', color: COLORS.muted, textTransform: 'uppercase', marginBottom: 10 },
610
+ emptyBrands: { paddingVertical: 24, alignItems: 'center' },
611
+ emptyBrandsText: { fontSize: 14, color: COLORS.muted, textAlign: 'center' },
591
612
 
592
613
  // Brand rows
593
614
  brandRow: {
@@ -281,18 +281,41 @@ export const ConnectScreen: React.FC<ConnectScreenProps> = ({
281
281
  client = getApiClient();
282
282
  }
283
283
  if (!client) {
284
- setInstitutions([]);
285
- setLinkedInstitutions([]);
286
- setStep('search');
284
+ setErrorMessage('Could not initialize the loyalty session. Please try again.');
285
+ setStep('error');
287
286
  return;
288
287
  }
289
288
 
290
- const [instData, acctData, portableData] = await Promise.all([
291
- client.get<{ institutions: Institution[] }>('/api/sdk/institutions').catch(() => null),
289
+ // Fetch all three concurrently. Institutions are load-bearing — if that
290
+ // call fails the screen has nothing real to show, so surface the error
291
+ // instead of a silently empty "No programs available" list (which masks
292
+ // a broken session or a backend outage as an empty catalog). Account +
293
+ // portable data are supplementary and may fail without blocking the flow.
294
+ // Wrap the institutions promise so a rejection while we await the
295
+ // supplementary calls doesn't surface as an unhandled rejection; we
296
+ // inspect the outcome explicitly below.
297
+ const instResult = client
298
+ .get<{ institutions: Institution[] }>('/api/sdk/institutions')
299
+ .then((data) => ({ ok: true as const, data }))
300
+ .catch((err: any) => ({ ok: false as const, err }));
301
+ const [acctData, portableData, inst] = await Promise.all([
292
302
  client.get<{ connected_brands?: any[] }>('/api/sdk/account').catch(() => null),
293
303
  client.get<{ consent_status?: string; consumer_identity_id?: string }>('/api/sdk/portable-programs').catch(() => null),
304
+ instResult,
294
305
  ]);
295
306
 
307
+ if (!inst.ok) {
308
+ console.warn('[OuterJoyn] ConnectScreen institutions fetch failed:', inst.err?.message ?? inst.err);
309
+ const message =
310
+ inst.err?.message ??
311
+ 'Could not load loyalty programs. Please check your connection and try again.';
312
+ setErrorMessage(message);
313
+ setStep('error');
314
+ onError?.(new Error(message));
315
+ return;
316
+ }
317
+ const instData = inst.data;
318
+
296
319
  // Check if link portability consent is needed
297
320
  if (portableData?.consent_status === 'required') {
298
321
  setConsentRequired(true);
@@ -323,9 +346,12 @@ export const ConnectScreen: React.FC<ConnectScreenProps> = ({
323
346
  }
324
347
  } catch (err: any) {
325
348
  console.warn('[OuterJoyn] ConnectScreen loadData failed:', err.message);
326
- setInstitutions([]);
327
- setLinkedInstitutions([]);
328
- setStep('search');
349
+ const message =
350
+ err?.message ??
351
+ 'Could not load loyalty programs. Please check your connection and try again.';
352
+ setErrorMessage(message);
353
+ setStep('error');
354
+ onError?.(new Error(message));
329
355
  }
330
356
  }, [isDemoMode, preselectedInstitutionId, apiBaseUrl, sessionToken, onError]);
331
357
 
@@ -599,6 +625,40 @@ export const ConnectScreen: React.FC<ConnectScreenProps> = ({
599
625
  );
600
626
  };
601
627
 
628
+ // Plaid-style grid tile — default (no-search) picker view. Mirrors the web
629
+ // SDK ConnectWidget's institution-select grid; searching switches to the
630
+ // detailed renderInstitutionItem rows where linked/portable state helps
631
+ // disambiguate near-matches.
632
+ const renderGridItem = ({ item }: { item: Institution }) => {
633
+ const isLinked = linkedIds.has(item.institution_id) || providerLinkedNames.has(item.name.toLowerCase());
634
+ const isPortable = portableNames.has(item.name.toLowerCase());
635
+ return (
636
+ <Pressable
637
+ style={[s.gridTile, isLinked && s.gridTileLinked]}
638
+ onPress={() => handleSelectInstitution(item)}
639
+ accessibilityRole="button"
640
+ accessibilityLabel={isLinked ? `${item.name} (already connected)` : `Connect ${item.name}`}
641
+ >
642
+ {item.logo_url ? (
643
+ <Image source={{ uri: item.logo_url }} style={s.institutionLogo} resizeMode="contain" />
644
+ ) : (
645
+ <View style={[s.institutionLogoFallback, { backgroundColor: C.primary }]}>
646
+ <Text style={s.logoFallbackText}>{item.name.charAt(0).toUpperCase()}</Text>
647
+ </View>
648
+ )}
649
+ <Text style={s.gridTileName} numberOfLines={1}>
650
+ {item.name}
651
+ </Text>
652
+ {isLinked && (
653
+ <View style={[s.linkedBadge, { marginLeft: 0, marginTop: 6 }]}>
654
+ <Text style={s.linkedBadgeCheck}>{'✓'}</Text>
655
+ <Text style={s.linkedBadgeText}>{isPortable ? 'Portable' : t('connect.connected')}</Text>
656
+ </View>
657
+ )}
658
+ </Pressable>
659
+ );
660
+ };
661
+
602
662
  const renderSearch = () => (
603
663
  <View style={s.flex1}>
604
664
  {/* Header */}
@@ -658,11 +718,16 @@ export const ConnectScreen: React.FC<ConnectScreenProps> = ({
658
718
  </View>
659
719
  )}
660
720
 
661
- {/* Institution List */}
721
+ {/* Institution List — Plaid-style: 2-column brand grid by default,
722
+ detailed rows once the user types. `key` forces the remount
723
+ FlatList requires when numColumns changes. */}
662
724
  <FlatList
725
+ key={search.trim() === '' ? 'grid' : 'list'}
663
726
  data={filteredInstitutions}
664
727
  keyExtractor={(item) => item.institution_id}
665
- renderItem={renderInstitutionItem}
728
+ renderItem={search.trim() === '' ? renderGridItem : renderInstitutionItem}
729
+ numColumns={search.trim() === '' ? 2 : 1}
730
+ columnWrapperStyle={search.trim() === '' ? s.gridColumnWrapper : undefined}
666
731
  contentContainerStyle={s.listContent}
667
732
  showsVerticalScrollIndicator={false}
668
733
  keyboardShouldPersistTaps="handled"
@@ -773,7 +838,7 @@ export const ConnectScreen: React.FC<ConnectScreenProps> = ({
773
838
  {selectedInstitution.logo_url ? (
774
839
  <Image source={{ uri: selectedInstitution.logo_url }} style={s.consentLogo} resizeMode="contain" />
775
840
  ) : (
776
- <View style={[s.consentLogoFallback, { backgroundColor: C.success }]}>
841
+ <View style={[s.consentLogoFallback, { backgroundColor: C.primary }]}>
777
842
  <Text style={s.consentLogoFallbackText}>
778
843
  {selectedInstitution.name.charAt(0).toUpperCase()}
779
844
  </Text>
@@ -830,36 +895,53 @@ export const ConnectScreen: React.FC<ConnectScreenProps> = ({
830
895
  ) as any;
831
896
 
832
897
  const client = getApiClient();
833
- if (client) {
834
- try {
835
- await client.post('/api/sdk/sessions/connect/disconnect', {
898
+ if (!client) {
899
+ onError?.({ code: 'no_client', message: 'Cannot disconnect — no API client available.' } as any);
900
+ return;
901
+ }
902
+
903
+ // The disconnect MUST persist server-side, otherwise the
904
+ // program reappears as "Connected" on the next open (the
905
+ // linked list is rebuilt from sessions/context). So we only
906
+ // update the UI after a confirmed server write — no more
907
+ // swallowing the error and faking a local "disconnected"
908
+ // mask (which loadData() reset on every reopen).
909
+ try {
910
+ const resp = await client.post<{ disconnected_links?: number }>(
911
+ '/api/sdk/sessions/connect/disconnect',
912
+ {
836
913
  ...(providerMatch?.partnershipId
837
914
  ? { partnership_id: providerMatch.partnershipId }
838
915
  : { institution_id: selectedInstitution.institution_id }),
839
- });
840
- } catch (err) {
841
- console.warn('[OuterJoyn] Disconnect API failed:', (err as Error)?.message);
916
+ },
917
+ );
918
+
919
+ // A 2xx is not enough — the server returns how many links
920
+ // it actually deactivated. If we sent an id it couldn't
921
+ // match (e.g. wrong id-space), it 2xx-no-ops with
922
+ // disconnected_links: 0, and the program is STILL linked.
923
+ // Treat that as a failure so we don't wrongly prune the UI
924
+ // (which would show it "gone" until the next reload).
925
+ const removed = Number(resp?.disconnected_links ?? 0);
926
+ if (!Number.isFinite(removed) || removed < 1) {
927
+ onError?.({ code: 'disconnect_noop', message: 'Could not disconnect this program. Please try again.' } as any);
928
+ Alert.alert(t('account.unlink'), 'Could not disconnect this program. Please try again.');
929
+ return; // do NOT mutate UI — the link is still connected
842
930
  }
843
- } else {
844
- console.warn('[OuterJoyn] Disconnect skipped — no API client available');
845
- }
846
-
847
- // Remove from provider state so balance UI updates
848
- const unlinkFn = (ctx as any)?.unlinkProgram;
849
- if (typeof unlinkFn === 'function' && providerMatch?.id) {
850
- unlinkFn(providerMatch.id);
931
+ } catch (err) {
932
+ console.warn('[OuterJoyn] Disconnect API failed:', (err as Error)?.message);
933
+ onError?.({ code: 'disconnect_failed', message: (err as Error)?.message || 'Disconnect failed. Please try again.' } as any);
934
+ Alert.alert(t('account.unlink'), (err as Error)?.message || 'Disconnect failed. Please try again.');
935
+ return; // do NOT mutate UI — the link is still connected
851
936
  }
852
937
 
853
- // Refresh provider balances and wait for it to settle
938
+ // Confirmed server-side. Refresh the authoritative linked
939
+ // list and wait for it to settle before trusting the UI.
854
940
  const refreshFn = (ctx as any)?.refreshBalances;
855
941
  if (typeof refreshFn === 'function') {
856
942
  try { await refreshFn(); } catch { /* non-fatal */ }
857
943
  }
858
944
 
859
- // Mark as disconnected so derived linked checks
860
- // exclude it even if provider context is stale.
861
- const disconnectedName = selectedInstitution.name.toLowerCase();
862
- setDisconnectedNames((prev) => new Set(prev).add(disconnectedName));
863
945
  setLinkedInstitutions((prev) =>
864
946
  prev.filter((li) => li.institution_id !== selectedInstitution.institution_id),
865
947
  );
@@ -935,7 +1017,7 @@ export const ConnectScreen: React.FC<ConnectScreenProps> = ({
935
1017
  </View>
936
1018
  <Text style={s.errorTitle}>{t('common.error')}</Text>
937
1019
  <Text style={s.errorDesc}>{errorMessage || t('common.error')}</Text>
938
- <Pressable style={s.retryBtn} onPress={handleBack}>
1020
+ <Pressable style={s.retryBtn} onPress={loadData}>
939
1021
  <Text style={s.retryBtnText}>{t('common.retry')}</Text>
940
1022
  </Pressable>
941
1023
  <Pressable style={s.closeBtnSecondary} onPress={handleClose}>
@@ -1037,7 +1119,9 @@ const s = StyleSheet.create({
1037
1119
  paddingHorizontal: 14,
1038
1120
  height: 48,
1039
1121
  backgroundColor: '#F1F5F9',
1040
- borderRadius: 12,
1122
+ // Pill search — Plaid-style picker (parity with the web SDK ConnectWidget
1123
+ // + wallet-web ConnectModal, 2026-07-21).
1124
+ borderRadius: 999,
1041
1125
  borderWidth: 1,
1042
1126
  borderColor: C.border,
1043
1127
  },
@@ -1059,6 +1143,34 @@ const s = StyleSheet.create({
1059
1143
  paddingTop: 8,
1060
1144
  paddingBottom: 24,
1061
1145
  },
1146
+ // Plaid-style 2-column brand grid — the default (no-search) picker view;
1147
+ // typing a query switches to the detailed rows. Parity with the web SDK
1148
+ // ConnectWidget + wallet-web ConnectModal (2026-07-21).
1149
+ gridColumnWrapper: {
1150
+ gap: 10,
1151
+ },
1152
+ gridTile: {
1153
+ flex: 1,
1154
+ alignItems: 'center',
1155
+ paddingVertical: 16,
1156
+ paddingHorizontal: 10,
1157
+ marginBottom: 10,
1158
+ borderRadius: 16,
1159
+ borderWidth: 1,
1160
+ borderColor: C.border,
1161
+ backgroundColor: C.bg,
1162
+ },
1163
+ gridTileLinked: {
1164
+ borderColor: `${C.success}60`,
1165
+ backgroundColor: `${C.success}06`,
1166
+ },
1167
+ gridTileName: {
1168
+ fontSize: 12.5,
1169
+ fontWeight: '700',
1170
+ color: C.text,
1171
+ marginTop: 8,
1172
+ textAlign: 'center',
1173
+ },
1062
1174
  institutionRow: {
1063
1175
  flexDirection: 'row',
1064
1176
  alignItems: 'center',
@@ -1167,7 +1279,7 @@ const s = StyleSheet.create({
1167
1279
  backgroundColor: `${C.primary}08`,
1168
1280
  },
1169
1281
  consentHeaderLinked: {
1170
- backgroundColor: `${C.success}08`,
1282
+ backgroundColor: C.bgSecondary,
1171
1283
  },
1172
1284
  consentLogo: {
1173
1285
  width: 56,
@@ -1318,11 +1430,11 @@ const s = StyleSheet.create({
1318
1430
  paddingHorizontal: 24,
1319
1431
  borderTopWidth: 1,
1320
1432
  borderTopColor: C.border,
1321
- backgroundColor: '#f0fdf4',
1433
+ backgroundColor: C.bgSecondary,
1322
1434
  },
1323
1435
  securityText: {
1324
1436
  fontSize: 11,
1325
- color: '#15803d',
1437
+ color: C.textTertiary,
1326
1438
  textAlign: 'center',
1327
1439
  },
1328
1440
  securityRow: {
@@ -1335,7 +1447,7 @@ const s = StyleSheet.create({
1335
1447
  },
1336
1448
  securityLabel: {
1337
1449
  fontSize: 11,
1338
- color: '#15803d',
1450
+ color: C.textTertiary,
1339
1451
  fontWeight: '500',
1340
1452
  },
1341
1453
  securityLogo: {
@@ -121,8 +121,14 @@ export function ExchangeScreen({
121
121
  const ctx = useOuterJoyn();
122
122
  const { t } = ctx;
123
123
  const token = propToken ?? ctx.sessionToken;
124
- const programs = ctx.linkedPrograms.length > 0 ? ctx.linkedPrograms : DEMO_PROGRAMS;
125
- const isDemo = ctx.demoMode || programs === DEMO_PROGRAMS;
124
+ // Demo mode (offline/no-token showcase) uses sample programs. A real
125
+ // authenticated session ALWAYS uses its actual linked programs — never
126
+ // substitute fabricated SkyMiles/Glow programs, which would present a
127
+ // live-looking exchange UI the user can't actually execute.
128
+ const isDemo = ctx.demoMode || !token;
129
+ const programs = isDemo ? DEMO_PROGRAMS : ctx.linkedPrograms;
130
+ // Points exchange requires at least two linked programs to move between.
131
+ const hasEnoughPrograms = programs.length >= 2;
126
132
 
127
133
  // Use shared API client from context, fall back to creating one (fix #11)
128
134
  const clientRef = useRef<APIClient | null>(null);
@@ -334,7 +340,28 @@ export function ExchangeScreen({
334
340
  // Render steps
335
341
  // =========================================================================
336
342
 
337
- const renderAmount = () => (
343
+ const renderAmount = () => {
344
+ if (!hasEnoughPrograms) {
345
+ return (
346
+ <View style={styles.centeredContent}>
347
+ <Text style={styles.emptyTitle}>Not enough programs to exchange</Text>
348
+ <Text style={styles.emptyDetail}>
349
+ You need at least two linked loyalty programs to move points between
350
+ them. Link another program to get started.
351
+ </Text>
352
+ <Pressable
353
+ style={styles.primaryButton}
354
+ onPress={() => {
355
+ onClose?.();
356
+ ctx.openConnect();
357
+ }}
358
+ >
359
+ <Text style={styles.primaryButtonText}>Link a program</Text>
360
+ </Pressable>
361
+ </View>
362
+ );
363
+ }
364
+ return (
338
365
  <ScrollView style={styles.content} keyboardShouldPersistTaps="handled">
339
366
  {/* Source */}
340
367
  {renderPicker(source, setSource, target?.id ?? null, showSourcePicker, setShowSourcePicker, t('exchange.from'))}
@@ -407,7 +434,8 @@ export function ExchangeScreen({
407
434
  <Text style={styles.primaryButtonText}>{t('exchange.confirm')}</Text>
408
435
  </Pressable>
409
436
  </ScrollView>
410
- );
437
+ );
438
+ };
411
439
 
412
440
  const renderConfirm = () => (
413
441
  <View style={styles.content}>
@@ -676,6 +704,10 @@ const styles = StyleSheet.create({
676
704
  // Processing
677
705
  processingText: { fontSize: 16, color: COLORS.muted, marginTop: 16 },
678
706
 
707
+ // Empty (not enough programs)
708
+ emptyTitle: { fontSize: 20, fontWeight: '700', color: COLORS.text, marginBottom: 10, textAlign: 'center' },
709
+ emptyDetail: { fontSize: 15, color: COLORS.muted, textAlign: 'center', lineHeight: 22, marginBottom: 8 },
710
+
679
711
  // Success
680
712
  checkCircle: {
681
713
  width: 64,
@@ -22,6 +22,7 @@ import {
22
22
  Image,
23
23
  StyleSheet,
24
24
  Alert,
25
+ Linking,
25
26
  } from 'react-native';
26
27
  import { useOuterJoyn } from '../useOuterJoyn';
27
28
  import { APIClient } from '../core/api-client';
@@ -51,6 +52,14 @@ interface RedemptionResult {
51
52
  pointsCost: number;
52
53
  code?: string;
53
54
  status: string;
55
+ /**
56
+ * Reward-row identity from the redemption's fulfillment. Present only when the
57
+ * redeemed product actually issued a wallet-eligible reward (voucher/coupon/
58
+ * gift card). Used to gate + mint the "Add to Wallet" pass. Absent today until
59
+ * Go instant-code fulfillment ships, so the wallet button stays hidden.
60
+ */
61
+ rewardId?: string;
62
+ rewardType?: string;
54
63
  }
55
64
 
56
65
  interface CatalogItem {
@@ -132,7 +141,11 @@ export function RedeemScreen({
132
141
  const [selectedItem, setSelectedItem] = useState<CatalogItem | null>(null);
133
142
  const [result, setResult] = useState<RedemptionResult | null>(null);
134
143
  const [error, setError] = useState<string | null>(null);
135
- const [balance, setBalance] = useState(DEMO_BALANCE);
144
+ // Add-to-Wallet state on the success screen.
145
+ const [walletState, setWalletState] = useState<'idle' | 'adding' | 'added' | 'unavailable'>('idle');
146
+ // Start at 0 for real sessions; demo mode explicitly sets DEMO_BALANCE below.
147
+ const [balance, setBalance] = useState(0);
148
+ const [reloadKey, setReloadKey] = useState(0);
136
149
  const searchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
137
150
 
138
151
  // Load catalog
@@ -143,14 +156,18 @@ export function RedeemScreen({
143
156
  setBalance(ctx.totalAvailablePoints || DEMO_BALANCE);
144
157
  return;
145
158
  }
146
- // If apiClient not yet initialized, fall back to demo catalog
159
+ // If apiClient not yet initialized, wait — the effect re-runs when
160
+ // ctx.apiClient lands (clientRef is updated in a sibling effect and
161
+ // ctx.apiClient is a dependency below). Do NOT substitute the demo
162
+ // catalog for a real session: that would show fabricated rewards a
163
+ // user can't actually redeem.
147
164
  if (!clientRef.current) {
148
- setCatalog(DEMO_CATALOG);
149
- setBalance(ctx.totalAvailablePoints || DEMO_BALANCE);
150
165
  return;
151
166
  }
152
167
 
153
168
  setLoading(true);
169
+ setError(null);
170
+ setStep('catalog');
154
171
  clientRef.current
155
172
  .get<any>('/api/sdk/catalog')
156
173
  .then((data) => {
@@ -171,16 +188,23 @@ export function RedeemScreen({
171
188
  terms_and_conditions: item.terms_and_conditions ?? item.termsAndConditions,
172
189
  expiry_days: item.expiry_days ?? item.expiryDays,
173
190
  }));
174
- setCatalog(normalized.length > 0 ? normalized : DEMO_CATALOG);
191
+ // A genuinely empty catalog is a real (empty) state — render it as
192
+ // such via ListEmptyComponent rather than masking it with demo items.
193
+ setCatalog(normalized);
194
+ })
195
+ .catch((e: any) => {
196
+ // Real session, catalog failed to load: surface the failure instead
197
+ // of silently showing a fake catalog the user can't redeem against.
198
+ setError(e?.message ?? 'Could not load rewards. Please try again.');
199
+ setStep('error');
175
200
  })
176
- .catch(() => setCatalog(DEMO_CATALOG))
177
201
  .finally(() => setLoading(false));
178
202
 
179
203
  clientRef.current
180
204
  .get<any>('/api/sdk/balance')
181
- .then((data) => setBalance(data?.points_balance ?? data?.pointsBalance ?? data?.balance ?? DEMO_BALANCE))
205
+ .then((data) => setBalance(data?.points_balance ?? data?.pointsBalance ?? data?.balance ?? 0))
182
206
  .catch(() => {});
183
- }, [visible, isDemo]);
207
+ }, [visible, isDemo, ctx.apiClient, reloadKey]);
184
208
 
185
209
  // Reset on close
186
210
  useEffect(() => {
@@ -255,8 +279,12 @@ export function RedeemScreen({
255
279
  pointsCost: selectedItem.points_cost,
256
280
  code: data.code ?? data.fulfillment?.code,
257
281
  status: data.status ?? 'fulfilled',
282
+ // Snowflake IDs stay strings.
283
+ rewardId: data.fulfillment?.rewardId != null ? String(data.fulfillment.rewardId) : undefined,
284
+ rewardType: data.fulfillment?.rewardType,
258
285
  };
259
286
  setResult(res);
287
+ setWalletState('idle');
260
288
  setStep('success');
261
289
  onSuccess?.(res);
262
290
  ctx.refreshBalances();
@@ -279,6 +307,39 @@ export function RedeemScreen({
279
307
  }
280
308
  }, [result]);
281
309
 
310
+ // Add the just-redeemed reward to the wallet: mint a reward pass server-side
311
+ // from the redemption, then open the platform hand-off URL (iOS shows the
312
+ // Add-Pass sheet; Android opens Google Wallet). Only reachable when the
313
+ // redemption actually issued a wallet-eligible reward (result.rewardId set).
314
+ const handleAddToWallet = useCallback(async () => {
315
+ if (!result?.redemptionId || !clientRef.current) return;
316
+ setWalletState('adding');
317
+ try {
318
+ if (isDemo) {
319
+ await new Promise((r) => setTimeout(r, 700));
320
+ setWalletState('added');
321
+ return;
322
+ }
323
+ const data = await clientRef.current.post<any>('/api/sdk/wallet/passes/from-redemption', {
324
+ redemptionId: String(result.redemptionId),
325
+ });
326
+ const pass = data?.pass;
327
+ // iOS → .pkpass; Android → Google save URL. Linking hands it to the OS.
328
+ const url = pass?.appleDownloadUrl || pass?.googleSaveUrl;
329
+ if (url) await Linking.openURL(url).catch(() => {});
330
+ setWalletState('added');
331
+ } catch (e: any) {
332
+ // Brand has no reward template / redemption not pass-eligible → hide the
333
+ // button rather than show an error.
334
+ if (/no_default_template|no_brand|not_pass_eligible/.test(e?.message ?? '')) {
335
+ setWalletState('unavailable');
336
+ } else {
337
+ setWalletState('idle');
338
+ Alert.alert('Add to Wallet', e?.message ?? 'Could not add to wallet.');
339
+ }
340
+ }
341
+ }, [result, isDemo]);
342
+
282
343
  const fmt = (n: number) => n.toLocaleString();
283
344
 
284
345
  // =========================================================================
@@ -426,7 +487,22 @@ export function RedeemScreen({
426
487
  </Pressable>
427
488
  )}
428
489
 
429
- <Pressable style={styles.primaryButton} onPress={() => { setStep('catalog'); setSelectedItem(null); }}>
490
+ {/* Add to Wallet — only for a wallet-eligible reward (rewardId present) and
491
+ while it hasn't been marked unavailable. Hidden for rewards that don't
492
+ issue a code, so nothing looks broken. */}
493
+ {result?.rewardId && result?.code && walletState !== 'unavailable' && (
494
+ <Pressable
495
+ style={[styles.walletButton, (walletState === 'adding' || walletState === 'added') && styles.walletButtonDisabled]}
496
+ onPress={handleAddToWallet}
497
+ disabled={walletState === 'adding' || walletState === 'added'}
498
+ >
499
+ <Text style={styles.walletButtonText}>
500
+ {walletState === 'added' ? '✓ Added to Wallet' : walletState === 'adding' ? 'Adding…' : 'Add to Wallet'}
501
+ </Text>
502
+ </Pressable>
503
+ )}
504
+
505
+ <Pressable style={styles.primaryButton} onPress={() => { setStep('catalog'); setSelectedItem(null); setWalletState('idle'); }}>
430
506
  <Text style={styles.primaryButtonText}>{t('redeem.browse_more')}</Text>
431
507
  </Pressable>
432
508
  <Pressable style={styles.secondaryButton} onPress={onClose}>
@@ -442,7 +518,19 @@ export function RedeemScreen({
442
518
  </View>
443
519
  <Text style={styles.errorTitle}>{t('common.error')}</Text>
444
520
  <Text style={styles.errorDetail}>{error ?? t('common.error')}</Text>
445
- <Pressable style={styles.primaryButton} onPress={() => setStep('confirm')}>
521
+ <Pressable
522
+ style={styles.primaryButton}
523
+ onPress={() => {
524
+ // If the catalog itself failed to load there's no item to
525
+ // re-confirm — reload the catalog. Otherwise retry the redemption.
526
+ if (catalog.length === 0 || !selectedItem) {
527
+ setError(null);
528
+ setReloadKey((k) => k + 1);
529
+ } else {
530
+ setStep('confirm');
531
+ }
532
+ }}
533
+ >
446
534
  <Text style={styles.primaryButtonText}>{t('common.retry')}</Text>
447
535
  </Pressable>
448
536
  <Pressable style={styles.secondaryButton} onPress={onClose}>
@@ -616,6 +704,17 @@ const styles = StyleSheet.create({
616
704
  width: '100%',
617
705
  },
618
706
  primaryButtonText: { fontSize: 16, fontWeight: '700', color: '#FFFFFF' },
707
+ walletButton: {
708
+ marginTop: 12,
709
+ paddingVertical: 16,
710
+ borderRadius: 14,
711
+ // Apple/Google wallet-badge black convention.
712
+ backgroundColor: '#000000',
713
+ alignItems: 'center',
714
+ width: '100%',
715
+ },
716
+ walletButtonDisabled: { opacity: 0.7 },
717
+ walletButtonText: { fontSize: 16, fontWeight: '700', color: '#FFFFFF' },
619
718
  disabledButton: { opacity: 0.4 },
620
719
  secondaryButton: { marginTop: 12, paddingVertical: 14, alignItems: 'center' },
621
720
  secondaryButtonText: { fontSize: 15, fontWeight: '600', color: COLORS.muted },
package/src/types.ts CHANGED
@@ -61,9 +61,30 @@ export interface RedeemSheetProps extends OuterJoynConfig {
61
61
  onClose?: () => void;
62
62
  }
63
63
 
64
+ export interface WalletPassSheetProps extends OuterJoynConfig {
65
+ /** Whether the sheet is visible */
66
+ visible: boolean;
67
+ /** Called after the pass is added / the save flow completes */
68
+ onSuccess?: (result: any) => void;
69
+ onError?: (error: SDKError) => void;
70
+ /** Called when the user closes the sheet */
71
+ onClose?: () => void;
72
+ /**
73
+ * One-tap: when the member has a single active pass, auto-fire the Add-to-Wallet
74
+ * hand-off as soon as the sheet opens instead of showing an in-sheet button the
75
+ * user must tap again. Defaults to true — opening this sheet is already an
76
+ * explicit "Add to Wallet" intent. Set false to always show the pass list.
77
+ */
78
+ autoAdd?: boolean;
79
+ }
80
+
64
81
  export interface WalletPassButtonProps extends OuterJoynConfig {
65
- /** Pass type */
66
- passType?: 'apple' | 'google' | 'both';
82
+ /** Button label (default: "Add to Wallet") */
83
+ label?: string;
84
+ /** Optional style override for the touchable container */
85
+ style?: any;
86
+ /** Optional style override for the label text */
87
+ textStyle?: any;
67
88
  onSuccess?: (result: any) => void;
68
89
  onError?: (error: SDKError) => void;
69
90
  }
package/src/widgets.tsx CHANGED
@@ -16,6 +16,7 @@ import type {
16
16
  ConnectSheetProps,
17
17
  ExchangeSheetProps,
18
18
  RedeemSheetProps,
19
+ WalletPassSheetProps,
19
20
  } from './types';
20
21
 
21
22
  // Try to read from provider context (optional — sheets work standalone too)
@@ -224,3 +225,51 @@ export function AccountSheet({
224
225
  />
225
226
  );
226
227
  }
228
+
229
+ /**
230
+ * Add-to-Wallet bottom sheet (Apple Wallet / Google Wallet).
231
+ *
232
+ * Renders the SDK's `walletPass` widget, which detects the device and shows the
233
+ * platform-appropriate Add-to-Apple-Wallet / Save-to-Google-Wallet badge, then
234
+ * hands off to the pass-add flow. Like the other sheets, `sessionToken` and
235
+ * `theme` are auto-read from <OuterJoynProvider> when present.
236
+ *
237
+ * NOTE (v1): this uses the CDN web widget in a WebView. A future release will
238
+ * add a native module that hands the signed `.pkpass` to iOS
239
+ * `PKAddPassesViewController` directly — see docs guide "Wallet Pass (SDK)".
240
+ */
241
+ export function WalletPassSheet({
242
+ visible,
243
+ sessionToken,
244
+ apiBaseUrl,
245
+ theme,
246
+ onSuccess,
247
+ onError,
248
+ onClose,
249
+ autoAdd = true,
250
+ }: WalletPassSheetProps) {
251
+ const ctx = useOptionalContext();
252
+ const token = sessionToken || ctx?.sessionToken;
253
+ const base = apiBaseUrl || ctx?.apiBaseUrl;
254
+ const resolvedTheme = theme || ctx?.brandConfig?.theme;
255
+
256
+ return (
257
+ <OuterJoynSheet
258
+ visible={visible}
259
+ sessionToken={token}
260
+ apiBaseUrl={base}
261
+ theme={resolvedTheme}
262
+ // The SDK registers this widget under the camelCase `walletPass` namespace.
263
+ // The widget itself detects the device and shows the correct Apple/Google
264
+ // badge, so no pass-type option is passed through here.
265
+ module="walletPass"
266
+ title="Add to Wallet"
267
+ // One-tap: opening this sheet is already an "Add to Wallet" intent, so a
268
+ // single active pass auto-issues + hands off to the OS without a 2nd tap.
269
+ widgetOptions={{ autoAdd }}
270
+ onSuccess={onSuccess}
271
+ onError={onError}
272
+ onClose={onClose}
273
+ />
274
+ );
275
+ }