@quantaroute/checkout 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.
@@ -38,6 +38,7 @@ const PaymentStep: React.FC<PaymentStepProps> = ({
38
38
  amountPaise,
39
39
  enableCod = false,
40
40
  codAllowed = false,
41
+ addressRisk,
41
42
  theme = 'light',
42
43
  onComplete,
43
44
  onBack,
@@ -125,6 +126,9 @@ const PaymentStep: React.FC<PaymentStepProps> = ({
125
126
  };
126
127
 
127
128
  const amountDisplay = `₹${(amountPaise / 100).toLocaleString('en-IN')}`;
129
+ const codBlockedByRisk = addressRisk?.interventions.includes('hide_cod') ?? false;
130
+ const riskTone =
131
+ addressRisk?.level === 'high' ? 'high' : addressRisk?.level === 'medium' ? 'medium' : 'low';
128
132
 
129
133
  return (
130
134
  <div className={`qr-payment-step${isDark ? ' qr-payment-step--dark' : ''}`}>
@@ -140,6 +144,18 @@ const PaymentStep: React.FC<PaymentStepProps> = ({
140
144
 
141
145
  {error ? <p className="qr-auth-step__error" role="alert">{error}</p> : null}
142
146
 
147
+ {addressRisk && addressRisk.level !== 'low' ? (
148
+ <div className={`qr-risk-banner qr-risk-banner--${riskTone}`} role="status">
149
+ <strong>
150
+ {addressRisk.level === 'high' ? 'Address needs extra confirmation' : 'Address confidence check'}
151
+ </strong>
152
+ <span>{addressRisk.reasons[0]}</span>
153
+ {codBlockedByRisk ? (
154
+ <span>Cash on Delivery is disabled for this order. Online payment is still available.</span>
155
+ ) : null}
156
+ </div>
157
+ ) : null}
158
+
143
159
  <button
144
160
  type="button"
145
161
  className="qr-payment-option qr-payment-option--primary"
@@ -156,7 +172,7 @@ const PaymentStep: React.FC<PaymentStepProps> = ({
156
172
  <strong className="qr-payment-option__amount">{amountDisplay}</strong>
157
173
  </button>
158
174
 
159
- {enableCod && codAllowed ? (
175
+ {enableCod && codAllowed && !codBlockedByRisk ? (
160
176
  <button
161
177
  type="button"
162
178
  className="qr-payment-option qr-payment-option--secondary"
@@ -386,6 +386,85 @@ export interface ServiceabilityResult {
386
386
  | 'invalid_response';
387
387
  }
388
388
 
389
+ // ─── Address Intelligence ─────────────────────────────────────────────────────
390
+
391
+ export type AddressRiskLevel = 'low' | 'medium' | 'high';
392
+
393
+ export type AddressIntervention =
394
+ | 'none'
395
+ | 'request_missing_details'
396
+ | 'reconfirm_pin'
397
+ | 'prepaid_nudge'
398
+ | 'hide_cod'
399
+ | 'manual_review'
400
+ | 'delivery_instruction';
401
+
402
+ export type AddressConfidenceState =
403
+ | 'new_source_collected'
404
+ | 'buyer_reconfirmed'
405
+ | 'merchant_successful'
406
+ | 'courier_corrected'
407
+ | 'rto_associated'
408
+ | 'trusted_repeat';
409
+
410
+ export interface AddressRiskSignals {
411
+ merchant_history_records: number;
412
+ buyer_successful_deliveries: number;
413
+ buyer_rto_orders: number;
414
+ pincode_successful_deliveries: number;
415
+ pincode_rto_orders: number;
416
+ digipin_cell_successful_deliveries: number;
417
+ digipin_cell_rto_orders: number;
418
+ repeat_verified_address: boolean;
419
+ imported_address_pending_digipin: boolean;
420
+ cod_requested: boolean;
421
+ address_edit_count: number;
422
+ }
423
+
424
+ export interface AddressRiskScore {
425
+ level: AddressRiskLevel;
426
+ score: number;
427
+ reasons: string[];
428
+ interventions: AddressIntervention[];
429
+ confidence_state: AddressConfidenceState;
430
+ signals: AddressRiskSignals;
431
+ scored_at: string;
432
+ }
433
+
434
+ export interface AddressRiskPayload {
435
+ address_id?: string;
436
+ digipin?: string;
437
+ lat?: number;
438
+ lng?: number;
439
+ pincode?: string;
440
+ state?: string;
441
+ district?: string;
442
+ locality?: string;
443
+ delivery_status?: string;
444
+ flat_number?: string;
445
+ floor_number?: string;
446
+ building_name?: string;
447
+ street_name?: string;
448
+ payment_method?: string;
449
+ }
450
+
451
+ export async function scoreAddressRisk(
452
+ config: CheckoutApiConfig,
453
+ sessionToken: string,
454
+ payload: AddressRiskPayload
455
+ ): Promise<AddressRiskScore> {
456
+ const res = await fetch(`${config.functionBaseUrl}/checkout-addresses`, {
457
+ method: 'POST',
458
+ headers: addressHeaders(sessionToken),
459
+ body: JSON.stringify({ action: 'address_risk', data: payload }),
460
+ });
461
+ const data = await res.json().catch(() => ({}));
462
+ if (!res.ok || !data.success) {
463
+ throw new Error(data.error ?? 'Failed to score address risk.');
464
+ }
465
+ return data.data as AddressRiskScore;
466
+ }
467
+
389
468
  /**
390
469
  * Check merchant courier serviceability for a pincode.
391
470
  * Uses the merchant's configured webhook on checkout.merchants and fails open.
@@ -0,0 +1,100 @@
1
+ import type {
2
+ Map as MapLibreMap,
3
+ MapMouseEvent,
4
+ Marker as MapLibreMarker,
5
+ } from 'maplibre-gl';
6
+
7
+ /** Subset of maplibre-gl used by the web MapPinSelector. */
8
+ export interface MapRuntime {
9
+ Map: new (
10
+ options: ConstructorParameters<typeof import('maplibre-gl').Map>[0]
11
+ ) => MapLibreMap;
12
+ Marker: new (
13
+ options?: ConstructorParameters<typeof import('maplibre-gl').Marker>[0]
14
+ ) => MapLibreMarker;
15
+ AttributionControl?: new (
16
+ options?: ConstructorParameters<
17
+ NonNullable<typeof import('maplibre-gl').AttributionControl>
18
+ >[0]
19
+ ) => import('maplibre-gl').AttributionControl;
20
+ NavigationControl?: new (
21
+ options?: ConstructorParameters<
22
+ NonNullable<typeof import('maplibre-gl').NavigationControl>
23
+ >[0]
24
+ ) => import('maplibre-gl').NavigationControl;
25
+ }
26
+
27
+ export type { MapLibreMap, MapLibreMarker, MapMouseEvent };
28
+
29
+ /**
30
+ * How the host provides MapLibre GL JS.
31
+ * - `bundled`: import from `maplibre-gl` (default — Next.js, Vite apps with the peer installed)
32
+ * - `external`: read from `window.maplibregl` (CDN script loaded before the widget, e.g. Shopify)
33
+ */
34
+ export type MapEmbedMode = 'bundled' | 'external';
35
+
36
+ /** Carto Positron — default basemap for standard web embeds. */
37
+ export const DEFAULT_MAP_STYLE_URL =
38
+ 'https://basemaps.cartocdn.com/gl/positron-gl-style/style.json';
39
+
40
+ /** OpenFreeMap Positron — free, no API key (used when Carto credentials are unavailable). */
41
+ export const OPENFREEMAP_POSITRON_STYLE_URL =
42
+ 'https://tiles.openfreemap.org/styles/positron';
43
+
44
+ const MAPLIBRE_WAIT_MS = 8_000;
45
+ const MAPLIBRE_RETRY_MS = 100;
46
+
47
+ declare global {
48
+ interface Window {
49
+ maplibregl?: MapRuntime;
50
+ }
51
+ }
52
+
53
+ export function getExternalMapRuntime(): MapRuntime | null {
54
+ if (typeof window === 'undefined') return null;
55
+ const maplibre = window.maplibregl;
56
+ if (
57
+ !maplibre ||
58
+ typeof maplibre.Map !== 'function' ||
59
+ typeof maplibre.Marker !== 'function'
60
+ ) {
61
+ return null;
62
+ }
63
+ return maplibre;
64
+ }
65
+
66
+ /**
67
+ * Poll `window.maplibregl` until available or timeout (for async CDN loads).
68
+ * Returns a cancel function for useEffect cleanup.
69
+ */
70
+ export function waitForExternalMapRuntime(
71
+ onReady: (runtime: MapRuntime) => void,
72
+ onUnavailable: () => void,
73
+ waitMs: number = MAPLIBRE_WAIT_MS,
74
+ retryMs: number = MAPLIBRE_RETRY_MS
75
+ ): () => void {
76
+ const startedAt = Date.now();
77
+ let retryTimer: number | null = null;
78
+ let cancelled = false;
79
+
80
+ const tryGet = () => {
81
+ if (cancelled) return;
82
+ const runtime = getExternalMapRuntime();
83
+ if (runtime) {
84
+ onReady(runtime);
85
+ return;
86
+ }
87
+ if (Date.now() - startedAt >= waitMs) {
88
+ onUnavailable();
89
+ return;
90
+ }
91
+ retryTimer = window.setTimeout(tryGet, retryMs);
92
+ };
93
+
94
+ tryGet();
95
+
96
+ return () => {
97
+ cancelled = true;
98
+ if (retryTimer !== null) window.clearTimeout(retryTimer);
99
+ };
100
+ }
package/src/core/types.ts CHANGED
@@ -1,6 +1,12 @@
1
1
  import type { ReactNode } from 'react';
2
+ import type { MapEmbedMode } from './map-runtime';
2
3
  import type { UtmParams } from './utm';
3
- import type { CheckoutApiConfig, ServiceabilityResult, SessionContextPayload } from './checkout-api';
4
+ import type {
5
+ AddressRiskScore,
6
+ CheckoutApiConfig,
7
+ ServiceabilityResult,
8
+ SessionContextPayload,
9
+ } from './checkout-api';
4
10
 
5
11
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
6
12
  type AnyStyle = any; // CSSProperties on web · StyleProp<ViewStyle> on native
@@ -95,6 +101,8 @@ export interface CompleteAddress {
95
101
  labelText?: string;
96
102
  /** Set when the buyer re-selected an existing saved row (skip createAddress). */
97
103
  addressId?: string;
104
+ /** Explainable checkout-time address discrepancy risk, when enabled. */
105
+ addressRisk?: AddressRiskScore;
98
106
  }
99
107
 
100
108
  /** Imperative hooks for host pages (e.g. Shopify pre-checkout shell). */
@@ -133,6 +141,7 @@ export type CheckoutEventType =
133
141
  | 'location_confirmed'
134
142
  | 'form_step_viewed'
135
143
  | 'address_completed'
144
+ | 'address_risk_scored'
136
145
  | 'widget_reset'
137
146
  | 'payment_step_viewed'
138
147
  | 'payment_method_selected'
@@ -167,6 +176,10 @@ export interface CheckoutEvent {
167
176
  experimentVariant?: string;
168
177
  /** DigiPin of the confirmed location. Available after `location_confirmed` and `address_completed`. */
169
178
  digipin?: string;
179
+ /** Address risk level when `address_risk_scored` fires. */
180
+ addressRiskLevel?: AddressRiskScore['level'];
181
+ /** Address risk score (0-100) when address intelligence is enabled. */
182
+ addressRiskScore?: number;
170
183
  /** ISO timestamp of when the event fired. */
171
184
  timestamp: string;
172
185
  }
@@ -204,6 +217,16 @@ export interface MapPinSelectorProps {
204
217
  * Brand accent colour (hex, e.g. `#7c3aed`). Sets map pin, buttons, focus rings via `--qr-primary` on web.
205
218
  */
206
219
  brandColor?: string;
220
+ /**
221
+ * MapLibre style URL for the basemap. Defaults to Carto Positron.
222
+ * Use `OPENFREEMAP_POSITRON_STYLE_URL` when Carto credentials are unavailable.
223
+ */
224
+ mapStyle?: string;
225
+ /**
226
+ * How MapLibre GL JS is loaded on web. `bundled` imports the peer dependency;
227
+ * `external` waits for `window.maplibregl` (CDN script loaded by the host).
228
+ */
229
+ embedMode?: MapEmbedMode;
207
230
  }
208
231
 
209
232
  /** Pre-fill manual fields when verifying an imported saved address. */
@@ -285,6 +308,16 @@ export interface CheckoutWidgetProps {
285
308
  * Example: indiaBoundaryUrl="/geojson/india.geojson"
286
309
  */
287
310
  indiaBoundaryUrl?: string;
311
+ /**
312
+ * MapLibre style URL for the map step. Defaults to Carto Positron.
313
+ * Pass `OPENFREEMAP_POSITRON_STYLE_URL` when Carto basemaps require credentials.
314
+ */
315
+ mapStyle?: string;
316
+ /**
317
+ * How MapLibre GL JS is loaded on web. `external` waits for `window.maplibregl`
318
+ * when the host loads MapLibre from a CDN (e.g. Shopify theme extensions).
319
+ */
320
+ embedMode?: MapEmbedMode;
288
321
  /**
289
322
  * Show the smart search bar on the map step (default: true).
290
323
  * Supports address search (API) and DigiPin lookup (100% offline).
@@ -330,6 +363,11 @@ export interface CheckoutWidgetProps {
330
363
  * Requires `merchantId`, `supabaseFunctionBaseUrl`, and an authenticated checkout session.
331
364
  */
332
365
  enableServiceabilityCheck?: boolean;
366
+ /**
367
+ * Score address-discrepancy-led RTO risk after address completion.
368
+ * Requires `merchantId`, `supabaseFunctionBaseUrl`, and phone/email auth or `codSessionToken`.
369
+ */
370
+ enableAddressIntelligence?: boolean;
333
371
  /**
334
372
  * Opt-in fallback banner for India Post "Non Delivery" pincodes.
335
373
  * Defaults off because courier partners may still deliver.
@@ -467,6 +505,7 @@ export interface PaymentStepProps {
467
505
  amountPaise: number;
468
506
  enableCod?: boolean;
469
507
  codAllowed?: boolean;
508
+ addressRisk?: AddressRiskScore | null;
470
509
  theme?: 'light' | 'dark';
471
510
  onComplete: (result: {
472
511
  paymentMethod: string;
package/src/index.ts CHANGED
@@ -74,6 +74,7 @@ export {
74
74
  selectAddress,
75
75
  verifyDigipin,
76
76
  checkCodEligibility,
77
+ scoreAddressRisk,
77
78
  checkServiceability,
78
79
  notifyAddressCompleted,
79
80
  logFunnelEvent,
@@ -93,6 +94,11 @@ export type {
93
94
  SavedAddressPayload,
94
95
  VerifyDigipinPayload,
95
96
  CodEligibilityResult,
97
+ AddressRiskScore,
98
+ AddressRiskPayload,
99
+ AddressRiskLevel,
100
+ AddressIntervention,
101
+ AddressConfidenceState,
96
102
  ServiceabilityResult,
97
103
  SessionContextPayload,
98
104
  FunnelEventPayload,
@@ -118,6 +124,19 @@ export { useDigiPin } from './hooks/useDigiPin';
118
124
  export { captureUtmFromUrl, hasUtmParams } from './core/utm';
119
125
  export type { UtmParams } from './core/utm';
120
126
  export { getWebDeviceContext, detectDeviceType, detectPlatform } from './core/device';
127
+ export type {
128
+ MapRuntime,
129
+ MapEmbedMode,
130
+ MapLibreMap,
131
+ MapLibreMarker,
132
+ MapMouseEvent,
133
+ } from './core/map-runtime';
134
+ export {
135
+ DEFAULT_MAP_STYLE_URL,
136
+ OPENFREEMAP_POSITRON_STYLE_URL,
137
+ getExternalMapRuntime,
138
+ waitForExternalMapRuntime,
139
+ } from './core/map-runtime';
121
140
  export type {
122
141
  CheckoutWidgetProps,
123
142
  CheckoutMobilePresentation,
@@ -101,6 +101,28 @@
101
101
  display: none;
102
102
  }
103
103
 
104
+ .qr-risk-banner {
105
+ display: grid;
106
+ gap: 4px;
107
+ margin: 12px 0;
108
+ padding: 10px 12px;
109
+ border: 1px solid color-mix(in srgb, var(--qr-warning) 40%, var(--qr-border));
110
+ border-radius: var(--qr-radius);
111
+ background: color-mix(in srgb, var(--qr-warning) 11%, var(--qr-bg));
112
+ color: var(--qr-text);
113
+ font-size: 12px;
114
+ line-height: 1.45;
115
+ }
116
+
117
+ .qr-risk-banner strong {
118
+ font-size: 13px;
119
+ }
120
+
121
+ .qr-risk-banner--high {
122
+ border-color: color-mix(in srgb, var(--qr-error) 45%, var(--qr-border));
123
+ background: color-mix(in srgb, var(--qr-error) 10%, var(--qr-bg));
124
+ }
125
+
104
126
  .qr-header__title {
105
127
  font-size: 15px;
106
128
  font-weight: 600;
@@ -411,12 +433,8 @@
411
433
  display: none;
412
434
  }
413
435
  /* When zoom controls are hidden, position locate button at top-right */
414
- .qr-locate-btn {
415
- top: 10px;
416
- right: 10px;
417
- }
418
436
  .qr-geo-error {
419
- top: 52px; /* Below locate button when zoom controls are hidden (10px + 34px + 8px gap) */
437
+ top: 47px; /* Below locate button when zoom controls are hidden (10px + 29px + 8px gap) */
420
438
  }
421
439
  }
422
440
 
@@ -565,28 +583,35 @@
565
583
 
566
584
  /* ── Locate-me button ────────────────────────────────────── */
567
585
  .qr-locate-btn {
586
+ /* Match MapLibre NavigationControl: 29×29px buttons, 10px inset, 58px nav stack */
587
+ --qr-map-ctrl-inset: 10px;
588
+ --qr-map-ctrl-size: 29px;
589
+ --qr-map-nav-height: 58px;
590
+ --qr-map-ctrl-gap: 4px;
591
+
568
592
  position: absolute;
569
- top: 72px; /* Positioned below MapLibre's NavigationControl (zoom buttons: ~30px each + gap) */
570
- right: 12px; /* Align with MapLibre controls (they use 10px right margin) */
593
+ top: calc(var(--qr-map-ctrl-inset) + var(--qr-map-nav-height) + var(--qr-map-ctrl-gap));
594
+ right: var(--qr-map-ctrl-inset);
571
595
  z-index: 10;
572
- width: 24px; /* Match MapLibre's control button width */
573
- height: 24px; /* Match MapLibre's control button height */
574
- border-radius: 4px; /* Match MapLibre's control button border radius */
596
+ width: var(--qr-map-ctrl-size);
597
+ height: var(--qr-map-ctrl-size);
598
+ box-sizing: border-box;
599
+ padding: 0;
600
+ border-radius: 4px;
575
601
  background: var(--qr-bg);
576
- border: 1px solid var(--qr-border);
602
+ border: 0;
577
603
  color: var(--qr-text);
578
604
  cursor: pointer;
579
605
  display: flex;
580
606
  align-items: center;
581
607
  justify-content: center;
582
- box-shadow: 0 0 0 1px rgba(0,0,0,.1), 0 1px 2px rgba(0,0,0,.1);
583
- transition: background var(--qr-transition), border-color var(--qr-transition), transform 80ms;
608
+ box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.1);
609
+ transition: background var(--qr-transition), box-shadow var(--qr-transition), transform 80ms;
584
610
  touch-action: manipulation;
585
611
  }
586
612
 
587
613
  .qr-locate-btn:hover:not(:disabled) {
588
614
  background: var(--qr-primary-light);
589
- border-color: var(--qr-primary);
590
615
  color: var(--qr-primary);
591
616
  }
592
617
 
@@ -616,20 +641,23 @@
616
641
  .qr-locate-btn__label {
617
642
  display: none;
618
643
  }
619
- .qr-locate-btn {
620
- width: 34px;
621
- padding: 0;
622
- }
623
644
  }
624
645
 
625
646
  .qr-locate-btn--loading {
626
647
  cursor: wait;
627
648
  }
628
649
 
650
+ /* When MapLibre nav is hidden (≤380px), sit locate at the top-right inset */
651
+ @media (max-width: 380px) {
652
+ .qr-locate-btn {
653
+ top: var(--qr-map-ctrl-inset);
654
+ }
655
+ }
656
+
629
657
  /* ── Geo error toast ─────────────────────────────────────── */
630
658
  .qr-geo-error {
631
659
  position: absolute;
632
- top: 132px; /* Positioned below locate button (72px + 34px + 8px gap) */
660
+ top: 109px; /* Below locate button (72px + 29px + 8px gap) */
633
661
  right: 10px;
634
662
  left: 10px;
635
663
  z-index: 20;
@@ -2441,15 +2469,6 @@
2441
2469
  border-radius: 999px;
2442
2470
  }
2443
2471
 
2444
- .qr-locate-btn {
2445
- top: auto;
2446
- right: 14px;
2447
- bottom: 14px;
2448
- width: 42px;
2449
- height: 42px;
2450
- border-radius: 14px;
2451
- }
2452
-
2453
2472
  .qr-map-actions,
2454
2473
  .qr-form-actions {
2455
2474
  position: sticky;