@outerjoyn/react-native 1.7.0 → 1.7.2

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.7.0",
3
+ "version": "1.7.2",
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",
@@ -47,6 +47,7 @@ import {
47
47
  amountError,
48
48
  blockedReason,
49
49
  ceilingCents,
50
+ fewestPointsForValue,
50
51
  floorToIncrement,
51
52
  rulesSummary,
52
53
  uncappedCeilingCents,
@@ -193,9 +194,14 @@ export const CheckoutPointsApply = forwardRef<CheckoutPointsApplyHandle, Checkou
193
194
 
194
195
  const selectedPoints = sliderValues[progId] ?? 0;
195
196
  if (selectedPoints <= 0) return;
196
- // The store's minimum and step, checked here so the shopper gets the
197
- // refusal (with a figure that works) before the server's.
198
- const ruleError = amountError(selectedPoints, redemptionRules);
197
+ // The store's minimum and step, and points that would buy nothing,
198
+ // checked here so the shopper gets the refusal (with a figure that
199
+ // works) before the server's.
200
+ const fewest = fewestPointsForValue(selectedPoints, prog.pointValueAmount, redemptionRules);
201
+ const ruleError = amountError(selectedPoints, redemptionRules)
202
+ ?? (fewest < selectedPoints
203
+ ? `${selectedPoints.toLocaleString()} points pay the same as ${fewest.toLocaleString()} here. Use ${fewest.toLocaleString()}.`
204
+ : null);
199
205
  if (ruleError) {
200
206
  setApiError((prev) => ({ ...prev, [progId]: ruleError }));
201
207
  return;
@@ -409,7 +415,7 @@ export const CheckoutPointsApply = forwardRef<CheckoutPointsApplyHandle, Checkou
409
415
  };
410
416
  // The most points value this order can take: before and after the store's percent cap.
411
417
  const orderCeilingCents = ceilingCents(order, redemptionRules);
412
- const orderUncappedCents = uncappedCeilingCents(order);
418
+ const orderUncappedCents = uncappedCeilingCents(order, redemptionRules);
413
419
  const rulesLine = rulesSummary(redemptionRules);
414
420
 
415
421
  // Calculate already-confirmed total to cap remaining programs
@@ -436,7 +442,7 @@ export const CheckoutPointsApply = forwardRef<CheckoutPointsApplyHandle, Checkou
436
442
  const maxPointsFor = (ceiling: number) => {
437
443
  const remaining = Math.max(0, ceiling - otherConfirmedCents);
438
444
  const pts = prog.pointValueAmount > 0 ? Math.floor(remaining / prog.pointValueAmount) : prog.pointsBalance;
439
- return floorToIncrement(Math.min(prog.pointsBalance, pts), redemptionRules);
445
+ return fewestPointsForValue(floorToIncrement(Math.min(prog.pointsBalance, pts), redemptionRules), prog.pointValueAmount, redemptionRules);
440
446
  };
441
447
  const maxSlider = maxPointsFor(orderCeilingCents);
442
448
  const blocked = blockedReason(prog.pointsBalance, maxSlider, maxPointsFor(orderUncappedCents), redemptionRules);
@@ -18,6 +18,12 @@ export interface PortabilityHandoff {
18
18
  expires_at: string;
19
19
  }
20
20
 
21
+ /** True only when the server says the hosted page could finish (programs to share, a verified email or phone). */
22
+ export async function getPortabilityHandoffAvailable(client: APIClient): Promise<boolean> {
23
+ const r = await client.get<{ available?: unknown }>('/api/connect/identity/portability/availability');
24
+ return r?.available === true;
25
+ }
26
+
21
27
  export function createPortabilityHandoff(client: APIClient): Promise<PortabilityHandoff> {
22
28
  return client.post<PortabilityHandoff>('/api/connect/identity/portability/requests', {});
23
29
  }
@@ -45,6 +45,22 @@ export function floorToIncrement(points: number, rules: RedemptionRules | null):
45
45
  return inc > 1 ? Math.floor(points / inc) * inc : points;
46
46
  }
47
47
 
48
+ /**
49
+ * The fewest points, in the store's steps, worth what `points` are worth at
50
+ * `pointValue` cents a point. Checkout values points at floor(points × value),
51
+ * so below a cent a point the last points can buy nothing (51 at 0.5 cents pay
52
+ * what 50 do) and it refuses such an amount (points_buy_nothing). Down only.
53
+ */
54
+ export function fewestPointsForValue(points: number, pointValue: number, rules: RedemptionRules | null): number {
55
+ const inc = rules?.pointsIncrement ?? 0;
56
+ const step = inc > 1 ? inc : 1;
57
+ const lowest = Math.max(1, smallestValidPoints(rules));
58
+ const value = Math.floor(points * pointValue);
59
+ let fewest = points;
60
+ while (fewest - step >= lowest && Math.floor((fewest - step) * pointValue) === value) fewest -= step;
61
+ return fewest;
62
+ }
63
+
48
64
  /** The smallest amount that meets BOTH the minimum and the step (min 450, step 100 -> 500). */
49
65
  export function smallestValidPoints(rules: RedemptionRules | null): number {
50
66
  const min = rules?.minPoints ?? 0;
@@ -61,37 +77,44 @@ export interface OrderBreakdown {
61
77
  shippingCents?: number;
62
78
  }
63
79
 
64
- /** The most points value this order can take before the percent cap. */
65
- export function uncappedCeilingCents(order: OrderBreakdown): number {
66
- return order.merchandiseSubtotalCents != null
67
- ? Math.min(order.orderTotalCents, order.merchandiseSubtotalCents)
68
- : order.orderTotalCents;
80
+ /**
81
+ * The most points value this order can take before the percent cap: the same
82
+ * amount the checkout accepts. In tender mode the store's tax/shipping settings
83
+ * let points pay those too. Discount,
84
+ * coupon, an unset mode or a missing component keep the merchandise ceiling;
85
+ * the server names what is missing.
86
+ */
87
+ export function uncappedCeilingCents(order: OrderBreakdown, rules: RedemptionRules | null): number {
88
+ const merchandiseCeiling =
89
+ order.merchandiseSubtotalCents != null
90
+ ? Math.min(order.orderTotalCents, order.merchandiseSubtotalCents)
91
+ : order.orderTotalCents;
92
+ if (rules?.applicationMode !== 'tender') return merchandiseCeiling;
93
+ if (rules.includeTax && rules.includeShipping) return order.orderTotalCents;
94
+ if (order.merchandiseSubtotalCents == null) return merchandiseCeiling;
95
+ let basis = order.merchandiseSubtotalCents;
96
+ if (rules.includeTax) {
97
+ if (order.taxCents == null) return merchandiseCeiling;
98
+ basis += order.taxCents;
99
+ }
100
+ if (rules.includeShipping) {
101
+ if (order.shippingCents == null) return merchandiseCeiling;
102
+ basis += order.shippingCents;
103
+ }
104
+ return Math.min(basis, order.orderTotalCents);
69
105
  }
70
106
 
71
107
  /**
72
108
  * The most points value this order can take, with the store's percent cap
73
- * applied to the same amount the server caps (in tender mode the tax/shipping
74
- * settings widen it). A missing component falls back to merchandise only:
75
- * offering less is safe, offering more on a guess is not. Floors, so "Use Max"
76
- * always stages a figure the server accepts.
109
+ * taken of that same basis. Floors, so "Use Max" always stages a figure the
110
+ * server accepts.
77
111
  */
78
112
  export function ceilingCents(order: OrderBreakdown, rules: RedemptionRules | null): number {
79
- const uncapped = uncappedCeilingCents(order);
113
+ const basis = uncappedCeilingCents(order, rules);
80
114
  const pct = rules?.maxPercent ?? 0;
81
115
  // Coupon mode has no percent cap on the server (the store's code caps instead).
82
- if (!rules || pct <= 0 || pct >= 100 || rules.applicationMode === 'coupon') return uncapped;
83
- let basis = uncapped;
84
- if (rules.applicationMode === 'tender') {
85
- if (rules.includeTax && rules.includeShipping) {
86
- basis = order.orderTotalCents;
87
- } else if (order.merchandiseSubtotalCents != null) {
88
- let b = order.merchandiseSubtotalCents;
89
- if (rules.includeTax && order.taxCents != null) b += order.taxCents;
90
- if (rules.includeShipping && order.shippingCents != null) b += order.shippingCents;
91
- basis = Math.min(b, order.orderTotalCents);
92
- }
93
- }
94
- return Math.min(uncapped, Math.floor((basis * pct) / 100));
116
+ if (!rules || pct <= 0 || pct >= 100 || rules.applicationMode === 'coupon') return basis;
117
+ return Math.floor((basis * pct) / 100);
95
118
  }
96
119
 
97
120
  /**
@@ -73,6 +73,17 @@ export function planRedeemTender(
73
73
  return null;
74
74
  }
75
75
 
76
+ /** The rows that may pay for one item: a partner reward is priced in one
77
+ * currency (its pay_currency_id) and only that row pays for it. */
78
+ export function rowsPayingIn<T extends TenderRowLike>(
79
+ payableRows: readonly T[] | null | undefined,
80
+ payCurrencyId: string | null | undefined
81
+ ): readonly T[] {
82
+ const rows = payableRows ?? [];
83
+ if (!payCurrencyId) return rows;
84
+ return rows.filter((r) => String(r?.currencyId ?? r?.currency_id ?? '').trim() === payCurrencyId);
85
+ }
86
+
76
87
  /** Max a SINGLE tender can put toward one item (scalar or biggest row). */
77
88
  export function maxTenderableBalance(
78
89
  scalarPointsBalance: number | null | undefined,
@@ -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.7.0';
17
+ export const SDK_VERSION = '1.7.2';
package/src/index.ts CHANGED
@@ -85,7 +85,7 @@ export type {
85
85
 
86
86
  // Core
87
87
  export { APIClient, SDKError } from './core/api-client';
88
- export { createPortabilityHandoff, getPortabilityHandoffStatus } from './core/portabilityHandoff';
88
+ export { createPortabilityHandoff, getPortabilityHandoffAvailable, getPortabilityHandoffStatus } from './core/portabilityHandoff';
89
89
  export type { PortabilityHandoff, PortabilityOutcome } from './core/portabilityHandoff';
90
90
  export { OuterJoynErrorBoundary } from './core/ErrorBoundary';
91
91
  export { SDK_VERSION } from './core/version';
@@ -44,7 +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
+ import { createPortabilityHandoff, getPortabilityHandoffAvailable, getPortabilityHandoffStatus } from '../core/portabilityHandoff';
48
48
 
49
49
  const OJ_LOGO_URL = 'https://app.outerjoyn.com/outerjoyn-logo.png';
50
50
 
@@ -317,8 +317,12 @@ export const ConnectScreen: React.FC<ConnectScreenProps> = ({
317
317
  }
318
318
  const instData = inst.data;
319
319
 
320
- // Check if link portability consent is needed
321
- if (portableData?.consent_status === 'required') {
320
+ // Offer the hand-off only when the hosted page could finish it; one that
321
+ // can only say "we can't confirm it's you" is not offered.
322
+ if (
323
+ portableData?.consent_status === 'required' &&
324
+ (await getPortabilityHandoffAvailable(client).catch(() => false))
325
+ ) {
322
326
  setConsentRequired(true);
323
327
  }
324
328
 
@@ -500,9 +504,10 @@ export const ConnectScreen: React.FC<ConnectScreenProps> = ({
500
504
  const publicToken = params.get('public_token'); // legacy
501
505
 
502
506
  if (error || status === 'error') {
503
- setErrorMessage(error ?? 'Authorization failed');
507
+ const message = params.get('error_description') ?? error ?? 'Authorization failed';
508
+ setErrorMessage(message);
504
509
  setStep('error');
505
- onError?.(new Error(error ?? 'Authorization failed'));
510
+ onError?.(new Error(message));
506
511
  return;
507
512
  }
508
513
 
@@ -190,17 +190,18 @@ export function ExchangeScreen({
190
190
 
191
191
  if (!isDemo && clientRef.current) {
192
192
  clientRef.current
193
- .get<any>('/api/sdk/exchange/rate', {
193
+ .get<any>('/api/v1/exchange/rates', {
194
194
  source_currency_id: String(source.currencyId),
195
195
  target_currency_id: String(target.currencyId),
196
- amount: String(amountNum),
197
196
  })
198
197
  .then((data) => {
198
+ const found = data.rates?.[0];
199
+ if (!found) return;
199
200
  setRate({
200
- rate: data.rate ?? r,
201
- sourceValueAmount: data.source_value_cents ?? amountNum * source.pointValueAmount,
202
- targetValueAmount: data.target_value_cents ?? targetAmount * target.pointValueAmount,
203
- fee: data.fee ?? 0,
201
+ rate: found.rate,
202
+ sourceValueAmount: amountNum * source.pointValueAmount,
203
+ targetValueAmount: Math.floor(amountNum * found.rate) * target.pointValueAmount,
204
+ fee: 0,
204
205
  });
205
206
  })
206
207
  .catch(() => {
@@ -237,21 +238,21 @@ export function ExchangeScreen({
237
238
  return;
238
239
  }
239
240
 
240
- // Fix #8: add idempotency_key to mutation POST
241
241
  if (!clientRef.current) {
242
242
  throw new Error('API client not available');
243
243
  }
244
- const data = await clientRef.current.post<any>('/api/sdk/exchange', {
245
- source_currency_id: source.currencyId,
246
- target_currency_id: target.currencyId,
247
- amount: amountNum,
248
- idempotency_key: Date.now() + '_' + Math.random().toString(36).slice(2),
244
+ // The key travels in the body so the client's network retry replays it.
245
+ const data = await clientRef.current.post<any>('/api/v1/exchange', {
246
+ sourceCurrencyId: String(source.currencyId),
247
+ targetCurrencyId: String(target.currencyId),
248
+ sourceAmount: amountNum,
249
+ idempotencyKey: Date.now() + '_' + Math.random().toString(36).slice(2),
249
250
  });
250
251
 
251
252
  const res: ExchangeResult = {
252
- transactionId: data.transaction_id ?? data.id ?? '',
253
- sourceAmount: amountNum,
254
- targetAmount: data.target_amount ?? targetAmount,
253
+ transactionId: String(data.transactionId),
254
+ sourceAmount: data.sourceAmount,
255
+ targetAmount: data.targetAmount,
255
256
  sourceCurrency: source.currencyName,
256
257
  targetCurrency: target.currencyName,
257
258
  status: data.status ?? 'completed',
@@ -25,7 +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
+ import { planRedeemTender, maxTenderableBalance, rowsPayingIn } from '../core/tender';
29
29
  import { APIClient } from '../core/api-client';
30
30
 
31
31
  // =============================================================================
@@ -77,6 +77,10 @@ interface CatalogItem {
77
77
  inventory_count?: number;
78
78
  terms_and_conditions?: string;
79
79
  expiry_days?: number;
80
+ /** Snowflake STRINGS on a partner reward: the partnership it is shared
81
+ * through and the one currency its price is in. */
82
+ partnership_id?: string;
83
+ pay_currency_id?: string;
80
84
  }
81
85
 
82
86
  const OJ_LOGO_URL = 'https://app.outerjoyn.com/outerjoyn-logo.png';
@@ -161,7 +165,7 @@ export function RedeemScreen({
161
165
  // Category chip filter ('' = All) — Plaid-grade redesign 2026-07-21.
162
166
  const [categoryFilter, setCategoryFilter] = useState('');
163
167
 
164
- // "Available to spend": /api/sdk/balance only reads the single brand
168
+ // "Available to spend": the account's points_balance only reads the single brand
165
169
  // Member.points_balance, which is 0 for cross-program demo members even
166
170
  // when the provider holds six-figure payable balances — the infamous
167
171
  // "Total Available Value: 0 pts" header. Prefer the provider's
@@ -212,6 +216,8 @@ export function RedeemScreen({
212
216
  inventory_count: item.inventory_count ?? item.inventoryCount,
213
217
  terms_and_conditions: item.terms_and_conditions ?? item.termsAndConditions,
214
218
  expiry_days: item.expiry_days ?? item.expiryDays,
219
+ partnership_id: item.partnership_id ?? item.partnershipId,
220
+ pay_currency_id: item.pay_currency_id ?? item.payCurrencyId,
215
221
  }));
216
222
  // A genuinely empty catalog is a real (empty) state — render it as
217
223
  // such via ListEmptyComponent rather than masking it with demo items.
@@ -226,8 +232,8 @@ export function RedeemScreen({
226
232
  .finally(() => setLoading(false));
227
233
 
228
234
  clientRef.current
229
- .get<any>('/api/sdk/balance')
230
- .then((data) => setBalance(data?.points_balance ?? data?.pointsBalance ?? data?.balance ?? 0))
235
+ .get<any>('/api/sdk/account')
236
+ .then((data) => setBalance(data?.member?.points_balance ?? 0))
231
237
  .catch(() => {});
232
238
  }, [visible, isDemo, ctx.apiClient, reloadKey]);
233
239
 
@@ -279,7 +285,7 @@ export function RedeemScreen({
279
285
  // cross-program TOTAL) — a sum no single tender can spend, so it enabled
280
286
  // confirms the server would reject. Plan against the scalar + per-row
281
287
  // balances instead; effectiveBalance stays display-only.
282
- const tenderRows = useMemo(
288
+ const allTenderRows = useMemo(
283
289
  () =>
284
290
  (ctx.linkedPrograms ?? []).map((p) => ({
285
291
  balance: p.pointsBalance,
@@ -288,6 +294,11 @@ export function RedeemScreen({
288
294
  })),
289
295
  [ctx.linkedPrograms]
290
296
  );
297
+ // A partner reward is paid only from the currency it is priced in.
298
+ const tenderRows = useMemo(
299
+ () => rowsPayingIn(allTenderRows, selectedItem?.pay_currency_id),
300
+ [allTenderRows, selectedItem]
301
+ );
291
302
 
292
303
  const handleRedeem = useCallback(() => {
293
304
  if (!selectedItem) return;
@@ -346,6 +357,7 @@ export function RedeemScreen({
346
357
  const data = await clientRef.current.post<any>('/api/sdk/redeem', {
347
358
  product_id: selectedItem.product_id,
348
359
  payment,
360
+ ...(selectedItem.partnership_id ? { partnershipId: selectedItem.partnership_id } : {}),
349
361
  idempotency_key: Date.now() + '_' + Math.random().toString(36).slice(2),
350
362
  });
351
363
  const res: RedemptionResult = {
@@ -371,7 +383,7 @@ export function RedeemScreen({
371
383
  // DEPS: balance, tenderRows and ctx are READ in this callback and MUST be
372
384
  // listed. They were omitted once, which froze the callback at its
373
385
  // mount-time values (balance 0, tenderRows []) — both are populated
374
- // asynchronously (/api/sdk/balance and /sessions/context). planRedeemTender
386
+ // asynchronously (/api/sdk/account and /sessions/context). planRedeemTender
375
387
  // then returned null on every real redemption, and the old
376
388
  // `?? {method:'points'}` fallback submitted a points tender against a
377
389
  // scalar of 0: a guaranteed 400 insufficient_balance for exactly the
@@ -467,7 +479,7 @@ export function RedeemScreen({
467
479
  const renderCatalog = () => (
468
480
  <View style={styles.content}>
469
481
  {/* Available-to-spend chip — cross-program totals from the provider
470
- (the old header read /api/sdk/balance = single-brand
482
+ (the old header read the account's single-brand
471
483
  Member.points_balance, which rendered "0 pts" for cross-program
472
484
  demo members). */}
473
485
  <View style={styles.balanceChip}>