@outerjoyn/react-native 1.4.2 → 1.6.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
@@ -75,13 +75,49 @@ function HomeScreen() {
75
75
  function CheckoutScreen() {
76
76
  const { openPay } = useOuterJoyn();
77
77
  return (
78
- <Button title="Pay with Points" onPress={() => openPay({ orderTotalCents: 4999 })} />
78
+ <Button
79
+ title="Pay with Points"
80
+ onPress={() =>
81
+ openPay({
82
+ orderTotalCents: 4999,
83
+ // Send the breakdown you have. The server derives the redeemable
84
+ // basis from it and fails closed (422) without it on most
85
+ // storefronts. Omit a field you don't have — `absent` is NOT `0`.
86
+ merchandiseSubtotalCents: 4200,
87
+ taxCents: 399,
88
+ shippingCents: 400,
89
+ })
90
+ }
91
+ />
79
92
  );
80
93
  }
81
94
  ```
82
95
 
83
96
  **~20 lines of code.** Theme, field visibility, and availability come from platform config automatically.
84
97
 
98
+ ### Order breakdown (important)
99
+
100
+ `orderTotalCents` alone is only enough when the storefront is in `tender` mode with
101
+ both "include tax" and "include shipping" on. Every other configuration derives the
102
+ **redeemable basis** from the breakdown and rejects the reserve without it:
103
+
104
+ | Storefront mode | Redeemable basis | Required fields |
105
+ |---|---|---|
106
+ | `coupon` | uncapped | — |
107
+ | `discount` | merchandise subtotal | `merchandiseSubtotalCents` |
108
+ | `tender`, tax off / ship off | merchandise subtotal | `merchandiseSubtotalCents` |
109
+ | `tender`, tax on | merchandise + tax | `merchandiseSubtotalCents`, `taxCents` |
110
+ | `tender`, ship on | merchandise + shipping | `merchandiseSubtotalCents`, `shippingCents` |
111
+ | `tender`, tax on + ship on | full order total | — |
112
+
113
+ A missing required field returns 422 `merchandise_subtotal_required`,
114
+ `tax_amount_required`, or `shipping_amount_required`.
115
+
116
+ **Do not substitute `0` for a value you don't have.** The gateway distinguishes
117
+ absent from zero: `0` asserts a genuinely zero subtotal and caps redemption at
118
+ nothing, while an omitted field produces a clear 422 instead of a silent
119
+ zero-point checkout.
120
+
85
121
  ## Components
86
122
 
87
123
  ### Provider + Hook
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@outerjoyn/react-native",
3
- "version": "1.4.2",
3
+ "version": "1.6.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",
@@ -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 => ({
@@ -608,7 +608,14 @@ export function OuterJoynProvider({
608
608
  );
609
609
 
610
610
  const openPay = useCallback(
611
- (opts: { orderTotalCents: number; merchantOrderId?: string }) => {
611
+ (opts: {
612
+ orderTotalCents: number;
613
+ merchantOrderId?: string;
614
+ currencyCode?: string;
615
+ merchandiseSubtotalCents?: number;
616
+ taxCents?: number;
617
+ shippingCents?: number;
618
+ }) => {
612
619
  analyticsRef.current?.trackOpen('pay');
613
620
  openSheet('pay', opts);
614
621
  },
@@ -683,7 +690,7 @@ export function OuterJoynProvider({
683
690
  isReturningUser,
684
691
  linkedPrograms,
685
692
  portablePrograms,
686
- consumerIdentityId,
693
+ consumerRef,
687
694
  totalAvailablePoints,
688
695
  totalAvailableValue,
689
696
  loading,
@@ -718,7 +725,7 @@ export function OuterJoynProvider({
718
725
  isReturningUser,
719
726
  linkedPrograms,
720
727
  portablePrograms,
721
- consumerIdentityId,
728
+ consumerRef,
722
729
  totalAvailablePoints,
723
730
  totalAvailableValue,
724
731
  loading,
@@ -759,6 +766,9 @@ export function OuterJoynProvider({
759
766
  theme={resolvedTheme}
760
767
  orderTotal={sheetProps.orderTotalCents}
761
768
  currencyCode={sheetProps.currencyCode}
769
+ merchandiseSubtotalCents={sheetProps.merchandiseSubtotalCents}
770
+ taxCents={sheetProps.taxCents}
771
+ shippingCents={sheetProps.shippingCents}
762
772
  onSuccess={handleSheetSuccess}
763
773
  onError={handleSheetError}
764
774
  onClose={closeSheet}
@@ -9,6 +9,25 @@ import {
9
9
  Linking,
10
10
  } from 'react-native';
11
11
  import { WebView } from 'react-native-webview';
12
+
13
+ /**
14
+ * `react-native-webview` declares its component as
15
+ * `class WebView<P = undefined> extends Component<WebViewProps & P>`. Left at
16
+ * that default, React's JSX prop resolution reduces the element's accepted
17
+ * props to `never`, so EVERY prop we pass reports "Type X is not assignable to
18
+ * type 'never'" — errors that point at this file but originate in that
19
+ * declaration. It also cascades: `onShouldStartLoadWithRequest`'s parameter
20
+ * loses its contextual type and trips `noImplicitAny`.
21
+ *
22
+ * Supplying the type argument explicitly (`{}` — we add no extra props) is
23
+ * enough to keep the intersection well-formed. This is a type-level fix only:
24
+ * `WebViewTyped` IS `WebView` at runtime.
25
+ *
26
+ * Because `prepublishOnly` runs `typecheck`, the `never` cascade blocked every
27
+ * publish of this package — see `src/react-native-codegen-types.d.ts` for the
28
+ * other half of that story.
29
+ */
30
+ const WebViewTyped = WebView<{}>;
12
31
  import type { WebViewMessage, SDKError } from './types';
13
32
  import { generateWidgetHTML } from './html';
14
33
 
@@ -66,7 +85,7 @@ export function OuterJoynSheet({
66
85
  title,
67
86
  heightRatio = 0.85,
68
87
  }: SheetProps) {
69
- const webViewRef = useRef<WebView>(null);
88
+ const webViewRef = useRef<WebView<{}>>(null);
70
89
  const [loading, setLoading] = useState(true);
71
90
 
72
91
  const html = generateWidgetHTML(
@@ -135,7 +154,7 @@ export function OuterJoynSheet({
135
154
  <ActivityIndicator size="large" color="#6366f1" />
136
155
  </View>
137
156
  )}
138
- <WebView
157
+ <WebViewTyped
139
158
  ref={webViewRef}
140
159
  source={{ html }}
141
160
  style={styles.webView}
@@ -0,0 +1,119 @@
1
+ /**
2
+ * CONTRACT — the pay order breakdown survives the whole RN → hosted-widget chain.
3
+ *
4
+ * WHY THIS FILE EXISTS
5
+ *
6
+ * The breakdown crosses FOUR hand-maintained mirrors before it reaches the
7
+ * gateway, and every one of them is a place a field can be silently dropped:
8
+ *
9
+ * openPay(opts) core/types.ts (mirror 1)
10
+ * → openSheet('pay', opts) → sheetProps
11
+ * → <PaySheet {...} /> OuterJoynProvider (mirror 2)
12
+ * → PaySheetProps types.ts (mirror 3)
13
+ * → widgetOptions widgets.tsx (mirror 4)
14
+ * → hosted oj.pay.open() → frame INIT → checkout POST
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
19
+ * field does not fail loudly — it produces a 422 at reserve time, or worse, a
20
+ * silently capped redemption. Types alone never caught it because each mirror
21
+ * is independently well-formed.
22
+ *
23
+ * WHAT THIS PINS
24
+ *
25
+ * A compile error here means a breakdown field exists on one side of a mirror
26
+ * and not the other. The package's `typecheck` script runs `tsc --noEmit` over
27
+ * `src`, and `prepublishOnly` runs `typecheck` — so this also blocks a publish
28
+ * that would ship a broken chain. It is types-only: no runtime, no test runner,
29
+ * nothing exported from the package index.
30
+ *
31
+ * WHAT THIS CANNOT PIN
32
+ *
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.
38
+ *
39
+ * `absent` IS NOT `0`
40
+ *
41
+ * The gateway guards on `== null` (Go `*int` + `omitempty`), so a `0` asserts a
42
+ * genuinely zero subtotal and caps redemption at nothing, while an omitted
43
+ * field fails closed with a diagnosable 422. Every field below is therefore
44
+ * OPTIONAL on purpose — do not "fix" a mirror by defaulting one to 0.
45
+ */
46
+ import type { OuterJoynContextValue } from '../core/types';
47
+ import type { PaySheetProps } from '../types';
48
+
49
+ /** Compile error unless T and U have exactly the same keys. */
50
+ type SameKeys<T, U> = [keyof T] extends [keyof U]
51
+ ? [keyof U] extends [keyof T]
52
+ ? true
53
+ : { missing_from_first: Exclude<keyof U, keyof T> }
54
+ : { missing_from_second: Exclude<keyof T, keyof U> };
55
+
56
+ /** The breakdown fields, as the gateway's redeemable-basis ladder reads them. */
57
+ type BreakdownKeys = 'merchandiseSubtotalCents' | 'taxCents' | 'shippingCents';
58
+
59
+ type OpenPayOptions = Parameters<OuterJoynContextValue['openPay']>[0];
60
+
61
+ // --- Mirror 1: openPay's options carry the breakdown ------------------------
62
+ type OpenPayBreakdown = Pick<OpenPayOptions, BreakdownKeys & keyof OpenPayOptions>;
63
+ const _openPayCarriesBreakdown: SameKeys<
64
+ OpenPayBreakdown,
65
+ Record<BreakdownKeys, unknown>
66
+ > = true;
67
+
68
+ // --- Mirror 3: PaySheetProps carry the breakdown ----------------------------
69
+ type PaySheetBreakdown = Pick<PaySheetProps, BreakdownKeys & keyof PaySheetProps>;
70
+ const _paySheetCarriesBreakdown: SameKeys<
71
+ PaySheetBreakdown,
72
+ Record<BreakdownKeys, unknown>
73
+ > = true;
74
+
75
+ // --- Mirrors 1 ⇄ 3 agree, so the provider can pass them straight through ----
76
+ const _mirrorsAgree: SameKeys<OpenPayBreakdown, PaySheetBreakdown> = true;
77
+
78
+ // --- Every field is optional: `absent` must remain expressible --------------
79
+ // `{}` must satisfy the breakdown slice. If a field were made required, or
80
+ // defaulted to 0 to "simplify", this line stops compiling.
81
+ const _absenceIsExpressible: OpenPayBreakdown = {};
82
+ const _absenceIsExpressibleOnSheet: PaySheetBreakdown = {};
83
+
84
+ // --- Fields are numeric minor units, not strings or bigints -----------------
85
+ const _minorUnits: OpenPayBreakdown = {
86
+ merchandiseSubtotalCents: 4200,
87
+ taxCents: 399,
88
+ shippingCents: 400,
89
+ };
90
+
91
+ // --- `currencyCode` rides the same mirrors ----------------------------------
92
+ // It travels the identical four-mirror path and has ALREADY been a dead path
93
+ // 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
95
+ // again does not 422 — the gateway defaults nothing, but the SDK sends 'USD',
96
+ // so a non-USD order silently records a same-currency session with NO FX
97
+ // conversion and values points at parity. That is a mispricing, not an error,
98
+ // which is exactly why it needs a compile-time pin rather than a test.
99
+ type CurrencyKey = 'currencyCode';
100
+ const _openPayCarriesCurrency: SameKeys<
101
+ Pick<OpenPayOptions, CurrencyKey & keyof OpenPayOptions>,
102
+ Record<CurrencyKey, unknown>
103
+ > = true;
104
+ const _paySheetCarriesCurrency: SameKeys<
105
+ Pick<PaySheetProps, CurrencyKey & keyof PaySheetProps>,
106
+ Record<CurrencyKey, unknown>
107
+ > = true;
108
+
109
+ // Reference the bindings so `noUnusedLocals` stays satisfiable if enabled.
110
+ export type __PayBreakdownContract = [
111
+ typeof _openPayCarriesBreakdown,
112
+ typeof _paySheetCarriesBreakdown,
113
+ typeof _mirrorsAgree,
114
+ typeof _absenceIsExpressible,
115
+ typeof _absenceIsExpressibleOnSheet,
116
+ typeof _minorUnits,
117
+ typeof _openPayCarriesCurrency,
118
+ typeof _paySheetCarriesCurrency,
119
+ ];
@@ -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,10 +91,21 @@ 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;
98
+ /**
99
+ * ISO 4217 currency of the order. Defaults to `'USD'`.
100
+ *
101
+ * This is NOT cosmetic: the server prices the order against it, converting
102
+ * from the issuer's valuation currency at the current FX rate. Sending `USD`
103
+ * for a non-USD order records a same-currency session with NO conversion, so
104
+ * points are valued at parity — a silent mispricing rather than an error.
105
+ *
106
+ * Pass the currency the order is actually denominated in.
107
+ */
108
+ currencyCode?: string;
97
109
  /** Called whenever the user adjusts sliders */
98
110
  onPointsChanged?: (payload: PointsChangedPayload) => void;
99
111
  /** Called when the user taps "Link another program". If provided, overrides the default sheet flow. */
@@ -107,6 +119,7 @@ export const CheckoutPointsApply = forwardRef<CheckoutPointsApplyHandle, Checkou
107
119
  merchandiseSubtotalCents,
108
120
  taxCents,
109
121
  shippingCents,
122
+ currencyCode = 'USD',
110
123
  onPointsChanged,
111
124
  onLinkAnother,
112
125
  style,
@@ -191,6 +204,14 @@ export const CheckoutPointsApply = forwardRef<CheckoutPointsApplyHandle, Checkou
191
204
  if (tx !== undefined) breakdown.taxCents = tx;
192
205
  if (sh !== undefined) breakdown.shippingCents = sh;
193
206
 
207
+ // The server requires a 3-letter ISO 4217 code and rejects anything else
208
+ // with a 400, so a caller passing '' or 'usd' must not break the reserve.
209
+ // Unlike the breakdown above, an omitted currency has a safe default —
210
+ // there is no "absent means fail closed" semantics here.
211
+ const orderCurrency = (typeof currencyCode === 'string' && currencyCode.trim().length === 3)
212
+ ? currencyCode.trim().toUpperCase()
213
+ : 'USD';
214
+
194
215
  // In demo mode or no apiClient, skip API calls
195
216
  if (demoMode || !apiClient) {
196
217
  setConfirmedPrograms((prev) => {
@@ -220,7 +241,7 @@ export const CheckoutPointsApply = forwardRef<CheckoutPointsApplyHandle, Checkou
220
241
  }>('/api/sdk/pay/checkout', {
221
242
  merchantOrderId: `checkout_${Date.now()}`,
222
243
  orderTotalCents: validOrderTotal,
223
- currencyCode: 'USD',
244
+ currencyCode: orderCurrency,
224
245
  ...breakdown,
225
246
  reservations: [{
226
247
  memberCurrencyId: prog.memberCurrencyId,
@@ -261,7 +282,7 @@ export const CheckoutPointsApply = forwardRef<CheckoutPointsApplyHandle, Checkou
261
282
  setApiLoading((prev) => ({ ...prev, [progId]: false }));
262
283
  }
263
284
  },
264
- [programs, sliderValues, demoMode, apiClient, orderTotalCents, merchandiseSubtotalCents, taxCents, shippingCents, buildPayload, onPointsChanged, redemptionTokens],
285
+ [programs, sliderValues, demoMode, apiClient, orderTotalCents, merchandiseSubtotalCents, taxCents, shippingCents, currencyCode, buildPayload, onPointsChanged, redemptionTokens],
265
286
  );
266
287
 
267
288
  const handleRemove = useCallback(
@@ -564,18 +585,22 @@ export const CheckoutPointsApply = forwardRef<CheckoutPointsApplyHandle, Checkou
564
585
  </View>
565
586
  )}
566
587
 
567
- {/* Link another program */}
568
- {(onLinkAnother || ctx.openConnect) && (
569
- <Pressable
570
- style={styles.linkMoreButton}
571
- onPress={() => (onLinkAnother ? onLinkAnother() : ctx.openConnect?.())}
572
- accessibilityRole="button"
573
- accessibilityLabel="Link another loyalty program"
574
- >
575
- <Text style={styles.linkMorePlus}>+</Text>
576
- <Text style={styles.linkMoreText}>Link another program</Text>
577
- </Pressable>
578
- )}
588
+ {/* Link another program.
589
+ Rendered unconditionally: `ctx.openConnect` is non-optional on
590
+ `OuterJoynContextValue` and `useOuterJoyn()` throws outside a
591
+ provider, so there is always a way to link. The former
592
+ `(onLinkAnother || ctx.openConnect) &&` guard could never be false —
593
+ `tsc` flagged it as TS2774 — and the `?.` below was dead for the same
594
+ reason. `onLinkAnother` still wins when a caller supplies it. */}
595
+ <Pressable
596
+ style={styles.linkMoreButton}
597
+ onPress={() => (onLinkAnother ? onLinkAnother() : ctx.openConnect())}
598
+ accessibilityRole="button"
599
+ accessibilityLabel="Link another loyalty program"
600
+ >
601
+ <Text style={styles.linkMorePlus}>+</Text>
602
+ <Text style={styles.linkMoreText}>Link another program</Text>
603
+ </Pressable>
579
604
 
580
605
  <View style={styles.poweredByRow}>
581
606
  <Text style={styles.poweredByText}>Powered by</Text>
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Portability consent hand-off (TK-527060, 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,90 @@
1
+ // packages/outerjoyn-react-native/src/core/tender.ts
2
+ // RN twin of src/sdk/core/payable.ts's planRedeemTender (TK-200068) — this
3
+ // package can't import from the app's src tree, so the ~30 lines are
4
+ // duplicated with the same contract. Keep the two in sync; the web copy's
5
+ // doc comment is the canonical rationale. A shared test in the main repo
6
+ // (src/sdk/core/__tests__/rnTenderParity.test.ts) asserts the twins agree.
7
+ //
8
+ // Contract: the Go redeem handler debits Member.points_balance for
9
+ // payment.method='points' and ONE MemberCurrency row (by currency id) for
10
+ // 'partner_currency'. Scalar covers → points (pre-existing behavior kept);
11
+ // else the largest single covering payable row pays as partner_currency;
12
+ // else null (can't afford — no tender exists). Snowflake ids stay STRINGS.
13
+
14
+ export interface TenderRowLike {
15
+ balance?: number | string | null;
16
+ currencyId?: number | string | null;
17
+ currency_id?: number | string | null;
18
+ /** USD-per-point rate from the session's accepted-currency resolution —
19
+ * used to pick the cheapest-for-the-member covering row. */
20
+ pointValueAmount?: number | string | null;
21
+ point_value_amount?: number | string | null;
22
+ }
23
+
24
+ export type RedeemTender =
25
+ | { method: 'points' }
26
+ | { method: 'partner_currency'; partnerCurrencyId: string };
27
+
28
+ export function planRedeemTender(
29
+ scalarPointsBalance: number | null | undefined,
30
+ payableRows: readonly TenderRowLike[] | null | undefined,
31
+ totalCost: number
32
+ ): RedeemTender | null {
33
+ if (!(totalCost > 0)) return { method: 'points' }; // nothing to charge
34
+ if ((Number(scalarPointsBalance) || 0) >= totalCost) {
35
+ return { method: 'points' };
36
+ }
37
+ let best: TenderRowLike | null = null;
38
+ let bestRate = Number.POSITIVE_INFINITY;
39
+ let bestBalance = -1;
40
+ for (const row of payableRows ?? []) {
41
+ const b = Number(row?.balance) || 0;
42
+ const id = row?.currencyId ?? row?.currency_id;
43
+ // Synthetic rows (demo personas, magic-test sessions) carry NEGATIVE
44
+ // currency ids (-1..-7 client and server side) that can never name a
45
+ // real MemberCurrency row — sending one is a guaranteed 400. Only a
46
+ // positive id can tender.
47
+ //
48
+ // Tested as a STRING, never Number()-coerced: currency ids are
49
+ // snowflakes and coercion truncates past 2^53 (the repo's
50
+ // check-snowflake-id-coercion guard rejects it, correctly — a
51
+ // "just for the sign" coercion is still the pattern that teaches the
52
+ // next reader it is fine here). `/^[1-9]\d*$/` accepts exactly the
53
+ // positive integers of any length and rejects '0', '-1', '', 'abc'
54
+ // and decimals.
55
+ if (b < totalCost || id == null || !/^[1-9]\d*$/.test(String(id).trim())) continue;
56
+ // Among covering rows, pick the one whose points cost the member the
57
+ // least real value: rates vary per currency (pointValueAmount, USD per
58
+ // point — a 3x spread exists in live data), and the item's cost is a
59
+ // fixed POINT count, so paying from the lowest-rate row minimizes the
60
+ // member's real spend. Rows without a known rate sort after rated ones;
61
+ // ties (and the all-unrated case) break to the largest balance.
62
+ const rawRate = Number(row?.pointValueAmount ?? row?.point_value_amount);
63
+ const rate = Number.isFinite(rawRate) && rawRate > 0 ? rawRate : Number.POSITIVE_INFINITY;
64
+ if (rate < bestRate || (rate === bestRate && b > bestBalance)) {
65
+ best = row;
66
+ bestRate = rate;
67
+ bestBalance = b;
68
+ }
69
+ }
70
+ if (best) {
71
+ return {
72
+ method: 'partner_currency',
73
+ partnerCurrencyId: String(best.currencyId ?? best.currency_id),
74
+ };
75
+ }
76
+ return null;
77
+ }
78
+
79
+ /** Max a SINGLE tender can put toward one item (scalar or biggest row). */
80
+ export function maxTenderableBalance(
81
+ scalarPointsBalance: number | null | undefined,
82
+ payableRows: readonly TenderRowLike[] | null | undefined
83
+ ): number {
84
+ let max = Number(scalarPointsBalance) || 0;
85
+ for (const row of payableRows ?? []) {
86
+ const b = Number(row?.balance) || 0;
87
+ if (b > max) max = b;
88
+ }
89
+ return max;
90
+ }
package/src/core/types.ts CHANGED
@@ -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;
@@ -190,7 +194,25 @@ export interface OuterJoynContextValue {
190
194
  openConnect: (opts?: { institutionId?: string }) => void;
191
195
  openExchange: (opts?: { sourceCurrencyId?: number | string }) => void;
192
196
  openRedeem: (opts?: { category?: string }) => void;
193
- openPay: (opts: { orderTotalCents: number; merchantOrderId?: string }) => void;
197
+ /**
198
+ * Open the pay-with-points sheet.
199
+ *
200
+ * The order breakdown is what the server derives the REDEEMABLE BASIS from.
201
+ * Without it the reserve fails closed on every storefront basis except tender
202
+ * with both redeem_include_tax and redeem_include_shipping on — 422
203
+ * `merchandise_subtotal_required` / `tax_amount_required` /
204
+ * `shipping_amount_required`. `absent` is NOT `0`: the gateway's guard is
205
+ * `== null`, so passing 0 asserts a zero subtotal and caps redemption at
206
+ * nothing. Omit what you don't have.
207
+ */
208
+ openPay: (opts: {
209
+ orderTotalCents: number;
210
+ merchantOrderId?: string;
211
+ currencyCode?: string;
212
+ merchandiseSubtotalCents?: number;
213
+ taxCents?: number;
214
+ shippingCents?: number;
215
+ }) => void;
194
216
  openAccount: () => void;
195
217
  closeSheet: () => void;
196
218
  unlinkProgram: (programId: string) => void;
@@ -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.4.2';
17
+ export const SDK_VERSION = '1.6.0';
package/src/index.ts CHANGED
@@ -15,9 +15,20 @@
15
15
  * // Show a banner on any screen
16
16
  * <LoyaltyBanner />
17
17
  *
18
- * // Pay with points at checkout
18
+ * // Pay with points at checkout. Send the order breakdown — the server derives
19
+ * // the redeemable basis from it and 422s without it on most storefronts.
19
20
  * const { openPay } = useOuterJoyn();
20
- * <Button onPress={() => openPay({ orderTotalCents: 4999 })} title="Pay with Points" />
21
+ * <Button
22
+ * onPress={() =>
23
+ * openPay({
24
+ * orderTotalCents: 4999,
25
+ * merchandiseSubtotalCents: 4200,
26
+ * taxCents: 399,
27
+ * shippingCents: 400,
28
+ * })
29
+ * }
30
+ * title="Pay with Points"
31
+ * />
21
32
  * ```
22
33
  */
23
34
 
@@ -74,6 +85,8 @@ export type {
74
85
 
75
86
  // Core
76
87
  export { APIClient, SDKError } from './core/api-client';
88
+ export { createPortabilityHandoff, getPortabilityHandoffStatus } from './core/portabilityHandoff';
89
+ export type { PortabilityHandoff, PortabilityOutcome } from './core/portabilityHandoff';
77
90
  export { OuterJoynErrorBoundary } from './core/ErrorBoundary';
78
91
  export { SDK_VERSION } from './core/version';
79
92
 
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Ambient shim for `react-native/Libraries/Types/CodegenTypes`.
3
+ *
4
+ * WHY THIS EXISTS — this is the reason `npm publish` was broken.
5
+ *
6
+ * `react-native-webview`'s own `lib/RNCWebViewNativeComponent.d.ts` imports
7
+ * `DirectEventHandler`, `Double`, `Int32` and `WithDefault` from
8
+ * `react-native/Libraries/Types/CodegenTypes`. React Native 0.73 ships that
9
+ * module as **`CodegenTypes.js` only — there is no `CodegenTypes.d.ts`**, so
10
+ * TypeScript cannot resolve the specifier.
11
+ *
12
+ * The failure is silent and non-local, which is what made it hard to place:
13
+ * the unresolved import degrades `WebViewNativeEvent` & co, which degrades
14
+ * `IOSWebViewProps & AndroidWebViewProps & WindowsWebViewProps`, so the
15
+ * exported `WebViewProps` intersection collapses to `never`. Every single prop
16
+ * we pass in `OuterJoynSheet.tsx` then reports "Type X is not assignable to
17
+ * type 'never'" — ten errors that look like OUR bug and are not. `tsc` reports
18
+ * them against our source, and `skipLibCheck` cannot help because the `never`
19
+ * leaks out of the declaration file into our code.
20
+ *
21
+ * Because `prepublishOnly` runs `typecheck`, this blocked EVERY publish of this
22
+ * package — which is why `@outerjoyn/react-native` 1.5.0 could not ship.
23
+ *
24
+ * Verified (2026-08-21): every published `react-native-webview` 13.x — from the
25
+ * declared floor 13.6.0 through 13.17.0 — imports these same types, so there is
26
+ * no version to pin to. It is fixed upstream by RN shipping the declarations.
27
+ * DELETE THIS FILE once `react-native/Libraries/Types/CodegenTypes.d.ts` exists
28
+ * in the installed RN version.
29
+ *
30
+ * The definitions mirror React Native's own codegen types.
31
+ */
32
+ declare module 'react-native/Libraries/Types/CodegenTypes' {
33
+ /** A double-precision number at the native bridge. */
34
+ export type Double = number;
35
+ /** A 32-bit integer at the native bridge. */
36
+ export type Int32 = number;
37
+ /** A float at the native bridge. */
38
+ export type Float = number;
39
+
40
+ /** A prop with a codegen-declared default value. */
41
+ export type WithDefault<Type, Value extends Type | string | undefined = undefined> =
42
+ Type | undefined;
43
+
44
+ /** Handler for an event emitted directly by the native component. */
45
+ export type DirectEventHandler<
46
+ Event,
47
+ Name extends string | undefined = string,
48
+ > = (event: { nativeEvent: Event }) => void;
49
+
50
+ /** Handler for an event that bubbles through the view hierarchy. */
51
+ export type BubblingEventHandler<
52
+ Event,
53
+ Name extends string | undefined = string,
54
+ > = (event: { nativeEvent: Event }) => void;
55
+
56
+ export type UnsafeObject = object;
57
+ export type UnsafeMixed = unknown;
58
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Ambient declaration for `react-native-sse`.
3
+ *
4
+ * This package is an OPTIONAL peer: `core/event-stream.ts` reaches it through a
5
+ * dynamic `import()` inside a try/catch and degrades to "real-time updates
6
+ * disabled" when it is absent. That runtime posture is deliberate — consumers
7
+ * who do not want SSE should not have to install it, so it is intentionally
8
+ * absent from `dependencies`, `peerDependencies` and `devDependencies`.
9
+ *
10
+ * TypeScript still has to resolve the module specifier at compile time, though,
11
+ * and without this shim `tsc --noEmit` fails with TS2307. Because
12
+ * `prepublishOnly` runs `typecheck`, that failure blocked EVERY publish of this
13
+ * package — the real reason 1.5.0 could not ship.
14
+ *
15
+ * Do not "fix" this by adding the package as a dependency: that would make an
16
+ * optional feature mandatory for every consumer. If the real types are ever
17
+ * wanted, add `react-native-sse` to devDependencies and delete this file — the
18
+ * shape below is intentionally minimal and covers only what event-stream.ts
19
+ * uses.
20
+ */
21
+ declare module 'react-native-sse' {
22
+ export interface EventSourceOptions {
23
+ headers?: Record<string, string>;
24
+ [key: string]: unknown;
25
+ }
26
+
27
+ export interface EventSourceEvent {
28
+ /** Raw SSE payload; event-stream.ts JSON.parses this. */
29
+ data?: string;
30
+ [key: string]: unknown;
31
+ }
32
+
33
+ export default class EventSource {
34
+ constructor(url: string, options?: EventSourceOptions);
35
+ addEventListener(type: string, listener: (event: EventSourceEvent) => void): void;
36
+ removeAllEventListeners?(): void;
37
+ close(): void;
38
+ }
39
+ }
@@ -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
 
@@ -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. TK-527060 (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
  )}
@@ -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 (TK-200068): 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 (TK-200068).
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 (TK-200068). 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
@@ -30,6 +30,21 @@ export interface PaySheetProps extends OuterJoynConfig {
30
30
  orderTotal?: number;
31
31
  /** ISO 4217 currency code (default: USD) */
32
32
  currencyCode?: string;
33
+ /**
34
+ * Order breakdown (minor units). The server derives the REDEEMABLE BASIS from
35
+ * these and fails closed without them: every storefront basis except tender
36
+ * with both redeem_include_tax and redeem_include_shipping on rejects the
37
+ * reserve with 422 `merchandise_subtotal_required` / `tax_amount_required` /
38
+ * `shipping_amount_required`.
39
+ *
40
+ * `absent` is NOT `0` — the gateway's guard is `== null`, so a 0 asserts a
41
+ * zero subtotal and caps redemption at nothing. Omit what you don't have.
42
+ */
43
+ merchandiseSubtotalCents?: number;
44
+ /** Tax in cents. Required when the storefront sets redeem_include_tax. */
45
+ taxCents?: number;
46
+ /** Shipping in cents. Required when the storefront sets redeem_include_shipping. */
47
+ shippingCents?: number;
33
48
  /** Called when payment completes successfully */
34
49
  onSuccess?: (result: PayResult) => void;
35
50
  /** Called when an error occurs */
@@ -14,7 +14,16 @@
14
14
  * return (
15
15
  * <Button
16
16
  * title={`Pay with ${totalAvailableValue}c in points`}
17
- * onPress={() => openPay({ orderTotalCents: 2499 })}
17
+ * onPress={() =>
18
+ * // The breakdown decides how much of the order points may cover.
19
+ * // Omit a field you don't have — `absent` is NOT `0`.
20
+ * openPay({
21
+ * orderTotalCents: 2499,
22
+ * merchandiseSubtotalCents: 2100,
23
+ * taxCents: 199,
24
+ * shippingCents: 200,
25
+ * })
26
+ * }
18
27
  * />
19
28
  * );
20
29
  * }
package/src/widgets.tsx CHANGED
@@ -47,6 +47,9 @@ export function PaySheet({
47
47
  theme,
48
48
  orderTotal,
49
49
  currencyCode,
50
+ merchandiseSubtotalCents,
51
+ taxCents,
52
+ shippingCents,
50
53
  onSuccess,
51
54
  onError,
52
55
  onClose,
@@ -74,6 +77,12 @@ export function PaySheet({
74
77
  widgetOptions={{
75
78
  ...(orderTotal !== undefined ? { orderTotal } : {}),
76
79
  ...(currencyCode !== undefined ? { currencyCode } : {}),
80
+ // Order breakdown — forwarded verbatim to the hosted widget's
81
+ // pay.open(). `absent` is NOT `0` (the gateway guards on `== null`),
82
+ // so an undefined field must stay off the wire entirely.
83
+ ...(merchandiseSubtotalCents !== undefined ? { merchandiseSubtotalCents } : {}),
84
+ ...(taxCents !== undefined ? { taxCents } : {}),
85
+ ...(shippingCents !== undefined ? { shippingCents } : {}),
77
86
  ...(onPointsChanged ? { onPointsChanged } : {}),
78
87
  }}
79
88
  />
@@ -197,6 +206,7 @@ export function AccountSheet({
197
206
  sessionToken,
198
207
  apiBaseUrl,
199
208
  theme,
209
+ onSuccess,
200
210
  onClose,
201
211
  onError,
202
212
  }: {
@@ -204,6 +214,12 @@ export function AccountSheet({
204
214
  sessionToken?: string;
205
215
  apiBaseUrl?: string;
206
216
  theme?: any;
217
+ // Declared AND forwarded below. Omitting it here made
218
+ // `OuterJoynSDK.present('account')` unresolvable: the imperative bridge
219
+ // passes `onSuccess` to settle its promise, the prop was silently dropped,
220
+ // and the only remaining settle path was `dismiss()` — which *rejects*.
221
+ // A completed account flow therefore threw "Dismissed by user".
222
+ onSuccess?: () => void;
207
223
  onClose?: () => void;
208
224
  onError?: (error: any) => void;
209
225
  }) {
@@ -220,6 +236,7 @@ export function AccountSheet({
220
236
  theme={resolvedTheme}
221
237
  module="account"
222
238
  title="My Account"
239
+ onSuccess={onSuccess}
223
240
  onClose={onClose}
224
241
  onError={onError}
225
242
  />