@ticketboothapp/booking 0.1.11 → 0.1.13
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/package.json +2 -1
- package/src/app/photo-sessions/photo-packages.ts +75 -0
- package/src/assets/icons/partner-logos/getyourguide.svg +8 -0
- package/src/assets/icons/plus.svg +3 -0
- package/src/colours.css +23 -0
- package/src/components/BookingDetails.module.css +1591 -0
- package/src/components/BookingDetails.tsx +2072 -354
- package/src/components/BookingWidget.tsx +28 -248
- package/src/components/JobApplicationDialog.module.css +440 -0
- package/src/components/JobApplicationDialog.tsx +620 -0
- package/src/components/ManageBookingView.tsx +28 -36
- package/src/components/PhoneInputWithCountry.module.css +131 -0
- package/src/components/PhoneInputWithCountry.tsx +44 -0
- package/src/components/PickupLocationDialog.module.css +360 -0
- package/src/components/PickupLocationDialog.tsx +357 -0
- package/src/components/PickupLocationMap.tsx +110 -0
- package/src/components/PostBookingDependentAddOnUpsell.module.css +174 -0
- package/src/components/PostBookingDependentAddOnUpsell.tsx +407 -0
- package/src/components/accordion.css +27 -0
- package/src/components/accordion.tsx +29 -0
- package/src/components/analytics/AnalyticsConsentRestore.tsx +19 -0
- package/src/components/analytics/AnalyticsScripts.tsx +106 -0
- package/src/components/analytics/CookieConsentBanner.css +86 -0
- package/src/components/analytics/CookieConsentBanner.tsx +102 -0
- package/src/components/booking/AddOnsSection.module.css +10 -0
- package/src/components/booking/AddOnsSection.tsx +184 -0
- package/src/components/booking/AdminPaymentChoiceModal.tsx +98 -0
- package/src/components/booking/BookingDialog.module.css +643 -0
- package/src/components/booking/BookingDialog.tsx +356 -0
- package/src/components/booking/BookingFlow.tsx +4385 -0
- package/src/components/booking/BookingFlowCollage.module.css +148 -0
- package/src/components/booking/BookingFlowCollage.tsx +184 -0
- package/src/components/booking/BookingFlowPlaceholder.module.css +27 -0
- package/src/components/booking/BookingFlowPlaceholder.tsx +25 -0
- package/src/components/booking/BookingFlowPreview.tsx +51 -0
- package/src/components/booking/BookingProductGrid.module.css +359 -0
- package/src/components/booking/BookingProductGrid.tsx +497 -0
- package/src/components/booking/Calendar.module.css +616 -0
- package/src/components/{Calendar.tsx → booking/Calendar.tsx} +464 -247
- package/src/components/booking/CancellationPolicySelector.module.css +124 -0
- package/src/components/booking/CancellationPolicySelector.tsx +142 -0
- package/src/components/booking/ChangeBookingDialog.tsx +562 -0
- package/src/components/booking/CheckoutForm.module.css +244 -0
- package/src/components/booking/CheckoutForm.tsx +364 -0
- package/src/components/{CheckoutModal.tsx → booking/CheckoutModal.tsx} +176 -19
- package/src/components/booking/DapFlowCollage.tsx +88 -0
- package/src/components/booking/DapTourDescription.tsx +35 -0
- package/src/components/booking/DependentAddOnBookingDialog.tsx +1350 -0
- package/src/components/booking/DependentAddOnPaymentForm.tsx +124 -0
- package/src/components/booking/InfoTooltip.tsx +108 -0
- package/src/components/booking/ItineraryBox.module.css +258 -0
- package/src/components/booking/ItineraryBox.tsx +550 -0
- package/src/components/{ItineraryBuilder.tsx → booking/ItineraryBuilder.tsx} +1 -2
- package/src/components/booking/ItineraryPlaceholder.module.css +45 -0
- package/src/components/booking/ItineraryPlaceholder.tsx +26 -0
- package/src/components/{MealDrinkAddOnSelector.tsx → booking/MealDrinkAddOnSelector.tsx} +21 -13
- package/src/components/booking/PickupLocationSelector.module.css +124 -0
- package/src/components/{PickupLocationSelector.tsx → booking/PickupLocationSelector.tsx} +315 -290
- package/src/components/booking/PickupTimeSelector.module.css +134 -0
- package/src/components/booking/PickupTimeSelector.tsx +112 -0
- package/src/components/{PriceBreakdown.tsx → booking/PriceBreakdown.tsx} +3 -3
- package/src/components/{PriceSummary.tsx → booking/PriceSummary.tsx} +51 -28
- package/src/components/booking/PrivateShuttleBookingFlow.module.css +357 -0
- package/src/components/booking/PrivateShuttleBookingFlow.tsx +2662 -0
- package/src/components/booking/PromoCodeInput.module.css +166 -0
- package/src/components/booking/PromoCodeInput.tsx +99 -0
- package/src/components/booking/ReturnTimeSelector.module.css +173 -0
- package/src/components/booking/ReturnTimeSelector.tsx +145 -0
- package/src/components/{TermsAcceptance.tsx → booking/TermsAcceptance.tsx} +9 -8
- package/src/components/booking/TicketSelector.module.css +164 -0
- package/src/components/booking/TicketSelector.tsx +199 -0
- package/src/components/booking/TourDescription.module.css +304 -0
- package/src/components/booking/TourDescription.tsx +273 -0
- package/src/components/booking/booking-flow-ui.ts +15 -1
- package/src/components/booking/booking-flow.css +944 -0
- package/src/components/bottom-sheet.module.css +78 -0
- package/src/components/bottom-sheet.tsx +60 -0
- package/src/components/breadcrumb.module.css +40 -0
- package/src/components/breadcrumb.tsx +36 -0
- package/src/components/button.css +245 -0
- package/src/components/button.tsx +152 -0
- package/src/components/client-bottom-sheet.tsx +14 -0
- package/src/components/colorable-svg.tsx +29 -0
- package/src/components/conditional-footer.tsx +27 -0
- package/src/components/contact-us.module.css +147 -0
- package/src/components/contact-us.tsx +49 -0
- package/src/components/email-signup.css +151 -0
- package/src/components/email-signup.tsx +63 -0
- package/src/components/faq-wrapper.module.css +47 -0
- package/src/components/faq-wrapper.tsx +15 -0
- package/src/components/footer.css +187 -0
- package/src/components/footer.tsx +143 -0
- package/src/components/global-simple-modal.tsx +33 -0
- package/src/components/google-review-summary.module.css +77 -0
- package/src/components/google-review-summary.tsx +50 -0
- package/src/components/hero-image.css +13 -0
- package/src/components/hero-image.tsx +44 -0
- package/src/components/image.css +29 -0
- package/src/components/image.tsx +113 -0
- package/src/components/language-aware-link.tsx +72 -0
- package/src/components/language-switcher.module.css +124 -0
- package/src/components/language-switcher.tsx +75 -0
- package/src/components/map-section.css +59 -0
- package/src/components/map-section.tsx +63 -0
- package/src/components/navbar.module.css +152 -0
- package/src/components/navbar.tsx +125 -0
- package/src/components/parallax-provider.tsx +11 -0
- package/src/components/partner/PartnerBookingPage.module.css +130 -0
- package/src/components/partner/PartnerBookingPage.tsx +390 -0
- package/src/components/partner/PartnerBookingPageWithBrowserMetadata.tsx +19 -35
- package/src/components/product-tag.module.css +30 -0
- package/src/components/product-tag.tsx +34 -0
- package/src/components/product-theme-pages/best-option.module.css +70 -0
- package/src/components/product-theme-pages/best-option.tsx +35 -0
- package/src/components/product-theme-pages/extended-tour-options.module.css +22 -0
- package/src/components/product-theme-pages/extended-tour-options.tsx +11 -0
- package/src/components/product-theme-pages/image-modal.tsx +248 -0
- package/src/components/product-theme-pages/photo-gallery.module.css +200 -0
- package/src/components/product-theme-pages/photo-gallery.tsx +90 -0
- package/src/components/product-theme-pages/product-theme-page-layout.module.css +13 -0
- package/src/components/product-theme-pages/product-theme-page-layout.tsx +67 -0
- package/src/components/product-theme-pages/top-of-fold.module.css +179 -0
- package/src/components/product-theme-pages/top-of-fold.tsx +80 -0
- package/src/components/product-tile/image-only-product-tile-desktop.module.css +106 -0
- package/src/components/product-tile/image-only-product-tile-desktop.tsx +56 -0
- package/src/components/product-tile/image-only-product-tile-mobile.module.css +122 -0
- package/src/components/product-tile/image-only-product-tile-mobile.tsx +89 -0
- package/src/components/product-tile/image-only-product-tile.tsx +44 -0
- package/src/components/product-tile/product-tile-card.module.css +84 -0
- package/src/components/product-tile/product-tile-card.tsx +61 -0
- package/src/components/review-highlights-section.css +85 -0
- package/src/components/review-highlights-section.tsx +127 -0
- package/src/components/season-closure-overlay.module.css +99 -0
- package/src/components/season-closure-overlay.tsx +98 -0
- package/src/components/simple-modal.tsx +69 -0
- package/src/components/simple-top-of-fold.module.css +76 -0
- package/src/components/simple-top-of-fold.tsx +34 -0
- package/src/components/spacer.css +41 -0
- package/src/components/spacer.tsx +23 -0
- package/src/components/star-rating.module.css +74 -0
- package/src/components/star-rating.tsx +48 -0
- package/src/components/terms/TermsContent.tsx +178 -0
- package/src/components/title-subtitle.module.css +10 -0
- package/src/components/title-subtitle.tsx +30 -0
- package/src/components/translatable-reviews.tsx +75 -0
- package/src/components/value-pill.module.css +59 -0
- package/src/components/value-pill.tsx +46 -0
- package/src/components/value-props.css +185 -0
- package/src/components/value-props.tsx +88 -0
- package/src/constants/booking-guide-quiz.ts +64 -0
- package/src/constants/contact-info.ts +2 -0
- package/src/constants/faq.ts +44 -0
- package/src/constants/images.ts +556 -0
- package/src/constants/json-ld/faq-json-ld.tsx +170 -0
- package/src/constants/json-ld/homepage-json-ld.tsx +138 -0
- package/src/constants/json-ld/job-posting-json-ld.tsx +92 -0
- package/src/constants/json-ld/organization-json-ld.tsx +62 -0
- package/src/constants/json-ld/page-json-ld.tsx +6 -0
- package/src/constants/json-ld/product-json-ld.tsx +154 -0
- package/src/constants/json-ld/review-json-ld.tsx +377 -0
- package/src/constants/navigation-links/footer-links.ts +48 -0
- package/src/constants/navigation-links/nav-bar-links.ts +41 -0
- package/src/constants/navigation-links/navigation-link.ts +6 -0
- package/src/constants/pill-values.ts +210 -0
- package/src/constants/products.ts +155 -0
- package/src/constants/quiz-recommendations.ts +506 -0
- package/src/constants/reviews.ts +75 -0
- package/src/constants/staff.ts +197 -0
- package/src/constants/value-props.ts +58 -0
- package/src/data/dap-descriptions/session-couples-families-friends.en.json +61 -0
- package/src/data/dap-descriptions/session-elopements.en.json +60 -0
- package/src/data/dap-descriptions/session-proposals.en.json +60 -0
- package/src/data/product-descriptions/afternoon-delight.en.json +35 -0
- package/src/data/product-descriptions/emerald-lake-escape.en.json +68 -0
- package/src/data/product-descriptions/lake-louise-adventure.en.json +74 -0
- package/src/data/product-descriptions/moraine-lake-adventure.en.json +78 -0
- package/src/data/product-descriptions/moraine-lake-sunrise-lake-louise-golden-hour.en.json +65 -0
- package/src/data/product-descriptions/moraine-lake-sunrise.en.json +64 -0
- package/src/data/product-descriptions/private-tour.en.json +80 -0
- package/src/data/product-descriptions/two-lakes-combo.en.json +65 -0
- package/src/data/products-config.json +101 -0
- package/src/hooks/use-bottom-sheet.tsx +15 -0
- package/src/hooks/use-simple-modal.tsx +27 -0
- package/src/hooks/useBookingSourceMetadataFromLocation.ts +21 -0
- package/src/hooks/useEmailSubscription.tsx +103 -0
- package/src/hooks/useEmbeddedInIframe.ts +16 -0
- package/src/hooks/useIsBookingLaunchLive.ts +49 -0
- package/src/hooks/useQuiz.tsx +210 -0
- package/src/index.ts +27 -2
- package/src/lib/analytics.ts +197 -0
- package/src/lib/booking/booking-source.ts +20 -2
- package/src/lib/{checkout-breakdown.ts → booking/checkout-breakdown.ts} +1 -1
- package/src/lib/booking/correlation-id.ts +46 -0
- package/src/lib/{i18n → booking/i18n}/messages/en.json +48 -4
- package/src/lib/{i18n → booking/i18n}/messages/fr.json +48 -4
- package/src/lib/booking/itinerary-display.ts +36 -0
- package/src/lib/{itinerary-labels.ts → booking/itinerary-labels.ts} +1 -1
- package/src/lib/{location-calculations.ts → booking/location-calculations.ts} +4 -4
- package/src/lib/{location-utils.ts → booking/location-utils.ts} +26 -0
- package/src/lib/{map-utils.ts → booking/map-utils.ts} +3 -3
- package/src/lib/booking/normalize-booking-product-id.ts +7 -0
- package/src/lib/{pickup-location-types.ts → booking/pickup-location-types.ts} +2 -2
- package/src/lib/{pricing.ts → booking/pricing.ts} +2 -2
- package/src/lib/booking/product-option-id.ts +35 -0
- package/src/lib/booking/source-metadata.ts +72 -7
- package/src/lib/booking/sunday-week.ts +14 -0
- package/src/lib/booking/trace-context.ts +62 -0
- package/src/lib/booking-api.ts +1793 -0
- package/src/lib/{constants.ts → booking-constants.ts} +11 -5
- package/src/lib/booking-types.ts +36 -0
- package/src/lib/currency.ts +38 -45
- package/src/lib/dap-descriptions.ts +50 -0
- package/src/lib/dap-itinerary-preview.ts +315 -0
- package/src/lib/dependent-add-on-api.ts +434 -0
- package/src/lib/env.ts +89 -5
- package/src/lib/firebase.ts +20 -0
- package/src/lib/job-application-api.ts +83 -0
- package/src/lib/manage-booking-embed-print.ts +16 -0
- package/src/lib/manage-booking-post-checkout.ts +68 -0
- package/src/lib/photo-dap-config.ts +228 -0
- package/src/lib/pickup/map-utils.ts +56 -0
- package/src/lib/pickup/marker-icons.ts +19 -0
- package/src/lib/product-descriptions.ts +66 -0
- package/src/lib/products-config.ts +73 -0
- package/src/providers/booking-dialog-provider.tsx +107 -38
- package/src/providers/bottom-sheet-provider.tsx +40 -0
- package/src/providers/dependent-add-on-dialog-provider.tsx +105 -0
- package/src/radius.css +5 -0
- package/src/spacing.css +7 -0
- package/src/strings/en.json +1774 -0
- package/src/strings/es.json +1573 -0
- package/src/strings/fr.json +1573 -0
- package/src/strings/index.js +23 -0
- package/src/text-style.css +97 -0
- package/src/types/fareharbor.d.ts +12 -0
- package/src/types/quiz.ts +59 -0
- package/src/utils/currency-converter.ts +101 -0
- package/src/components/BookingFlow.tsx +0 -2952
- package/src/components/LanguageSwitcher.tsx +0 -30
- package/src/components/PrivateShuttleBookingFlow.tsx +0 -2290
- package/src/components/ProductList.tsx +0 -78
- package/src/components/WhatsAppPhoneInput.tsx +0 -224
- package/src/components/index.ts +0 -31
- package/src/lib/api.ts +0 -801
- package/src/lib/booking-api-auth.ts +0 -9
- package/src/lib/checkout-breakdown.test.ts +0 -70
- package/src/types/google-maps.d.ts +0 -2
- /package/src/components/{CurrencySwitcher.tsx → booking/CurrencySwitcher.tsx} +0 -0
- /package/src/components/{ErrorBoundary.tsx → booking/ErrorBoundary.tsx} +0 -0
- /package/src/lib/{i18n → booking/i18n}/config.ts +0 -0
- /package/src/lib/{i18n → booking/i18n}/index.tsx +0 -0
- /package/src/lib/{marker-icons.ts → booking/marker-icons.ts} +0 -0
- /package/src/lib/{places-api.ts → booking/places-api.ts} +0 -0
- /package/src/lib/{theme.ts → booking/theme.ts} +0 -0
- /package/src/lib/{utils.ts → booking/utils.ts} +0 -0
|
@@ -0,0 +1,4385 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import { useState, useEffect, useMemo, useRef, useCallback } from 'react';
|
|
4
|
+
import { parseISO, addWeeks, format, isBefore, isAfter, startOfDay, endOfDay } from 'date-fns';
|
|
5
|
+
import { formatInTimeZone, fromZonedTime } from 'date-fns-tz';
|
|
6
|
+
import {
|
|
7
|
+
getAvailabilities,
|
|
8
|
+
createReservation,
|
|
9
|
+
cancelReservation,
|
|
10
|
+
cancelReservationBestEffort,
|
|
11
|
+
createPaymentIntent,
|
|
12
|
+
quoteChangeBooking,
|
|
13
|
+
confirmFreeChangeBooking,
|
|
14
|
+
createChangeBookingPaymentIntent,
|
|
15
|
+
confirmFreeBooking,
|
|
16
|
+
confirmBookingWithoutPayment,
|
|
17
|
+
confirmPartnerBookingWithoutPayment,
|
|
18
|
+
getAddOns,
|
|
19
|
+
validatePromoCode,
|
|
20
|
+
getPromoDiscount,
|
|
21
|
+
type Product,
|
|
22
|
+
type Availability,
|
|
23
|
+
type ReturnOption,
|
|
24
|
+
type AddOn,
|
|
25
|
+
isInsufficientCapacityReserveError,
|
|
26
|
+
describeStandardTourCapacityConflictMessage,
|
|
27
|
+
reportReserveCapacityConflictClientContext,
|
|
28
|
+
} from '@/lib/booking-api';
|
|
29
|
+
import {
|
|
30
|
+
EARLIEST_AVAILABILITY_DATE,
|
|
31
|
+
LATEST_AVAILABILITY_DATE,
|
|
32
|
+
INITIAL_FETCH_WEEKS,
|
|
33
|
+
} from '@/lib/booking-constants';
|
|
34
|
+
import { getSundayOfWeek } from '@/lib/booking/sunday-week';
|
|
35
|
+
import { Calendar } from './Calendar';
|
|
36
|
+
import { AdminPaymentChoiceModal } from './AdminPaymentChoiceModal';
|
|
37
|
+
import { ItineraryBox } from './ItineraryBox';
|
|
38
|
+
import { ItineraryPlaceholder } from './ItineraryPlaceholder';
|
|
39
|
+
import { PickupTimeSelector } from './PickupTimeSelector';
|
|
40
|
+
import { ReturnTimeSelector } from './ReturnTimeSelector';
|
|
41
|
+
import { CancellationPolicySelector } from './CancellationPolicySelector';
|
|
42
|
+
import { TicketSelector } from './TicketSelector';
|
|
43
|
+
import { AddOnsSection } from './AddOnsSection';
|
|
44
|
+
import { CheckoutForm } from './CheckoutForm';
|
|
45
|
+
import { PromoCodeInput } from './PromoCodeInput';
|
|
46
|
+
import { useTranslations, useLocale } from '@/lib/booking/i18n';
|
|
47
|
+
import { type Currency } from './CurrencySwitcher';
|
|
48
|
+
import { formatBookingRefForDisplay } from '@/lib/booking-ref';
|
|
49
|
+
import {
|
|
50
|
+
formatCurrencyAmount,
|
|
51
|
+
reconcileChangeBookingProposedTotal,
|
|
52
|
+
} from '@/lib/currency';
|
|
53
|
+
import { buildCheckoutBreakdown } from '@/lib/booking/checkout-breakdown';
|
|
54
|
+
import type { PricingConfig, PrecomputedPricesByCategory, ItineraryDisplayStep } from '@/lib/booking-api';
|
|
55
|
+
import { ItineraryStepType as StepType } from '@/lib/booking-api';
|
|
56
|
+
import {
|
|
57
|
+
getDisplayPriceFromBaseInDisplayCurrency,
|
|
58
|
+
computePriceBreakdown,
|
|
59
|
+
computeOrderSummary,
|
|
60
|
+
type PriceBreakdown as PriceBreakdownData,
|
|
61
|
+
type OrderSummary,
|
|
62
|
+
} from '@/lib/booking/pricing';
|
|
63
|
+
import { useCompanyTimezone } from '@/contexts/CompanyContext';
|
|
64
|
+
import { useBookingApp } from '@/contexts/BookingAppContext';
|
|
65
|
+
import { useAvailabilitiesCache, buildAvailabilitiesCacheKey } from '@/contexts/AvailabilitiesCacheContext';
|
|
66
|
+
import { type PriceSummaryLine } from './PriceSummary';
|
|
67
|
+
import { CheckoutModal, type CheckoutModalLineItem } from './CheckoutModal';
|
|
68
|
+
import { BookingFlowCollage } from './BookingFlowCollage';
|
|
69
|
+
import { TourDescription } from './TourDescription';
|
|
70
|
+
import { getProductByIdOrSlug } from '@/lib/products-config';
|
|
71
|
+
import { getProducts } from '@/constants/products';
|
|
72
|
+
import defaultStrings from '@/strings';
|
|
73
|
+
import { trackViewItem } from '@/lib/analytics';
|
|
74
|
+
import {
|
|
75
|
+
buildBookingSourceContext,
|
|
76
|
+
inferClientBookingSourceFromProductIds,
|
|
77
|
+
type BookingSourceMetadata,
|
|
78
|
+
} from '@/lib/booking/source-metadata';
|
|
79
|
+
import { getItineraryStepLabel } from '@/lib/booking/itinerary-display';
|
|
80
|
+
import { MANAGE_BOOKING_FROM_CHANGE_PAYMENT, MANAGE_BOOKING_QUERY_FROM } from '@/lib/manage-booking-post-checkout';
|
|
81
|
+
import { ENV } from '@/lib/env';
|
|
82
|
+
import type { BookingFlowUiOptions } from './booking-flow-ui';
|
|
83
|
+
import { BOOKING_FLOW_ABANDON_EVENT } from '@/providers/booking-dialog-provider';
|
|
84
|
+
|
|
85
|
+
/** Live selection snapshot for change-booking compare UI (parent dialog). */
|
|
86
|
+
export interface ChangeFlowSelectionPreview {
|
|
87
|
+
tourName: string;
|
|
88
|
+
dateTime: string | null;
|
|
89
|
+
ticketsLine: string;
|
|
90
|
+
itinerarySteps: Array<{ time: string | null; label: string }>;
|
|
91
|
+
/** Whether the selected date/time differs from the original booking. */
|
|
92
|
+
dateChanged: boolean;
|
|
93
|
+
/** Whether the selected tickets/product option differs from the original booking. */
|
|
94
|
+
ticketsChanged: boolean;
|
|
95
|
+
/** When false, UI can hide the “new booking” column (selection matches original). */
|
|
96
|
+
hasChangesFromInitial: boolean;
|
|
97
|
+
/** New selection grand total (before change-due delta) for summary UI in parent dialog. */
|
|
98
|
+
selectionTotal: number;
|
|
99
|
+
selectionCurrency: Currency;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function formatTicketLineItemsForSummary(lines: Array<{ category: string; qty: number }>): string {
|
|
103
|
+
const labels: Record<string, string> = {
|
|
104
|
+
ADULT: 'adult',
|
|
105
|
+
CHILD: 'child',
|
|
106
|
+
INFANT: 'infant',
|
|
107
|
+
SENIOR: 'senior',
|
|
108
|
+
STUDENT: 'student',
|
|
109
|
+
};
|
|
110
|
+
const parts = lines
|
|
111
|
+
.filter((l) => l.qty > 0)
|
|
112
|
+
.map((l) => {
|
|
113
|
+
const label = labels[l.category] || l.category.toLowerCase();
|
|
114
|
+
return `${l.qty} ${label}${l.qty !== 1 ? 's' : ''}`;
|
|
115
|
+
});
|
|
116
|
+
return parts.length > 0 ? parts.join(', ') : '—';
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function normalizeTicketCategoryFromReceiptLabel(raw: string): string | null {
|
|
120
|
+
const normalized = raw.trim().toUpperCase();
|
|
121
|
+
if (!normalized) return null;
|
|
122
|
+
if (['ADULT', 'CHILD', 'INFANT', 'SENIOR', 'STUDENT'].includes(normalized)) return normalized;
|
|
123
|
+
const compact = normalized.replace(/[^A-Z]/g, ' ').replace(/\s+/g, ' ').trim();
|
|
124
|
+
if (/\bADULTS?\b/.test(compact)) return 'ADULT';
|
|
125
|
+
if (/\bCHILD(REN)?\b/.test(compact)) return 'CHILD';
|
|
126
|
+
if (/\bINFANTS?\b/.test(compact)) return 'INFANT';
|
|
127
|
+
if (/\bSENIORS?\b/.test(compact)) return 'SENIOR';
|
|
128
|
+
if (/\bSTUDENTS?\b/.test(compact)) return 'STUDENT';
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function extractTrailingQty(label: string): { baseLabel: string; qty: number } {
|
|
133
|
+
const trimmed = label.trim();
|
|
134
|
+
const m = trimmed.match(/^(.*?)(?:\s*[×x]\s*(\d+))$/);
|
|
135
|
+
if (!m) return { baseLabel: trimmed, qty: 1 };
|
|
136
|
+
const baseLabel = (m[1] || '').trim();
|
|
137
|
+
const qty = Math.max(1, Number(m[2]) || 1);
|
|
138
|
+
return { baseLabel, qty };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function deriveAddOnSelectionsFromReceiptLines(
|
|
142
|
+
addOns: AddOn[],
|
|
143
|
+
lines: Array<{ type?: string; label?: string; amount?: number; quantity?: number }>
|
|
144
|
+
): Array<{ addOnId: string; variantId?: string; quantity?: number }> {
|
|
145
|
+
const selections: Array<{ addOnId: string; variantId?: string; quantity?: number }> = [];
|
|
146
|
+
for (const line of lines) {
|
|
147
|
+
const type = (line.type || '').trim().toUpperCase();
|
|
148
|
+
if (type !== 'FEE') continue;
|
|
149
|
+
const amount = Number(line.amount ?? 0);
|
|
150
|
+
if (!Number.isFinite(amount) || amount <= 0) continue;
|
|
151
|
+
const rawLabel = (line.label || '').trim();
|
|
152
|
+
if (!rawLabel) continue;
|
|
153
|
+
|
|
154
|
+
const { baseLabel, qty } = extractTrailingQty(rawLabel);
|
|
155
|
+
let matched = false;
|
|
156
|
+
|
|
157
|
+
for (const addOn of addOns) {
|
|
158
|
+
if (matched) break;
|
|
159
|
+
const addOnName = addOn.name?.trim();
|
|
160
|
+
if (!addOnName) continue;
|
|
161
|
+
|
|
162
|
+
if (addOn.variantType === 'single_choice' || addOn.variantType === 'multi_quantity') {
|
|
163
|
+
for (const variant of addOn.variants ?? []) {
|
|
164
|
+
const variantLabel = variant.label?.trim();
|
|
165
|
+
if (!variantLabel) continue;
|
|
166
|
+
if (baseLabel === `${addOnName} (${variantLabel})`) {
|
|
167
|
+
selections.push({ addOnId: addOn.addOnId, variantId: variant.id, quantity: qty });
|
|
168
|
+
matched = true;
|
|
169
|
+
break;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
} else if (baseLabel === addOnName) {
|
|
173
|
+
selections.push({ addOnId: addOn.addOnId, quantity: qty });
|
|
174
|
+
matched = true;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return selections;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function findMergedAvailabilityForSelection(
|
|
182
|
+
merged: Availability[],
|
|
183
|
+
selected: Availability | null
|
|
184
|
+
): Availability | undefined {
|
|
185
|
+
if (!selected) return undefined;
|
|
186
|
+
const optId = selected.productOptionId ?? undefined;
|
|
187
|
+
const dt = selected.dateTime;
|
|
188
|
+
const availId = selected.availabilityId?.trim();
|
|
189
|
+
if (availId && optId) {
|
|
190
|
+
const exact = merged.find(
|
|
191
|
+
(a) =>
|
|
192
|
+
a.availabilityId === availId &&
|
|
193
|
+
(a.productOptionId === optId || a.productOptionId === undefined)
|
|
194
|
+
);
|
|
195
|
+
if (exact) return exact;
|
|
196
|
+
}
|
|
197
|
+
return merged.find((a) => a.dateTime === dt && a.productOptionId === optId);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function findMergedReturnVacancies(
|
|
201
|
+
outbound: Availability | undefined,
|
|
202
|
+
selectedReturn: ReturnOption | null | undefined
|
|
203
|
+
): number | null {
|
|
204
|
+
if (!selectedReturn?.returnAvailabilityId || !outbound?.returnOptions?.length) return null;
|
|
205
|
+
const ro = outbound.returnOptions.find(
|
|
206
|
+
(r) => r.returnAvailabilityId === selectedReturn.returnAvailabilityId
|
|
207
|
+
);
|
|
208
|
+
return ro ? ro.vacancies : null;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function normalizeAddOnSelections(
|
|
212
|
+
selections: Array<{ addOnId: string; variantId?: string; quantity?: number }>
|
|
213
|
+
): Array<{ addOnId: string; variantId?: string; quantity?: number }> {
|
|
214
|
+
const qtyByKey = new Map<string, number>();
|
|
215
|
+
for (const sel of selections) {
|
|
216
|
+
const addOnId = sel.addOnId?.trim();
|
|
217
|
+
if (!addOnId) continue;
|
|
218
|
+
const variantId = sel.variantId?.trim() || '';
|
|
219
|
+
const key = `${addOnId}::${variantId}`;
|
|
220
|
+
qtyByKey.set(key, (qtyByKey.get(key) ?? 0) + Math.max(1, Number(sel.quantity) || 1));
|
|
221
|
+
}
|
|
222
|
+
return Array.from(qtyByKey.entries()).map(([key, qty]) => {
|
|
223
|
+
const [addOnId, variantIdRaw] = key.split('::');
|
|
224
|
+
const variantId = variantIdRaw?.trim() || undefined;
|
|
225
|
+
return { addOnId, variantId, quantity: qty };
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
interface BookingFlowProps {
|
|
230
|
+
product: Product;
|
|
231
|
+
/** Product slug (e.g. from URL) - used to look up collage images and video */
|
|
232
|
+
productId?: string;
|
|
233
|
+
onBack: () => void;
|
|
234
|
+
currency: Currency;
|
|
235
|
+
/** Scroll container ref (e.g. from BookingDialog) - scroll happens inside this element, not window */
|
|
236
|
+
contentRef?: React.RefObject<HTMLDivElement | null>;
|
|
237
|
+
/**
|
|
238
|
+
* Optional callback called when reservation is successfully created (before checkout redirect)
|
|
239
|
+
* If provided, indicates we're in an embedded context (e.g., provider dashboard)
|
|
240
|
+
*/
|
|
241
|
+
onSuccess?: (data: { reservationReference: string; bookingReference?: string }) => void;
|
|
242
|
+
/** When true, shows tour description only (no calendar/checkout). Used for time-gated launch. */
|
|
243
|
+
isPartialLaunch?: boolean;
|
|
244
|
+
/**
|
|
245
|
+
* When true, treat the window as the scroll container (full-page layout),
|
|
246
|
+
* instead of relying on an internal scrollable div. Used on partner booking pages.
|
|
247
|
+
*/
|
|
248
|
+
useWindowScroll?: boolean;
|
|
249
|
+
/** Optional promo code to auto-apply when the flow loads (e.g., partner pages). */
|
|
250
|
+
autoAppliedPromoCode?: string;
|
|
251
|
+
/** Optional extra discount percent to show on calendar date badges. */
|
|
252
|
+
calendarDiscountPercent?: number;
|
|
253
|
+
/** Optional pickup location IDs to prioritize/highlight in selector (e.g. partner-preferred). */
|
|
254
|
+
highlightedPickupLocationIds?: string[];
|
|
255
|
+
mode?: 'standard' | 'change';
|
|
256
|
+
onPricePreviewChange?: (preview: {
|
|
257
|
+
subtotal: number;
|
|
258
|
+
tax: number;
|
|
259
|
+
total: number;
|
|
260
|
+
currency: Currency;
|
|
261
|
+
} | null) => void;
|
|
262
|
+
/** Change mode: called when date/tickets/itinerary selection updates (for side-by-side compare in dialog). */
|
|
263
|
+
onChangeFlowSelectionPreview?: (preview: ChangeFlowSelectionPreview | null) => void;
|
|
264
|
+
originalReceipt?: {
|
|
265
|
+
subtotal: number;
|
|
266
|
+
tax: number;
|
|
267
|
+
total: number;
|
|
268
|
+
currency: Currency;
|
|
269
|
+
promoAmount?: number;
|
|
270
|
+
promoLabel?: string | null;
|
|
271
|
+
lineItems?: Array<{
|
|
272
|
+
type?: string;
|
|
273
|
+
label?: string;
|
|
274
|
+
amount?: number;
|
|
275
|
+
quantity?: number;
|
|
276
|
+
}>;
|
|
277
|
+
} | null;
|
|
278
|
+
initialValues?: {
|
|
279
|
+
bookingReference?: string | null;
|
|
280
|
+
dateTime?: string | null;
|
|
281
|
+
/** Inventory slot id from booking (when API persists it); strongest match for change flow. */
|
|
282
|
+
availabilityId?: string | null;
|
|
283
|
+
productOptionId?: string | null;
|
|
284
|
+
pickupLocationId?: string | null;
|
|
285
|
+
/** Original booked return slot (round-trip), when API provides it. */
|
|
286
|
+
returnAvailabilityId?: string | null;
|
|
287
|
+
/** Fallback when only return datetime is on the booking payload. */
|
|
288
|
+
returnDateTime?: string | null;
|
|
289
|
+
bookingItems?: Array<{ category: string; count: number }> | null;
|
|
290
|
+
addOnSelections?: Array<{ addOnId: string; variantId?: string; quantity?: number }> | null;
|
|
291
|
+
customer?: {
|
|
292
|
+
firstName?: string | null;
|
|
293
|
+
lastName?: string | null;
|
|
294
|
+
email?: string | null;
|
|
295
|
+
} | null;
|
|
296
|
+
promoCode?: string | null;
|
|
297
|
+
/** Booked policy id (change flow); must match server quote which uses booking.cancellationPolicyId. */
|
|
298
|
+
cancellationPolicyId?: string | null;
|
|
299
|
+
};
|
|
300
|
+
/**
|
|
301
|
+
* When true, suppress the built-in itinerary box/placeholder.
|
|
302
|
+
* Useful when a parent dialog already renders its own itinerary summary UI.
|
|
303
|
+
*/
|
|
304
|
+
hideItineraryBox?: boolean;
|
|
305
|
+
/** Partner / embed-only tweaks; omit for default website behavior. */
|
|
306
|
+
flowUi?: BookingFlowUiOptions;
|
|
307
|
+
/** Explicit reserve/checkout source metadata (browser URL layer + optional portal merge at call site). */
|
|
308
|
+
bookingSourceAttribution: Partial<BookingSourceMetadata>;
|
|
309
|
+
/** Dedicated partner portal app (`booking.*`): persist reserve `source` as PARTNER_PORTAL. */
|
|
310
|
+
partnerPortalBooking?: boolean;
|
|
311
|
+
/** When set (e.g. partner portal), get-availabilities requests this pricing profile from the API. */
|
|
312
|
+
availabilityPricingProfileId?: string | null;
|
|
313
|
+
/** When set (e.g. partner portal), get-availabilities filters cancellation policies by this profile. */
|
|
314
|
+
availabilityCancellationPolicyProfileId?: string | null;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function parseAvailabilityDateTime(value: string): Date {
|
|
318
|
+
// If API omits timezone offset, treat it as UTC to prevent user-local day shifts.
|
|
319
|
+
const hasExplicitOffset = /(?:Z|[+-]\d{2}:?\d{2})$/i.test(value);
|
|
320
|
+
return parseISO(hasExplicitOffset ? value : `${value}Z`);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function deriveDefaultQuantitiesFromAvailabilities(
|
|
324
|
+
availabilities: Availability[]
|
|
325
|
+
): Record<string, number> | null {
|
|
326
|
+
const firstWithRates = availabilities.find((avail) => avail.rates && avail.rates.length > 0);
|
|
327
|
+
if (!firstWithRates?.rates?.length) return null;
|
|
328
|
+
|
|
329
|
+
const initialQuantities: Record<string, number> = {};
|
|
330
|
+
firstWithRates.rates.forEach((rate) => {
|
|
331
|
+
initialQuantities[rate.category] = rate.category === 'ADULT' ? 1 : 0;
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
return Object.keys(initialQuantities).length > 0 ? initialQuantities : null;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** Clock time (minutes from midnight) for `isoDateTime` in the given IANA zone — use company TZ only, never `Intl` default / browser local. */
|
|
338
|
+
function getMinutesFromMidnightInTimezone(isoDateTime: string, ianaTimeZone: string): number {
|
|
339
|
+
const dt = parseAvailabilityDateTime(isoDateTime);
|
|
340
|
+
const h = parseInt(formatInTimeZone(dt, ianaTimeZone, 'H'), 10);
|
|
341
|
+
const m = parseInt(formatInTimeZone(dt, ianaTimeZone, 'm'), 10);
|
|
342
|
+
return h * 60 + m;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** Smallest difference between two clock times on a 24h circle (handles near-midnight edge cases). */
|
|
346
|
+
function minCircularMinutesDiff(a: number, b: number): number {
|
|
347
|
+
const d = Math.abs(a - b);
|
|
348
|
+
return Math.min(d, 24 * 60 - d);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Change-booking only: after a new calendar date, prefer same product option then closest departure time-of-day.
|
|
353
|
+
* `companyTimezone` must be the company IANA zone (e.g. from useCompanyTimezone) — all wall-clock math is there, not user local.
|
|
354
|
+
*/
|
|
355
|
+
function pickOutboundMatchingPreviousSelection(
|
|
356
|
+
timesForSelectedDate: Availability[],
|
|
357
|
+
anchor: { productOptionId: string | null; minutesFromMidnight: number },
|
|
358
|
+
companyTimezone: string,
|
|
359
|
+
optionsMap: Map<string, { mostPopular?: boolean }>,
|
|
360
|
+
isAdmin: boolean
|
|
361
|
+
): Availability | null {
|
|
362
|
+
const selectable = timesForSelectedDate.filter((a) => (a.vacancies ?? 0) > 0 || isAdmin);
|
|
363
|
+
if (selectable.length === 0) return null;
|
|
364
|
+
|
|
365
|
+
const withOption =
|
|
366
|
+
anchor.productOptionId != null
|
|
367
|
+
? selectable.filter((a) => a.productOptionId === anchor.productOptionId)
|
|
368
|
+
: [];
|
|
369
|
+
const pool = withOption.length > 0 ? withOption : selectable;
|
|
370
|
+
|
|
371
|
+
const sorted = [...pool].sort((a, b) => {
|
|
372
|
+
const da = minCircularMinutesDiff(
|
|
373
|
+
getMinutesFromMidnightInTimezone(a.dateTime, companyTimezone),
|
|
374
|
+
anchor.minutesFromMidnight
|
|
375
|
+
);
|
|
376
|
+
const db = minCircularMinutesDiff(
|
|
377
|
+
getMinutesFromMidnightInTimezone(b.dateTime, companyTimezone),
|
|
378
|
+
anchor.minutesFromMidnight
|
|
379
|
+
);
|
|
380
|
+
if (Math.abs(da - db) > 0.5) return da - db;
|
|
381
|
+
const aPop = optionsMap.get(a.productOptionId ?? '')?.mostPopular ? 1 : 0;
|
|
382
|
+
const bPop = optionsMap.get(b.productOptionId ?? '')?.mostPopular ? 1 : 0;
|
|
383
|
+
if (aPop !== bPop) return bPop - aPop;
|
|
384
|
+
return parseAvailabilityDateTime(a.dateTime).getTime() - parseAvailabilityDateTime(b.dateTime).getTime();
|
|
385
|
+
});
|
|
386
|
+
return sorted[0] ?? null;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Change-booking only: same return location string then closest return time-of-day in `companyTimezone` (IANA), not user local.
|
|
391
|
+
*/
|
|
392
|
+
function pickReturnMatchingPreviousSelection(
|
|
393
|
+
sortedReturnOptions: ReturnOption[],
|
|
394
|
+
anchor: { returnLocation: string; minutesFromMidnight: number },
|
|
395
|
+
companyTimezone: string,
|
|
396
|
+
isAdmin: boolean
|
|
397
|
+
): ReturnOption | null {
|
|
398
|
+
const eligible = sortedReturnOptions.filter((o) => (o.vacancies ?? 0) > 0 || isAdmin);
|
|
399
|
+
if (eligible.length === 0) return null;
|
|
400
|
+
|
|
401
|
+
const sameLoc = eligible.filter((o) => o.returnLocation === anchor.returnLocation);
|
|
402
|
+
const pool = sameLoc.length > 0 ? sameLoc : eligible;
|
|
403
|
+
|
|
404
|
+
const sorted = [...pool].sort((a, b) => {
|
|
405
|
+
const da = minCircularMinutesDiff(
|
|
406
|
+
getMinutesFromMidnightInTimezone(a.dateTime, companyTimezone),
|
|
407
|
+
anchor.minutesFromMidnight
|
|
408
|
+
);
|
|
409
|
+
const db = minCircularMinutesDiff(
|
|
410
|
+
getMinutesFromMidnightInTimezone(b.dateTime, companyTimezone),
|
|
411
|
+
anchor.minutesFromMidnight
|
|
412
|
+
);
|
|
413
|
+
if (Math.abs(da - db) > 0.5) return da - db;
|
|
414
|
+
return parseAvailabilityDateTime(a.dateTime).getTime() - parseAvailabilityDateTime(b.dateTime).getTime();
|
|
415
|
+
});
|
|
416
|
+
return sorted[0] ?? null;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function scoreTicketSubtotalForOption(
|
|
420
|
+
optionId: string | undefined,
|
|
421
|
+
bookingItems: Array<{ category: string; count: number }> | null | undefined,
|
|
422
|
+
precomputedPricesByOption: Record<string, PrecomputedPricesByCategory> | null | undefined,
|
|
423
|
+
currency: Currency
|
|
424
|
+
): number | null {
|
|
425
|
+
if (!optionId || !bookingItems?.length || !precomputedPricesByOption?.[optionId]) return null;
|
|
426
|
+
const precomputed = precomputedPricesByOption[optionId];
|
|
427
|
+
let sum = 0;
|
|
428
|
+
for (const { category, count } of bookingItems) {
|
|
429
|
+
if (count <= 0) continue;
|
|
430
|
+
const key = category?.trim();
|
|
431
|
+
if (!key) continue;
|
|
432
|
+
const unit =
|
|
433
|
+
precomputed[key]?.[currency] ??
|
|
434
|
+
precomputed[key.toUpperCase()]?.[currency] ??
|
|
435
|
+
precomputed[key.toLowerCase()]?.[currency];
|
|
436
|
+
if (unit == null) return null;
|
|
437
|
+
sum += unit * count;
|
|
438
|
+
}
|
|
439
|
+
return sum;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** When several availabilities share the same departure instant, pick using stored option id or closest ticket subtotal to the original receipt. */
|
|
443
|
+
function disambiguateAvailabilityCandidates(
|
|
444
|
+
candidates: Availability[],
|
|
445
|
+
initialProductOptionId: string | undefined,
|
|
446
|
+
bookingItems: Array<{ category: string; count: number }> | null | undefined,
|
|
447
|
+
precomputedPricesByOption: Record<string, PrecomputedPricesByCategory> | null | undefined,
|
|
448
|
+
currency: Currency,
|
|
449
|
+
originalSubtotalBeforeTax: number | undefined
|
|
450
|
+
): Availability | null {
|
|
451
|
+
const withVacancyFirst = [...candidates].sort((a, b) => (b.vacancies > 0 ? 1 : 0) - (a.vacancies > 0 ? 1 : 0));
|
|
452
|
+
const pool = withVacancyFirst.length > 0 ? withVacancyFirst : candidates;
|
|
453
|
+
if (pool.length === 0) return null;
|
|
454
|
+
if (pool.length === 1) return pool[0];
|
|
455
|
+
|
|
456
|
+
if (initialProductOptionId) {
|
|
457
|
+
const matched = pool.find((a) => a.productOptionId === initialProductOptionId);
|
|
458
|
+
if (matched) return matched;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
if (originalSubtotalBeforeTax != null && precomputedPricesByOption && bookingItems?.length) {
|
|
462
|
+
let best: Availability | null = null;
|
|
463
|
+
let bestDiff = Infinity;
|
|
464
|
+
for (const c of pool) {
|
|
465
|
+
const score = scoreTicketSubtotalForOption(c.productOptionId, bookingItems, precomputedPricesByOption, currency);
|
|
466
|
+
if (score == null) continue;
|
|
467
|
+
const diff = Math.abs(score - originalSubtotalBeforeTax);
|
|
468
|
+
if (
|
|
469
|
+
diff < bestDiff - 0.005 ||
|
|
470
|
+
(diff <= bestDiff + 0.005 && (best == null || (c.vacancies > 0 && best.vacancies <= 0)))
|
|
471
|
+
) {
|
|
472
|
+
bestDiff = diff;
|
|
473
|
+
best = c;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
if (best) return best;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
return pool.find((a) => a.vacancies > 0) ?? pool[0];
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* Map a stored booking datetime (+ optional ids) to a row in `timesForSelectedDate`.
|
|
484
|
+
* When several options share the same wall time, may defer until `precomputedPricesByOption` is loaded.
|
|
485
|
+
*/
|
|
486
|
+
function resolveInitialAvailabilityFromBooking(
|
|
487
|
+
timesForSelectedDate: Availability[],
|
|
488
|
+
target: Date,
|
|
489
|
+
companyTimezone: string,
|
|
490
|
+
initialAvailabilityId: string | null | undefined,
|
|
491
|
+
initialProductOptionId: string | null | undefined,
|
|
492
|
+
bookingItems: Array<{ category: string; count: number }> | null | undefined,
|
|
493
|
+
precomputedPricesByOption: Record<string, PrecomputedPricesByCategory> | null | undefined,
|
|
494
|
+
currency: Currency,
|
|
495
|
+
originalSubtotalBeforeTax: number | undefined
|
|
496
|
+
): { selection: Availability | null; defer: boolean } {
|
|
497
|
+
const availId = initialAvailabilityId?.trim() || null;
|
|
498
|
+
const optId = initialProductOptionId?.trim() || null;
|
|
499
|
+
|
|
500
|
+
if (availId) {
|
|
501
|
+
const byAvail = timesForSelectedDate.find((a) => a.availabilityId === availId);
|
|
502
|
+
if (byAvail) return { selection: byAvail, defer: false };
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
const targetMs = target.getTime();
|
|
506
|
+
const sameInstant = timesForSelectedDate.filter(
|
|
507
|
+
(a) => parseAvailabilityDateTime(a.dateTime).getTime() === targetMs
|
|
508
|
+
);
|
|
509
|
+
|
|
510
|
+
if (sameInstant.length > 0) {
|
|
511
|
+
if (sameInstant.length === 1) {
|
|
512
|
+
return { selection: sameInstant[0], defer: false };
|
|
513
|
+
}
|
|
514
|
+
const ambiguous =
|
|
515
|
+
!optId &&
|
|
516
|
+
!availId &&
|
|
517
|
+
new Set(sameInstant.map((s) => s.productOptionId).filter(Boolean)).size > 1;
|
|
518
|
+
if (ambiguous && !precomputedPricesByOption) {
|
|
519
|
+
return { selection: null, defer: true };
|
|
520
|
+
}
|
|
521
|
+
const picked = disambiguateAvailabilityCandidates(
|
|
522
|
+
sameInstant,
|
|
523
|
+
optId ?? undefined,
|
|
524
|
+
bookingItems,
|
|
525
|
+
precomputedPricesByOption,
|
|
526
|
+
currency,
|
|
527
|
+
originalSubtotalBeforeTax
|
|
528
|
+
);
|
|
529
|
+
return { selection: picked, defer: false };
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
const localKey = formatInTimeZone(target, companyTimezone, 'yyyy-MM-dd HH:mm');
|
|
533
|
+
const sameLocalWall = timesForSelectedDate.filter((a) => {
|
|
534
|
+
const key = formatInTimeZone(parseAvailabilityDateTime(a.dateTime), companyTimezone, 'yyyy-MM-dd HH:mm');
|
|
535
|
+
return key === localKey;
|
|
536
|
+
});
|
|
537
|
+
|
|
538
|
+
if (sameLocalWall.length > 0) {
|
|
539
|
+
if (sameLocalWall.length === 1) {
|
|
540
|
+
return { selection: sameLocalWall[0], defer: false };
|
|
541
|
+
}
|
|
542
|
+
const ambiguous =
|
|
543
|
+
!optId &&
|
|
544
|
+
!availId &&
|
|
545
|
+
new Set(sameLocalWall.map((s) => s.productOptionId).filter(Boolean)).size > 1;
|
|
546
|
+
if (ambiguous && !precomputedPricesByOption) {
|
|
547
|
+
return { selection: null, defer: true };
|
|
548
|
+
}
|
|
549
|
+
const picked = disambiguateAvailabilityCandidates(
|
|
550
|
+
sameLocalWall,
|
|
551
|
+
optId ?? undefined,
|
|
552
|
+
bookingItems,
|
|
553
|
+
precomputedPricesByOption,
|
|
554
|
+
currency,
|
|
555
|
+
originalSubtotalBeforeTax
|
|
556
|
+
);
|
|
557
|
+
return { selection: picked, defer: false };
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
if (optId) {
|
|
561
|
+
const byOption = timesForSelectedDate.filter((a) => a.productOptionId === optId);
|
|
562
|
+
if (byOption.length > 0) {
|
|
563
|
+
const timeMatch = byOption.find((a) => parseAvailabilityDateTime(a.dateTime).getTime() === targetMs);
|
|
564
|
+
if (timeMatch) return { selection: timeMatch, defer: false };
|
|
565
|
+
const localMatch = byOption.find(
|
|
566
|
+
(a) =>
|
|
567
|
+
formatInTimeZone(parseAvailabilityDateTime(a.dateTime), companyTimezone, 'yyyy-MM-dd HH:mm') === localKey
|
|
568
|
+
);
|
|
569
|
+
if (localMatch) return { selection: localMatch, defer: false };
|
|
570
|
+
const picked = disambiguateAvailabilityCandidates(
|
|
571
|
+
byOption,
|
|
572
|
+
optId,
|
|
573
|
+
bookingItems,
|
|
574
|
+
precomputedPricesByOption,
|
|
575
|
+
currency,
|
|
576
|
+
originalSubtotalBeforeTax
|
|
577
|
+
);
|
|
578
|
+
return { selection: picked, defer: false };
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
const fallback = timesForSelectedDate.find((a) => a.vacancies > 0) ?? null;
|
|
583
|
+
return { selection: fallback, defer: false };
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
export function BookingFlow({
|
|
587
|
+
product,
|
|
588
|
+
productId,
|
|
589
|
+
onBack,
|
|
590
|
+
currency,
|
|
591
|
+
contentRef,
|
|
592
|
+
onSuccess,
|
|
593
|
+
isPartialLaunch = false,
|
|
594
|
+
useWindowScroll = false,
|
|
595
|
+
autoAppliedPromoCode,
|
|
596
|
+
calendarDiscountPercent,
|
|
597
|
+
highlightedPickupLocationIds,
|
|
598
|
+
mode = 'standard',
|
|
599
|
+
onPricePreviewChange,
|
|
600
|
+
onChangeFlowSelectionPreview,
|
|
601
|
+
originalReceipt = null,
|
|
602
|
+
initialValues,
|
|
603
|
+
hideItineraryBox = false,
|
|
604
|
+
flowUi,
|
|
605
|
+
bookingSourceAttribution,
|
|
606
|
+
partnerPortalBooking = false,
|
|
607
|
+
availabilityPricingProfileId,
|
|
608
|
+
availabilityCancellationPolicyProfileId,
|
|
609
|
+
}: BookingFlowProps) {
|
|
610
|
+
const { t } = useTranslations();
|
|
611
|
+
const { locale } = useLocale();
|
|
612
|
+
const companyTimezone = useCompanyTimezone(); // Get timezone from context
|
|
613
|
+
const pricingProfileIdForAvailabilities = (availabilityPricingProfileId ?? '').trim() || null;
|
|
614
|
+
const cancellationPolicyProfileIdForAvailabilities =
|
|
615
|
+
(availabilityCancellationPolicyProfileId ?? '').trim() || null;
|
|
616
|
+
const {
|
|
617
|
+
permissions,
|
|
618
|
+
isSimplifiedPricingView,
|
|
619
|
+
onShowManage,
|
|
620
|
+
getSuccessUrl,
|
|
621
|
+
suppressCalendarDateScroll,
|
|
622
|
+
mode: bookingAppMode,
|
|
623
|
+
} = useBookingApp();
|
|
624
|
+
const availabilitiesCache = useAvailabilitiesCache();
|
|
625
|
+
const isAdmin = permissions.viewerRole === 'admin';
|
|
626
|
+
const [availabilities, setAvailabilities] = useState<Availability[]>([]);
|
|
627
|
+
const [selectedAvailability, setSelectedAvailability] = useState<Availability | null>(null);
|
|
628
|
+
const [selectedReturnOption, setSelectedReturnOption] = useState<ReturnOption | null>(null);
|
|
629
|
+
const [quantities, setQuantities] = useState<Record<string, number>>({});
|
|
630
|
+
const [email, setEmail] = useState('');
|
|
631
|
+
const [firstName, setFirstName] = useState('');
|
|
632
|
+
const [lastName, setLastName] = useState('');
|
|
633
|
+
const [promoCodeInput, setPromoCodeInput] = useState('');
|
|
634
|
+
const [appliedPromoCode, setAppliedPromoCode] = useState<string | null>(null);
|
|
635
|
+
const [promoCodeError, setPromoCodeError] = useState('');
|
|
636
|
+
/** When set by a promo, this policy is forced and shown as a non-selectable row. */
|
|
637
|
+
const [forcedCancellationPolicy, setForcedCancellationPolicy] = useState<{
|
|
638
|
+
id: string;
|
|
639
|
+
label: string;
|
|
640
|
+
refundTiers?: Array<{ hoursBefore: number; refundPercent: number }>;
|
|
641
|
+
changeWindowHoursBefore?: number | null;
|
|
642
|
+
} | null>(null);
|
|
643
|
+
const cancellationPolicyRef = useRef<HTMLDivElement>(null);
|
|
644
|
+
const [promoCodeValidating, setPromoCodeValidating] = useState(false);
|
|
645
|
+
const [pickupLocationId, setPickupLocationId] = useState<string | null>(null);
|
|
646
|
+
const [pickupLocationSkipped, setPickupLocationSkipped] = useState(false);
|
|
647
|
+
// Cancellation: change flow seeds from the booking so totals match the quote (server uses booking.cancellationPolicyId).
|
|
648
|
+
// Standard flow defaults to cheapest policy when pricing config loads.
|
|
649
|
+
const [cancellationPolicyId, setCancellationPolicyId] = useState<string | null>(() => {
|
|
650
|
+
const fromBooking = initialValues?.cancellationPolicyId?.trim();
|
|
651
|
+
if (mode === 'change' && fromBooking) return fromBooking;
|
|
652
|
+
return null;
|
|
653
|
+
});
|
|
654
|
+
/** Add-on selections (lunch, animals, etc.) - filtered by selected product option */
|
|
655
|
+
const [addOnSelections, setAddOnSelections] = useState<Array<{ addOnId: string; variantId?: string; quantity?: number }>>(() =>
|
|
656
|
+
normalizeAddOnSelections(initialValues?.addOnSelections ?? [])
|
|
657
|
+
);
|
|
658
|
+
/** Fetched add-ons for the selected product option */
|
|
659
|
+
const [addOns, setAddOns] = useState<AddOn[]>([]);
|
|
660
|
+
|
|
661
|
+
// Auto-apply promo code when parent page passes one (e.g. partner pages).
|
|
662
|
+
// Seed input only; validate/apply runs after date/time + tickets exist (debounced + handleApplyPromo).
|
|
663
|
+
useEffect(() => {
|
|
664
|
+
if (!autoAppliedPromoCode) return;
|
|
665
|
+
const normalizedPromo = autoAppliedPromoCode.trim().toUpperCase();
|
|
666
|
+
if (!normalizedPromo) return;
|
|
667
|
+
setPromoCodeInput((current) => current || normalizedPromo);
|
|
668
|
+
}, [autoAppliedPromoCode]);
|
|
669
|
+
const [loading, setLoading] = useState(false);
|
|
670
|
+
const [loadingAvailabilities, setLoadingAvailabilities] = useState(true);
|
|
671
|
+
/** True when fetching additional availability (e.g. new month in dropdown) - shows spinner in date picker */
|
|
672
|
+
const [isFetchingMoreAvailabilities, setIsFetchingMoreAvailabilities] = useState(false);
|
|
673
|
+
const [error, setError] = useState('');
|
|
674
|
+
const [pricingConfig, setPricingConfig] = useState<PricingConfig | null>(null);
|
|
675
|
+
/** Precomputed prices from ticketbooth-product-prices per option (optionId -> category -> currency -> price). Used for display; rates[].price is for GYG only. */
|
|
676
|
+
const [precomputedPricesByOption, setPrecomputedPricesByOption] = useState<Record<string, PrecomputedPricesByCategory> | null>(null);
|
|
677
|
+
const pricingConfigSetRef = useRef(false); // Track if pricingConfig has been set (optimize: only set once)
|
|
678
|
+
const fetchingRef = useRef(false); // Prevent concurrent fetches
|
|
679
|
+
const fetchedRangesRef = useRef<Array<{ start: Date; end: Date }>>([]); // Track fetched date ranges
|
|
680
|
+
const pendingRangeRef = useRef<{ start: Date; end: Date } | null>(null); // Range to fetch when current fetch completes (user navigated during fetch)
|
|
681
|
+
const [visibleRange, setVisibleRange] = useState<{ start: Date; end: Date } | null>(null);
|
|
682
|
+
const [selectedDate, setSelectedDate] = useState<string>(() => {
|
|
683
|
+
if (mode !== 'change' || !initialValues?.dateTime?.trim()) return '';
|
|
684
|
+
try {
|
|
685
|
+
const target = parseAvailabilityDateTime(initialValues.dateTime.trim());
|
|
686
|
+
return formatInTimeZone(target, companyTimezone, 'yyyy-MM-dd');
|
|
687
|
+
} catch {
|
|
688
|
+
return '';
|
|
689
|
+
}
|
|
690
|
+
});
|
|
691
|
+
const [isItinerarySticky, setIsItinerarySticky] = useState(false);
|
|
692
|
+
const isItineraryStickyRef = useRef(false);
|
|
693
|
+
const [isMobile, setIsMobile] = useState(false);
|
|
694
|
+
const [showTooltip, setShowTooltip] = useState(false);
|
|
695
|
+
const itineraryRef = useRef<HTMLDivElement>(null);
|
|
696
|
+
const [showCheckoutModal, setShowCheckoutModal] = useState(false);
|
|
697
|
+
/** Pending reservation while user is in checkout (RESERVED until confirmed/cancelled). */
|
|
698
|
+
const pendingReservationRef = useRef<{ reservationReference: string } | null>(null);
|
|
699
|
+
/** True while Stripe is confirming payment/redirecting; skip unload cancellation during this window. */
|
|
700
|
+
const paymentSubmitInFlightRef = useRef(false);
|
|
701
|
+
const [termsAccepted, setTermsAccepted] = useState(false);
|
|
702
|
+
const [termsAcceptedAt, setTermsAcceptedAt] = useState<string | null>(null);
|
|
703
|
+
const [partnerAttributionConfirmed, setPartnerAttributionConfirmed] = useState(false);
|
|
704
|
+
const [checkoutClientSecret, setCheckoutClientSecret] = useState('');
|
|
705
|
+
const [checkoutModalData, setCheckoutModalData] = useState<{
|
|
706
|
+
reservationReference: string;
|
|
707
|
+
reservationExpiration?: string;
|
|
708
|
+
customerLastName?: string;
|
|
709
|
+
bookingDate?: string;
|
|
710
|
+
successUrlOverride?: string;
|
|
711
|
+
ticketLines: CheckoutModalLineItem[];
|
|
712
|
+
feeLineItems: OrderSummary['feeLineItems'];
|
|
713
|
+
returnPriceAdjustment: number;
|
|
714
|
+
cancellationPolicyFee: number;
|
|
715
|
+
cancellationPolicyLabel?: string;
|
|
716
|
+
subtotal: number;
|
|
717
|
+
tax: number;
|
|
718
|
+
total: number;
|
|
719
|
+
promoDiscountAmount?: number;
|
|
720
|
+
discountLabel?: string | null;
|
|
721
|
+
totalQuantity: number;
|
|
722
|
+
isTaxIncludedInPrice: boolean;
|
|
723
|
+
taxRate: number;
|
|
724
|
+
changeTotals?: {
|
|
725
|
+
previousTotal: number;
|
|
726
|
+
newTotal: number;
|
|
727
|
+
differenceTotal: number;
|
|
728
|
+
};
|
|
729
|
+
} | null>(null);
|
|
730
|
+
/** Admin only: skip sending confirmation at creation (provider dashboard). */
|
|
731
|
+
const [skipConfirmationCommunications, setSkipConfirmationCommunications] = useState(false);
|
|
732
|
+
/** Admin only: disable all auto communications for this booking (provider dashboard). */
|
|
733
|
+
const [disableAutoCommunications, setDisableAutoCommunications] = useState(false);
|
|
734
|
+
/** Admin only: show choice to pay now or confirm without payment (full balance owed). */
|
|
735
|
+
const [showAdminPaymentChoice, setShowAdminPaymentChoice] = useState(false);
|
|
736
|
+
const hasAppliedInitialValuesRef = useRef(false);
|
|
737
|
+
const hasAppliedInitialQuantitiesRef = useRef(false);
|
|
738
|
+
const hasHydratedAddOnsFromReceiptRef = useRef(false);
|
|
739
|
+
const hasAutoSelectedPartnerDateRef = useRef(false);
|
|
740
|
+
const hasAutoSelectedPartnerPickupRef = useRef(false);
|
|
741
|
+
const handleDateSelectRef = useRef<(date: string) => void>(() => {});
|
|
742
|
+
const isChangeFlow = mode === 'change';
|
|
743
|
+
|
|
744
|
+
useEffect(() => {
|
|
745
|
+
setPartnerAttributionConfirmed(false);
|
|
746
|
+
}, [flowUi?.partnerAttributionSummary, flowUi?.partnerAttributionConfirmLabel]);
|
|
747
|
+
/**
|
|
748
|
+
* Change flow: if the booking payload has no return id/datetime, we still need to detect when the
|
|
749
|
+
* user picks a different return time — baseline is the first auto-selected return for this outbound.
|
|
750
|
+
*/
|
|
751
|
+
const [implicitReturnBaselineId, setImplicitReturnBaselineId] = useState<string | null>(null);
|
|
752
|
+
const lockedPromoCode = isChangeFlow
|
|
753
|
+
? (initialValues?.promoCode?.trim().toUpperCase() || null)
|
|
754
|
+
: null;
|
|
755
|
+
/** Change booking: cannot reduce tickets below original counts (can still decrease after increasing). */
|
|
756
|
+
const changeBookingMinimumQuantities = useMemo(() => {
|
|
757
|
+
if (!isChangeFlow || !initialValues?.bookingItems?.length) return undefined;
|
|
758
|
+
const m: Record<string, number> = {};
|
|
759
|
+
for (const item of initialValues.bookingItems) {
|
|
760
|
+
const key = item.category?.trim();
|
|
761
|
+
if (!key) continue;
|
|
762
|
+
m[key] = Math.max(0, Number(item.count) || 0);
|
|
763
|
+
}
|
|
764
|
+
return m;
|
|
765
|
+
}, [isChangeFlow, initialValues?.bookingItems]);
|
|
766
|
+
const [adminChoiceData, setAdminChoiceData] = useState<{
|
|
767
|
+
reservationReference: string;
|
|
768
|
+
reservationExpiration?: string;
|
|
769
|
+
checkoutBreakdown: { lineItems: Array<{ label: string; amount: number; type?: string; quantity?: number }>; totalAmount: number; currency: string };
|
|
770
|
+
totalAmount: number;
|
|
771
|
+
datePart: string;
|
|
772
|
+
timePart: string;
|
|
773
|
+
availabilityProductOptionId: string;
|
|
774
|
+
itineraryDisplay?: ItineraryDisplayStep[] | null;
|
|
775
|
+
clientSecret: string;
|
|
776
|
+
ticketLinesForModal: CheckoutModalLineItem[];
|
|
777
|
+
feeLineItems: OrderSummary['feeLineItems'];
|
|
778
|
+
returnPriceAdjustment: number;
|
|
779
|
+
cancellationPolicyFee: number;
|
|
780
|
+
cancellationPolicyLabel?: string;
|
|
781
|
+
subtotal: number;
|
|
782
|
+
tax: number;
|
|
783
|
+
totalQuantity: number;
|
|
784
|
+
isTaxIncludedInPrice: boolean;
|
|
785
|
+
taxRate: number;
|
|
786
|
+
promoDiscountAmount: number;
|
|
787
|
+
discountLabel?: string | null;
|
|
788
|
+
} | null>(null);
|
|
789
|
+
const [latestChangeQuote, setLatestChangeQuote] = useState<{
|
|
790
|
+
priceDiff: number;
|
|
791
|
+
currency: Currency;
|
|
792
|
+
canProceed: boolean;
|
|
793
|
+
reasonIfBlocked?: string;
|
|
794
|
+
changeIntentId?: string;
|
|
795
|
+
quotedTotal?: number;
|
|
796
|
+
} | null>(null);
|
|
797
|
+
const [changeQuoteLoading, setChangeQuoteLoading] = useState(false);
|
|
798
|
+
const [changeQuoteFetchError, setChangeQuoteFetchError] = useState<string | null>(null);
|
|
799
|
+
const changeQuoteRequestSeq = useRef(0);
|
|
800
|
+
/** When the user picks a new calendar date in change flow, we match outbound/return from these anchors. */
|
|
801
|
+
const changeFlowOutboundAnchorRef = useRef<{
|
|
802
|
+
productOptionId: string | null;
|
|
803
|
+
minutesFromMidnight: number;
|
|
804
|
+
} | null>(null);
|
|
805
|
+
const changeFlowReturnAnchorRef = useRef<{
|
|
806
|
+
returnLocation: string;
|
|
807
|
+
minutesFromMidnight: number;
|
|
808
|
+
} | null>(null);
|
|
809
|
+
|
|
810
|
+
// Get all active product options (memoized to prevent recreating array on each render)
|
|
811
|
+
const activeOptions = useMemo(() =>
|
|
812
|
+
product.options?.filter(opt => opt.status === 'ACTIVE') || [],
|
|
813
|
+
[product.options]
|
|
814
|
+
);
|
|
815
|
+
|
|
816
|
+
// Detect if this is a Private Shuttle product
|
|
817
|
+
const isPrivateShuttle = product.productType === 'PRIVATE_SHUTTLE';
|
|
818
|
+
|
|
819
|
+
// Create stable string key from option IDs for dependency array
|
|
820
|
+
const activeOptionIdsKey = useMemo(() =>
|
|
821
|
+
activeOptions.map(opt => opt.optionId).sort().join(','),
|
|
822
|
+
[activeOptions]
|
|
823
|
+
);
|
|
824
|
+
|
|
825
|
+
// Create a Map for O(1) option lookups by optionId (performance optimization)
|
|
826
|
+
const optionsMap = useMemo(() => {
|
|
827
|
+
const map = new Map<string, typeof activeOptions[0]>();
|
|
828
|
+
activeOptions.forEach(opt => map.set(opt.optionId, opt));
|
|
829
|
+
return map;
|
|
830
|
+
}, [activeOptions]);
|
|
831
|
+
|
|
832
|
+
// Fire view_item when product is first displayed
|
|
833
|
+
const hasFiredViewItem = useRef(false);
|
|
834
|
+
useEffect(() => {
|
|
835
|
+
if (!hasFiredViewItem.current && product) {
|
|
836
|
+
hasFiredViewItem.current = true;
|
|
837
|
+
const id = productId || product.productId;
|
|
838
|
+
const price = product.minPriceByCurrency?.[currency] ?? 0;
|
|
839
|
+
trackViewItem(id, product.name, price, currency);
|
|
840
|
+
}
|
|
841
|
+
}, [product, productId, currency]);
|
|
842
|
+
|
|
843
|
+
// Helper function to check if we need to fetch a date range
|
|
844
|
+
const needsFetch = (start: Date, end: Date): boolean => {
|
|
845
|
+
if (fetchedRangesRef.current.length === 0) return true;
|
|
846
|
+
|
|
847
|
+
// Check if the requested range is fully covered by fetched ranges
|
|
848
|
+
// For simplicity, check if any single fetched range fully covers the requested range
|
|
849
|
+
return !fetchedRangesRef.current.some(range => {
|
|
850
|
+
const rangeStart = range.start.getTime();
|
|
851
|
+
const rangeEnd = range.end.getTime();
|
|
852
|
+
const reqStart = start.getTime();
|
|
853
|
+
const reqEnd = end.getTime();
|
|
854
|
+
|
|
855
|
+
// Check if this fetched range fully covers the requested range
|
|
856
|
+
return rangeStart <= reqStart && rangeEnd >= reqEnd;
|
|
857
|
+
});
|
|
858
|
+
};
|
|
859
|
+
|
|
860
|
+
/** Re-fetch current calendar window so vacancies/booked counts match server after a reserve race. */
|
|
861
|
+
const reloadAvailabilitiesAfterReserveConflict = useCallback(async (): Promise<Availability[]> => {
|
|
862
|
+
if (isPartialLaunch || !visibleRange || activeOptions.length === 0) {
|
|
863
|
+
return [];
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
const startOfEarliestDay = fromZonedTime(new Date(2026, 5, 1, 0, 0, 0, 0), companyTimezone);
|
|
867
|
+
const endOfLatestDay = fromZonedTime(new Date(2026, 9, 12, 23, 59, 59, 999), companyTimezone);
|
|
868
|
+
const clampedStart = isBefore(visibleRange.start, startOfEarliestDay)
|
|
869
|
+
? startOfEarliestDay
|
|
870
|
+
: visibleRange.start;
|
|
871
|
+
let clampedEnd = isAfter(visibleRange.end, endOfLatestDay) ? endOfLatestDay : visibleRange.end;
|
|
872
|
+
|
|
873
|
+
if (selectedDate) {
|
|
874
|
+
try {
|
|
875
|
+
const selectedDateObj = parseISO(selectedDate);
|
|
876
|
+
if (isAfter(selectedDateObj, clampedEnd)) {
|
|
877
|
+
clampedEnd = selectedDateObj;
|
|
878
|
+
}
|
|
879
|
+
} catch {
|
|
880
|
+
/* ignore */
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
let startDateStr: string;
|
|
885
|
+
let endDateStr: string;
|
|
886
|
+
|
|
887
|
+
if (isPrivateShuttle) {
|
|
888
|
+
startDateStr = format(startOfDay(clampedStart), 'yyyy-MM-dd');
|
|
889
|
+
endDateStr = format(endOfDay(clampedEnd), 'yyyy-MM-dd');
|
|
890
|
+
} else {
|
|
891
|
+
const startDateInTz = formatInTimeZone(clampedStart, companyTimezone, 'yyyy-MM-dd');
|
|
892
|
+
const endDateInTz = formatInTimeZone(clampedEnd, companyTimezone, 'yyyy-MM-dd');
|
|
893
|
+
const startMoment = fromZonedTime(parseISO(`${startDateInTz}T00:00:00.000`), companyTimezone);
|
|
894
|
+
const endMoment = fromZonedTime(parseISO(`${endDateInTz}T23:59:59.999`), companyTimezone);
|
|
895
|
+
startDateStr = formatInTimeZone(startMoment, 'UTC', "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
|
|
896
|
+
endDateStr = formatInTimeZone(endMoment, 'UTC', "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
const availabilityPromises = activeOptions.map(async (option) => {
|
|
900
|
+
const result = await getAvailabilities(option.optionId, startDateStr, endDateStr, {
|
|
901
|
+
promoCode: appliedPromoCode || undefined,
|
|
902
|
+
...(pricingProfileIdForAvailabilities
|
|
903
|
+
? { pricingProfileId: pricingProfileIdForAvailabilities }
|
|
904
|
+
: {}),
|
|
905
|
+
...(cancellationPolicyProfileIdForAvailabilities
|
|
906
|
+
? { cancellationPolicyProfileId: cancellationPolicyProfileIdForAvailabilities }
|
|
907
|
+
: {}),
|
|
908
|
+
});
|
|
909
|
+
if (result.pricingConfig && !pricingConfigSetRef.current) {
|
|
910
|
+
setPricingConfig((prev) => {
|
|
911
|
+
if (!prev) {
|
|
912
|
+
pricingConfigSetRef.current = true;
|
|
913
|
+
return result.pricingConfig!;
|
|
914
|
+
}
|
|
915
|
+
return prev;
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
return {
|
|
919
|
+
optionId: option.optionId,
|
|
920
|
+
availabilities: result.availabilities.map((avail) => ({
|
|
921
|
+
...avail,
|
|
922
|
+
productOptionId: option.optionId,
|
|
923
|
+
})),
|
|
924
|
+
precomputedPrices: result.precomputedPrices,
|
|
925
|
+
pricingConfig: result.pricingConfig,
|
|
926
|
+
};
|
|
927
|
+
});
|
|
928
|
+
|
|
929
|
+
const results = await Promise.all(availabilityPromises);
|
|
930
|
+
const allFetchedAvailabilities = results.flatMap((r) => r.availabilities);
|
|
931
|
+
|
|
932
|
+
setPrecomputedPricesByOption((prev) => {
|
|
933
|
+
const next = { ...(prev || {}) };
|
|
934
|
+
results.forEach((r) => {
|
|
935
|
+
if (r.precomputedPrices && Object.keys(r.precomputedPrices).length > 0) {
|
|
936
|
+
next[r.optionId] = r.precomputedPrices;
|
|
937
|
+
}
|
|
938
|
+
});
|
|
939
|
+
return Object.keys(next).length > 0 ? next : prev;
|
|
940
|
+
});
|
|
941
|
+
|
|
942
|
+
let mergedOut: Availability[] = [];
|
|
943
|
+
setAvailabilities((prev) => {
|
|
944
|
+
const existingMap = new Map(
|
|
945
|
+
prev.map((avail) => [`${avail.dateTime}-${avail.productOptionId}`, avail])
|
|
946
|
+
);
|
|
947
|
+
allFetchedAvailabilities.forEach((avail) => {
|
|
948
|
+
existingMap.set(`${avail.dateTime}-${avail.productOptionId}`, avail);
|
|
949
|
+
});
|
|
950
|
+
mergedOut = Array.from(existingMap.values());
|
|
951
|
+
return mergedOut;
|
|
952
|
+
});
|
|
953
|
+
|
|
954
|
+
fetchedRangesRef.current.push({ start: new Date(clampedStart), end: new Date(clampedEnd) });
|
|
955
|
+
fetchedRangesRef.current.sort((a, b) => a.start.getTime() - b.start.getTime());
|
|
956
|
+
const mergedRanges: Array<{ start: Date; end: Date }> = [];
|
|
957
|
+
for (const r of fetchedRangesRef.current) {
|
|
958
|
+
if (mergedRanges.length === 0 || mergedRanges[mergedRanges.length - 1].end < r.start) {
|
|
959
|
+
mergedRanges.push({ start: r.start, end: r.end });
|
|
960
|
+
} else {
|
|
961
|
+
mergedRanges[mergedRanges.length - 1].end =
|
|
962
|
+
r.end > mergedRanges[mergedRanges.length - 1].end
|
|
963
|
+
? r.end
|
|
964
|
+
: mergedRanges[mergedRanges.length - 1].end;
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
fetchedRangesRef.current = mergedRanges;
|
|
968
|
+
|
|
969
|
+
const cacheKey = availabilitiesCache
|
|
970
|
+
? buildAvailabilitiesCacheKey(
|
|
971
|
+
product.productId,
|
|
972
|
+
activeOptionIdsKey,
|
|
973
|
+
appliedPromoCode,
|
|
974
|
+
pricingProfileIdForAvailabilities,
|
|
975
|
+
)
|
|
976
|
+
: null;
|
|
977
|
+
if (cacheKey && availabilitiesCache) {
|
|
978
|
+
const existingCache = availabilitiesCache.get(cacheKey);
|
|
979
|
+
const existingAvailabilities = existingCache?.availabilities ?? [];
|
|
980
|
+
const mergedAvailabilitiesMap = new Map(
|
|
981
|
+
existingAvailabilities.map((a) => [`${a.dateTime}-${a.productOptionId}`, a])
|
|
982
|
+
);
|
|
983
|
+
allFetchedAvailabilities.forEach((a) => {
|
|
984
|
+
mergedAvailabilitiesMap.set(`${a.dateTime}-${a.productOptionId}`, a);
|
|
985
|
+
});
|
|
986
|
+
const mergedPrecomputed = { ...(existingCache?.precomputedPricesByOption ?? {}) };
|
|
987
|
+
results.forEach((r) => {
|
|
988
|
+
if (r.precomputedPrices && Object.keys(r.precomputedPrices).length > 0) {
|
|
989
|
+
mergedPrecomputed[r.optionId] = r.precomputedPrices;
|
|
990
|
+
}
|
|
991
|
+
});
|
|
992
|
+
const firstPricingConfig =
|
|
993
|
+
(results[0] as { pricingConfig?: PricingConfig } | undefined)?.pricingConfig ??
|
|
994
|
+
existingCache?.pricingConfig ??
|
|
995
|
+
null;
|
|
996
|
+
availabilitiesCache.merge(cacheKey, {
|
|
997
|
+
fetchedRanges: mergedRanges,
|
|
998
|
+
availabilities: Array.from(mergedAvailabilitiesMap.values()),
|
|
999
|
+
pricingConfig: firstPricingConfig,
|
|
1000
|
+
precomputedPricesByOption: Object.keys(mergedPrecomputed).length > 0 ? mergedPrecomputed : null,
|
|
1001
|
+
});
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
return mergedOut;
|
|
1005
|
+
}, [
|
|
1006
|
+
isPartialLaunch,
|
|
1007
|
+
visibleRange,
|
|
1008
|
+
companyTimezone,
|
|
1009
|
+
selectedDate,
|
|
1010
|
+
isPrivateShuttle,
|
|
1011
|
+
activeOptions,
|
|
1012
|
+
appliedPromoCode,
|
|
1013
|
+
pricingProfileIdForAvailabilities,
|
|
1014
|
+
cancellationPolicyProfileIdForAvailabilities,
|
|
1015
|
+
product.productId,
|
|
1016
|
+
activeOptionIdsKey,
|
|
1017
|
+
availabilitiesCache,
|
|
1018
|
+
]);
|
|
1019
|
+
|
|
1020
|
+
// Initialize visible range when unset. Change flow: start the fetch window on the booking week so
|
|
1021
|
+
// availability for the current trip loads first; otherwise anchor at season open for fast first paint.
|
|
1022
|
+
useEffect(() => {
|
|
1023
|
+
if (!visibleRange) {
|
|
1024
|
+
const startOfEarliestDay = fromZonedTime(new Date(2026, 5, 1, 0, 0, 0, 0), companyTimezone);
|
|
1025
|
+
const endOfLatestDay = fromZonedTime(new Date(2026, 9, 12, 23, 59, 59, 999), companyTimezone);
|
|
1026
|
+
|
|
1027
|
+
if (isChangeFlow && initialValues?.dateTime?.trim()) {
|
|
1028
|
+
try {
|
|
1029
|
+
const target = parseAvailabilityDateTime(initialValues.dateTime.trim());
|
|
1030
|
+
const dateStr = formatInTimeZone(target, companyTimezone, 'yyyy-MM-dd');
|
|
1031
|
+
const weekStartStr = getSundayOfWeek(dateStr, companyTimezone);
|
|
1032
|
+
let rangeStart = fromZonedTime(parseISO(`${weekStartStr}T12:00:00`), companyTimezone);
|
|
1033
|
+
if (isBefore(rangeStart, startOfEarliestDay)) {
|
|
1034
|
+
rangeStart = startOfEarliestDay;
|
|
1035
|
+
}
|
|
1036
|
+
let rangeEnd = addWeeks(rangeStart, INITIAL_FETCH_WEEKS);
|
|
1037
|
+
if (isAfter(rangeEnd, endOfLatestDay)) {
|
|
1038
|
+
rangeEnd = endOfLatestDay;
|
|
1039
|
+
}
|
|
1040
|
+
if (!isBefore(rangeEnd, rangeStart)) {
|
|
1041
|
+
setVisibleRange({ start: rangeStart, end: rangeEnd });
|
|
1042
|
+
return;
|
|
1043
|
+
}
|
|
1044
|
+
} catch {
|
|
1045
|
+
/* fall through to default */
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
const initialEnd = addWeeks(EARLIEST_AVAILABILITY_DATE, INITIAL_FETCH_WEEKS);
|
|
1050
|
+
setVisibleRange({ start: EARLIEST_AVAILABILITY_DATE, end: initialEnd });
|
|
1051
|
+
}
|
|
1052
|
+
}, [visibleRange, isChangeFlow, initialValues?.dateTime, companyTimezone]);
|
|
1053
|
+
|
|
1054
|
+
// Fetch availabilities for visible range + buffer
|
|
1055
|
+
useEffect(() => {
|
|
1056
|
+
if (isPartialLaunch) {
|
|
1057
|
+
setLoadingAvailabilities(false);
|
|
1058
|
+
return;
|
|
1059
|
+
}
|
|
1060
|
+
if (activeOptions.length === 0) {
|
|
1061
|
+
setError('No active product options available');
|
|
1062
|
+
setLoadingAvailabilities(false);
|
|
1063
|
+
return;
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
if (!visibleRange) {
|
|
1067
|
+
// Wait for initial range to be set
|
|
1068
|
+
return;
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
async function fetchAvailabilities() {
|
|
1072
|
+
// Prevent concurrent fetches - store range to fetch when current one completes
|
|
1073
|
+
if (fetchingRef.current && visibleRange) {
|
|
1074
|
+
pendingRangeRef.current = { start: visibleRange.start, end: visibleRange.end };
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
// Clamp to available date range (use company timezone - date-fns startOfDay/endOfDay use local TZ which can exclude Oct 12)
|
|
1079
|
+
// For end date, we need end of Oct 12 in company timezone (inclusive)
|
|
1080
|
+
if (!visibleRange) return;
|
|
1081
|
+
|
|
1082
|
+
const startOfEarliestDay = fromZonedTime(new Date(2026, 5, 1, 0, 0, 0, 0), companyTimezone);
|
|
1083
|
+
const endOfLatestDay = fromZonedTime(new Date(2026, 9, 12, 23, 59, 59, 999), companyTimezone);
|
|
1084
|
+
const clampedStart = isBefore(visibleRange.start, startOfEarliestDay)
|
|
1085
|
+
? startOfEarliestDay
|
|
1086
|
+
: visibleRange.start;
|
|
1087
|
+
let clampedEnd = isAfter(visibleRange.end, endOfLatestDay)
|
|
1088
|
+
? endOfLatestDay
|
|
1089
|
+
: visibleRange.end;
|
|
1090
|
+
|
|
1091
|
+
// Ensure we include the selected date if it's after the visible range end
|
|
1092
|
+
// This handles the case where user selects a date that's not yet in the visible range
|
|
1093
|
+
if (selectedDate) {
|
|
1094
|
+
try {
|
|
1095
|
+
const selectedDateObj = parseISO(selectedDate);
|
|
1096
|
+
if (isAfter(selectedDateObj, clampedEnd)) {
|
|
1097
|
+
clampedEnd = selectedDateObj;
|
|
1098
|
+
}
|
|
1099
|
+
} catch {
|
|
1100
|
+
// Ignore parse errors
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
// Check cache first - avoid refetch when reopening same product
|
|
1105
|
+
const cacheKey = availabilitiesCache
|
|
1106
|
+
? buildAvailabilitiesCacheKey(
|
|
1107
|
+
product.productId,
|
|
1108
|
+
activeOptionIdsKey,
|
|
1109
|
+
appliedPromoCode,
|
|
1110
|
+
pricingProfileIdForAvailabilities,
|
|
1111
|
+
)
|
|
1112
|
+
: null;
|
|
1113
|
+
const cached = cacheKey ? availabilitiesCache!.get(cacheKey) : undefined;
|
|
1114
|
+
if (cached && cached.availabilities.length > 0) {
|
|
1115
|
+
const cachedInitialQuantities = deriveDefaultQuantitiesFromAvailabilities(cached.availabilities);
|
|
1116
|
+
if (cachedInitialQuantities) {
|
|
1117
|
+
setQuantities((prev) => (Object.keys(prev).length > 0 ? prev : cachedInitialQuantities));
|
|
1118
|
+
}
|
|
1119
|
+
const cacheCoversRange = cached.fetchedRanges.some(
|
|
1120
|
+
(r) => r.start.getTime() <= clampedStart.getTime() && r.end.getTime() >= clampedEnd.getTime()
|
|
1121
|
+
);
|
|
1122
|
+
const isStale = availabilitiesCache?.isStale(cached) ?? false;
|
|
1123
|
+
if (cacheCoversRange) {
|
|
1124
|
+
setAvailabilities(cached.availabilities);
|
|
1125
|
+
if (cached.pricingConfig) {
|
|
1126
|
+
setPricingConfig(cached.pricingConfig);
|
|
1127
|
+
pricingConfigSetRef.current = true;
|
|
1128
|
+
}
|
|
1129
|
+
if (cached.precomputedPricesByOption && Object.keys(cached.precomputedPricesByOption).length > 0) {
|
|
1130
|
+
setPrecomputedPricesByOption(cached.precomputedPricesByOption);
|
|
1131
|
+
}
|
|
1132
|
+
setLoadingAvailabilities(false);
|
|
1133
|
+
setIsFetchingMoreAvailabilities(false);
|
|
1134
|
+
if (!isStale) {
|
|
1135
|
+
fetchedRangesRef.current = [...cached.fetchedRanges];
|
|
1136
|
+
fetchingRef.current = false;
|
|
1137
|
+
return;
|
|
1138
|
+
}
|
|
1139
|
+
// Stale-while-revalidate: show cached data, fetch in background (don't set fetchedRangesRef so we fall through)
|
|
1140
|
+
}
|
|
1141
|
+
// Partial cache: show cached data immediately, then fetch missing range below
|
|
1142
|
+
setAvailabilities(cached.availabilities);
|
|
1143
|
+
if (cached.pricingConfig) {
|
|
1144
|
+
setPricingConfig(cached.pricingConfig);
|
|
1145
|
+
pricingConfigSetRef.current = true;
|
|
1146
|
+
}
|
|
1147
|
+
if (cached.precomputedPricesByOption && Object.keys(cached.precomputedPricesByOption).length > 0) {
|
|
1148
|
+
setPrecomputedPricesByOption(cached.precomputedPricesByOption);
|
|
1149
|
+
}
|
|
1150
|
+
fetchedRangesRef.current = [...cached.fetchedRanges];
|
|
1151
|
+
setLoadingAvailabilities(false);
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
// Check if we need to fetch this range
|
|
1155
|
+
// Backend always returns CAD prices without fee/tax, so no need to refetch on currency change
|
|
1156
|
+
const shouldFetch = needsFetch(clampedStart, clampedEnd);
|
|
1157
|
+
if (!shouldFetch) {
|
|
1158
|
+
// Range already fetched - ensure loading state is cleared
|
|
1159
|
+
setLoadingAvailabilities(false);
|
|
1160
|
+
setIsFetchingMoreAvailabilities(false);
|
|
1161
|
+
fetchingRef.current = false;
|
|
1162
|
+
return;
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
const hasPartialCache = cached && cached.availabilities.length > 0;
|
|
1166
|
+
fetchingRef.current = true;
|
|
1167
|
+
if (!hasPartialCache) setLoadingAvailabilities(true);
|
|
1168
|
+
else setIsFetchingMoreAvailabilities(true);
|
|
1169
|
+
|
|
1170
|
+
try {
|
|
1171
|
+
let startDateStr: string;
|
|
1172
|
+
let endDateStr: string;
|
|
1173
|
+
|
|
1174
|
+
if (isPrivateShuttle) {
|
|
1175
|
+
// Private Shuttle: use date-only format (YYYY-MM-DD)
|
|
1176
|
+
startDateStr = format(startOfDay(clampedStart), 'yyyy-MM-dd');
|
|
1177
|
+
// Use endOfDay to include the full last day
|
|
1178
|
+
endDateStr = format(endOfDay(clampedEnd), 'yyyy-MM-dd');
|
|
1179
|
+
} else {
|
|
1180
|
+
// Standard products: API expects UTC. Get full first/last days in company TZ, then format as UTC.
|
|
1181
|
+
const startDateInTz = formatInTimeZone(clampedStart, companyTimezone, 'yyyy-MM-dd');
|
|
1182
|
+
const endDateInTz = formatInTimeZone(clampedEnd, companyTimezone, 'yyyy-MM-dd');
|
|
1183
|
+
const startMoment = fromZonedTime(parseISO(`${startDateInTz}T00:00:00.000`), companyTimezone);
|
|
1184
|
+
const endMoment = fromZonedTime(parseISO(`${endDateInTz}T23:59:59.999`), companyTimezone);
|
|
1185
|
+
startDateStr = formatInTimeZone(startMoment, 'UTC', "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
|
|
1186
|
+
endDateStr = formatInTimeZone(endMoment, 'UTC', "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
// Fetch availabilities for all product options in parallel (no currency param - we use precomputedPrices for display)
|
|
1190
|
+
const availabilityPromises = activeOptions.map(async (option) => {
|
|
1191
|
+
const result = await getAvailabilities(option.optionId, startDateStr, endDateStr, {
|
|
1192
|
+
promoCode: appliedPromoCode || undefined,
|
|
1193
|
+
...(pricingProfileIdForAvailabilities
|
|
1194
|
+
? { pricingProfileId: pricingProfileIdForAvailabilities }
|
|
1195
|
+
: {}),
|
|
1196
|
+
...(cancellationPolicyProfileIdForAvailabilities
|
|
1197
|
+
? { cancellationPolicyProfileId: cancellationPolicyProfileIdForAvailabilities }
|
|
1198
|
+
: {}),
|
|
1199
|
+
});
|
|
1200
|
+
// Store pricing config from first response only (all responses have same config)
|
|
1201
|
+
if (result.pricingConfig && !pricingConfigSetRef.current) {
|
|
1202
|
+
setPricingConfig(prev => {
|
|
1203
|
+
if (!prev) {
|
|
1204
|
+
pricingConfigSetRef.current = true;
|
|
1205
|
+
return result.pricingConfig!;
|
|
1206
|
+
}
|
|
1207
|
+
return prev;
|
|
1208
|
+
});
|
|
1209
|
+
}
|
|
1210
|
+
// Tag each availability with its productOptionId and carry precomputedPrices for this option
|
|
1211
|
+
return {
|
|
1212
|
+
optionId: option.optionId,
|
|
1213
|
+
availabilities: result.availabilities.map(avail => ({
|
|
1214
|
+
...avail,
|
|
1215
|
+
productOptionId: option.optionId
|
|
1216
|
+
})),
|
|
1217
|
+
precomputedPrices: result.precomputedPrices,
|
|
1218
|
+
pricingConfig: result.pricingConfig,
|
|
1219
|
+
};
|
|
1220
|
+
});
|
|
1221
|
+
|
|
1222
|
+
const results = await Promise.all(availabilityPromises);
|
|
1223
|
+
const allFetchedAvailabilities = results.flatMap(r => r.availabilities);
|
|
1224
|
+
setPrecomputedPricesByOption(prev => {
|
|
1225
|
+
const next = { ...(prev || {}) };
|
|
1226
|
+
results.forEach(r => {
|
|
1227
|
+
if (r.precomputedPrices && Object.keys(r.precomputedPrices).length > 0) {
|
|
1228
|
+
next[r.optionId] = r.precomputedPrices;
|
|
1229
|
+
}
|
|
1230
|
+
});
|
|
1231
|
+
return Object.keys(next).length > 0 ? next : prev;
|
|
1232
|
+
});
|
|
1233
|
+
|
|
1234
|
+
// Merge with existing availabilities (avoid duplicates by dateTime + productOptionId)
|
|
1235
|
+
setAvailabilities(prev => {
|
|
1236
|
+
const existingMap = new Map(
|
|
1237
|
+
prev.map(avail => [`${avail.dateTime}-${avail.productOptionId}`, avail])
|
|
1238
|
+
);
|
|
1239
|
+
|
|
1240
|
+
// Merge new availabilities - update existing ones or add new ones
|
|
1241
|
+
allFetchedAvailabilities.forEach(avail => {
|
|
1242
|
+
const key = `${avail.dateTime}-${avail.productOptionId}`;
|
|
1243
|
+
// Always update to get latest data (vacancies, prices, etc.)
|
|
1244
|
+
existingMap.set(key, avail);
|
|
1245
|
+
});
|
|
1246
|
+
|
|
1247
|
+
return Array.from(existingMap.values());
|
|
1248
|
+
});
|
|
1249
|
+
|
|
1250
|
+
// Mark this range as fetched
|
|
1251
|
+
fetchedRangesRef.current.push({ start: new Date(clampedStart), end: new Date(clampedEnd) });
|
|
1252
|
+
// Sort and merge overlapping ranges
|
|
1253
|
+
fetchedRangesRef.current.sort((a, b) => a.start.getTime() - b.start.getTime());
|
|
1254
|
+
const merged: Array<{ start: Date; end: Date }> = [];
|
|
1255
|
+
for (const r of fetchedRangesRef.current) {
|
|
1256
|
+
if (merged.length === 0 || merged[merged.length - 1].end < r.start) {
|
|
1257
|
+
merged.push({ start: r.start, end: r.end });
|
|
1258
|
+
} else {
|
|
1259
|
+
merged[merged.length - 1].end = r.end > merged[merged.length - 1].end
|
|
1260
|
+
? r.end
|
|
1261
|
+
: merged[merged.length - 1].end;
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
fetchedRangesRef.current = merged;
|
|
1265
|
+
|
|
1266
|
+
// Update cache for instant load when reopening same product
|
|
1267
|
+
if (cacheKey && availabilitiesCache) {
|
|
1268
|
+
const existingCache = availabilitiesCache.get(cacheKey);
|
|
1269
|
+
const existingAvailabilities = existingCache?.availabilities ?? [];
|
|
1270
|
+
const mergedAvailabilitiesMap = new Map(
|
|
1271
|
+
existingAvailabilities.map((a) => [`${a.dateTime}-${a.productOptionId}`, a])
|
|
1272
|
+
);
|
|
1273
|
+
allFetchedAvailabilities.forEach((a) => {
|
|
1274
|
+
mergedAvailabilitiesMap.set(`${a.dateTime}-${a.productOptionId}`, a);
|
|
1275
|
+
});
|
|
1276
|
+
const mergedPrecomputed = { ...(existingCache?.precomputedPricesByOption ?? {}) };
|
|
1277
|
+
results.forEach((r) => {
|
|
1278
|
+
if (r.precomputedPrices && Object.keys(r.precomputedPrices).length > 0) {
|
|
1279
|
+
mergedPrecomputed[r.optionId] = r.precomputedPrices;
|
|
1280
|
+
}
|
|
1281
|
+
});
|
|
1282
|
+
const firstPricingConfig = (results[0] as { pricingConfig?: PricingConfig } | undefined)?.pricingConfig ?? existingCache?.pricingConfig ?? null;
|
|
1283
|
+
availabilitiesCache.merge(cacheKey, {
|
|
1284
|
+
fetchedRanges: merged,
|
|
1285
|
+
availabilities: Array.from(mergedAvailabilitiesMap.values()),
|
|
1286
|
+
pricingConfig: firstPricingConfig,
|
|
1287
|
+
precomputedPricesByOption: Object.keys(mergedPrecomputed).length > 0 ? mergedPrecomputed : null,
|
|
1288
|
+
});
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
// Initialize quantities based on first availability's categories (only if not already set)
|
|
1292
|
+
// Use functional update to avoid dependency on quantities state
|
|
1293
|
+
const fetchedInitialQuantities = deriveDefaultQuantitiesFromAvailabilities(allFetchedAvailabilities);
|
|
1294
|
+
if (fetchedInitialQuantities) {
|
|
1295
|
+
setQuantities((prev) => (Object.keys(prev).length > 0 ? prev : fetchedInitialQuantities));
|
|
1296
|
+
}
|
|
1297
|
+
} catch (err) {
|
|
1298
|
+
setError(err instanceof Error ? err.message : 'Failed to load availabilities');
|
|
1299
|
+
console.error('Error fetching availabilities:', err);
|
|
1300
|
+
} finally {
|
|
1301
|
+
setLoadingAvailabilities(false);
|
|
1302
|
+
setIsFetchingMoreAvailabilities(false);
|
|
1303
|
+
fetchingRef.current = false;
|
|
1304
|
+
// If user navigated during fetch, trigger fetch for the pending range
|
|
1305
|
+
const pending = pendingRangeRef.current;
|
|
1306
|
+
if (pending) {
|
|
1307
|
+
pendingRangeRef.current = null;
|
|
1308
|
+
setVisibleRange({ start: pending.start, end: pending.end });
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
fetchAvailabilities();
|
|
1314
|
+
// Use activeOptionIdsKey only — activeOptions is a new array reference when product.options identity changes and would refetch in a tight loop.
|
|
1315
|
+
}, [
|
|
1316
|
+
isPartialLaunch,
|
|
1317
|
+
visibleRange,
|
|
1318
|
+
activeOptionIdsKey,
|
|
1319
|
+
isPrivateShuttle,
|
|
1320
|
+
companyTimezone,
|
|
1321
|
+
selectedDate,
|
|
1322
|
+
appliedPromoCode,
|
|
1323
|
+
pricingProfileIdForAvailabilities,
|
|
1324
|
+
cancellationPolicyProfileIdForAvailabilities,
|
|
1325
|
+
]);
|
|
1326
|
+
|
|
1327
|
+
// When promo or partner pricing profile changes, clear fetched ranges so we refetch with new pricing
|
|
1328
|
+
useEffect(() => {
|
|
1329
|
+
fetchedRangesRef.current = [];
|
|
1330
|
+
}, [
|
|
1331
|
+
appliedPromoCode,
|
|
1332
|
+
pricingProfileIdForAvailabilities,
|
|
1333
|
+
cancellationPolicyProfileIdForAvailabilities,
|
|
1334
|
+
]);
|
|
1335
|
+
|
|
1336
|
+
// Memoized callback for visible range changes
|
|
1337
|
+
// Only update if the range actually changed to avoid unnecessary fetches
|
|
1338
|
+
const lastVisibleRangeRef = useRef<{ start: Date; end: Date } | null>(null);
|
|
1339
|
+
const handleVisibleRangeChange = useCallback((start: Date, end: Date) => {
|
|
1340
|
+
const lastRange = lastVisibleRangeRef.current;
|
|
1341
|
+
// Update if this is the first range or if it changed significantly (more than a day)
|
|
1342
|
+
const rangeChanged = !lastRange ||
|
|
1343
|
+
Math.abs(lastRange.start.getTime() - start.getTime()) > 24 * 60 * 60 * 1000 ||
|
|
1344
|
+
Math.abs(lastRange.end.getTime() - end.getTime()) > 24 * 60 * 60 * 1000;
|
|
1345
|
+
|
|
1346
|
+
if (rangeChanged) {
|
|
1347
|
+
lastVisibleRangeRef.current = { start, end };
|
|
1348
|
+
// Always update state to trigger fetch, even if needsFetch might return false
|
|
1349
|
+
// The needsFetch check will prevent unnecessary API calls, but we want the state update
|
|
1350
|
+
setVisibleRange({ start, end });
|
|
1351
|
+
}
|
|
1352
|
+
}, []);
|
|
1353
|
+
|
|
1354
|
+
// Group availabilities by date (in company timezone) and sort by time
|
|
1355
|
+
// Memoized to prevent recalculation on every render
|
|
1356
|
+
const availabilitiesByDate = useMemo(() => {
|
|
1357
|
+
const grouped = availabilities.reduce((acc, avail) => {
|
|
1358
|
+
// Parse the dateTime and extract the date in company timezone
|
|
1359
|
+
const dateTime = parseAvailabilityDateTime(avail.dateTime);
|
|
1360
|
+
const dateInCompanyTz = formatInTimeZone(dateTime, companyTimezone, 'yyyy-MM-dd');
|
|
1361
|
+
if (!acc[dateInCompanyTz]) acc[dateInCompanyTz] = [];
|
|
1362
|
+
acc[dateInCompanyTz].push(avail);
|
|
1363
|
+
return acc;
|
|
1364
|
+
}, {} as Record<string, Availability[]>);
|
|
1365
|
+
|
|
1366
|
+
// Sort availabilities within each date by time (create new sorted arrays, don't mutate)
|
|
1367
|
+
const sorted: Record<string, Availability[]> = {};
|
|
1368
|
+
Object.keys(grouped).forEach(date => {
|
|
1369
|
+
sorted[date] = [...grouped[date]].sort((a, b) => {
|
|
1370
|
+
const timeA = parseAvailabilityDateTime(a.dateTime).getTime();
|
|
1371
|
+
const timeB = parseAvailabilityDateTime(b.dateTime).getTime();
|
|
1372
|
+
return timeA - timeB;
|
|
1373
|
+
});
|
|
1374
|
+
});
|
|
1375
|
+
|
|
1376
|
+
return sorted;
|
|
1377
|
+
}, [availabilities, companyTimezone]);
|
|
1378
|
+
|
|
1379
|
+
const dates = useMemo(() => Object.keys(availabilitiesByDate).sort(), [availabilitiesByDate]);
|
|
1380
|
+
|
|
1381
|
+
// Track mobile state
|
|
1382
|
+
useEffect(() => {
|
|
1383
|
+
const checkMobile = () => {
|
|
1384
|
+
setIsMobile(window.innerWidth < 640); // sm breakpoint
|
|
1385
|
+
};
|
|
1386
|
+
checkMobile();
|
|
1387
|
+
window.addEventListener('resize', checkMobile);
|
|
1388
|
+
return () => window.removeEventListener('resize', checkMobile);
|
|
1389
|
+
}, []);
|
|
1390
|
+
|
|
1391
|
+
// Close tooltip when clicking outside
|
|
1392
|
+
useEffect(() => {
|
|
1393
|
+
if (!showTooltip) return;
|
|
1394
|
+
|
|
1395
|
+
const handleClickOutside = (e: MouseEvent | TouchEvent) => {
|
|
1396
|
+
const target = e.target as HTMLElement;
|
|
1397
|
+
if (!target.closest('[data-tooltip-icon]')) {
|
|
1398
|
+
setShowTooltip(false);
|
|
1399
|
+
}
|
|
1400
|
+
};
|
|
1401
|
+
|
|
1402
|
+
document.addEventListener('mousedown', handleClickOutside);
|
|
1403
|
+
document.addEventListener('touchstart', handleClickOutside);
|
|
1404
|
+
|
|
1405
|
+
return () => {
|
|
1406
|
+
document.removeEventListener('mousedown', handleClickOutside);
|
|
1407
|
+
document.removeEventListener('touchstart', handleClickOutside);
|
|
1408
|
+
};
|
|
1409
|
+
}, [showTooltip]);
|
|
1410
|
+
|
|
1411
|
+
// Detect when itinerary box becomes sticky
|
|
1412
|
+
// In viavia the scroll usually happens inside the dialog content div, not window.
|
|
1413
|
+
// On full-page partner layouts, we instead listen to window scroll (useWindowScroll = true).
|
|
1414
|
+
const lastStickyChangeRef = useRef<number>(0);
|
|
1415
|
+
useEffect(() => {
|
|
1416
|
+
const el = itineraryRef.current;
|
|
1417
|
+
if (!el) return;
|
|
1418
|
+
|
|
1419
|
+
const findScrollParent = (node: HTMLElement): HTMLElement | null => {
|
|
1420
|
+
let parent = node.parentElement;
|
|
1421
|
+
while (parent) {
|
|
1422
|
+
const { overflowY } = getComputedStyle(parent);
|
|
1423
|
+
if (overflowY === 'auto' || overflowY === 'scroll' || overflowY === 'overlay') return parent;
|
|
1424
|
+
parent = parent.parentElement;
|
|
1425
|
+
}
|
|
1426
|
+
return null;
|
|
1427
|
+
};
|
|
1428
|
+
|
|
1429
|
+
const scrollParent = findScrollParent(el);
|
|
1430
|
+
const scrollTarget =
|
|
1431
|
+
useWindowScroll || !scrollParent
|
|
1432
|
+
? (typeof window !== 'undefined' ? window : null)
|
|
1433
|
+
: scrollParent;
|
|
1434
|
+
|
|
1435
|
+
let ticking = false;
|
|
1436
|
+
const COOLDOWN_MS = 600; // After a state change, ignore reverse changes for this long (covers 0.25s collapse animation + layout settle)
|
|
1437
|
+
const atTopBand = 48; // px - must scroll back up past this band to expand again (wider = less oscillation at edges)
|
|
1438
|
+
|
|
1439
|
+
const updateStickyState = () => {
|
|
1440
|
+
if (!itineraryRef.current) return;
|
|
1441
|
+
|
|
1442
|
+
const rect = itineraryRef.current.getBoundingClientRect();
|
|
1443
|
+
const currentTop = rect.top;
|
|
1444
|
+
const wasSticky = isItineraryStickyRef.current;
|
|
1445
|
+
|
|
1446
|
+
const containerTop =
|
|
1447
|
+
scrollParent && !useWindowScroll ? scrollParent.getBoundingClientRect().top : 0;
|
|
1448
|
+
const topInset = Math.max(0, flowUi?.itineraryStickyTopOffsetPx ?? 0);
|
|
1449
|
+
const stickLine = containerTop + topInset;
|
|
1450
|
+
const enterStickyThreshold = stickLine + 1;
|
|
1451
|
+
const nextSticky = wasSticky
|
|
1452
|
+
? currentTop >= stickLine - atTopBand && currentTop <= stickLine + atTopBand
|
|
1453
|
+
: currentTop <= enterStickyThreshold;
|
|
1454
|
+
|
|
1455
|
+
if (nextSticky !== wasSticky) {
|
|
1456
|
+
const now = Date.now();
|
|
1457
|
+
if (now - lastStickyChangeRef.current < COOLDOWN_MS) return; // Cooldown: prevent rapid toggling
|
|
1458
|
+
|
|
1459
|
+
lastStickyChangeRef.current = now;
|
|
1460
|
+
isItineraryStickyRef.current = nextSticky;
|
|
1461
|
+
setIsItinerarySticky(nextSticky);
|
|
1462
|
+
}
|
|
1463
|
+
};
|
|
1464
|
+
|
|
1465
|
+
const handleScroll = () => {
|
|
1466
|
+
if (!ticking) {
|
|
1467
|
+
window.requestAnimationFrame(() => {
|
|
1468
|
+
updateStickyState();
|
|
1469
|
+
ticking = false;
|
|
1470
|
+
});
|
|
1471
|
+
ticking = true;
|
|
1472
|
+
}
|
|
1473
|
+
};
|
|
1474
|
+
|
|
1475
|
+
if (scrollTarget) {
|
|
1476
|
+
scrollTarget.addEventListener('scroll', handleScroll, { passive: true });
|
|
1477
|
+
updateStickyState();
|
|
1478
|
+
return () => scrollTarget.removeEventListener('scroll', handleScroll);
|
|
1479
|
+
}
|
|
1480
|
+
return undefined;
|
|
1481
|
+
}, [selectedDate, selectedAvailability, useWindowScroll, flowUi?.itineraryStickyTopOffsetPx]); // Re-check when itinerary / scroll mode / host chrome changes
|
|
1482
|
+
|
|
1483
|
+
// Find the earliest availability date - memoize with a stable reference
|
|
1484
|
+
// Only recalculate if we don't have a cached value or if the new earliest is actually earlier
|
|
1485
|
+
// IMPORTANT: Never return null once we have a value, to prevent calendar reset during loading
|
|
1486
|
+
const earliestAvailabilityDateRef = useRef<Date | null>(null);
|
|
1487
|
+
const earliestAvailabilityDate = useMemo(() => {
|
|
1488
|
+
if (dates.length === 0) {
|
|
1489
|
+
// If we have a cached value, keep using it even during loading
|
|
1490
|
+
return earliestAvailabilityDateRef.current || EARLIEST_AVAILABILITY_DATE;
|
|
1491
|
+
}
|
|
1492
|
+
const firstDate = dates[0];
|
|
1493
|
+
const firstAvail = availabilitiesByDate[firstDate]?.[0];
|
|
1494
|
+
let newEarliest: Date;
|
|
1495
|
+
if (firstAvail) {
|
|
1496
|
+
newEarliest = parseISO(firstAvail.dateTime);
|
|
1497
|
+
} else {
|
|
1498
|
+
// Fallback: parse the date string
|
|
1499
|
+
// Use company timezone noon to avoid one-day shifts for users in other timezones.
|
|
1500
|
+
newEarliest = fromZonedTime(parseISO(`${firstDate}T12:00:00`), companyTimezone);
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
// Only update if we don't have a cached value or if the new one is earlier
|
|
1504
|
+
if (!earliestAvailabilityDateRef.current || newEarliest < earliestAvailabilityDateRef.current) {
|
|
1505
|
+
earliestAvailabilityDateRef.current = newEarliest;
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
return earliestAvailabilityDateRef.current;
|
|
1509
|
+
}, [dates, availabilitiesByDate]);
|
|
1510
|
+
|
|
1511
|
+
const timesForSelectedDate = useMemo(() => {
|
|
1512
|
+
return selectedDate ? availabilitiesByDate[selectedDate] || [] : [];
|
|
1513
|
+
}, [selectedDate, availabilitiesByDate]);
|
|
1514
|
+
const timesForSelectedDateSelectionKey = useMemo(
|
|
1515
|
+
() =>
|
|
1516
|
+
timesForSelectedDate
|
|
1517
|
+
.map(
|
|
1518
|
+
(avail) =>
|
|
1519
|
+
`${avail.dateTime}|${avail.productOptionId ?? ''}|${avail.vacancies ?? 0}`,
|
|
1520
|
+
)
|
|
1521
|
+
.join('||'),
|
|
1522
|
+
[timesForSelectedDate],
|
|
1523
|
+
);
|
|
1524
|
+
|
|
1525
|
+
useEffect(() => {
|
|
1526
|
+
if (hasAppliedInitialValuesRef.current || !initialValues) return;
|
|
1527
|
+
const trimmedEmail = initialValues.customer?.email?.trim();
|
|
1528
|
+
const trimmedFirstName = initialValues.customer?.firstName?.trim();
|
|
1529
|
+
const trimmedLastName = initialValues.customer?.lastName?.trim();
|
|
1530
|
+
const trimmedPromo = initialValues.promoCode?.trim().toUpperCase();
|
|
1531
|
+
if (trimmedEmail) setEmail(trimmedEmail);
|
|
1532
|
+
if (trimmedFirstName) setFirstName(trimmedFirstName);
|
|
1533
|
+
if (trimmedLastName) setLastName(trimmedLastName);
|
|
1534
|
+
if (initialValues.pickupLocationId?.trim()) {
|
|
1535
|
+
setPickupLocationId(initialValues.pickupLocationId.trim());
|
|
1536
|
+
setPickupLocationSkipped(false);
|
|
1537
|
+
}
|
|
1538
|
+
if (trimmedPromo) {
|
|
1539
|
+
setPromoCodeInput(trimmedPromo);
|
|
1540
|
+
setAppliedPromoCode(trimmedPromo);
|
|
1541
|
+
}
|
|
1542
|
+
hasAppliedInitialValuesRef.current = true;
|
|
1543
|
+
}, [initialValues]);
|
|
1544
|
+
|
|
1545
|
+
useEffect(() => {
|
|
1546
|
+
if (!lockedPromoCode) return;
|
|
1547
|
+
if (appliedPromoCode !== lockedPromoCode) setAppliedPromoCode(lockedPromoCode);
|
|
1548
|
+
if (promoCodeInput !== lockedPromoCode) setPromoCodeInput(lockedPromoCode);
|
|
1549
|
+
}, [lockedPromoCode, appliedPromoCode, promoCodeInput]);
|
|
1550
|
+
|
|
1551
|
+
useEffect(() => {
|
|
1552
|
+
if (!initialValues?.dateTime || selectedAvailability) return;
|
|
1553
|
+
const target = parseAvailabilityDateTime(initialValues.dateTime);
|
|
1554
|
+
const targetDate = formatInTimeZone(target, companyTimezone, 'yyyy-MM-dd');
|
|
1555
|
+
if (!selectedDate) {
|
|
1556
|
+
setSelectedDate(targetDate);
|
|
1557
|
+
return;
|
|
1558
|
+
}
|
|
1559
|
+
if (selectedDate !== targetDate || timesForSelectedDate.length === 0) return;
|
|
1560
|
+
const { selection, defer } = resolveInitialAvailabilityFromBooking(
|
|
1561
|
+
timesForSelectedDate,
|
|
1562
|
+
target,
|
|
1563
|
+
companyTimezone,
|
|
1564
|
+
initialValues.availabilityId ?? null,
|
|
1565
|
+
initialValues.productOptionId ?? null,
|
|
1566
|
+
initialValues.bookingItems ?? null,
|
|
1567
|
+
precomputedPricesByOption,
|
|
1568
|
+
currency,
|
|
1569
|
+
originalReceipt?.subtotal
|
|
1570
|
+
);
|
|
1571
|
+
if (defer) return;
|
|
1572
|
+
if (selection) {
|
|
1573
|
+
setSelectedAvailability(selection);
|
|
1574
|
+
setError('');
|
|
1575
|
+
}
|
|
1576
|
+
}, [
|
|
1577
|
+
initialValues?.dateTime,
|
|
1578
|
+
initialValues?.availabilityId,
|
|
1579
|
+
initialValues?.productOptionId,
|
|
1580
|
+
initialValues?.bookingItems,
|
|
1581
|
+
selectedAvailability,
|
|
1582
|
+
selectedDate,
|
|
1583
|
+
timesForSelectedDate,
|
|
1584
|
+
companyTimezone,
|
|
1585
|
+
precomputedPricesByOption,
|
|
1586
|
+
currency,
|
|
1587
|
+
originalReceipt?.subtotal,
|
|
1588
|
+
]);
|
|
1589
|
+
|
|
1590
|
+
useEffect(() => {
|
|
1591
|
+
if (
|
|
1592
|
+
hasAppliedInitialQuantitiesRef.current ||
|
|
1593
|
+
!initialValues?.bookingItems ||
|
|
1594
|
+
initialValues.bookingItems.length === 0 ||
|
|
1595
|
+
!selectedAvailability
|
|
1596
|
+
) {
|
|
1597
|
+
return;
|
|
1598
|
+
}
|
|
1599
|
+
const next: Record<string, number> = {};
|
|
1600
|
+
for (const item of initialValues.bookingItems) {
|
|
1601
|
+
const key = item.category?.trim();
|
|
1602
|
+
if (!key) continue;
|
|
1603
|
+
next[key] = Math.max(0, Number(item.count) || 0);
|
|
1604
|
+
}
|
|
1605
|
+
if (Object.keys(next).length > 0) {
|
|
1606
|
+
setQuantities((prev) => ({ ...prev, ...next }));
|
|
1607
|
+
hasAppliedInitialQuantitiesRef.current = true;
|
|
1608
|
+
}
|
|
1609
|
+
}, [initialValues, selectedAvailability]);
|
|
1610
|
+
|
|
1611
|
+
useEffect(() => {
|
|
1612
|
+
if (!isChangeFlow) return;
|
|
1613
|
+
if (!initialValues?.addOnSelections?.length) return;
|
|
1614
|
+
setAddOnSelections((prev) => (prev.length > 0 ? prev : normalizeAddOnSelections(initialValues.addOnSelections!)));
|
|
1615
|
+
}, [isChangeFlow, initialValues?.addOnSelections]);
|
|
1616
|
+
|
|
1617
|
+
useEffect(() => {
|
|
1618
|
+
if (!isChangeFlow) return;
|
|
1619
|
+
if (hasHydratedAddOnsFromReceiptRef.current) return;
|
|
1620
|
+
if ((initialValues?.addOnSelections?.length ?? 0) > 0) return;
|
|
1621
|
+
if (addOnSelections.length > 0) return;
|
|
1622
|
+
if (addOns.length === 0) return;
|
|
1623
|
+
const receiptLines = originalReceipt?.lineItems ?? [];
|
|
1624
|
+
if (receiptLines.length === 0) return;
|
|
1625
|
+
const derived = deriveAddOnSelectionsFromReceiptLines(addOns, receiptLines);
|
|
1626
|
+
hasHydratedAddOnsFromReceiptRef.current = true;
|
|
1627
|
+
if (derived.length > 0) {
|
|
1628
|
+
setAddOnSelections(normalizeAddOnSelections(derived));
|
|
1629
|
+
}
|
|
1630
|
+
}, [
|
|
1631
|
+
isChangeFlow,
|
|
1632
|
+
initialValues?.addOnSelections,
|
|
1633
|
+
addOnSelections.length,
|
|
1634
|
+
addOns,
|
|
1635
|
+
originalReceipt?.lineItems,
|
|
1636
|
+
]);
|
|
1637
|
+
|
|
1638
|
+
const initialAddOnBaselineSelections = useMemo(() => {
|
|
1639
|
+
if (!isChangeFlow) return [] as Array<{ addOnId: string; variantId?: string; quantity?: number }>;
|
|
1640
|
+
if ((initialValues?.addOnSelections?.length ?? 0) > 0) {
|
|
1641
|
+
return normalizeAddOnSelections(initialValues!.addOnSelections!);
|
|
1642
|
+
}
|
|
1643
|
+
if ((originalReceipt?.lineItems?.length ?? 0) > 0 && addOns.length > 0) {
|
|
1644
|
+
return normalizeAddOnSelections(deriveAddOnSelectionsFromReceiptLines(addOns, originalReceipt!.lineItems!));
|
|
1645
|
+
}
|
|
1646
|
+
return [] as Array<{ addOnId: string; variantId?: string; quantity?: number }>;
|
|
1647
|
+
}, [isChangeFlow, initialValues?.addOnSelections, originalReceipt?.lineItems, addOns]);
|
|
1648
|
+
|
|
1649
|
+
const initialAddOnMinQtyByKey = useMemo(() => {
|
|
1650
|
+
const map = new Map<string, number>();
|
|
1651
|
+
if (!isChangeFlow) return map;
|
|
1652
|
+
for (const sel of initialAddOnBaselineSelections) {
|
|
1653
|
+
const key = `${sel.addOnId.trim()}::${sel.variantId?.trim() || ''}`;
|
|
1654
|
+
map.set(key, (map.get(key) ?? 0) + Math.max(1, Number(sel.quantity) || 1));
|
|
1655
|
+
}
|
|
1656
|
+
return map;
|
|
1657
|
+
}, [isChangeFlow, initialAddOnBaselineSelections]);
|
|
1658
|
+
|
|
1659
|
+
const initialAddOnMinTotalByAddOnId = useMemo(() => {
|
|
1660
|
+
const map = new Map<string, number>();
|
|
1661
|
+
if (!isChangeFlow) return map;
|
|
1662
|
+
for (const sel of initialAddOnBaselineSelections) {
|
|
1663
|
+
const addOnId = sel.addOnId.trim();
|
|
1664
|
+
map.set(addOnId, (map.get(addOnId) ?? 0) + Math.max(1, Number(sel.quantity) || 1));
|
|
1665
|
+
}
|
|
1666
|
+
return map;
|
|
1667
|
+
}, [isChangeFlow, initialAddOnBaselineSelections]);
|
|
1668
|
+
|
|
1669
|
+
const applyChangeFlowAddOnFloor = useCallback(
|
|
1670
|
+
(nextSelections: Array<{ addOnId: string; variantId?: string; quantity?: number }>) => {
|
|
1671
|
+
if (!isChangeFlow || initialAddOnMinQtyByKey.size === 0) return nextSelections;
|
|
1672
|
+
const qtyByKey = new Map<string, number>();
|
|
1673
|
+
for (const sel of nextSelections) {
|
|
1674
|
+
const key = `${sel.addOnId.trim()}::${sel.variantId?.trim() || ''}`;
|
|
1675
|
+
qtyByKey.set(key, (qtyByKey.get(key) ?? 0) + Math.max(1, Number(sel.quantity) || 1));
|
|
1676
|
+
}
|
|
1677
|
+
|
|
1678
|
+
const totalByAddOnId = new Map<string, number>();
|
|
1679
|
+
for (const [key, qty] of qtyByKey.entries()) {
|
|
1680
|
+
const addOnId = key.split('::')[0];
|
|
1681
|
+
totalByAddOnId.set(addOnId, (totalByAddOnId.get(addOnId) ?? 0) + qty);
|
|
1682
|
+
}
|
|
1683
|
+
|
|
1684
|
+
for (const [addOnId, minTotal] of initialAddOnMinTotalByAddOnId.entries()) {
|
|
1685
|
+
const currentTotal = totalByAddOnId.get(addOnId) ?? 0;
|
|
1686
|
+
if (currentTotal >= minTotal) continue;
|
|
1687
|
+
const deficit = minTotal - currentTotal;
|
|
1688
|
+
const existingKey = Array.from(qtyByKey.keys()).find((k) => k.startsWith(`${addOnId}::`));
|
|
1689
|
+
const targetKey = existingKey ?? `${addOnId}::`;
|
|
1690
|
+
qtyByKey.set(targetKey, (qtyByKey.get(targetKey) ?? 0) + deficit);
|
|
1691
|
+
}
|
|
1692
|
+
return Array.from(qtyByKey.entries()).map(([key, qty]) => {
|
|
1693
|
+
const [addOnId, variantIdRaw] = key.split('::');
|
|
1694
|
+
const variantId = variantIdRaw?.trim() || undefined;
|
|
1695
|
+
return { addOnId, variantId, quantity: qty };
|
|
1696
|
+
});
|
|
1697
|
+
},
|
|
1698
|
+
[isChangeFlow, initialAddOnMinQtyByKey, initialAddOnMinTotalByAddOnId]
|
|
1699
|
+
);
|
|
1700
|
+
|
|
1701
|
+
const updateAddOnSelections = useCallback(
|
|
1702
|
+
(
|
|
1703
|
+
updater:
|
|
1704
|
+
| Array<{ addOnId: string; variantId?: string; quantity?: number }>
|
|
1705
|
+
| ((prev: Array<{ addOnId: string; variantId?: string; quantity?: number }>) => Array<{ addOnId: string; variantId?: string; quantity?: number }>)
|
|
1706
|
+
) => {
|
|
1707
|
+
setAddOnSelections((prev) => {
|
|
1708
|
+
const rawNext = typeof updater === 'function' ? updater(prev) : updater;
|
|
1709
|
+
return applyChangeFlowAddOnFloor(rawNext);
|
|
1710
|
+
});
|
|
1711
|
+
},
|
|
1712
|
+
[applyChangeFlowAddOnFloor]
|
|
1713
|
+
);
|
|
1714
|
+
|
|
1715
|
+
// Get selected pickup location
|
|
1716
|
+
const selectedPickupLocation = useMemo(() =>
|
|
1717
|
+
product.pickupLocations?.find(loc => loc.id === pickupLocationId),
|
|
1718
|
+
[product.pickupLocations, pickupLocationId]
|
|
1719
|
+
);
|
|
1720
|
+
|
|
1721
|
+
// Calculate maximum time offset from all pickup locations (for range display when location is unknown)
|
|
1722
|
+
const maxTimeOffsetMinutes = useMemo(() => {
|
|
1723
|
+
if (!product.pickupLocations || product.pickupLocations.length === 0) {
|
|
1724
|
+
return 0;
|
|
1725
|
+
}
|
|
1726
|
+
return Math.max(...product.pickupLocations.map(loc => loc.pickupTimeOffsetMinutes ?? 0));
|
|
1727
|
+
}, [product.pickupLocations]);
|
|
1728
|
+
|
|
1729
|
+
// Calculate pickup times based on availability times + pickup location offset
|
|
1730
|
+
interface PickupTimeInfo extends Availability {
|
|
1731
|
+
pickupTime: string;
|
|
1732
|
+
displayTime: string;
|
|
1733
|
+
originalTime: string;
|
|
1734
|
+
displayTimeRange?: string; // Time range when pickup location is unknown
|
|
1735
|
+
}
|
|
1736
|
+
|
|
1737
|
+
const pickupTimes = useMemo((): PickupTimeInfo[] => {
|
|
1738
|
+
if (!selectedDate || !timesForSelectedDate.length) {
|
|
1739
|
+
return [];
|
|
1740
|
+
}
|
|
1741
|
+
|
|
1742
|
+
// Show base availability times (without pickup location offset) when pickup location not selected yet
|
|
1743
|
+
// Once pickup location is selected, we can show adjusted times
|
|
1744
|
+
const offsetMinutes = pickupLocationSkipped
|
|
1745
|
+
? 0
|
|
1746
|
+
: (selectedPickupLocation?.pickupTimeOffsetMinutes ?? 0);
|
|
1747
|
+
|
|
1748
|
+
return timesForSelectedDate.map(avail => {
|
|
1749
|
+
// Parse the dateTime (which should already be in company timezone from backend)
|
|
1750
|
+
const availabilityTime = parseISO(avail.dateTime);
|
|
1751
|
+
|
|
1752
|
+
// Only apply offset if it's set and > 0 and location is selected
|
|
1753
|
+
const pickupTime = (offsetMinutes > 0 && selectedPickupLocation)
|
|
1754
|
+
? new Date(availabilityTime.getTime() + offsetMinutes * 60 * 1000)
|
|
1755
|
+
: availabilityTime;
|
|
1756
|
+
|
|
1757
|
+
// Format in company timezone (not user's local timezone)
|
|
1758
|
+
const displayTime = formatInTimeZone(pickupTime, companyTimezone, 'h:mm a');
|
|
1759
|
+
const originalTime = formatInTimeZone(availabilityTime, companyTimezone, 'h:mm a');
|
|
1760
|
+
|
|
1761
|
+
// If pickup location is skipped, calculate and display time range
|
|
1762
|
+
let displayTimeRange: string | undefined;
|
|
1763
|
+
if (pickupLocationSkipped && maxTimeOffsetMinutes > 0) {
|
|
1764
|
+
const latestPickupTime = new Date(availabilityTime.getTime() + maxTimeOffsetMinutes * 60 * 1000);
|
|
1765
|
+
const latestTimeStr = formatInTimeZone(latestPickupTime, companyTimezone, 'h:mm a');
|
|
1766
|
+
displayTimeRange = `${originalTime} - ${latestTimeStr}`;
|
|
1767
|
+
}
|
|
1768
|
+
|
|
1769
|
+
return {
|
|
1770
|
+
...avail,
|
|
1771
|
+
pickupTime: pickupTime.toISOString(),
|
|
1772
|
+
displayTime,
|
|
1773
|
+
originalTime,
|
|
1774
|
+
displayTimeRange,
|
|
1775
|
+
};
|
|
1776
|
+
});
|
|
1777
|
+
}, [selectedDate, selectedPickupLocation, timesForSelectedDate, pickupLocationSkipped, maxTimeOffsetMinutes, companyTimezone]);
|
|
1778
|
+
|
|
1779
|
+
// Check if any pickup time has "most popular" tag (memoized for performance)
|
|
1780
|
+
const hasAnyMostPopular = useMemo(() => {
|
|
1781
|
+
if (pickupTimes.length <= 1) return false;
|
|
1782
|
+
return pickupTimes.some(t => {
|
|
1783
|
+
if (!t.productOptionId) return false;
|
|
1784
|
+
const opt = optionsMap.get(t.productOptionId);
|
|
1785
|
+
return opt?.mostPopular;
|
|
1786
|
+
});
|
|
1787
|
+
}, [pickupTimes, optionsMap]);
|
|
1788
|
+
|
|
1789
|
+
// Helper function to get effective itinerary based on selected date and overrides
|
|
1790
|
+
const getEffectiveItinerary = useCallback((option: typeof activeOptions[0], date: Date): typeof option.itinerary => {
|
|
1791
|
+
if (!option.itinerary) return undefined;
|
|
1792
|
+
|
|
1793
|
+
const monthDay = formatInTimeZone(date, companyTimezone, 'MM-dd');
|
|
1794
|
+
|
|
1795
|
+
// Check for date-specific override
|
|
1796
|
+
if (option.itineraryOverrides && option.itineraryOverrides.length > 0) {
|
|
1797
|
+
for (const override of option.itineraryOverrides) {
|
|
1798
|
+
if (monthDay >= override.startDate && monthDay <= override.endDate) {
|
|
1799
|
+
return override.itinerary;
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
|
|
1804
|
+
return option.itinerary;
|
|
1805
|
+
}, [companyTimezone]);
|
|
1806
|
+
|
|
1807
|
+
// Helper function to calculate stay summary for a specific return option
|
|
1808
|
+
const calculateStaySummary = useCallback((returnDateTime: Date): string | null => {
|
|
1809
|
+
if (!selectedAvailability) return null;
|
|
1810
|
+
|
|
1811
|
+
const availabilityProductOptionId = selectedAvailability.productOptionId || activeOptions[0]?.optionId;
|
|
1812
|
+
const selectedOption = activeOptions.find(opt => opt.optionId === availabilityProductOptionId);
|
|
1813
|
+
if (!selectedOption) return null;
|
|
1814
|
+
|
|
1815
|
+
const tourStartTime = parseISO(selectedAvailability.dateTime);
|
|
1816
|
+
const itinerary = getEffectiveItinerary(selectedOption, tourStartTime);
|
|
1817
|
+
const hasItinerary = itinerary && itinerary.length > 0 && product.destinations && product.destinations.length > 0;
|
|
1818
|
+
|
|
1819
|
+
if (!hasItinerary || !product.destinations || !itinerary) return null;
|
|
1820
|
+
|
|
1821
|
+
const destinationMap = new Map(product.destinations.map(d => [d.name, d]));
|
|
1822
|
+
let lastDepartureTime = tourStartTime;
|
|
1823
|
+
|
|
1824
|
+
const stays: Array<{ destinationName: string; durationHours: number }> = [];
|
|
1825
|
+
|
|
1826
|
+
itinerary.forEach((itineraryItem, index) => {
|
|
1827
|
+
const destination = destinationMap.get(itineraryItem.destinationName);
|
|
1828
|
+
if (!destination) return;
|
|
1829
|
+
|
|
1830
|
+
const arrivalTime = new Date(
|
|
1831
|
+
lastDepartureTime.getTime() + (itineraryItem.travelTimeFromPreviousHours * 60 * 60 * 1000)
|
|
1832
|
+
);
|
|
1833
|
+
|
|
1834
|
+
const isLastDestination = index === itinerary.length - 1;
|
|
1835
|
+
|
|
1836
|
+
if (isLastDestination) {
|
|
1837
|
+
// For the last destination, calculate time from arrival to return time
|
|
1838
|
+
const timeDiffMs = returnDateTime.getTime() - arrivalTime.getTime();
|
|
1839
|
+
const timeDiffHours = timeDiffMs / (1000 * 60 * 60);
|
|
1840
|
+
|
|
1841
|
+
if (timeDiffHours > 0) {
|
|
1842
|
+
stays.push({
|
|
1843
|
+
destinationName: destination.name,
|
|
1844
|
+
durationHours: timeDiffHours,
|
|
1845
|
+
});
|
|
1846
|
+
}
|
|
1847
|
+
} else {
|
|
1848
|
+
// For non-last destinations (including first), use durationHours only if there's more than one stop
|
|
1849
|
+
if (itinerary.length > 1 && itineraryItem.durationHours && itineraryItem.durationHours > 0) {
|
|
1850
|
+
stays.push({
|
|
1851
|
+
destinationName: destination.name,
|
|
1852
|
+
durationHours: itineraryItem.durationHours,
|
|
1853
|
+
});
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
|
|
1857
|
+
const departureTime = itineraryItem.durationHours && !isLastDestination
|
|
1858
|
+
? new Date(arrivalTime.getTime() + (itineraryItem.durationHours * 60 * 60 * 1000))
|
|
1859
|
+
: arrivalTime;
|
|
1860
|
+
|
|
1861
|
+
lastDepartureTime = departureTime;
|
|
1862
|
+
});
|
|
1863
|
+
|
|
1864
|
+
if (stays.length === 0) return null;
|
|
1865
|
+
|
|
1866
|
+
// Build summary string e.g. "2 hours at [destination] + 2 hours at [destination]"
|
|
1867
|
+
return stays.map(stay => {
|
|
1868
|
+
const hours = Math.floor(stay.durationHours);
|
|
1869
|
+
const minutes = Math.round((stay.durationHours - hours) * 60);
|
|
1870
|
+
let timeStr = '';
|
|
1871
|
+
if (hours === 0 && minutes === 0) {
|
|
1872
|
+
timeStr = '0 min';
|
|
1873
|
+
} else if (hours === 0) {
|
|
1874
|
+
timeStr = `${minutes} min`;
|
|
1875
|
+
} else if (minutes === 0) {
|
|
1876
|
+
timeStr = `${hours} ${hours === 1 ? 'hour' : 'hours'}`;
|
|
1877
|
+
} else {
|
|
1878
|
+
timeStr = `${hours} ${hours === 1 ? 'hour' : 'hours'} ${minutes} min`;
|
|
1879
|
+
}
|
|
1880
|
+
return `${timeStr} at ${stay.destinationName}`;
|
|
1881
|
+
}).join(' + ');
|
|
1882
|
+
}, [selectedAvailability, activeOptions, product.destinations, getEffectiveItinerary]);
|
|
1883
|
+
|
|
1884
|
+
// Helper function to compute itinerary display for storage (returns same shape as "Your Itinerary" box)
|
|
1885
|
+
const computeItineraryDisplay = useCallback((): ItineraryDisplayStep[] | null => {
|
|
1886
|
+
if (!selectedAvailability) return null;
|
|
1887
|
+
const availabilityProductOptionId = selectedAvailability.productOptionId || activeOptions[0]?.optionId;
|
|
1888
|
+
const selectedOption = activeOptions.find(opt => opt.optionId === availabilityProductOptionId);
|
|
1889
|
+
if (!selectedOption) return null;
|
|
1890
|
+
const tourStartTime = parseISO(selectedAvailability.dateTime);
|
|
1891
|
+
const itinerary = getEffectiveItinerary(selectedOption, tourStartTime);
|
|
1892
|
+
const hasItinerary = itinerary && itinerary.length > 0 && product.destinations && product.destinations.length > 0;
|
|
1893
|
+
if (!hasItinerary || !product.destinations || !itinerary) return null;
|
|
1894
|
+
|
|
1895
|
+
const itineraryItems: ItineraryDisplayStep[] = [];
|
|
1896
|
+
const destinationMap = new Map(product.destinations.map(d => [d.name, d]));
|
|
1897
|
+
const pickupOffsetMinutes = pickupLocationSkipped ? 0 : (selectedPickupLocation?.pickupTimeOffsetMinutes ?? 0);
|
|
1898
|
+
const actualPickupTime = pickupOffsetMinutes > 0
|
|
1899
|
+
? new Date(tourStartTime.getTime() + pickupOffsetMinutes * 60 * 1000)
|
|
1900
|
+
: tourStartTime;
|
|
1901
|
+
let pickupTimeDisplay: string;
|
|
1902
|
+
if (pickupLocationSkipped && maxTimeOffsetMinutes > 0) {
|
|
1903
|
+
const latestPickupTime = new Date(tourStartTime.getTime() + maxTimeOffsetMinutes * 60 * 1000);
|
|
1904
|
+
pickupTimeDisplay = `${formatInTimeZone(tourStartTime, companyTimezone, 'h:mm a')} - ${formatInTimeZone(latestPickupTime, companyTimezone, 'h:mm a')}`;
|
|
1905
|
+
} else {
|
|
1906
|
+
pickupTimeDisplay = formatInTimeZone(actualPickupTime, companyTimezone, 'h:mm a');
|
|
1907
|
+
}
|
|
1908
|
+
const pickupPlace = pickupLocationSkipped || !selectedPickupLocation ? 'your_pickup_location' : selectedPickupLocation.name;
|
|
1909
|
+
itineraryItems.push({ stepType: StepType.pickup, time: pickupTimeDisplay, place: pickupPlace });
|
|
1910
|
+
let lastDepartureTime = tourStartTime;
|
|
1911
|
+
itinerary.forEach((itineraryItem, index) => {
|
|
1912
|
+
const destination = destinationMap.get(itineraryItem.destinationName);
|
|
1913
|
+
if (!destination) return;
|
|
1914
|
+
const arrivalTime = new Date(lastDepartureTime.getTime() + (itineraryItem.travelTimeFromPreviousHours * 60 * 60 * 1000));
|
|
1915
|
+
itineraryItems.push({
|
|
1916
|
+
stepType: StepType.arrive,
|
|
1917
|
+
time: formatInTimeZone(arrivalTime, companyTimezone, 'h:mm a'),
|
|
1918
|
+
place: destination.name
|
|
1919
|
+
});
|
|
1920
|
+
const departureTime = itineraryItem.durationHours
|
|
1921
|
+
? new Date(arrivalTime.getTime() + (itineraryItem.durationHours * 60 * 60 * 1000))
|
|
1922
|
+
: arrivalTime;
|
|
1923
|
+
const hasMoreDestinations = index < itinerary.length - 1;
|
|
1924
|
+
if (itineraryItem.durationHours && hasMoreDestinations) {
|
|
1925
|
+
itineraryItems.push({
|
|
1926
|
+
stepType: StepType.depart,
|
|
1927
|
+
time: formatInTimeZone(departureTime, companyTimezone, 'h:mm a'),
|
|
1928
|
+
place: destination.name
|
|
1929
|
+
});
|
|
1930
|
+
}
|
|
1931
|
+
lastDepartureTime = departureTime;
|
|
1932
|
+
});
|
|
1933
|
+
// Return time: from selected return option (products with return selection) OR from itinerary's last departure (e.g. Emerald Lake shuttle with fixed multi-stop itinerary)
|
|
1934
|
+
const returnDateTime = selectedReturnOption
|
|
1935
|
+
? parseISO(selectedReturnOption.dateTime)
|
|
1936
|
+
: lastDepartureTime;
|
|
1937
|
+
const lastDestination = itinerary.length > 0 ? destinationMap.get(itinerary[itinerary.length - 1].destinationName) : null;
|
|
1938
|
+
const lastDestName = itinerary.length > 0 && product.destinations
|
|
1939
|
+
? (destinationMap.get(itinerary[itinerary.length - 1].destinationName)?.name ?? null)
|
|
1940
|
+
: null;
|
|
1941
|
+
const getDropOffMinutes = (loc: { travelMinutesFromDestination?: Record<string, number> }) => {
|
|
1942
|
+
if (lastDestName && loc.travelMinutesFromDestination?.[lastDestName] != null) return loc.travelMinutesFromDestination[lastDestName];
|
|
1943
|
+
return 0;
|
|
1944
|
+
};
|
|
1945
|
+
const hasDropOffEstimate = (loc: { travelMinutesFromDestination?: Record<string, number> }) =>
|
|
1946
|
+
Boolean(lastDestName && loc.travelMinutesFromDestination?.[lastDestName] != null);
|
|
1947
|
+
const dropOffPlace = pickupLocationSkipped || !selectedPickupLocation ? 'your_pickup_location' : selectedPickupLocation!.name;
|
|
1948
|
+
|
|
1949
|
+
if (selectedReturnOption) {
|
|
1950
|
+
itineraryItems.push({
|
|
1951
|
+
stepType: StepType.depart,
|
|
1952
|
+
time: formatInTimeZone(returnDateTime, companyTimezone, 'h:mm a'),
|
|
1953
|
+
place: lastDestination?.name ?? 'the_destination'
|
|
1954
|
+
});
|
|
1955
|
+
} else if (lastDestination) {
|
|
1956
|
+
// No return options: show depart from last stop (e.g. Vermillion Lakes for Emerald Lake shuttle)
|
|
1957
|
+
itineraryItems.push({
|
|
1958
|
+
stepType: StepType.depart,
|
|
1959
|
+
time: formatInTimeZone(returnDateTime, companyTimezone, 'h:mm a'),
|
|
1960
|
+
place: lastDestination.name
|
|
1961
|
+
});
|
|
1962
|
+
}
|
|
1963
|
+
// Add drop-off step (works for both return-option products and itinerary-only products like Emerald Lake)
|
|
1964
|
+
if (selectedPickupLocation && hasDropOffEstimate(selectedPickupLocation)) {
|
|
1965
|
+
const dropOffOffsetMinutes = getDropOffMinutes(selectedPickupLocation);
|
|
1966
|
+
const dropOffTime = new Date(returnDateTime.getTime() + dropOffOffsetMinutes * 60 * 1000);
|
|
1967
|
+
itineraryItems.push({
|
|
1968
|
+
stepType: StepType.drop_off,
|
|
1969
|
+
time: formatInTimeZone(dropOffTime, companyTimezone, 'h:mm a'),
|
|
1970
|
+
place: dropOffPlace
|
|
1971
|
+
});
|
|
1972
|
+
} else if (pickupLocationSkipped || !selectedPickupLocation) {
|
|
1973
|
+
itineraryItems.push({ stepType: StepType.drop_off, time: 'TBD', place: dropOffPlace });
|
|
1974
|
+
} else if (product.pickupLocations?.length) {
|
|
1975
|
+
const dropOffOffsets = product.pickupLocations.map(getDropOffMinutes);
|
|
1976
|
+
const [minOffset, maxOffset] = [Math.min(...dropOffOffsets), Math.max(...dropOffOffsets)];
|
|
1977
|
+
const earliestDropOff = new Date(returnDateTime.getTime() + minOffset * 60 * 1000);
|
|
1978
|
+
const latestDropOff = new Date(returnDateTime.getTime() + maxOffset * 60 * 1000);
|
|
1979
|
+
itineraryItems.push({
|
|
1980
|
+
stepType: StepType.drop_off,
|
|
1981
|
+
time: minOffset === maxOffset
|
|
1982
|
+
? formatInTimeZone(earliestDropOff, companyTimezone, 'h:mm a')
|
|
1983
|
+
: `${formatInTimeZone(earliestDropOff, companyTimezone, 'h:mm a')} - ${formatInTimeZone(latestDropOff, companyTimezone, 'h:mm a')}`,
|
|
1984
|
+
place: dropOffPlace
|
|
1985
|
+
});
|
|
1986
|
+
} else {
|
|
1987
|
+
itineraryItems.push({ stepType: StepType.drop_off, time: 'TBD', place: dropOffPlace });
|
|
1988
|
+
}
|
|
1989
|
+
return itineraryItems;
|
|
1990
|
+
}, [selectedAvailability, selectedReturnOption, selectedPickupLocation, pickupLocationSkipped, activeOptions, product, getEffectiveItinerary, companyTimezone, maxTimeOffsetMinutes]);
|
|
1991
|
+
|
|
1992
|
+
/**
|
|
1993
|
+
* Itinerary for storage only (API/DB). When pickup is unknown, pickup step time is always a range
|
|
1994
|
+
* (e.g. "9 AM - 10:00 AM") so /manage and confirmation email show it; drop-off stays TBD.
|
|
1995
|
+
* UI during booking is unchanged (uses computeItineraryDisplay).
|
|
1996
|
+
*/
|
|
1997
|
+
const computeItineraryDisplayForStorage = useCallback((): ItineraryDisplayStep[] | null => {
|
|
1998
|
+
const base = computeItineraryDisplay();
|
|
1999
|
+
if (!base || base.length === 0) return base;
|
|
2000
|
+
const pickupUnknown = pickupLocationSkipped || (!selectedPickupLocation && product.pickupLocations && product.pickupLocations.length > 0);
|
|
2001
|
+
if (!pickupUnknown) return base;
|
|
2002
|
+
const tourStartTime = selectedAvailability ? parseISO(selectedAvailability.dateTime) : null;
|
|
2003
|
+
if (!tourStartTime) return base;
|
|
2004
|
+
const rangeMinutes = maxTimeOffsetMinutes > 0 ? maxTimeOffsetMinutes : 60;
|
|
2005
|
+
const latestPickupTime = new Date(tourStartTime.getTime() + rangeMinutes * 60 * 1000);
|
|
2006
|
+
const startStr = formatInTimeZone(tourStartTime, companyTimezone, 'h:mm a');
|
|
2007
|
+
const endStr = formatInTimeZone(latestPickupTime, companyTimezone, 'h:mm a');
|
|
2008
|
+
const pickupRangeTime = startStr === endStr ? startStr : `${startStr} - ${endStr}`;
|
|
2009
|
+
return base.map((step, i) =>
|
|
2010
|
+
i === 0 && step.stepType === StepType.pickup && step.place === 'your_pickup_location'
|
|
2011
|
+
? { ...step, time: pickupRangeTime }
|
|
2012
|
+
: step
|
|
2013
|
+
);
|
|
2014
|
+
}, [computeItineraryDisplay, pickupLocationSkipped, selectedPickupLocation, product.pickupLocations, selectedAvailability, companyTimezone, maxTimeOffsetMinutes]);
|
|
2015
|
+
|
|
2016
|
+
// Product has fees from config (e.g. product-fees.json); API sends these in pricingConfig.fees
|
|
2017
|
+
const hasFees = useMemo(() =>
|
|
2018
|
+
Boolean(pricingConfig?.fees && Object.keys(pricingConfig.fees).length > 0 && Object.values(pricingConfig.fees).some(v => (v?.feePerPerson ?? 0) > 0)),
|
|
2019
|
+
[pricingConfig?.fees]
|
|
2020
|
+
);
|
|
2021
|
+
|
|
2022
|
+
const changeFlowTicketPriceFloorByCategory = useMemo(() => {
|
|
2023
|
+
if (!isChangeFlow || !originalReceipt?.lineItems?.length) return new Map<string, number>();
|
|
2024
|
+
const amountByCategory = new Map<string, number>();
|
|
2025
|
+
const qtyByCategory = new Map<string, number>();
|
|
2026
|
+
for (const line of originalReceipt.lineItems) {
|
|
2027
|
+
const type = (line.type || '').trim().toUpperCase();
|
|
2028
|
+
if (type !== 'TICKET') continue;
|
|
2029
|
+
const category = normalizeTicketCategoryFromReceiptLabel(line.label || '');
|
|
2030
|
+
const amount = Number(line.amount ?? 0);
|
|
2031
|
+
const qty = Number(line.quantity ?? 0);
|
|
2032
|
+
if (!category || !Number.isFinite(amount) || !Number.isFinite(qty) || amount <= 0 || qty <= 0) continue;
|
|
2033
|
+
amountByCategory.set(category, (amountByCategory.get(category) ?? 0) + amount);
|
|
2034
|
+
qtyByCategory.set(category, (qtyByCategory.get(category) ?? 0) + qty);
|
|
2035
|
+
}
|
|
2036
|
+
const floors = new Map<string, number>();
|
|
2037
|
+
for (const [category, qty] of qtyByCategory.entries()) {
|
|
2038
|
+
const totalAmount = amountByCategory.get(category) ?? 0;
|
|
2039
|
+
if (totalAmount > 0 && qty > 0) floors.set(category, totalAmount / qty);
|
|
2040
|
+
}
|
|
2041
|
+
return floors;
|
|
2042
|
+
}, [isChangeFlow, originalReceipt?.lineItems]);
|
|
2043
|
+
|
|
2044
|
+
const changeFlowReturnUnitFloorPerPerson = useMemo(() => {
|
|
2045
|
+
if (!isChangeFlow || !originalReceipt?.lineItems?.length) return null;
|
|
2046
|
+
const fallbackBookedQty =
|
|
2047
|
+
(initialValues?.bookingItems ?? []).reduce((sum, item) => sum + Math.max(0, Number(item.count) || 0), 0);
|
|
2048
|
+
let totalAmount = 0;
|
|
2049
|
+
let totalQty = 0;
|
|
2050
|
+
for (const line of originalReceipt.lineItems) {
|
|
2051
|
+
const type = (line.type || '').trim().toUpperCase();
|
|
2052
|
+
if (type !== 'RETURN_OPTION') continue;
|
|
2053
|
+
const amount = Number(line.amount ?? 0);
|
|
2054
|
+
const qtyRaw = Number(line.quantity ?? 0);
|
|
2055
|
+
const qty = qtyRaw > 0 ? qtyRaw : fallbackBookedQty;
|
|
2056
|
+
if (!Number.isFinite(amount) || !Number.isFinite(qty) || amount <= 0 || qty <= 0) continue;
|
|
2057
|
+
totalAmount += amount;
|
|
2058
|
+
totalQty += qty;
|
|
2059
|
+
}
|
|
2060
|
+
if (totalAmount <= 0 || totalQty <= 0) return null;
|
|
2061
|
+
return totalAmount / totalQty;
|
|
2062
|
+
}, [isChangeFlow, originalReceipt?.lineItems, initialValues?.bookingItems]);
|
|
2063
|
+
|
|
2064
|
+
const returnOptionsWithFloor = useMemo(() => {
|
|
2065
|
+
const options = selectedAvailability?.returnOptions ?? [];
|
|
2066
|
+
if (!isChangeFlow || changeFlowReturnUnitFloorPerPerson == null) return options;
|
|
2067
|
+
return options.map((opt) => {
|
|
2068
|
+
const rawPerPerson = opt.priceAdjustmentByCurrency?.[currency] ?? 0;
|
|
2069
|
+
const flooredPerPerson = Math.max(rawPerPerson, changeFlowReturnUnitFloorPerPerson);
|
|
2070
|
+
if (flooredPerPerson === rawPerPerson) return opt;
|
|
2071
|
+
return {
|
|
2072
|
+
...opt,
|
|
2073
|
+
priceAdjustmentByCurrency: {
|
|
2074
|
+
...(opt.priceAdjustmentByCurrency ?? {}),
|
|
2075
|
+
[currency]: flooredPerPerson,
|
|
2076
|
+
},
|
|
2077
|
+
};
|
|
2078
|
+
});
|
|
2079
|
+
}, [selectedAvailability?.returnOptions, isChangeFlow, changeFlowReturnUnitFloorPerPerson, currency]);
|
|
2080
|
+
|
|
2081
|
+
const selectedReturnOptionWithFloor = useMemo(() => {
|
|
2082
|
+
if (!selectedReturnOption || !isChangeFlow || changeFlowReturnUnitFloorPerPerson == null) return selectedReturnOption;
|
|
2083
|
+
const rawPerPerson = selectedReturnOption.priceAdjustmentByCurrency?.[currency] ?? 0;
|
|
2084
|
+
const flooredPerPerson = Math.max(rawPerPerson, changeFlowReturnUnitFloorPerPerson);
|
|
2085
|
+
if (flooredPerPerson === rawPerPerson) return selectedReturnOption;
|
|
2086
|
+
return {
|
|
2087
|
+
...selectedReturnOption,
|
|
2088
|
+
priceAdjustmentByCurrency: {
|
|
2089
|
+
...(selectedReturnOption.priceAdjustmentByCurrency ?? {}),
|
|
2090
|
+
[currency]: flooredPerPerson,
|
|
2091
|
+
},
|
|
2092
|
+
};
|
|
2093
|
+
}, [selectedReturnOption, isChangeFlow, changeFlowReturnUnitFloorPerPerson, currency]);
|
|
2094
|
+
|
|
2095
|
+
// Ticket prices: use breakdown final price so booking flow total matches the price breakdown. All conversion in mid-layer.
|
|
2096
|
+
const pricing = useMemo(() => {
|
|
2097
|
+
if (!selectedAvailability || !pricingConfig) return [];
|
|
2098
|
+
const optionId = selectedAvailability.productOptionId;
|
|
2099
|
+
const selectedOption = activeOptions.find(opt => opt.optionId === optionId);
|
|
2100
|
+
const precomputed = optionId ? precomputedPricesByOption?.[optionId] : undefined;
|
|
2101
|
+
const rateToDisplayPrice = (backendInDisplayCurrency: number) =>
|
|
2102
|
+
getDisplayPriceFromBaseInDisplayCurrency(backendInDisplayCurrency, currency, pricingConfig, hasFees);
|
|
2103
|
+
const getBaseInDisplayCurrency = (category: string) => {
|
|
2104
|
+
const fromPrecomputed = precomputed?.[category]?.[currency];
|
|
2105
|
+
if (fromPrecomputed != null) return fromPrecomputed;
|
|
2106
|
+
return 0;
|
|
2107
|
+
};
|
|
2108
|
+
const buildRate = (
|
|
2109
|
+
category: string,
|
|
2110
|
+
backendPriceCAD: number,
|
|
2111
|
+
backendInDisplayCurrency: number,
|
|
2112
|
+
baseInDisplayCurrency: number,
|
|
2113
|
+
appliedAdjustments: Array<{ type: string; id: string; name: string; changeByCurrency?: Record<string, number> }>
|
|
2114
|
+
) => {
|
|
2115
|
+
const basePriceCAD = selectedOption?.pricing?.[category.toUpperCase()] ?? 0;
|
|
2116
|
+
const isPublicMode = isSimplifiedPricingView;
|
|
2117
|
+
const breakdown = computePriceBreakdown(
|
|
2118
|
+
pricingConfig,
|
|
2119
|
+
currency,
|
|
2120
|
+
backendPriceCAD,
|
|
2121
|
+
basePriceCAD,
|
|
2122
|
+
hasFees,
|
|
2123
|
+
appliedAdjustments,
|
|
2124
|
+
undefined,
|
|
2125
|
+
baseInDisplayCurrency,
|
|
2126
|
+
isPublicMode
|
|
2127
|
+
);
|
|
2128
|
+
const price = breakdown?.finalPrice ?? rateToDisplayPrice(backendInDisplayCurrency);
|
|
2129
|
+
return { category, baseInDisplayCurrency, appliedAdjustments, price, priceCAD: backendPriceCAD };
|
|
2130
|
+
};
|
|
2131
|
+
return selectedAvailability.rates?.map(rate => {
|
|
2132
|
+
const backendPriceCAD = rate.price ?? 0;
|
|
2133
|
+
const backendInDisplayCurrency = rate.priceByCurrency?.[currency] ?? (currency === 'CAD' ? backendPriceCAD : 0);
|
|
2134
|
+
const baseInDisplayCurrency = getBaseInDisplayCurrency(rate.category);
|
|
2135
|
+
const built = buildRate(rate.category, backendPriceCAD, backendInDisplayCurrency, baseInDisplayCurrency, rate.appliedAdjustments ?? rate.applied_adjustments ?? []);
|
|
2136
|
+
const floorUnitPrice = changeFlowTicketPriceFloorByCategory.get(rate.category.toUpperCase());
|
|
2137
|
+
const price = floorUnitPrice != null ? Math.max(built.price, floorUnitPrice) : built.price;
|
|
2138
|
+
return {
|
|
2139
|
+
category: rate.category,
|
|
2140
|
+
rateId: rate.rateId || rate.category,
|
|
2141
|
+
available: rate.available,
|
|
2142
|
+
price,
|
|
2143
|
+
priceCAD: built.priceCAD,
|
|
2144
|
+
baseInDisplayCurrency: built.baseInDisplayCurrency,
|
|
2145
|
+
appliedAdjustments: built.appliedAdjustments,
|
|
2146
|
+
};
|
|
2147
|
+
}) || selectedAvailability.pricesByCategory?.retailPrices?.map(p => {
|
|
2148
|
+
const priceCADFromApi = p.price / 100;
|
|
2149
|
+
const baseInDisplayCurrency = getBaseInDisplayCurrency(p.category);
|
|
2150
|
+
const backendInDisplayCurrency = currency === 'CAD' ? priceCADFromApi : 0;
|
|
2151
|
+
const built = buildRate(p.category, priceCADFromApi, backendInDisplayCurrency, baseInDisplayCurrency, []);
|
|
2152
|
+
const floorUnitPrice = changeFlowTicketPriceFloorByCategory.get(p.category.toUpperCase());
|
|
2153
|
+
const price = floorUnitPrice != null ? Math.max(built.price, floorUnitPrice) : built.price;
|
|
2154
|
+
return {
|
|
2155
|
+
category: p.category,
|
|
2156
|
+
rateId: p.category,
|
|
2157
|
+
available: selectedAvailability.vacancies,
|
|
2158
|
+
price,
|
|
2159
|
+
priceCAD: built.priceCAD,
|
|
2160
|
+
baseInDisplayCurrency: built.baseInDisplayCurrency,
|
|
2161
|
+
appliedAdjustments: built.appliedAdjustments,
|
|
2162
|
+
};
|
|
2163
|
+
}) || [];
|
|
2164
|
+
}, [selectedAvailability, currency, hasFees, pricingConfig, precomputedPricesByOption, activeOptions, isSimplifiedPricingView, changeFlowTicketPriceFloorByCategory]);
|
|
2165
|
+
|
|
2166
|
+
// Price breakdown: mid-layer returns line items (base + one per rule/deal). UI renders each line; rate in brackets when used.
|
|
2167
|
+
const getPriceBreakdown = useCallback((category: string, priceCAD: number, baseInDisplayCurrency: number | undefined, appliedAdjustments: Array<{ type: string; id: string; name: string; changeByCurrency?: Record<string, number> }> = []): PriceBreakdownData | null => {
|
|
2168
|
+
if (!pricingConfig) return null;
|
|
2169
|
+
const selectedOption = activeOptions.find(opt => opt.optionId === selectedAvailability?.productOptionId);
|
|
2170
|
+
const basePriceCAD = selectedOption?.pricing?.[category.toUpperCase()] ?? 0;
|
|
2171
|
+
const isPublicMode = isSimplifiedPricingView;
|
|
2172
|
+
return computePriceBreakdown(
|
|
2173
|
+
pricingConfig,
|
|
2174
|
+
currency,
|
|
2175
|
+
priceCAD,
|
|
2176
|
+
basePriceCAD,
|
|
2177
|
+
hasFees,
|
|
2178
|
+
appliedAdjustments,
|
|
2179
|
+
undefined,
|
|
2180
|
+
baseInDisplayCurrency,
|
|
2181
|
+
isPublicMode
|
|
2182
|
+
);
|
|
2183
|
+
}, [pricingConfig, currency, hasFees, activeOptions, selectedAvailability, isSimplifiedPricingView]);
|
|
2184
|
+
|
|
2185
|
+
// Order summary from mid-layer; UI only displays these values (no calculations).
|
|
2186
|
+
const orderSummary: OrderSummary = useMemo(
|
|
2187
|
+
() =>
|
|
2188
|
+
computeOrderSummary(
|
|
2189
|
+
quantities,
|
|
2190
|
+
pricing,
|
|
2191
|
+
selectedReturnOptionWithFloor,
|
|
2192
|
+
pricingConfig ?? null,
|
|
2193
|
+
currency,
|
|
2194
|
+
hasFees,
|
|
2195
|
+
cancellationPolicyId
|
|
2196
|
+
),
|
|
2197
|
+
[quantities, pricing, selectedReturnOptionWithFloor, pricingConfig, currency, hasFees, cancellationPolicyId]
|
|
2198
|
+
);
|
|
2199
|
+
const { totalQuantity, subtotal, tax, total: totalFromSummary, feeLineItems, returnPriceAdjustment, cancellationPolicyFee, isTaxIncludedInPrice, ticketLineItems } = orderSummary;
|
|
2200
|
+
/** Round-trip party limit: both legs must fit — use the tighter of outbound vs return vacancies. */
|
|
2201
|
+
const effectivePartySizeCap = useMemo(() => {
|
|
2202
|
+
if (!selectedAvailability) return 0;
|
|
2203
|
+
const outbound = selectedAvailability.vacancies ?? 0;
|
|
2204
|
+
if (selectedReturnOption == null) return outbound;
|
|
2205
|
+
return Math.min(outbound, selectedReturnOption.vacancies ?? 0);
|
|
2206
|
+
}, [selectedAvailability, selectedReturnOption]);
|
|
2207
|
+
|
|
2208
|
+
const selectedCancellationPolicy = pricingConfig?.cancellationPolicies?.find((p) => p.id === cancellationPolicyId);
|
|
2209
|
+
/** Label for display when policy may be forced by promo (not in pricingConfig list). */
|
|
2210
|
+
const effectiveCancellationPolicyLabel = selectedCancellationPolicy?.label ?? forcedCancellationPolicy?.label ?? (t('booking.flexibleCancellation') || 'Flexible cancellation');
|
|
2211
|
+
|
|
2212
|
+
// When return selection (or refreshed availabilities) caps the party below current ticket counts, trim tickets (non-admin).
|
|
2213
|
+
useEffect(() => {
|
|
2214
|
+
if (isAdmin || !selectedAvailability) return;
|
|
2215
|
+
const cap = effectivePartySizeCap;
|
|
2216
|
+
if (totalQuantity <= cap) return;
|
|
2217
|
+
const over = totalQuantity - cap;
|
|
2218
|
+
setQuantities((prev) => {
|
|
2219
|
+
const next = { ...prev };
|
|
2220
|
+
let remaining = over;
|
|
2221
|
+
const cats = Object.keys(next)
|
|
2222
|
+
.filter((c) => (next[c] ?? 0) > 0)
|
|
2223
|
+
.sort((a, b) => (next[b] ?? 0) - (next[a] ?? 0));
|
|
2224
|
+
for (const cat of cats) {
|
|
2225
|
+
if (remaining <= 0) break;
|
|
2226
|
+
const minQ =
|
|
2227
|
+
changeBookingMinimumQuantities != null
|
|
2228
|
+
? Math.max(0, changeBookingMinimumQuantities[cat] ?? 0)
|
|
2229
|
+
: 0;
|
|
2230
|
+
const q = next[cat] ?? 0;
|
|
2231
|
+
const reducible = Math.max(0, q - minQ);
|
|
2232
|
+
const dec = Math.min(reducible, remaining);
|
|
2233
|
+
next[cat] = q - dec;
|
|
2234
|
+
remaining -= dec;
|
|
2235
|
+
}
|
|
2236
|
+
return next;
|
|
2237
|
+
});
|
|
2238
|
+
}, [
|
|
2239
|
+
effectivePartySizeCap,
|
|
2240
|
+
totalQuantity,
|
|
2241
|
+
selectedAvailability,
|
|
2242
|
+
isAdmin,
|
|
2243
|
+
changeBookingMinimumQuantities,
|
|
2244
|
+
]);
|
|
2245
|
+
|
|
2246
|
+
// Add-on totals (lunch, animals, etc.)
|
|
2247
|
+
const addOnTotal = useMemo(() => {
|
|
2248
|
+
let sum = 0;
|
|
2249
|
+
for (const sel of addOnSelections) {
|
|
2250
|
+
const addOn = addOns.find((a) => a.addOnId === sel.addOnId);
|
|
2251
|
+
if (!addOn) continue;
|
|
2252
|
+
const basePrice = addOn.price ?? 0;
|
|
2253
|
+
const hasVariant = (addOn.variantType === 'single_choice' || addOn.variantType === 'multi_quantity') && sel.variantId;
|
|
2254
|
+
const variantAdjustment = hasVariant
|
|
2255
|
+
? (addOn.variants?.find((v) => v.id === sel.variantId)?.priceAdjustment ?? 0)
|
|
2256
|
+
: 0;
|
|
2257
|
+
sum += (basePrice + variantAdjustment) * (sel.quantity ?? 1);
|
|
2258
|
+
}
|
|
2259
|
+
return sum;
|
|
2260
|
+
}, [addOnSelections, addOns]);
|
|
2261
|
+
|
|
2262
|
+
// Effective subtotal includes add-ons (for promo discount and total)
|
|
2263
|
+
const effectiveSubtotal = subtotal + addOnTotal;
|
|
2264
|
+
|
|
2265
|
+
/** Stable signature for promo discount API (avoid effect re-fire on object identity churn). */
|
|
2266
|
+
const quantitiesSignature = useMemo(
|
|
2267
|
+
() =>
|
|
2268
|
+
Object.entries(quantities)
|
|
2269
|
+
.filter(([, n]) => (n ?? 0) > 0)
|
|
2270
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
2271
|
+
.map(([c, n]) => `${c}:${n}`)
|
|
2272
|
+
.join('|'),
|
|
2273
|
+
[quantities]
|
|
2274
|
+
);
|
|
2275
|
+
|
|
2276
|
+
// Fee line items including add-ons (for PriceSummary and CheckoutModal)
|
|
2277
|
+
const feeLineItemsWithAddOns = useMemo(() => {
|
|
2278
|
+
const addOnLines = addOnSelections
|
|
2279
|
+
.map((sel) => {
|
|
2280
|
+
const addOn = addOns.find((a) => a.addOnId === sel.addOnId);
|
|
2281
|
+
if (!addOn) return null;
|
|
2282
|
+
const base = addOn.price ?? 0;
|
|
2283
|
+
const hasVariant = (addOn.variantType === 'single_choice' || addOn.variantType === 'multi_quantity') && sel.variantId;
|
|
2284
|
+
const adj = hasVariant ? (addOn.variants?.find((v) => v.id === sel.variantId)?.priceAdjustment ?? 0) : 0;
|
|
2285
|
+
const qty = sel.quantity ?? 1;
|
|
2286
|
+
const amt = (base + adj) * qty;
|
|
2287
|
+
const variantLabel = hasVariant ? addOn.variants?.find((v) => v.id === sel.variantId)?.label : null;
|
|
2288
|
+
const name = variantLabel ? `${addOn.name} (${variantLabel})${qty > 1 ? ` × ${qty}` : ''}` : addOn.name;
|
|
2289
|
+
return { name, totalAmount: amt, description: addOn.description ?? undefined };
|
|
2290
|
+
})
|
|
2291
|
+
.filter((x): x is NonNullable<typeof x> => x != null);
|
|
2292
|
+
return [...feeLineItems, ...addOnLines];
|
|
2293
|
+
}, [feeLineItems, addOnSelections, addOns]);
|
|
2294
|
+
|
|
2295
|
+
const checkoutPriceSummaryLines = useMemo((): PriceSummaryLine[] => {
|
|
2296
|
+
if (!selectedAvailability) return [];
|
|
2297
|
+
return [
|
|
2298
|
+
...ticketLineItems.map((line): PriceSummaryLine => {
|
|
2299
|
+
const rate = pricing.find((r) => r.category === line.category);
|
|
2300
|
+
const breakdown = getPriceBreakdown(
|
|
2301
|
+
line.category,
|
|
2302
|
+
rate?.priceCAD ?? 0,
|
|
2303
|
+
rate?.baseInDisplayCurrency,
|
|
2304
|
+
rate?.appliedAdjustments ?? [],
|
|
2305
|
+
);
|
|
2306
|
+
return {
|
|
2307
|
+
kind: 'ticket',
|
|
2308
|
+
category: line.category,
|
|
2309
|
+
qty: line.qty,
|
|
2310
|
+
itemTotal: line.itemTotal,
|
|
2311
|
+
breakdown,
|
|
2312
|
+
};
|
|
2313
|
+
}),
|
|
2314
|
+
...(selectedReturnOption && returnPriceAdjustment !== 0
|
|
2315
|
+
? [
|
|
2316
|
+
{
|
|
2317
|
+
kind: 'line' as const,
|
|
2318
|
+
label: `${t('booking.returnOption')} (${totalQuantity} ${totalQuantity === 1 ? 'person' : 'people'})`,
|
|
2319
|
+
amount: returnPriceAdjustment,
|
|
2320
|
+
type: 'return',
|
|
2321
|
+
},
|
|
2322
|
+
]
|
|
2323
|
+
: []),
|
|
2324
|
+
...(cancellationPolicyFee > 0 && (selectedCancellationPolicy || forcedCancellationPolicy)
|
|
2325
|
+
? [
|
|
2326
|
+
{
|
|
2327
|
+
kind: 'line' as const,
|
|
2328
|
+
label: effectiveCancellationPolicyLabel,
|
|
2329
|
+
amount: cancellationPolicyFee,
|
|
2330
|
+
type: 'cancellation',
|
|
2331
|
+
},
|
|
2332
|
+
]
|
|
2333
|
+
: []),
|
|
2334
|
+
...feeLineItemsWithAddOns.map((fee) => {
|
|
2335
|
+
const isMoraineLakeRoadAccessFee =
|
|
2336
|
+
fee.name.toLowerCase().includes('moraine') &&
|
|
2337
|
+
(fee.name.toLowerCase().includes('access') ||
|
|
2338
|
+
fee.name.toLowerCase().includes('road') ||
|
|
2339
|
+
fee.name.toLowerCase().includes('license'));
|
|
2340
|
+
return {
|
|
2341
|
+
kind: 'line' as const,
|
|
2342
|
+
label: feeLineItems.some((f) => f.name === fee.name)
|
|
2343
|
+
? `${fee.name} (${totalQuantity} ${totalQuantity === 1 ? 'person' : 'people'})`
|
|
2344
|
+
: fee.name,
|
|
2345
|
+
amount: fee.totalAmount,
|
|
2346
|
+
type: 'fee',
|
|
2347
|
+
tooltip: isMoraineLakeRoadAccessFee
|
|
2348
|
+
? "Since 2025, Parks Canada charges a per-trip fee for License of Occupation. Based on our capacity, this per-person fee contributes towards Parks Canada's Moraine Lake Road operations."
|
|
2349
|
+
: undefined,
|
|
2350
|
+
};
|
|
2351
|
+
}),
|
|
2352
|
+
];
|
|
2353
|
+
}, [
|
|
2354
|
+
selectedAvailability,
|
|
2355
|
+
ticketLineItems,
|
|
2356
|
+
pricing,
|
|
2357
|
+
getPriceBreakdown,
|
|
2358
|
+
selectedReturnOption,
|
|
2359
|
+
returnPriceAdjustment,
|
|
2360
|
+
totalQuantity,
|
|
2361
|
+
t,
|
|
2362
|
+
cancellationPolicyFee,
|
|
2363
|
+
selectedCancellationPolicy,
|
|
2364
|
+
forcedCancellationPolicy,
|
|
2365
|
+
effectiveCancellationPolicyLabel,
|
|
2366
|
+
feeLineItemsWithAddOns,
|
|
2367
|
+
feeLineItems,
|
|
2368
|
+
]);
|
|
2369
|
+
|
|
2370
|
+
// Promo discount from backend (order-level only; rates are pre-promo)
|
|
2371
|
+
const [promoDiscountAmount, setPromoDiscountAmount] = useState(0);
|
|
2372
|
+
const [isGiftCard, setIsGiftCard] = useState(false);
|
|
2373
|
+
const [isVoucher, setIsVoucher] = useState(false);
|
|
2374
|
+
/** Monotonic id per discount fetch; stale responses are ignored. */
|
|
2375
|
+
const promoDiscountFetchGenerationRef = useRef(0);
|
|
2376
|
+
/** Latest cart context for get-promo-discount; effect only keys off promoDiscountFetchKey. */
|
|
2377
|
+
const promoDiscountParamsRef = useRef({
|
|
2378
|
+
selectedAvailability: null as Availability | null,
|
|
2379
|
+
ticketLineItems: [] as Array<{ category: string; qty: number }>,
|
|
2380
|
+
effectiveSubtotal: 0,
|
|
2381
|
+
appliedPromoCode: null as string | null,
|
|
2382
|
+
});
|
|
2383
|
+
|
|
2384
|
+
const promoDiscountFetchKey = useMemo(() => {
|
|
2385
|
+
if (!appliedPromoCode || !selectedAvailability || totalQuantity === 0) return '';
|
|
2386
|
+
const companyId = product.companyId ?? ENV.COMPANY_ID;
|
|
2387
|
+
if (!companyId) return '';
|
|
2388
|
+
const optionId = selectedAvailability.productOptionId;
|
|
2389
|
+
if (!optionId || !quantitiesSignature) return '';
|
|
2390
|
+
return [
|
|
2391
|
+
appliedPromoCode,
|
|
2392
|
+
companyId,
|
|
2393
|
+
product.productId,
|
|
2394
|
+
optionId,
|
|
2395
|
+
selectedAvailability.dateTime,
|
|
2396
|
+
selectedAvailability.availabilityId ?? '',
|
|
2397
|
+
currency,
|
|
2398
|
+
quantitiesSignature,
|
|
2399
|
+
String(Math.round(effectiveSubtotal * 100)),
|
|
2400
|
+
].join('::');
|
|
2401
|
+
}, [
|
|
2402
|
+
appliedPromoCode,
|
|
2403
|
+
selectedAvailability?.dateTime,
|
|
2404
|
+
selectedAvailability?.productOptionId,
|
|
2405
|
+
selectedAvailability?.availabilityId,
|
|
2406
|
+
totalQuantity,
|
|
2407
|
+
product.companyId,
|
|
2408
|
+
product.productId,
|
|
2409
|
+
currency,
|
|
2410
|
+
quantitiesSignature,
|
|
2411
|
+
effectiveSubtotal,
|
|
2412
|
+
]);
|
|
2413
|
+
|
|
2414
|
+
promoDiscountParamsRef.current = {
|
|
2415
|
+
selectedAvailability,
|
|
2416
|
+
ticketLineItems: ticketLineItems.map((l) => ({ category: l.category, qty: l.qty })),
|
|
2417
|
+
effectiveSubtotal,
|
|
2418
|
+
appliedPromoCode,
|
|
2419
|
+
};
|
|
2420
|
+
|
|
2421
|
+
useEffect(() => {
|
|
2422
|
+
if (!promoDiscountFetchKey) {
|
|
2423
|
+
setPromoDiscountAmount(0);
|
|
2424
|
+
setIsGiftCard(false);
|
|
2425
|
+
setIsVoucher(false);
|
|
2426
|
+
return;
|
|
2427
|
+
}
|
|
2428
|
+
|
|
2429
|
+
let cancelled = false;
|
|
2430
|
+
const debounceMs = 120;
|
|
2431
|
+
const timer = window.setTimeout(() => {
|
|
2432
|
+
if (cancelled) return;
|
|
2433
|
+
const {
|
|
2434
|
+
selectedAvailability: sel,
|
|
2435
|
+
ticketLineItems: lines,
|
|
2436
|
+
effectiveSubtotal: sub,
|
|
2437
|
+
appliedPromoCode: code,
|
|
2438
|
+
} = promoDiscountParamsRef.current;
|
|
2439
|
+
if (!code || !sel) return;
|
|
2440
|
+
const companyId = product.companyId ?? ENV.COMPANY_ID;
|
|
2441
|
+
const optionId = sel.productOptionId;
|
|
2442
|
+
if (!companyId || !optionId) return;
|
|
2443
|
+
const items = lines.map((l) => ({ category: l.category, qty: l.qty }));
|
|
2444
|
+
if (items.length === 0) return;
|
|
2445
|
+
|
|
2446
|
+
const generation = ++promoDiscountFetchGenerationRef.current;
|
|
2447
|
+
getPromoDiscount(
|
|
2448
|
+
code,
|
|
2449
|
+
companyId,
|
|
2450
|
+
product.productId,
|
|
2451
|
+
optionId,
|
|
2452
|
+
currency,
|
|
2453
|
+
items,
|
|
2454
|
+
sel.dateTime,
|
|
2455
|
+
sub
|
|
2456
|
+
)
|
|
2457
|
+
.then((res) => {
|
|
2458
|
+
if (cancelled) return;
|
|
2459
|
+
if (generation !== promoDiscountFetchGenerationRef.current) return;
|
|
2460
|
+
setPromoDiscountAmount(res.discount ?? 0);
|
|
2461
|
+
setIsGiftCard(res.isGiftCard ?? false);
|
|
2462
|
+
setIsVoucher(res.isVoucher ?? false);
|
|
2463
|
+
})
|
|
2464
|
+
.catch(() => {
|
|
2465
|
+
if (cancelled) return;
|
|
2466
|
+
if (generation !== promoDiscountFetchGenerationRef.current) return;
|
|
2467
|
+
setPromoDiscountAmount(0);
|
|
2468
|
+
setIsGiftCard(false);
|
|
2469
|
+
setIsVoucher(false);
|
|
2470
|
+
});
|
|
2471
|
+
}, debounceMs);
|
|
2472
|
+
|
|
2473
|
+
return () => {
|
|
2474
|
+
cancelled = true;
|
|
2475
|
+
window.clearTimeout(timer);
|
|
2476
|
+
};
|
|
2477
|
+
}, [promoDiscountFetchKey, product.companyId, product.productId, currency]);
|
|
2478
|
+
|
|
2479
|
+
// Percentage/fixed promos: tax on discounted amount (promo before GST per CRA guidance).
|
|
2480
|
+
// Vouchers and gift cards: tax on full subtotal (voucher discount includes tax on free portion; gift card is payment).
|
|
2481
|
+
// Change booking: same as normal — discount from get-promo-discount on the new selection (promo code from booking).
|
|
2482
|
+
const lockedPromoFallbackAmount =
|
|
2483
|
+
isChangeFlow && lockedPromoCode
|
|
2484
|
+
? Math.max(0, originalReceipt?.promoAmount ?? 0)
|
|
2485
|
+
: 0;
|
|
2486
|
+
const effectivePromoDiscountAmount =
|
|
2487
|
+
promoDiscountAmount > 0 ? promoDiscountAmount : lockedPromoFallbackAmount;
|
|
2488
|
+
const taxOnSubtotal = isTaxIncludedInPrice ? 0 : effectiveSubtotal * (pricingConfig?.taxRate ?? 0);
|
|
2489
|
+
const effectiveTax =
|
|
2490
|
+
effectivePromoDiscountAmount > 0 && !isGiftCard && !isVoucher
|
|
2491
|
+
? (effectiveSubtotal - effectivePromoDiscountAmount) * (pricingConfig?.taxRate ?? 0)
|
|
2492
|
+
: taxOnSubtotal;
|
|
2493
|
+
const totalPrice = effectiveSubtotal + effectiveTax - effectivePromoDiscountAmount;
|
|
2494
|
+
const changeFlowProposedTotal = isChangeFlow && originalReceipt
|
|
2495
|
+
? reconcileChangeBookingProposedTotal(totalPrice, originalReceipt.total)
|
|
2496
|
+
: totalPrice;
|
|
2497
|
+
const changeSelectionDetails = useMemo(() => {
|
|
2498
|
+
if (!isChangeFlow || !initialValues) {
|
|
2499
|
+
return { hasChangesFromInitial: true, dateChanged: false, ticketsChanged: false };
|
|
2500
|
+
}
|
|
2501
|
+
if (!selectedAvailability) {
|
|
2502
|
+
return { hasChangesFromInitial: false, dateChanged: false, ticketsChanged: false };
|
|
2503
|
+
}
|
|
2504
|
+
const initialMs = initialValues.dateTime ? parseAvailabilityDateTime(initialValues.dateTime).getTime() : null;
|
|
2505
|
+
const selectedMs = parseAvailabilityDateTime(selectedAvailability.dateTime).getTime();
|
|
2506
|
+
// Only treat as date change when we have an original datetime to compare (otherwise we’d always flag “changed”).
|
|
2507
|
+
const dateChanged = initialMs != null && initialMs !== selectedMs;
|
|
2508
|
+
// productOptionId on the booking is the option id, not productId — compare only when both are known.
|
|
2509
|
+
const initialOpt = initialValues.productOptionId?.trim() || null;
|
|
2510
|
+
const selectedOpt = selectedAvailability.productOptionId?.trim() || null;
|
|
2511
|
+
const optionChanged = Boolean(
|
|
2512
|
+
initialOpt && selectedOpt && initialOpt !== selectedOpt
|
|
2513
|
+
);
|
|
2514
|
+
const pickupChanged = (initialValues.pickupLocationId ?? null) !== (pickupLocationId ?? null);
|
|
2515
|
+
const normalizeCounts = (items: Array<{ category: string; count: number }> | null | undefined) => {
|
|
2516
|
+
const map = new Map<string, number>();
|
|
2517
|
+
for (const item of items ?? []) {
|
|
2518
|
+
const key = item.category?.trim();
|
|
2519
|
+
if (!key) continue;
|
|
2520
|
+
map.set(key, Math.max(0, Number(item.count) || 0));
|
|
2521
|
+
}
|
|
2522
|
+
return map;
|
|
2523
|
+
};
|
|
2524
|
+
const initialCounts = normalizeCounts(initialValues.bookingItems ?? null);
|
|
2525
|
+
const currentCounts = new Map<string, number>();
|
|
2526
|
+
for (const [category, count] of Object.entries(quantities)) {
|
|
2527
|
+
const key = category?.trim();
|
|
2528
|
+
if (!key) continue;
|
|
2529
|
+
currentCounts.set(key, Math.max(0, Number(count) || 0));
|
|
2530
|
+
}
|
|
2531
|
+
const allKeys = new Set([...initialCounts.keys(), ...currentCounts.keys()]);
|
|
2532
|
+
let countsChanged = false;
|
|
2533
|
+
for (const key of allKeys) {
|
|
2534
|
+
if ((initialCounts.get(key) ?? 0) !== (currentCounts.get(key) ?? 0)) {
|
|
2535
|
+
countsChanged = true;
|
|
2536
|
+
break;
|
|
2537
|
+
}
|
|
2538
|
+
}
|
|
2539
|
+
const currentAddOnQtyByKey = new Map<string, number>();
|
|
2540
|
+
for (const sel of addOnSelections) {
|
|
2541
|
+
const key = `${sel.addOnId.trim()}::${sel.variantId?.trim() || ''}`;
|
|
2542
|
+
currentAddOnQtyByKey.set(key, (currentAddOnQtyByKey.get(key) ?? 0) + Math.max(1, Number(sel.quantity) || 1));
|
|
2543
|
+
}
|
|
2544
|
+
const allAddOnKeys = new Set([...initialAddOnMinQtyByKey.keys(), ...currentAddOnQtyByKey.keys()]);
|
|
2545
|
+
let addOnsChanged = false;
|
|
2546
|
+
for (const key of allAddOnKeys) {
|
|
2547
|
+
if ((initialAddOnMinQtyByKey.get(key) ?? 0) !== (currentAddOnQtyByKey.get(key) ?? 0)) {
|
|
2548
|
+
addOnsChanged = true;
|
|
2549
|
+
break;
|
|
2550
|
+
}
|
|
2551
|
+
}
|
|
2552
|
+
const hasReturnOptions = (selectedAvailability?.returnOptions?.length ?? 0) > 0;
|
|
2553
|
+
const initialReturnId = initialValues.returnAvailabilityId?.trim() || null;
|
|
2554
|
+
const initialReturnDt = initialValues.returnDateTime?.trim() || null;
|
|
2555
|
+
const selectedReturnId = selectedReturnOption?.returnAvailabilityId?.trim() || null;
|
|
2556
|
+
const selectedReturnDt = selectedReturnOption?.dateTime?.trim() || null;
|
|
2557
|
+
let returnChanged = false;
|
|
2558
|
+
if (hasReturnOptions && selectedReturnOption) {
|
|
2559
|
+
if (initialReturnId && selectedReturnId) {
|
|
2560
|
+
returnChanged = initialReturnId !== selectedReturnId;
|
|
2561
|
+
} else if (initialReturnDt && selectedReturnDt) {
|
|
2562
|
+
returnChanged =
|
|
2563
|
+
parseAvailabilityDateTime(initialReturnDt).getTime() !==
|
|
2564
|
+
parseAvailabilityDateTime(selectedReturnDt).getTime();
|
|
2565
|
+
} else if (implicitReturnBaselineId != null && selectedReturnId != null) {
|
|
2566
|
+
returnChanged = implicitReturnBaselineId !== selectedReturnId;
|
|
2567
|
+
}
|
|
2568
|
+
}
|
|
2569
|
+
return {
|
|
2570
|
+
hasChangesFromInitial:
|
|
2571
|
+
dateChanged ||
|
|
2572
|
+
optionChanged ||
|
|
2573
|
+
pickupChanged ||
|
|
2574
|
+
countsChanged ||
|
|
2575
|
+
addOnsChanged ||
|
|
2576
|
+
returnChanged,
|
|
2577
|
+
dateChanged,
|
|
2578
|
+
// Tickets line corresponds to "option + ticket counts"; add-ons and pickup changes affect itinerary but not the ticket label.
|
|
2579
|
+
ticketsChanged: Boolean(optionChanged || countsChanged),
|
|
2580
|
+
};
|
|
2581
|
+
}, [
|
|
2582
|
+
isChangeFlow,
|
|
2583
|
+
initialValues,
|
|
2584
|
+
selectedAvailability,
|
|
2585
|
+
selectedReturnOption,
|
|
2586
|
+
implicitReturnBaselineId,
|
|
2587
|
+
pickupLocationId,
|
|
2588
|
+
quantities,
|
|
2589
|
+
addOnSelections,
|
|
2590
|
+
initialAddOnMinQtyByKey,
|
|
2591
|
+
]);
|
|
2592
|
+
const hasChangeSelection = changeSelectionDetails.hasChangesFromInitial;
|
|
2593
|
+
|
|
2594
|
+
const changeFlowNeedsServerPrice =
|
|
2595
|
+
isChangeFlow &&
|
|
2596
|
+
hasChangeSelection &&
|
|
2597
|
+
!!initialValues?.bookingReference?.trim() &&
|
|
2598
|
+
!!lastName.trim();
|
|
2599
|
+
|
|
2600
|
+
const isChangeQuoteBlocked = isChangeFlow && latestChangeQuote?.canProceed === false;
|
|
2601
|
+
const requiresReturnInChangeFlow = isChangeFlow && !!initialValues?.returnAvailabilityId?.trim();
|
|
2602
|
+
const missingRequiredReturnSelection = requiresReturnInChangeFlow && !selectedReturnOption;
|
|
2603
|
+
|
|
2604
|
+
const changeFlowSubmitDisabled =
|
|
2605
|
+
isChangeFlow &&
|
|
2606
|
+
(missingRequiredReturnSelection ||
|
|
2607
|
+
(changeFlowNeedsServerPrice && (changeQuoteLoading || (!latestChangeQuote && !changeQuoteFetchError))));
|
|
2608
|
+
|
|
2609
|
+
const changeFlowClientEstimateDue = originalReceipt
|
|
2610
|
+
? Math.max(changeFlowProposedTotal - originalReceipt.total, 0)
|
|
2611
|
+
: totalPrice;
|
|
2612
|
+
|
|
2613
|
+
/**
|
|
2614
|
+
* Amount owed for change flow: same recipe as normal booking — FE `totalPrice` vs original receipt.
|
|
2615
|
+
* Quote is still required before submit (session + canProceed); `clientProposedTotal` on quote keeps BE in sync.
|
|
2616
|
+
*/
|
|
2617
|
+
const changeFlowAmountDueRaw = isChangeFlow ? changeFlowClientEstimateDue : totalPrice;
|
|
2618
|
+
const changeFlowAmountDue =
|
|
2619
|
+
isChangeFlow ? Math.round(changeFlowAmountDueRaw * 100) / 100 : changeFlowAmountDueRaw;
|
|
2620
|
+
|
|
2621
|
+
const changeCheckoutButtonLabel = (() => {
|
|
2622
|
+
if (!isChangeFlow) return undefined;
|
|
2623
|
+
if (!hasChangeSelection) return undefined;
|
|
2624
|
+
if (changeFlowNeedsServerPrice) {
|
|
2625
|
+
if (changeQuoteLoading) {
|
|
2626
|
+
const tr = t('booking.updatingPrice');
|
|
2627
|
+
return tr !== 'booking.updatingPrice' ? tr : 'Updating price…';
|
|
2628
|
+
}
|
|
2629
|
+
if (changeQuoteFetchError) {
|
|
2630
|
+
const tr = t('booking.changeBookingRetry');
|
|
2631
|
+
return tr !== 'booking.changeBookingRetry' ? tr : 'Change booking (retry)';
|
|
2632
|
+
}
|
|
2633
|
+
if (isChangeQuoteBlocked) {
|
|
2634
|
+
const tr = t('booking.changeBookingNotAvailable');
|
|
2635
|
+
return tr !== 'booking.changeBookingNotAvailable' ? tr : 'Change not available';
|
|
2636
|
+
}
|
|
2637
|
+
if (latestChangeQuote) {
|
|
2638
|
+
const d = Math.round(changeFlowClientEstimateDue * 100) / 100;
|
|
2639
|
+
return d > 0
|
|
2640
|
+
? `Change booking (${formatCurrencyAmount(d, currency, locale as 'en' | 'fr')})`
|
|
2641
|
+
: 'Change booking (no charge)';
|
|
2642
|
+
}
|
|
2643
|
+
const tr = t('booking.changeBooking');
|
|
2644
|
+
return tr !== 'booking.changeBooking' ? tr : 'Change booking';
|
|
2645
|
+
}
|
|
2646
|
+
const est = Math.round(changeFlowClientEstimateDue * 100) / 100;
|
|
2647
|
+
return est > 0
|
|
2648
|
+
? `Change booking (${formatCurrencyAmount(est, currency, locale as 'en' | 'fr')})`
|
|
2649
|
+
: 'Change booking (no charge)';
|
|
2650
|
+
})();
|
|
2651
|
+
const deferredInvoiceSubmitLabel =
|
|
2652
|
+
!isChangeFlow && flowUi?.partnerDeferredInvoice
|
|
2653
|
+
? flowUi.partnerDeferredInvoiceSubmitLabel || 'Continue to book'
|
|
2654
|
+
: undefined;
|
|
2655
|
+
|
|
2656
|
+
const checkoutFormError =
|
|
2657
|
+
(error || '') ||
|
|
2658
|
+
(missingRequiredReturnSelection ? 'Removing return option in self-serve is not available. Please contact support.' : '') ||
|
|
2659
|
+
(isChangeQuoteBlocked ? (latestChangeQuote?.reasonIfBlocked ?? '') : '') ||
|
|
2660
|
+
(changeQuoteFetchError ?? '');
|
|
2661
|
+
|
|
2662
|
+
const changeFlowSelectionPreview = useMemo((): ChangeFlowSelectionPreview | null => {
|
|
2663
|
+
if (!isChangeFlow) return null;
|
|
2664
|
+
if (!selectedAvailability || totalQuantity <= 0) return null;
|
|
2665
|
+
const ticketsLine = formatTicketLineItemsForSummary(
|
|
2666
|
+
ticketLineItems.map((l) => ({ category: l.category, qty: l.qty }))
|
|
2667
|
+
);
|
|
2668
|
+
const itinerary = computeItineraryDisplay();
|
|
2669
|
+
const itinerarySteps =
|
|
2670
|
+
itinerary?.map((s) => ({
|
|
2671
|
+
time: s.time?.trim() || null,
|
|
2672
|
+
label: getItineraryStepLabel(s),
|
|
2673
|
+
})) ?? [];
|
|
2674
|
+
return {
|
|
2675
|
+
tourName: product.name?.trim() || '',
|
|
2676
|
+
dateTime: selectedAvailability.dateTime,
|
|
2677
|
+
ticketsLine,
|
|
2678
|
+
itinerarySteps,
|
|
2679
|
+
dateChanged: changeSelectionDetails.dateChanged,
|
|
2680
|
+
ticketsChanged: changeSelectionDetails.ticketsChanged,
|
|
2681
|
+
hasChangesFromInitial: changeSelectionDetails.hasChangesFromInitial,
|
|
2682
|
+
selectionTotal: totalPrice,
|
|
2683
|
+
selectionCurrency: currency,
|
|
2684
|
+
};
|
|
2685
|
+
}, [
|
|
2686
|
+
isChangeFlow,
|
|
2687
|
+
selectedAvailability,
|
|
2688
|
+
totalQuantity,
|
|
2689
|
+
ticketLineItems,
|
|
2690
|
+
computeItineraryDisplay,
|
|
2691
|
+
product.name,
|
|
2692
|
+
changeSelectionDetails,
|
|
2693
|
+
totalPrice,
|
|
2694
|
+
currency,
|
|
2695
|
+
]);
|
|
2696
|
+
|
|
2697
|
+
useEffect(() => {
|
|
2698
|
+
if (!isChangeFlow || !onChangeFlowSelectionPreview) return;
|
|
2699
|
+
onChangeFlowSelectionPreview(changeFlowSelectionPreview);
|
|
2700
|
+
}, [isChangeFlow, changeFlowSelectionPreview, onChangeFlowSelectionPreview]);
|
|
2701
|
+
|
|
2702
|
+
useEffect(() => {
|
|
2703
|
+
if (!onPricePreviewChange) return;
|
|
2704
|
+
if (!selectedAvailability || totalQuantity <= 0) {
|
|
2705
|
+
onPricePreviewChange(null);
|
|
2706
|
+
return;
|
|
2707
|
+
}
|
|
2708
|
+
onPricePreviewChange({
|
|
2709
|
+
subtotal: effectiveSubtotal,
|
|
2710
|
+
tax: !isTaxIncludedInPrice ? effectiveTax : 0,
|
|
2711
|
+
total: totalPrice,
|
|
2712
|
+
currency,
|
|
2713
|
+
});
|
|
2714
|
+
}, [
|
|
2715
|
+
onPricePreviewChange,
|
|
2716
|
+
selectedAvailability,
|
|
2717
|
+
totalQuantity,
|
|
2718
|
+
effectiveSubtotal,
|
|
2719
|
+
effectiveTax,
|
|
2720
|
+
changeFlowProposedTotal,
|
|
2721
|
+
currency,
|
|
2722
|
+
isTaxIncludedInPrice,
|
|
2723
|
+
]);
|
|
2724
|
+
|
|
2725
|
+
/** Debounced server quote so CTA + “amount owed” match PaymentIntent; avoids free confirm when FE estimate ≠ BE. */
|
|
2726
|
+
useEffect(() => {
|
|
2727
|
+
if (!isChangeFlow) {
|
|
2728
|
+
setChangeQuoteLoading(false);
|
|
2729
|
+
setChangeQuoteFetchError(null);
|
|
2730
|
+
return;
|
|
2731
|
+
}
|
|
2732
|
+
|
|
2733
|
+
if (
|
|
2734
|
+
!hasChangeSelection ||
|
|
2735
|
+
!selectedAvailability ||
|
|
2736
|
+
!initialValues?.bookingReference?.trim() ||
|
|
2737
|
+
!lastName.trim() ||
|
|
2738
|
+
missingRequiredReturnSelection
|
|
2739
|
+
) {
|
|
2740
|
+
setLatestChangeQuote(null);
|
|
2741
|
+
setChangeQuoteLoading(false);
|
|
2742
|
+
setChangeQuoteFetchError(null);
|
|
2743
|
+
return;
|
|
2744
|
+
}
|
|
2745
|
+
|
|
2746
|
+
const optionId =
|
|
2747
|
+
selectedAvailability.productOptionId?.trim() || activeOptions[0]?.optionId;
|
|
2748
|
+
if (!optionId) {
|
|
2749
|
+
setLatestChangeQuote(null);
|
|
2750
|
+
setChangeQuoteLoading(false);
|
|
2751
|
+
setChangeQuoteFetchError(null);
|
|
2752
|
+
return;
|
|
2753
|
+
}
|
|
2754
|
+
|
|
2755
|
+
setChangeQuoteLoading(true);
|
|
2756
|
+
setChangeQuoteFetchError(null);
|
|
2757
|
+
const seq = ++changeQuoteRequestSeq.current;
|
|
2758
|
+
const bookingReferenceForQuote = initialValues.bookingReference.trim();
|
|
2759
|
+
const timer = window.setTimeout(() => {
|
|
2760
|
+
void (async () => {
|
|
2761
|
+
const bookingItems = Object.entries(quantities)
|
|
2762
|
+
.filter(([, count]) => count > 0)
|
|
2763
|
+
.map(([category, count]) => ({ category, count }));
|
|
2764
|
+
try {
|
|
2765
|
+
const quote = await quoteChangeBooking({
|
|
2766
|
+
bookingReference: bookingReferenceForQuote,
|
|
2767
|
+
lastName: lastName.trim(),
|
|
2768
|
+
newProductId: optionId,
|
|
2769
|
+
newDateTime: selectedAvailability.dateTime,
|
|
2770
|
+
newAvailabilityId: selectedAvailability.availabilityId || null,
|
|
2771
|
+
newPickupLocationId: pickupLocationId || null,
|
|
2772
|
+
newReturnAvailabilityId: selectedReturnOption?.returnAvailabilityId ?? null,
|
|
2773
|
+
newPassengerCounts: bookingItems,
|
|
2774
|
+
// Omit when empty: backend treats [] as "clear all"; missing = preserve stored selections (BookingChangeIntentService).
|
|
2775
|
+
...(addOnSelections.length > 0 ? { newAddOnSelections: addOnSelections } : {}),
|
|
2776
|
+
clientProposedTotal: changeFlowProposedTotal,
|
|
2777
|
+
});
|
|
2778
|
+
if (seq !== changeQuoteRequestSeq.current) return;
|
|
2779
|
+
const canProceed = quote.canProceed !== false;
|
|
2780
|
+
const quoteCurrency = (quote.currency || currency) as Currency;
|
|
2781
|
+
const quotedPriceDiff =
|
|
2782
|
+
quote.amountDueCents != null
|
|
2783
|
+
? quote.amountDueCents / 100
|
|
2784
|
+
: quote.priceDiff ?? 0;
|
|
2785
|
+
setLatestChangeQuote({
|
|
2786
|
+
priceDiff: quotedPriceDiff,
|
|
2787
|
+
currency: quoteCurrency,
|
|
2788
|
+
canProceed,
|
|
2789
|
+
reasonIfBlocked: quote.reasonIfBlocked,
|
|
2790
|
+
changeIntentId: quote.changeIntentId,
|
|
2791
|
+
quotedTotal: quote.proposed?.total ?? quote.newReceipt?.total,
|
|
2792
|
+
});
|
|
2793
|
+
} catch (e) {
|
|
2794
|
+
if (seq !== changeQuoteRequestSeq.current) return;
|
|
2795
|
+
setLatestChangeQuote(null);
|
|
2796
|
+
setChangeQuoteFetchError(e instanceof Error ? e.message : 'Failed to get price for this change');
|
|
2797
|
+
} finally {
|
|
2798
|
+
if (seq === changeQuoteRequestSeq.current) {
|
|
2799
|
+
setChangeQuoteLoading(false);
|
|
2800
|
+
}
|
|
2801
|
+
}
|
|
2802
|
+
})();
|
|
2803
|
+
}, 450);
|
|
2804
|
+
|
|
2805
|
+
return () => {
|
|
2806
|
+
window.clearTimeout(timer);
|
|
2807
|
+
};
|
|
2808
|
+
}, [
|
|
2809
|
+
isChangeFlow,
|
|
2810
|
+
hasChangeSelection,
|
|
2811
|
+
selectedAvailability,
|
|
2812
|
+
selectedAvailability?.dateTime,
|
|
2813
|
+
selectedAvailability?.productOptionId,
|
|
2814
|
+
initialValues?.bookingReference,
|
|
2815
|
+
lastName,
|
|
2816
|
+
missingRequiredReturnSelection,
|
|
2817
|
+
pickupLocationId,
|
|
2818
|
+
selectedReturnOption?.returnAvailabilityId,
|
|
2819
|
+
quantities,
|
|
2820
|
+
addOnSelections,
|
|
2821
|
+
totalPrice,
|
|
2822
|
+
currency,
|
|
2823
|
+
activeOptions,
|
|
2824
|
+
]);
|
|
2825
|
+
|
|
2826
|
+
// Auto-select product option when date is selected: most popular if set, otherwise first available.
|
|
2827
|
+
// Change flow after a calendar change: prefer same product option, then closest departure time-of-day.
|
|
2828
|
+
useEffect(() => {
|
|
2829
|
+
if (selectedDate && timesForSelectedDate.length > 0 && !selectedAvailability) {
|
|
2830
|
+
// Change flow on the booking's calendar day: pickup must come from resolveInitialAvailabilityFromBooking
|
|
2831
|
+
// (availabilityId / productOptionId / wall time). If we run "most popular" here too, both effects fire in
|
|
2832
|
+
// the same commit, this still sees selectedAvailability === null, and overwrites the correct slot.
|
|
2833
|
+
if (isChangeFlow && initialValues?.dateTime?.trim()) {
|
|
2834
|
+
try {
|
|
2835
|
+
const bookingDay = formatInTimeZone(
|
|
2836
|
+
parseAvailabilityDateTime(initialValues.dateTime.trim()),
|
|
2837
|
+
companyTimezone,
|
|
2838
|
+
'yyyy-MM-dd'
|
|
2839
|
+
);
|
|
2840
|
+
if (selectedDate === bookingDay) {
|
|
2841
|
+
return;
|
|
2842
|
+
}
|
|
2843
|
+
} catch {
|
|
2844
|
+
/* fall through */
|
|
2845
|
+
}
|
|
2846
|
+
}
|
|
2847
|
+
|
|
2848
|
+
const anchor = changeFlowOutboundAnchorRef.current;
|
|
2849
|
+
if (isChangeFlow && anchor) {
|
|
2850
|
+
const matched = pickOutboundMatchingPreviousSelection(
|
|
2851
|
+
timesForSelectedDate,
|
|
2852
|
+
anchor,
|
|
2853
|
+
companyTimezone,
|
|
2854
|
+
optionsMap,
|
|
2855
|
+
isAdmin
|
|
2856
|
+
);
|
|
2857
|
+
changeFlowOutboundAnchorRef.current = null;
|
|
2858
|
+
if (matched) {
|
|
2859
|
+
setSelectedAvailability(matched);
|
|
2860
|
+
setError('');
|
|
2861
|
+
return;
|
|
2862
|
+
}
|
|
2863
|
+
}
|
|
2864
|
+
|
|
2865
|
+
const mostPopularOption = activeOptions.find(opt => opt.mostPopular);
|
|
2866
|
+
const candidate = mostPopularOption
|
|
2867
|
+
? timesForSelectedDate.find(avail => avail.productOptionId === mostPopularOption.optionId && avail.vacancies > 0)
|
|
2868
|
+
: null;
|
|
2869
|
+
const fallback = timesForSelectedDate.find(avail => avail.vacancies > 0);
|
|
2870
|
+
const toSelect = candidate ?? fallback;
|
|
2871
|
+
if (toSelect) {
|
|
2872
|
+
setSelectedAvailability(toSelect);
|
|
2873
|
+
setError('');
|
|
2874
|
+
}
|
|
2875
|
+
}
|
|
2876
|
+
}, [
|
|
2877
|
+
selectedDate,
|
|
2878
|
+
timesForSelectedDateSelectionKey,
|
|
2879
|
+
activeOptionIdsKey,
|
|
2880
|
+
selectedAvailability,
|
|
2881
|
+
isChangeFlow,
|
|
2882
|
+
initialValues?.dateTime,
|
|
2883
|
+
companyTimezone,
|
|
2884
|
+
]);
|
|
2885
|
+
|
|
2886
|
+
// Currency change does NOT trigger a refetch. Backend returns per-currency data (priceByCurrency,
|
|
2887
|
+
// changeByCurrency, feesByCurrency, precomputedPrices, etc.) in one response; we just
|
|
2888
|
+
// re-render with the new currency and pick the right values.
|
|
2889
|
+
|
|
2890
|
+
// Sync selectedAvailability when the availabilities list changes (e.g. after refetch for new date range)
|
|
2891
|
+
useEffect(() => {
|
|
2892
|
+
if (selectedAvailability && availabilities.length > 0) {
|
|
2893
|
+
const updatedAvailability = availabilities.find(
|
|
2894
|
+
avail =>
|
|
2895
|
+
avail.dateTime === selectedAvailability.dateTime &&
|
|
2896
|
+
avail.productOptionId === selectedAvailability.productOptionId
|
|
2897
|
+
);
|
|
2898
|
+
if (updatedAvailability) {
|
|
2899
|
+
setSelectedAvailability(updatedAvailability);
|
|
2900
|
+
|
|
2901
|
+
// Also update selectedReturnOption if it exists
|
|
2902
|
+
if (selectedReturnOption && updatedAvailability.returnOptions) {
|
|
2903
|
+
const updatedReturnOption = updatedAvailability.returnOptions.find(
|
|
2904
|
+
opt => opt.returnAvailabilityId === selectedReturnOption.returnAvailabilityId
|
|
2905
|
+
);
|
|
2906
|
+
if (updatedReturnOption) {
|
|
2907
|
+
setSelectedReturnOption(updatedReturnOption);
|
|
2908
|
+
}
|
|
2909
|
+
}
|
|
2910
|
+
}
|
|
2911
|
+
}
|
|
2912
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
2913
|
+
}, [availabilities]); // Update when availabilities change (selectedAvailability/selectedReturnOption intentionally excluded to avoid loops)
|
|
2914
|
+
|
|
2915
|
+
// Reset implicit return baseline when outbound changes or API provides explicit return hints.
|
|
2916
|
+
useEffect(() => {
|
|
2917
|
+
if (!isChangeFlow) {
|
|
2918
|
+
setImplicitReturnBaselineId(null);
|
|
2919
|
+
return;
|
|
2920
|
+
}
|
|
2921
|
+
const hasApiReturnHint =
|
|
2922
|
+
Boolean(initialValues?.returnAvailabilityId?.trim()) ||
|
|
2923
|
+
Boolean(initialValues?.returnDateTime?.trim());
|
|
2924
|
+
if (hasApiReturnHint) {
|
|
2925
|
+
setImplicitReturnBaselineId(null);
|
|
2926
|
+
return;
|
|
2927
|
+
}
|
|
2928
|
+
setImplicitReturnBaselineId(null);
|
|
2929
|
+
}, [
|
|
2930
|
+
isChangeFlow,
|
|
2931
|
+
selectedAvailability?.dateTime,
|
|
2932
|
+
selectedAvailability?.productOptionId,
|
|
2933
|
+
initialValues?.returnAvailabilityId,
|
|
2934
|
+
initialValues?.returnDateTime,
|
|
2935
|
+
]);
|
|
2936
|
+
|
|
2937
|
+
// Auto-select return option when outbound is selected (prefer booked return in change flow).
|
|
2938
|
+
// After a calendar date change in change flow: prefer same return location, then closest return time-of-day.
|
|
2939
|
+
useEffect(() => {
|
|
2940
|
+
if (selectedAvailability?.returnOptions && selectedAvailability.returnOptions.length > 0 && !selectedReturnOption) {
|
|
2941
|
+
const sorted = [...selectedAvailability.returnOptions].sort(
|
|
2942
|
+
(a, b) => parseISO(a.dateTime).getTime() - parseISO(b.dateTime).getTime()
|
|
2943
|
+
);
|
|
2944
|
+
const initialReturnIdForSelect = initialValues?.returnAvailabilityId?.trim();
|
|
2945
|
+
const initialReturnDtForSelect = initialValues?.returnDateTime?.trim();
|
|
2946
|
+
|
|
2947
|
+
const returnAnchor = changeFlowReturnAnchorRef.current;
|
|
2948
|
+
if (isChangeFlow && returnAnchor) {
|
|
2949
|
+
const fromAnchor = pickReturnMatchingPreviousSelection(
|
|
2950
|
+
sorted,
|
|
2951
|
+
returnAnchor,
|
|
2952
|
+
companyTimezone,
|
|
2953
|
+
isAdmin
|
|
2954
|
+
);
|
|
2955
|
+
changeFlowReturnAnchorRef.current = null;
|
|
2956
|
+
if (fromAnchor) {
|
|
2957
|
+
setSelectedReturnOption(fromAnchor);
|
|
2958
|
+
if (isChangeFlow) {
|
|
2959
|
+
const hasApiReturnHint =
|
|
2960
|
+
Boolean(initialReturnIdForSelect) || Boolean(initialReturnDtForSelect);
|
|
2961
|
+
if (!hasApiReturnHint) {
|
|
2962
|
+
setImplicitReturnBaselineId((prev) => prev ?? fromAnchor.returnAvailabilityId);
|
|
2963
|
+
}
|
|
2964
|
+
}
|
|
2965
|
+
return;
|
|
2966
|
+
}
|
|
2967
|
+
}
|
|
2968
|
+
|
|
2969
|
+
const preferBooked =
|
|
2970
|
+
isChangeFlow && initialReturnIdForSelect
|
|
2971
|
+
? sorted.find((opt) => opt.returnAvailabilityId === initialReturnIdForSelect && opt.vacancies > 0)
|
|
2972
|
+
: undefined;
|
|
2973
|
+
const preferByDateTime =
|
|
2974
|
+
isChangeFlow && initialReturnDtForSelect && !preferBooked
|
|
2975
|
+
? sorted.find((opt) => {
|
|
2976
|
+
if (opt.vacancies <= 0) return false;
|
|
2977
|
+
try {
|
|
2978
|
+
return (
|
|
2979
|
+
parseAvailabilityDateTime(opt.dateTime).getTime() ===
|
|
2980
|
+
parseAvailabilityDateTime(initialReturnDtForSelect).getTime()
|
|
2981
|
+
);
|
|
2982
|
+
} catch {
|
|
2983
|
+
return false;
|
|
2984
|
+
}
|
|
2985
|
+
})
|
|
2986
|
+
: undefined;
|
|
2987
|
+
const firstAvailable = sorted.find((opt) => opt.vacancies > 0);
|
|
2988
|
+
const toSelect = preferBooked ?? preferByDateTime ?? firstAvailable;
|
|
2989
|
+
if (toSelect) {
|
|
2990
|
+
setSelectedReturnOption(toSelect);
|
|
2991
|
+
if (isChangeFlow) {
|
|
2992
|
+
const hasApiReturnHint =
|
|
2993
|
+
Boolean(initialReturnIdForSelect) || Boolean(initialReturnDtForSelect);
|
|
2994
|
+
if (!hasApiReturnHint) {
|
|
2995
|
+
setImplicitReturnBaselineId((prev) => prev ?? toSelect.returnAvailabilityId);
|
|
2996
|
+
}
|
|
2997
|
+
}
|
|
2998
|
+
}
|
|
2999
|
+
}
|
|
3000
|
+
}, [
|
|
3001
|
+
selectedAvailability,
|
|
3002
|
+
selectedReturnOption,
|
|
3003
|
+
isChangeFlow,
|
|
3004
|
+
companyTimezone,
|
|
3005
|
+
isAdmin,
|
|
3006
|
+
initialValues?.returnAvailabilityId,
|
|
3007
|
+
initialValues?.returnDateTime,
|
|
3008
|
+
]);
|
|
3009
|
+
|
|
3010
|
+
// Fetch add-ons when availability (product option) is selected; clear selections when option changes
|
|
3011
|
+
const availabilityProductOptionId = selectedAvailability?.productOptionId ?? null;
|
|
3012
|
+
const prevAvailabilityProductOptionIdRef = useRef<string | null>(null);
|
|
3013
|
+
useEffect(() => {
|
|
3014
|
+
if (!availabilityProductOptionId || !product.companyId) {
|
|
3015
|
+
setAddOns([]);
|
|
3016
|
+
if (!isChangeFlow) setAddOnSelections([]);
|
|
3017
|
+
return;
|
|
3018
|
+
}
|
|
3019
|
+
const optionChanged = prevAvailabilityProductOptionIdRef.current !== availabilityProductOptionId;
|
|
3020
|
+
if (optionChanged) {
|
|
3021
|
+
if (!isChangeFlow) setAddOnSelections([]);
|
|
3022
|
+
prevAvailabilityProductOptionIdRef.current = availabilityProductOptionId;
|
|
3023
|
+
}
|
|
3024
|
+
getAddOns(product.companyId, { productOptionId: availabilityProductOptionId, preCheckout: true })
|
|
3025
|
+
.then(setAddOns)
|
|
3026
|
+
.catch(() => setAddOns([]));
|
|
3027
|
+
}, [availabilityProductOptionId, product.companyId, isChangeFlow]);
|
|
3028
|
+
|
|
3029
|
+
// Auto-select cheapest cancellation policy when pricing config loads (not when change flow already has the booked policy)
|
|
3030
|
+
useEffect(() => {
|
|
3031
|
+
if (pricingConfig?.cancellationPolicies && pricingConfig.cancellationPolicies.length > 0 && !cancellationPolicyId) {
|
|
3032
|
+
const sorted = [...pricingConfig.cancellationPolicies].sort((a, b) => {
|
|
3033
|
+
const feeA = a.feeByCurrency[currency] ?? 0;
|
|
3034
|
+
const feeB = b.feeByCurrency[currency] ?? 0;
|
|
3035
|
+
return feeA - feeB;
|
|
3036
|
+
});
|
|
3037
|
+
setCancellationPolicyId(sorted[0].id);
|
|
3038
|
+
}
|
|
3039
|
+
}, [pricingConfig?.cancellationPolicies, cancellationPolicyId, currency]);
|
|
3040
|
+
|
|
3041
|
+
const handleDateSelect = (date: string) => {
|
|
3042
|
+
if (date === selectedDate) return;
|
|
3043
|
+
if (isChangeFlow && selectedAvailability) {
|
|
3044
|
+
changeFlowOutboundAnchorRef.current = {
|
|
3045
|
+
productOptionId: selectedAvailability.productOptionId ?? null,
|
|
3046
|
+
minutesFromMidnight: getMinutesFromMidnightInTimezone(
|
|
3047
|
+
selectedAvailability.dateTime,
|
|
3048
|
+
companyTimezone
|
|
3049
|
+
),
|
|
3050
|
+
};
|
|
3051
|
+
if (selectedReturnOption) {
|
|
3052
|
+
changeFlowReturnAnchorRef.current = {
|
|
3053
|
+
returnLocation: selectedReturnOption.returnLocation,
|
|
3054
|
+
minutesFromMidnight: getMinutesFromMidnightInTimezone(
|
|
3055
|
+
selectedReturnOption.dateTime,
|
|
3056
|
+
companyTimezone
|
|
3057
|
+
),
|
|
3058
|
+
};
|
|
3059
|
+
} else {
|
|
3060
|
+
changeFlowReturnAnchorRef.current = null;
|
|
3061
|
+
}
|
|
3062
|
+
}
|
|
3063
|
+
setSelectedAvailability(null);
|
|
3064
|
+
setSelectedReturnOption(null);
|
|
3065
|
+
};
|
|
3066
|
+
|
|
3067
|
+
handleDateSelectRef.current = handleDateSelect;
|
|
3068
|
+
|
|
3069
|
+
useEffect(() => {
|
|
3070
|
+
if (flowUi?.autoSelectFirstAvailableDate !== true) return;
|
|
3071
|
+
if (isChangeFlow || isPartialLaunch) return;
|
|
3072
|
+
if (initialValues?.dateTime?.trim()) return;
|
|
3073
|
+
if (selectedDate !== '') return;
|
|
3074
|
+
if (dates.length === 0) return;
|
|
3075
|
+
if (hasAutoSelectedPartnerDateRef.current) return;
|
|
3076
|
+
|
|
3077
|
+
// Match Calendar: a day is "sold out" only when every slot has 0 vacancies. Admins may still pick sold-out days.
|
|
3078
|
+
const first = isAdmin
|
|
3079
|
+
? dates[0]
|
|
3080
|
+
: dates.find((d) =>
|
|
3081
|
+
(availabilitiesByDate[d] ?? []).some((a) => (a.vacancies ?? 0) > 0),
|
|
3082
|
+
);
|
|
3083
|
+
if (!first) return;
|
|
3084
|
+
|
|
3085
|
+
hasAutoSelectedPartnerDateRef.current = true;
|
|
3086
|
+
setSelectedDate(first);
|
|
3087
|
+
handleDateSelectRef.current(first);
|
|
3088
|
+
if (!suppressCalendarDateScroll) {
|
|
3089
|
+
setTimeout(() => {
|
|
3090
|
+
const container = contentRef?.current;
|
|
3091
|
+
if (!useWindowScroll && container && container.scrollHeight > container.clientHeight + 16) {
|
|
3092
|
+
container.scrollBy({ top: 400, behavior: 'smooth' });
|
|
3093
|
+
} else if (typeof window !== 'undefined') {
|
|
3094
|
+
window.scrollBy({ top: 400, behavior: 'smooth' });
|
|
3095
|
+
}
|
|
3096
|
+
}, 100);
|
|
3097
|
+
}
|
|
3098
|
+
}, [
|
|
3099
|
+
flowUi?.autoSelectFirstAvailableDate,
|
|
3100
|
+
isChangeFlow,
|
|
3101
|
+
isPartialLaunch,
|
|
3102
|
+
initialValues?.dateTime,
|
|
3103
|
+
selectedDate,
|
|
3104
|
+
dates,
|
|
3105
|
+
availabilitiesByDate,
|
|
3106
|
+
isAdmin,
|
|
3107
|
+
useWindowScroll,
|
|
3108
|
+
contentRef,
|
|
3109
|
+
suppressCalendarDateScroll,
|
|
3110
|
+
]);
|
|
3111
|
+
|
|
3112
|
+
useEffect(() => {
|
|
3113
|
+
if (flowUi?.autoSelectFirstHighlightedPickup !== true) return;
|
|
3114
|
+
if (hasAutoSelectedPartnerPickupRef.current) return;
|
|
3115
|
+
if (!highlightedPickupLocationIds?.length) return;
|
|
3116
|
+
if (pickupLocationId) return;
|
|
3117
|
+
if (pickupLocationSkipped) return;
|
|
3118
|
+
if (initialValues?.pickupLocationId?.trim()) return;
|
|
3119
|
+
const locs = product.pickupLocations;
|
|
3120
|
+
if (!locs?.length) return;
|
|
3121
|
+
const match = highlightedPickupLocationIds.find((id) => locs.some((l) => l.id === id));
|
|
3122
|
+
if (!match) return;
|
|
3123
|
+
hasAutoSelectedPartnerPickupRef.current = true;
|
|
3124
|
+
setPickupLocationId(match);
|
|
3125
|
+
setPickupLocationSkipped(false);
|
|
3126
|
+
}, [
|
|
3127
|
+
flowUi?.autoSelectFirstHighlightedPickup,
|
|
3128
|
+
highlightedPickupLocationIds,
|
|
3129
|
+
pickupLocationId,
|
|
3130
|
+
pickupLocationSkipped,
|
|
3131
|
+
initialValues?.pickupLocationId,
|
|
3132
|
+
product.pickupLocations,
|
|
3133
|
+
]);
|
|
3134
|
+
|
|
3135
|
+
const handleTimeSelect = (availability: Availability) => {
|
|
3136
|
+
setSelectedAvailability(availability);
|
|
3137
|
+
setSelectedReturnOption(null); // Clear return selection when changing start time
|
|
3138
|
+
setError('');
|
|
3139
|
+
};
|
|
3140
|
+
|
|
3141
|
+
const handleQuantityChange = (category: string, delta: number) => {
|
|
3142
|
+
const maxAvailable = isAdmin ? Number.MAX_SAFE_INTEGER : effectivePartySizeCap;
|
|
3143
|
+
const currentQty = quantities[category] || 0;
|
|
3144
|
+
const minQ =
|
|
3145
|
+
changeBookingMinimumQuantities != null
|
|
3146
|
+
? Math.max(0, changeBookingMinimumQuantities[category] ?? 0)
|
|
3147
|
+
: 0;
|
|
3148
|
+
const newQty = Math.max(minQ, currentQty + delta);
|
|
3149
|
+
// Admin can overbook; non-admin cannot exceed vacancies
|
|
3150
|
+
if (delta > 0 && !isAdmin && orderSummary.totalQuantity >= maxAvailable) {
|
|
3151
|
+
return;
|
|
3152
|
+
}
|
|
3153
|
+
setQuantities(prev => ({
|
|
3154
|
+
...prev,
|
|
3155
|
+
[category]: newQty,
|
|
3156
|
+
}));
|
|
3157
|
+
setError('');
|
|
3158
|
+
};
|
|
3159
|
+
|
|
3160
|
+
// Selected availability has a deal applied (promo codes not allowed with deals; vouchers/gift cards still allowed; dynamic pricing alone is ok)
|
|
3161
|
+
const hasOngoingDiscount = useMemo(
|
|
3162
|
+
() =>
|
|
3163
|
+
selectedAvailability?.rates?.some((r) =>
|
|
3164
|
+
(r.appliedAdjustments ?? r.applied_adjustments ?? []).some((a) => (a.type ?? '').toLowerCase() === 'deal')
|
|
3165
|
+
) ?? false,
|
|
3166
|
+
[selectedAvailability]
|
|
3167
|
+
);
|
|
3168
|
+
const selectedAvailabilityKey = useMemo(
|
|
3169
|
+
() => `${selectedAvailability?.dateTime ?? ''}::${selectedAvailability?.productOptionId ?? ''}`,
|
|
3170
|
+
[selectedAvailability?.dateTime, selectedAvailability?.productOptionId]
|
|
3171
|
+
);
|
|
3172
|
+
// Remember where promo was successfully applied to avoid self-clearing on same selection.
|
|
3173
|
+
const promoAppliedSelectionKeyRef = useRef<string | null>(null);
|
|
3174
|
+
const promoValidateInFlightRef = useRef(false);
|
|
3175
|
+
|
|
3176
|
+
const handleApplyPromo = useCallback(async () => {
|
|
3177
|
+
const code = promoCodeInput.trim().toUpperCase();
|
|
3178
|
+
if (!code) return;
|
|
3179
|
+
// Promo validation/application requires a concrete booking context.
|
|
3180
|
+
if (!selectedAvailability || totalQuantity <= 0) {
|
|
3181
|
+
return;
|
|
3182
|
+
}
|
|
3183
|
+
if (appliedPromoCode === code) return; // Already applied, skip API call
|
|
3184
|
+
const companyId = product.companyId;
|
|
3185
|
+
if (!companyId) return;
|
|
3186
|
+
if (promoValidateInFlightRef.current) return;
|
|
3187
|
+
promoValidateInFlightRef.current = true;
|
|
3188
|
+
setPromoCodeError('');
|
|
3189
|
+
setPromoCodeValidating(true);
|
|
3190
|
+
try {
|
|
3191
|
+
const result = await validatePromoCode(code, companyId, product.productId, hasOngoingDiscount);
|
|
3192
|
+
if (result.valid) {
|
|
3193
|
+
promoAppliedSelectionKeyRef.current = selectedAvailabilityKey;
|
|
3194
|
+
setAppliedPromoCode(code);
|
|
3195
|
+
fetchedRangesRef.current = [];
|
|
3196
|
+
if (result.forcedCancellationPolicyId && result.forcedCancellationPolicyLabel) {
|
|
3197
|
+
setForcedCancellationPolicy({
|
|
3198
|
+
id: result.forcedCancellationPolicyId,
|
|
3199
|
+
label: result.forcedCancellationPolicyLabel,
|
|
3200
|
+
refundTiers: result.forcedCancellationPolicyRefundTiers,
|
|
3201
|
+
changeWindowHoursBefore: result.forcedChangeWindowHoursBefore ?? undefined,
|
|
3202
|
+
});
|
|
3203
|
+
setCancellationPolicyId(result.forcedCancellationPolicyId);
|
|
3204
|
+
// Scroll to cancellation policy section so user sees the forced policy (after state flush)
|
|
3205
|
+
setTimeout(() => {
|
|
3206
|
+
cancellationPolicyRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
|
3207
|
+
}, 100);
|
|
3208
|
+
} else {
|
|
3209
|
+
setForcedCancellationPolicy(null);
|
|
3210
|
+
}
|
|
3211
|
+
} else {
|
|
3212
|
+
const errorMsg =
|
|
3213
|
+
result.error === 'Promo codes cannot be stacked with deals'
|
|
3214
|
+
? (t('booking.promoCodesCannotStackWithDiscounts') || result.error)
|
|
3215
|
+
: (result.error || t('booking.invalidPromoCode') || 'Invalid or expired promo code');
|
|
3216
|
+
setPromoCodeError(errorMsg);
|
|
3217
|
+
}
|
|
3218
|
+
} catch (err) {
|
|
3219
|
+
setPromoCodeError(err instanceof Error ? err.message : 'Failed to validate promo code');
|
|
3220
|
+
} finally {
|
|
3221
|
+
promoValidateInFlightRef.current = false;
|
|
3222
|
+
setPromoCodeValidating(false);
|
|
3223
|
+
}
|
|
3224
|
+
}, [promoCodeInput, appliedPromoCode, product.companyId, product.productId, hasOngoingDiscount, t, selectedAvailabilityKey, selectedAvailability, totalQuantity]);
|
|
3225
|
+
|
|
3226
|
+
// When user selects a time with ongoing discount and has a promo applied, re-validate and clear if promo can't be stacked
|
|
3227
|
+
useEffect(() => {
|
|
3228
|
+
if (isChangeFlow) return;
|
|
3229
|
+
if (!appliedPromoCode || !hasOngoingDiscount) return;
|
|
3230
|
+
// Only run this guard when user moved away from the selection where promo was applied.
|
|
3231
|
+
// On the same selection, "deal" adjustments can be promo-driven and would self-clear incorrectly.
|
|
3232
|
+
if (promoAppliedSelectionKeyRef.current === selectedAvailabilityKey) {
|
|
3233
|
+
return;
|
|
3234
|
+
}
|
|
3235
|
+
let cancelled = false;
|
|
3236
|
+
validatePromoCode(appliedPromoCode, product.companyId ?? '', product.productId, true).then((result) => {
|
|
3237
|
+
if (cancelled) return;
|
|
3238
|
+
if (!result.valid && result.error === 'Promo codes cannot be stacked with deals') {
|
|
3239
|
+
promoAppliedSelectionKeyRef.current = null;
|
|
3240
|
+
setAppliedPromoCode(null);
|
|
3241
|
+
setPromoCodeInput(appliedPromoCode);
|
|
3242
|
+
setPromoCodeError(t('booking.promoCodesCannotStackWithDiscounts') || result.error);
|
|
3243
|
+
setForcedCancellationPolicy(null);
|
|
3244
|
+
setCancellationPolicyId(null);
|
|
3245
|
+
fetchedRangesRef.current = [];
|
|
3246
|
+
}
|
|
3247
|
+
});
|
|
3248
|
+
return () => { cancelled = true; };
|
|
3249
|
+
}, [isChangeFlow, hasOngoingDiscount, appliedPromoCode, product.companyId, product.productId, t, selectedAvailabilityKey]);
|
|
3250
|
+
|
|
3251
|
+
// Ref to avoid effect re-running when handleApplyPromo identity changes (t changes every render)
|
|
3252
|
+
const handleApplyPromoRef = useRef(handleApplyPromo);
|
|
3253
|
+
handleApplyPromoRef.current = handleApplyPromo;
|
|
3254
|
+
|
|
3255
|
+
// Auto-apply promo when user stops typing (mobile-friendly, no Enter key needed).
|
|
3256
|
+
// Do not depend on promoCodeValidating: when it flips false after a failed validate, that would
|
|
3257
|
+
// re-run this effect and schedule another timer → repeated /validate for the same bad code.
|
|
3258
|
+
useEffect(() => {
|
|
3259
|
+
const trimmed = promoCodeInput.trim().toUpperCase();
|
|
3260
|
+
if (!trimmed) return;
|
|
3261
|
+
if (!selectedAvailability || totalQuantity <= 0) return;
|
|
3262
|
+
if (appliedPromoCode === trimmed) return;
|
|
3263
|
+
|
|
3264
|
+
const timer = setTimeout(() => {
|
|
3265
|
+
handleApplyPromoRef.current();
|
|
3266
|
+
}, 600);
|
|
3267
|
+
|
|
3268
|
+
return () => clearTimeout(timer);
|
|
3269
|
+
}, [promoCodeInput, appliedPromoCode, selectedAvailability, totalQuantity]);
|
|
3270
|
+
|
|
3271
|
+
const cancelPendingReservation = useCallback(() => {
|
|
3272
|
+
if (paymentSubmitInFlightRef.current) return;
|
|
3273
|
+
const pending = pendingReservationRef.current;
|
|
3274
|
+
if (!pending) return;
|
|
3275
|
+
pendingReservationRef.current = null;
|
|
3276
|
+
cancelReservation(pending.reservationReference).catch(() => {});
|
|
3277
|
+
setShowCheckoutModal(false);
|
|
3278
|
+
setCheckoutModalData(null);
|
|
3279
|
+
setCheckoutClientSecret('');
|
|
3280
|
+
}, []);
|
|
3281
|
+
|
|
3282
|
+
const cancelPendingReservationBestEffort = useCallback(() => {
|
|
3283
|
+
if (paymentSubmitInFlightRef.current) return;
|
|
3284
|
+
const pending = pendingReservationRef.current;
|
|
3285
|
+
if (!pending) return;
|
|
3286
|
+
pendingReservationRef.current = null;
|
|
3287
|
+
cancelReservationBestEffort(pending.reservationReference);
|
|
3288
|
+
setShowCheckoutModal(false);
|
|
3289
|
+
setCheckoutModalData(null);
|
|
3290
|
+
setCheckoutClientSecret('');
|
|
3291
|
+
}, []);
|
|
3292
|
+
|
|
3293
|
+
// Parent surfaces (dialog close / embedded back) emit this when user abandons the booking flow.
|
|
3294
|
+
useEffect(() => {
|
|
3295
|
+
const handleAbandon = () => {
|
|
3296
|
+
cancelPendingReservation();
|
|
3297
|
+
};
|
|
3298
|
+
window.addEventListener(BOOKING_FLOW_ABANDON_EVENT, handleAbandon);
|
|
3299
|
+
return () => window.removeEventListener(BOOKING_FLOW_ABANDON_EVENT, handleAbandon);
|
|
3300
|
+
}, [cancelPendingReservation]);
|
|
3301
|
+
|
|
3302
|
+
useEffect(() => {
|
|
3303
|
+
const handlePageHide = () => {
|
|
3304
|
+
cancelPendingReservationBestEffort();
|
|
3305
|
+
};
|
|
3306
|
+
window.addEventListener('pagehide', handlePageHide);
|
|
3307
|
+
return () => window.removeEventListener('pagehide', handlePageHide);
|
|
3308
|
+
}, [cancelPendingReservationBestEffort]);
|
|
3309
|
+
|
|
3310
|
+
const handleCheckout = async () => {
|
|
3311
|
+
if (!selectedAvailability || totalQuantity === 0) {
|
|
3312
|
+
setError(t('booking.selectTimeAndTickets'));
|
|
3313
|
+
return;
|
|
3314
|
+
}
|
|
3315
|
+
if (isChangeFlow && missingRequiredReturnSelection) {
|
|
3316
|
+
setError('Removing return option in self-serve is not available. Please contact support.');
|
|
3317
|
+
return;
|
|
3318
|
+
}
|
|
3319
|
+
|
|
3320
|
+
// Validate email (required)
|
|
3321
|
+
if (!email) {
|
|
3322
|
+
setError(t('booking.enterEmail') || 'Please enter your email address');
|
|
3323
|
+
return;
|
|
3324
|
+
}
|
|
3325
|
+
|
|
3326
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
|
|
3327
|
+
setError(t('booking.invalidEmail') || 'Please enter a valid email address');
|
|
3328
|
+
return;
|
|
3329
|
+
}
|
|
3330
|
+
|
|
3331
|
+
// Validate first name (required)
|
|
3332
|
+
if (!firstName?.trim()) {
|
|
3333
|
+
setError(t('booking.enterFirstName') || 'Please enter your first name');
|
|
3334
|
+
return;
|
|
3335
|
+
}
|
|
3336
|
+
|
|
3337
|
+
// Validate last name (required for manage booking lookup)
|
|
3338
|
+
if (!lastName?.trim()) {
|
|
3339
|
+
setError(t('booking.enterLastName') || 'Please enter your last name');
|
|
3340
|
+
return;
|
|
3341
|
+
}
|
|
3342
|
+
|
|
3343
|
+
|
|
3344
|
+
// Allow checkout if pickup location is selected OR if user chose "I don't know"
|
|
3345
|
+
if (product.pickupLocations && product.pickupLocations.length > 0 && !pickupLocationId && !pickupLocationSkipped) {
|
|
3346
|
+
setError(t('booking.selectPickupLocation'));
|
|
3347
|
+
return;
|
|
3348
|
+
}
|
|
3349
|
+
|
|
3350
|
+
setLoading(true);
|
|
3351
|
+
setError('');
|
|
3352
|
+
paymentSubmitInFlightRef.current = false;
|
|
3353
|
+
|
|
3354
|
+
try {
|
|
3355
|
+
const bookingItems = Object.entries(quantities)
|
|
3356
|
+
.filter(([, count]) => count > 0)
|
|
3357
|
+
.map(([category, count]) => ({ category, count }));
|
|
3358
|
+
|
|
3359
|
+
// Get the productOptionId from the selected availability (we tagged it when fetching)
|
|
3360
|
+
const availabilityProductOptionId = selectedAvailability.productOptionId
|
|
3361
|
+
|| activeOptions[0]?.optionId;
|
|
3362
|
+
|
|
3363
|
+
if (!availabilityProductOptionId) {
|
|
3364
|
+
setError('No product option selected');
|
|
3365
|
+
setLoading(false);
|
|
3366
|
+
return;
|
|
3367
|
+
}
|
|
3368
|
+
|
|
3369
|
+
const bookingSourceContext = buildBookingSourceContext(bookingSourceAttribution, {
|
|
3370
|
+
clientChannelSource: inferClientBookingSourceFromProductIds(
|
|
3371
|
+
product.productId,
|
|
3372
|
+
availabilityProductOptionId,
|
|
3373
|
+
),
|
|
3374
|
+
forcePartnerPortalChannel: partnerPortalBooking,
|
|
3375
|
+
forceDashboardSource: bookingAppMode === 'provider-dashboard',
|
|
3376
|
+
});
|
|
3377
|
+
|
|
3378
|
+
// Get the hotel name if a pickup location was selected
|
|
3379
|
+
const selectedPickupLocation = pickupLocationId
|
|
3380
|
+
? product.pickupLocations?.find(loc => loc.id === pickupLocationId)
|
|
3381
|
+
: null;
|
|
3382
|
+
let quotedPriceDiff: number | null = null;
|
|
3383
|
+
let changeIntentIdForCheckout: string | undefined;
|
|
3384
|
+
let changeBookingReferenceForPaidFlow: string | undefined;
|
|
3385
|
+
|
|
3386
|
+
if (isChangeFlow) {
|
|
3387
|
+
const changeBookingReference = initialValues?.bookingReference?.trim();
|
|
3388
|
+
const changeLastName = lastName.trim();
|
|
3389
|
+
if (!changeBookingReference || !changeLastName) {
|
|
3390
|
+
throw new Error('Missing booking reference or last name for change quote');
|
|
3391
|
+
}
|
|
3392
|
+
const quote = await quoteChangeBooking({
|
|
3393
|
+
bookingReference: changeBookingReference,
|
|
3394
|
+
lastName: changeLastName,
|
|
3395
|
+
newProductId: availabilityProductOptionId,
|
|
3396
|
+
newDateTime: selectedAvailability.dateTime,
|
|
3397
|
+
newAvailabilityId: selectedAvailability.availabilityId || null,
|
|
3398
|
+
newPickupLocationId: pickupLocationId || null,
|
|
3399
|
+
newReturnAvailabilityId: selectedReturnOption?.returnAvailabilityId ?? null,
|
|
3400
|
+
newPassengerCounts: bookingItems,
|
|
3401
|
+
...(addOnSelections.length > 0 ? { newAddOnSelections: addOnSelections } : {}),
|
|
3402
|
+
clientProposedTotal: changeFlowProposedTotal,
|
|
3403
|
+
});
|
|
3404
|
+
const canProceed = quote.canProceed !== false;
|
|
3405
|
+
const quoteCurrency = (quote.currency || currency) as Currency;
|
|
3406
|
+
quotedPriceDiff =
|
|
3407
|
+
quote.amountDueCents != null
|
|
3408
|
+
? quote.amountDueCents / 100
|
|
3409
|
+
: quote.priceDiff ?? 0;
|
|
3410
|
+
changeBookingReferenceForPaidFlow = changeBookingReference;
|
|
3411
|
+
changeIntentIdForCheckout = quote.changeIntentId ?? undefined;
|
|
3412
|
+
setLatestChangeQuote({
|
|
3413
|
+
priceDiff: quotedPriceDiff,
|
|
3414
|
+
currency: quoteCurrency,
|
|
3415
|
+
canProceed,
|
|
3416
|
+
reasonIfBlocked: quote.reasonIfBlocked,
|
|
3417
|
+
changeIntentId: quote.changeIntentId,
|
|
3418
|
+
quotedTotal: quote.proposed?.total ?? quote.newReceipt?.total,
|
|
3419
|
+
});
|
|
3420
|
+
if (!canProceed) {
|
|
3421
|
+
throw new Error(quote.reasonIfBlocked || 'This booking change cannot be completed right now.');
|
|
3422
|
+
}
|
|
3423
|
+
const feChangeDue = Math.max(0, changeFlowProposedTotal - (originalReceipt?.total ?? 0));
|
|
3424
|
+
const serverAmountDue =
|
|
3425
|
+
quote.amountDueCents != null
|
|
3426
|
+
? Math.max(0, quote.amountDueCents / 100)
|
|
3427
|
+
: Math.max(0, quote.priceDiff ?? 0);
|
|
3428
|
+
if (feChangeDue > 0.02 && serverAmountDue <= 0.009) {
|
|
3429
|
+
throw new Error(
|
|
3430
|
+
'This change requires payment, but the price could not be confirmed. Please refresh and try again.'
|
|
3431
|
+
);
|
|
3432
|
+
}
|
|
3433
|
+
// No-payment change: FE shows nothing owed — still require server agreement so we never confirm free when a charge is due.
|
|
3434
|
+
if (serverAmountDue <= 0.009) {
|
|
3435
|
+
if (feChangeDue > 0.02) {
|
|
3436
|
+
throw new Error(
|
|
3437
|
+
'This change requires payment, but the price could not be confirmed. Please refresh and try again.'
|
|
3438
|
+
);
|
|
3439
|
+
}
|
|
3440
|
+
const p = quote.proposed?.total ?? quote.newReceipt?.total;
|
|
3441
|
+
const o = quote.original?.total ?? quote.originalReceipt?.total;
|
|
3442
|
+
if (p != null && o != null && p - o > 0.01) {
|
|
3443
|
+
throw new Error(
|
|
3444
|
+
'This change requires payment, but the price could not be confirmed. Please refresh and try again.'
|
|
3445
|
+
);
|
|
3446
|
+
}
|
|
3447
|
+
if (!quote.changeIntentId) {
|
|
3448
|
+
throw new Error('Missing change intent for booking change confirmation.');
|
|
3449
|
+
}
|
|
3450
|
+
const freeConfirm = await confirmFreeChangeBooking(quote.changeIntentId);
|
|
3451
|
+
if (freeConfirm.status && freeConfirm.status !== 'APPLIED') {
|
|
3452
|
+
throw new Error('We could not apply this booking change yet. Please try again.');
|
|
3453
|
+
}
|
|
3454
|
+
onSuccess?.({ reservationReference: changeBookingReference });
|
|
3455
|
+
setLoading(false);
|
|
3456
|
+
return;
|
|
3457
|
+
}
|
|
3458
|
+
if (!changeIntentIdForCheckout) {
|
|
3459
|
+
throw new Error('Missing change intent for payment.');
|
|
3460
|
+
}
|
|
3461
|
+
}
|
|
3462
|
+
|
|
3463
|
+
let reservation: { reservationReference: string; expiresAt?: string; totalAmount?: number; currency?: string } | null = null;
|
|
3464
|
+
const shouldCreateReservation = !isChangeFlow;
|
|
3465
|
+
if (shouldCreateReservation) {
|
|
3466
|
+
reservation = await createReservation({
|
|
3467
|
+
productId: availabilityProductOptionId, // GetYourGuide passes productOptionId values in productId field
|
|
3468
|
+
dateTime: selectedAvailability.dateTime,
|
|
3469
|
+
availabilityId: selectedAvailability.availabilityId || undefined,
|
|
3470
|
+
bookingItems,
|
|
3471
|
+
pickupLocationId: pickupLocationId || undefined,
|
|
3472
|
+
returnAvailabilityId: selectedReturnOption?.returnAvailabilityId,
|
|
3473
|
+
currency: currency,
|
|
3474
|
+
promoCode: (lockedPromoCode || appliedPromoCode) || undefined,
|
|
3475
|
+
cancellationPolicyId: cancellationPolicyId || undefined,
|
|
3476
|
+
addOnSelections: addOnSelections.length > 0 ? addOnSelections : undefined,
|
|
3477
|
+
...(isAdmin ? { allowOverbook: true } : {}),
|
|
3478
|
+
// Pass hotel name when pickup location is selected (for reference)
|
|
3479
|
+
// Don't set travelerHotel when user selects "I don't know" - leave it undefined
|
|
3480
|
+
// This allows us to distinguish between "unknown" (null) and "unmapped hotel name" (not null)
|
|
3481
|
+
travelerHotel: selectedPickupLocation?.name || undefined,
|
|
3482
|
+
// For standard bookings, backend calculates startTime from availability + pickup location offset
|
|
3483
|
+
// When pickup location is skipped, backend will store null for startTime
|
|
3484
|
+
...(bookingSourceContext.sourceMetadata
|
|
3485
|
+
? {
|
|
3486
|
+
source: bookingSourceContext.source,
|
|
3487
|
+
sourceMetadata: bookingSourceContext.sourceMetadata,
|
|
3488
|
+
source_metadata: bookingSourceContext.source_metadata,
|
|
3489
|
+
}
|
|
3490
|
+
: {}),
|
|
3491
|
+
});
|
|
3492
|
+
pendingReservationRef.current = { reservationReference: reservation.reservationReference };
|
|
3493
|
+
} else {
|
|
3494
|
+
pendingReservationRef.current = null;
|
|
3495
|
+
}
|
|
3496
|
+
|
|
3497
|
+
if (shouldCreateReservation && (!reservation || !reservation.reservationReference)) {
|
|
3498
|
+
throw new Error('Invalid reservation response: missing reservationReference');
|
|
3499
|
+
}
|
|
3500
|
+
|
|
3501
|
+
// Note: Do NOT call onSuccess here for paid bookings — we're about to show the Stripe
|
|
3502
|
+
// CheckoutModal. onSuccess (e.g. closing the parent dialog) should only run when we're
|
|
3503
|
+
// actually done (free booking redirect, admin confirm-without-payment). Calling it here
|
|
3504
|
+
// would close the dialog before the payment modal opens.
|
|
3505
|
+
|
|
3506
|
+
// Update stored booking data with reservation reference
|
|
3507
|
+
try {
|
|
3508
|
+
const storedBooking = sessionStorage.getItem('pendingBooking');
|
|
3509
|
+
if (storedBooking) {
|
|
3510
|
+
const booking = JSON.parse(storedBooking);
|
|
3511
|
+
if (reservation?.reservationReference) {
|
|
3512
|
+
booking.reservationReference = reservation.reservationReference;
|
|
3513
|
+
}
|
|
3514
|
+
booking.totalPrice = reservation?.totalAmount || totalPrice;
|
|
3515
|
+
booking.currency = reservation?.currency || currency || selectedAvailability.currency || 'CAD';
|
|
3516
|
+
sessionStorage.setItem('pendingBooking', JSON.stringify(booking));
|
|
3517
|
+
}
|
|
3518
|
+
} catch (e) {
|
|
3519
|
+
console.warn('Failed to update booking data', e);
|
|
3520
|
+
}
|
|
3521
|
+
|
|
3522
|
+
// Create Payment Intent for embedded checkout modal (order summary with strikethrough + green, Payment Element)
|
|
3523
|
+
const datePart = selectedAvailability.dateTime.split('T')[0];
|
|
3524
|
+
const timePart = selectedAvailability.dateTime.split('T')[1]?.substring(0, 5) || '00:00';
|
|
3525
|
+
|
|
3526
|
+
// Itinerary for storage: when pickup unknown, pickup step is always a range (e.g. "9 AM - 10:00 AM") so /manage and email show it; drop-off stays TBD
|
|
3527
|
+
const itineraryDisplay = computeItineraryDisplayForStorage() ?? computeItineraryDisplay();
|
|
3528
|
+
|
|
3529
|
+
// Build checkout breakdown from the exact same values we show in the UI and Stripe modal.
|
|
3530
|
+
// Backend will charge totalAmount and store this as the receipt so /manage matches.
|
|
3531
|
+
const taxForBreakdown = effectivePromoDiscountAmount > 0 ? effectiveTax : tax;
|
|
3532
|
+
const amountDueForCheckout = isChangeFlow
|
|
3533
|
+
? Math.max(0, changeFlowProposedTotal - (originalReceipt?.total ?? 0))
|
|
3534
|
+
: totalPrice;
|
|
3535
|
+
const lines = [
|
|
3536
|
+
...ticketLineItems.map((line) => ({
|
|
3537
|
+
label: line.category,
|
|
3538
|
+
amount: line.itemTotal,
|
|
3539
|
+
type: 'TICKET' as const,
|
|
3540
|
+
quantity: line.qty,
|
|
3541
|
+
})),
|
|
3542
|
+
...(returnPriceAdjustment !== 0
|
|
3543
|
+
? [
|
|
3544
|
+
{
|
|
3545
|
+
label: `${t('booking.returnOption') || 'Return option'} (${totalQuantity} ${totalQuantity === 1 ? (t('booking.person') || 'person') : (t('booking.people') || 'people')})`,
|
|
3546
|
+
amount: returnPriceAdjustment,
|
|
3547
|
+
type: 'RETURN_OPTION' as const,
|
|
3548
|
+
quantity: totalQuantity,
|
|
3549
|
+
},
|
|
3550
|
+
]
|
|
3551
|
+
: []),
|
|
3552
|
+
...(cancellationPolicyFee > 0
|
|
3553
|
+
? [
|
|
3554
|
+
{
|
|
3555
|
+
label: effectiveCancellationPolicyLabel,
|
|
3556
|
+
amount: cancellationPolicyFee,
|
|
3557
|
+
type: 'CANCELLATION_UPGRADE' as const,
|
|
3558
|
+
},
|
|
3559
|
+
]
|
|
3560
|
+
: []),
|
|
3561
|
+
...addOnSelections
|
|
3562
|
+
.map((sel) => {
|
|
3563
|
+
const addOn = addOns.find((a) => a.addOnId === sel.addOnId);
|
|
3564
|
+
if (!addOn) return null;
|
|
3565
|
+
const base = addOn.price ?? 0;
|
|
3566
|
+
const hasVariant = (addOn.variantType === 'single_choice' || addOn.variantType === 'multi_quantity') && sel.variantId;
|
|
3567
|
+
const adj = hasVariant ? (addOn.variants?.find((v) => v.id === sel.variantId)?.priceAdjustment ?? 0) : 0;
|
|
3568
|
+
const qty = sel.quantity ?? 1;
|
|
3569
|
+
const amt = (base + adj) * qty;
|
|
3570
|
+
const variantLabel = hasVariant ? addOn.variants?.find((v) => v.id === sel.variantId)?.label : null;
|
|
3571
|
+
return {
|
|
3572
|
+
label: variantLabel ? `${addOn.name} (${variantLabel})${qty > 1 ? ` × ${qty}` : ''}` : addOn.name,
|
|
3573
|
+
amount: amt,
|
|
3574
|
+
type: 'FEE' as const,
|
|
3575
|
+
quantity: qty,
|
|
3576
|
+
};
|
|
3577
|
+
})
|
|
3578
|
+
.filter((x): x is NonNullable<typeof x> => x != null),
|
|
3579
|
+
...feeLineItems.map((fee) => ({
|
|
3580
|
+
label: `${fee.name} (${totalQuantity} ${totalQuantity === 1 ? (t('booking.person') || 'person') : (t('booking.people') || 'people')})`,
|
|
3581
|
+
amount: fee.totalAmount,
|
|
3582
|
+
type: 'FEE' as const,
|
|
3583
|
+
quantity: totalQuantity,
|
|
3584
|
+
})),
|
|
3585
|
+
...(!isTaxIncludedInPrice && taxForBreakdown > 0
|
|
3586
|
+
? [
|
|
3587
|
+
{
|
|
3588
|
+
label: t('booking.tax') !== 'booking.tax' ? t('booking.tax') : 'Taxes and fees',
|
|
3589
|
+
amount: taxForBreakdown,
|
|
3590
|
+
type: 'TAX' as const,
|
|
3591
|
+
},
|
|
3592
|
+
]
|
|
3593
|
+
: []),
|
|
3594
|
+
...(effectivePromoDiscountAmount > 0
|
|
3595
|
+
? [
|
|
3596
|
+
{
|
|
3597
|
+
label: appliedPromoCode ? `Promo: ${appliedPromoCode}` : (originalReceipt?.promoLabel || (t('booking.discount') || 'Discount')),
|
|
3598
|
+
amount: -effectivePromoDiscountAmount,
|
|
3599
|
+
type: isGiftCard ? 'GIFT_CARD' : 'PROMO_CODE',
|
|
3600
|
+
},
|
|
3601
|
+
]
|
|
3602
|
+
: []),
|
|
3603
|
+
];
|
|
3604
|
+
const checkoutBreakdown = buildCheckoutBreakdown({
|
|
3605
|
+
lines,
|
|
3606
|
+
totalAmount: amountDueForCheckout,
|
|
3607
|
+
currency,
|
|
3608
|
+
roundingLabel: t('booking.rounding') || 'Rounding',
|
|
3609
|
+
});
|
|
3610
|
+
|
|
3611
|
+
if (!isChangeFlow && flowUi?.partnerDeferredInvoice) {
|
|
3612
|
+
if (!reservation?.reservationReference) {
|
|
3613
|
+
throw new Error('Missing reservation reference for partner booking confirmation');
|
|
3614
|
+
}
|
|
3615
|
+
const confirmedBooking = await confirmPartnerBookingWithoutPayment({
|
|
3616
|
+
reservationReference: reservation.reservationReference,
|
|
3617
|
+
productId: product.productId,
|
|
3618
|
+
optionId: availabilityProductOptionId,
|
|
3619
|
+
date: datePart,
|
|
3620
|
+
time: timePart,
|
|
3621
|
+
customerEmail: email || undefined,
|
|
3622
|
+
customerFirstName: firstName.trim() || undefined,
|
|
3623
|
+
customerLastName: lastName.trim() || undefined,
|
|
3624
|
+
currency: currency,
|
|
3625
|
+
travelerHotel: selectedPickupLocation?.name || undefined,
|
|
3626
|
+
pickupLocationId: pickupLocationId || undefined,
|
|
3627
|
+
itineraryDisplay: itineraryDisplay ?? undefined,
|
|
3628
|
+
termsAcceptedAt: termsAcceptedAt ?? undefined,
|
|
3629
|
+
skipConfirmationCommunications: isAdmin && skipConfirmationCommunications ? true : undefined,
|
|
3630
|
+
disableAutoCommunications: isAdmin && disableAutoCommunications ? true : undefined,
|
|
3631
|
+
checkoutBreakdown,
|
|
3632
|
+
depositAmount: 0,
|
|
3633
|
+
balanceAmount: amountDueForCheckout,
|
|
3634
|
+
totalAmount: amountDueForCheckout,
|
|
3635
|
+
...bookingSourceContext,
|
|
3636
|
+
});
|
|
3637
|
+
pendingReservationRef.current = null;
|
|
3638
|
+
const ref = formatBookingRefForDisplay(confirmedBooking.bookingReference);
|
|
3639
|
+
const ln = lastName.trim();
|
|
3640
|
+
onSuccess?.({
|
|
3641
|
+
reservationReference: reservation.reservationReference,
|
|
3642
|
+
bookingReference: confirmedBooking.bookingReference,
|
|
3643
|
+
});
|
|
3644
|
+
if (onShowManage) {
|
|
3645
|
+
onShowManage({ ref, lastName: ln });
|
|
3646
|
+
} else {
|
|
3647
|
+
const params = new URLSearchParams({ ref, lastName: ln, booking_complete: '1' });
|
|
3648
|
+
window.location.href = `/manage-booking?${params.toString()}`;
|
|
3649
|
+
}
|
|
3650
|
+
setLoading(false);
|
|
3651
|
+
return;
|
|
3652
|
+
}
|
|
3653
|
+
|
|
3654
|
+
const paymentIntent = isChangeFlow
|
|
3655
|
+
? await createChangeBookingPaymentIntent(
|
|
3656
|
+
(() => {
|
|
3657
|
+
const id = changeIntentIdForCheckout ?? latestChangeQuote?.changeIntentId;
|
|
3658
|
+
if (!id) {
|
|
3659
|
+
throw new Error('Missing change intent for payment.');
|
|
3660
|
+
}
|
|
3661
|
+
return id;
|
|
3662
|
+
})()
|
|
3663
|
+
)
|
|
3664
|
+
: await createPaymentIntent({
|
|
3665
|
+
productId: product.productId,
|
|
3666
|
+
optionId: availabilityProductOptionId,
|
|
3667
|
+
date: datePart,
|
|
3668
|
+
time: timePart,
|
|
3669
|
+
quantity: totalQuantity,
|
|
3670
|
+
customerEmail: email,
|
|
3671
|
+
customerFirstName: firstName.trim() || undefined,
|
|
3672
|
+
customerLastName: lastName.trim() || undefined,
|
|
3673
|
+
currency: currency,
|
|
3674
|
+
reservationReference: reservation?.reservationReference,
|
|
3675
|
+
travelerHotel: selectedPickupLocation?.name || undefined,
|
|
3676
|
+
pickupLocationId: pickupLocationId || undefined,
|
|
3677
|
+
itineraryDisplay: itineraryDisplay ?? undefined,
|
|
3678
|
+
returnAvailabilityId: selectedReturnOption?.returnAvailabilityId,
|
|
3679
|
+
promoCode: (lockedPromoCode || appliedPromoCode) || undefined,
|
|
3680
|
+
cancellationPolicyId: cancellationPolicyId || undefined,
|
|
3681
|
+
termsAcceptedAt: termsAcceptedAt ?? undefined,
|
|
3682
|
+
checkoutBreakdown,
|
|
3683
|
+
skipConfirmationCommunications: isAdmin && skipConfirmationCommunications ? true : undefined,
|
|
3684
|
+
disableAutoCommunications: isAdmin && disableAutoCommunications ? true : undefined,
|
|
3685
|
+
...bookingSourceContext,
|
|
3686
|
+
});
|
|
3687
|
+
|
|
3688
|
+
// Free booking (e.g. voucher covers full total): confirm without payment, then redirect to success
|
|
3689
|
+
if (!isChangeFlow && 'freeBooking' in paymentIntent && paymentIntent.freeBooking) {
|
|
3690
|
+
if (!reservation?.reservationReference) {
|
|
3691
|
+
throw new Error('Missing reservation reference for free booking confirmation');
|
|
3692
|
+
}
|
|
3693
|
+
|
|
3694
|
+
const freeBookingResult = await confirmFreeBooking({
|
|
3695
|
+
reservationReference: reservation?.reservationReference ?? changeBookingReferenceForPaidFlow ?? '',
|
|
3696
|
+
productId: product.productId,
|
|
3697
|
+
optionId: availabilityProductOptionId,
|
|
3698
|
+
date: datePart,
|
|
3699
|
+
time: timePart,
|
|
3700
|
+
customerEmail: email || undefined,
|
|
3701
|
+
customerFirstName: firstName.trim() || undefined,
|
|
3702
|
+
customerLastName: lastName.trim() || undefined,
|
|
3703
|
+
currency: currency,
|
|
3704
|
+
travelerHotel: selectedPickupLocation?.name || undefined,
|
|
3705
|
+
pickupLocationId: pickupLocationId || undefined,
|
|
3706
|
+
itineraryDisplay: itineraryDisplay ?? undefined,
|
|
3707
|
+
termsAcceptedAt: termsAcceptedAt ?? undefined,
|
|
3708
|
+
skipConfirmationCommunications: isAdmin && skipConfirmationCommunications ? true : undefined,
|
|
3709
|
+
disableAutoCommunications: isAdmin && disableAutoCommunications ? true : undefined,
|
|
3710
|
+
...bookingSourceContext,
|
|
3711
|
+
});
|
|
3712
|
+
pendingReservationRef.current = null;
|
|
3713
|
+
|
|
3714
|
+
// Show manage UI: in provider-dashboard use callback (e.g. dialog); otherwise redirect to /manage
|
|
3715
|
+
const ref = formatBookingRefForDisplay(freeBookingResult.bookingReference);
|
|
3716
|
+
const ln = lastName.trim();
|
|
3717
|
+
onSuccess?.({ reservationReference: reservation?.reservationReference ?? changeBookingReferenceForPaidFlow ?? '' });
|
|
3718
|
+
if (onShowManage) {
|
|
3719
|
+
onShowManage({ ref, lastName: ln });
|
|
3720
|
+
} else {
|
|
3721
|
+
const params = new URLSearchParams({ ref, lastName: ln, booking_complete: '1' });
|
|
3722
|
+
window.location.href = `/manage-booking?${params.toString()}`;
|
|
3723
|
+
}
|
|
3724
|
+
setLoading(false);
|
|
3725
|
+
return;
|
|
3726
|
+
}
|
|
3727
|
+
|
|
3728
|
+
// Admin: show choice to pay now or confirm without payment (customer owes full balance)
|
|
3729
|
+
if (isAdmin) {
|
|
3730
|
+
if (!reservation?.reservationReference) {
|
|
3731
|
+
throw new Error('Missing reservation reference for admin payment flow');
|
|
3732
|
+
}
|
|
3733
|
+
setError('');
|
|
3734
|
+
setAdminChoiceData({
|
|
3735
|
+
reservationReference: reservation.reservationReference,
|
|
3736
|
+
reservationExpiration: reservation.expiresAt,
|
|
3737
|
+
checkoutBreakdown,
|
|
3738
|
+
totalAmount: amountDueForCheckout,
|
|
3739
|
+
datePart,
|
|
3740
|
+
timePart,
|
|
3741
|
+
availabilityProductOptionId,
|
|
3742
|
+
itineraryDisplay: itineraryDisplay ?? undefined,
|
|
3743
|
+
clientSecret: paymentIntent.clientSecret ?? '',
|
|
3744
|
+
ticketLinesForModal: ticketLineItems.map((line) => {
|
|
3745
|
+
const rate = pricing.find((r) => r.category === line.category);
|
|
3746
|
+
const breakdown = getPriceBreakdown(
|
|
3747
|
+
line.category,
|
|
3748
|
+
rate?.priceCAD ?? 0,
|
|
3749
|
+
rate?.baseInDisplayCurrency,
|
|
3750
|
+
rate?.appliedAdjustments ?? []
|
|
3751
|
+
);
|
|
3752
|
+
return { line, breakdown };
|
|
3753
|
+
}),
|
|
3754
|
+
feeLineItems: feeLineItemsWithAddOns,
|
|
3755
|
+
returnPriceAdjustment,
|
|
3756
|
+
cancellationPolicyFee,
|
|
3757
|
+
cancellationPolicyLabel: effectiveCancellationPolicyLabel,
|
|
3758
|
+
subtotal: effectiveSubtotal,
|
|
3759
|
+
tax: effectivePromoDiscountAmount > 0 ? effectiveTax : tax,
|
|
3760
|
+
totalQuantity,
|
|
3761
|
+
isTaxIncludedInPrice,
|
|
3762
|
+
taxRate: pricingConfig?.taxRate ?? 0,
|
|
3763
|
+
promoDiscountAmount: effectivePromoDiscountAmount > 0 ? effectivePromoDiscountAmount : 0,
|
|
3764
|
+
discountLabel: appliedPromoCode ? `Promo: ${appliedPromoCode}` : (originalReceipt?.promoLabel || undefined),
|
|
3765
|
+
});
|
|
3766
|
+
setShowAdminPaymentChoice(true);
|
|
3767
|
+
setLoading(false);
|
|
3768
|
+
return;
|
|
3769
|
+
}
|
|
3770
|
+
|
|
3771
|
+
const ticketLinesForModal: CheckoutModalLineItem[] = ticketLineItems.map((line) => {
|
|
3772
|
+
const rate = pricing.find((r) => r.category === line.category);
|
|
3773
|
+
const breakdown = getPriceBreakdown(
|
|
3774
|
+
line.category,
|
|
3775
|
+
rate?.priceCAD ?? 0,
|
|
3776
|
+
rate?.baseInDisplayCurrency,
|
|
3777
|
+
rate?.appliedAdjustments ?? []
|
|
3778
|
+
);
|
|
3779
|
+
return { line, breakdown };
|
|
3780
|
+
});
|
|
3781
|
+
|
|
3782
|
+
setCheckoutClientSecret(paymentIntent.clientSecret ?? '');
|
|
3783
|
+
setCheckoutModalData({
|
|
3784
|
+
reservationReference: reservation?.reservationReference ?? changeBookingReferenceForPaidFlow ?? '',
|
|
3785
|
+
reservationExpiration: reservation?.expiresAt,
|
|
3786
|
+
customerLastName: lastName.trim(),
|
|
3787
|
+
bookingDate: datePart,
|
|
3788
|
+
// Paid change: always return to stable ref+lastName + explicit intent (not reservationRef).
|
|
3789
|
+
// /manage-booking runs bounded refresh only when `from=change_payment` (see manage-booking page).
|
|
3790
|
+
successUrlOverride:
|
|
3791
|
+
isChangeFlow && changeBookingReferenceForPaidFlow
|
|
3792
|
+
? (() => {
|
|
3793
|
+
const origin = typeof window !== 'undefined' ? window.location.origin : '';
|
|
3794
|
+
const ref = encodeURIComponent(
|
|
3795
|
+
formatBookingRefForDisplay(changeBookingReferenceForPaidFlow) || changeBookingReferenceForPaidFlow,
|
|
3796
|
+
);
|
|
3797
|
+
const ln = encodeURIComponent(lastName.trim());
|
|
3798
|
+
const fromQ = `${MANAGE_BOOKING_QUERY_FROM}=${encodeURIComponent(MANAGE_BOOKING_FROM_CHANGE_PAYMENT)}`;
|
|
3799
|
+
const intentQ = changeIntentIdForCheckout
|
|
3800
|
+
? `&changeIntentId=${encodeURIComponent(changeIntentIdForCheckout)}`
|
|
3801
|
+
: '';
|
|
3802
|
+
return `${origin}/manage-booking?ref=${ref}&lastName=${ln}&${fromQ}${intentQ}`;
|
|
3803
|
+
})()
|
|
3804
|
+
: undefined,
|
|
3805
|
+
ticketLines: ticketLinesForModal,
|
|
3806
|
+
feeLineItems: feeLineItemsWithAddOns,
|
|
3807
|
+
returnPriceAdjustment,
|
|
3808
|
+
cancellationPolicyFee,
|
|
3809
|
+
cancellationPolicyLabel: effectiveCancellationPolicyLabel,
|
|
3810
|
+
subtotal: effectiveSubtotal,
|
|
3811
|
+
tax: effectivePromoDiscountAmount > 0 ? effectiveTax : tax,
|
|
3812
|
+
total: amountDueForCheckout,
|
|
3813
|
+
totalQuantity,
|
|
3814
|
+
isTaxIncludedInPrice,
|
|
3815
|
+
taxRate: pricingConfig?.taxRate ?? 0,
|
|
3816
|
+
promoDiscountAmount: effectivePromoDiscountAmount > 0 ? effectivePromoDiscountAmount : 0,
|
|
3817
|
+
discountLabel: appliedPromoCode ? `Promo: ${appliedPromoCode}` : (originalReceipt?.promoLabel || undefined),
|
|
3818
|
+
changeTotals:
|
|
3819
|
+
isChangeFlow && originalReceipt
|
|
3820
|
+
? {
|
|
3821
|
+
previousTotal: originalReceipt.total,
|
|
3822
|
+
newTotal: totalPrice,
|
|
3823
|
+
differenceTotal: amountDueForCheckout,
|
|
3824
|
+
}
|
|
3825
|
+
: undefined,
|
|
3826
|
+
});
|
|
3827
|
+
setShowCheckoutModal(true);
|
|
3828
|
+
setLoading(false);
|
|
3829
|
+
} catch (err) {
|
|
3830
|
+
if (isInsufficientCapacityReserveError(err)) {
|
|
3831
|
+
try {
|
|
3832
|
+
const merged = await reloadAvailabilitiesAfterReserveConflict();
|
|
3833
|
+
const outbound = findMergedAvailabilityForSelection(merged, selectedAvailability);
|
|
3834
|
+
const outboundVacancies = outbound?.vacancies ?? null;
|
|
3835
|
+
const returnVacancies = findMergedReturnVacancies(outbound, selectedReturnOption);
|
|
3836
|
+
setError(
|
|
3837
|
+
describeStandardTourCapacityConflictMessage({
|
|
3838
|
+
partySize: totalQuantity,
|
|
3839
|
+
outboundVacancies,
|
|
3840
|
+
returnVacancies,
|
|
3841
|
+
hasReturnSelection: !!selectedReturnOption,
|
|
3842
|
+
})
|
|
3843
|
+
);
|
|
3844
|
+
reportReserveCapacityConflictClientContext({
|
|
3845
|
+
flow: 'standard_tour',
|
|
3846
|
+
productId: product.productId,
|
|
3847
|
+
selectedDate: selectedDate || null,
|
|
3848
|
+
outboundDateTime: selectedAvailability?.dateTime ?? null,
|
|
3849
|
+
outboundVacanciesAfterRefresh: outboundVacancies,
|
|
3850
|
+
returnVacanciesAfterRefresh: returnVacancies,
|
|
3851
|
+
partySizeOrPassengers: totalQuantity,
|
|
3852
|
+
hasReturnSelection: !!selectedReturnOption,
|
|
3853
|
+
returnAvailabilityId: selectedReturnOption?.returnAvailabilityId ?? null,
|
|
3854
|
+
reloadAvailabilitiesSucceeded: true,
|
|
3855
|
+
});
|
|
3856
|
+
} catch (reloadErr) {
|
|
3857
|
+
setError(
|
|
3858
|
+
describeStandardTourCapacityConflictMessage({
|
|
3859
|
+
partySize: totalQuantity,
|
|
3860
|
+
outboundVacancies: null,
|
|
3861
|
+
returnVacancies: null,
|
|
3862
|
+
hasReturnSelection: !!selectedReturnOption,
|
|
3863
|
+
})
|
|
3864
|
+
);
|
|
3865
|
+
reportReserveCapacityConflictClientContext({
|
|
3866
|
+
flow: 'standard_tour',
|
|
3867
|
+
productId: product.productId,
|
|
3868
|
+
selectedDate: selectedDate || null,
|
|
3869
|
+
outboundDateTime: selectedAvailability?.dateTime ?? null,
|
|
3870
|
+
outboundVacanciesAfterRefresh: null,
|
|
3871
|
+
returnVacanciesAfterRefresh: null,
|
|
3872
|
+
partySizeOrPassengers: totalQuantity,
|
|
3873
|
+
hasReturnSelection: !!selectedReturnOption,
|
|
3874
|
+
returnAvailabilityId: selectedReturnOption?.returnAvailabilityId ?? null,
|
|
3875
|
+
reloadAvailabilitiesSucceeded: false,
|
|
3876
|
+
reloadErrorMessage:
|
|
3877
|
+
reloadErr instanceof Error ? reloadErr.message : String(reloadErr),
|
|
3878
|
+
});
|
|
3879
|
+
}
|
|
3880
|
+
setLoading(false);
|
|
3881
|
+
return;
|
|
3882
|
+
}
|
|
3883
|
+
setError(err instanceof Error ? err.message : 'Something went wrong');
|
|
3884
|
+
setLoading(false);
|
|
3885
|
+
}
|
|
3886
|
+
};
|
|
3887
|
+
|
|
3888
|
+
const handleConfirmWithoutPayment = async () => {
|
|
3889
|
+
if (!adminChoiceData) return;
|
|
3890
|
+
setLoading(true);
|
|
3891
|
+
setError('');
|
|
3892
|
+
try {
|
|
3893
|
+
const bookingSourceContext = buildBookingSourceContext(bookingSourceAttribution, {
|
|
3894
|
+
clientChannelSource: inferClientBookingSourceFromProductIds(
|
|
3895
|
+
product.productId,
|
|
3896
|
+
adminChoiceData.availabilityProductOptionId,
|
|
3897
|
+
),
|
|
3898
|
+
forcePartnerPortalChannel: partnerPortalBooking,
|
|
3899
|
+
forceDashboardSource: bookingAppMode === 'provider-dashboard',
|
|
3900
|
+
});
|
|
3901
|
+
const result = await confirmBookingWithoutPayment({
|
|
3902
|
+
reservationReference: adminChoiceData.reservationReference,
|
|
3903
|
+
productId: product.productId,
|
|
3904
|
+
optionId: adminChoiceData.availabilityProductOptionId,
|
|
3905
|
+
date: adminChoiceData.datePart,
|
|
3906
|
+
time: adminChoiceData.timePart,
|
|
3907
|
+
customerEmail: email || undefined,
|
|
3908
|
+
customerFirstName: firstName.trim() || undefined,
|
|
3909
|
+
customerLastName: lastName.trim() || undefined,
|
|
3910
|
+
currency: currency,
|
|
3911
|
+
travelerHotel: product.pickupLocations?.find(loc => loc.id === pickupLocationId)?.name || undefined,
|
|
3912
|
+
pickupLocationId: pickupLocationId || undefined,
|
|
3913
|
+
itineraryDisplay: adminChoiceData.itineraryDisplay ?? undefined,
|
|
3914
|
+
termsAcceptedAt: termsAcceptedAt ?? undefined,
|
|
3915
|
+
skipConfirmationCommunications: skipConfirmationCommunications ? true : undefined,
|
|
3916
|
+
disableAutoCommunications: disableAutoCommunications ? true : undefined,
|
|
3917
|
+
checkoutBreakdown: adminChoiceData.checkoutBreakdown,
|
|
3918
|
+
depositAmount: 0,
|
|
3919
|
+
balanceAmount: adminChoiceData.totalAmount,
|
|
3920
|
+
totalAmount: adminChoiceData.totalAmount,
|
|
3921
|
+
...bookingSourceContext,
|
|
3922
|
+
});
|
|
3923
|
+
pendingReservationRef.current = null;
|
|
3924
|
+
const ref = formatBookingRefForDisplay(result.bookingReference);
|
|
3925
|
+
const ln = lastName.trim();
|
|
3926
|
+
setShowAdminPaymentChoice(false);
|
|
3927
|
+
setAdminChoiceData(null);
|
|
3928
|
+
onSuccess?.({ reservationReference: adminChoiceData.reservationReference });
|
|
3929
|
+
if (onShowManage) {
|
|
3930
|
+
onShowManage({ ref, lastName: ln });
|
|
3931
|
+
} else {
|
|
3932
|
+
const params = new URLSearchParams({ ref, lastName: ln, booking_complete: '1' });
|
|
3933
|
+
window.location.href = `/manage-booking?${params.toString()}`;
|
|
3934
|
+
}
|
|
3935
|
+
} catch (err) {
|
|
3936
|
+
setError(err instanceof Error ? err.message : 'Failed to confirm booking');
|
|
3937
|
+
} finally {
|
|
3938
|
+
setLoading(false);
|
|
3939
|
+
}
|
|
3940
|
+
};
|
|
3941
|
+
|
|
3942
|
+
const handlePayNow = () => {
|
|
3943
|
+
if (!adminChoiceData) return;
|
|
3944
|
+
setShowAdminPaymentChoice(false);
|
|
3945
|
+
setCheckoutClientSecret(adminChoiceData.clientSecret);
|
|
3946
|
+
setCheckoutModalData({
|
|
3947
|
+
reservationReference: adminChoiceData.reservationReference,
|
|
3948
|
+
reservationExpiration: adminChoiceData.reservationExpiration,
|
|
3949
|
+
customerLastName: lastName.trim(),
|
|
3950
|
+
ticketLines: adminChoiceData.ticketLinesForModal,
|
|
3951
|
+
feeLineItems: adminChoiceData.feeLineItems,
|
|
3952
|
+
returnPriceAdjustment: adminChoiceData.returnPriceAdjustment,
|
|
3953
|
+
cancellationPolicyFee: adminChoiceData.cancellationPolicyFee,
|
|
3954
|
+
cancellationPolicyLabel: adminChoiceData.cancellationPolicyLabel,
|
|
3955
|
+
subtotal: adminChoiceData.subtotal,
|
|
3956
|
+
tax: adminChoiceData.tax,
|
|
3957
|
+
total: adminChoiceData.totalAmount,
|
|
3958
|
+
totalQuantity: adminChoiceData.totalQuantity,
|
|
3959
|
+
isTaxIncludedInPrice: adminChoiceData.isTaxIncludedInPrice,
|
|
3960
|
+
taxRate: adminChoiceData.taxRate,
|
|
3961
|
+
promoDiscountAmount: adminChoiceData.promoDiscountAmount,
|
|
3962
|
+
discountLabel: adminChoiceData.discountLabel,
|
|
3963
|
+
});
|
|
3964
|
+
setShowCheckoutModal(true);
|
|
3965
|
+
setAdminChoiceData(null);
|
|
3966
|
+
};
|
|
3967
|
+
|
|
3968
|
+
if (activeOptions.length === 0) {
|
|
3969
|
+
return (
|
|
3970
|
+
<div className="flex items-center justify-center py-16">
|
|
3971
|
+
<div className="text-red-600">{t('booking.noActiveOption') || 'No active product options available'}</div>
|
|
3972
|
+
</div>
|
|
3973
|
+
);
|
|
3974
|
+
}
|
|
3975
|
+
|
|
3976
|
+
return (
|
|
3977
|
+
<div className="booking-flow-root space-y-8">
|
|
3978
|
+
{/* Admin: choose to pay now or confirm without payment (full balance owed) */}
|
|
3979
|
+
<AdminPaymentChoiceModal
|
|
3980
|
+
open={!!(showAdminPaymentChoice && adminChoiceData)}
|
|
3981
|
+
totalAmount={adminChoiceData?.totalAmount ?? 0}
|
|
3982
|
+
currency={currency}
|
|
3983
|
+
loading={loading}
|
|
3984
|
+
error={error}
|
|
3985
|
+
onPayNow={handlePayNow}
|
|
3986
|
+
onConfirmWithoutPayment={handleConfirmWithoutPayment}
|
|
3987
|
+
onCancel={() => { setShowAdminPaymentChoice(false); setAdminChoiceData(null); setError(''); }}
|
|
3988
|
+
/>
|
|
3989
|
+
{checkoutModalData && (
|
|
3990
|
+
<CheckoutModal
|
|
3991
|
+
open={showCheckoutModal}
|
|
3992
|
+
onClose={cancelPendingReservation}
|
|
3993
|
+
onPaymentSubmitStart={() => {
|
|
3994
|
+
paymentSubmitInFlightRef.current = true;
|
|
3995
|
+
}}
|
|
3996
|
+
onPaymentSubmitError={() => {
|
|
3997
|
+
paymentSubmitInFlightRef.current = false;
|
|
3998
|
+
}}
|
|
3999
|
+
clientSecret={checkoutClientSecret}
|
|
4000
|
+
reservationReference={checkoutModalData.reservationReference}
|
|
4001
|
+
reservationExpiration={checkoutModalData.reservationExpiration}
|
|
4002
|
+
customerLastName={checkoutModalData.customerLastName}
|
|
4003
|
+
successUrlOverride={
|
|
4004
|
+
checkoutModalData.successUrlOverride ??
|
|
4005
|
+
(getSuccessUrl
|
|
4006
|
+
? getSuccessUrl({
|
|
4007
|
+
reservationRef: checkoutModalData.reservationReference,
|
|
4008
|
+
lastName: checkoutModalData.customerLastName ?? '',
|
|
4009
|
+
focusDate: checkoutModalData.bookingDate,
|
|
4010
|
+
})
|
|
4011
|
+
: undefined)
|
|
4012
|
+
}
|
|
4013
|
+
ticketLines={checkoutModalData.ticketLines}
|
|
4014
|
+
feeLineItems={checkoutModalData.feeLineItems}
|
|
4015
|
+
returnPriceAdjustment={checkoutModalData.returnPriceAdjustment}
|
|
4016
|
+
cancellationPolicyFee={checkoutModalData.cancellationPolicyFee}
|
|
4017
|
+
cancellationPolicyLabel={checkoutModalData.cancellationPolicyLabel}
|
|
4018
|
+
subtotal={checkoutModalData.subtotal}
|
|
4019
|
+
tax={checkoutModalData.tax}
|
|
4020
|
+
total={checkoutModalData.total}
|
|
4021
|
+
promoDiscountAmount={checkoutModalData.promoDiscountAmount ?? 0}
|
|
4022
|
+
discountLabel={checkoutModalData.discountLabel}
|
|
4023
|
+
totalQuantity={checkoutModalData.totalQuantity}
|
|
4024
|
+
isTaxIncludedInPrice={checkoutModalData.isTaxIncludedInPrice}
|
|
4025
|
+
taxRate={checkoutModalData.taxRate}
|
|
4026
|
+
changeTotals={checkoutModalData.changeTotals}
|
|
4027
|
+
currency={currency}
|
|
4028
|
+
locale={locale}
|
|
4029
|
+
t={t}
|
|
4030
|
+
/>
|
|
4031
|
+
)}
|
|
4032
|
+
{/* Image/video collage - vertical video on left, image grid on right */}
|
|
4033
|
+
{productId && !isChangeFlow && flowUi?.showCollage !== false && (() => {
|
|
4034
|
+
const config = getProductByIdOrSlug(productId);
|
|
4035
|
+
const displayProducts = getProducts(defaultStrings);
|
|
4036
|
+
const displayProduct = Object.values(displayProducts).find((p) => p.id === productId);
|
|
4037
|
+
const collageImageIds = config?.display?.collageImageIds ?? config?.display?.imageIds ?? [];
|
|
4038
|
+
const hasVideo = !!displayProduct?.videoUrl;
|
|
4039
|
+
const hasImages = collageImageIds.length > 0;
|
|
4040
|
+
if (!hasVideo && !hasImages) return null;
|
|
4041
|
+
return (
|
|
4042
|
+
<div className="booking-collage-wrapper">
|
|
4043
|
+
<BookingFlowCollage
|
|
4044
|
+
video={displayProduct?.videoUrl}
|
|
4045
|
+
videoPosterImageId={config?.display?.imageIds?.[0]}
|
|
4046
|
+
imageIds={hasImages ? collageImageIds : [config?.display?.imageIds?.[0]].filter(Boolean) as string[]}
|
|
4047
|
+
altPrefix={product.name}
|
|
4048
|
+
/>
|
|
4049
|
+
</div>
|
|
4050
|
+
);
|
|
4051
|
+
})()}
|
|
4052
|
+
|
|
4053
|
+
{!isChangeFlow && flowUi?.showTourDescription !== false && (
|
|
4054
|
+
<TourDescription productSlug={productId} locale={locale} defaultExpanded={isPartialLaunch} />
|
|
4055
|
+
)}
|
|
4056
|
+
|
|
4057
|
+
{isPartialLaunch ? null : (
|
|
4058
|
+
<div className="booking-calendar-section">
|
|
4059
|
+
{loadingAvailabilities && availabilities.length === 0 ? (
|
|
4060
|
+
<div className="flex flex-col items-center justify-center py-12 gap-4">
|
|
4061
|
+
<div className="booking-loading-spinner" aria-hidden />
|
|
4062
|
+
<div className="text-stone-600">{t('booking.loadingTimes')}</div>
|
|
4063
|
+
</div>
|
|
4064
|
+
) : availabilities.length === 0 ? (
|
|
4065
|
+
<div className="text-center py-8 text-stone-500">
|
|
4066
|
+
{t('booking.noAvailability')}
|
|
4067
|
+
</div>
|
|
4068
|
+
) : (
|
|
4069
|
+
<>
|
|
4070
|
+
{/* Date Selection */}
|
|
4071
|
+
<div>
|
|
4072
|
+
<div className="relative">
|
|
4073
|
+
{loadingAvailabilities && (
|
|
4074
|
+
<div className="absolute inset-0 bg-white/80 backdrop-blur-sm flex items-center justify-center z-10 rounded-lg">
|
|
4075
|
+
<div className="flex flex-col items-center gap-3">
|
|
4076
|
+
<div className="booking-loading-spinner" aria-hidden />
|
|
4077
|
+
<div className="text-stone-600">{t('booking.loadingTimes')}</div>
|
|
4078
|
+
</div>
|
|
4079
|
+
</div>
|
|
4080
|
+
)}
|
|
4081
|
+
<Calendar
|
|
4082
|
+
availabilitiesByDate={availabilitiesByDate}
|
|
4083
|
+
selectedDate={selectedDate}
|
|
4084
|
+
syncVisibleWeekToSelectedDate={isChangeFlow}
|
|
4085
|
+
isLoading={loadingAvailabilities || isFetchingMoreAvailabilities}
|
|
4086
|
+
onDateSelect={(date) => {
|
|
4087
|
+
setSelectedDate(date);
|
|
4088
|
+
handleDateSelect(date);
|
|
4089
|
+
if (suppressCalendarDateScroll) return;
|
|
4090
|
+
// Scroll so calendar is almost at top and user sees the rest of the booking flow.
|
|
4091
|
+
// Dialog: scroll inside contentRef. Full-page: fall back to window scroll.
|
|
4092
|
+
setTimeout(() => {
|
|
4093
|
+
const container = contentRef?.current;
|
|
4094
|
+
if (!useWindowScroll && container && container.scrollHeight > container.clientHeight + 16) {
|
|
4095
|
+
container.scrollBy({ top: 400, behavior: 'smooth' });
|
|
4096
|
+
} else if (typeof window !== 'undefined') {
|
|
4097
|
+
window.scrollBy({ top: 400, behavior: 'smooth' });
|
|
4098
|
+
}
|
|
4099
|
+
}, 100);
|
|
4100
|
+
}}
|
|
4101
|
+
timezone={companyTimezone}
|
|
4102
|
+
earliestDate={earliestAvailabilityDate}
|
|
4103
|
+
onVisibleRangeChange={handleVisibleRangeChange}
|
|
4104
|
+
currency={currency}
|
|
4105
|
+
showCapacity={isAdmin}
|
|
4106
|
+
extraDiscountPercent={calendarDiscountPercent}
|
|
4107
|
+
capDiscountToSelectedDate={isChangeFlow && changeFlowTicketPriceFloorByCategory.size > 0}
|
|
4108
|
+
/>
|
|
4109
|
+
</div>
|
|
4110
|
+
</div>
|
|
4111
|
+
|
|
4112
|
+
{/* Form sections - equal spacing between each */}
|
|
4113
|
+
<div className="mt-6 space-y-6">
|
|
4114
|
+
{/* Your itinerary box - shown after date selection, before pickup/return/tickets/pickup location */}
|
|
4115
|
+
{selectedDate && !hideItineraryBox && (() => {
|
|
4116
|
+
const hasItineraryAny = activeOptions.some(o => o.itinerary?.length) && (product.destinations?.length ?? 0) > 0;
|
|
4117
|
+
if (!hasItineraryAny) return null;
|
|
4118
|
+
const formattedDate = selectedDate ? format(parseISO(selectedDate), 'MMM d') : '';
|
|
4119
|
+
if (!selectedAvailability) {
|
|
4120
|
+
return <ItineraryPlaceholder formattedDate={formattedDate} t={t} />;
|
|
4121
|
+
}
|
|
4122
|
+
const itineraryItems = computeItineraryDisplay();
|
|
4123
|
+
if (!itineraryItems || itineraryItems.length === 0) return null;
|
|
4124
|
+
const isBookingComplete = Boolean(selectedAvailability &&
|
|
4125
|
+
selectedReturnOption &&
|
|
4126
|
+
(pickupLocationId || pickupLocationSkipped || !product.pickupLocations || product.pickupLocations.length === 0) &&
|
|
4127
|
+
Object.values(quantities).some(qty => qty > 0) &&
|
|
4128
|
+
email.trim() !== '' &&
|
|
4129
|
+
firstName.trim() !== '' &&
|
|
4130
|
+
lastName.trim() !== '');
|
|
4131
|
+
return (
|
|
4132
|
+
<ItineraryBox
|
|
4133
|
+
selectedDate={selectedDate}
|
|
4134
|
+
formattedDate={formattedDate}
|
|
4135
|
+
itineraryItems={itineraryItems}
|
|
4136
|
+
isBookingComplete={isBookingComplete}
|
|
4137
|
+
isItinerarySticky={isItinerarySticky}
|
|
4138
|
+
stickyTopPx={flowUi?.itineraryStickyTopOffsetPx}
|
|
4139
|
+
isMobile={isMobile}
|
|
4140
|
+
useWindowScroll={useWindowScroll}
|
|
4141
|
+
showTooltip={showTooltip}
|
|
4142
|
+
selectedPickupLocation={selectedPickupLocation}
|
|
4143
|
+
pickupLocationSkipped={pickupLocationSkipped}
|
|
4144
|
+
pickupLocationsCount={product.pickupLocations?.length ?? 0}
|
|
4145
|
+
itineraryRef={itineraryRef}
|
|
4146
|
+
t={t}
|
|
4147
|
+
onTooltipToggle={() => setShowTooltip(!showTooltip)}
|
|
4148
|
+
onTooltipShow={setShowTooltip}
|
|
4149
|
+
/>
|
|
4150
|
+
);
|
|
4151
|
+
})()}
|
|
4152
|
+
|
|
4153
|
+
{/* Select pickup time */}
|
|
4154
|
+
{selectedDate && (
|
|
4155
|
+
<PickupTimeSelector
|
|
4156
|
+
pickupTimes={pickupTimes}
|
|
4157
|
+
selectedDateTime={selectedAvailability?.dateTime ?? null}
|
|
4158
|
+
selectedTicketCount={totalQuantity}
|
|
4159
|
+
optionsMap={optionsMap}
|
|
4160
|
+
hasAnyMostPopular={hasAnyMostPopular}
|
|
4161
|
+
isAdmin={isAdmin}
|
|
4162
|
+
pickupLocationSkipped={pickupLocationSkipped}
|
|
4163
|
+
t={t}
|
|
4164
|
+
onTimeSelect={handleTimeSelect}
|
|
4165
|
+
/>
|
|
4166
|
+
)}
|
|
4167
|
+
|
|
4168
|
+
{/* Select return time */}
|
|
4169
|
+
{selectedAvailability && selectedAvailability.returnOptions && selectedAvailability.returnOptions.length > 0 && (
|
|
4170
|
+
<ReturnTimeSelector
|
|
4171
|
+
returnOptions={returnOptionsWithFloor}
|
|
4172
|
+
selectedReturnOption={selectedReturnOptionWithFloor}
|
|
4173
|
+
selectedTicketCount={totalQuantity}
|
|
4174
|
+
companyTimezone={companyTimezone}
|
|
4175
|
+
currency={currency}
|
|
4176
|
+
locale={locale}
|
|
4177
|
+
isAdmin={isAdmin}
|
|
4178
|
+
t={t}
|
|
4179
|
+
onReturnSelect={(option) => {
|
|
4180
|
+
const raw = selectedAvailability.returnOptions?.find(
|
|
4181
|
+
(opt) => opt.returnAvailabilityId === option.returnAvailabilityId
|
|
4182
|
+
);
|
|
4183
|
+
setSelectedReturnOption(raw ?? option);
|
|
4184
|
+
}}
|
|
4185
|
+
getStaySummary={calculateStaySummary}
|
|
4186
|
+
/>
|
|
4187
|
+
)}
|
|
4188
|
+
|
|
4189
|
+
{/* Cancellation policy selection - all options from config, sorted by cheapest first. Also show when forced by promo. */}
|
|
4190
|
+
{!isChangeFlow && selectedAvailability && ((pricingConfig?.cancellationPolicies?.length ?? 0) > 0 || forcedCancellationPolicy) && (() => {
|
|
4191
|
+
const sortedPolicies = [...(pricingConfig?.cancellationPolicies ?? [])].sort((a, b) => {
|
|
4192
|
+
const feeA = a.feeByCurrency[currency] ?? 0;
|
|
4193
|
+
const feeB = b.feeByCurrency[currency] ?? 0;
|
|
4194
|
+
return feeA - feeB;
|
|
4195
|
+
});
|
|
4196
|
+
return (
|
|
4197
|
+
<div ref={cancellationPolicyRef}>
|
|
4198
|
+
<CancellationPolicySelector
|
|
4199
|
+
policies={sortedPolicies}
|
|
4200
|
+
selectedPolicyId={cancellationPolicyId}
|
|
4201
|
+
currency={currency}
|
|
4202
|
+
locale={locale}
|
|
4203
|
+
t={t}
|
|
4204
|
+
onPolicySelect={setCancellationPolicyId}
|
|
4205
|
+
forcedPolicy={forcedCancellationPolicy}
|
|
4206
|
+
/>
|
|
4207
|
+
</div>
|
|
4208
|
+
);
|
|
4209
|
+
})()}
|
|
4210
|
+
|
|
4211
|
+
{/* Ticket Selection */}
|
|
4212
|
+
{selectedAvailability && (
|
|
4213
|
+
<TicketSelector
|
|
4214
|
+
pricing={pricing}
|
|
4215
|
+
quantities={quantities}
|
|
4216
|
+
totalQuantity={totalQuantity}
|
|
4217
|
+
selectedVacancies={effectivePartySizeCap}
|
|
4218
|
+
companyTimezone={companyTimezone}
|
|
4219
|
+
pickupDateTime={selectedAvailability.dateTime}
|
|
4220
|
+
pickupVacancies={selectedAvailability.vacancies ?? 0}
|
|
4221
|
+
returnDateTime={selectedReturnOption?.dateTime ?? null}
|
|
4222
|
+
returnVacancies={
|
|
4223
|
+
selectedReturnOption != null ? (selectedReturnOption.vacancies ?? 0) : null
|
|
4224
|
+
}
|
|
4225
|
+
resourceCount={selectedReturnOption ? null : (selectedAvailability.resourceCount ?? null)}
|
|
4226
|
+
currency={currency}
|
|
4227
|
+
locale={locale}
|
|
4228
|
+
isAdmin={isAdmin}
|
|
4229
|
+
isSimplifiedPricingView={isSimplifiedPricingView}
|
|
4230
|
+
t={t}
|
|
4231
|
+
onQuantityChange={handleQuantityChange}
|
|
4232
|
+
minimumQuantities={changeBookingMinimumQuantities}
|
|
4233
|
+
ticketUnitFloorByCategory={isChangeFlow ? changeFlowTicketPriceFloorByCategory : undefined}
|
|
4234
|
+
/>
|
|
4235
|
+
)}
|
|
4236
|
+
|
|
4237
|
+
{/* Add-ons — optional extras for the selected product option */}
|
|
4238
|
+
{selectedAvailability && totalQuantity > 0 && addOns.length > 0 && (
|
|
4239
|
+
<AddOnsSection
|
|
4240
|
+
addOns={addOns}
|
|
4241
|
+
addOnSelections={addOnSelections}
|
|
4242
|
+
currency={currency}
|
|
4243
|
+
locale={locale}
|
|
4244
|
+
onSelectionsChange={updateAddOnSelections}
|
|
4245
|
+
minimumTotalByAddOnId={isChangeFlow ? initialAddOnMinTotalByAddOnId : undefined}
|
|
4246
|
+
/>
|
|
4247
|
+
)}
|
|
4248
|
+
|
|
4249
|
+
{/* Total and Checkout — shared PriceSummary component */}
|
|
4250
|
+
{selectedAvailability && (
|
|
4251
|
+
<CheckoutForm
|
|
4252
|
+
priceSummaryLines={checkoutPriceSummaryLines}
|
|
4253
|
+
totalPrice={changeFlowAmountDue}
|
|
4254
|
+
totalSummaryLabel={
|
|
4255
|
+
isChangeFlow
|
|
4256
|
+
? (t('booking.totalOwedForBookingChange') &&
|
|
4257
|
+
t('booking.totalOwedForBookingChange') !== 'booking.totalOwedForBookingChange'
|
|
4258
|
+
? t('booking.totalOwedForBookingChange')
|
|
4259
|
+
: 'Total owed for booking difference')
|
|
4260
|
+
: undefined
|
|
4261
|
+
}
|
|
4262
|
+
subtotal={subtotal !== totalFromSummary || effectivePromoDiscountAmount > 0 || addOnTotal > 0 ? effectiveSubtotal : undefined}
|
|
4263
|
+
taxAmount={!isTaxIncludedInPrice && (effectivePromoDiscountAmount > 0 ? effectiveTax : tax) > 0 ? (effectivePromoDiscountAmount > 0 ? effectiveTax : tax) : 0}
|
|
4264
|
+
taxRate={pricingConfig?.taxRate}
|
|
4265
|
+
currency={currency}
|
|
4266
|
+
locale={locale}
|
|
4267
|
+
t={t}
|
|
4268
|
+
extraBetweenTaxAndTotal={
|
|
4269
|
+
<>
|
|
4270
|
+
{isChangeFlow && originalReceipt && lockedPromoCode ? (
|
|
4271
|
+
<PromoCodeInput
|
|
4272
|
+
promoCodeInput={promoCodeInput}
|
|
4273
|
+
appliedPromoCode={appliedPromoCode}
|
|
4274
|
+
promoCodeError={promoCodeError}
|
|
4275
|
+
promoCodeValidating={promoCodeValidating}
|
|
4276
|
+
promoDiscountAmount={effectivePromoDiscountAmount}
|
|
4277
|
+
currency={currency}
|
|
4278
|
+
locale={locale}
|
|
4279
|
+
t={t}
|
|
4280
|
+
onInputChange={() => {}}
|
|
4281
|
+
onApply={() => {}}
|
|
4282
|
+
onRemove={() => {}}
|
|
4283
|
+
locked
|
|
4284
|
+
/>
|
|
4285
|
+
) : (
|
|
4286
|
+
!isChangeFlow ? (
|
|
4287
|
+
<PromoCodeInput
|
|
4288
|
+
promoCodeInput={promoCodeInput}
|
|
4289
|
+
appliedPromoCode={appliedPromoCode}
|
|
4290
|
+
promoCodeError={promoCodeError}
|
|
4291
|
+
promoCodeValidating={promoCodeValidating}
|
|
4292
|
+
promoDiscountAmount={promoDiscountAmount}
|
|
4293
|
+
currency={currency}
|
|
4294
|
+
locale={locale}
|
|
4295
|
+
t={t}
|
|
4296
|
+
onInputChange={(v) => {
|
|
4297
|
+
setPromoCodeInput(v);
|
|
4298
|
+
setPromoCodeError('');
|
|
4299
|
+
}}
|
|
4300
|
+
onApply={handleApplyPromo}
|
|
4301
|
+
onRemove={() => {
|
|
4302
|
+
promoAppliedSelectionKeyRef.current = null;
|
|
4303
|
+
setAppliedPromoCode(null);
|
|
4304
|
+
setPromoCodeInput('');
|
|
4305
|
+
setPromoCodeError('');
|
|
4306
|
+
setForcedCancellationPolicy(null);
|
|
4307
|
+
setCancellationPolicyId(null); // Reset so auto-select effect picks cheapest
|
|
4308
|
+
fetchedRangesRef.current = [];
|
|
4309
|
+
}}
|
|
4310
|
+
/>
|
|
4311
|
+
) : null
|
|
4312
|
+
)}
|
|
4313
|
+
</>
|
|
4314
|
+
}
|
|
4315
|
+
firstName={firstName}
|
|
4316
|
+
lastName={lastName}
|
|
4317
|
+
email={email}
|
|
4318
|
+
onFirstNameChange={(v) => { setFirstName(v); setError(''); }}
|
|
4319
|
+
onLastNameChange={(v) => { setLastName(v); setError(''); }}
|
|
4320
|
+
onEmailChange={(v) => { setEmail(v); setError(''); }}
|
|
4321
|
+
readOnlyContactFields={isChangeFlow}
|
|
4322
|
+
pickupLocations={
|
|
4323
|
+
selectedDate && product.pickupLocations && product.pickupLocations.length > 0
|
|
4324
|
+
? product.pickupLocations
|
|
4325
|
+
: undefined
|
|
4326
|
+
}
|
|
4327
|
+
destinations={product.destinations}
|
|
4328
|
+
pickupLocationId={pickupLocationId}
|
|
4329
|
+
pickupLocationSkipped={pickupLocationSkipped}
|
|
4330
|
+
selectedPickupLocation={selectedPickupLocation}
|
|
4331
|
+
highlightedPickupLocationIds={highlightedPickupLocationIds}
|
|
4332
|
+
onLocationSelect={(locationId) => {
|
|
4333
|
+
setPickupLocationId(locationId);
|
|
4334
|
+
setError('');
|
|
4335
|
+
if (locationId === null && pickupLocationSkipped) {
|
|
4336
|
+
setPickupLocationSkipped(false);
|
|
4337
|
+
} else if (locationId !== null) {
|
|
4338
|
+
setPickupLocationSkipped(false);
|
|
4339
|
+
}
|
|
4340
|
+
}}
|
|
4341
|
+
onSkip={() => {
|
|
4342
|
+
setPickupLocationSkipped(true);
|
|
4343
|
+
setPickupLocationId(null);
|
|
4344
|
+
setError('');
|
|
4345
|
+
}}
|
|
4346
|
+
onChangePickup={() => {
|
|
4347
|
+
setPickupLocationId(null);
|
|
4348
|
+
setPickupLocationSkipped(false);
|
|
4349
|
+
}}
|
|
4350
|
+
termsAccepted={termsAccepted}
|
|
4351
|
+
onTermsChange={(checked) => {
|
|
4352
|
+
setTermsAccepted(checked);
|
|
4353
|
+
setTermsAcceptedAt(checked ? new Date().toISOString() : null);
|
|
4354
|
+
}}
|
|
4355
|
+
isAdmin={isAdmin}
|
|
4356
|
+
skipConfirmationCommunications={skipConfirmationCommunications}
|
|
4357
|
+
disableAutoCommunications={disableAutoCommunications}
|
|
4358
|
+
onSkipConfirmationChange={setSkipConfirmationCommunications}
|
|
4359
|
+
onDisableCommunicationsChange={setDisableAutoCommunications}
|
|
4360
|
+
error={checkoutFormError}
|
|
4361
|
+
loading={loading}
|
|
4362
|
+
totalQuantity={totalQuantity}
|
|
4363
|
+
onCheckout={handleCheckout}
|
|
4364
|
+
submitLabel={changeCheckoutButtonLabel ?? deferredInvoiceSubmitLabel}
|
|
4365
|
+
hideSubmitButton={
|
|
4366
|
+
showCheckoutModal ||
|
|
4367
|
+
showAdminPaymentChoice ||
|
|
4368
|
+
(isChangeFlow && (!hasChangeSelection || isChangeQuoteBlocked))
|
|
4369
|
+
}
|
|
4370
|
+
submitDisabled={changeFlowSubmitDisabled}
|
|
4371
|
+
attributionSummary={flowUi?.partnerAttributionSummary}
|
|
4372
|
+
attributionConfirmLabel={flowUi?.partnerAttributionConfirmLabel}
|
|
4373
|
+
attributionConfirmed={partnerAttributionConfirmed}
|
|
4374
|
+
onAttributionConfirmedChange={setPartnerAttributionConfirmed}
|
|
4375
|
+
/>
|
|
4376
|
+
)}
|
|
4377
|
+
</div>
|
|
4378
|
+
</>
|
|
4379
|
+
)}
|
|
4380
|
+
</div>
|
|
4381
|
+
)}
|
|
4382
|
+
</div>
|
|
4383
|
+
);
|
|
4384
|
+
}
|
|
4385
|
+
|