@quantaroute/checkout 1.7.0 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,8 +11,10 @@ import {
11
11
  logFunnelEvent,
12
12
  notifySessionAbandoned,
13
13
  fetchSessionOffer,
14
+ scoreAddressRisk,
14
15
  selectAddress,
15
16
  verifyDigipin,
17
+ type AddressRiskScore,
16
18
  type SessionOffer,
17
19
  } from '../core/checkout-api';
18
20
  import type { CheckoutEvent, CheckoutWidgetProps, CompleteAddress } from '../core/types';
@@ -218,6 +220,7 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
218
220
  onCheckoutEvent,
219
221
  enableCod = false,
220
222
  enableServiceabilityCheck = false,
223
+ enableAddressIntelligence = false,
221
224
  showIndiaPostDeliveryWarning = false,
222
225
  serviceabilityBlockCheckout,
223
226
  codCartTotalPaise,
@@ -246,6 +249,7 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
246
249
  const [emailCodeReused, setEmailCodeReused] = useState(false);
247
250
  const [codAllowed, setCodAllowed] = useState(false);
248
251
  const [sessionOffer, setSessionOffer] = useState<SessionOffer | null>(null);
252
+ const [addressRisk, setAddressRisk] = useState<AddressRiskScore | null>(null);
249
253
  const [paymentMethod, setPaymentMethod] = useState<string | null>(null);
250
254
  const [verifyAddress, setVerifyAddress] = useState<SavedAddress | null>(null);
251
255
  const [paymentBackStep, setPaymentBackStep] = useState<Step>('form');
@@ -474,14 +478,9 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
474
478
  address: CompleteAddress,
475
479
  options?: { skipCreate?: boolean; paymentBackStep?: Step }
476
480
  ) => {
477
- setCompletedAddress(address);
481
+ let addressForCompletion: CompleteAddress = address;
482
+ setCompletedAddress(addressForCompletion);
478
483
  setPaymentBackStep(options?.paymentBackStep ?? 'form');
479
- emit({
480
- type: 'address_completed',
481
- step: withPayment ? 'payment' : 'done',
482
- digipin: address.digipin,
483
- buyerId: auth?.buyerId,
484
- });
485
484
 
486
485
  if (auth?.sessionToken) {
487
486
  notifyAddressCompleted(checkoutConfig, auth.sessionToken, {
@@ -494,7 +493,7 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
494
493
 
495
494
  if (!options?.skipCreate && !address.addressId) {
496
495
  try {
497
- await createAddress(checkoutConfig, auth.sessionToken, {
496
+ const saved = await createAddress(checkoutConfig, auth.sessionToken, {
498
497
  digipin: address.digipin,
499
498
  lat: address.lat,
500
499
  lng: address.lng,
@@ -513,22 +512,66 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
513
512
  address.label === 'other' ? (address.labelText?.trim() || null) : null,
514
513
  is_default: false,
515
514
  });
515
+ addressForCompletion = { ...addressForCompletion, addressId: saved.id };
516
+ setCompletedAddress(addressForCompletion);
516
517
  } catch {
517
518
  // Silent
518
519
  }
519
520
  }
520
521
  }
521
522
 
523
+ if (enableAddressIntelligence && merchantId && supabaseFunctionBaseUrl && codSession) {
524
+ try {
525
+ const risk = await scoreAddressRisk(checkoutConfig, codSession, {
526
+ address_id: addressForCompletion.addressId,
527
+ digipin: addressForCompletion.digipin,
528
+ lat: addressForCompletion.lat,
529
+ lng: addressForCompletion.lng,
530
+ state: addressForCompletion.state,
531
+ district: addressForCompletion.district,
532
+ locality: addressForCompletion.locality,
533
+ pincode: addressForCompletion.pincode,
534
+ delivery_status: addressForCompletion.delivery,
535
+ flat_number: addressForCompletion.flatNumber,
536
+ floor_number: addressForCompletion.floorNumber,
537
+ building_name: addressForCompletion.buildingName,
538
+ street_name: addressForCompletion.streetName,
539
+ });
540
+ setAddressRisk(risk);
541
+ addressForCompletion = { ...addressForCompletion, addressRisk: risk };
542
+ setCompletedAddress(addressForCompletion);
543
+ emit({
544
+ type: 'address_risk_scored',
545
+ step: withPayment ? 'payment' : 'done',
546
+ digipin: addressForCompletion.digipin,
547
+ buyerId: auth?.buyerId,
548
+ addressRiskLevel: risk.level,
549
+ addressRiskScore: risk.score,
550
+ });
551
+ } catch {
552
+ setAddressRisk(null);
553
+ }
554
+ } else {
555
+ setAddressRisk(null);
556
+ }
557
+
558
+ emit({
559
+ type: 'address_completed',
560
+ step: withPayment ? 'payment' : 'done',
561
+ digipin: addressForCompletion.digipin,
562
+ buyerId: auth?.buyerId,
563
+ });
564
+
522
565
  if (withPayment && codSession) {
523
566
  setStep('payment');
524
567
  } else if (withPayment && !codSession) {
525
568
  onError?.(new Error('enablePayment requires phone/email auth or a codSessionToken prop.'));
526
569
  setStep('done');
527
- onComplete(address);
570
+ onComplete(addressForCompletion);
528
571
  return;
529
572
  } else {
530
573
  setStep('done');
531
- onComplete(address);
574
+ onComplete(addressForCompletion);
532
575
  }
533
576
  };
534
577
 
@@ -632,6 +675,7 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
632
675
  setStep(initialStep);
633
676
  setConfirmedLocation(null);
634
677
  setCompletedAddress(null);
678
+ setAddressRisk(null);
635
679
  setVerifyAddress(null);
636
680
  };
637
681
 
@@ -962,7 +1006,8 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
962
1006
  sessionId={auth?.sessionId}
963
1007
  amountPaise={paymentAmountPaise}
964
1008
  enableCod={enableCod}
965
- codAllowed={codAllowed}
1009
+ codAllowed={codAllowed && !addressRisk?.interventions.includes('hide_cod')}
1010
+ addressRisk={addressRisk}
966
1011
  theme={theme}
967
1012
  onComplete={handlePaymentComplete}
968
1013
  onBack={handleBack}
@@ -286,6 +286,15 @@ const MapPinSelector: React.FC<MapPinSelectorProps> = ({
286
286
  map.on('load', () => {
287
287
  setMapLoaded(true);
288
288
 
289
+ // MapLibre compact attribution starts expanded; collapse to icon-only.
290
+ const attribEl = containerRef.current?.querySelector(
291
+ '.maplibregl-ctrl-attrib.maplibregl-compact'
292
+ );
293
+ if (attribEl instanceof HTMLElement) {
294
+ attribEl.classList.remove('maplibregl-compact-show');
295
+ attribEl.setAttribute('open', '');
296
+ }
297
+
289
298
  // ── India boundary overlay (legal compliance) ────────────────────────
290
299
  // Resolves instantly if the fetch finished before map loaded (typical),
291
300
  // or waits the remaining milliseconds if still in-flight.
@@ -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.
package/src/core/types.ts CHANGED
@@ -1,6 +1,11 @@
1
1
  import type { ReactNode } from 'react';
2
2
  import type { UtmParams } from './utm';
3
- import type { CheckoutApiConfig, ServiceabilityResult, SessionContextPayload } from './checkout-api';
3
+ import type {
4
+ AddressRiskScore,
5
+ CheckoutApiConfig,
6
+ ServiceabilityResult,
7
+ SessionContextPayload,
8
+ } from './checkout-api';
4
9
 
5
10
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
6
11
  type AnyStyle = any; // CSSProperties on web · StyleProp<ViewStyle> on native
@@ -95,6 +100,8 @@ export interface CompleteAddress {
95
100
  labelText?: string;
96
101
  /** Set when the buyer re-selected an existing saved row (skip createAddress). */
97
102
  addressId?: string;
103
+ /** Explainable checkout-time address discrepancy risk, when enabled. */
104
+ addressRisk?: AddressRiskScore;
98
105
  }
99
106
 
100
107
  /** Imperative hooks for host pages (e.g. Shopify pre-checkout shell). */
@@ -133,6 +140,7 @@ export type CheckoutEventType =
133
140
  | 'location_confirmed'
134
141
  | 'form_step_viewed'
135
142
  | 'address_completed'
143
+ | 'address_risk_scored'
136
144
  | 'widget_reset'
137
145
  | 'payment_step_viewed'
138
146
  | 'payment_method_selected'
@@ -167,6 +175,10 @@ export interface CheckoutEvent {
167
175
  experimentVariant?: string;
168
176
  /** DigiPin of the confirmed location. Available after `location_confirmed` and `address_completed`. */
169
177
  digipin?: string;
178
+ /** Address risk level when `address_risk_scored` fires. */
179
+ addressRiskLevel?: AddressRiskScore['level'];
180
+ /** Address risk score (0-100) when address intelligence is enabled. */
181
+ addressRiskScore?: number;
170
182
  /** ISO timestamp of when the event fired. */
171
183
  timestamp: string;
172
184
  }
@@ -330,6 +342,11 @@ export interface CheckoutWidgetProps {
330
342
  * Requires `merchantId`, `supabaseFunctionBaseUrl`, and an authenticated checkout session.
331
343
  */
332
344
  enableServiceabilityCheck?: boolean;
345
+ /**
346
+ * Score address-discrepancy-led RTO risk after address completion.
347
+ * Requires `merchantId`, `supabaseFunctionBaseUrl`, and phone/email auth or `codSessionToken`.
348
+ */
349
+ enableAddressIntelligence?: boolean;
333
350
  /**
334
351
  * Opt-in fallback banner for India Post "Non Delivery" pincodes.
335
352
  * Defaults off because courier partners may still deliver.
@@ -467,6 +484,7 @@ export interface PaymentStepProps {
467
484
  amountPaise: number;
468
485
  enableCod?: boolean;
469
486
  codAllowed?: boolean;
487
+ addressRisk?: AddressRiskScore | null;
470
488
  theme?: 'light' | 'dark';
471
489
  onComplete: (result: {
472
490
  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,
@@ -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;