@outerjoyn/react-native 1.5.0 → 1.6.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@outerjoyn/react-native",
3
- "version": "1.5.0",
3
+ "version": "1.6.1",
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",
@@ -235,7 +235,7 @@ export function OuterJoynProvider({
235
235
 
236
236
  const [isReturningUser, setIsReturningUser] = useState(false);
237
237
  const [portablePrograms, setPortablePrograms] = useState<LinkedProgram[]>([]);
238
- const [consumerIdentityId, setConsumerIdentityId] = useState<string | null>(null);
238
+ const [consumerRef, setConsumerRef] = useState<string | null>(null);
239
239
 
240
240
  // Derived — include portable programs in linked count for checkout availability
241
241
  const allPrograms = useMemo(() => [...linkedPrograms, ...portablePrograms], [linkedPrograms, portablePrograms]);
@@ -455,7 +455,7 @@ export function OuterJoynProvider({
455
455
  // These are programs the consumer linked in Joyn Wallet or other
456
456
  // brand apps that this BU's partnerships accept.
457
457
  client.get<{
458
- consumer_identity_id: string | null;
458
+ consumer_ref: string | null;
459
459
  portable_programs: Array<{
460
460
  currency_id: string;
461
461
  currency_name: string;
@@ -472,8 +472,8 @@ export function OuterJoynProvider({
472
472
  consent_status: string;
473
473
  }>('/api/sdk/portable-programs').then((portableData) => {
474
474
  if (cancelled || !mountedRef.current) return;
475
- if (portableData.consumer_identity_id) {
476
- setConsumerIdentityId(portableData.consumer_identity_id);
475
+ if (portableData.consumer_ref) {
476
+ setConsumerRef(portableData.consumer_ref);
477
477
  }
478
478
  if (portableData.portable_programs?.length > 0) {
479
479
  const mapped = portableData.portable_programs.map((pp, i): LinkedProgram => ({
@@ -641,8 +641,8 @@ export function OuterJoynProvider({
641
641
  // the sheet. Awaiting is important: if the sheet closes before
642
642
  // the refresh lands, `CheckoutPointsApply` and other consumers
643
643
  // re-render with stale `linkedPrograms` and the user sees their
644
- // old balances for one frame. See HOSTED-OAUTH-PROVIDER-PLAN.md
645
- // ("race between handleSheetSuccess and refreshBalances").
644
+ // old balances for one frame (a race between handleSheetSuccess and
645
+ // refreshBalances).
646
646
  try {
647
647
  await refreshBalances();
648
648
  } catch (err) {
@@ -690,7 +690,7 @@ export function OuterJoynProvider({
690
690
  isReturningUser,
691
691
  linkedPrograms,
692
692
  portablePrograms,
693
- consumerIdentityId,
693
+ consumerRef,
694
694
  totalAvailablePoints,
695
695
  totalAvailableValue,
696
696
  loading,
@@ -725,7 +725,7 @@ export function OuterJoynProvider({
725
725
  isReturningUser,
726
726
  linkedPrograms,
727
727
  portablePrograms,
728
- consumerIdentityId,
728
+ consumerRef,
729
729
  totalAvailablePoints,
730
730
  totalAvailableValue,
731
731
  loading,
@@ -13,9 +13,9 @@
13
13
  * → widgetOptions widgets.tsx (mirror 4)
14
14
  * → hosted oj.pay.open() → frame INIT → checkout POST
15
15
  *
16
- * This exact mirror shape has drawn blood three times on the web SDK's
17
- * `PayOpenOptions`: #5126 dropped `merchandiseSubtotalCents` (discount-mode
18
- * checkouts could never reserve) and #5130 dropped `applicationMode`. A dropped
16
+ * This exact mirror shape has broken before on the web SDK's `PayOpenOptions`:
17
+ * one change dropped `merchandiseSubtotalCents` (discount-mode checkouts could
18
+ * never reserve) and another dropped `applicationMode`. A dropped
19
19
  * field does not fail loudly — it produces a 422 at reserve time, or worse, a
20
20
  * silently capped redemption. Types alone never caught it because each mirror
21
21
  * is independently well-formed.
@@ -31,10 +31,9 @@
31
31
  * WHAT THIS CANNOT PIN
32
32
  *
33
33
  * That `widgets.tsx` actually FORWARDS each field into `widgetOptions` — a
34
- * mirror can carry a key while the plumbing drops it (the #5126 shape). The
35
- * forwarding is guarded on the hosted side by
36
- * `src/sdk/__tests__/pay-open-options.contract.test.tsx`, whose runtime layer
37
- * asserts the values reach the iframe INIT payload.
34
+ * mirror can carry a key while the plumbing drops it. The forwarding is
35
+ * guarded on the hosted side by a contract test whose runtime layer asserts the
36
+ * values reach the iframe INIT payload.
38
37
  *
39
38
  * `absent` IS NOT `0`
40
39
  *
@@ -91,7 +90,7 @@ const _minorUnits: OpenPayBreakdown = {
91
90
  // --- `currencyCode` rides the same mirrors ----------------------------------
92
91
  // It travels the identical four-mirror path and has ALREADY been a dead path
93
92
  // once: the provider read `sheetProps.currencyCode` while `openPay`'s options
94
- // never declared it, so no caller could set it (fixed in #5613). Dropping it
93
+ // never declared it, so no caller could set it (since fixed). Dropping it
95
94
  // again does not 422 — the gateway defaults nothing, but the SDK sends 'USD',
96
95
  // so a non-USD order silently records a same-currency session with NO FX
97
96
  // conversion and values points at parity. That is a mispricing, not an error,
@@ -75,10 +75,11 @@ export interface CheckoutPointsApplyHandle {
75
75
  }
76
76
 
77
77
  export interface CheckoutPointsApplyProps {
78
- /** Order total in cents (required) */
78
+ /** Order total in integer MINOR UNITS of the order currency (required) —
79
+ * cents for USD ($50.00 = 5000), whole yen for JPY (¥1,850 = 1850). */
79
80
  orderTotalCents: number;
80
81
  /**
81
- * Merchandise subtotal in cents — the order total minus tax and shipping.
82
+ * Merchandise subtotal in minor units — the order total minus tax and shipping.
82
83
  *
83
84
  * REQUIRED for every storefront basis except `tender` with both
84
85
  * `redeem_include_tax` and `redeem_include_shipping` enabled (where the order
@@ -90,9 +91,9 @@ export interface CheckoutPointsApplyProps {
90
91
  * that ignores it.
91
92
  */
92
93
  merchandiseSubtotalCents?: number;
93
- /** Tax in cents. Required when the storefront's basis includes tax. */
94
+ /** Tax in minor units. Required when the storefront's basis includes tax. */
94
95
  taxCents?: number;
95
- /** Shipping in cents. Required when the storefront's basis includes shipping. */
96
+ /** Shipping in minor units. Required when the storefront's basis includes shipping. */
96
97
  shippingCents?: number;
97
98
  /**
98
99
  * ISO 4217 currency of the order. Defaults to `'USD'`.
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * API Client for React Native SDK
3
3
  *
4
- * Ported from src/sdk/core/api-client.ts with RN-specific adaptations:
4
+ * Ported from the web SDK's API client with RN-specific adaptations:
5
5
  * - Uses plain fetch() (available in Hermes)
6
6
  * - AbortController for timeouts (available in Hermes)
7
7
  * - No browser-specific APIs (credentials, mode, DOMException)
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Portability consent hand-off (the Plaid model).
3
+ *
4
+ * A brand app can NOT grant "carry my linked programs across brands" — the
5
+ * member grants it only on the OuterJoyn-hosted, OTP-verified consent page. The
6
+ * app asks for a hand-off with its session, opens the hosted URL in the system
7
+ * browser, and learns ONLY the outcome (granted / declined / expired) — never an
8
+ * identity id. The old POST /api/sdk/portable-programs/consent now returns 403
9
+ * hosted_consent_required.
10
+ */
11
+ import type { APIClient } from './api-client';
12
+
13
+ export type PortabilityOutcome = 'granted' | 'declined' | 'expired' | 'pending';
14
+
15
+ export interface PortabilityHandoff {
16
+ request_id: string;
17
+ hosted_url: string;
18
+ expires_at: string;
19
+ }
20
+
21
+ export function createPortabilityHandoff(client: APIClient): Promise<PortabilityHandoff> {
22
+ return client.post<PortabilityHandoff>('/api/connect/identity/portability/requests', {});
23
+ }
24
+
25
+ export async function getPortabilityHandoffStatus(client: APIClient, requestId: string): Promise<PortabilityOutcome> {
26
+ const r = await client.get<{ status?: string }>(
27
+ `/api/connect/identity/portability/requests/${encodeURIComponent(requestId)}`,
28
+ );
29
+ const s = r?.status;
30
+ return s === 'granted' || s === 'declined' || s === 'expired' ? s : 'pending';
31
+ }
@@ -0,0 +1,87 @@
1
+ // RN twin of the web SDK's planRedeemTender — the same ~30 lines with the same
2
+ // contract, kept in sync with the web copy (a parity test asserts the two
3
+ // agree).
4
+ //
5
+ // Contract: the Go redeem handler debits the member's main-currency
6
+ // MemberCurrency row for payment.method='points' and ONE MemberCurrency row (by currency id) for
7
+ // 'partner_currency'. Scalar covers → points (pre-existing behavior kept);
8
+ // else the largest single covering payable row pays as partner_currency;
9
+ // else null (can't afford — no tender exists). Snowflake ids stay STRINGS.
10
+
11
+ export interface TenderRowLike {
12
+ balance?: number | string | null;
13
+ currencyId?: number | string | null;
14
+ currency_id?: number | string | null;
15
+ /** USD-per-point rate from the session's accepted-currency resolution —
16
+ * used to pick the cheapest-for-the-member covering row. */
17
+ pointValueAmount?: number | string | null;
18
+ point_value_amount?: number | string | null;
19
+ }
20
+
21
+ export type RedeemTender =
22
+ | { method: 'points' }
23
+ | { method: 'partner_currency'; partnerCurrencyId: string };
24
+
25
+ export function planRedeemTender(
26
+ scalarPointsBalance: number | null | undefined,
27
+ payableRows: readonly TenderRowLike[] | null | undefined,
28
+ totalCost: number
29
+ ): RedeemTender | null {
30
+ if (!(totalCost > 0)) return { method: 'points' }; // nothing to charge
31
+ if ((Number(scalarPointsBalance) || 0) >= totalCost) {
32
+ return { method: 'points' };
33
+ }
34
+ let best: TenderRowLike | null = null;
35
+ let bestRate = Number.POSITIVE_INFINITY;
36
+ let bestBalance = -1;
37
+ for (const row of payableRows ?? []) {
38
+ const b = Number(row?.balance) || 0;
39
+ const id = row?.currencyId ?? row?.currency_id;
40
+ // Synthetic rows (demo personas, magic-test sessions) carry NEGATIVE
41
+ // currency ids (-1..-7 client and server side) that can never name a
42
+ // real MemberCurrency row — sending one is a guaranteed 400. Only a
43
+ // positive id can tender.
44
+ //
45
+ // Tested as a STRING, never Number()-coerced: currency ids are
46
+ // snowflakes and coercion truncates past 2^53 (the repo's
47
+ // check-snowflake-id-coercion guard rejects it, correctly — a
48
+ // "just for the sign" coercion is still the pattern that teaches the
49
+ // next reader it is fine here). `/^[1-9]\d*$/` accepts exactly the
50
+ // positive integers of any length and rejects '0', '-1', '', 'abc'
51
+ // and decimals.
52
+ if (b < totalCost || id == null || !/^[1-9]\d*$/.test(String(id).trim())) continue;
53
+ // Among covering rows, pick the one whose points cost the member the
54
+ // least real value: rates vary per currency (pointValueAmount, USD per
55
+ // point — a 3x spread exists in live data), and the item's cost is a
56
+ // fixed POINT count, so paying from the lowest-rate row minimizes the
57
+ // member's real spend. Rows without a known rate sort after rated ones;
58
+ // ties (and the all-unrated case) break to the largest balance.
59
+ const rawRate = Number(row?.pointValueAmount ?? row?.point_value_amount);
60
+ const rate = Number.isFinite(rawRate) && rawRate > 0 ? rawRate : Number.POSITIVE_INFINITY;
61
+ if (rate < bestRate || (rate === bestRate && b > bestBalance)) {
62
+ best = row;
63
+ bestRate = rate;
64
+ bestBalance = b;
65
+ }
66
+ }
67
+ if (best) {
68
+ return {
69
+ method: 'partner_currency',
70
+ partnerCurrencyId: String(best.currencyId ?? best.currency_id),
71
+ };
72
+ }
73
+ return null;
74
+ }
75
+
76
+ /** Max a SINGLE tender can put toward one item (scalar or biggest row). */
77
+ export function maxTenderableBalance(
78
+ scalarPointsBalance: number | null | undefined,
79
+ payableRows: readonly TenderRowLike[] | null | undefined
80
+ ): number {
81
+ let max = Number(scalarPointsBalance) || 0;
82
+ for (const row of payableRows ?? []) {
83
+ const b = Number(row?.balance) || 0;
84
+ if (b > max) max = b;
85
+ }
86
+ return max;
87
+ }
package/src/core/types.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Core types for @outerjoyn/react-native SDK
3
3
  *
4
- * Derived from API response schemas documented in RN-SDK-REFACTOR-PLAN.md.
4
+ * Derived from the API response schemas.
5
5
  * These are the source of truth for the RN SDK's state model.
6
6
  */
7
7
 
@@ -39,7 +39,7 @@ export interface PayableBalance {
39
39
  // Snowflake IDs (memberCurrencyId/currencyId/partnershipId) ride as JSON
40
40
  // strings on the wire post-audit-D2; kept `number | string` to also accept
41
41
  // the legacy numeric shape. Amounts/balances stay numeric.
42
- // Go gateway returns camelCase
42
+ // Some routes return camelCase
43
43
  memberCurrencyId?: number | string;
44
44
  currencyId?: number | string;
45
45
  currencyName?: string;
@@ -51,7 +51,7 @@ export interface PayableBalance {
51
51
  pointValueAmount?: number;
52
52
  valueAmount?: number;
53
53
  partnershipId?: number | string;
54
- // Express returns snake_case
54
+ // Others return snake_case
55
55
  member_currency_id?: number | string;
56
56
  currency_id?: number | string;
57
57
  currency_name?: string;
@@ -176,8 +176,12 @@ export interface OuterJoynContextValue {
176
176
  linkedPrograms: LinkedProgram[];
177
177
  /** Programs linked in Joyn Wallet or other apps, portable to this BU via ConsumerIdentity. */
178
178
  portablePrograms: LinkedProgram[];
179
- /** Cross-BU consumer identity ID, if resolved. */
180
- consumerIdentityId: string | null;
179
+ /**
180
+ * This brand's pseudonymous reference for the consumer (`ojc_...`), if
181
+ * resolved. Stable for your brand, different at every other brand — the
182
+ * global OuterJoyn identity id is never exposed.
183
+ */
184
+ consumerRef: string | null;
181
185
  totalAvailablePoints: number;
182
186
  totalAvailableValue: number;
183
187
  loading: boolean;
@@ -14,4 +14,4 @@
14
14
  * (It is not imported from package.json because that inlines the entire
15
15
  * manifest — repo URLs, scripts, devDependencies — into consumer bundles.)
16
16
  */
17
- export const SDK_VERSION = '1.5.0';
17
+ export const SDK_VERSION = '1.6.1';
package/src/html.ts CHANGED
@@ -62,6 +62,7 @@ export function generateWidgetHTML(
62
62
 
63
63
  mod.open(Object.assign({
64
64
  container: document.getElementById('widget-container'),
65
+ ${module === 'connect' ? "presentation: 'sheet'," : ''}
65
66
  onSuccess: function(result) { sendToNative({ type: 'sdk_success', result: result }); },
66
67
  onError: function(err) { sendToNative({ type: 'sdk_error', error: err }); },
67
68
  onClose: function() { sendToNative({ type: 'sdk_close' }); },
package/src/index.ts CHANGED
@@ -85,6 +85,8 @@ export type {
85
85
 
86
86
  // Core
87
87
  export { APIClient, SDKError } from './core/api-client';
88
+ export { createPortabilityHandoff, getPortabilityHandoffStatus } from './core/portabilityHandoff';
89
+ export type { PortabilityHandoff, PortabilityOutcome } from './core/portabilityHandoff';
88
90
  export { OuterJoynErrorBoundary } from './core/ErrorBoundary';
89
91
  export { SDK_VERSION } from './core/version';
90
92
 
@@ -44,6 +44,7 @@ import {
44
44
  import * as WebBrowser from 'expo-web-browser';
45
45
  import { OuterJoynContext } from '../OuterJoynProvider';
46
46
  import { APIClient } from '../core/api-client';
47
+ import { createPortabilityHandoff, getPortabilityHandoffStatus } from '../core/portabilityHandoff';
47
48
 
48
49
  const OJ_LOGO_URL = 'https://app.outerjoyn.com/outerjoyn-logo.png';
49
50
 
@@ -300,7 +301,7 @@ export const ConnectScreen: React.FC<ConnectScreenProps> = ({
300
301
  .catch((err: any) => ({ ok: false as const, err }));
301
302
  const [acctData, portableData, inst] = await Promise.all([
302
303
  client.get<{ connected_brands?: any[] }>('/api/sdk/account').catch(() => null),
303
- client.get<{ consent_status?: string; consumer_identity_id?: string }>('/api/sdk/portable-programs').catch(() => null),
304
+ client.get<{ consent_status?: string; consumer_ref?: string | null }>('/api/sdk/portable-programs').catch(() => null),
304
305
  instResult,
305
306
  ]);
306
307
 
@@ -381,7 +382,7 @@ export const ConnectScreen: React.FC<ConnectScreenProps> = ({
381
382
  }
382
383
 
383
384
  // For real (non-demo) mode, skip the SDK consent step —
384
- // the wallet-web consent page handles auth + consent in one flow.
385
+ // the hosted consent page handles auth + consent in one flow.
385
386
  if (!isDemoMode) {
386
387
  setStep('processing');
387
388
  initiateConnectForInstitution(institution);
@@ -686,34 +687,41 @@ export const ConnectScreen: React.FC<ConnectScreenProps> = ({
686
687
  />
687
688
  </View>
688
689
 
689
- {/* Consent banner — shown when consumer has a ConsumerIdentity but hasn't
690
- granted link_portability_consent. Granting enables cross-BU program sharing. */}
690
+ {/* Portability banner — shown when the consumer has an identity but no
691
+ portability grant covering this app. The Plaid model: the
692
+ app can NOT grant it; tapping opens the OuterJoyn-hosted, OTP-verified
693
+ consent page in the system browser and reads back only the outcome. */}
691
694
  {consentRequired && !consentGranting && (
692
695
  <View style={s.consentBanner}>
693
696
  <Text style={s.consentBannerText}>
694
- Share your linked programs across partner apps? Use your points without re-linking.
697
+ Use programs you linked at other brands here? Joyn will confirm it{'\u2019'}s you.
695
698
  </Text>
696
699
  <Pressable
697
700
  style={s.consentBannerBtn}
698
701
  onPress={async () => {
699
702
  setConsentGranting(true);
700
703
  try {
701
- if (apiClient.current) {
702
- // Route through Express (not direct CRUD) — SDK session tokens
703
- // can't authenticate against the Go CRUD API key middleware.
704
- await apiClient.current.post('/api/sdk/portable-programs/consent');
705
- setConsentRequired(false);
706
- // Refresh provider to pick up portable programs
707
- const refreshFn = (ctx as any)?.refreshBalances;
708
- if (typeof refreshFn === 'function') refreshFn().catch(() => {});
704
+ const client = apiClient.current;
705
+ if (client) {
706
+ const handoff = await createPortabilityHandoff(client);
707
+ await WebBrowser.openBrowserAsync(handoff.hosted_url);
708
+ // The browser has been dismissed; read the authoritative outcome.
709
+ const outcome = await getPortabilityHandoffStatus(client, handoff.request_id);
710
+ if (outcome === 'granted') {
711
+ setConsentRequired(false);
712
+ const refreshFn = (ctx as any)?.refreshBalances;
713
+ if (typeof refreshFn === 'function') refreshFn().catch(() => {});
714
+ } else if (outcome === 'declined') {
715
+ setConsentRequired(false);
716
+ }
709
717
  }
710
718
  } catch {
711
- // Non-fatal
719
+ // Non-fatal: nothing to share, or the hand-off could not open.
712
720
  }
713
721
  setConsentGranting(false);
714
722
  }}
715
723
  >
716
- <Text style={s.consentBannerBtnText}>Allow</Text>
724
+ <Text style={s.consentBannerBtnText}>Continue with Joyn</Text>
717
725
  </Pressable>
718
726
  </View>
719
727
  )}
@@ -1119,8 +1127,8 @@ const s = StyleSheet.create({
1119
1127
  paddingHorizontal: 14,
1120
1128
  height: 48,
1121
1129
  backgroundColor: '#F1F5F9',
1122
- // Pill search — Plaid-style picker (parity with the web SDK ConnectWidget
1123
- // + wallet-web ConnectModal, 2026-07-21).
1130
+ // Pill search — Plaid-style picker (parity with the web SDK's connect
1131
+ // picker).
1124
1132
  borderRadius: 999,
1125
1133
  borderWidth: 1,
1126
1134
  borderColor: C.border,
@@ -1144,8 +1152,8 @@ const s = StyleSheet.create({
1144
1152
  paddingBottom: 24,
1145
1153
  },
1146
1154
  // 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).
1155
+ // typing a query switches to the detailed rows. Parity with the web SDK's
1156
+ // connect picker.
1149
1157
  gridColumnWrapper: {
1150
1158
  gap: 10,
1151
1159
  },
@@ -25,6 +25,7 @@ import {
25
25
  Linking,
26
26
  } from 'react-native';
27
27
  import { useOuterJoyn } from '../useOuterJoyn';
28
+ import { planRedeemTender, maxTenderableBalance } from '../core/tender';
28
29
  import { APIClient } from '../core/api-client';
29
30
 
30
31
  // =============================================================================
@@ -87,22 +88,24 @@ type Step = 'catalog' | 'detail' | 'confirm' | 'processing' | 'success' | 'error
87
88
  // =============================================================================
88
89
 
89
90
  /**
90
- * Category visuals for image-less rewards (2026-07-21 Plaid-grade redesign,
91
- * built against the approved HTML rendering): a soft pastel tile background
92
- * plus an emoji monogram in a floating white square — replaces the old flat
93
- * saturated color block with the category name shouting in white caps.
91
+ * Category visuals for image-less rewards (2026-07-21 Plaid-grade redesign):
92
+ * a soft pastel tile background plus a letter monogram in a floating white
93
+ * square. A letter, not an emoji: emoji render differently on every OS and
94
+ * ignore the brand's colours (no-emoji rule, 2026-10-12).
94
95
  */
95
- const CATEGORY_VISUALS: Record<string, { bg: string; emoji: string }> = {
96
- 'Gift Cards': { bg: '#EEF4FF', emoji: '🎁' },
97
- 'Electronics': { bg: '#EDF7FE', emoji: '🎧' },
98
- 'Experiences': { bg: '#EEF4FF', emoji: '🌴' },
99
- 'Merchandise': { bg: '#F5F0FE', emoji: '👕' },
100
- 'Wellness': { bg: '#EFFDF4', emoji: '🧘' },
101
- 'Skincare': { bg: '#FDF2F8', emoji: '✨' },
102
- 'Rewards': { bg: '#F6F9FC', emoji: '⭐' },
96
+ const CATEGORY_BG: Record<string, string> = {
97
+ 'Gift Cards': '#EEF4FF',
98
+ 'Electronics': '#EDF7FE',
99
+ 'Experiences': '#EEF4FF',
100
+ 'Merchandise': '#F5F0FE',
101
+ 'Wellness': '#EFFDF4',
102
+ 'Skincare': '#FDF2F8',
103
+ 'Rewards': '#F6F9FC',
103
104
  };
104
- const categoryVisual = (category: string) =>
105
- CATEGORY_VISUALS[category] ?? { bg: '#F6F9FC', emoji: '⭐' };
105
+ const categoryVisual = (category: string) => ({
106
+ bg: CATEGORY_BG[category] ?? '#F6F9FC',
107
+ monogram: (category.trim()[0] ?? 'R').toUpperCase(),
108
+ });
106
109
 
107
110
  const DEMO_CATALOG: CatalogItem[] = [
108
111
  { product_id: 1, name: '$10 Coffee Gift Card', description: 'Redeemable at any Urban Coffee Co location.', category: 'Gift Cards', points_cost: 2000, cash_price: 1000, image_url: 'https://images.unsplash.com/photo-1509042239860-f550ce710b93?w=400&h=400&fit=crop' },
@@ -270,14 +273,35 @@ export function RedeemScreen({
270
273
  setStep('detail');
271
274
  }, []);
272
275
 
276
+ // Tender planning: the server debits Member.points_balance
277
+ // for points tender and ONE MemberCurrency row for partner_currency. The
278
+ // old gate compared cost against effectiveBalance = max(scalar,
279
+ // cross-program TOTAL) — a sum no single tender can spend, so it enabled
280
+ // confirms the server would reject. Plan against the scalar + per-row
281
+ // balances instead; effectiveBalance stays display-only.
282
+ const tenderRows = useMemo(
283
+ () =>
284
+ (ctx.linkedPrograms ?? []).map((p) => ({
285
+ balance: p.pointsBalance,
286
+ currencyId: p.currencyId,
287
+ pointValueAmount: p.pointValueAmount,
288
+ })),
289
+ [ctx.linkedPrograms]
290
+ );
291
+
273
292
  const handleRedeem = useCallback(() => {
274
293
  if (!selectedItem) return;
275
- if (selectedItem.points_cost > effectiveBalance) {
276
- Alert.alert(t('redeem.insufficient'), t('redeem.points', { cost: String(selectedItem.points_cost) }));
294
+ if (planRedeemTender(balance, tenderRows, selectedItem.points_cost) === null) {
295
+ const best = maxTenderableBalance(balance, tenderRows);
296
+ Alert.alert(
297
+ t('redeem.insufficient'),
298
+ t('redeem.points', { cost: String(selectedItem.points_cost) }) +
299
+ (best > 0 ? ` (${String(best)})` : '')
300
+ );
277
301
  return;
278
302
  }
279
303
  setStep('confirm');
280
- }, [selectedItem, effectiveBalance]);
304
+ }, [selectedItem, balance, tenderRows]);
281
305
 
282
306
  const handleConfirmRedeem = useCallback(async () => {
283
307
  if (!selectedItem) return;
@@ -302,8 +326,26 @@ export function RedeemScreen({
302
326
  if (!clientRef.current) {
303
327
  throw new Error('API client not available');
304
328
  }
329
+ // payment is REQUIRED by the Go handler (a body without it 400s
330
+ // MISSING_PAYMENT_METHOD — this POST shipped without one). Pay from
331
+ // the store that can cover it: scalar via points, else the covering
332
+ // MemberCurrency row via partner_currency.
333
+ //
334
+ // NO `?? {method:'points'}` FALLBACK. A null plan means no single
335
+ // tender covers this item, and defaulting to points there submits the
336
+ // one tender we KNOW is short — turning a loud local failure into a
337
+ // confusing server 400. handleRedeem already proved a plan exists
338
+ // before advancing to this screen, so null here means the balances
339
+ // moved underneath us; say so and stop.
340
+ const payment = planRedeemTender(balance, tenderRows, selectedItem.points_cost);
341
+ if (!payment) {
342
+ setError(t('redeem.insufficient'));
343
+ setStep('error');
344
+ return;
345
+ }
305
346
  const data = await clientRef.current.post<any>('/api/sdk/redeem', {
306
347
  product_id: selectedItem.product_id,
348
+ payment,
307
349
  idempotency_key: Date.now() + '_' + Math.random().toString(36).slice(2),
308
350
  });
309
351
  const res: RedemptionResult = {
@@ -326,7 +368,17 @@ export function RedeemScreen({
326
368
  setStep('error');
327
369
  onError?.(e);
328
370
  }
329
- }, [selectedItem, isDemo, onSuccess, onError]);
371
+ // DEPS: balance, tenderRows and ctx are READ in this callback and MUST be
372
+ // listed. They were omitted once, which froze the callback at its
373
+ // mount-time values (balance 0, tenderRows []) — both are populated
374
+ // asynchronously (/api/sdk/balance and /sessions/context). planRedeemTender
375
+ // then returned null on every real redemption, and the old
376
+ // `?? {method:'points'}` fallback submitted a points tender against a
377
+ // scalar of 0: a guaranteed 400 insufficient_balance for exactly the
378
+ // cross-program member this work exists to serve — while renderConfirm,
379
+ // which recomputes the plan fresh, displayed the CORRECT partner_currency
380
+ // preview. Gate and submit must read the same values.
381
+ }, [selectedItem, isDemo, onSuccess, onError, balance, tenderRows, ctx, t]);
330
382
 
331
383
  const handleCopyCode = useCallback(() => {
332
384
  if (!result?.code) return;
@@ -391,7 +443,7 @@ export function RedeemScreen({
391
443
  <Image source={{ uri: item.image_url }} style={styles.catalogImage} resizeMode="cover" />
392
444
  ) : (
393
445
  <View style={styles.monogram}>
394
- <Text style={styles.monogramEmoji}>{visual.emoji}</Text>
446
+ <Text style={styles.monogramLetter}>{visual.monogram}</Text>
395
447
  </View>
396
448
  )}
397
449
  <View style={styles.pointsPill}>
@@ -495,10 +547,17 @@ export function RedeemScreen({
495
547
 
496
548
  const renderDetail = () => {
497
549
  if (!selectedItem) return null;
498
- const affordable = selectedItem.points_cost <= effectiveBalance;
499
- const shortfall = Math.max(0, selectedItem.points_cost - effectiveBalance);
550
+ // Gate on the tender PLAN, not the cross-program sum: effectiveBalance
551
+ // is max(scalar, TOTAL across programs) — a number no single tender can
552
+ // spend, so the old check enabled a button whose press could only
553
+ // produce an "insufficient" alert. The meter/shortfall use
554
+ // the best SINGLE tender for the same reason.
555
+ const detailPlan = planRedeemTender(balance, tenderRows, selectedItem.points_cost);
556
+ const bestTender = maxTenderableBalance(balance, tenderRows);
557
+ const affordable = detailPlan !== null;
558
+ const shortfall = Math.max(0, selectedItem.points_cost - bestTender);
500
559
  const progress = selectedItem.points_cost > 0
501
- ? Math.max(0.03, Math.min(1, effectiveBalance / selectedItem.points_cost))
560
+ ? Math.max(0.03, Math.min(1, bestTender / selectedItem.points_cost))
502
561
  : 1;
503
562
  const visual = categoryVisual(selectedItem.category);
504
563
  return (
@@ -512,7 +571,7 @@ export function RedeemScreen({
512
571
  <Image source={{ uri: selectedItem.image_url }} style={styles.detailImage} resizeMode="cover" />
513
572
  ) : (
514
573
  <View style={[styles.monogram, styles.detailMonogram]}>
515
- <Text style={styles.detailMonogramEmoji}>{visual.emoji}</Text>
574
+ <Text style={styles.detailMonogramLetter}>{visual.monogram}</Text>
516
575
  </View>
517
576
  )}
518
577
  <View style={[styles.pointsPill, styles.detailPointsPill]}>
@@ -538,7 +597,9 @@ export function RedeemScreen({
538
597
  <View style={[styles.meterFill, { width: `${Math.round(progress * 100)}%` }]} />
539
598
  </View>
540
599
  <Text style={styles.meterHint}>
541
- You have <Text style={styles.meterHintStrong}>{fmt(effectiveBalance)} pts</Text>
600
+ {/* bestTender, not the cross-program sum: this sentence carries
601
+ the affordable/shortfall verdict, which is single-tender. */}
602
+ You have <Text style={styles.meterHintStrong}>{fmt(bestTender)} pts</Text>
542
603
  {affordable
543
604
  ? ' \u2014 plenty to redeem this'
544
605
  : <Text> \u2014 <Text style={styles.meterHintAccent}>{fmt(shortfall)} more</Text> to unlock this</Text>}
@@ -573,7 +634,17 @@ export function RedeemScreen({
573
634
  <Text style={styles.confirmLabel}>{fmt(selectedItem?.points_cost ?? 0)} points</Text>
574
635
  </View>
575
636
  <Text style={styles.confirmBalance}>
576
- Remaining balance: {fmt(effectiveBalance - (selectedItem?.points_cost ?? 0))} pts
637
+ {/* Remaining = the PAYING store's balance − cost (points → scalar;
638
+ partner_currency → the chosen row) — the cross-program sum would
639
+ preview a store that isn't being charged. */}
640
+ Remaining balance: {fmt((() => {
641
+ const cost = selectedItem?.points_cost ?? 0;
642
+ const plan = selectedItem ? planRedeemTender(balance, tenderRows, cost) : null;
643
+ if (!plan) return 0;
644
+ if (plan.method === 'points') return balance - cost;
645
+ const row = tenderRows.find((r) => String(r.currencyId ?? '') === plan.partnerCurrencyId);
646
+ return (Number(row?.balance) || 0) - cost;
647
+ })())} pts
577
648
  </Text>
578
649
  <Pressable style={styles.primaryButton} onPress={handleConfirmRedeem}>
579
650
  <Text style={styles.primaryButtonText}>{t('exchange.confirm')}</Text>
@@ -824,7 +895,7 @@ const styles = StyleSheet.create({
824
895
  shadowColor: COLORS.navy, shadowOpacity: 0.1, shadowRadius: 8,
825
896
  shadowOffset: { width: 0, height: 2 }, elevation: 2,
826
897
  },
827
- monogramEmoji: { fontSize: 20 },
898
+ monogramLetter: { fontSize: 18, fontWeight: '700', color: '#475569' },
828
899
  pointsPill: {
829
900
  position: 'absolute', bottom: 8, left: 8,
830
901
  backgroundColor: 'rgba(16,24,74,0.82)',
@@ -854,7 +925,7 @@ const styles = StyleSheet.create({
854
925
  },
855
926
  detailImage: { width: '100%', height: '100%' },
856
927
  detailMonogram: { width: 64, height: 64, borderRadius: 20 },
857
- detailMonogramEmoji: { fontSize: 30 },
928
+ detailMonogramLetter: { fontSize: 28, fontWeight: '700', color: '#475569' },
858
929
  detailPointsPill: { bottom: 12, left: 12, paddingVertical: 6, paddingHorizontal: 12 },
859
930
  detailEyebrow: { fontSize: 11, fontWeight: '700', letterSpacing: 0.8, textTransform: 'uppercase', color: COLORS.accent, marginBottom: 6 },
860
931
  detailName: { fontSize: 23, fontWeight: '800', color: COLORS.text, letterSpacing: -0.4, marginBottom: 8 },
package/src/types.ts CHANGED
@@ -122,8 +122,8 @@ export interface PayResult {
122
122
  }
123
123
 
124
124
  export interface ConnectResult {
125
- // Snowflake ID: emitted as a JSON string on the wire (see audit D2). Widened
126
- // to accept the legacy numeric shape too for pre-D2 servers.
125
+ // Snowflake ID: emitted as a JSON string on the wire. Widened to accept the
126
+ // legacy numeric shape too, from older servers.
127
127
  linkedProgramId: number | string;
128
128
  programName: string;
129
129
  }