@outerjoyn/react-native 1.6.1 → 1.7.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@outerjoyn/react-native",
3
- "version": "1.6.1",
3
+ "version": "1.7.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",
@@ -35,6 +35,7 @@ import { PaySheet, ConnectSheet, ExchangeSheet, RedeemSheet, _setContextRef } fr
35
35
  import { OuterJoynSheet } from './OuterJoynSheet';
36
36
 
37
37
  import { OJ_COLORS } from './core/colors';
38
+ import { parseRedemptionRules, type RedemptionRules } from './core/redemptionRules';
38
39
  import type {
39
40
  OuterJoynProviderProps,
40
41
  OuterJoynContextValue,
@@ -216,6 +217,7 @@ export function OuterJoynProvider({
216
217
  const [demoMode, setDemoMode] = useState(false);
217
218
  const [linkedPrograms, setLinkedPrograms] = useState<LinkedProgram[]>([]);
218
219
  const [brandConfig, setBrandConfig] = useState<BrandConfig | null>(null);
220
+ const [redemptionRules, setRedemptionRules] = useState<RedemptionRules | null>(null);
219
221
  const [sessionStatus, setSessionStatus] = useState<
220
222
  'idle' | 'loading' | 'ready' | 'link_required' | 'error'
221
223
  >('idle');
@@ -355,6 +357,7 @@ export function OuterJoynProvider({
355
357
  if (ctx.brand_config) {
356
358
  setBrandConfig(ctx.brand_config);
357
359
  }
360
+ setRedemptionRules(parseRedemptionRules(ctx.redemption_rules));
358
361
 
359
362
  if (ctx.expires_at) {
360
363
  scheduleRefresh(ctx.expires_at);
@@ -430,6 +433,7 @@ export function OuterJoynProvider({
430
433
 
431
434
  setLinkedPrograms(programs);
432
435
  setBrandConfig(ctx.brand_config ?? null);
436
+ setRedemptionRules(parseRedemptionRules(ctx.redemption_rules));
433
437
 
434
438
  // Persist to offline cache
435
439
  if (offlineCacheRef.current) {
@@ -697,6 +701,7 @@ export function OuterJoynProvider({
697
701
  error,
698
702
  demoMode,
699
703
  brandConfig,
704
+ redemptionRules,
700
705
 
701
706
  // Actions
702
707
  refreshBalances,
@@ -732,6 +737,7 @@ export function OuterJoynProvider({
732
737
  error,
733
738
  demoMode,
734
739
  brandConfig,
740
+ redemptionRules,
735
741
  refreshBalances,
736
742
  openConnect,
737
743
  openExchange,
@@ -43,6 +43,14 @@ import {
43
43
  import Slider from '@react-native-community/slider';
44
44
  import { useOuterJoyn } from '../useOuterJoyn';
45
45
  import { OJ_COLORS } from '../core/colors';
46
+ import {
47
+ amountError,
48
+ blockedReason,
49
+ ceilingCents,
50
+ floorToIncrement,
51
+ rulesSummary,
52
+ uncappedCeilingCents,
53
+ } from '../core/redemptionRules';
46
54
 
47
55
  const OJ_LOGO_URL = 'https://app.outerjoyn.com/outerjoyn-logo.png';
48
56
  const PRIMARY = OJ_COLORS.primary;
@@ -125,7 +133,7 @@ export const CheckoutPointsApply = forwardRef<CheckoutPointsApplyHandle, Checkou
125
133
  style,
126
134
  }: CheckoutPointsApplyProps, ref) {
127
135
  const ctx = useOuterJoyn();
128
- const { isReady, isLinked, linkedPrograms, loading, demoMode, apiClient, t } = ctx;
136
+ const { isReady, isLinked, linkedPrograms, loading, demoMode, apiClient, redemptionRules, t } = ctx;
129
137
 
130
138
  const [sliderValues, setSliderValues] = useState<Record<string, number>>({});
131
139
  const [confirmedPrograms, setConfirmedPrograms] = useState<Set<string>>(new Set());
@@ -185,6 +193,13 @@ export const CheckoutPointsApply = forwardRef<CheckoutPointsApplyHandle, Checkou
185
193
 
186
194
  const selectedPoints = sliderValues[progId] ?? 0;
187
195
  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);
199
+ if (ruleError) {
200
+ setApiError((prev) => ({ ...prev, [progId]: ruleError }));
201
+ return;
202
+ }
188
203
 
189
204
  // Validate orderTotalCents inside callback scope
190
205
  const validOrderTotal = (typeof orderTotalCents === 'number' && !Number.isNaN(orderTotalCents))
@@ -282,7 +297,7 @@ export const CheckoutPointsApply = forwardRef<CheckoutPointsApplyHandle, Checkou
282
297
  setApiLoading((prev) => ({ ...prev, [progId]: false }));
283
298
  }
284
299
  },
285
- [programs, sliderValues, demoMode, apiClient, orderTotalCents, merchandiseSubtotalCents, taxCents, shippingCents, currencyCode, buildPayload, onPointsChanged, redemptionTokens],
300
+ [programs, sliderValues, demoMode, apiClient, orderTotalCents, merchandiseSubtotalCents, taxCents, shippingCents, currencyCode, buildPayload, onPointsChanged, redemptionTokens, redemptionRules],
286
301
  );
287
302
 
288
303
  const handleRemove = useCallback(
@@ -386,6 +401,17 @@ export const CheckoutPointsApply = forwardRef<CheckoutPointsApplyHandle, Checkou
386
401
  if (!isReady && !loading) return null;
387
402
  if (!isLinked || programs.length === 0) return null;
388
403
 
404
+ const order = {
405
+ orderTotalCents: safeOrderTotalCents,
406
+ merchandiseSubtotalCents: Number.isFinite(merchandiseSubtotalCents) ? merchandiseSubtotalCents : undefined,
407
+ taxCents: Number.isFinite(taxCents) ? taxCents : undefined,
408
+ shippingCents: Number.isFinite(shippingCents) ? shippingCents : undefined,
409
+ };
410
+ // The most points value this order can take: before and after the store's percent cap.
411
+ const orderCeilingCents = ceilingCents(order, redemptionRules);
412
+ const orderUncappedCents = uncappedCeilingCents(order);
413
+ const rulesLine = rulesSummary(redemptionRules);
414
+
389
415
  // Calculate already-confirmed total to cap remaining programs
390
416
  const confirmedTotalCents = programs.reduce((sum, prog) => {
391
417
  if (confirmedPrograms.has(prog.id)) {
@@ -397,6 +423,7 @@ export const CheckoutPointsApply = forwardRef<CheckoutPointsApplyHandle, Checkou
397
423
  return (
398
424
  <View style={[styles.container, style]}>
399
425
  <Text style={styles.sectionLabel}>{t('banner.pay_with_points')}</Text>
426
+ {rulesLine && <Text style={styles.rulesText}>{rulesLine}</Text>}
400
427
 
401
428
  {programs.map((prog) => {
402
429
  const isConfirmed = confirmedPrograms.has(prog.id);
@@ -404,15 +431,17 @@ export const CheckoutPointsApply = forwardRef<CheckoutPointsApplyHandle, Checkou
404
431
  const previewValueAmount = Math.round(currentPts * prog.pointValueAmount);
405
432
  const previewDollars = (previewValueAmount / 100).toFixed(2);
406
433
 
407
- // Cap slider so total doesn't exceed order
434
+ // Cap the slider at what this order can still take, in the store's steps.
408
435
  const otherConfirmedCents = confirmedTotalCents - (isConfirmed ? previewValueAmount : 0);
409
- const remainingCents = Math.max(0, safeOrderTotalCents - otherConfirmedCents);
410
- const maxPointsForRemaining =
411
- prog.pointValueAmount > 0
412
- ? Math.ceil(remainingCents / prog.pointValueAmount)
413
- : prog.pointsBalance;
414
- const maxSlider = Math.min(prog.pointsBalance, maxPointsForRemaining);
415
- const sliderStep = Math.max(1, Math.floor(maxSlider / 100));
436
+ const maxPointsFor = (ceiling: number) => {
437
+ const remaining = Math.max(0, ceiling - otherConfirmedCents);
438
+ const pts = prog.pointValueAmount > 0 ? Math.floor(remaining / prog.pointValueAmount) : prog.pointsBalance;
439
+ return floorToIncrement(Math.min(prog.pointsBalance, pts), redemptionRules);
440
+ };
441
+ const maxSlider = maxPointsFor(orderCeilingCents);
442
+ const blocked = blockedReason(prog.pointsBalance, maxSlider, maxPointsFor(orderUncappedCents), redemptionRules);
443
+ const increment = redemptionRules?.pointsIncrement ?? 0;
444
+ const sliderStep = increment > 1 ? increment : Math.max(1, Math.floor(maxSlider / 100));
416
445
 
417
446
  const isLoading = apiLoading[prog.id] ?? false;
418
447
  const errorMsg = apiError[prog.id];
@@ -420,7 +449,7 @@ export const CheckoutPointsApply = forwardRef<CheckoutPointsApplyHandle, Checkou
420
449
  return (
421
450
  <View
422
451
  key={prog.id}
423
- style={[styles.programCard, isConfirmed && styles.programCardApplied]}
452
+ style={[styles.programCard, isConfirmed && styles.programCardApplied, !isConfirmed && blocked ? styles.programCardBlocked : null]}
424
453
  >
425
454
  {/* Header */}
426
455
  <View style={styles.programHeader}>
@@ -469,7 +498,9 @@ export const CheckoutPointsApply = forwardRef<CheckoutPointsApplyHandle, Checkou
469
498
  )}
470
499
 
471
500
  {/* Applied state */}
472
- {isConfirmed ? (
501
+ {!isConfirmed && blocked ? (
502
+ <Text style={styles.blockedText}>{blocked}</Text>
503
+ ) : isConfirmed ? (
473
504
  <View style={styles.appliedRow}>
474
505
  <Text style={[styles.checkmark, { color: SUCCESS }]}>{'\u2714'}</Text>
475
506
  <Text style={styles.appliedLabel}>
@@ -634,6 +665,9 @@ const styles = StyleSheet.create({
634
665
  borderColor: SUCCESS,
635
666
  backgroundColor: '#F0FDF4',
636
667
  },
668
+ programCardBlocked: {
669
+ opacity: 0.6,
670
+ },
637
671
  programHeader: {
638
672
  flexDirection: 'row',
639
673
  alignItems: 'center',
@@ -679,6 +713,17 @@ const styles = StyleSheet.create({
679
713
  fontWeight: '600',
680
714
  padding: 4,
681
715
  },
716
+ rulesText: {
717
+ fontSize: 12,
718
+ color: '#6B7280',
719
+ marginTop: -6,
720
+ marginBottom: 10,
721
+ },
722
+ blockedText: {
723
+ fontSize: 12,
724
+ color: '#6B7280',
725
+ marginTop: 8,
726
+ },
682
727
  errorText: {
683
728
  fontSize: 12,
684
729
  color: '#DC2626',
@@ -0,0 +1,152 @@
1
+ /**
2
+ * The store's pay-with-points rules, as served on /api/sdk/sessions/context
3
+ * (`redemption_rules`): a minimum, a step size, and a cap on how much of an
4
+ * order points may pay. The server enforces them at reserve; this module only
5
+ * shapes the input so the shopper meets a rule here instead of as an error
6
+ * after Apply. Same semantics as the web pay widget.
7
+ */
8
+
9
+ export interface RedemptionRules {
10
+ /** 0 = no cap; 1..99 = points may pay at most this percent of the order's redeemable amount. */
11
+ maxPercent: number;
12
+ /** 0 = no minimum; else the fewest points one program may apply. */
13
+ minPoints: number;
14
+ /** 0 = none; else points must be a whole multiple of this. */
15
+ pointsIncrement: number;
16
+ allowRewardStacking: boolean;
17
+ /** 'discount' | 'tender' | 'coupon' | '' (unset). */
18
+ applicationMode: string;
19
+ includeTax: boolean;
20
+ includeShipping: boolean;
21
+ }
22
+
23
+ /** Wrong type or out of range reads as "no rule", never a lockout. */
24
+ export function parseRedemptionRules(raw: unknown): RedemptionRules | null {
25
+ if (!raw || typeof raw !== 'object') return null;
26
+ const rr = raw as Record<string, unknown>;
27
+ const intOr0 = (v: unknown, lo: number, hi: number) => {
28
+ const n = typeof v === 'number' && Number.isFinite(v) ? Math.floor(v) : 0;
29
+ return n >= lo && n <= hi ? n : 0;
30
+ };
31
+ return {
32
+ maxPercent: intOr0(rr.max_percent, 1, 99),
33
+ minPoints: intOr0(rr.min_points, 1, Number.MAX_SAFE_INTEGER),
34
+ pointsIncrement: intOr0(rr.points_increment, 2, Number.MAX_SAFE_INTEGER),
35
+ allowRewardStacking: rr.allow_reward_stacking !== false,
36
+ applicationMode: typeof rr.application_mode === 'string' ? rr.application_mode : '',
37
+ includeTax: rr.redeem_include_tax === true,
38
+ includeShipping: rr.redeem_include_shipping === true,
39
+ };
40
+ }
41
+
42
+ /** Round DOWN to the step (identity when none): never more points than asked. */
43
+ export function floorToIncrement(points: number, rules: RedemptionRules | null): number {
44
+ const inc = rules?.pointsIncrement ?? 0;
45
+ return inc > 1 ? Math.floor(points / inc) * inc : points;
46
+ }
47
+
48
+ /** The smallest amount that meets BOTH the minimum and the step (min 450, step 100 -> 500). */
49
+ export function smallestValidPoints(rules: RedemptionRules | null): number {
50
+ const min = rules?.minPoints ?? 0;
51
+ const inc = rules?.pointsIncrement ?? 0;
52
+ const lowest = min > 0 ? min : 1;
53
+ if (inc <= 1) return min > 0 ? min : 0;
54
+ return Math.max(inc, Math.ceil(lowest / inc) * inc);
55
+ }
56
+
57
+ export interface OrderBreakdown {
58
+ orderTotalCents: number;
59
+ merchandiseSubtotalCents?: number;
60
+ taxCents?: number;
61
+ shippingCents?: number;
62
+ }
63
+
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;
69
+ }
70
+
71
+ /**
72
+ * 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.
77
+ */
78
+ export function ceilingCents(order: OrderBreakdown, rules: RedemptionRules | null): number {
79
+ const uncapped = uncappedCeilingCents(order);
80
+ const pct = rules?.maxPercent ?? 0;
81
+ // 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));
95
+ }
96
+
97
+ /**
98
+ * Why a program can't be used on this order, as shopper copy, or null.
99
+ * `maxPoints` is the most this program may apply (already capped and stepped);
100
+ * `uncappedMaxPoints` is the same figure without the percent cap, so the reason
101
+ * can name the cap when it is the cause.
102
+ */
103
+ export function blockedReason(
104
+ balance: number,
105
+ maxPoints: number,
106
+ uncappedMaxPoints: number,
107
+ rules: RedemptionRules | null,
108
+ ): string | null {
109
+ const floor = rules?.minPoints ?? 0;
110
+ if (floor <= 0 || maxPoints >= floor) return null;
111
+ const pts = floor.toLocaleString();
112
+ if (balance < floor) return `You need at least ${pts} points to redeem from this program.`;
113
+ if (uncappedMaxPoints > maxPoints && uncappedMaxPoints >= floor) {
114
+ return `Points can pay up to ${rules!.maxPercent}% of this order — less than the ${pts}-point minimum.`;
115
+ }
116
+ return `This order is too small to use the ${pts}-point minimum.`;
117
+ }
118
+
119
+ /** The refusal for an amount the server would turn down, as shopper copy, or null. */
120
+ export function amountError(points: number, rules: RedemptionRules | null): string | null {
121
+ const floor = rules?.minPoints ?? 0;
122
+ const inc = rules?.pointsIncrement ?? 0;
123
+ if (inc > 1 && points % inc !== 0) {
124
+ const snapped = floorToIncrement(points, rules);
125
+ if (floor > 0 && snapped < floor) {
126
+ return `You need to use at least ${smallestValidPoints(rules).toLocaleString()} points at a time.`;
127
+ }
128
+ if (snapped <= 0) return `Points can only be used in multiples of ${inc.toLocaleString()}.`;
129
+ return `Points can only be used in multiples of ${inc.toLocaleString()} — try ${snapped.toLocaleString()}.`;
130
+ }
131
+ if (floor > 0 && points < floor) {
132
+ return `You need to use at least ${floor.toLocaleString()} points at a time.`;
133
+ }
134
+ return null;
135
+ }
136
+
137
+ /** One plain line naming the store's rules, or null when there are none. */
138
+ export function rulesSummary(rules: RedemptionRules | null): string | null {
139
+ if (!rules) return null;
140
+ const parts: string[] = [];
141
+ if (rules.minPoints > 0 && rules.pointsIncrement > 1) {
142
+ parts.push(`Use at least ${rules.minPoints.toLocaleString()} points, in steps of ${rules.pointsIncrement.toLocaleString()}.`);
143
+ } else if (rules.minPoints > 0) {
144
+ parts.push(`Use at least ${rules.minPoints.toLocaleString()} points.`);
145
+ } else if (rules.pointsIncrement > 1) {
146
+ parts.push(`Points are used in steps of ${rules.pointsIncrement.toLocaleString()}.`);
147
+ }
148
+ if (rules.maxPercent > 0 && rules.applicationMode !== 'coupon') {
149
+ parts.push(`Points can pay up to ${rules.maxPercent}% of this order.`);
150
+ }
151
+ return parts.length ? parts.join(' ') : null;
152
+ }
package/src/core/types.ts CHANGED
@@ -33,6 +33,8 @@ export interface SessionContextResponse {
33
33
  payable_balances?: PayableBalance[];
34
34
  brand_config?: BrandConfig;
35
35
  returning_user?: boolean;
36
+ /** The store's pay-with-points rules; absent when the key has no storefront. */
37
+ redemption_rules?: Record<string, unknown>;
36
38
  }
37
39
 
38
40
  export interface PayableBalance {
@@ -188,6 +190,11 @@ export interface OuterJoynContextValue {
188
190
  error: Error | null;
189
191
  demoMode: boolean;
190
192
  brandConfig: BrandConfig | null;
193
+ /**
194
+ * The store's pay-with-points rules (minimum, step, percent cap), or null
195
+ * when the store sets none. Display only: the server enforces them.
196
+ */
197
+ redemptionRules: import('./redemptionRules').RedemptionRules | null;
191
198
 
192
199
  // Actions
193
200
  refreshBalances: () => Promise<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.6.1';
17
+ export const SDK_VERSION = '1.7.0';
package/src/index.ts CHANGED
@@ -101,6 +101,7 @@ export type {
101
101
  OuterJoynProviderProps,
102
102
  OuterJoynContextValue,
103
103
  } from './core/types';
104
+ export type { RedemptionRules } from './core/redemptionRules';
104
105
 
105
106
  export type {
106
107
  OuterJoynConfig,