@quantaroute/checkout 1.3.2 → 1.4.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.
@@ -0,0 +1,281 @@
1
+ import React, { useState, useEffect, useCallback } from 'react';
2
+ import { listAddresses, deleteAddress, setDefaultAddress } from '../core/checkout-api';
3
+ import type { SavedAddress } from '../core/checkout-api';
4
+ import type { SavedAddressStepProps } from '../core/types';
5
+
6
+ // ─── Label icons ──────────────────────────────────────────────────────────────
7
+
8
+ const HomeIcon = () => (
9
+ <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
10
+ <path d="M3 9.5L12 3l9 6.5V20a1 1 0 01-1 1H4a1 1 0 01-1-1V9.5z" />
11
+ <path d="M9 21V12h6v9" />
12
+ </svg>
13
+ );
14
+
15
+ const WorkIcon = () => (
16
+ <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
17
+ <rect x="2" y="7" width="20" height="14" rx="2" />
18
+ <path d="M16 7V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v2" />
19
+ </svg>
20
+ );
21
+
22
+ const PinIcon = () => (
23
+ <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
24
+ <path d="M12 2C8.134 2 5 5.134 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.866-3.134-7-7-7z" />
25
+ <circle cx="12" cy="9" r="2.5" />
26
+ </svg>
27
+ );
28
+
29
+ function LabelIcon({ label }: { label: string }) {
30
+ if (label === 'home') return <HomeIcon />;
31
+ if (label === 'work') return <WorkIcon />;
32
+ return <PinIcon />;
33
+ }
34
+
35
+ // ─── Address card ─────────────────────────────────────────────────────────────
36
+
37
+ interface AddressCardProps {
38
+ address: SavedAddress;
39
+ onUse: () => void;
40
+ onDelete: () => void;
41
+ onSetDefault: () => void;
42
+ deleting: boolean;
43
+ }
44
+
45
+ function AddressCard({ address, onUse, onDelete, onSetDefault, deleting }: AddressCardProps) {
46
+ const parts = [
47
+ address.flat_number,
48
+ address.building_name,
49
+ address.street_name,
50
+ address.locality,
51
+ address.district,
52
+ address.state,
53
+ address.pincode,
54
+ ].filter(Boolean);
55
+ const line1 = [address.flat_number, address.building_name, address.street_name].filter(Boolean).join(', ');
56
+ const line2 = [address.locality, address.district].filter(Boolean).join(', ');
57
+ const line3 = [address.state, address.pincode].filter(Boolean).join(' – ');
58
+ const summary = parts.length > 0 ? undefined : address.locality || address.district || address.state;
59
+
60
+ return (
61
+ <div className={`qr-addr-card${address.is_default ? ' qr-addr-card--default' : ''}`}>
62
+ <div className="qr-addr-card__header">
63
+ <div className="qr-addr-card__label-icon">
64
+ <LabelIcon label={address.label} />
65
+ </div>
66
+ <span className="qr-addr-card__label">
67
+ {address.label.charAt(0).toUpperCase() + address.label.slice(1)}
68
+ </span>
69
+ {address.is_default && (
70
+ <span className="qr-addr-card__default-badge">Default</span>
71
+ )}
72
+ <div className="qr-addr-card__actions">
73
+ {!address.is_default && (
74
+ <button
75
+ type="button"
76
+ className="qr-icon-btn"
77
+ title="Set as default"
78
+ onClick={onSetDefault}
79
+ aria-label="Set as default address"
80
+ >
81
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
82
+ <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
83
+ </svg>
84
+ </button>
85
+ )}
86
+ <button
87
+ type="button"
88
+ className="qr-icon-btn qr-icon-btn--danger"
89
+ title="Delete address"
90
+ onClick={onDelete}
91
+ disabled={deleting}
92
+ aria-label="Delete address"
93
+ >
94
+ {deleting ? (
95
+ <span className="qr-spinner qr-spinner--xs" aria-hidden="true" />
96
+ ) : (
97
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
98
+ <polyline points="3 6 5 6 21 6" />
99
+ <path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6" />
100
+ <path d="M10 11v6M14 11v6" />
101
+ <path d="M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2" />
102
+ </svg>
103
+ )}
104
+ </button>
105
+ </div>
106
+ </div>
107
+
108
+ <div className="qr-addr-card__body">
109
+ {summary ? (
110
+ <p className="qr-addr-card__line">{summary}</p>
111
+ ) : (
112
+ <>
113
+ {line1 && <p className="qr-addr-card__line">{line1}</p>}
114
+ {line2 && <p className="qr-addr-card__line qr-addr-card__line--muted">{line2}</p>}
115
+ {line3 && <p className="qr-addr-card__line qr-addr-card__line--muted">{line3}</p>}
116
+ </>
117
+ )}
118
+ <div className="qr-addr-card__meta">
119
+ <span className="qr-digipin-badge qr-digipin-badge--inline qr-digipin-badge--sm">
120
+ <span className="qr-digipin-badge__label">DigiPin</span>
121
+ <span className="qr-digipin-badge__code">{address.digipin}</span>
122
+ </span>
123
+ {address.saved_at_brand && (
124
+ <span className="qr-addr-card__brand-chip" title={`First saved at ${address.saved_at_brand}`}>
125
+ <svg viewBox="0 0 12 12" fill="currentColor" aria-hidden="true">
126
+ <path d="M1 1h4.5l5.5 5.5-4.5 4.5L1 5.5V1zm2 1.5a.75.75 0 100 1.5.75.75 0 000-1.5z" />
127
+ </svg>
128
+ {address.saved_at_brand}
129
+ </span>
130
+ )}
131
+ </div>
132
+ </div>
133
+
134
+ <button
135
+ type="button"
136
+ className="qr-btn qr-btn--primary qr-btn--full qr-btn--sm"
137
+ onClick={onUse}
138
+ >
139
+ Deliver here
140
+ </button>
141
+ </div>
142
+ );
143
+ }
144
+
145
+ // ─── Main component ───────────────────────────────────────────────────────────
146
+
147
+ const SavedAddressStep: React.FC<SavedAddressStepProps> = ({
148
+ sessionToken,
149
+ functionBaseUrl,
150
+ merchantId,
151
+ onSelectAddress,
152
+ onAddNew,
153
+ }) => {
154
+ const [addresses, setAddresses] = useState<SavedAddress[]>([]);
155
+ const [loadingList, setLoadingList] = useState(true);
156
+ const [listError, setListError] = useState<string | null>(null);
157
+ const [deletingId, setDeletingId] = useState<string | null>(null);
158
+
159
+ const config = { functionBaseUrl, merchantId };
160
+
161
+ const load = useCallback(async () => {
162
+ setLoadingList(true);
163
+ setListError(null);
164
+ try {
165
+ const list = await listAddresses(config, sessionToken);
166
+ if (list.length === 0) {
167
+ // No saved addresses — go straight to map
168
+ onAddNew();
169
+ return;
170
+ }
171
+ setAddresses(list);
172
+ } catch (err: unknown) {
173
+ setListError(err instanceof Error ? err.message : 'Failed to load addresses.');
174
+ } finally {
175
+ setLoadingList(false);
176
+ }
177
+ // eslint-disable-next-line react-hooks/exhaustive-deps
178
+ }, [sessionToken]);
179
+
180
+ useEffect(() => { load(); }, [load]);
181
+
182
+ const handleDelete = useCallback(async (id: string) => {
183
+ setDeletingId(id);
184
+ try {
185
+ await deleteAddress(config, sessionToken, id);
186
+ setAddresses((prev) => {
187
+ const updated = prev.filter((a) => a.id !== id);
188
+ if (updated.length === 0) { onAddNew(); }
189
+ return updated;
190
+ });
191
+ } catch (err: unknown) {
192
+ setListError(err instanceof Error ? err.message : 'Failed to delete address.');
193
+ } finally {
194
+ setDeletingId(null);
195
+ }
196
+ // eslint-disable-next-line react-hooks/exhaustive-deps
197
+ }, [sessionToken, onAddNew]);
198
+
199
+ const handleSetDefault = useCallback(async (id: string) => {
200
+ try {
201
+ await setDefaultAddress(config, sessionToken, id);
202
+ setAddresses((prev) => prev.map((a) => ({ ...a, is_default: a.id === id })));
203
+ } catch (err: unknown) {
204
+ setListError(err instanceof Error ? err.message : 'Failed to set default.');
205
+ }
206
+ // eslint-disable-next-line react-hooks/exhaustive-deps
207
+ }, [sessionToken]);
208
+
209
+ // ── Loading ──────────────────────────────────────────────────────────────────
210
+ if (loadingList) {
211
+ return (
212
+ <div className="qr-saved-step">
213
+ <div className="qr-saved-step__loading" aria-live="polite">
214
+ <span className="qr-spinner" aria-label="Loading addresses" />
215
+ </div>
216
+ </div>
217
+ );
218
+ }
219
+
220
+ // ── Error ────────────────────────────────────────────────────────────────────
221
+ if (listError && addresses.length === 0) {
222
+ return (
223
+ <div className="qr-saved-step">
224
+ <p className="qr-auth-step__error" role="alert">{listError}</p>
225
+ <button type="button" className="qr-btn qr-btn--ghost qr-btn--full" onClick={load}>
226
+ Retry
227
+ </button>
228
+ <button type="button" className="qr-auth-step__skip" onClick={onAddNew}>
229
+ Enter address manually
230
+ </button>
231
+ </div>
232
+ );
233
+ }
234
+
235
+ return (
236
+ <div className="qr-saved-step">
237
+ <div className="qr-step-header">
238
+ <div className="qr-step-badge qr-step-badge--saved">
239
+ <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
240
+ <path d="M12 2C8.134 2 5 5.134 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.866-3.134-7-7-7z" />
241
+ <circle cx="12" cy="9" r="2.5" />
242
+ </svg>
243
+ </div>
244
+ <div className="qr-step-text">
245
+ <span className="qr-step-title">Saved Addresses</span>
246
+ <span className="qr-step-sub">Pick one or add a new location</span>
247
+ </div>
248
+ </div>
249
+
250
+ {listError && (
251
+ <p className="qr-auth-step__error" role="alert">{listError}</p>
252
+ )}
253
+
254
+ <div className="qr-saved-step__list">
255
+ {addresses.map((addr) => (
256
+ <AddressCard
257
+ key={addr.id}
258
+ address={addr}
259
+ onUse={() => onSelectAddress(addr)}
260
+ onDelete={() => handleDelete(addr.id)}
261
+ onSetDefault={() => handleSetDefault(addr.id)}
262
+ deleting={deletingId === addr.id}
263
+ />
264
+ ))}
265
+ </div>
266
+
267
+ <button
268
+ type="button"
269
+ className="qr-btn qr-btn--ghost qr-btn--full"
270
+ onClick={onAddNew}
271
+ >
272
+ <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
273
+ <path d="M12 5v14M5 12h14" />
274
+ </svg>
275
+ Add new address
276
+ </button>
277
+ </div>
278
+ );
279
+ };
280
+
281
+ export default SavedAddressStep;
package/src/core/api.ts CHANGED
@@ -116,6 +116,92 @@ export async function lookupLocation(
116
116
  return data;
117
117
  }
118
118
 
119
+ // ─── Pincode validation (India Post database) ─────────────────────────────────
120
+
121
+ /** One office row from /v1/pincode/validate/:pincode */
122
+ export interface PincodeOffice {
123
+ office_name: string;
124
+ delivery: string | null;
125
+ district: string | null;
126
+ state: string | null;
127
+ circle: string | null;
128
+ region: string | null;
129
+ division: string | null;
130
+ }
131
+
132
+ export interface PincodeValidateData {
133
+ isValid: boolean;
134
+ pincode: string;
135
+ count: number;
136
+ offices: PincodeOffice[];
137
+ }
138
+
139
+ interface PincodeValidateResponse {
140
+ success: boolean;
141
+ data: PincodeValidateData;
142
+ message?: string;
143
+ }
144
+
145
+ /**
146
+ * Validate a 6-digit Indian pincode against QuantaRoute's postal database.
147
+ * Rejects fake codes (e.g. 123456) that are not in India Post records.
148
+ */
149
+ export async function validatePincode(
150
+ pincode: string,
151
+ apiKey: string,
152
+ baseUrl: string = DEFAULT_BASE_URL
153
+ ): Promise<PincodeValidateData> {
154
+ const cleaned = pincode.replace(/\D/g, '').slice(0, 6);
155
+ if (!/^[1-9][0-9]{5}$/.test(cleaned)) {
156
+ throw new Error('Pincode must be a 6-digit number starting with 1–9.');
157
+ }
158
+
159
+ const url = `${baseUrl.replace(/\/$/, '')}/v1/pincode/validate/${cleaned}`;
160
+ let res: Response;
161
+ try {
162
+ res = await fetch(url, {
163
+ method: 'GET',
164
+ headers: { 'x-api-key': apiKey },
165
+ signal: makeTimeoutSignal(12_000),
166
+ });
167
+ } catch (err) {
168
+ if (err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError')) {
169
+ throw new Error('Pincode validation timed out.');
170
+ }
171
+ throw new Error(`Network error: ${err instanceof Error ? err.message : String(err)}`);
172
+ }
173
+
174
+ if (!res.ok) {
175
+ if (res.status === 401 || res.status === 403) {
176
+ throw new Error('Invalid API key.');
177
+ }
178
+ if (res.status === 429) {
179
+ throw new Error('Rate limit exceeded.');
180
+ }
181
+ let body = '';
182
+ try {
183
+ body = await res.text();
184
+ } catch {
185
+ // ignore
186
+ }
187
+ throw new Error(`Pincode validation failed (${res.status}): ${body || res.statusText}`);
188
+ }
189
+
190
+ const json = (await res.json()) as PincodeValidateResponse;
191
+ if (!json.success || !json.data) {
192
+ throw new Error(json.message ?? 'Pincode validation failed.');
193
+ }
194
+ return json.data;
195
+ }
196
+
197
+ /**
198
+ * Whether this pincode has at least one post office with India Post "Delivery" status
199
+ * (vs "Non Delivery" only — e.g. remote or PO-box-only areas).
200
+ */
201
+ export function pincodeHasDeliveryOffice(offices: PincodeOffice[]): boolean {
202
+ return offices.some((o) => (o.delivery ?? '').trim().toLowerCase() === 'delivery');
203
+ }
204
+
119
205
  // ─── Autocomplete ─────────────────────────────────────────────────────────────
120
206
 
121
207
  /** One address suggestion from /v1/digipin/autocomplete */