@quantaroute/checkout 1.8.0 → 1.8.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.
@@ -29,6 +29,7 @@ import EmailOtpStep from './EmailOtpStep';
29
29
  import { getWebDeviceContext } from '../core/device';
30
30
  import { captureUtmFromUrl } from '../core/utm';
31
31
  import '../styles/checkout.css';
32
+ import { DEFAULT_CHECKOUT_FUNCTIONS_URL } from '../core/map-runtime';
32
33
 
33
34
  // ─── Types ────────────────────────────────────────────────────────────────────
34
35
 
@@ -218,7 +219,7 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
218
219
  mapsKey,
219
220
  enablePhoneAuth = false,
220
221
  merchantId = '',
221
- supabaseFunctionBaseUrl = '',
222
+ supabaseFunctionBaseUrl = DEFAULT_CHECKOUT_FUNCTIONS_URL,
222
223
  brandColor,
223
224
  logoUrl,
224
225
  headerBanner,
@@ -445,8 +446,10 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
445
446
  try {
446
447
  await selectAddress(checkoutConfig, auth.sessionToken, saved.id);
447
448
  } catch (err: unknown) {
448
- onError?.(err instanceof Error ? err : new Error('Failed to select address.'));
449
- return;
449
+ const error = err instanceof Error ? err : new Error('Failed to select address.');
450
+ onError?.(error);
451
+ // Rethrow so the saved-address step shows the error and re-enables the button.
452
+ throw error;
450
453
  }
451
454
 
452
455
  if (!saved.digipin) {
@@ -980,7 +983,7 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
980
983
  mapStyle={mapStyle}
981
984
  mapTheme={mapTheme}
982
985
  embedMode={embedMode}
983
- mapsKey={mapsKey}
986
+ mapsKey={mapsKey ?? apiKey}
984
987
  />
985
988
  </>
986
989
  )}
@@ -1001,7 +1004,7 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
1001
1004
  mapStyle={mapStyle}
1002
1005
  mapTheme={mapTheme}
1003
1006
  embedMode={embedMode}
1004
- mapsKey={mapsKey}
1007
+ mapsKey={mapsKey ?? apiKey}
1005
1008
  />
1006
1009
  )}
1007
1010
 
@@ -16,7 +16,7 @@ import { getDigiPin, getLatLngFromDigiPin, formatDigiPin, isWithinIndia } from '
16
16
  import { autocompleteAddress, looksLikeDigiPin, couldBeDigiPinInput } from '../core/api';
17
17
  import type { AutocompleteSuggestion } from '../core/api';
18
18
  import type { MapPinSelectorProps } from '../core/types';
19
- import { QUANTAROUTE_MAP_STYLE_URL, withMapsKey } from '../core/map-runtime';
19
+ import { CARTO_POSITRON_STYLE_URL, QUANTAROUTE_MAP_STYLE_URL, withMapsKey } from '../core/map-runtime';
20
20
  import { styles, COLORS } from '../styles/checkout.native';
21
21
 
22
22
  // ─── Constants ────────────────────────────────────────────────────────────────
@@ -59,7 +59,8 @@ function computeDigiPinSafe(lat: number, lng: number): string | null {
59
59
 
60
60
  /**
61
61
  * Native (iOS/Android) map pin selector.
62
- * Uses expo-osm-sdk's OSMView with a draggable marker over Carto Positron tiles.
62
+ * Uses expo-osm-sdk's OSMView with a draggable marker over the QuantaRoute basemap
63
+ * (Carto Positron only when no maps key is given).
63
64
  * Metro resolves this file on native; MapPinSelector.tsx is used on web.
64
65
  */
65
66
  const MapPinSelector: React.FC<MapPinSelectorProps> = ({
@@ -323,7 +324,11 @@ const MapPinSelector: React.FC<MapPinSelectorProps> = ({
323
324
  style={{ flex: 1 }}
324
325
  initialCenter={{ latitude: initLat, longitude: initLng }}
325
326
  initialZoom={hasDefault ? STREET_ZOOM : OVERVIEW_ZOOM}
326
- styleUrl={withMapsKey(QUANTAROUTE_MAP_STYLE_URL, mapsKey)}
327
+ styleUrl={
328
+ mapsKey
329
+ ? withMapsKey(QUANTAROUTE_MAP_STYLE_URL, mapsKey)
330
+ : CARTO_POSITRON_STYLE_URL
331
+ }
327
332
  markers={pinMarkers}
328
333
  showUserLocation={false}
329
334
  scrollEnabled
@@ -1,4 +1,4 @@
1
- import React, { useState, useEffect, useCallback } from 'react';
1
+ import React, { useState, useEffect, useCallback, useRef } from 'react';
2
2
  import { listAddresses, deleteAddress, setDefaultAddress } from '../core/checkout-api';
3
3
  import type { SavedAddress } from '../core/checkout-api';
4
4
  import type { SavedAddressStepProps } from '../core/types';
@@ -46,9 +46,13 @@ interface AddressCardProps {
46
46
  onDelete: () => void;
47
47
  onSetDefault: () => void;
48
48
  deleting: boolean;
49
+ /** This card's "Deliver here" is in progress. */
50
+ selecting: boolean;
51
+ /** Another card is being selected: block every action. */
52
+ locked: boolean;
49
53
  }
50
54
 
51
- function AddressCard({ address, onUse, onDelete, onSetDefault, deleting }: AddressCardProps) {
55
+ function AddressCard({ address, onUse, onDelete, onSetDefault, deleting, selecting, locked }: AddressCardProps) {
52
56
  const parts = [
53
57
  address.flat_number,
54
58
  address.building_name,
@@ -82,6 +86,7 @@ function AddressCard({ address, onUse, onDelete, onSetDefault, deleting }: Addre
82
86
  className="qr-icon-btn"
83
87
  title="Set as default"
84
88
  onClick={onSetDefault}
89
+ disabled={locked}
85
90
  aria-label="Set as default address"
86
91
  >
87
92
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
@@ -94,7 +99,7 @@ function AddressCard({ address, onUse, onDelete, onSetDefault, deleting }: Addre
94
99
  className="qr-icon-btn qr-icon-btn--danger"
95
100
  title="Delete address"
96
101
  onClick={onDelete}
97
- disabled={deleting}
102
+ disabled={deleting || locked}
98
103
  aria-label="Delete address"
99
104
  >
100
105
  {deleting ? (
@@ -145,8 +150,15 @@ function AddressCard({ address, onUse, onDelete, onSetDefault, deleting }: Addre
145
150
  type="button"
146
151
  className="qr-btn qr-btn--primary qr-btn--full qr-btn--sm"
147
152
  onClick={onUse}
153
+ disabled={locked}
154
+ aria-busy={selecting}
148
155
  >
149
- Deliver here
156
+ {selecting ? (
157
+ <>
158
+ <span className="qr-spinner qr-spinner--sm" aria-hidden="true" />
159
+ Confirming…
160
+ </>
161
+ ) : 'Deliver here'}
150
162
  </button>
151
163
  </div>
152
164
  );
@@ -165,6 +177,9 @@ const SavedAddressStep: React.FC<SavedAddressStepProps> = ({
165
177
  const [loadingList, setLoadingList] = useState(true);
166
178
  const [listError, setListError] = useState<string | null>(null);
167
179
  const [deletingId, setDeletingId] = useState<string | null>(null);
180
+ const [selectingId, setSelectingId] = useState<string | null>(null);
181
+ // A ref, not state, so a second click in the same frame is still ignored.
182
+ const selectingRef = useRef(false);
168
183
 
169
184
  const config = { functionBaseUrl, merchantId };
170
185
 
@@ -216,6 +231,22 @@ const SavedAddressStep: React.FC<SavedAddressStepProps> = ({
216
231
  // eslint-disable-next-line react-hooks/exhaustive-deps
217
232
  }, [sessionToken]);
218
233
 
234
+ const handleUse = useCallback(async (address: SavedAddress) => {
235
+ if (selectingRef.current) return;
236
+ selectingRef.current = true;
237
+ setSelectingId(address.id);
238
+ setListError(null);
239
+ try {
240
+ await onSelectAddress(address);
241
+ // On success the widget moves to the next step and this one unmounts;
242
+ // keep the spinner until then.
243
+ } catch (err: unknown) {
244
+ setListError(err instanceof Error ? err.message : 'Could not use this address. Please try again.');
245
+ selectingRef.current = false;
246
+ setSelectingId(null);
247
+ }
248
+ }, [onSelectAddress]);
249
+
219
250
  // ── Loading ──────────────────────────────────────────────────────────────────
220
251
  if (loadingList) {
221
252
  return (
@@ -266,10 +297,12 @@ const SavedAddressStep: React.FC<SavedAddressStepProps> = ({
266
297
  <AddressCard
267
298
  key={addr.id}
268
299
  address={addr}
269
- onUse={() => onSelectAddress(addr)}
300
+ onUse={() => { void handleUse(addr); }}
270
301
  onDelete={() => handleDelete(addr.id)}
271
302
  onSetDefault={() => handleSetDefault(addr.id)}
272
303
  deleting={deletingId === addr.id}
304
+ selecting={selectingId === addr.id}
305
+ locked={selectingId !== null}
273
306
  />
274
307
  ))}
275
308
  </div>
@@ -278,6 +311,7 @@ const SavedAddressStep: React.FC<SavedAddressStepProps> = ({
278
311
  type="button"
279
312
  className="qr-btn qr-btn--ghost qr-btn--full"
280
313
  onClick={onAddNew}
314
+ disabled={selectingId !== null}
281
315
  >
282
316
  <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
283
317
  <path d="M12 5v14M5 12h14" />
@@ -193,3 +193,7 @@ export function waitForExternalMapRuntime(
193
193
  if (retryTimer !== null) window.clearTimeout(retryTimer);
194
194
  };
195
195
  }
196
+
197
+ /** Hosted QuantaRoute checkout functions. Every merchant uses these; override only for testing. */
198
+ export const DEFAULT_CHECKOUT_FUNCTIONS_URL =
199
+ 'https://ikfiewesidedxozotmrl.supabase.co/functions/v1';
package/src/core/types.ts CHANGED
@@ -519,7 +519,8 @@ export interface SavedAddressStepProps {
519
519
  sessionToken: string;
520
520
  functionBaseUrl: string;
521
521
  merchantId: string;
522
- onSelectAddress: (address: import('./checkout-api').SavedAddress) => void;
522
+ /** May return a promise; the step shows a spinner until it settles and an error if it rejects. */
523
+ onSelectAddress: (address: import('./checkout-api').SavedAddress) => void | Promise<void>;
523
524
  onAddNew: () => void;
524
525
  }
525
526
 
@@ -101,7 +101,6 @@ const truthy = (value: string | undefined) =>
101
101
  *
102
102
  * <script src=".../quantaroute-checkout.js"
103
103
  * data-merchant-id="…" data-api-key="dp_…" data-maps-key="dp_…"
104
- * data-functions-url="https://….supabase.co/functions/v1"
105
104
  * data-trigger="#checkout-button" data-redirect-url="https://shop/pay?sid={sessionId}">
106
105
  * </script>
107
106
  *
@@ -10,7 +10,6 @@
10
10
  *
11
11
  * <script src="https://cdn.jsdelivr.net/npm/@quantaroute/checkout@1/dist/embed/quantaroute-checkout.js"
12
12
  * data-merchant-id="…" data-api-key="dp_…" data-maps-key="dp_…"
13
- * data-functions-url="https://….supabase.co/functions/v1"
14
13
  * data-trigger="#checkout-button"
15
14
  * data-redirect-url="https://yourshop.com/pay?session={sessionId}">
16
15
  * </script>
@@ -26,6 +25,7 @@ import {
26
25
  readScriptConfig,
27
26
  type HandoffPayload,
28
27
  } from './handoff';
28
+ import { DEFAULT_CHECKOUT_FUNCTIONS_URL } from '../core/map-runtime';
29
29
 
30
30
  export type { HandoffPayload } from './handoff';
31
31
 
@@ -36,8 +36,8 @@ export interface EmbedOptions {
36
36
  apiKey: string;
37
37
  /** Public dp_ key with the Maps scope (usually the same key). */
38
38
  mapsKey?: string;
39
- /** Base URL of the checkout functions, e.g. https://xyz.supabase.co/functions/v1 */
40
- functionsUrl: string;
39
+ /** Optional override of the hosted checkout functions URL (testing only). */
40
+ functionsUrl?: string;
41
41
  /** CSS selector(s) of the merchant's Checkout button(s). Clicks open the checkout. */
42
42
  triggers?: string | string[];
43
43
  /** Where to send the shopper afterwards. Supports {sessionId}, {pincode}, {digipin}, … */
@@ -163,9 +163,9 @@ function toPayload(address: CompleteAddress, sessionId: string): HandoffPayload
163
163
  }
164
164
 
165
165
  function init(options: EmbedOptions): EmbedController {
166
- if (!options?.merchantId || !options?.apiKey || !options?.functionsUrl) {
166
+ if (!options?.merchantId || !options?.apiKey) {
167
167
  console.warn(
168
- '[QuantaRouteCheckout] merchantId, apiKey and functionsUrl are required (data-merchant-id, data-api-key, data-functions-url).'
168
+ '[QuantaRouteCheckout] merchantId and apiKey are required (data-merchant-id, data-api-key).'
169
169
  );
170
170
  }
171
171
 
@@ -210,7 +210,7 @@ function init(options: EmbedOptions): EmbedController {
210
210
  key={runKey}
211
211
  apiKey={options.apiKey}
212
212
  merchantId={options.merchantId}
213
- supabaseFunctionBaseUrl={options.functionsUrl}
213
+ supabaseFunctionBaseUrl={options.functionsUrl || DEFAULT_CHECKOUT_FUNCTIONS_URL}
214
214
  mapsKey={options.mapsKey ?? options.apiKey}
215
215
  embedMode="external"
216
216
  enableEmailAuth={options.authMode !== 'phone' && options.authMode !== 'none'}
@@ -1,86 +0,0 @@
1
- import { describe, it } from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { buildRedirectUrl, parseSelectors, readScriptConfig } from './handoff.ts';
4
-
5
- describe('buildRedirectUrl', () => {
6
- it('fills single and double brace placeholders and encodes values', () => {
7
- const url = buildRedirectUrl(
8
- 'https://shop.example/pay?sid={sessionId}&pin={{pincode}}&addr={formattedAddress}',
9
- { sessionId: 'abc-123', pincode: '560099', formattedAddress: '4B, MG Road & Co' }
10
- );
11
- assert.equal(
12
- url,
13
- 'https://shop.example/pay?sid=abc-123&pin=560099&addr=4B%2C%20MG%20Road%20%26%20Co'
14
- );
15
- });
16
-
17
- it('handles numbers and leaves unknown or missing placeholders empty', () => {
18
- const url = buildRedirectUrl('https://x.test/?lat={lat}&lng={lng}&u={unknown}&s={sessionId}', {
19
- lat: 12.9716,
20
- lng: 77.5946,
21
- });
22
- assert.equal(url, 'https://x.test/?lat=12.9716&lng=77.5946&u=&s=');
23
- });
24
-
25
- it('leaves a template without placeholders alone', () => {
26
- assert.equal(buildRedirectUrl('https://x.test/pay', { sessionId: 'a' }), 'https://x.test/pay');
27
- });
28
- });
29
-
30
- describe('parseSelectors', () => {
31
- it('splits on top-level commas and trims', () => {
32
- assert.deepEqual(parseSelectors('#a, .b ,button[name="checkout"]'), [
33
- '#a',
34
- '.b',
35
- 'button[name="checkout"]',
36
- ]);
37
- });
38
-
39
- it('keeps commas inside brackets, parentheses and quotes', () => {
40
- assert.deepEqual(parseSelectors('a[href*="x,y"], :is(.a, .b)'), [
41
- 'a[href*="x,y"]',
42
- ':is(.a, .b)',
43
- ]);
44
- });
45
-
46
- it('accepts arrays and empty input', () => {
47
- assert.deepEqual(parseSelectors([' #a ', '', '.b']), ['#a', '.b']);
48
- assert.deepEqual(parseSelectors(undefined), []);
49
- assert.deepEqual(parseSelectors(''), []);
50
- });
51
- });
52
-
53
- describe('readScriptConfig', () => {
54
- it('reads data attributes and auto-inits when merchant id and key are present', () => {
55
- const config = readScriptConfig({
56
- merchantId: 'm1',
57
- apiKey: 'dp_key',
58
- mapsKey: 'dp_key',
59
- functionsUrl: 'https://f.test/functions/v1',
60
- trigger: '#checkout, .go',
61
- redirectUrl: 'https://shop/pay?sid={sessionId}',
62
- theme: 'dark',
63
- auth: 'phone',
64
- });
65
- assert.equal(config.autoInit, true);
66
- assert.deepEqual(config.triggers, ['#checkout', '.go']);
67
- assert.equal(config.theme, 'dark');
68
- assert.equal(config.authMode, 'phone');
69
- assert.equal(config.functionsUrl, 'https://f.test/functions/v1');
70
- });
71
-
72
- it('does not auto-init without credentials or when switched off', () => {
73
- assert.equal(readScriptConfig({}).autoInit, false);
74
- assert.equal(readScriptConfig({ merchantId: 'm1' }).autoInit, false);
75
- assert.equal(
76
- readScriptConfig({ merchantId: 'm1', apiKey: 'k', autoInit: 'false' }).autoInit,
77
- false
78
- );
79
- });
80
-
81
- it('ignores unknown theme and auth values', () => {
82
- const config = readScriptConfig({ merchantId: 'm', apiKey: 'k', theme: 'neon', auth: 'sms' });
83
- assert.equal(config.theme, undefined);
84
- assert.equal(config.authMode, undefined);
85
- });
86
- });