/* eslint-disable react-hooks/rules-of-hooks */ /* eslint-disable no-nested-ternary */ import { isEmpty } from "lodash-es"; import { useRouter } from "next/navigation"; import { useCallback, useEffect, useRef, useState } from "react"; import { useBoolean } from "usehooks-ts"; import Form from "@/components/form/form"; import Container from "@/components/shared/container"; import { Button } from "@/components/ui/button/button"; import { Skeleton } from "@/components/ui/skeleton/skeleton"; import { GROUP_KEY_PREFIX } from "@/features/core/summary/components/core-summary"; import CoreSummaryContent from "@/features/core/summary/components/core-summary-content"; import CoreSummaryCouponCode from "@/features/core/summary/components/core-summary-coupon-code/core-summary-coupon-code"; import type { CoreSummaryHandles } from "@/features/core/summary/components/core-summary-form"; import CoreSummaryForm, { CoreSummaryPassengerGroup, } from "@/features/core/summary/components/core-summary-form"; import CoreSummaryHeader from "@/features/core/summary/components/core-summary-header"; import CoreSummaryInvoiceNoteFormItem from "@/features/core/summary/components/core-summary-invoice-note-form-item"; import CoreSummaryMainColumn from "@/features/core/summary/components/core-summary-main-column"; import CoreSummaryNoteFormItem from "@/features/core/summary/components/core-summary-note-form-input"; import CoreSummaryPolicyFormItem from "@/features/core/summary/components/core-summary-policy-form-item"; import CoreSummaryRequestNoteFormItem from "@/features/core/summary/components/core-summary-request-note-form-item"; import CoreSummarySideColumn from "@/features/core/summary/components/core-summary-side-column"; import { CoreSummaryCtxProvider, useCoreSummaryCtx, } from "@/features/core/summary/context/core-summary-context"; import { getBillingRequestDataFromBillingForm, getBillingRequestDataFromPassengerInfo, } from "@/features/core/summary/libs/billing-helper"; import { getGroupPassengers } from "@/features/core/summary/libs/group-passenger-helper"; import type { IBillingInfoForm } from "@/features/customer/billing-info/billing-info-form"; import BillingInfoForm from "@/features/customer/billing-info/billing-info-form"; import { useFlighSummaryCtx } from "@/features/flight/components/flight-summary/context/flight-summary-context"; import { usePayment } from "@/features/modules/payment/hooks/use-payment"; import type { HotelPaymentListHandles } from "@/features/modules/payment/payment-list"; import PaymentList from "@/features/modules/payment/payment-list"; import { useApp } from "@/hooks/useApp"; import { useBreakpoints } from "@/hooks/useBreakpoints"; import { useLabels } from "@/hooks/useLabels"; import { useLocale } from "@/hooks/useLocale"; import { sortCombinationGroups, sortFlightSegments, } from "@/libs/helpers/flight-helper"; import { useLocalStateCache } from "@/libs/helpers/local-state-cache-helper"; import { localeStorageHelper } from "@/libs/helpers/locale-storage-helper"; import { CorePassengerHelper } from "@/libs/helpers/passenger-helper"; import { PriceManager } from "@/libs/price-manager/price-manager"; import { storageManager } from "@/libs/storage-manager"; import type { IFlightAddToCartResponse } from "@/services/eva-display/flight/flight-add-to-cart/flight-add-to-cart.service"; import { useFlightCreatePostWithResultMutation } from "@/services/eva-display/flight/flight-create-post/flight-create-post.service"; import type { IFlightDetailResponse } from "@/services/eva-display/flight/flight-detail/flight-detail.service"; import { useFlightValidateMutation } from "@/services/eva-display/flight/flight-validate/flight-validate.service"; import { useMasterpassStore } from "@/store/masterpass-store/use-masterpass-store"; import { useNotifyStore } from "@/store/notify-store/use-notify-store"; import FlightSummaryReservationInfo from "./flight-summary-reservation-info"; interface FlightSummaryViewProps { addToCartData: IFlightAddToCartResponse; detailData: IFlightDetailResponse; } const FlightSummaryView = (props: FlightSummaryViewProps) => { const { setNotify } = useNotifyStore(); const labels = useLabels(); const router = useRouter(); const { isB2E, isB2C } = useApp(); const { paymentState, setBookingData, setPaymentState } = usePayment(); const { setMasterpassData } = useMasterpassStore(); const [milesState, setMilesState] = useState({}); const { actions } = useCoreSummaryCtx(); const diffrentBillingInfoBoolean = useBoolean(); const { tpPassengers, employees, passengers, searchId, travelReasonId, pricingCombinationKeys, combinationGroupKeys, branchOfficeId, } = useFlighSummaryCtx(); const validateMutation = useFlightValidateMutation(); const createPostMutation = useFlightCreatePostWithResultMutation(); const coreSummaryFormRef = useRef(null); const paymentRef = useRef(null); const paymentFormRef = useRef(null); const { isDesktop } = useBreakpoints(); const { t } = useLocale(); function getPassengersForCore() { return getGroupPassengers( { passengerKeys: passengers, employees, passengerGroups: [ { employee: { count: tpPassengers?.employee?.count ?? 0, }, child: { count: tpPassengers?.child?.count ?? 0, }, guest: { count: tpPassengers?.guest?.count ?? 0, }, }, ], }, labels, ); } const passengersGroups = getPassengersForCore(); const { getLocalStateCacheValues } = useLocalStateCache( "flightFormFields", passengersGroups, ); function getDefaultValues() { const defaultValues: any = getLocalStateCacheValues(); if (!isEmpty(defaultValues)) { return defaultValues; } passengersGroups[0]?.forEach((passenger: any) => { if (passenger.type === "employee") { defaultValues[`${GROUP_KEY_PREFIX}_0-${passenger.key}-employee`] = passenger.defaultValue; } }); return defaultValues; } const defaultValues = getDefaultValues(); const combinationGroups = sortCombinationGroups( props.detailData?.pricingCombinations[0]?.combinationGroups ?? [], ); if (!combinationGroups) { return (
); } const flightSegments = sortFlightSegments( combinationGroups[0]?.flightSegments!, ); const milesAndSmilesAirlineCodes = ["TK", "AJ0"]; const isShowMilesCode = flightSegments?.some((flightSegment) => { return ( milesAndSmilesAirlineCodes.includes( flightSegment?.marketingAirlineCode, ) || milesAndSmilesAirlineCodes.includes(flightSegment?.operatingAirlineCode) ); }) || false; function formatPhoneNumber(phoneNumber: string | any) { return typeof phoneNumber === "object" && phoneNumber.dialCode ? `+${phoneNumber.dialCode} ${phoneNumber.phoneNumber}` : phoneNumber; } function getPhoneNumberObjFromPhoneNumber(phoneNumber: string | null) { if (!phoneNumber) { return null; } return { CountryCode: formatPhoneNumber(phoneNumber)?.split?.(" ")?.[0] ?? "90", AreaCode: formatPhoneNumber(phoneNumber)?.split(" ")?.[1]?.slice(0, 3) ?? "90", Number: formatPhoneNumber(phoneNumber)?.split(" ")?.[1]?.slice(3), Type: 3, }; } function isAbroad() { const storagedValues = localeStorageHelper.get("flight-cart"); return Boolean(storagedValues?.isAbroad); } const isRoundTrip = combinationGroups.length > 1 || combinationGroupKeys?.length > 1; function renderCouponCode() { if (isB2C && Boolean(paymentState?.payload?.transactionId)) { return ( ); } return null; } function handleSubmitButtonClick() { if (paymentState?.payload.paymentStatus === "payment") { paymentFormRef.current?.submit(); paymentRef.current?.onlyValidate(); } else { coreSummaryFormRef.current?.submit(); } } function handleClickBackButton() { if (paymentState?.payload.paymentStatus === "payment") { setPaymentState("idle"); storageManager.delete("core-payment"); } } useEffect(() => { window.scrollTo(0, 0); }, [paymentState?.payload?.paymentStatus]); const onBackButtonEvent = useCallback( (e: PopStateEvent) => { const getCorePayment = storageManager.get("core-payment"); if (getCorePayment?.payload?.paymentStatus === "payment") { e.preventDefault(); storageManager.delete("core-payment"); actions.clearCreditCardCampaigns(); setPaymentState("idle"); } else { // eslint-disable-next-line no-restricted-globals history.back(); } }, [paymentState?.payload?.paymentStatus], ); useEffect(() => { window.history.pushState(null, "", window.location.pathname); window.addEventListener("popstate", onBackButtonEvent); return () => { window.removeEventListener("popstate", onBackButtonEvent); }; }, [paymentState?.payload?.paymentStatus]); return ( {({ discounts }) => (
{isB2E ? props.addToCartData.reservationSummaryCaption : paymentState?.payload.paymentStatus === "payment" ? t("Payment Options") : "Yolcu Bilgileri"} {paymentState?.payload?.paymentStatus === "payment" && ( {!isDesktop && renderCouponCode()}
{ paymentRef.current?.submit(); }} shouldAutoScroll > x.type === "CouponCode"), )} handles={{ onBookSuccess(payload) { sessionStorage.setItem( payload.bookingCode, JSON.stringify(props.detailData), ); router.push( `/booking-success?bookingId=${payload.bookingCode}`, ); }, onBookFail(payload) { setNotify({ title: "Bir Hata Oluştu!", message: payload.message, variant: "error", }); }, }} />
)} {paymentState?.payload?.paymentStatus !== "payment" && ( ref={coreSummaryFormRef} wrapperClassName="space-y-4" formItemPrefixes={["billingInfo"]} onSubmit={async (values) => { const passengersInformations = values.passengers .map((x) => ({ ...x, milesCode: milesState[`${x.employeeId}`], })) .map((psg) => { const psgConverted = CorePassengerHelper.corePassengerToPassengerInformation( psg, ); return { ...psgConverted, Gender: psgConverted.Gender === 2 ? 1 : psgConverted.Gender, PhoneNumbers: [ getPhoneNumberObjFromPhoneNumber( psg.phoneNumber ?? null, ), ].filter((x) => Boolean(x)), }; }); // eslint-disable-next-line no-underscore-dangle, @typescript-eslint/naming-convention const _passengersInformations = values.passengers.map( (psg) => CorePassengerHelper.corePassengerToPassengerInformation( psg, ), ); const passengerWithBillingInfo = _passengersInformations.find( (x) => x.Address.Street !== "", ); const billingInfo = diffrentBillingInfoBoolean.value ? getBillingRequestDataFromBillingForm( values.values?.billingInfo!, passengerWithBillingInfo!, ) : getBillingRequestDataFromPassengerInfo( passengerWithBillingInfo!, ); if (isB2C) { const resp = await validateMutation.mutateAsync({ FlightValidateBookingRequest: { BillingRequest: billingInfo, BookingPassengers: passengersInformations.map( (x) => ({ ...x, Gender: x.Gender === null ? 1 : x.Gender, }), ) as any, AddOnsKeyList: [], CancelWarrantySearchId: "", SearchId: searchId, CartId: props.addToCartData.cartId, KvkkApproval: true, ReservationNotes: values.specialNote || "", }, }); if ( !resp.data?.result?.serviceResponse?.success || !resp.data?.result?.serviceResponse?.result ?.transactionKey ) { if (resp.data?.result?.serviceResponse?.errors) { setNotify({ title: "Bir Hata Oluştu!", message: resp.data.result.serviceResponse.errors?.[0] .message, variant: "error", }); return; } setNotify({ title: "Bir Hata Oluştu!", message: "Bir hata oluştu", variant: "error", }); return; } setBookingData({ cartId: props.addToCartData.cartId, searchId: searchId!, transactionId: resp.data.result.serviceResponse.result .transactionKey, preSaleAgreementText: resp.data.result.serviceResponse.result .preSaleAgreementText, saleAgreementText: resp.data.result.serviceResponse.result .saleAgreementText, }); if ( resp.data.result.serviceResponse.result .masterPassUserData ) { setMasterpassData({ moduleName: "Hotel", payload: { masterpassLoginState: false, masterpassOtherUser: false, cardList: [], masterpassUserData: resp.data.result.serviceResponse.result .masterPassUserData, customerEmail: values.passengers[0]!.email, masterPassengerName: values.passengers[0]!.name! + values.passengers[0]!.surname!, }, }); } } else { const passengersWithoutGenderInfo = CorePassengerHelper.getPassengersWithoutGenderInfo( values.passengers, ); if (passengersWithoutGenderInfo.length > 0) { setNotify({ variant: "error", title: "Bir Hata Oluştu!", message: `${"Seçilen kullanıcının cinsiyet bilgisini doldurunuz."} \n ${passengersWithoutGenderInfo.reduce((acc, curr) => `${acc} ${curr.name} ${curr.surname},`, "").slice(0, -1)}`, }); return; } const resp = await createPostMutation.mutateAsync({ CorpCreateFlightRequest: { SearchId: searchId, CartId: props.addToCartData.cartId, RequestId: null, TravelReasonId: !travelReasonId ? 1 : +travelReasonId, BranchId: !branchOfficeId ? undefined : +branchOfficeId, LinkId: "", SearchProductKey: pricingCombinationKeys[0]!, PassengerInformations: passengersInformations as any, IsPreBook: true, KvkkStatus: false, PriceCombinationKeys: [...pricingCombinationKeys], ProjectCode: values.invoiceNote, ReservationNote: values.requestNote, RequesterUserIds: values.passengers .filter((x) => x.type === "employee") .map((x) => x.employeeGUID ?? ""), }, }); if ( resp.result?.requestId && resp.result?.requestId !== 0 ) { router.push( `/booking-request-success?bookingId=${resp.result.requestId}`, ); } else { setNotify({ title: "Hata", message: resp.errors?.[0]?.message ?? "Bir hata oluştu", variant: "error", }); } } }} defaultValues={defaultValues} > { setMilesState((prev: any) => ({ ...prev, [userId]: milesCode, })); }} hasPassportInfos={isAbroad()} hasReservationNote={!isB2E} /> {isB2E && ( <> )} {isB2C && ( <> { diffrentBillingInfoBoolean.setValue(value); }} open={defaultValues?.billingInfoCompOpen} /> )} )} acc + +item.price, 0), })} button={ } > {isDesktop && renderCouponCode()}
)}
); }; export default FlightSummaryView;