@quantaroute/checkout 1.4.0 → 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.
- package/CHANGELOG.md +91 -0
- package/README.md +67 -49
- package/dist/lib/index.d.ts +12 -3
- package/dist/lib/quantaroute-checkout.es.js +44 -42
- package/dist/lib/quantaroute-checkout.umd.js +34 -32
- package/package.json +2 -1
- package/src/components/CheckoutWidget.tsx +4 -1
- package/src/components/EmailOtpStep.tsx +4 -1
- package/src/components/EmailStep.tsx +2 -2
- package/src/core/checkout-api.ts +7 -1
- package/src/core/types.ts +4 -2
- package/src/index.ts +1 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `@quantaroute/checkout` are documented here.
|
|
4
|
+
|
|
5
|
+
Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
6
|
+
Release dates are from git history where available; earlier versions are estimated from the first public commit.
|
|
7
|
+
|
|
8
|
+
## [1.4.1](https://github.com/quantaroute/checkout/compare/v1.4.0...v1.4.1) — 2026-06-13
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- Consistent email OTP — same code reused for up to 10 checkouts per email+merchant
|
|
13
|
+
- `SendEmailOtpResult` export with `reused` flag when send skips Resend
|
|
14
|
+
- `EmailOtpStep` copy when an existing code is still valid
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- Email OTP rate limits — max 3 fresh codes / 24h; silent reuse when code is still active
|
|
19
|
+
- Verify lockout after 5 failed attempts (15 min)
|
|
20
|
+
|
|
21
|
+
### Documentation
|
|
22
|
+
|
|
23
|
+
- OpenAPI spec for `/checkout-email-otp` (send, verify, `reused`, rate-limit responses)
|
|
24
|
+
|
|
25
|
+
## [1.4.0](https://github.com/quantaroute/checkout/compare/v1.3.1...v1.4.0) — 2026-06-04
|
|
26
|
+
|
|
27
|
+
### Added
|
|
28
|
+
|
|
29
|
+
- Email OTP auth (`enableEmailAuth`, `EmailStep`, `EmailOtpStep`, `checkout-email-otp` Edge Function)
|
|
30
|
+
- Per-merchant email templates (`email_from_name`, `email_logo_url`, `email_subject_template`)
|
|
31
|
+
- COD controls (`enableCod`, `CodAvailabilityBanner`, `checkCodEligibility()`)
|
|
32
|
+
- Server-side webhooks (`phone_verified`, `email_verified`, `address_completed`, `session.expired`)
|
|
33
|
+
- Automatic session expiry (`checkout-session-expiry` Edge Function + pg_cron)
|
|
34
|
+
- SDK exports: `sendEmailOtp`, `verifyEmailOtp`, `notifyAddressCompleted`
|
|
35
|
+
- Checkout events: `email_step_viewed`, `email_otp_sent`, `email_verified`
|
|
36
|
+
|
|
37
|
+
## [1.3.1](https://github.com/quantaroute/checkout/compare/v1.3.0...v1.3.1) — 2026-03-14
|
|
38
|
+
|
|
39
|
+
### Added
|
|
40
|
+
|
|
41
|
+
- Unified map search bar (`enableSearch`) with DigiPin and address autocomplete
|
|
42
|
+
|
|
43
|
+
### Fixed
|
|
44
|
+
|
|
45
|
+
- DigiPin typing in the search box
|
|
46
|
+
|
|
47
|
+
## [1.3.0](https://github.com/quantaroute/checkout/compare/v1.2.1...v1.3.0) — 2026-03-01
|
|
48
|
+
|
|
49
|
+
*Estimated — phone OTP and saved-address work landed before the 1.3.1 publish; no tagged commit.*
|
|
50
|
+
|
|
51
|
+
### Added
|
|
52
|
+
|
|
53
|
+
- Phone OTP auth (`enablePhoneAuth`, `PhoneStep`, `OtpStep`, `checkout-otp` Edge Function)
|
|
54
|
+
- Saved addresses (`SavedAddressStep`, `checkout-addresses` CRUD API)
|
|
55
|
+
- Pincode validation and non-delivery warnings in `AddressForm`
|
|
56
|
+
- Per-merchant branding (`brandColor`, `logoUrl`, `headerBanner`)
|
|
57
|
+
- Client analytics hook (`onCheckoutEvent`, `CheckoutEvent` types)
|
|
58
|
+
- Checkout API client exports (`sendOtp`, `verifyOtp`, address helpers)
|
|
59
|
+
|
|
60
|
+
## [1.2.1](https://github.com/quantaroute/checkout/compare/v1.2.0...v1.2.1) — 2026-02-19
|
|
61
|
+
|
|
62
|
+
### Fixed
|
|
63
|
+
|
|
64
|
+
- npm package export paths for CSS and native entry points
|
|
65
|
+
|
|
66
|
+
## [1.2.0](https://github.com/quantaroute/checkout/compare/v1.1.0...v1.2.0) — 2026-02-19
|
|
67
|
+
|
|
68
|
+
### Added
|
|
69
|
+
|
|
70
|
+
- iOS and Android support via React Native / Expo (`*.native.tsx`, `expo-plugin.js`)
|
|
71
|
+
- Native map pin selector, address form, and checkout widget
|
|
72
|
+
- GPS geolocation on native (`useGeolocation.native.ts`)
|
|
73
|
+
- Native design system (`checkout.native.ts`, light + dark)
|
|
74
|
+
|
|
75
|
+
## [1.1.0](https://github.com/quantaroute/checkout/compare/v1.0.0...v1.1.0) — 2026-02-18
|
|
76
|
+
|
|
77
|
+
### Added
|
|
78
|
+
|
|
79
|
+
- DigiPin badge overlay on map
|
|
80
|
+
- Locality alternatives dropdown
|
|
81
|
+
- OSM address pre-fill (building, road, suburb)
|
|
82
|
+
- India boundary GeoJSON overlay
|
|
83
|
+
|
|
84
|
+
## [1.0.0](https://github.com/quantaroute/checkout/releases/tag/v1.0.0) — 2026-02-17
|
|
85
|
+
|
|
86
|
+
### Added
|
|
87
|
+
|
|
88
|
+
- Web checkout widget with MapLibre GL + Carto Positron
|
|
89
|
+
- Offline DigiPin generation and QuantaRoute API integration
|
|
90
|
+
- Mobile-first layout, dark mode, reduced-motion, keyboard accessibility
|
|
91
|
+
|
package/README.md
CHANGED
|
@@ -380,6 +380,8 @@ When `enableEmailAuth` is true the widget starts with an email-entry step. The b
|
|
|
380
380
|
|
|
381
381
|
#### Setting up Resend (required for `enableEmailAuth`)
|
|
382
382
|
|
|
383
|
+
> **Hosted merchants (recommended):** If you onboarded at [developers.quantaroute.com](https://developers.quantaroute.com), QuantaRoute already runs Resend on shared infrastructure. Skip steps 1–5 below — just set `enableEmailAuth={true}` and register your domain in the portal. The steps below apply only when **self-hosting** the `checkout-email-otp` Edge Function in your own Supabase project.
|
|
384
|
+
|
|
383
385
|
1. **Create a Resend account** at [resend.com](https://resend.com) — free tier covers ~3 000 emails / month.
|
|
384
386
|
|
|
385
387
|
2. **Verify your sending domain** (e.g. `checkout.yourbrand.com` or `yourbrand.com`):
|
|
@@ -644,7 +646,7 @@ In the [Supabase Dashboard](https://supabase.com/dashboard) → your project →
|
|
|
644
646
|
|
|
645
647
|
### 4 · Add your domain to the allowed list
|
|
646
648
|
|
|
647
|
-
In the developer portal at **[developers.quantaroute.com/dashboard/checkout](https://developers.quantaroute.com/dashboard/checkout)**, add your storefront's domain (e.g. `yourbrand.com`). The `checkout-otp` Edge
|
|
649
|
+
In the developer portal at **[developers.quantaroute.com/dashboard/checkout](https://developers.quantaroute.com/dashboard/checkout)**, add your storefront's domain (e.g. `yourbrand.com`). The `checkout-email-otp` and `checkout-otp` Edge Functions enforce this list — requests from unlisted origins receive `403 Origin not allowed`.
|
|
648
650
|
|
|
649
651
|
### Minimal Next.js integration
|
|
650
652
|
|
|
@@ -769,12 +771,75 @@ The offline DigiPin algorithm is the official India Post implementation:
|
|
|
769
771
|
|
|
770
772
|
| Doc | Description |
|
|
771
773
|
|-----|-------------|
|
|
774
|
+
| [Changelog](./CHANGELOG.md) | Version history and release notes |
|
|
772
775
|
| [Checkout roadmap](./docs/CHECKOUT_ROADMAP.md) | Feature phases and implementation status |
|
|
773
776
|
| [MSG91 OTP setup](./docs/MSG91_INDIA_OTP_SETUP.md) | India SMS / DLT configuration for phone OTP |
|
|
774
777
|
| [Brand teardown](./docs/brand-teardown.md) | Competitive analysis (Shopflo) |
|
|
775
778
|
|
|
776
779
|
---
|
|
777
780
|
|
|
781
|
+
## Security & integration
|
|
782
|
+
|
|
783
|
+
### What ships in the npm package
|
|
784
|
+
|
|
785
|
+
The published tarball contains **no secrets** — only client-side widget code:
|
|
786
|
+
|
|
787
|
+
| Included | Excluded |
|
|
788
|
+
|---|---|
|
|
789
|
+
| `dist/lib/*.js` (Terser-minified ES + UMD) | `supabase/`, Edge Functions, migrations |
|
|
790
|
+
| `dist/lib/index.d.ts` | `demo/`, `docs/`, `openapi.yaml`, `.env*` |
|
|
791
|
+
| `dist/style.css` | `vite.config.ts`, dev tooling |
|
|
792
|
+
| `src/` (required for React Native / Metro) | `node_modules/` |
|
|
793
|
+
|
|
794
|
+
- **Geocoding `apiKey`** (`dp_…`) is designed for the browser bundle — rate-limited, scoped to your merchant plan.
|
|
795
|
+
- **Admin API key** (`qca_…`) must **never** ship in frontend code. Use it server-side only (`x-api-key` on `checkout-admin`).
|
|
796
|
+
- OTP delivery (Resend) and session minting run on **QuantaRoute-hosted Edge Functions**, not inside the npm bundle.
|
|
797
|
+
- **Consistent email OTP:** the same 6-digit code is stored per `(email, merchant)` and reused for up to **10 successful logins** (not single-use). Repeat send requests skip Resend when the code is still active. This reduces email cost but is weaker than banking-grade OTP — document for your shoppers if required by policy.
|
|
798
|
+
|
|
799
|
+
Verify before every publish:
|
|
800
|
+
|
|
801
|
+
```bash
|
|
802
|
+
npm run type-check && npm run build:lib
|
|
803
|
+
npm pack --dry-run # confirm 36 files, no .env / supabase / demo
|
|
804
|
+
rg -i 're_|sk_|service.role|password' dist/ # should return no matches
|
|
805
|
+
```
|
|
806
|
+
|
|
807
|
+
### Merchant integration checklist (email OTP on web)
|
|
808
|
+
|
|
809
|
+
Use this when embedding `@quantaroute/checkout` on a **hosted QuantaRoute** storefront (onboarded via [developers.quantaroute.com](https://developers.quantaroute.com)):
|
|
810
|
+
|
|
811
|
+
1. **Onboard** — complete [merchant onboarding](https://developers.quantaroute.com/onboarding/merchant); copy `merchantId`, geocoding `apiKey`, and `supabaseFunctionBaseUrl` from the wizard or [Checkout dashboard](https://developers.quantaroute.com/dashboard/checkout).
|
|
812
|
+
2. **Install** — `npm install @quantaroute/checkout maplibre-gl` (+ CSS imports).
|
|
813
|
+
3. **Env vars** — expose only public values (`NEXT_PUBLIC_QUANTAROUTE_KEY`, `NEXT_PUBLIC_MERCHANT_ID`, `NEXT_PUBLIC_SUPABASE_FUNCTION_URL`). Never commit `.env` to git.
|
|
814
|
+
4. **Allowed domains** — in the developer portal, add every origin that will host the widget (e.g. `yourbrand.com`, `www.yourbrand.com`, `*.yourbrand.com` for subdomains). Both `checkout-otp` and `checkout-email-otp` reject requests from unlisted origins.
|
|
815
|
+
5. **Enable auth** — set `enableEmailAuth={true}` with `merchantId` and `supabaseFunctionBaseUrl`. Auth is **opt-in** and **web-only** today (React Native widget does not include the email OTP steps).
|
|
816
|
+
6. **Optional branding** — `brandColor`, `logoUrl`; per-merchant email template columns (`email_from_name`, `email_logo_url`, `email_subject_template`) in the portal.
|
|
817
|
+
7. **Handle completion** — implement `onComplete` to pass the `CompleteAddress` to your cart / payment gateway. Built-in payment (`enablePayment`) and COD (`enableCod`) are separate opt-in props.
|
|
818
|
+
|
|
819
|
+
> **Resend is platform-managed for hosted merchants.** QuantaRoute operates the shared `checkout-email-otp` Edge Function and Resend sender (`RESEND_API_KEY`, `RESEND_FROM_EMAIL`). Merchants do **not** need their own Resend account for the hosted MVP. See [Setting up Resend](#setting-up-resend-required-for-enableemailauth) only if you self-host the Edge Functions.
|
|
820
|
+
|
|
821
|
+
### Platform responsibilities (QuantaRoute)
|
|
822
|
+
|
|
823
|
+
| Item | Owner |
|
|
824
|
+
|---|---|
|
|
825
|
+
| Deploy & operate `checkout-email-otp`, `checkout-addresses`, `checkout-session-expiry` | QuantaRoute |
|
|
826
|
+
| `RESEND_API_KEY`, `RESEND_FROM_EMAIL`, Supabase service role | QuantaRoute (Edge Function secrets) |
|
|
827
|
+
| `checkout.merchants` provisioning, `allowed_domains`, email template columns | QuantaRoute portal + DB |
|
|
828
|
+
| Buyer OTP consistent reuse (10 logins per code), fresh-code limit (3 / 24h), verify lockout (5 fails → 15 min) | Edge Function |
|
|
829
|
+
| Geocoding API key issuance & plan rate limits | QuantaRoute |
|
|
830
|
+
|
|
831
|
+
### Maintainer publish checklist
|
|
832
|
+
|
|
833
|
+
When publishing a new version to npm (maintainers only):
|
|
834
|
+
|
|
835
|
+
1. Enable **npm 2FA** on the `@quantaroute` org account (publish + modify).
|
|
836
|
+
2. Run `npm run type-check && npm run build:lib && npm pack --dry-run` — confirm tarball contents.
|
|
837
|
+
3. Confirm no `.env`, `.pem`, or `supabase/` paths in the pack list.
|
|
838
|
+
4. Publish from a **clean git tag** with provenance: `npm publish --provenance --access public`.
|
|
839
|
+
5. Do **not** bump version in the same change unless releasing; current version is `1.4.0`.
|
|
840
|
+
|
|
841
|
+
---
|
|
842
|
+
|
|
778
843
|
## Development
|
|
779
844
|
|
|
780
845
|
```bash
|
|
@@ -807,54 +872,7 @@ npx expo run:android # requires Android Studio
|
|
|
807
872
|
|
|
808
873
|
## Changelog
|
|
809
874
|
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
- **Email OTP auth** — `enableEmailAuth` prop; `EmailStep` / `EmailOtpStep` components; `checkout-email-otp` Edge Function (Resend); no TRAI dependency
|
|
813
|
-
- **Per-merchant email template** — `email_from_name`, `email_logo_url`, `email_subject_template` columns on `checkout.merchants`; `{code}` / `{brand}` placeholders in subject
|
|
814
|
-
- **COD controls** — `enableCod` prop + `CodAvailabilityBanner`; `cod_blocked_pincodes[]`, `cod_max_cart_value_paise`, `enable_cod` on merchant row; `checkCodEligibility()` in SDK
|
|
815
|
-
- **Server-side webhooks** — `session.phone_verified`, `session.email_verified`, `session.address_completed`, `session.expired`; HMAC-SHA256 signed; 3-retry delivery log in `checkout.webhook_deliveries`
|
|
816
|
-
- **Automatic session expiry** — `checkout-session-expiry` Edge Function; pg_cron job fires every 10 min
|
|
817
|
-
- **New SDK exports** — `sendEmailOtp`, `verifyEmailOtp`, `VerifyEmailOtpResult`, `checkCodEligibility`, `notifyAddressCompleted`
|
|
818
|
-
- **Event types** — added `email_step_viewed`, `email_otp_sent`, `email_verified` to `onCheckoutEvent`
|
|
819
|
-
|
|
820
|
-
### v1.3.x
|
|
821
|
-
|
|
822
|
-
- **Phone OTP + saved addresses** — `enablePhoneAuth`, `merchantId`, `supabaseFunctionBaseUrl` props; `PhoneStep`, `OtpStep`, `SavedAddressStep` components
|
|
823
|
-
- **Address autocomplete + DigiPin search** — unified search bar via `enableSearch`; "near me" / location-biased 3-pass Nominatim strategy on backend
|
|
824
|
-
- **Pincode validation** — `validatePincode()` in `AddressForm`; fake codes (e.g. `123456`) are blocked with an inline error; non-delivery areas show a warning banner
|
|
825
|
-
- **Per-merchant branding** — `brandColor` (hex), `logoUrl`, `headerBanner`; map pin and all accent elements use the brand colour on web and native
|
|
826
|
-
- **Cross-merchant "Saved at [Brand]" chip** — address cards show the brand name where the address was first saved
|
|
827
|
-
- **Client-side analytics hook** — `onCheckoutEvent` fires on every step transition for MoEngage / GTM / custom backends
|
|
828
|
-
- `CheckoutEvent` and `CheckoutEventType` exported from the package
|
|
829
|
-
- Checkout API client (`checkout-api.ts`) and types exported (`sendOtp`, `verifyOtp`, `listAddresses`, `createAddress`, `deleteAddress`, `setDefaultAddress`)
|
|
830
|
-
|
|
831
|
-
### v1.2.0
|
|
832
|
-
|
|
833
|
-
- **iOS & Android support** via `expo-osm-sdk` (MapLibre GL Native)
|
|
834
|
-
- `MapPinSelector.native.tsx` — draggable OSMView pin
|
|
835
|
-
- `AddressForm.native.tsx` — `TextInput` / `ScrollView` / `Modal` locality picker
|
|
836
|
-
- `CheckoutWidget.native.tsx` — `SafeAreaView` layout with identical flow logic
|
|
837
|
-
- `useGeolocation.native.ts` — GPS via `expo-location`
|
|
838
|
-
- `checkout.native.ts` — complete `StyleSheet` design system (light + dark)
|
|
839
|
-
- `expo-plugin.js` — one-line `app.json` setup for iOS/Android
|
|
840
|
-
- `babel.config.js` — Metro transpilation config
|
|
841
|
-
- `mapHeight` prop now accepts `number` (native) or `string` (web, e.g. `'380px'`)
|
|
842
|
-
- All native peer dependencies marked optional (zero impact on web bundles)
|
|
843
|
-
|
|
844
|
-
### v1.1.x
|
|
845
|
-
|
|
846
|
-
- DigiPin badge overlay on map
|
|
847
|
-
- Locality alternatives dropdown
|
|
848
|
-
- OSM address pre-fill (building name, road, suburb)
|
|
849
|
-
- India boundary GeoJSON overlay
|
|
850
|
-
|
|
851
|
-
### v1.0.0
|
|
852
|
-
|
|
853
|
-
- Initial release: MapLibre GL + Carto Positron
|
|
854
|
-
- Offline DigiPin generation
|
|
855
|
-
- QuantaRoute API integration
|
|
856
|
-
- Mobile-first responsive design
|
|
857
|
-
- Dark mode, reduced-motion, keyboard accessible
|
|
875
|
+
See [CHANGELOG.md](./CHANGELOG.md) for version history. Current release: **v1.4.1**.
|
|
858
876
|
|
|
859
877
|
---
|
|
860
878
|
|
package/dist/lib/index.d.ts
CHANGED
|
@@ -403,6 +403,8 @@ export declare const EmailOtpStep: default_2.FC<EmailOtpStepProps>;
|
|
|
403
403
|
|
|
404
404
|
export declare interface EmailOtpStepProps {
|
|
405
405
|
email: string;
|
|
406
|
+
/** When true, no new email was sent — shopper should use their existing code. */
|
|
407
|
+
codeReused?: boolean;
|
|
406
408
|
onVerified: (sessionToken: string, buyerId: string, sessionId?: string) => void;
|
|
407
409
|
onBack: () => void;
|
|
408
410
|
functionBaseUrl: string;
|
|
@@ -413,8 +415,10 @@ export declare interface EmailOtpStepProps {
|
|
|
413
415
|
export declare const EmailStep: default_2.FC<EmailStepProps>;
|
|
414
416
|
|
|
415
417
|
export declare interface EmailStepProps {
|
|
416
|
-
/** Called with the normalised (lowercased) email once OTP is
|
|
417
|
-
onOtpSent: (email: string
|
|
418
|
+
/** Called with the normalised (lowercased) email once OTP is ready (sent or reused). */
|
|
419
|
+
onOtpSent: (email: string, info?: {
|
|
420
|
+
reused?: boolean;
|
|
421
|
+
}) => void;
|
|
418
422
|
onSkip: () => void;
|
|
419
423
|
functionBaseUrl: string;
|
|
420
424
|
merchantId: string;
|
|
@@ -720,7 +724,12 @@ export declare interface SavedAddressStepProps {
|
|
|
720
724
|
}
|
|
721
725
|
|
|
722
726
|
/** Send a 6-digit OTP to the given email via Resend (Edge: `checkout-email-otp`). */
|
|
723
|
-
export declare function sendEmailOtp(config: CheckoutApiConfig, email: string): Promise<
|
|
727
|
+
export declare function sendEmailOtp(config: CheckoutApiConfig, email: string): Promise<SendEmailOtpResult>;
|
|
728
|
+
|
|
729
|
+
/** Result from send email OTP — includes whether an existing code was reused (no new email). */
|
|
730
|
+
export declare interface SendEmailOtpResult {
|
|
731
|
+
reused: boolean;
|
|
732
|
+
}
|
|
724
733
|
|
|
725
734
|
/** Send OTP to the given mobile number. Throws on failure. */
|
|
726
735
|
export declare function sendOtp(config: CheckoutApiConfig, mobile: string): Promise<void>;
|
|
@@ -75,16 +75,16 @@ if(!i.success)throw new Error(i.message??"Reverse geocoding failed")
|
|
|
75
75
|
return i}function E(){const[e,r]=t({loading:!1,error:null})
|
|
76
76
|
return{...e,locate:i(e=>{navigator.geolocation?(r({loading:!0,error:null}),navigator.geolocation.getCurrentPosition(({coords:n})=>{r({loading:!1,error:null}),e(n.latitude,n.longitude)},e=>{let n="Unable to get location."
|
|
77
77
|
e.code===e.PERMISSION_DENIED?n="Location permission denied. Please enable it in browser settings.":e.code===e.POSITION_UNAVAILABLE?n="Location unavailable. Try again or place the pin manually.":e.code===e.TIMEOUT&&(n="Location request timed out. Try again."),r({loading:!1,error:n})},{enableHighAccuracy:!0,timeout:12e3,maximumAge:0})):r({loading:!1,error:"Geolocation is not supported by your browser."})},[]),clearError:i(()=>{r(e=>({...e,error:null}))},[])}}function S(e,r){if(!b(e,r))return null
|
|
78
|
-
try{return m(e,r)}catch{return null}}const L="#0ea5e9",I=({onLocationConfirm:n,defaultLat:a,defaultLng:d,mapHeight:c="380px",theme:h="light",indiaBoundaryUrl:p,enableSearch:m=!0,apiKey:y,apiBaseUrl:b,brandColor:v=L})=>{const _=o(null),g=o(null),q=o(null),w=a??13.00427,N=d??77.589291,x=void 0!==a&&void 0!==d,[I,P]=t(w),[T,A]=t(N),[B,D]=t(()=>S(w,N)),[M,$]=t(!1),[O,
|
|
78
|
+
try{return m(e,r)}catch{return null}}const L="#0ea5e9",I=({onLocationConfirm:n,defaultLat:a,defaultLng:d,mapHeight:c="380px",theme:h="light",indiaBoundaryUrl:p,enableSearch:m=!0,apiKey:y,apiBaseUrl:b,brandColor:v=L})=>{const _=o(null),g=o(null),q=o(null),w=a??13.00427,N=d??77.589291,x=void 0!==a&&void 0!==d,[I,P]=t(w),[T,A]=t(N),[B,D]=t(()=>S(w,N)),[M,$]=t(!1),[O,U]=t(""),[F,R]=t([]),[j,W]=t(!1),[J,z]=t(null),[V,H]=t(!1),K=o(null),G=o(null),Z=l(),{loading:Y,error:Q,locate:X,clearError:ee}=E(),re=i((e,r)=>{D(S(e,r))},[]),ne=i((e,r)=>{var n
|
|
79
79
|
P(e),A(r),re(e,r),g.current&&g.current.flyTo({center:[r,e],zoom:18,duration:900,essential:!0}),null==(n=q.current)||n.setLngLat([r,e])},[re]),ae=i(e=>{const r=e.target.value
|
|
80
|
-
|
|
80
|
+
U(r),z(null),K.current&&clearTimeout(K.current)
|
|
81
81
|
const n=r.trim()
|
|
82
82
|
if(!n)return R([]),H(!1),void W(!1)
|
|
83
83
|
if(k(n))try{const e=f(n.toUpperCase()),r=parseFloat(e.latitude),a=parseFloat(e.longitude)
|
|
84
|
-
ne(r,a),R([]),H(!1),
|
|
84
|
+
ne(r,a),R([]),H(!1),U(n.toUpperCase())}catch{z("Invalid DigiPin code")}else{if(n.length<3)return R([]),void H(!1)
|
|
85
85
|
W(!0),K.current=setTimeout(async()=>{try{const e=y??"",r=await C(n,e,b,5,I,T)
|
|
86
86
|
R(r),H(r.length>0)}catch(e){z(e instanceof Error?e.message:"Search failed"),R([]),H(!1)}finally{W(!1)}},400)}},[y,b,ne]),te=i(e=>{var r
|
|
87
|
-
ne(e.coordinates.latitude,e.coordinates.longitude),
|
|
87
|
+
ne(e.coordinates.latitude,e.coordinates.longitude),U(""),R([]),H(!1),null==(r=G.current)||r.blur()},[ne]),ie=i(e=>{"Escape"===e.key&&(R([]),H(!1),U(""))},[])
|
|
88
88
|
s(()=>{if(!_.current)return
|
|
89
89
|
const e=p?fetch(p).then(e=>e.ok?e.json():null).catch(()=>null):Promise.resolve(null),r=x?18:9,n=new u.Map({container:_.current,style:"https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",center:[N,w],zoom:r,minZoom:6,attributionControl:!1,touchZoomRotate:!0})
|
|
90
90
|
return n.addControl(new u.AttributionControl({compact:!0,customAttribution:'© <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">OpenStreetMap</a> contributors © <a href="https://carto.com/attributions" target="_blank" rel="noopener">CARTO</a>'}),"bottom-right"),n.addControl(new u.NavigationControl({showCompass:!1}),"top-right"),n.on("load",()=>{$(!0),e.then(e=>{if(e&&n.isStyleLoaded())try{n.addSource("india-boundary",{type:"geojson",data:e}),n.addLayer({id:"india-boundary-line",type:"line",source:"india-boundary",paint:{"line-color":"#94a3b8","line-width":1.5,"line-opacity":.65}})}catch{}})
|
|
@@ -97,7 +97,7 @@ const a=e.lngLat
|
|
|
97
97
|
null==(r=q.current)||r.setLngLat([a.lng,a.lat]),P(a.lat),A(a.lng),re(a.lat,a.lng),n.easeTo({center:[a.lng,a.lat],duration:200})}),g.current=n,()=>{n.remove(),g.current=null,q.current=null}},[])
|
|
98
98
|
const oe=i(()=>{ee(),X((e,r)=>{var n
|
|
99
99
|
P(e),A(r),re(e,r),g.current&&g.current.flyTo({center:[r,e],zoom:18,duration:1400,essential:!0}),null==(n=q.current)||n.setLngLat([r,e])})},[X,ee,re]),le=i(()=>{B&&n(I,T,B)},[I,T,B,n]),se=null!==B,de=se&&M
|
|
100
|
-
return e("div",{className:"qr-map-wrapper",children:[e("div",{className:"qr-step-header",children:[r("div",{className:"qr-step-badge",children:"1"}),e("div",{className:"qr-step-text",children:[r("span",{className:"qr-step-title",children:"Pin Your Location"}),r("span",{className:"qr-step-sub",children:"Tap the map or drag the pin to your exact home / office"})]})]}),m&&e("div",{className:"qr-search-bar",role:"search",children:[e("div",{className:"qr-search-bar__input-wrap",children:[e("svg",{className:"qr-search-bar__icon","aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r("circle",{cx:"11",cy:"11",r:"8"}),r("path",{d:"M21 21l-4.35-4.35"})]}),r("input",{ref:G,type:"search",className:"qr-search-bar__input",placeholder:"Search address, 'pharmacy near me', or DigiPin…",value:O,onChange:ae,onKeyDown:ie,autoComplete:"off",autoCorrect:"off",autoCapitalize:"characters",spellCheck:!1,"aria-label":"Search address or DigiPin","aria-autocomplete":"list","aria-controls":V?Z:void 0,"aria-expanded":V}),j&&r("span",{className:"qr-search-bar__spinner qr-spinner qr-spinner--sm","aria-hidden":"true"}),O&&!j&&r("button",{type:"button",className:"qr-search-bar__clear",onClick:()=>{
|
|
100
|
+
return e("div",{className:"qr-map-wrapper",children:[e("div",{className:"qr-step-header",children:[r("div",{className:"qr-step-badge",children:"1"}),e("div",{className:"qr-step-text",children:[r("span",{className:"qr-step-title",children:"Pin Your Location"}),r("span",{className:"qr-step-sub",children:"Tap the map or drag the pin to your exact home / office"})]})]}),m&&e("div",{className:"qr-search-bar",role:"search",children:[e("div",{className:"qr-search-bar__input-wrap",children:[e("svg",{className:"qr-search-bar__icon","aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r("circle",{cx:"11",cy:"11",r:"8"}),r("path",{d:"M21 21l-4.35-4.35"})]}),r("input",{ref:G,type:"search",className:"qr-search-bar__input",placeholder:"Search address, 'pharmacy near me', or DigiPin…",value:O,onChange:ae,onKeyDown:ie,autoComplete:"off",autoCorrect:"off",autoCapitalize:"characters",spellCheck:!1,"aria-label":"Search address or DigiPin","aria-autocomplete":"list","aria-controls":V?Z:void 0,"aria-expanded":V}),j&&r("span",{className:"qr-search-bar__spinner qr-spinner qr-spinner--sm","aria-hidden":"true"}),O&&!j&&r("button",{type:"button",className:"qr-search-bar__clear",onClick:()=>{U(""),R([]),H(!1),z(null)},"aria-label":"Clear search",tabIndex:-1,children:"×"})]}),J&&r("p",{className:"qr-search-bar__error",role:"alert",children:J}),V&&F.length>0&&r("ul",{id:Z,className:"qr-search-bar__dropdown",role:"listbox","aria-label":"Address suggestions",children:F.map((n,a)=>e("li",{className:"qr-search-bar__suggestion",role:"option","aria-selected":"false",onMouseDown:e=>{e.preventDefault(),te(n)},children:[e("svg",{className:"qr-search-bar__suggestion-icon","aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[r("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"}),r("circle",{cx:"12",cy:"9",r:"2.5"})]}),e("div",{className:"qr-search-bar__suggestion-text",children:[r("span",{className:"qr-search-bar__suggestion-name",children:n.displayName}),n.address&&n.address!==n.displayName&&r("span",{className:"qr-search-bar__suggestion-sub",children:n.address})]})]},a))}),e("p",{className:"qr-search-bar__hint",children:[r("span",{className:"qr-search-bar__hint-chip",children:"DigiPin"}),"Type your DigiPin code for instant offline lookup — no API call"]})]}),e("div",{className:"qr-map-outer",style:{height:c},children:[r("div",{ref:_,className:"qr-map-canvas"}),B&&e("div",{className:"qr-digipin-badge","aria-live":"polite","aria-label":`DigiPin: ${B}`,children:[r("span",{className:"qr-digipin-badge__label",children:"DigiPin"}),r("span",{className:"qr-digipin-badge__code",children:B})]}),!se&&M&&r("div",{className:"qr-map-notice",role:"status",children:"Move map to India to get a DigiPin"}),r("button",{className:"qr-locate-btn"+(Y?" qr-locate-btn--loading":""),onClick:oe,disabled:Y,title:"Use my current location","aria-label":"Use my current location",type:"button",children:Y?r("span",{className:"qr-spinner","aria-hidden":"true"}):e("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"}),r("circle",{cx:"12",cy:"12",r:"7"}),r("path",{d:"M12 2v3M12 19v3M2 12h3M19 12h3"})]})}),Q&&e("div",{className:"qr-geo-error",role:"alert",children:[r("span",{children:Q}),r("button",{type:"button",className:"qr-geo-error__dismiss",onClick:ee,"aria-label":"Dismiss error",children:"×"})]})]}),M&&e("div",{className:"qr-coords-strip","aria-label":"Current pin coordinates",children:[e("span",{children:[I.toFixed(5),"° N"]}),r("span",{className:"qr-coords-sep",children:"·"}),e("span",{children:[T.toFixed(5),"° E"]})]}),e("div",{className:"qr-map-actions",children:[e("button",{type:"button",className:"qr-btn qr-btn--primary qr-btn--full",onClick:le,disabled:!de,children:["Confirm Location",r("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:r("path",{d:"M5 12h14M12 5l7 7-7 7"})})]}),!se&&M&&r("p",{className:"qr-map-hint",children:"Move the pin to a location in India to continue"})]})]})},P={flatNumber:"",floorNumber:"",buildingName:"",streetName:""}
|
|
101
101
|
function T(e,r){switch(r.type){case"LOAD_START":return{status:"loading"}
|
|
102
102
|
case"LOAD_SUCCESS":{const e=function(e){const r={}
|
|
103
103
|
e.name?r.buildingName=e.name:e.building_name?r.buildingName=e.building_name:e.addr_housename&&(r.buildingName=e.addr_housename)
|
|
@@ -130,11 +130,12 @@ return i}function M(e){return{"Content-Type":"application/json","x-session-token
|
|
|
130
130
|
if(!n.ok||!a.success)throw new Error(a.error??"Failed to load saved addresses.")
|
|
131
131
|
return a.data??[]}async function O(e,r,n){const a=await fetch(`${e.functionBaseUrl}/checkout-addresses`,{method:"POST",headers:M(r),body:JSON.stringify({action:"create",address:n})}),t=await a.json().catch(()=>({}))
|
|
132
132
|
if(!a.ok||!t.success)throw new Error(t.error??"Failed to save address.")
|
|
133
|
-
return t.data}async function
|
|
134
|
-
if(!a.ok||!t.success)throw new Error(t.error??"Failed to delete address.")}async function
|
|
133
|
+
return t.data}async function U(e,r,n){const a=await fetch(`${e.functionBaseUrl}/checkout-addresses`,{method:"POST",headers:M(r),body:JSON.stringify({action:"delete",address_id:n})}),t=await a.json().catch(()=>({}))
|
|
134
|
+
if(!a.ok||!t.success)throw new Error(t.error??"Failed to delete address.")}async function F(e,r,n){const a=await fetch(`${e.functionBaseUrl}/checkout-addresses`,{method:"POST",headers:M(r),body:JSON.stringify({action:"set_default",address_id:n})}),t=await a.json().catch(()=>({}))
|
|
135
135
|
if(!a.ok||!t.success)throw new Error(t.error??"Failed to set default address.")}async function R(e,r,n){const a=await fetch(`${e.functionBaseUrl}/checkout-addresses`,{method:"POST",headers:M(r),body:JSON.stringify({action:"address_completed",data:n})}),t=await a.json().catch(()=>({}))
|
|
136
136
|
!a.ok||t.success}async function j(e,r){const n=await fetch(`${e.functionBaseUrl}/checkout-email-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"send",email:r,merchant_id:e.merchantId})}),a=await n.json().catch(()=>({}))
|
|
137
|
-
if(!n.ok||!a.success)throw new Error(a.error??"Failed to send OTP. Please try again.")
|
|
137
|
+
if(!n.ok||!a.success)throw new Error(a.error??"Failed to send OTP. Please try again.")
|
|
138
|
+
return{reused:Boolean(a.reused)}}async function W(e,r,n,a){const t=await fetch(`${e.functionBaseUrl}/checkout-email-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"verify",email:r,code:n,merchant_id:e.merchantId,...a})}),i=await t.json().catch(()=>({}))
|
|
138
139
|
if(!t.ok||!i.success)throw new Error(i.error??"Invalid or expired code.")
|
|
139
140
|
return i}async function J(e,r,n,a){const t={action:"cod_eligibility",pincode:n}
|
|
140
141
|
void 0!==a&&(t.cart_total_paise=a)
|
|
@@ -180,8 +181,8 @@ if(0===e.length)return void d()
|
|
|
180
181
|
u(e)}catch(e){f(e instanceof Error?e.message:"Failed to load addresses.")}finally{p(!1)}},[n])
|
|
181
182
|
s(()=>{_()},[_])
|
|
182
183
|
const g=i(async e=>{b(e)
|
|
183
|
-
try{await
|
|
184
|
-
return 0===n.length&&d(),n})}catch(e){f(e instanceof Error?e.message:"Failed to delete address.")}finally{b(null)}},[n,d]),q=i(async e=>{try{await
|
|
184
|
+
try{await U(v,n,e),u(r=>{const n=r.filter(r=>r.id!==e)
|
|
185
|
+
return 0===n.length&&d(),n})}catch(e){f(e instanceof Error?e.message:"Failed to delete address.")}finally{b(null)}},[n,d]),q=i(async e=>{try{await F(v,n,e),u(r=>r.map(r=>({...r,is_default:r.id===e})))}catch(e){f(e instanceof Error?e.message:"Failed to set default.")}},[n])
|
|
185
186
|
return h?r("div",{className:"qr-saved-step",children:r("div",{className:"qr-saved-step__loading","aria-live":"polite",children:r("span",{className:"qr-spinner","aria-label":"Loading addresses"})})}):m&&0===c.length?e("div",{className:"qr-saved-step",children:[r("p",{className:"qr-auth-step__error",role:"alert",children:m}),r("button",{type:"button",className:"qr-btn qr-btn--ghost qr-btn--full",onClick:_,children:"Retry"}),r("button",{type:"button",className:"qr-auth-step__skip",onClick:d,children:"Enter address manually"})]}):e("div",{className:"qr-saved-step",children:[e("div",{className:"qr-step-header",children:[r("div",{className:"qr-step-badge qr-step-badge--saved",children:e("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r("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"}),r("circle",{cx:"12",cy:"9",r:"2.5"})]})}),e("div",{className:"qr-step-text",children:[r("span",{className:"qr-step-title",children:"Saved Addresses"}),r("span",{className:"qr-step-sub",children:"Pick one or add a new location"})]})]}),m&&r("p",{className:"qr-auth-step__error",role:"alert",children:m}),r("div",{className:"qr-saved-step__list",children:c.map(e=>r(ie,{address:e,onUse:()=>l(e),onDelete:()=>g(e.id),onSetDefault:()=>q(e.id),deleting:y===e.id},e.id))}),e("button",{type:"button",className:"qr-btn qr-btn--ghost qr-btn--full",onClick:d,children:[r("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:r("path",{d:"M12 5v14M5 12h14"})}),"Add new address"]})]})},le=({checkoutConfig:n,sessionToken:a,pincode:i,cartTotalPaise:o,theme:l="light",onCodAllowedChange:d})=>{const[c,u]=t("loading"),[h,p]=t(!1),[m,f]=t()
|
|
186
187
|
return s(()=>{let e=!1
|
|
187
188
|
return u("loading"),(async()=>{try{const r=await J(n,a,i,o)
|
|
@@ -205,53 +206,54 @@ try{const e=await Z(n,a)
|
|
|
205
206
|
null==p||p("payment_method_selected",e.payment_method),u(e.payment_method)}catch(e){b(e instanceof Error?e.message:"Failed to select COD")}finally{f(!1)}},disabled:m,style:{marginTop:8},children:"Cash on Delivery"}):null,i?e("p",{className:"qr-payment-step__meta",children:["Session ",i.slice(0,8),"…"]}):null]})},ue=({onOtpSent:a,onSkip:l,functionBaseUrl:s,merchantId:d})=>{const[c,u]=t(""),[h,p]=t(!1),[m,f]=t(null),y=o(null),b=i(e=>{u(e.target.value.trim()),f(null)},[]),v=i(async e=>{var r
|
|
206
207
|
if(e.preventDefault(),!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(c))return f("Enter a valid email address."),void(null==(r=y.current)||r.focus())
|
|
207
208
|
p(!0),f(null)
|
|
208
|
-
try{await j({functionBaseUrl:s,merchantId:d},c)
|
|
209
|
+
try{const{reused:e}=await j({functionBaseUrl:s,merchantId:d},c)
|
|
210
|
+
a(c.toLowerCase(),{reused:e})}catch(e){f(e instanceof Error?e.message:"Failed to send code. Please try again.")}finally{p(!1)}},[c,s,d,a])
|
|
209
211
|
return e("div",{className:"qr-auth-step",children:[r("div",{className:"qr-auth-step__icon","aria-hidden":"true",children:e("svg",{viewBox:"0 0 48 48",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r("circle",{cx:"24",cy:"24",r:"24",fill:"var(--qr-primary-light)"}),r("rect",{x:"11",y:"15",width:"26",height:"18",rx:"3",stroke:"var(--qr-primary)",strokeWidth:"1.8",fill:"none"}),r("path",{d:"M11 18l13 9 13-9",stroke:"var(--qr-primary)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})]})}),r("h3",{className:"qr-auth-step__title",children:"Faster checkout"}),r("p",{className:"qr-auth-step__sub",children:"Enter your email to load saved addresses"}),e("form",{onSubmit:v,noValidate:!0,children:[r("div",{className:"qr-email-field"+(m?" qr-email-field--error":""),children:r("input",{ref:y,type:"email",inputMode:"email",className:"qr-email-field__input",placeholder:"you@example.com",value:c,onChange:b,autoComplete:"email","aria-label":"Email address","aria-describedby":m?"qr-email-error":void 0,"aria-invalid":!!m,disabled:h})}),m&&r("p",{id:"qr-email-error",className:"qr-auth-step__error",role:"alert",children:m}),r("button",{type:"submit",className:"qr-btn qr-btn--primary qr-btn--full",disabled:h||c.length<5,children:h?r("span",{className:"qr-spinner qr-spinner--sm","aria-hidden":"true"}):e(n,{children:["Send Code",r("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:r("path",{d:"M5 12h14M12 5l7 7-7 7"})})]})})]}),r("button",{type:"button",className:"qr-auth-step__skip",onClick:l,disabled:h,children:"Skip, enter address manually"})]})}
|
|
210
212
|
function he(e){const[r,n]=e.split("@")
|
|
211
|
-
return!n||r.length<=1?e:`${r[0]}***@${n}`}const pe=({email:
|
|
212
|
-
s(()=>(
|
|
213
|
-
const
|
|
214
|
-
return null==(r=
|
|
215
|
-
|
|
216
|
-
return a[e]=n,a}),n&&e<5&&
|
|
217
|
-
return n[e]="",n}):e>0&&(
|
|
218
|
-
return n[e-1]="",n}),
|
|
213
|
+
return!n||r.length<=1?e:`${r[0]}***@${n}`}const pe=({email:a,codeReused:l=!1,onVerified:d,onBack:c,functionBaseUrl:u,merchantId:h,sessionContext:p})=>{const[m,f]=t(Array(6).fill("")),[y,b]=t(!1),[v,_]=t(null),[g,q]=t(60),[w,N]=t(!1),k=o([]),C=o(null)
|
|
214
|
+
s(()=>(C.current=setInterval(()=>{q(e=>e<=1?(clearInterval(C.current),0):e-1)},1e3),()=>{C.current&&clearInterval(C.current)}),[])
|
|
215
|
+
const x=e=>{var r
|
|
216
|
+
return null==(r=k.current[e])?void 0:r.focus()},E=i((e,r)=>{const n=r.replace(/\D/g,"").slice(-1)
|
|
217
|
+
_(null),f(r=>{const a=[...r]
|
|
218
|
+
return a[e]=n,a}),n&&e<5&&x(e+1)},[]),S=i((e,r)=>{"Backspace"===r.key?m[e]?f(r=>{const n=[...r]
|
|
219
|
+
return n[e]="",n}):e>0&&(f(r=>{const n=[...r]
|
|
220
|
+
return n[e-1]="",n}),x(e-1)):"ArrowLeft"===r.key&&e>0?x(e-1):"ArrowRight"===r.key&&e<5&&x(e+1)},[m]),L=i(e=>{e.preventDefault()
|
|
219
221
|
const r=e.clipboardData.getData("text").replace(/\D/g,"").slice(0,6)
|
|
220
222
|
if(!r)return
|
|
221
223
|
const n=Array(6).fill("")
|
|
222
|
-
r.split("").forEach((e,r)=>{n[r]=e}),
|
|
223
|
-
try{const e=await W({functionBaseUrl:
|
|
224
|
-
|
|
225
|
-
s(()=>{
|
|
226
|
-
const
|
|
227
|
-
try{await j({functionBaseUrl:
|
|
228
|
-
return e("div",{className:"qr-auth-step",children:[r("button",{type:"button",className:"qr-back-btn qr-back-btn--auth",onClick:
|
|
224
|
+
r.split("").forEach((e,r)=>{n[r]=e}),f(n),_(null),x(Math.min(r.length,5))},[]),I=m.join(""),P=6===I.length&&!m.includes(""),T=i(async()=>{if(P){b(!0),_(null)
|
|
225
|
+
try{const e=await W({functionBaseUrl:u,merchantId:h},a,I,p)
|
|
226
|
+
d(e.session_token,e.buyer_id,e.session_id)}catch(e){_(e instanceof Error?e.message:"Verification failed. Please try again."),f(Array(6).fill("")),x(0)}finally{b(!1)}}},[P,I,a,u,h,d,p])
|
|
227
|
+
s(()=>{P&&!y&&T()},[P])
|
|
228
|
+
const A=i(async()=>{if(!(g>0||w)){N(!0),_(null),f(Array(6).fill(""))
|
|
229
|
+
try{await j({functionBaseUrl:u,merchantId:h},a),q(60),C.current=setInterval(()=>{q(e=>e<=1?(clearInterval(C.current),0):e-1)},1e3),x(0)}catch(e){_(e instanceof Error?e.message:"Failed to resend code.")}finally{N(!1)}}},[g,w,u,h,a])
|
|
230
|
+
return e("div",{className:"qr-auth-step",children:[r("button",{type:"button",className:"qr-back-btn qr-back-btn--auth",onClick:c,disabled:y,children:r("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:r("path",{d:"M19 12H5M12 5l-7 7 7 7"})})}),r("div",{className:"qr-auth-step__icon","aria-hidden":"true",children:e("svg",{viewBox:"0 0 48 48",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r("circle",{cx:"24",cy:"24",r:"24",fill:"var(--qr-primary-light)"}),r("rect",{x:"11",y:"15",width:"26",height:"18",rx:"3",stroke:"var(--qr-primary)",strokeWidth:"1.8",fill:"none"}),r("path",{d:"M11 18l13 9 13-9",stroke:"var(--qr-primary)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})]})}),r("h3",{className:"qr-auth-step__title",children:"Check your email"}),r("p",{className:"qr-auth-step__sub",children:l?r(n,{children:"Use the code we sent earlier — it's still valid for your next checkout."}):e(n,{children:["6-digit code sent to ",r("strong",{children:he(a)})]})}),r("div",{className:"qr-otp-boxes",role:"group","aria-label":"Enter verification code",children:m.map((e,n)=>r("input",{ref:e=>{k.current[n]=e},type:"text",inputMode:"numeric",maxLength:1,className:`qr-otp-box${e?" qr-otp-box--filled":""}${v?" qr-otp-box--error":""}`,value:e,onChange:e=>E(n,e.target.value),onKeyDown:e=>S(n,e),onPaste:L,onFocus:e=>e.target.select(),"aria-label":`Code digit ${n+1}`,disabled:y,autoComplete:0===n?"one-time-code":"off"},n))}),v&&r("p",{className:"qr-auth-step__error",role:"alert",children:v}),r("button",{type:"button",className:"qr-btn qr-btn--primary qr-btn--full",onClick:T,disabled:!P||y,children:y?r("span",{className:"qr-spinner qr-spinner--sm","aria-hidden":"true"}):"Verify Code"}),r("p",{className:"qr-auth-step__resend",children:g>0?e("span",{children:["Resend code in ",g,"s"]}):r("button",{type:"button",className:"qr-link-btn",onClick:A,disabled:w,children:w?"Sending…":"Resend Code"})})]})}
|
|
229
231
|
function me(e){if("undefined"!=typeof window){const e=window.innerWidth
|
|
230
232
|
return e<768?"mobile":e<1024?"tablet":"desktop"}const r=(e??"").toLowerCase()
|
|
231
233
|
return/ipad|tablet/.test(r)?"tablet":/mobile|iphone|android/.test(r)?"mobile":"desktop"}function fe(){return"web"}function ye(){const e=function(){if("undefined"!=typeof navigator&&navigator.userAgent)return navigator.userAgent.slice(0,512)}()
|
|
232
234
|
return{deviceType:me(e),platform:"web",userAgent:e}}const be=["utm_source","utm_medium","utm_campaign"]
|
|
233
235
|
function ve(e){try{const r=new URL(e??("undefined"!=typeof window?window.location.href:"")),n={}
|
|
234
236
|
for(const e of be){const a=r.searchParams.get(e)
|
|
235
|
-
a&&(n[e]=a.slice(0,256))}return n}catch{return{}}}function _e(e){return Boolean(e.utm_source||e.utm_medium||e.utm_campaign)}const ge=({address:n,onEditAddress:a})=>e("div",{className:"qr-success",children:[r("div",{className:"qr-success__icon","aria-hidden":"true",children:e("svg",{viewBox:"0 0 52 52",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r("circle",{cx:"26",cy:"26",r:"26",fill:"var(--qr-success, #10b981)",opacity:"0.12"}),r("circle",{cx:"26",cy:"26",r:"20",fill:"var(--qr-success, #10b981)"}),r("path",{d:"M15 26l8 8 14-16",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round"})]})}),r("h3",{className:"qr-success__title",children:"Address Saved!"}),r("p",{className:"qr-success__address",children:n.formattedAddress}),r("div",{className:"qr-success__meta",children:e("span",{className:"qr-digipin-badge qr-digipin-badge--inline",children:[r("span",{className:"qr-digipin-badge__label",children:"DigiPin"}),r("span",{className:"qr-digipin-badge__code",children:n.digipin})]})}),r("button",{type:"button",className:"qr-btn qr-btn--ghost qr-btn--sm",onClick:a,children:"Change Address"})]}),qe=({apiKey:l,apiBaseUrl:d="https://api.quantaroute.com",onComplete:u,onError:h,defaultLat:p,defaultLng:m,theme:f="light",className:y="",style:b,mapHeight:v="380px",title:_="Add Delivery Address",indiaBoundaryUrl:g,enableSearch:q=!0,enablePhoneAuth:w=!1,merchantId:N="",supabaseFunctionBaseUrl:k="",brandColor:C,logoUrl:x,headerBanner:E,onCheckoutEvent:S,enableCod:L=!1,codCartTotalPaise:P,codSessionToken:T="",enableEmailAuth:B=!1,variant:D,utmParams:M,enablePayment:$=!1,paymentAmountPaise:
|
|
236
|
-
s(()=>{
|
|
237
|
-
const
|
|
238
|
-
if(S)try{S(r)}catch{}N&&k&&z(
|
|
237
|
+
a&&(n[e]=a.slice(0,256))}return n}catch{return{}}}function _e(e){return Boolean(e.utm_source||e.utm_medium||e.utm_campaign)}const ge=({address:n,onEditAddress:a})=>e("div",{className:"qr-success",children:[r("div",{className:"qr-success__icon","aria-hidden":"true",children:e("svg",{viewBox:"0 0 52 52",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r("circle",{cx:"26",cy:"26",r:"26",fill:"var(--qr-success, #10b981)",opacity:"0.12"}),r("circle",{cx:"26",cy:"26",r:"20",fill:"var(--qr-success, #10b981)"}),r("path",{d:"M15 26l8 8 14-16",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round"})]})}),r("h3",{className:"qr-success__title",children:"Address Saved!"}),r("p",{className:"qr-success__address",children:n.formattedAddress}),r("div",{className:"qr-success__meta",children:e("span",{className:"qr-digipin-badge qr-digipin-badge--inline",children:[r("span",{className:"qr-digipin-badge__label",children:"DigiPin"}),r("span",{className:"qr-digipin-badge__code",children:n.digipin})]})}),r("button",{type:"button",className:"qr-btn qr-btn--ghost qr-btn--sm",onClick:a,children:"Change Address"})]}),qe=({apiKey:l,apiBaseUrl:d="https://api.quantaroute.com",onComplete:u,onError:h,defaultLat:p,defaultLng:m,theme:f="light",className:y="",style:b,mapHeight:v="380px",title:_="Add Delivery Address",indiaBoundaryUrl:g,enableSearch:q=!0,enablePhoneAuth:w=!1,merchantId:N="",supabaseFunctionBaseUrl:k="",brandColor:C,logoUrl:x,headerBanner:E,onCheckoutEvent:S,enableCod:L=!1,codCartTotalPaise:P,codSessionToken:T="",enableEmailAuth:B=!1,variant:D,utmParams:M,enablePayment:$=!1,paymentAmountPaise:U,onPaymentComplete:F,enablePrepaidNudge:j=!1,prepaidNudgeCopy:W,prepaidNudgeCtaUrl:J})=>{const K=w?"phone":B?"email":"none",G="phone"===K?"phone":"email"===K?"email":"map",Z=Boolean($&&U&&k),[Y,X]=t(G),[re,ne]=t(null),[ae,te]=t(null),[ie,de]=t(null),[he,me]=t(""),[fe,be]=t(!1),[_e,qe]=t(!1),[we,Ne]=t(null),[ke,Ce]=t(null),xe=o(Y),Ee=c(()=>M??ve(),[M]),Se=c(()=>ye(),[]),Le=c(()=>({utm_source:Ee.utm_source,utm_medium:Ee.utm_medium,utm_campaign:Ee.utm_campaign,device_type:Se.deviceType,platform:Se.platform,user_agent:Se.userAgent,experiment_variant:D}),[Ee,Se,D]),Ie={functionBaseUrl:k,merchantId:N},Pe=(null==ie?void 0:ie.sessionToken)||T
|
|
238
|
+
s(()=>{xe.current=Y},[Y])
|
|
239
|
+
const Te=i(e=>{const r={...e,sessionId:e.sessionId??(null==ie?void 0:ie.sessionId),buyerId:e.buyerId??(null==ie?void 0:ie.buyerId),authChannel:e.authChannel??("phone"===K?"phone":"email"===K?"email":"none"),deviceType:e.deviceType??Se.deviceType,platform:e.platform??Se.platform,userAgent:e.userAgent??Se.userAgent,experimentVariant:e.experimentVariant??D,timestamp:(new Date).toISOString()}
|
|
240
|
+
if(S)try{S(r)}catch{}N&&k&&z(Ie,{event_type:r.type,step:r.step,buyer_id:r.buyerId,auth_channel:r.authChannel,device_type:r.deviceType,platform:r.platform,user_agent:r.userAgent,payment_method:r.paymentMethod,experiment_variant:r.experimentVariant},null==ie?void 0:ie.sessionToken).catch(()=>{})},[ie,K,Se,D,S,N,k,Ie])
|
|
239
241
|
s(()=>{if(!N||!k)return
|
|
240
|
-
const e=()=>{"done"!==
|
|
241
|
-
return window.addEventListener("pagehide",e),()=>window.removeEventListener("pagehide",e)},[null==ie?void 0:ie.sessionToken,N,k,
|
|
242
|
-
const
|
|
242
|
+
const e=()=>{"done"!==xe.current&&(null==ie?void 0:ie.sessionToken)&&(V(Ie,ie.sessionToken,xe.current).catch(()=>{}),Te({type:"session_abandoned",step:xe.current}))}
|
|
243
|
+
return window.addEventListener("pagehide",e),()=>window.removeEventListener("pagehide",e)},[null==ie?void 0:ie.sessionToken,N,k,Ie,Te]),s(()=>{(null==ie?void 0:ie.sessionToken)&&N&&k&&H(Ie,ie.sessionToken).then(Ne).catch(()=>Ne(null))},[null==ie?void 0:ie.sessionToken,N,k,Ie])
|
|
244
|
+
const Ae=c(()=>function(e,r){const n=null==r?void 0:r.trim()
|
|
243
245
|
if(!n)return e
|
|
244
246
|
const a={"--qr-primary":n,"--qr-primary-dark":n,"--qr-border-focus":n,"--qr-primary-light":`color-mix(in srgb, ${n} 18%, white)`}
|
|
245
|
-
return e?{...e,...a}:a}(b,C),[b,C]),
|
|
246
|
-
try{await O(
|
|
247
|
+
return e?{...e,...a}:a}(b,C),[b,C]),Be=()=>{Te({type:"auth_skipped",step:"map"}),X("map")},De=async e=>{if(te(e),Te({type:"address_completed",step:Z?"payment":"done",digipin:e.digipin,buyerId:null==ie?void 0:ie.buyerId}),null==ie?void 0:ie.sessionToken){R(Ie,ie.sessionToken,{pincode:e.pincode,digipin:e.digipin,state:e.state,district:e.district,locality:e.locality}).catch(()=>{})
|
|
248
|
+
try{await O(Ie,ie.sessionToken,{digipin:e.digipin,lat:e.lat,lng:e.lng,state:e.state,district:e.district,locality:e.locality,pincode:e.pincode,delivery_status:e.delivery,flat_number:e.flatNumber,floor_number:e.floorNumber,building_name:e.buildingName,street_name:e.streetName,full_address_json:e,label:"home",is_default:!0})}catch{}}Z&&Pe?X("payment"):(X("done"),u(e))}
|
|
247
249
|
s(()=>{const e={phone:"phone_step_viewed",email:"email_step_viewed",saved:"saved_addresses_viewed",map:"map_step_viewed",form:"form_step_viewed",payment:"payment_step_viewed"}[Y]
|
|
248
|
-
e&&
|
|
249
|
-
const
|
|
250
|
+
e&&Te({type:e,step:Y,buyerId:null==ie?void 0:ie.buyerId})},[Y]),s(()=>{B&&"email"===K&&(N&&k||null==h||h(new Error("enableEmailAuth requires merchantId and supabaseFunctionBaseUrl on CheckoutWidget.")))},[B,K,N,k,h])
|
|
251
|
+
const Me=function(e,r,n){if("none"===r){if(n){const r=["map","form","payment","done"].indexOf(e)
|
|
250
252
|
return-1===r?0:r}return"map"===e?0:"form"===e?1:2}const a=("email"===r?n?["email","email-otp","saved","map","form","payment","done"]:["email","email-otp","saved","map","form","done"]:n?["phone","otp","saved","map","form","payment","done"]:["phone","otp","saved","map","form","done"]).indexOf(e)
|
|
251
|
-
return-1===a?0:a}(Y,K,Z)
|
|
252
|
-
return e("div",{className:`qr-checkout qr-checkout--${f} ${y}`,style:
|
|
253
|
-
return r("div",{className:"qr-progress",role:"progressbar","aria-valuenow":
|
|
253
|
+
return-1===a?0:a}(Y,K,Z),$e=function(e,r){return"none"===e?r?3:2:r?6:5}(K,Z)
|
|
254
|
+
return e("div",{className:`qr-checkout qr-checkout--${f} ${y}`,style:Ae,"data-testid":"quantaroute-checkout",children:["done"!==Y&&e(n,{children:[e("div",{className:"qr-header",children:[e("div",{className:"qr-header__brand",children:[x?r("img",{src:x,alt:"",className:"qr-header__logo-img",width:28,height:28,decoding:"async"}):e("svg",{className:"qr-header__logo","aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r("path",{d:"M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0118 0z"}),r("circle",{cx:"12",cy:"10",r:"3"})]}),r("span",{className:"qr-header__title",children:_})]}),(()=>{const n=Array.from({length:$e+1},(e,r)=>r)
|
|
255
|
+
return r("div",{className:"qr-progress",role:"progressbar","aria-valuenow":Me+1,"aria-valuemin":1,"aria-valuemax":$e+1,"aria-label":`Step ${Me+1} of ${$e+1}`,children:n.map(n=>e(a.Fragment,{children:[r("div",{className:"qr-progress__dot"+(Me>=n?" qr-progress__dot--active":"")}),n<$e&&r("div",{className:"qr-progress__line"+(Me>n?" qr-progress__line--active":"")})]},n))})})()]}),E?r("div",{className:"qr-header-banner",role:"region","aria-label":"Merchant message",children:E}):null,we?e("div",{className:"qr-offer-banner",role:"region","aria-label":"Special offer",children:[we.banner_copy,we.banner_cta_url?e(n,{children:[" ",r("a",{href:we.banner_cta_url,target:"_blank",rel:"noopener noreferrer",children:"Learn more"})]}):null]}):null]}),"email"===Y&&B&&r(ue,{onOtpSent:(e,r)=>{me(e),be(Boolean(null==r?void 0:r.reused)),Te({type:"email_otp_sent",step:"email-otp",mobile:e}),X("email-otp")},onSkip:Be,functionBaseUrl:k,merchantId:N}),"email-otp"===Y&&B&&he&&r(pe,{email:he,codeReused:fe,onVerified:(e,r,n)=>{de({mobile:he,sessionToken:e,sessionId:n??"",buyerId:r}),Te({type:"email_verified",step:"saved",buyerId:r,sessionId:n}),X("saved")},onBack:()=>X("email"),functionBaseUrl:k,merchantId:N,sessionContext:Le}),"phone"===Y&&w&&r(Q,{onOtpSent:e=>{de(r=>({mobile:e,sessionToken:"",sessionId:"",buyerId:(null==r?void 0:r.buyerId)??""})),Te({type:"otp_sent",step:"otp",mobile:e}),X("otp")},onSkip:Be,functionBaseUrl:k,merchantId:N}),"otp"===Y&&ie&&r(ee,{mobile:ie.mobile,onVerified:(e,r,n)=>{de({mobile:(null==ie?void 0:ie.mobile)??"",sessionToken:e,sessionId:n??"",buyerId:r}),Te({type:"phone_verified",step:"saved",buyerId:r,sessionId:n}),X("saved")},onBack:()=>X("phone"),functionBaseUrl:k,merchantId:N,sessionContext:Le}),"saved"===Y&&(null==ie?void 0:ie.sessionToken)&&r(oe,{sessionToken:ie.sessionToken,functionBaseUrl:k,merchantId:N,onSelectAddress:e=>{Te({type:"saved_address_selected",step:Z?"payment":"done",buyerId:null==ie?void 0:ie.buyerId,digipin:e.digipin}),(null==ie?void 0:ie.sessionToken)&&R(Ie,ie.sessionToken,{pincode:e.pincode,digipin:e.digipin,state:e.state,district:e.district,locality:e.locality}).catch(()=>{})
|
|
254
256
|
const r={digipin:e.digipin,lat:e.lat,lng:e.lng,state:e.state,district:e.district,division:"",locality:e.locality,pincode:e.pincode,delivery:e.delivery_status,country:"India",flatNumber:e.flat_number,floorNumber:e.floor_number,buildingName:e.building_name,streetName:e.street_name,formattedAddress:[e.flat_number,e.building_name,e.street_name,e.locality,e.district,e.state,e.pincode].filter(Boolean).join(", ")}
|
|
255
|
-
|
|
257
|
+
De(r)},onAddNew:()=>X("map")}),"map"===Y&&r(I,{onLocationConfirm:(e,r,n)=>{ne({lat:e,lng:r,digipin:n}),Te({type:"location_confirmed",step:"form",digipin:n,buyerId:null==ie?void 0:ie.buyerId}),X("form")},defaultLat:p,defaultLng:m,mapHeight:v,theme:f,indiaBoundaryUrl:g,enableSearch:q,apiKey:l,apiBaseUrl:d,brandColor:C}),"form"===Y&&re&&r(A,{digipin:re.digipin,lat:re.lat,lng:re.lng,apiKey:l,apiBaseUrl:d,onAddressComplete:async e=>{await De(e)},onBack:()=>{"form"===Y?X("map"):"map"===Y&&(null==ie?void 0:ie.sessionToken)?X("saved"):"email-otp"===Y&&X("email")},onError:h,theme:f}),"payment"===Y&&Z&&Pe&&U&&r(ce,{checkoutConfig:Ie,sessionToken:Pe,sessionId:null==ie?void 0:ie.sessionId,amountPaise:U,enableCod:L,codAllowed:_e,theme:f,onComplete:e=>{Ce(e),Te({type:"payment_method_selected",step:"done",paymentMethod:e}),X("done"),ae&&u(ae),null==F||F({paymentMethod:e,sessionId:null==ie?void 0:ie.sessionId})},onBack:()=>X("form"),onEvent:(e,r)=>Te({type:e,step:"payment",paymentMethod:r,buyerId:null==ie?void 0:ie.buyerId})}),"done"===Y&&ae&&e(n,{children:[r(ge,{address:ae,onEditAddress:()=>{Te({type:"widget_reset",step:G}),X(G),ne(null),te(null)}}),ke?e("p",{className:"qr-cod-banner__text qr-cod-banner__text--ok",style:{textAlign:"center",margin:"8px 16px"},children:["Paid via ","cod"===ke?"Cash on Delivery":"online payment"]}):null,L&&N&&k&&Pe?e(n,{children:[r(le,{checkoutConfig:Ie,sessionToken:Pe,pincode:ae.pincode,cartTotalPaise:P??U,theme:f,onCodAllowedChange:qe}),j&&_e?r(se,{copy:W??"Save more when you pay online — faster delivery & exclusive offers.",ctaUrl:J,theme:f}):null]}):null]}),e("div",{className:"qr-footer",children:[r("span",{children:"Powered by"}),r("a",{href:"https://quantaroute.com",target:"_blank",rel:"noopener noreferrer",className:"qr-footer__link",children:"QuantaRoute"}),r("span",{className:"qr-footer__flag","aria-label":"Made in India",children:"🇮🇳"})]})]})}
|
|
256
258
|
function we(e,r){return c(()=>{if(!b(e,r))return null
|
|
257
|
-
try{return m(e,r)}catch{return null}},[e,r])}export{A as AddressForm,qe as CheckoutWidget,le as CodAvailabilityBanner,p as DIGIPIN_BOUNDS,pe as EmailOtpStep,ue as EmailStep,I as MapPinSelector,ee as OtpStep,ce as PaymentStep,Q as PhoneStep,se as PrepaidNudge,oe as SavedAddressStep,C as autocompleteAddress,ve as captureUtmFromUrl,J as checkCodEligibility,O as createAddress,K as createPaymentOrder,qe as default,
|
|
259
|
+
try{return m(e,r)}catch{return null}},[e,r])}export{A as AddressForm,qe as CheckoutWidget,le as CodAvailabilityBanner,p as DIGIPIN_BOUNDS,pe as EmailOtpStep,ue as EmailStep,I as MapPinSelector,ee as OtpStep,ce as PaymentStep,Q as PhoneStep,se as PrepaidNudge,oe as SavedAddressStep,C as autocompleteAddress,ve as captureUtmFromUrl,J as checkCodEligibility,O as createAddress,K as createPaymentOrder,qe as default,U as deleteAddress,me as detectDeviceType,fe as detectPlatform,Y as fetchPrepaidNudgeConfig,H as fetchSessionOffer,m as getDigiPin,f as getLatLngFromDigiPin,ye as getWebDeviceContext,_e as hasUtmParams,y as isValidDigiPin,b as isWithinIndia,$ as listAddresses,z as logFunnelEvent,k as looksLikeDigiPin,q as lookupLocation,R as notifyAddressCompleted,V as notifySessionAbandoned,N as pincodeHasDeliveryOffice,Z as recordCodPayment,x as reverseGeocode,j as sendEmailOtp,B as sendOtp,F as setDefaultAddress,we as useDigiPin,E as useGeolocation,w as validatePincode,W as verifyEmailOtp,D as verifyOtp,G as verifyPayment}
|
|
@@ -130,7 +130,8 @@ return t.data}async function P(e,r,n){const a=await fetch(`${e.functionBaseUrl}/
|
|
|
130
130
|
if(!a.ok||!t.success)throw new Error(t.error??"Failed to delete address.")}async function I(e,r,n){const a=await fetch(`${e.functionBaseUrl}/checkout-addresses`,{method:"POST",headers:E(r),body:JSON.stringify({action:"set_default",address_id:n})}),t=await a.json().catch(()=>({}))
|
|
131
131
|
if(!a.ok||!t.success)throw new Error(t.error??"Failed to set default address.")}async function T(e,r,n){const a=await fetch(`${e.functionBaseUrl}/checkout-addresses`,{method:"POST",headers:E(r),body:JSON.stringify({action:"address_completed",data:n})}),t=await a.json().catch(()=>({}))
|
|
132
132
|
!a.ok||t.success}async function A(e,r){const n=await fetch(`${e.functionBaseUrl}/checkout-email-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"send",email:r,merchant_id:e.merchantId})}),a=await n.json().catch(()=>({}))
|
|
133
|
-
if(!n.ok||!a.success)throw new Error(a.error??"Failed to send OTP. Please try again.")
|
|
133
|
+
if(!n.ok||!a.success)throw new Error(a.error??"Failed to send OTP. Please try again.")
|
|
134
|
+
return{reused:Boolean(a.reused)}}async function B(e,r,n,a){const t=await fetch(`${e.functionBaseUrl}/checkout-email-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"verify",email:r,code:n,merchant_id:e.merchantId,...a})}),i=await t.json().catch(()=>({}))
|
|
134
135
|
if(!t.ok||!i.success)throw new Error(i.error??"Invalid or expired code.")
|
|
135
136
|
return i}async function M(e,r,n,a){const t={action:"cod_eligibility",pincode:n}
|
|
136
137
|
void 0!==a&&(t.cart_total_paise=a)
|
|
@@ -203,54 +204,55 @@ try{const r=await j(e,a)
|
|
|
203
204
|
null==u||u("payment_method_selected",r.payment_method),d(r.payment_method)}catch(e){f(e instanceof Error?e.message:"Failed to select COD")}finally{p(!1)}},disabled:h,style:{marginTop:8},children:"Cash on Delivery"}):null,t?r.jsxs("p",{className:"qr-payment-step__meta",children:["Session ",t.slice(0,8),"…"]}):null]})},re=({onOtpSent:e,onSkip:a,functionBaseUrl:t,merchantId:i})=>{const[o,l]=n.useState(""),[s,d]=n.useState(!1),[c,u]=n.useState(null),h=n.useRef(null),p=n.useCallback(e=>{l(e.target.value.trim()),u(null)},[]),m=n.useCallback(async r=>{var n
|
|
204
205
|
if(r.preventDefault(),!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o))return u("Enter a valid email address."),void(null==(n=h.current)||n.focus())
|
|
205
206
|
d(!0),u(null)
|
|
206
|
-
try{await A({functionBaseUrl:t,merchantId:i},o)
|
|
207
|
+
try{const{reused:r}=await A({functionBaseUrl:t,merchantId:i},o)
|
|
208
|
+
e(o.toLowerCase(),{reused:r})}catch(e){u(e instanceof Error?e.message:"Failed to send code. Please try again.")}finally{d(!1)}},[o,t,i,e])
|
|
207
209
|
return r.jsxs("div",{className:"qr-auth-step",children:[r.jsx("div",{className:"qr-auth-step__icon","aria-hidden":"true",children:r.jsxs("svg",{viewBox:"0 0 48 48",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.jsx("circle",{cx:"24",cy:"24",r:"24",fill:"var(--qr-primary-light)"}),r.jsx("rect",{x:"11",y:"15",width:"26",height:"18",rx:"3",stroke:"var(--qr-primary)",strokeWidth:"1.8",fill:"none"}),r.jsx("path",{d:"M11 18l13 9 13-9",stroke:"var(--qr-primary)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})]})}),r.jsx("h3",{className:"qr-auth-step__title",children:"Faster checkout"}),r.jsx("p",{className:"qr-auth-step__sub",children:"Enter your email to load saved addresses"}),r.jsxs("form",{onSubmit:m,noValidate:!0,children:[r.jsx("div",{className:"qr-email-field"+(c?" qr-email-field--error":""),children:r.jsx("input",{ref:h,type:"email",inputMode:"email",className:"qr-email-field__input",placeholder:"you@example.com",value:o,onChange:p,autoComplete:"email","aria-label":"Email address","aria-describedby":c?"qr-email-error":void 0,"aria-invalid":!!c,disabled:s})}),c&&r.jsx("p",{id:"qr-email-error",className:"qr-auth-step__error",role:"alert",children:c}),r.jsx("button",{type:"submit",className:"qr-btn qr-btn--primary qr-btn--full",disabled:s||o.length<5,children:s?r.jsx("span",{className:"qr-spinner qr-spinner--sm","aria-hidden":"true"}):r.jsxs(r.Fragment,{children:["Send Code",r.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M5 12h14M12 5l7 7-7 7"})})]})})]}),r.jsx("button",{type:"button",className:"qr-auth-step__skip",onClick:a,disabled:s,children:"Skip, enter address manually"})]})}
|
|
208
210
|
function ne(e){const[r,n]=e.split("@")
|
|
209
|
-
return!n||r.length<=1?e:`${r[0]}***@${n}`}const ae=({email:e,
|
|
210
|
-
n.useEffect(()=>(
|
|
211
|
-
const
|
|
212
|
-
return null==(r=
|
|
213
|
-
|
|
214
|
-
return a[e]=n,a}),n&&e<5&&
|
|
215
|
-
return n[e]="",n}):e>0&&(
|
|
216
|
-
return n[e-1]="",n}),
|
|
211
|
+
return!n||r.length<=1?e:`${r[0]}***@${n}`}const ae=({email:e,codeReused:a=!1,onVerified:t,onBack:i,functionBaseUrl:o,merchantId:l,sessionContext:s})=>{const[d,c]=n.useState(Array(6).fill("")),[u,h]=n.useState(!1),[p,m]=n.useState(null),[f,y]=n.useState(60),[b,v]=n.useState(!1),g=n.useRef([]),_=n.useRef(null)
|
|
212
|
+
n.useEffect(()=>(_.current=setInterval(()=>{y(e=>e<=1?(clearInterval(_.current),0):e-1)},1e3),()=>{_.current&&clearInterval(_.current)}),[])
|
|
213
|
+
const q=e=>{var r
|
|
214
|
+
return null==(r=g.current[e])?void 0:r.focus()},w=n.useCallback((e,r)=>{const n=r.replace(/\D/g,"").slice(-1)
|
|
215
|
+
m(null),c(r=>{const a=[...r]
|
|
216
|
+
return a[e]=n,a}),n&&e<5&&q(e+1)},[]),N=n.useCallback((e,r)=>{"Backspace"===r.key?d[e]?c(r=>{const n=[...r]
|
|
217
|
+
return n[e]="",n}):e>0&&(c(r=>{const n=[...r]
|
|
218
|
+
return n[e-1]="",n}),q(e-1)):"ArrowLeft"===r.key&&e>0?q(e-1):"ArrowRight"===r.key&&e<5&&q(e+1)},[d]),k=n.useCallback(e=>{e.preventDefault()
|
|
217
219
|
const r=e.clipboardData.getData("text").replace(/\D/g,"").slice(0,6)
|
|
218
220
|
if(!r)return
|
|
219
221
|
const n=Array(6).fill("")
|
|
220
|
-
r.split("").forEach((e,r)=>{n[r]=e}),
|
|
221
|
-
try{const r=await B({functionBaseUrl:
|
|
222
|
-
|
|
223
|
-
n.useEffect(()=>{
|
|
224
|
-
const
|
|
225
|
-
try{await A({functionBaseUrl:
|
|
226
|
-
return r.jsxs("div",{className:"qr-auth-step",children:[r.jsx("button",{type:"button",className:"qr-back-btn qr-back-btn--auth",onClick:
|
|
222
|
+
r.split("").forEach((e,r)=>{n[r]=e}),c(n),m(null),q(Math.min(r.length,5))},[]),C=d.join(""),x=6===C.length&&!d.includes(""),E=n.useCallback(async()=>{if(x){h(!0),m(null)
|
|
223
|
+
try{const r=await B({functionBaseUrl:o,merchantId:l},e,C,s)
|
|
224
|
+
t(r.session_token,r.buyer_id,r.session_id)}catch(e){m(e instanceof Error?e.message:"Verification failed. Please try again."),c(Array(6).fill("")),q(0)}finally{h(!1)}}},[x,C,e,o,l,t,s])
|
|
225
|
+
n.useEffect(()=>{x&&!u&&E()},[x])
|
|
226
|
+
const S=n.useCallback(async()=>{if(!(f>0||b)){v(!0),m(null),c(Array(6).fill(""))
|
|
227
|
+
try{await A({functionBaseUrl:o,merchantId:l},e),y(60),_.current=setInterval(()=>{y(e=>e<=1?(clearInterval(_.current),0):e-1)},1e3),q(0)}catch(e){m(e instanceof Error?e.message:"Failed to resend code.")}finally{v(!1)}}},[f,b,o,l,e])
|
|
228
|
+
return r.jsxs("div",{className:"qr-auth-step",children:[r.jsx("button",{type:"button",className:"qr-back-btn qr-back-btn--auth",onClick:i,disabled:u,children:r.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M19 12H5M12 5l-7 7 7 7"})})}),r.jsx("div",{className:"qr-auth-step__icon","aria-hidden":"true",children:r.jsxs("svg",{viewBox:"0 0 48 48",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.jsx("circle",{cx:"24",cy:"24",r:"24",fill:"var(--qr-primary-light)"}),r.jsx("rect",{x:"11",y:"15",width:"26",height:"18",rx:"3",stroke:"var(--qr-primary)",strokeWidth:"1.8",fill:"none"}),r.jsx("path",{d:"M11 18l13 9 13-9",stroke:"var(--qr-primary)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})]})}),r.jsx("h3",{className:"qr-auth-step__title",children:"Check your email"}),r.jsx("p",{className:"qr-auth-step__sub",children:a?r.jsx(r.Fragment,{children:"Use the code we sent earlier — it's still valid for your next checkout."}):r.jsxs(r.Fragment,{children:["6-digit code sent to ",r.jsx("strong",{children:ne(e)})]})}),r.jsx("div",{className:"qr-otp-boxes",role:"group","aria-label":"Enter verification code",children:d.map((e,n)=>r.jsx("input",{ref:e=>{g.current[n]=e},type:"text",inputMode:"numeric",maxLength:1,className:`qr-otp-box${e?" qr-otp-box--filled":""}${p?" qr-otp-box--error":""}`,value:e,onChange:e=>w(n,e.target.value),onKeyDown:e=>N(n,e),onPaste:k,onFocus:e=>e.target.select(),"aria-label":`Code digit ${n+1}`,disabled:u,autoComplete:0===n?"one-time-code":"off"},n))}),p&&r.jsx("p",{className:"qr-auth-step__error",role:"alert",children:p}),r.jsx("button",{type:"button",className:"qr-btn qr-btn--primary qr-btn--full",onClick:E,disabled:!x||u,children:u?r.jsx("span",{className:"qr-spinner qr-spinner--sm","aria-hidden":"true"}):"Verify Code"}),r.jsx("p",{className:"qr-auth-step__resend",children:f>0?r.jsxs("span",{children:["Resend code in ",f,"s"]}):r.jsx("button",{type:"button",className:"qr-link-btn",onClick:S,disabled:b,children:b?"Sending…":"Resend Code"})})]})}
|
|
227
229
|
function te(e){if("undefined"!=typeof window){const e=window.innerWidth
|
|
228
230
|
return e<768?"mobile":e<1024?"tablet":"desktop"}const r=(e??"").toLowerCase()
|
|
229
231
|
return/ipad|tablet/.test(r)?"tablet":/mobile|iphone|android/.test(r)?"mobile":"desktop"}function ie(){const e=function(){if("undefined"!=typeof navigator&&navigator.userAgent)return navigator.userAgent.slice(0,512)}()
|
|
230
232
|
return{deviceType:te(e),platform:"web",userAgent:e}}const oe=["utm_source","utm_medium","utm_campaign"]
|
|
231
233
|
function le(e){try{const r=new URL(e??("undefined"!=typeof window?window.location.href:"")),n={}
|
|
232
234
|
for(const e of oe){const a=r.searchParams.get(e)
|
|
233
|
-
a&&(n[e]=a.slice(0,256))}return n}catch{return{}}}const se=({address:e,onEditAddress:n})=>r.jsxs("div",{className:"qr-success",children:[r.jsx("div",{className:"qr-success__icon","aria-hidden":"true",children:r.jsxs("svg",{viewBox:"0 0 52 52",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.jsx("circle",{cx:"26",cy:"26",r:"26",fill:"var(--qr-success, #10b981)",opacity:"0.12"}),r.jsx("circle",{cx:"26",cy:"26",r:"20",fill:"var(--qr-success, #10b981)"}),r.jsx("path",{d:"M15 26l8 8 14-16",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round"})]})}),r.jsx("h3",{className:"qr-success__title",children:"Address Saved!"}),r.jsx("p",{className:"qr-success__address",children:e.formattedAddress}),r.jsx("div",{className:"qr-success__meta",children:r.jsxs("span",{className:"qr-digipin-badge qr-digipin-badge--inline",children:[r.jsx("span",{className:"qr-digipin-badge__label",children:"DigiPin"}),r.jsx("span",{className:"qr-digipin-badge__code",children:e.digipin})]})}),r.jsx("button",{type:"button",className:"qr-btn qr-btn--ghost qr-btn--sm",onClick:n,children:"Change Address"})]}),de=({apiKey:e,apiBaseUrl:a="https://api.quantaroute.com",onComplete:t,onError:i,defaultLat:o,defaultLng:l,theme:s="light",className:d="",style:c,mapHeight:u="380px",title:h="Add Delivery Address",indiaBoundaryUrl:p,enableSearch:m=!0,enablePhoneAuth:f=!1,merchantId:y="",supabaseFunctionBaseUrl:b="",brandColor:v,logoUrl:g,headerBanner:_,onCheckoutEvent:w,enableCod:N=!1,codCartTotalPaise:C,codSessionToken:x="",enableEmailAuth:E=!1,variant:S,utmParams:P,enablePayment:I=!1,paymentAmountPaise:A,onPaymentComplete:B,enablePrepaidNudge:M=!1,prepaidNudgeCopy:F,prepaidNudgeCtaUrl:U})=>{const j=f?"phone":E?"email":"none",W="phone"===j?"phone":"email"===j?"email":"map",z=Boolean(I&&A&&b),[V,H]=n.useState(W),[K,G]=n.useState(null),[X,ne]=n.useState(null),[te,oe]=n.useState(null),[de,ce]=n.useState(""),[ue,he]=n.useState(!1),[pe,me]=n.useState(
|
|
234
|
-
n.useEffect(()=>{
|
|
235
|
-
const
|
|
236
|
-
if(w)try{w(r)}catch{}y&&b&&$(
|
|
235
|
+
a&&(n[e]=a.slice(0,256))}return n}catch{return{}}}const se=({address:e,onEditAddress:n})=>r.jsxs("div",{className:"qr-success",children:[r.jsx("div",{className:"qr-success__icon","aria-hidden":"true",children:r.jsxs("svg",{viewBox:"0 0 52 52",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.jsx("circle",{cx:"26",cy:"26",r:"26",fill:"var(--qr-success, #10b981)",opacity:"0.12"}),r.jsx("circle",{cx:"26",cy:"26",r:"20",fill:"var(--qr-success, #10b981)"}),r.jsx("path",{d:"M15 26l8 8 14-16",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round"})]})}),r.jsx("h3",{className:"qr-success__title",children:"Address Saved!"}),r.jsx("p",{className:"qr-success__address",children:e.formattedAddress}),r.jsx("div",{className:"qr-success__meta",children:r.jsxs("span",{className:"qr-digipin-badge qr-digipin-badge--inline",children:[r.jsx("span",{className:"qr-digipin-badge__label",children:"DigiPin"}),r.jsx("span",{className:"qr-digipin-badge__code",children:e.digipin})]})}),r.jsx("button",{type:"button",className:"qr-btn qr-btn--ghost qr-btn--sm",onClick:n,children:"Change Address"})]}),de=({apiKey:e,apiBaseUrl:a="https://api.quantaroute.com",onComplete:t,onError:i,defaultLat:o,defaultLng:l,theme:s="light",className:d="",style:c,mapHeight:u="380px",title:h="Add Delivery Address",indiaBoundaryUrl:p,enableSearch:m=!0,enablePhoneAuth:f=!1,merchantId:y="",supabaseFunctionBaseUrl:b="",brandColor:v,logoUrl:g,headerBanner:_,onCheckoutEvent:w,enableCod:N=!1,codCartTotalPaise:C,codSessionToken:x="",enableEmailAuth:E=!1,variant:S,utmParams:P,enablePayment:I=!1,paymentAmountPaise:A,onPaymentComplete:B,enablePrepaidNudge:M=!1,prepaidNudgeCopy:F,prepaidNudgeCtaUrl:U})=>{const j=f?"phone":E?"email":"none",W="phone"===j?"phone":"email"===j?"email":"map",z=Boolean(I&&A&&b),[V,H]=n.useState(W),[K,G]=n.useState(null),[X,ne]=n.useState(null),[te,oe]=n.useState(null),[de,ce]=n.useState(""),[ue,he]=n.useState(!1),[pe,me]=n.useState(!1),[fe,ye]=n.useState(null),[be,ve]=n.useState(null),ge=n.useRef(V),_e=n.useMemo(()=>P??le(),[P]),qe=n.useMemo(()=>ie(),[]),we=n.useMemo(()=>({utm_source:_e.utm_source,utm_medium:_e.utm_medium,utm_campaign:_e.utm_campaign,device_type:qe.deviceType,platform:qe.platform,user_agent:qe.userAgent,experiment_variant:S}),[_e,qe,S]),Ne={functionBaseUrl:b,merchantId:y},ke=(null==te?void 0:te.sessionToken)||x
|
|
236
|
+
n.useEffect(()=>{ge.current=V},[V])
|
|
237
|
+
const Ce=n.useCallback(e=>{const r={...e,sessionId:e.sessionId??(null==te?void 0:te.sessionId),buyerId:e.buyerId??(null==te?void 0:te.buyerId),authChannel:e.authChannel??("phone"===j?"phone":"email"===j?"email":"none"),deviceType:e.deviceType??qe.deviceType,platform:e.platform??qe.platform,userAgent:e.userAgent??qe.userAgent,experimentVariant:e.experimentVariant??S,timestamp:(new Date).toISOString()}
|
|
238
|
+
if(w)try{w(r)}catch{}y&&b&&$(Ne,{event_type:r.type,step:r.step,buyer_id:r.buyerId,auth_channel:r.authChannel,device_type:r.deviceType,platform:r.platform,user_agent:r.userAgent,payment_method:r.paymentMethod,experiment_variant:r.experimentVariant},null==te?void 0:te.sessionToken).catch(()=>{})},[te,j,qe,S,w,y,b,Ne])
|
|
237
239
|
n.useEffect(()=>{if(!y||!b)return
|
|
238
|
-
const e=()=>{"done"!==
|
|
239
|
-
return window.addEventListener("pagehide",e),()=>window.removeEventListener("pagehide",e)},[null==te?void 0:te.sessionToken,y,b,
|
|
240
|
-
const
|
|
240
|
+
const e=()=>{"done"!==ge.current&&(null==te?void 0:te.sessionToken)&&(O(Ne,te.sessionToken,ge.current).catch(()=>{}),Ce({type:"session_abandoned",step:ge.current}))}
|
|
241
|
+
return window.addEventListener("pagehide",e),()=>window.removeEventListener("pagehide",e)},[null==te?void 0:te.sessionToken,y,b,Ne,Ce]),n.useEffect(()=>{(null==te?void 0:te.sessionToken)&&y&&b&&D(Ne,te.sessionToken).then(ye).catch(()=>ye(null))},[null==te?void 0:te.sessionToken,y,b,Ne])
|
|
242
|
+
const xe=n.useMemo(()=>function(e,r){const n=null==r?void 0:r.trim()
|
|
241
243
|
if(!n)return e
|
|
242
244
|
const a={"--qr-primary":n,"--qr-primary-dark":n,"--qr-border-focus":n,"--qr-primary-light":`color-mix(in srgb, ${n} 18%, white)`}
|
|
243
|
-
return e?{...e,...a}:a}(c,v),[c,v]),
|
|
244
|
-
try{await L(
|
|
245
|
+
return e?{...e,...a}:a}(c,v),[c,v]),Ee=()=>{Ce({type:"auth_skipped",step:"map"}),H("map")},Se=async e=>{if(ne(e),Ce({type:"address_completed",step:z?"payment":"done",digipin:e.digipin,buyerId:null==te?void 0:te.buyerId}),null==te?void 0:te.sessionToken){T(Ne,te.sessionToken,{pincode:e.pincode,digipin:e.digipin,state:e.state,district:e.district,locality:e.locality}).catch(()=>{})
|
|
246
|
+
try{await L(Ne,te.sessionToken,{digipin:e.digipin,lat:e.lat,lng:e.lng,state:e.state,district:e.district,locality:e.locality,pincode:e.pincode,delivery_status:e.delivery,flat_number:e.flatNumber,floor_number:e.floorNumber,building_name:e.buildingName,street_name:e.streetName,full_address_json:e,label:"home",is_default:!0})}catch{}}z&&ke?H("payment"):(H("done"),t(e))}
|
|
245
247
|
n.useEffect(()=>{const e={phone:"phone_step_viewed",email:"email_step_viewed",saved:"saved_addresses_viewed",map:"map_step_viewed",form:"form_step_viewed",payment:"payment_step_viewed"}[V]
|
|
246
|
-
e&&
|
|
247
|
-
const
|
|
248
|
+
e&&Ce({type:e,step:V,buyerId:null==te?void 0:te.buyerId})},[V]),n.useEffect(()=>{E&&"email"===j&&(y&&b||null==i||i(new Error("enableEmailAuth requires merchantId and supabaseFunctionBaseUrl on CheckoutWidget.")))},[E,j,y,b,i])
|
|
249
|
+
const Le=function(e,r,n){if("none"===r){if(n){const r=["map","form","payment","done"].indexOf(e)
|
|
248
250
|
return-1===r?0:r}return"map"===e?0:"form"===e?1:2}const a=("email"===r?n?["email","email-otp","saved","map","form","payment","done"]:["email","email-otp","saved","map","form","done"]:n?["phone","otp","saved","map","form","payment","done"]:["phone","otp","saved","map","form","done"]).indexOf(e)
|
|
249
|
-
return-1===a?0:a}(V,j,z),
|
|
250
|
-
return r.jsxs("div",{className:`qr-checkout qr-checkout--${s} ${d}`,style:
|
|
251
|
-
return r.jsx("div",{className:"qr-progress",role:"progressbar","aria-valuenow":
|
|
251
|
+
return-1===a?0:a}(V,j,z),Pe=function(e,r){return"none"===e?r?3:2:r?6:5}(j,z)
|
|
252
|
+
return r.jsxs("div",{className:`qr-checkout qr-checkout--${s} ${d}`,style:xe,"data-testid":"quantaroute-checkout",children:["done"!==V&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"qr-header",children:[r.jsxs("div",{className:"qr-header__brand",children:[g?r.jsx("img",{src:g,alt:"",className:"qr-header__logo-img",width:28,height:28,decoding:"async"}):r.jsxs("svg",{className:"qr-header__logo","aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0118 0z"}),r.jsx("circle",{cx:"12",cy:"10",r:"3"})]}),r.jsx("span",{className:"qr-header__title",children:h})]}),(()=>{const e=Array.from({length:Pe+1},(e,r)=>r)
|
|
253
|
+
return r.jsx("div",{className:"qr-progress",role:"progressbar","aria-valuenow":Le+1,"aria-valuemin":1,"aria-valuemax":Pe+1,"aria-label":`Step ${Le+1} of ${Pe+1}`,children:e.map(e=>r.jsxs(n.Fragment,{children:[r.jsx("div",{className:"qr-progress__dot"+(Le>=e?" qr-progress__dot--active":"")}),e<Pe&&r.jsx("div",{className:"qr-progress__line"+(Le>e?" qr-progress__line--active":"")})]},e))})})()]}),_?r.jsx("div",{className:"qr-header-banner",role:"region","aria-label":"Merchant message",children:_}):null,fe?r.jsxs("div",{className:"qr-offer-banner",role:"region","aria-label":"Special offer",children:[fe.banner_copy,fe.banner_cta_url?r.jsxs(r.Fragment,{children:[" ",r.jsx("a",{href:fe.banner_cta_url,target:"_blank",rel:"noopener noreferrer",children:"Learn more"})]}):null]}):null]}),"email"===V&&E&&r.jsx(re,{onOtpSent:(e,r)=>{ce(e),he(Boolean(null==r?void 0:r.reused)),Ce({type:"email_otp_sent",step:"email-otp",mobile:e}),H("email-otp")},onSkip:Ee,functionBaseUrl:b,merchantId:y}),"email-otp"===V&&E&&de&&r.jsx(ae,{email:de,codeReused:ue,onVerified:(e,r,n)=>{oe({mobile:de,sessionToken:e,sessionId:n??"",buyerId:r}),Ce({type:"email_verified",step:"saved",buyerId:r,sessionId:n}),H("saved")},onBack:()=>H("email"),functionBaseUrl:b,merchantId:y,sessionContext:we}),"phone"===V&&f&&r.jsx(R,{onOtpSent:e=>{oe(r=>({mobile:e,sessionToken:"",sessionId:"",buyerId:(null==r?void 0:r.buyerId)??""})),Ce({type:"otp_sent",step:"otp",mobile:e}),H("otp")},onSkip:Ee,functionBaseUrl:b,merchantId:y}),"otp"===V&&te&&r.jsx(J,{mobile:te.mobile,onVerified:(e,r,n)=>{oe({mobile:(null==te?void 0:te.mobile)??"",sessionToken:e,sessionId:n??"",buyerId:r}),Ce({type:"phone_verified",step:"saved",buyerId:r,sessionId:n}),H("saved")},onBack:()=>H("phone"),functionBaseUrl:b,merchantId:y,sessionContext:we}),"saved"===V&&(null==te?void 0:te.sessionToken)&&r.jsx(Z,{sessionToken:te.sessionToken,functionBaseUrl:b,merchantId:y,onSelectAddress:e=>{Ce({type:"saved_address_selected",step:z?"payment":"done",buyerId:null==te?void 0:te.buyerId,digipin:e.digipin}),(null==te?void 0:te.sessionToken)&&T(Ne,te.sessionToken,{pincode:e.pincode,digipin:e.digipin,state:e.state,district:e.district,locality:e.locality}).catch(()=>{})
|
|
252
254
|
const r={digipin:e.digipin,lat:e.lat,lng:e.lng,state:e.state,district:e.district,division:"",locality:e.locality,pincode:e.pincode,delivery:e.delivery_status,country:"India",flatNumber:e.flat_number,floorNumber:e.floor_number,buildingName:e.building_name,streetName:e.street_name,formattedAddress:[e.flat_number,e.building_name,e.street_name,e.locality,e.district,e.state,e.pincode].filter(Boolean).join(", ")}
|
|
253
|
-
|
|
255
|
+
Se(r)},onAddNew:()=>H("map")}),"map"===V&&r.jsx(q,{onLocationConfirm:(e,r,n)=>{G({lat:e,lng:r,digipin:n}),Ce({type:"location_confirmed",step:"form",digipin:n,buyerId:null==te?void 0:te.buyerId}),H("form")},defaultLat:o,defaultLng:l,mapHeight:u,theme:s,indiaBoundaryUrl:p,enableSearch:m,apiKey:e,apiBaseUrl:a,brandColor:v}),"form"===V&&K&&r.jsx(k,{digipin:K.digipin,lat:K.lat,lng:K.lng,apiKey:e,apiBaseUrl:a,onAddressComplete:async e=>{await Se(e)},onBack:()=>{"form"===V?H("map"):"map"===V&&(null==te?void 0:te.sessionToken)?H("saved"):"email-otp"===V&&H("email")},onError:i,theme:s}),"payment"===V&&z&&ke&&A&&r.jsx(ee,{checkoutConfig:Ne,sessionToken:ke,sessionId:null==te?void 0:te.sessionId,amountPaise:A,enableCod:N,codAllowed:pe,theme:s,onComplete:e=>{ve(e),Ce({type:"payment_method_selected",step:"done",paymentMethod:e}),H("done"),X&&t(X),null==B||B({paymentMethod:e,sessionId:null==te?void 0:te.sessionId})},onBack:()=>H("form"),onEvent:(e,r)=>Ce({type:e,step:"payment",paymentMethod:r,buyerId:null==te?void 0:te.buyerId})}),"done"===V&&X&&r.jsxs(r.Fragment,{children:[r.jsx(se,{address:X,onEditAddress:()=>{Ce({type:"widget_reset",step:W}),H(W),G(null),ne(null)}}),be?r.jsxs("p",{className:"qr-cod-banner__text qr-cod-banner__text--ok",style:{textAlign:"center",margin:"8px 16px"},children:["Paid via ","cod"===be?"Cash on Delivery":"online payment"]}):null,N&&y&&b&&ke?r.jsxs(r.Fragment,{children:[r.jsx(Y,{checkoutConfig:Ne,sessionToken:ke,pincode:X.pincode,cartTotalPaise:C??A,theme:s,onCodAllowedChange:me}),M&&pe?r.jsx(Q,{copy:F??"Save more when you pay online — faster delivery & exclusive offers.",ctaUrl:U,theme:s}):null]}):null]}),r.jsxs("div",{className:"qr-footer",children:[r.jsx("span",{children:"Powered by"}),r.jsx("a",{href:"https://quantaroute.com",target:"_blank",rel:"noopener noreferrer",className:"qr-footer__link",children:"QuantaRoute"}),r.jsx("span",{className:"qr-footer__flag","aria-label":"Made in India",children:"🇮🇳"})]})]})}
|
|
254
256
|
e.AddressForm=k,e.CheckoutWidget=de,e.CodAvailabilityBanner=Y,e.DIGIPIN_BOUNDS=i,e.EmailOtpStep=ae,e.EmailStep=re,e.MapPinSelector=q,e.OtpStep=J,e.PaymentStep=ee,e.PhoneStep=R,e.PrepaidNudge=Q,e.SavedAddressStep=Z,e.autocompleteAddress=y,e.captureUtmFromUrl=le,e.checkCodEligibility=M,e.createAddress=L,e.createPaymentOrder=F,e.default=de,e.deleteAddress=P,e.detectDeviceType=te,e.detectPlatform=function(){return"web"},e.fetchPrepaidNudgeConfig=async function(e,r){const n=await fetch(`${e}/checkout-admin?action=cod_config`,{headers:{"x-api-key":r}}),a=await n.json().catch(()=>({}))
|
|
255
257
|
return n.ok&&a.success?{prepaid_nudge_copy:a.data.prepaid_nudge_copy,prepaid_nudge_cta_url:a.data.prepaid_nudge_cta_url}:null},e.fetchSessionOffer=D,e.getDigiPin=o,e.getLatLngFromDigiPin=l,e.getWebDeviceContext=ie,e.hasUtmParams=function(e){return Boolean(e.utm_source||e.utm_medium||e.utm_campaign)},e.isValidDigiPin=function(e){if(!e||"string"!=typeof e)return!1
|
|
256
258
|
if(!/^[A-Z0-9]{3}-[A-Z0-9]{3}-[A-Z0-9]{4}$/i.test(e.trim()))return!1
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quantaroute/checkout",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.1",
|
|
4
4
|
"description": "Embeddable DigiPin-powered smart address checkout widget — React (web), React Native & Expo (iOS/Android)",
|
|
5
5
|
"main": "./dist/lib/quantaroute-checkout.umd.js",
|
|
6
6
|
"module": "./dist/lib/quantaroute-checkout.es.js",
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
"expo-plugin.js",
|
|
27
27
|
"babel.config.js",
|
|
28
28
|
"README.md",
|
|
29
|
+
"CHANGELOG.md",
|
|
29
30
|
"LICENSE"
|
|
30
31
|
],
|
|
31
32
|
"scripts": {
|
|
@@ -180,6 +180,7 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
|
|
|
180
180
|
const [completedAddress, setCompletedAddress] = useState<CompleteAddress | null>(null);
|
|
181
181
|
const [auth, setAuth] = useState<AuthState | null>(null);
|
|
182
182
|
const [emailPending, setEmailPending] = useState('');
|
|
183
|
+
const [emailCodeReused, setEmailCodeReused] = useState(false);
|
|
183
184
|
const [codAllowed, setCodAllowed] = useState(false);
|
|
184
185
|
const [sessionOffer, setSessionOffer] = useState<SessionOffer | null>(null);
|
|
185
186
|
const [paymentMethod, setPaymentMethod] = useState<string | null>(null);
|
|
@@ -323,8 +324,9 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
|
|
|
323
324
|
|
|
324
325
|
// ── Email step callbacks ──────────────────────────────────────────────────
|
|
325
326
|
|
|
326
|
-
const handleEmailOtpSent = (sentEmail: string) => {
|
|
327
|
+
const handleEmailOtpSent = (sentEmail: string, info?: { reused?: boolean }) => {
|
|
327
328
|
setEmailPending(sentEmail);
|
|
329
|
+
setEmailCodeReused(Boolean(info?.reused));
|
|
328
330
|
emit({ type: 'email_otp_sent', step: 'email-otp', mobile: sentEmail });
|
|
329
331
|
setStep('email-otp');
|
|
330
332
|
};
|
|
@@ -591,6 +593,7 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
|
|
|
591
593
|
{step === 'email-otp' && enableEmailAuth && emailPending && (
|
|
592
594
|
<EmailOtpStep
|
|
593
595
|
email={emailPending}
|
|
596
|
+
codeReused={emailCodeReused}
|
|
594
597
|
onVerified={handleEmailVerified}
|
|
595
598
|
onBack={() => setStep('email')}
|
|
596
599
|
functionBaseUrl={supabaseFunctionBaseUrl}
|
|
@@ -14,6 +14,7 @@ function maskEmail(email: string): string {
|
|
|
14
14
|
|
|
15
15
|
const EmailOtpStep: React.FC<EmailOtpStepProps> = ({
|
|
16
16
|
email,
|
|
17
|
+
codeReused = false,
|
|
17
18
|
onVerified,
|
|
18
19
|
onBack,
|
|
19
20
|
functionBaseUrl,
|
|
@@ -138,7 +139,9 @@ const EmailOtpStep: React.FC<EmailOtpStepProps> = ({
|
|
|
138
139
|
|
|
139
140
|
<h3 className="qr-auth-step__title">Check your email</h3>
|
|
140
141
|
<p className="qr-auth-step__sub">
|
|
141
|
-
|
|
142
|
+
{codeReused
|
|
143
|
+
? <>Use the code we sent earlier — it's still valid for your next checkout.</>
|
|
144
|
+
: <>6-digit code sent to <strong>{maskEmail(email)}</strong></>}
|
|
142
145
|
</p>
|
|
143
146
|
|
|
144
147
|
<div className="qr-otp-boxes" role="group" aria-label="Enter verification code">
|
|
@@ -28,8 +28,8 @@ const EmailStep: React.FC<EmailStepProps> = ({
|
|
|
28
28
|
setLoading(true);
|
|
29
29
|
setError(null);
|
|
30
30
|
try {
|
|
31
|
-
await sendEmailOtp({ functionBaseUrl, merchantId }, email);
|
|
32
|
-
onOtpSent(email.toLowerCase());
|
|
31
|
+
const { reused } = await sendEmailOtp({ functionBaseUrl, merchantId }, email);
|
|
32
|
+
onOtpSent(email.toLowerCase(), { reused });
|
|
33
33
|
} catch (err: unknown) {
|
|
34
34
|
setError(err instanceof Error ? err.message : 'Failed to send code. Please try again.');
|
|
35
35
|
} finally {
|
package/src/core/checkout-api.ts
CHANGED
|
@@ -206,11 +206,16 @@ export async function notifyAddressCompleted(
|
|
|
206
206
|
|
|
207
207
|
// ─── Email OTP auth ───────────────────────────────────────────────────────────
|
|
208
208
|
|
|
209
|
+
/** Result from send email OTP — includes whether an existing code was reused (no new email). */
|
|
210
|
+
export interface SendEmailOtpResult {
|
|
211
|
+
reused: boolean;
|
|
212
|
+
}
|
|
213
|
+
|
|
209
214
|
/** Send a 6-digit OTP to the given email via Resend (Edge: `checkout-email-otp`). */
|
|
210
215
|
export async function sendEmailOtp(
|
|
211
216
|
config: CheckoutApiConfig,
|
|
212
217
|
email: string
|
|
213
|
-
): Promise<
|
|
218
|
+
): Promise<SendEmailOtpResult> {
|
|
214
219
|
const res = await fetch(`${config.functionBaseUrl}/checkout-email-otp`, {
|
|
215
220
|
method: 'POST',
|
|
216
221
|
headers: { 'Content-Type': 'application/json' },
|
|
@@ -220,6 +225,7 @@ export async function sendEmailOtp(
|
|
|
220
225
|
if (!res.ok || !data.success) {
|
|
221
226
|
throw new Error(data.error ?? 'Failed to send OTP. Please try again.');
|
|
222
227
|
}
|
|
228
|
+
return { reused: Boolean(data.reused) };
|
|
223
229
|
}
|
|
224
230
|
|
|
225
231
|
export interface VerifyEmailOtpResult {
|
package/src/core/types.ts
CHANGED
|
@@ -339,8 +339,8 @@ export interface OtpStepProps {
|
|
|
339
339
|
}
|
|
340
340
|
|
|
341
341
|
export interface EmailStepProps {
|
|
342
|
-
/** Called with the normalised (lowercased) email once OTP is
|
|
343
|
-
onOtpSent: (email: string) => void;
|
|
342
|
+
/** Called with the normalised (lowercased) email once OTP is ready (sent or reused). */
|
|
343
|
+
onOtpSent: (email: string, info?: { reused?: boolean }) => void;
|
|
344
344
|
onSkip: () => void;
|
|
345
345
|
functionBaseUrl: string;
|
|
346
346
|
merchantId: string;
|
|
@@ -348,6 +348,8 @@ export interface EmailStepProps {
|
|
|
348
348
|
|
|
349
349
|
export interface EmailOtpStepProps {
|
|
350
350
|
email: string;
|
|
351
|
+
/** When true, no new email was sent — shopper should use their existing code. */
|
|
352
|
+
codeReused?: boolean;
|
|
351
353
|
onVerified: (sessionToken: string, buyerId: string, sessionId?: string) => void;
|
|
352
354
|
onBack: () => void;
|
|
353
355
|
functionBaseUrl: string;
|