UNPKG

@godaddy/react

Version:

The `createCheckoutSession` function creates a new checkout session with GoDaddy's commerce API.

987 lines (985 loc) 32.2 kB
import { $ as useDraftOrder, B as eventIds, C as useConvertMajorToMinorUnits, K as TrackingEventType, M as Skeleton, Q as useIsPaymentDisabled, W as useUpdateTaxes, _ as useConfirmCheckout, c as filterAndSortShippingMethods, d as mapOrderToFormValues, et as useDraftOrderTotals, g as PaymentProvider, o as useCheckoutContext, q as track, rt as useGoDaddyContext, u as useBuildPaymentRequest, w as useFormatCurrency, y as useLoadPoyntCollect } from "./checkout-CCruxHvk.js"; import { k as GraphQLErrorWithCodes } from "./utils-DWBfAHfx.js"; import { n as useGetShippingMethodByAddress, r as useGetPriceAdjustments, t as useGetTaxes } from "./use-get-taxes-mFqCMRYr.js"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useFormContext } from "react-hook-form"; import { Fragment, jsx, jsxs } from "react/jsx-runtime"; //#region src/components/checkout/payment/checkout-buttons/express/godaddy.tsx function ExpressCheckoutButton() { const formatCurrency = useFormatCurrency(); const convertMajorToMinorUnits = useConvertMajorToMinorUnits(); const { session, setCheckoutErrors, isConfirmingCheckout } = useCheckoutContext(); const isPaymentDisabled = useIsPaymentDisabled(); const { isPoyntLoaded } = useLoadPoyntCollect(); const isDisabled = isConfirmingCheckout || isPaymentDisabled; const { godaddyPaymentsConfig } = useCheckoutContext(); const { t } = useGoDaddyContext(); const [isCollectLoading, setIsCollectLoading] = useState(true); const [walletSource, setWalletSource] = useState(void 0); const [error, setError] = useState(""); const [calculatedTaxes, setCalculatedTaxes] = useState(null); const [shippingAddress, setShippingAddress] = useState(null); const [shippingMethods, setShippingMethods] = useState(null); const [shippingMethod, setShippingMethod] = useState(null); const { poyntExpressRequest } = useBuildPaymentRequest(); const { data: totals } = useDraftOrderTotals(); const { data: draftOrder } = useDraftOrder(); const currencyCode = totals?.total?.currencyCode || "USD"; const [godaddyTotals, setGoDaddyTotals] = useState({ taxes: { currencyCode, value: 0 }, shipping: { currencyCode, value: 0 } }); const form = useFormContext(); const getShippingMethodsByAddress = useGetShippingMethodByAddress(); const getTaxes = useGetTaxes(); const getPriceAdjustments = useGetPriceAdjustments(); const updateTaxes = useUpdateTaxes(); const countryCode = session?.shipping?.originAddress?.countryCode || "US"; const confirmCheckout = useConfirmCheckout(); const collect = useRef(null); const hasMounted = useRef(false); const handleExpressPayClickRef = useRef(async () => void 0); const appliedCouponCodeRef = useRef(null); const calculatedAdjustmentsRef = useRef(null); const calculateGodaddyExpressTaxes = useCallback(async ({ address, shippingAmount, discountAdjustments }) => { if (!address || !session?.enableTaxCollection) return null; const taxesRequest = { destination: { countryCode: address?.countryCode || "US", postalCode: address?.postalCode || "", adminArea2: address?.locality || "", adminArea1: address?.administrativeArea || "" }, lines: [{ type: "SHIPPING", subtotalPrice: { currencyCode, value: shippingAmount } }], discountAdjustments: discountAdjustments || void 0 }; return await getTaxes.mutateAsync(taxesRequest); }, [ getTaxes, session?.enableTaxCollection, currencyCode ]); const getSortedShippingMethods = useCallback(async ({ shippingAddress: address }) => { const shippingMethodsData = await getShippingMethodsByAddress.mutateAsync({ countryCode: address.countryCode || "US", postalCode: address.postalCode || "", adminArea2: address.locality || "", adminArea1: address.administrativeArea || "" }); setShippingMethods(shippingMethodsData); const orderSubTotal = totals?.subTotal?.value || 0; return filterAndSortShippingMethods({ shippingMethods: shippingMethodsData || [], orderSubTotal, experimentalRules: session?.experimental_rules })?.map((method) => { const shippingMethodPrice = formatCurrency({ amount: method.cost?.value || 0, currencyCode: method.cost?.currencyCode || currencyCode, inputInMinorUnits: true }); return { id: method?.displayName?.replace(/\s+/g, "-")?.toLowerCase(), label: method.displayName || "", detail: method.description ? `(${method.description}) ${shippingMethodPrice}` : `${shippingMethodPrice}`, amount: method.cost?.value || 0, displayAmount: formatCurrency({ amount: method.cost?.value || 0, currencyCode: method.cost?.currencyCode || currencyCode, inputInMinorUnits: true, returnRaw: true }) }; }); }, [ getShippingMethodsByAddress.mutateAsync, session, totals ]); handleExpressPayClickRef.current = useCallback(async ({ source }) => { if (isDisabled) return; const currentCouponCode = appliedCouponCodeRef.current; const currentAdjustments = calculatedAdjustmentsRef.current; let eventId; let expressRequest = { ...poyntExpressRequest }; if (currentCouponCode && currentAdjustments?.totalDiscountAmount) { const updatedLineItems = [...expressRequest.lineItems]; updatedLineItems.push({ label: t.totals.discount, amount: formatCurrency({ amount: -(currentAdjustments?.totalDiscountAmount?.value || 0), currencyCode, inputInMinorUnits: true, returnRaw: true }), isPending: false }); const totalAmount = formatCurrency({ amount: (totals?.subTotal?.value || 0) - (currentAdjustments?.totalDiscountAmount?.value || 0), currencyCode, inputInMinorUnits: true, returnRaw: true }); expressRequest = { ...expressRequest, lineItems: updatedLineItems, total: { label: t.payment.orderTotal, amount: totalAmount, isPending: false }, couponCode: { code: currentCouponCode, label: t.totals.discount, amount: formatCurrency({ amount: -(currentAdjustments?.totalDiscountAmount?.value || 0), currencyCode, inputInMinorUnits: true, returnRaw: true }) } }; } else expressRequest = { ...expressRequest, couponCode: { code: "", label: "", amount: "0.00" } }; setWalletSource(source); setCheckoutErrors(void 0); switch (source) { case "apple_pay": eventId = eventIds.expressApplePayClick; collect?.current?.startApplePaySession(expressRequest); break; case "google_pay": eventId = eventIds.expressGooglePayClick; collect?.current?.startGooglePaySession(expressRequest); break; case "paze": eventId = eventIds.pazePayClick; collect?.current?.startPazeSession(expressRequest); break; default: return; } track({ eventId, type: TrackingEventType.CLICK, properties: { paymentType: source } }); }, [ poyntExpressRequest, t, setCheckoutErrors, currencyCode, totals, formatCurrency, isDisabled ]); const [couponFetchStatus, setCouponFetchStatus] = useState("idle"); useEffect(() => { if (!draftOrder) return; if (couponFetchStatus === "fetching") return; const fetchPriceAdjustments = async () => { setCouponFetchStatus("fetching"); try { const allCodes = /* @__PURE__ */ new Set(); if (draftOrder?.discounts) { for (const discount of draftOrder.discounts) if (discount.code) allCodes.add(discount.code); } if (draftOrder?.lineItems) { for (const lineItem of draftOrder.lineItems) if (lineItem.discounts) { for (const discount of lineItem.discounts) if (discount.code) allCodes.add(discount.code); } } const discountCodes = Array.from(allCodes); if (discountCodes?.length && discountCodes?.[0]) { const result = await getPriceAdjustments.mutateAsync({ discountCodes: [discountCodes?.[0]] }); if (result) { appliedCouponCodeRef.current = discountCodes?.[0]; calculatedAdjustmentsRef.current = result; } } else { appliedCouponCodeRef.current = null; calculatedAdjustmentsRef.current = null; } } finally { setCouponFetchStatus("done"); } }; fetchPriceAdjustments(); }, [draftOrder, useMemo(() => { const allCodes = /* @__PURE__ */ new Set(); if (draftOrder?.discounts) { for (const discount of draftOrder.discounts) if (discount.code) allCodes.add(discount.code); } if (draftOrder?.lineItems) { for (const lineItem of draftOrder.lineItems) if (lineItem.discounts) { for (const discount of lineItem.discounts) if (discount.code) allCodes.add(discount.code); } } return Array.from(allCodes).sort().join(","); }, [draftOrder])]); useEffect(() => { if (!isPoyntLoaded || !godaddyPaymentsConfig || !isCollectLoading || !draftOrder || hasMounted.current || couponFetchStatus !== "done" || !godaddyPaymentsConfig?.businessId && !session?.businessId) return; if (!collect.current) { const currentAdjustments = calculatedAdjustmentsRef.current; const currentCouponCode = appliedCouponCodeRef.current; let couponConfig; if (currentAdjustments?.totalDiscountAmount && currentCouponCode) couponConfig = { code: currentCouponCode, label: t.totals.discount, amount: formatCurrency({ amount: currentAdjustments?.totalDiscountAmount?.value || 0, currencyCode, inputInMinorUnits: true, returnRaw: true }) }; collect.current = new window.TokenizeJs({ businessId: godaddyPaymentsConfig?.businessId || session?.businessId, storeId: session?.storeId, channelId: session?.channelId, applicationId: godaddyPaymentsConfig?.appId }, { country: countryCode, currency: currencyCode, merchantName: session?.storeName || "", requireEmail: true, requireShippingAddress: !!session?.enableShippingAddressCollection, supportCouponCode: !!session?.enablePromotionCodes, ...couponConfig ? { couponCode: couponConfig } : {} }); } if (collect.current) collect.current.supportWalletPayments().then((supports) => { const paymentMethods = []; if (supports.applePay) { track({ eventId: eventIds.expressApplePayImpression, type: TrackingEventType.IMPRESSION, properties: { provider: "poynt" } }); paymentMethods.push("apple_pay"); } if (supports.googlePay) { paymentMethods.push("google_pay"); track({ eventId: eventIds.expressGooglePayImpression, type: TrackingEventType.IMPRESSION, properties: { provider: "poynt" } }); } if (paymentMethods.length > 0 && !hasMounted.current) { hasMounted.current = true; collect.current?.mount("gdpay-express-pay-element", document, { paymentMethods, buttonsContainerOptions: { className: "gap-1 !flex-col sm:!flex-row place-items-center" }, buttonOptions: { type: "plain", margin: "0", height: "50px", width: "100%", justifyContent: "flex-start", onClick: (args) => handleExpressPayClickRef.current(args) } }); } }); }, [ isPoyntLoaded, godaddyPaymentsConfig, isCollectLoading, draftOrder, couponFetchStatus, countryCode, currencyCode, session?.businessId, session?.storeId, session?.channelId, session?.enablePromotionCodes, session?.enableShippingAddressCollection, session?.storeName, t, formatCurrency ]); const convertAddressToShippingLines = useCallback((address, selectedMethod) => { if (!address) return void 0; return [{ subTotal: { currencyCode, value: selectedMethod.amount }, name: selectedMethod.name }]; }, [currencyCode]); useEffect(() => { if (!collect.current || !isPoyntLoaded) return; collect.current.on("close_wallet", () => { setCouponFetchStatus("idle"); setCalculatedTaxes(null); appliedCouponCodeRef.current = null; calculatedAdjustmentsRef.current = null; setError(""); setShippingAddress(null); setShippingMethods(null); setShippingMethod(null); setGoDaddyTotals({ taxes: { currencyCode, value: 0 }, shipping: { currencyCode, value: 0 } }); form.reset(mapOrderToFormValues({ order: draftOrder, defaultCountryCode: session?.shipping?.originAddress?.countryCode })); if (session?.enableTaxCollection && draftOrder?.shipping?.address) try { updateTaxes.mutate(void 0); } catch (_error) {} }); collect.current.on("coupon_code_change", async (e) => { const couponCode = e.couponCode; let updatedOrder = {}; track({ eventId: couponCode ? eventIds.expressApplyCouponEvent : eventIds.expressRemoveCouponEvent, type: TrackingEventType.EVENT, properties: { couponCode: couponCode || "removed" } }); const baseLineItems = [...poyntExpressRequest.lineItems]; if (!couponCode) { appliedCouponCodeRef.current = null; calculatedAdjustmentsRef.current = null; let updatedTaxValue = godaddyTotals.taxes.value; if (shippingAddress) try { const recalculatedTaxes = await calculateGodaddyExpressTaxes({ address: shippingAddress, shippingAmount: godaddyTotals.shipping.value, discountAdjustments: {} }); if (recalculatedTaxes?.totalTaxAmount?.value != null) { updatedTaxValue = recalculatedTaxes.totalTaxAmount.value; setCalculatedTaxes(recalculatedTaxes); setGoDaddyTotals((value) => ({ ...value, taxes: { currencyCode, value: updatedTaxValue } })); } } catch (_taxError) { e.updateWith({ error: { code: "unknown", message: "Unable to calculate taxes. Please try again." } }); return; } const finalLineItems = [...baseLineItems]; if (godaddyTotals.shipping.value > 0) finalLineItems.push({ label: "Shipping", amount: formatCurrency({ amount: godaddyTotals.shipping.value, currencyCode, inputInMinorUnits: true, returnRaw: true }) }); if (updatedTaxValue > 0) finalLineItems.push({ label: t.totals.estimatedTaxes, amount: formatCurrency({ amount: updatedTaxValue, currencyCode, inputInMinorUnits: true, returnRaw: true }) }); const totalAmount = formatCurrency({ amount: (totals?.subTotal?.value || 0) + godaddyTotals.shipping.value + updatedTaxValue, currencyCode, inputInMinorUnits: true, returnRaw: true }); updatedOrder = { lineItems: finalLineItems, total: { label: t.payment.orderTotal, amount: totalAmount }, couponCode: { code: "", label: "", amount: "0.00" } }; } else try { let shippingLines; if (shippingAddress && shippingMethod) shippingLines = convertAddressToShippingLines(shippingAddress, { amount: godaddyTotals.shipping.value, name: shippingMethod }); const adjustments = await getPriceAdjustments.mutateAsync({ discountCodes: [couponCode], shippingLines }); if (adjustments?.totalDiscountAmount?.value) { appliedCouponCodeRef.current = couponCode; calculatedAdjustmentsRef.current = adjustments; const adjustmentValue = adjustments.totalDiscountAmount.value; let updatedTaxValue = godaddyTotals.taxes.value; if (shippingAddress) try { const recalculatedTaxes = await calculateGodaddyExpressTaxes({ address: shippingAddress, shippingAmount: godaddyTotals.shipping.value, discountAdjustments: adjustments }); if (recalculatedTaxes?.totalTaxAmount?.value != null) { updatedTaxValue = recalculatedTaxes.totalTaxAmount.value; setCalculatedTaxes(recalculatedTaxes); setGoDaddyTotals((value) => ({ ...value, taxes: { currencyCode, value: updatedTaxValue } })); } } catch (_taxError) { e.updateWith({ error: { code: "unknown", message: "Unable to calculate taxes. Please try again." } }); return; } const finalLineItems = [...baseLineItems]; if (godaddyTotals.shipping.value > 0) finalLineItems.push({ label: t.totals.shipping, amount: formatCurrency({ amount: godaddyTotals.shipping.value, currencyCode, inputInMinorUnits: true, returnRaw: true }) }); if (updatedTaxValue > 0) finalLineItems.push({ label: t.totals.estimatedTaxes, amount: formatCurrency({ amount: updatedTaxValue, currencyCode, inputInMinorUnits: true, returnRaw: true }) }); finalLineItems.push({ label: t.totals.discount, amount: formatCurrency({ amount: -adjustmentValue, currencyCode, inputInMinorUnits: true, returnRaw: true }) }); const totalAmount = formatCurrency({ amount: (totals?.subTotal?.value || 0) + godaddyTotals.shipping.value + updatedTaxValue - adjustmentValue, currencyCode, inputInMinorUnits: true, returnRaw: true }); updatedOrder = { lineItems: finalLineItems, total: { label: t.payment.orderTotal, amount: totalAmount }, couponCode: { code: couponCode, label: t.totals.discount, amount: formatCurrency({ amount: -adjustmentValue, currencyCode, inputInMinorUnits: true, returnRaw: true }) } }; } else { track({ eventId: eventIds.discountError, type: TrackingEventType.EVENT, properties: { success: false, errorType: "invalid_coupon", couponCode, errorCodes: "invalid_coupon_code" } }); updatedOrder = { error: { code: "invalid_coupon_code", message: `Coupon code ${couponCode} is not valid or cannot be applied` } }; } } catch (err) { track({ eventId: eventIds.discountError, type: TrackingEventType.EVENT, properties: { success: false, errorType: "coupon_application_error", couponCode, errorCodes: err instanceof Error ? err.name : "unknown" } }); updatedOrder = { error: { code: "invalid_coupon_code", message: `Could not apply coupon code ${couponCode}` } }; } e.updateWith(updatedOrder); }); collect.current.on("payment_authorized", async (event) => { const currentAdjustments = calculatedAdjustmentsRef.current; const nonce = event?.nonce; const selectedShippingMethod = shippingMethods?.find((method) => method.displayName === shippingMethod); if (nonce) { const checkoutBody = { paymentToken: nonce, paymentType: event?.source, paymentProvider: PaymentProvider.POYNT, isExpress: true, ...godaddyTotals.shipping ? { shippingTotal: godaddyTotals.shipping } : {}, ...calculatedTaxes ? { calculatedTaxes } : {}, ...currentAdjustments ? { calculatedAdjustments: currentAdjustments } : {}, ...event?.billingAddress ? { billing: { email: event.billingAddress.emailAddress || "", phone: event.billingAddress.phoneNumber || "", firstName: event.billingAddress.name?.split(" ")?.[0] || "", lastName: event.billingAddress.name ? event.billingAddress.name.split(" ").slice(1).join(" ") || "" : "", address: { countryCode: event.billingAddress.countryCode || "", postalCode: event.billingAddress.postalCode || "", adminArea1: event.billingAddress.administrativeArea || "", adminArea2: event.billingAddress.locality || "", addressLine1: event.billingAddress.addressLines?.[0] || "", addressLine2: event.billingAddress.addressLines?.[1] || "" } } } : {}, ...event?.shippingAddress ? { shipping: { email: event?.shippingAddress?.emailAddress || "", phone: event?.shippingAddress?.phoneNumber || "", firstName: event.shippingAddress.name?.split(" ")?.[0] || "", lastName: event.shippingAddress.name ? event.shippingAddress.name.split(" ").slice(1).join(" ") || "" : "", address: { countryCode: event?.shippingAddress?.countryCode || "", postalCode: event?.shippingAddress?.postalCode || "", adminArea1: event.shippingAddress?.administrativeArea || "", adminArea2: event?.shippingAddress?.locality || "", addressLine1: event?.shippingAddress?.addressLines?.[0] || "", addressLine2: event?.shippingAddress?.addressLines?.[1] || "" } } } : {}, ...selectedShippingMethod ? { shippingLines: [{ amount: godaddyTotals.shipping, name: selectedShippingMethod?.displayName || "", requestedProvider: selectedShippingMethod?.carrierCode || "", requestedService: selectedShippingMethod?.serviceCode || "", totals: { subTotal: godaddyTotals.shipping, taxTotal: { value: 0, currencyCode } } }] } : {} }; try { await confirmCheckout.mutateAsync(checkoutBody); event.complete(); } catch (err) { if (err instanceof GraphQLErrorWithCodes) { const walletError = { code: "invalid_payment_data", message: t.apiErrors?.[err.codes[0]] || t.errors.errorProcessingPayment }; track({ eventId: eventIds.expressCheckoutError, type: TrackingEventType.EVENT, properties: { paymentType: event.source, provider: "poynt", errorCodes: err.codes.join(",") } }); event.complete({ error: walletError }); } else { track({ eventId: eventIds.expressCheckoutError, type: TrackingEventType.EVENT, properties: { paymentType: event.source, provider: "poynt", errorType: "generic" } }); const walletError = { code: "invalid_payment_data", message: t.errors.errorProcessingPayment }; event.complete({ error: walletError }); } } } else { track({ eventId: eventIds.expressCheckoutError, type: TrackingEventType.EVENT, properties: { paymentType: event.source, provider: "poynt", errorCodes: "no_nonce" } }); const walletError = { code: "invalid_payment_data", message: t.errors.errorProcessingPayment }; event.complete({ error: walletError }); } }); collect.current.on("ready", () => { setIsCollectLoading(false); }); collect.current.on("error", (event) => { setError(event?.data?.error?.message || t.errors.errorProcessingPayment); }); collect.current.on("shipping_method_change", async (e) => { let updatedOrder = poyntExpressRequest; const poyntLineItems = [...poyntExpressRequest.lineItems]; if (e.shippingMethod && shippingAddress) { const shippingAmount = e.shippingMethod?.amount; poyntLineItems.push({ label: t.totals.shipping, amount: shippingAmount || "0", isPending: false }); setGoDaddyTotals((value) => ({ ...value, shipping: { currencyCode, value: convertMajorToMinorUnits(shippingAmount || "0", currencyCode) } })); setShippingMethod(e.shippingMethod?.label || null); let updatedAdjustments = calculatedAdjustmentsRef.current; const currentCouponCode = appliedCouponCodeRef.current; if (currentCouponCode) try { const shippingLines = convertAddressToShippingLines(shippingAddress, { amount: convertMajorToMinorUnits(shippingAmount || "0", currencyCode), name: e.shippingMethod?.label || t.totals.shipping }); const newAdjustments = await getPriceAdjustments.mutateAsync({ discountCodes: [currentCouponCode], shippingLines }); if (newAdjustments?.totalDiscountAmount) { updatedAdjustments = newAdjustments; calculatedAdjustmentsRef.current = newAdjustments; } else { updatedAdjustments = null; calculatedAdjustmentsRef.current = null; appliedCouponCodeRef.current = ""; } } catch (err) { track({ eventId: eventIds.discountError, type: TrackingEventType.EVENT, properties: { success: false, errorType: "shipping_method_price_adjustment_error", couponCode: currentCouponCode, errorCodes: err instanceof Error ? err.name : "unknown", shippingMethod: e.shippingMethod?.label || "" } }); } if (session?.enableTaxCollection) try { const taxesResult = await calculateGodaddyExpressTaxes({ address: shippingAddress, shippingAmount: convertMajorToMinorUnits(shippingAmount || "0", currencyCode), discountAdjustments: updatedAdjustments }); if (taxesResult?.totalTaxAmount?.value) { setCalculatedTaxes(taxesResult); poyntLineItems.push({ label: t.totals.estimatedTaxes, amount: formatCurrency({ amount: taxesResult?.totalTaxAmount?.value, currencyCode, inputInMinorUnits: true, returnRaw: true }), isPending: false }); setGoDaddyTotals((value) => ({ ...value, taxes: { currencyCode, value: taxesResult?.totalTaxAmount?.value || 0 } })); } } catch (_error) { if (walletSource !== "apple_pay") { e.updateWith({ error: { code: "unknown", message: t.apiErrors.TAX_CALCULATION_ERROR } }); return; } setCheckoutErrors([t.apiErrors.TAX_CALCULATION_ERROR]); collect?.current?.abortApplePaySession(); return; } if (updatedAdjustments?.totalDiscountAmount && currentCouponCode) poyntLineItems.push({ label: t.totals.discount, amount: formatCurrency({ amount: -(updatedAdjustments?.totalDiscountAmount?.value || 0), currencyCode, inputInMinorUnits: true, returnRaw: true }), isPending: false }); const totalAmount = poyntLineItems.reduce((acc, item) => acc + Number(item.amount), 0); updatedOrder = { ...updatedOrder, total: { label: t.payment.orderTotal, amount: formatCurrency({ amount: totalAmount, currencyCode, inputInMinorUnits: false, returnRaw: true }) }, lineItems: poyntLineItems }; if (currentCouponCode && updatedAdjustments?.totalDiscountAmount) updatedOrder.couponCode = { code: currentCouponCode, label: t.totals.discount, amount: formatCurrency({ amount: -(updatedAdjustments?.totalDiscountAmount?.value || 0), currencyCode, inputInMinorUnits: true, returnRaw: true }) }; e.updateWith(updatedOrder); } }); collect.current.on("shipping_address_change", async (e) => { let updatedOrder = poyntExpressRequest; const poyntLineItems = [...poyntExpressRequest.lineItems]; let updatedAdjustments = calculatedAdjustmentsRef.current; const currentCouponCode = appliedCouponCodeRef.current; if (e.shippingAddress) { setShippingAddress(e.shippingAddress); const methods = await getSortedShippingMethods({ shippingAddress: e.shippingAddress }); if (methods[0]) { setShippingMethod(methods[0]?.label || null); setGoDaddyTotals((value) => ({ ...value, shipping: { currencyCode, value: methods?.[0]?.amount || 0 } })); poyntLineItems.push({ label: t.totals.shipping, amount: methods?.[0]?.displayAmount || "0", isPending: false }); if (currentCouponCode) try { const shippingLines = convertAddressToShippingLines(e.shippingAddress, { amount: methods[0]?.amount || 0, name: methods[0]?.label || t.totals.shipping }); const newAdjustments = await getPriceAdjustments.mutateAsync({ discountCodes: [currentCouponCode], shippingLines }); if (newAdjustments?.totalDiscountAmount) { updatedAdjustments = newAdjustments; calculatedAdjustmentsRef.current = newAdjustments; } else { updatedAdjustments = null; calculatedAdjustmentsRef.current = null; appliedCouponCodeRef.current = ""; } } catch (err) { track({ eventId: eventIds.discountError, type: TrackingEventType.EVENT, properties: { success: false, errorType: "shipping_price_adjustment_error", couponCode: currentCouponCode, errorCodes: err instanceof Error ? err.name : "unknown", shippingMethod: methods[0]?.label || "" } }); } } else { e.updateWith({ error: { code: "invalid_shipping_address", message: t.shipping.noShippingMethods } }); setGoDaddyTotals((value) => ({ ...value, shipping: { currencyCode, value: 0 } })); } if (session?.enableTaxCollection) try { const taxesResult = await calculateGodaddyExpressTaxes({ address: e.shippingAddress, shippingAmount: methods?.[0]?.amount || 0, discountAdjustments: updatedAdjustments }); if (taxesResult?.totalTaxAmount?.value) { setCalculatedTaxes(taxesResult); poyntLineItems.push({ label: t.totals.estimatedTaxes, amount: formatCurrency({ amount: taxesResult.totalTaxAmount.value, currencyCode, inputInMinorUnits: true, returnRaw: true }), isPending: false }); setGoDaddyTotals((value) => ({ ...value, taxes: { currencyCode, value: taxesResult?.totalTaxAmount?.value || 0 } })); } } catch (_error) { if (walletSource !== "apple_pay") { e.updateWith({ error: { code: "unknown", message: t.apiErrors.TAX_CALCULATION_ERROR } }); return; } setCheckoutErrors([t.apiErrors.TAX_CALCULATION_ERROR]); collect?.current?.abortApplePaySession(); return; } if (updatedAdjustments?.totalDiscountAmount && currentCouponCode) poyntLineItems.push({ label: t.totals.discount, amount: formatCurrency({ amount: -(updatedAdjustments?.totalDiscountAmount?.value || 0), currencyCode, inputInMinorUnits: true, returnRaw: true }), isPending: false }); const totalAmount = poyntLineItems.reduce((acc, item) => acc + Number(item.amount), 0); updatedOrder = { ...poyntExpressRequest, total: { label: t.payment.orderTotal, amount: formatCurrency({ amount: totalAmount, currencyCode, inputInMinorUnits: false, returnRaw: true }) }, shippingMethods: methods.map((method) => ({ id: method.id || "", label: method.label, detail: method.detail, amount: method.displayAmount })), lineItems: poyntLineItems }; if (currentCouponCode && updatedAdjustments?.totalDiscountAmount) updatedOrder.couponCode = { code: currentCouponCode, label: currentCouponCode || "Discount", amount: formatCurrency({ amount: -(updatedAdjustments?.totalDiscountAmount?.value || 0), currencyCode, inputInMinorUnits: true, returnRaw: true }) }; else updatedOrder.couponCode = { code: "", label: "", amount: "0.00" }; e.updateWith(updatedOrder); } }); }, [ isPoyntLoaded, shippingAddress, shippingMethod, shippingMethods, godaddyTotals, poyntExpressRequest, currencyCode, confirmCheckout.mutateAsync, t.errors.errorProcessingPayment, t.apiErrors, calculateGodaddyExpressTaxes, getSortedShippingMethods, convertAddressToShippingLines, getPriceAdjustments.mutateAsync, t, form, draftOrder, session, updateTaxes.mutate, walletSource, setCheckoutErrors ]); return /* @__PURE__ */ jsxs(Fragment, { children: [ /* @__PURE__ */ jsx("div", { id: "gdpay-express-pay-element", className: isDisabled ? "opacity-50 pointer-events-none" : void 0 }), isCollectLoading ? /* @__PURE__ */ jsxs("div", { className: "grid gap-1 grid-cols-1 sm:grid-cols-2", children: [/* @__PURE__ */ jsx(Skeleton, { className: "h-12 w-full mb-1" }), /* @__PURE__ */ jsx(Skeleton, { className: "h-12 w-full mb-1" })] }) : null, error ? /* @__PURE__ */ jsx("p", { className: "text-destructive py-1", children: error }) : null ] }); } //#endregion export { ExpressCheckoutButton };