first commit
This commit is contained in:
@@ -0,0 +1,116 @@
|
||||
import { Listbox, Transition } from "@headlessui/react"
|
||||
import { ChevronsUpDown } from "lucide-react"
|
||||
import { clx } from "@modules/common/components/ui"
|
||||
import { Fragment, useMemo } from "react"
|
||||
|
||||
import compareAddresses from "@lib/util/compare-addresses"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import Radio from "@modules/common/components/radio"
|
||||
|
||||
type AddressSelectProps = {
|
||||
addresses: HttpTypes.StoreCustomerAddress[]
|
||||
addressInput: HttpTypes.StoreCartAddress | null
|
||||
onSelect: (
|
||||
address: HttpTypes.StoreCartAddress | undefined,
|
||||
email?: string
|
||||
) => void
|
||||
}
|
||||
|
||||
const AddressSelect = ({
|
||||
addresses,
|
||||
addressInput,
|
||||
onSelect,
|
||||
}: AddressSelectProps) => {
|
||||
const handleSelect = (id: string) => {
|
||||
const savedAddress = addresses.find((a) => a.id === id)
|
||||
if (savedAddress) {
|
||||
onSelect(savedAddress as HttpTypes.StoreCartAddress)
|
||||
}
|
||||
}
|
||||
|
||||
const selectedAddress = useMemo(() => {
|
||||
return addresses.find((a) => addressInput && compareAddresses(a, addressInput))
|
||||
}, [addresses, addressInput])
|
||||
|
||||
return (
|
||||
<Listbox onChange={handleSelect} value={selectedAddress?.id}>
|
||||
<div className="relative">
|
||||
<Listbox.Button
|
||||
className="relative w-full flex justify-between items-center px-4 py-[10px] text-left bg-white cursor-default focus:outline-none border rounded-rounded focus-visible:ring-2 focus-visible:ring-opacity-75 focus-visible:ring-white focus-visible:ring-offset-gray-300 focus-visible:ring-offset-2 focus-visible:border-gray-300 text-base-regular"
|
||||
data-testid="shipping-address-select"
|
||||
>
|
||||
{({ open }) => (
|
||||
<>
|
||||
<span className="block truncate">
|
||||
{selectedAddress
|
||||
? selectedAddress.address_1
|
||||
: "Choose an address"}
|
||||
</span>
|
||||
<ChevronsUpDown
|
||||
className={clx("h-4 w-4 transition-transform duration-200", {
|
||||
"transform rotate-180": open,
|
||||
})}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</Listbox.Button>
|
||||
<Transition
|
||||
as={Fragment}
|
||||
leave="transition ease-in duration-100"
|
||||
leaveFrom="opacity-100"
|
||||
leaveTo="opacity-0"
|
||||
>
|
||||
<Listbox.Options
|
||||
className="absolute z-20 w-full overflow-auto text-small-regular bg-white border border-top-0 max-h-60 focus:outline-none sm:text-sm"
|
||||
data-testid="shipping-address-options"
|
||||
>
|
||||
{addresses.map((address) => {
|
||||
return (
|
||||
<Listbox.Option
|
||||
key={address.id}
|
||||
value={address.id}
|
||||
className="cursor-default select-none relative pl-6 pr-10 hover:bg-gray-50 py-4"
|
||||
data-testid="shipping-address-option"
|
||||
>
|
||||
<div className="flex gap-x-4 items-start">
|
||||
<Radio
|
||||
checked={selectedAddress?.id === address.id}
|
||||
data-testid="shipping-address-radio"
|
||||
/>
|
||||
<div className="flex flex-col">
|
||||
<span className="text-left text-base-semi">
|
||||
{address.first_name} {address.last_name}
|
||||
</span>
|
||||
{address.company && (
|
||||
<span className="text-small-regular text-ui-fg-base">
|
||||
{address.company}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex flex-col text-left text-base-regular mt-2">
|
||||
<span>
|
||||
{address.address_1}
|
||||
{address.address_2 && (
|
||||
<span>, {address.address_2}</span>
|
||||
)}
|
||||
</span>
|
||||
<span>
|
||||
{address.postal_code}, {address.city}
|
||||
</span>
|
||||
<span>
|
||||
{address.province && `${address.province}, `}
|
||||
{address.country_code?.toUpperCase()}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Listbox.Option>
|
||||
)
|
||||
})}
|
||||
</Listbox.Options>
|
||||
</Transition>
|
||||
</div>
|
||||
</Listbox>
|
||||
)
|
||||
}
|
||||
|
||||
export default AddressSelect
|
||||
@@ -0,0 +1,184 @@
|
||||
"use client"
|
||||
import { setAddresses } from "@lib/data/cart"
|
||||
import useToggleState from "@lib/hooks/use-toggle-state"
|
||||
import compareAddresses from "@lib/util/compare-addresses"
|
||||
import { CheckCircle2 as CheckCircleSolid } from "lucide-react"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import Divider from "@modules/common/components/divider"
|
||||
import { Heading, Text } from "@modules/common/components/ui"
|
||||
import Spinner from "@modules/common/icons/spinner"
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation"
|
||||
import { useActionState } from "react"
|
||||
import BillingAddress from "../billing_address"
|
||||
import ErrorMessage from "../error-message"
|
||||
import ShippingAddress from "../shipping-address"
|
||||
import { SubmitButton } from "../submit-button"
|
||||
|
||||
const Addresses = ({
|
||||
cart,
|
||||
customer,
|
||||
}: {
|
||||
cart: HttpTypes.StoreCart | null
|
||||
customer: HttpTypes.StoreCustomer | null
|
||||
}) => {
|
||||
const searchParams = useSearchParams()
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
|
||||
const isOpen = searchParams.get("step") === "address"
|
||||
|
||||
const { state: sameAsBilling, toggle: toggleSameAsBilling } = useToggleState(
|
||||
cart?.shipping_address && cart?.billing_address
|
||||
? compareAddresses(cart?.shipping_address, cart?.billing_address)
|
||||
: true
|
||||
)
|
||||
|
||||
const handleEdit = () => {
|
||||
router.push(pathname + "?step=address")
|
||||
}
|
||||
|
||||
const [message, formAction] = useActionState(setAddresses, null)
|
||||
|
||||
return (
|
||||
<div className="bg-white">
|
||||
<div className="flex flex-row items-center justify-between mb-6">
|
||||
<Heading
|
||||
level="h2"
|
||||
className="flex flex-row text-3xl-regular gap-x-2 items-baseline"
|
||||
>
|
||||
Shipping Address
|
||||
{!isOpen && <CheckCircleSolid />}
|
||||
</Heading>
|
||||
{!isOpen && cart?.shipping_address && (
|
||||
<Text>
|
||||
<button
|
||||
onClick={handleEdit}
|
||||
className="text-ui-fg-interactive hover:text-ui-fg-interactive-hover"
|
||||
data-testid="edit-address-button"
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
</Text>
|
||||
)}
|
||||
</div>
|
||||
{isOpen ? (
|
||||
<form action={formAction}>
|
||||
<div className="pb-8">
|
||||
<ShippingAddress
|
||||
customer={customer}
|
||||
checked={sameAsBilling}
|
||||
onChange={toggleSameAsBilling}
|
||||
cart={cart}
|
||||
/>
|
||||
|
||||
{!sameAsBilling && (
|
||||
<div>
|
||||
<Heading
|
||||
level="h2"
|
||||
className="text-3xl-regular gap-x-4 pb-6 pt-8"
|
||||
>
|
||||
Billing address
|
||||
</Heading>
|
||||
|
||||
<BillingAddress cart={cart} />
|
||||
</div>
|
||||
)}
|
||||
<SubmitButton className="mt-6" data-testid="submit-address-button">
|
||||
Continue to delivery
|
||||
</SubmitButton>
|
||||
<ErrorMessage error={message} data-testid="address-error-message" />
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<div>
|
||||
<div className="text-small-regular">
|
||||
{cart && cart.shipping_address ? (
|
||||
<div className="flex items-start gap-x-8">
|
||||
<div className="flex items-start gap-x-1 w-full">
|
||||
<div
|
||||
className="flex flex-col w-1/3"
|
||||
data-testid="shipping-address-summary"
|
||||
>
|
||||
<Text className="txt-medium-plus text-ui-fg-base mb-1">
|
||||
Shipping Address
|
||||
</Text>
|
||||
<Text className="txt-medium text-ui-fg-subtle">
|
||||
{cart.shipping_address.first_name}{" "}
|
||||
{cart.shipping_address.last_name}
|
||||
</Text>
|
||||
<Text className="txt-medium text-ui-fg-subtle">
|
||||
{cart.shipping_address.address_1}{" "}
|
||||
{cart.shipping_address.address_2}
|
||||
</Text>
|
||||
<Text className="txt-medium text-ui-fg-subtle">
|
||||
{cart.shipping_address.postal_code},{" "}
|
||||
{cart.shipping_address.city}
|
||||
</Text>
|
||||
<Text className="txt-medium text-ui-fg-subtle">
|
||||
{cart.shipping_address.country_code?.toUpperCase()}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="flex flex-col w-1/3 "
|
||||
data-testid="shipping-contact-summary"
|
||||
>
|
||||
<Text className="txt-medium-plus text-ui-fg-base mb-1">
|
||||
Contact
|
||||
</Text>
|
||||
<Text className="txt-medium text-ui-fg-subtle">
|
||||
{cart.shipping_address.phone}
|
||||
</Text>
|
||||
<Text className="txt-medium text-ui-fg-subtle">
|
||||
{cart.email}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="flex flex-col w-1/3"
|
||||
data-testid="billing-address-summary"
|
||||
>
|
||||
<Text className="txt-medium-plus text-ui-fg-base mb-1">
|
||||
Billing Address
|
||||
</Text>
|
||||
|
||||
{sameAsBilling ? (
|
||||
<Text className="txt-medium text-ui-fg-subtle">
|
||||
Billing and delivery address are the same.
|
||||
</Text>
|
||||
) : (
|
||||
<>
|
||||
<Text className="txt-medium text-ui-fg-subtle">
|
||||
{cart.billing_address?.first_name}{" "}
|
||||
{cart.billing_address?.last_name}
|
||||
</Text>
|
||||
<Text className="txt-medium text-ui-fg-subtle">
|
||||
{cart.billing_address?.address_1}{" "}
|
||||
{cart.billing_address?.address_2}
|
||||
</Text>
|
||||
<Text className="txt-medium text-ui-fg-subtle">
|
||||
{cart.billing_address?.postal_code},{" "}
|
||||
{cart.billing_address?.city}
|
||||
</Text>
|
||||
<Text className="txt-medium text-ui-fg-subtle">
|
||||
{cart.billing_address?.country_code?.toUpperCase()}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<Spinner />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<Divider className="mt-8" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Addresses
|
||||
@@ -0,0 +1,114 @@
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import Input from "@modules/common/components/input"
|
||||
import React, { useState } from "react"
|
||||
import CountrySelect from "../country-select"
|
||||
|
||||
const BillingAddress = ({ cart }: { cart: HttpTypes.StoreCart | null }) => {
|
||||
const [formData, setFormData] = useState<Record<string, string>>({
|
||||
"billing_address.first_name": cart?.billing_address?.first_name || "",
|
||||
"billing_address.last_name": cart?.billing_address?.last_name || "",
|
||||
"billing_address.address_1": cart?.billing_address?.address_1 || "",
|
||||
"billing_address.company": cart?.billing_address?.company || "",
|
||||
"billing_address.postal_code": cart?.billing_address?.postal_code || "",
|
||||
"billing_address.city": cart?.billing_address?.city || "",
|
||||
"billing_address.country_code": cart?.billing_address?.country_code || "",
|
||||
"billing_address.province": cart?.billing_address?.province || "",
|
||||
"billing_address.phone": cart?.billing_address?.phone || "",
|
||||
})
|
||||
|
||||
const handleChange = (
|
||||
e: React.ChangeEvent<
|
||||
HTMLInputElement | HTMLInputElement | HTMLSelectElement
|
||||
>
|
||||
) => {
|
||||
setFormData({
|
||||
...formData,
|
||||
[e.target.name]: e.target.value,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Input
|
||||
label="First name"
|
||||
name="billing_address.first_name"
|
||||
autoComplete="given-name"
|
||||
value={formData["billing_address.first_name"]}
|
||||
onChange={handleChange}
|
||||
required
|
||||
data-testid="billing-first-name-input"
|
||||
/>
|
||||
<Input
|
||||
label="Last name"
|
||||
name="billing_address.last_name"
|
||||
autoComplete="family-name"
|
||||
value={formData["billing_address.last_name"]}
|
||||
onChange={handleChange}
|
||||
required
|
||||
data-testid="billing-last-name-input"
|
||||
/>
|
||||
<Input
|
||||
label="Address"
|
||||
name="billing_address.address_1"
|
||||
autoComplete="address-line1"
|
||||
value={formData["billing_address.address_1"]}
|
||||
onChange={handleChange}
|
||||
required
|
||||
data-testid="billing-address-input"
|
||||
/>
|
||||
<Input
|
||||
label="Company"
|
||||
name="billing_address.company"
|
||||
value={formData["billing_address.company"]}
|
||||
onChange={handleChange}
|
||||
autoComplete="organization"
|
||||
data-testid="billing-company-input"
|
||||
/>
|
||||
<Input
|
||||
label="Postal code"
|
||||
name="billing_address.postal_code"
|
||||
autoComplete="postal-code"
|
||||
value={formData["billing_address.postal_code"]}
|
||||
onChange={handleChange}
|
||||
required
|
||||
data-testid="billing-postal-input"
|
||||
/>
|
||||
<Input
|
||||
label="City"
|
||||
name="billing_address.city"
|
||||
autoComplete="address-level2"
|
||||
value={formData["billing_address.city"]}
|
||||
onChange={handleChange}
|
||||
/>
|
||||
<CountrySelect
|
||||
name="billing_address.country_code"
|
||||
autoComplete="country"
|
||||
region={cart?.region}
|
||||
value={formData["billing_address.country_code"]}
|
||||
onChange={handleChange}
|
||||
required
|
||||
data-testid="billing-country-select"
|
||||
/>
|
||||
<Input
|
||||
label="State / Province"
|
||||
name="billing_address.province"
|
||||
autoComplete="address-level1"
|
||||
value={formData["billing_address.province"]}
|
||||
onChange={handleChange}
|
||||
data-testid="billing-province-input"
|
||||
/>
|
||||
<Input
|
||||
label="Phone"
|
||||
name="billing_address.phone"
|
||||
autoComplete="tel"
|
||||
value={formData["billing_address.phone"]}
|
||||
onChange={handleChange}
|
||||
data-testid="billing-phone-input"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default BillingAddress
|
||||
@@ -0,0 +1,50 @@
|
||||
import { forwardRef, useImperativeHandle, useMemo, useRef } from "react"
|
||||
|
||||
import NativeSelect, {
|
||||
NativeSelectProps,
|
||||
} from "@modules/common/components/native-select"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
|
||||
const CountrySelect = forwardRef<
|
||||
HTMLSelectElement,
|
||||
NativeSelectProps & {
|
||||
region?: HttpTypes.StoreRegion
|
||||
}
|
||||
>(({ placeholder = "Country", region, defaultValue, ...props }, ref) => {
|
||||
const innerRef = useRef<HTMLSelectElement>(null)
|
||||
|
||||
useImperativeHandle<HTMLSelectElement | null, HTMLSelectElement | null>(
|
||||
ref,
|
||||
() => innerRef.current
|
||||
)
|
||||
|
||||
const countryOptions = useMemo(() => {
|
||||
if (!region) {
|
||||
return []
|
||||
}
|
||||
|
||||
return region.countries?.map((country) => ({
|
||||
value: country.iso_2,
|
||||
label: country.display_name,
|
||||
}))
|
||||
}, [region])
|
||||
|
||||
return (
|
||||
<NativeSelect
|
||||
ref={innerRef}
|
||||
placeholder={placeholder}
|
||||
defaultValue={defaultValue}
|
||||
{...props}
|
||||
>
|
||||
{countryOptions?.map(({ value, label }, index) => (
|
||||
<option key={index} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
)
|
||||
})
|
||||
|
||||
CountrySelect.displayName = "CountrySelect"
|
||||
|
||||
export default CountrySelect
|
||||
@@ -0,0 +1,150 @@
|
||||
"use client"
|
||||
|
||||
import React, { useState } from "react"
|
||||
import { applyPromotions } from "@lib/data/cart"
|
||||
import { convertToLocale } from "@lib/util/money"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Trash2, Tag } from "lucide-react"
|
||||
import ErrorMessage from "../error-message"
|
||||
import { SubmitButton } from "../submit-button"
|
||||
|
||||
type DiscountCodeProps = {
|
||||
cart: HttpTypes.StoreCart
|
||||
}
|
||||
|
||||
const DiscountCode: React.FC<DiscountCodeProps> = ({ cart }) => {
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const [errorMessage, setErrorMessage] = useState("")
|
||||
|
||||
const { promotions = [] } = cart
|
||||
|
||||
const removePromotionCode = async (code: string) => {
|
||||
const validPromotions = promotions.filter(
|
||||
(promotion) => promotion.code !== code
|
||||
)
|
||||
|
||||
await applyPromotions(
|
||||
validPromotions.filter((p) => p.code !== undefined).map((p) => p.code!)
|
||||
)
|
||||
}
|
||||
|
||||
const addPromotionCode = async (formData: FormData) => {
|
||||
setErrorMessage("")
|
||||
|
||||
const code = formData.get("code")
|
||||
if (!code) {
|
||||
return
|
||||
}
|
||||
const input = document.getElementById("promotion-input") as HTMLInputElement
|
||||
const codes = promotions
|
||||
.filter((p) => p.code !== undefined)
|
||||
.map((p) => p.code!)
|
||||
codes.push(code.toString())
|
||||
|
||||
try {
|
||||
await applyPromotions(codes)
|
||||
} catch (e) {
|
||||
setErrorMessage(e instanceof Error ? e.message : String(e))
|
||||
}
|
||||
|
||||
if (input) {
|
||||
input.value = ""
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-full flex flex-col gap-2">
|
||||
<form action={(a) => addPromotionCode(a)} className="w-full">
|
||||
<button
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
type="button"
|
||||
className="text-xs font-medium text-primary hover:underline flex items-center gap-1.5 py-1"
|
||||
data-testid="add-discount-button"
|
||||
>
|
||||
<Tag className="h-3.5 w-3.5" />
|
||||
<span>{isOpen ? "Zatvori unos koda" : "Imate promo kod ili popust?"}</span>
|
||||
</button>
|
||||
|
||||
{isOpen && (
|
||||
<div className="flex flex-col gap-2 mt-2">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="promotion-input"
|
||||
name="code"
|
||||
type="text"
|
||||
placeholder="Unesite promo kod"
|
||||
className="h-9 text-xs"
|
||||
data-testid="discount-input"
|
||||
/>
|
||||
<SubmitButton
|
||||
variant="secondary"
|
||||
data-testid="discount-apply-button"
|
||||
>
|
||||
Primijeni
|
||||
</SubmitButton>
|
||||
</div>
|
||||
|
||||
<ErrorMessage
|
||||
error={errorMessage}
|
||||
data-testid="discount-error-message"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
|
||||
{promotions.length > 0 && (
|
||||
<div className="flex flex-col gap-2 mt-2 pt-2 border-t border-border">
|
||||
<span className="text-xs font-semibold text-foreground">
|
||||
Primijenjeni popusti:
|
||||
</span>
|
||||
|
||||
{promotions.map((promotion) => (
|
||||
<div
|
||||
key={promotion.id}
|
||||
className="flex items-center justify-between text-xs"
|
||||
data-testid="discount-row"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={promotion.is_automatic ? "secondary" : "outline"} className="text-xs">
|
||||
{promotion.code}
|
||||
</Badge>
|
||||
{promotion.application_method?.value !== undefined &&
|
||||
promotion.application_method.currency_code !== undefined && (
|
||||
<span className="text-muted-foreground">
|
||||
({promotion.application_method.type === "percentage"
|
||||
? `${promotion.application_method.value}%`
|
||||
: convertToLocale({
|
||||
amount: +promotion.application_method.value,
|
||||
currency_code:
|
||||
promotion.application_method.currency_code,
|
||||
})})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{!promotion.is_automatic && (
|
||||
<button
|
||||
type="button"
|
||||
className="text-muted-foreground hover:text-destructive p-1"
|
||||
onClick={() => {
|
||||
if (promotion.code) {
|
||||
removePromotionCode(promotion.code)
|
||||
}
|
||||
}}
|
||||
data-testid="remove-discount-button"
|
||||
aria-label="Ukloni promo kod"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default DiscountCode
|
||||
@@ -0,0 +1,19 @@
|
||||
const ErrorMessage = ({
|
||||
error,
|
||||
"data-testid": dataTestid,
|
||||
}: {
|
||||
error?: string | null
|
||||
"data-testid"?: string
|
||||
}) => {
|
||||
if (!error) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="pt-1.5 text-destructive text-xs font-medium" data-testid={dataTestid}>
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ErrorMessage
|
||||
@@ -0,0 +1,167 @@
|
||||
"use client"
|
||||
|
||||
import "@adyen/adyen-web/styles/adyen.css"
|
||||
|
||||
import type {
|
||||
AdditionalDetailsActions,
|
||||
PaymentAction,
|
||||
PaymentMethodsResponse,
|
||||
ResultCode,
|
||||
SubmitActions,
|
||||
} from "@adyen/adyen-web"
|
||||
import { isAdyen } from "@lib/constants"
|
||||
import { AdyenPaymentResult, submitAdyenPayment } from "@lib/data/adyen"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import { Button } from "@modules/common/components/ui"
|
||||
import { useParams } from "next/navigation"
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import ErrorMessage from "../error-message"
|
||||
|
||||
const clientKey = process.env.NEXT_PUBLIC_ADYEN_CLIENT_KEY
|
||||
const environment =
|
||||
process.env.NEXT_PUBLIC_ADYEN_ENVIRONMENT === "live" ? "live" : "test"
|
||||
|
||||
type AdyenPaymentButtonProps = {
|
||||
cart: HttpTypes.StoreCart
|
||||
notReady: boolean
|
||||
"data-testid"?: string
|
||||
}
|
||||
|
||||
// Renders Adyen's Drop-in, whose pay button places the order. The session's data holds the
|
||||
// payment methods Drop-in offers, which are cards, Apple Pay, and Google Pay.
|
||||
const AdyenPaymentButton = ({
|
||||
cart,
|
||||
notReady,
|
||||
"data-testid": dataTestId,
|
||||
}: AdyenPaymentButtonProps) => {
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null)
|
||||
const { countryCode } = useParams()
|
||||
|
||||
const session = cart.payment_collection?.payment_sessions?.find((s) =>
|
||||
isAdyen(s.provider_id)
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!session || notReady || !clientKey || !containerRef.current) {
|
||||
return
|
||||
}
|
||||
|
||||
let cancelled = false
|
||||
let unmount: (() => void) | undefined
|
||||
|
||||
const handleResult = (
|
||||
result: AdyenPaymentResult,
|
||||
actions: SubmitActions | AdditionalDetailsActions
|
||||
) => {
|
||||
if ("action" in result) {
|
||||
actions.resolve({
|
||||
resultCode: result.resultCode as ResultCode,
|
||||
action: result.action as unknown as PaymentAction,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
setErrorMessage(result.error)
|
||||
actions.reject()
|
||||
}
|
||||
|
||||
const mount = async () => {
|
||||
const { AdyenCheckout, Dropin, Card, ApplePay, GooglePay } = await import(
|
||||
"@adyen/adyen-web"
|
||||
)
|
||||
|
||||
const checkout = await AdyenCheckout({
|
||||
clientKey,
|
||||
environment,
|
||||
locale: "en-US",
|
||||
countryCode: cart.billing_address?.country_code?.toUpperCase(),
|
||||
amount: {
|
||||
value: session.data?.amount as number,
|
||||
currency: session.data?.currency as string,
|
||||
},
|
||||
paymentMethodsResponse: session.data
|
||||
?.payment_methods as PaymentMethodsResponse,
|
||||
onSubmit: async (state, _component, actions) => {
|
||||
setErrorMessage(null)
|
||||
handleResult(
|
||||
await submitAdyenPayment({
|
||||
payment_method: state.data.paymentMethod,
|
||||
browser_info: state.data.browserInfo,
|
||||
store_payment_method: state.data.storePaymentMethod,
|
||||
origin: window.location.origin,
|
||||
// Used when the shopper's bank redirects them for authentication.
|
||||
return_url: `${window.location.origin}/api/payment-return?cart_id=${cart.id}&country_code=${countryCode}`,
|
||||
}),
|
||||
actions
|
||||
)
|
||||
},
|
||||
onAdditionalDetails: async (state, _component, actions) => {
|
||||
handleResult(
|
||||
await submitAdyenPayment({ details: state.data.details }),
|
||||
actions
|
||||
)
|
||||
},
|
||||
onError: (error) => {
|
||||
// Closing a wallet's payment sheet isn't an error worth showing.
|
||||
if (error.name !== "CANCEL") {
|
||||
setErrorMessage("Could not process the payment. Please try again.")
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
if (cancelled || !containerRef.current) {
|
||||
return
|
||||
}
|
||||
|
||||
const dropin = new Dropin(checkout, {
|
||||
paymentMethodComponents: [Card, ApplePay, GooglePay],
|
||||
paymentMethodsConfiguration: {
|
||||
card: {
|
||||
hasHolderName: true,
|
||||
holderNameRequired: true,
|
||||
// Saving cards needs an account holder, which only logged-in customers have.
|
||||
enableStoreDetails: !!session.data?.shopper_reference,
|
||||
},
|
||||
},
|
||||
}).mount(containerRef.current)
|
||||
|
||||
unmount = () => dropin.unmount()
|
||||
}
|
||||
|
||||
mount().catch(() => {
|
||||
setErrorMessage("Could not load the payment methods.")
|
||||
})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
unmount?.()
|
||||
}
|
||||
// Drop-in is mounted once per session, so the shopper's input isn't lost when the cart refreshes.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [session?.id, notReady])
|
||||
|
||||
if (notReady) {
|
||||
return (
|
||||
<Button disabled size="large" data-testid={dataTestId}>
|
||||
Place order
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div ref={containerRef} data-testid={dataTestId} />
|
||||
<ErrorMessage
|
||||
error={
|
||||
clientKey
|
||||
? errorMessage
|
||||
: "Adyen client key is missing. Set the NEXT_PUBLIC_ADYEN_CLIENT_KEY environment variable."
|
||||
}
|
||||
data-testid="adyen-payment-error-message"
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default AdyenPaymentButton
|
||||
@@ -0,0 +1,212 @@
|
||||
"use client"
|
||||
|
||||
import { isAdyen, isManual, isStripeLike } from "@lib/constants"
|
||||
import { placeOrder } from "@lib/data/cart"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import { Button } from "@modules/common/components/ui"
|
||||
import { useElements, useStripe } from "@stripe/react-stripe-js"
|
||||
import { useParams } from "next/navigation"
|
||||
import React, { useState } from "react"
|
||||
import ErrorMessage from "../error-message"
|
||||
import { getPaymentErrorMessage } from "@lib/util/payment-error"
|
||||
import AdyenPaymentButton from "./adyen-payment-button"
|
||||
|
||||
type PaymentButtonProps = {
|
||||
cart: HttpTypes.StoreCart
|
||||
"data-testid": string
|
||||
}
|
||||
|
||||
const PaymentButton: React.FC<PaymentButtonProps> = ({
|
||||
cart,
|
||||
"data-testid": dataTestId,
|
||||
}) => {
|
||||
const notReady =
|
||||
!cart ||
|
||||
!cart.shipping_address ||
|
||||
!cart.billing_address ||
|
||||
!cart.email ||
|
||||
(cart.shipping_methods?.length ?? 0) < 1
|
||||
|
||||
const paymentSession = cart.payment_collection?.payment_sessions?.[0]
|
||||
|
||||
switch (true) {
|
||||
case isStripeLike(paymentSession?.provider_id):
|
||||
return (
|
||||
<StripePaymentButton
|
||||
notReady={notReady}
|
||||
cart={cart}
|
||||
data-testid={dataTestId}
|
||||
/>
|
||||
)
|
||||
case isAdyen(paymentSession?.provider_id):
|
||||
return (
|
||||
<AdyenPaymentButton
|
||||
notReady={notReady}
|
||||
cart={cart}
|
||||
data-testid={dataTestId}
|
||||
/>
|
||||
)
|
||||
case isManual(paymentSession?.provider_id):
|
||||
return (
|
||||
<ManualTestPaymentButton notReady={notReady} data-testid={dataTestId} />
|
||||
)
|
||||
default:
|
||||
return <Button disabled>Select a payment method</Button>
|
||||
}
|
||||
}
|
||||
|
||||
const StripePaymentButton = ({
|
||||
cart,
|
||||
notReady,
|
||||
"data-testid": dataTestId,
|
||||
}: {
|
||||
cart: HttpTypes.StoreCart
|
||||
notReady: boolean
|
||||
"data-testid"?: string
|
||||
}) => {
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null)
|
||||
|
||||
const onPaymentCompleted = async () => {
|
||||
await placeOrder()
|
||||
.catch((err) => {
|
||||
setErrorMessage(err.message)
|
||||
})
|
||||
.finally(() => {
|
||||
setSubmitting(false)
|
||||
})
|
||||
}
|
||||
|
||||
const stripe = useStripe()
|
||||
const elements = useElements()
|
||||
const { countryCode } = useParams()
|
||||
|
||||
const disabled = !stripe || !elements ? true : false
|
||||
|
||||
const handlePayment = async () => {
|
||||
if (!stripe || !elements || !cart) {
|
||||
return
|
||||
}
|
||||
|
||||
setSubmitting(true)
|
||||
|
||||
await stripe
|
||||
.confirmPayment({
|
||||
elements,
|
||||
confirmParams: {
|
||||
return_url: `${window.location.origin}/api/payment-return?cart_id=${cart.id}&country_code=${countryCode}`,
|
||||
payment_method_data: {
|
||||
billing_details: {
|
||||
name:
|
||||
cart.billing_address?.first_name +
|
||||
" " +
|
||||
cart.billing_address?.last_name,
|
||||
address: {
|
||||
city: cart.billing_address?.city ?? undefined,
|
||||
country: cart.billing_address?.country_code ?? undefined,
|
||||
line1: cart.billing_address?.address_1 ?? undefined,
|
||||
line2: cart.billing_address?.address_2 ?? undefined,
|
||||
postal_code: cart.billing_address?.postal_code ?? undefined,
|
||||
state: cart.billing_address?.province ?? undefined,
|
||||
},
|
||||
email: cart.email,
|
||||
phone: cart.billing_address?.phone ?? undefined,
|
||||
},
|
||||
},
|
||||
},
|
||||
// Only leave the site when the selected method actually requires it, so
|
||||
// card payments still complete inline.
|
||||
redirect: "if_required",
|
||||
})
|
||||
.then(({ error, paymentIntent }) => {
|
||||
if (error) {
|
||||
const pi = error.payment_intent
|
||||
|
||||
if (
|
||||
(pi && pi.status === "requires_capture") ||
|
||||
(pi && pi.status === "succeeded")
|
||||
) {
|
||||
onPaymentCompleted()
|
||||
return
|
||||
}
|
||||
|
||||
setErrorMessage(getPaymentErrorMessage(error))
|
||||
setSubmitting(false)
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
paymentIntent.status === "requires_capture" ||
|
||||
paymentIntent.status === "succeeded"
|
||||
) {
|
||||
onPaymentCompleted()
|
||||
return
|
||||
}
|
||||
|
||||
setSubmitting(false)
|
||||
})
|
||||
.catch((error) => {
|
||||
setErrorMessage(getPaymentErrorMessage(error))
|
||||
setSubmitting(false)
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
disabled={disabled || notReady}
|
||||
onClick={handlePayment}
|
||||
size="large"
|
||||
isLoading={submitting}
|
||||
data-testid={dataTestId}
|
||||
>
|
||||
Place order
|
||||
</Button>
|
||||
<ErrorMessage
|
||||
error={errorMessage}
|
||||
data-testid="stripe-payment-error-message"
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const ManualTestPaymentButton = ({ notReady }: { notReady: boolean }) => {
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null)
|
||||
|
||||
const onPaymentCompleted = async () => {
|
||||
await placeOrder()
|
||||
.catch((err) => {
|
||||
setErrorMessage(err.message)
|
||||
})
|
||||
.finally(() => {
|
||||
setSubmitting(false)
|
||||
})
|
||||
}
|
||||
|
||||
const handlePayment = () => {
|
||||
setSubmitting(true)
|
||||
|
||||
onPaymentCompleted()
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
disabled={notReady}
|
||||
isLoading={submitting}
|
||||
onClick={handlePayment}
|
||||
size="large"
|
||||
data-testid="submit-order-button"
|
||||
>
|
||||
Place order
|
||||
</Button>
|
||||
<ErrorMessage
|
||||
error={errorMessage}
|
||||
data-testid="manual-payment-error-message"
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default PaymentButton
|
||||
@@ -0,0 +1,115 @@
|
||||
import { Radio as RadioGroupOption } from "@headlessui/react"
|
||||
import { Text, clx } from "@modules/common/components/ui"
|
||||
import React, { useContext } from "react"
|
||||
|
||||
import Radio from "@modules/common/components/radio"
|
||||
|
||||
import { getPaymentInfo, isManual } from "@lib/constants"
|
||||
import { getPaymentErrorMessage } from "@lib/util/payment-error"
|
||||
import SkeletonCardDetails from "@modules/skeletons/components/skeleton-card-details"
|
||||
import { PaymentElement } from "@stripe/react-stripe-js"
|
||||
import PaymentTest from "../payment-test"
|
||||
import { StripeContext } from "../payment-wrapper/stripe-wrapper"
|
||||
|
||||
type PaymentContainerProps = {
|
||||
paymentProviderId: string
|
||||
selectedPaymentOptionId: string | null
|
||||
disabled?: boolean
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
const PaymentContainer: React.FC<PaymentContainerProps> = ({
|
||||
paymentProviderId,
|
||||
selectedPaymentOptionId,
|
||||
disabled = false,
|
||||
children,
|
||||
}) => {
|
||||
const isDevelopment = process.env.NODE_ENV === "development"
|
||||
const paymentInfo = getPaymentInfo(paymentProviderId)
|
||||
|
||||
return (
|
||||
<RadioGroupOption
|
||||
key={paymentProviderId}
|
||||
value={paymentProviderId}
|
||||
disabled={disabled}
|
||||
className={clx(
|
||||
"flex flex-col gap-y-2 text-small-regular cursor-pointer py-4 border rounded-rounded px-8 mb-2 hover:shadow-borders-interactive-with-active",
|
||||
{
|
||||
"border-ui-border-interactive":
|
||||
selectedPaymentOptionId === paymentProviderId,
|
||||
}
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-between ">
|
||||
<div className="flex items-center gap-x-4">
|
||||
<Radio checked={selectedPaymentOptionId === paymentProviderId} />
|
||||
<Text className="text-base-regular">
|
||||
{paymentInfo?.title || paymentProviderId}
|
||||
</Text>
|
||||
{isManual(paymentProviderId) && isDevelopment && (
|
||||
<PaymentTest className="hidden small:block" />
|
||||
)}
|
||||
</div>
|
||||
<span className="justify-self-end text-ui-fg-base">
|
||||
{paymentInfo?.icon}
|
||||
</span>
|
||||
</div>
|
||||
{isManual(paymentProviderId) && isDevelopment && (
|
||||
<PaymentTest className="small:hidden text-[10px]" />
|
||||
)}
|
||||
{children}
|
||||
</RadioGroupOption>
|
||||
)
|
||||
}
|
||||
|
||||
export default PaymentContainer
|
||||
|
||||
export const StripePaymentContainer = ({
|
||||
paymentProviderId,
|
||||
selectedPaymentOptionId,
|
||||
disabled = false,
|
||||
setError,
|
||||
setPaymentComplete,
|
||||
}: Omit<PaymentContainerProps, "children"> & {
|
||||
setError: (error: string | null) => void
|
||||
setPaymentComplete: (complete: boolean) => void
|
||||
}) => {
|
||||
const stripeReady = useContext(StripeContext)
|
||||
|
||||
return (
|
||||
<PaymentContainer
|
||||
paymentProviderId={paymentProviderId}
|
||||
selectedPaymentOptionId={selectedPaymentOptionId}
|
||||
disabled={disabled}
|
||||
>
|
||||
{selectedPaymentOptionId === paymentProviderId &&
|
||||
(stripeReady ? (
|
||||
<div className="my-4 transition-all duration-150 ease-in-out">
|
||||
<Text className="txt-medium-plus text-ui-fg-base mb-1">
|
||||
Enter your payment details:
|
||||
</Text>
|
||||
<PaymentElement
|
||||
options={{ layout: "accordion" }}
|
||||
onChange={(e) => {
|
||||
setError(null)
|
||||
setPaymentComplete(e.complete)
|
||||
}}
|
||||
// Without a handler Stripe.js reports a failed mount as an
|
||||
// unhandled "payment Element loaderror" and the option renders
|
||||
// blank with no explanation. Surface it in the checkout's own
|
||||
// error slot instead.
|
||||
onLoadError={(e) => {
|
||||
setPaymentComplete(false)
|
||||
setError(
|
||||
getPaymentErrorMessage(e.error) ??
|
||||
"Could not load the payment methods."
|
||||
)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<SkeletonCardDetails />
|
||||
))}
|
||||
</PaymentContainer>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Badge } from "@modules/common/components/ui"
|
||||
|
||||
const PaymentTest = ({ className }: { className?: string }) => {
|
||||
return (
|
||||
<Badge color="orange" className={className}>
|
||||
<span className="font-semibold">Attention:</span> For testing purposes
|
||||
only.
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
|
||||
export default PaymentTest
|
||||
@@ -0,0 +1,65 @@
|
||||
"use client"
|
||||
|
||||
import { loadStripe, Stripe } from "@stripe/stripe-js"
|
||||
import React from "react"
|
||||
import StripeWrapper from "./stripe-wrapper"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import {
|
||||
getMedusaPaymentsAccount,
|
||||
isMedusaPayments,
|
||||
isStripeLike,
|
||||
} from "@lib/constants"
|
||||
|
||||
type PaymentWrapperProps = {
|
||||
cart: HttpTypes.StoreCart
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
const stripeKey = process.env.NEXT_PUBLIC_STRIPE_KEY
|
||||
const medusaPaymentsKey =
|
||||
process.env.NEXT_PUBLIC_MEDUSA_PAYMENTS_PUBLISHABLE_KEY
|
||||
|
||||
// loadStripe should only be called once per configuration, so we cache the promises.
|
||||
const stripePromises = new Map<string, Promise<Stripe | null>>()
|
||||
|
||||
const getStripePromise = (key: string, stripeAccount?: string) => {
|
||||
const cacheKey = `${key}:${stripeAccount ?? ""}`
|
||||
if (!stripePromises.has(cacheKey)) {
|
||||
stripePromises.set(
|
||||
cacheKey,
|
||||
loadStripe(key, stripeAccount ? { stripeAccount } : undefined)
|
||||
)
|
||||
}
|
||||
return stripePromises.get(cacheKey)!
|
||||
}
|
||||
|
||||
const PaymentWrapper: React.FC<PaymentWrapperProps> = ({ cart, children }) => {
|
||||
const paymentSession = cart.payment_collection?.payment_sessions?.find(
|
||||
(s) => s.status === "pending"
|
||||
)
|
||||
|
||||
if (paymentSession && isStripeLike(paymentSession.provider_id)) {
|
||||
// Medusa Payments creates the payment on the account's Stripe connected account,
|
||||
// so Stripe.js needs to be initialized for that account.
|
||||
const key = isMedusaPayments(paymentSession.provider_id)
|
||||
? medusaPaymentsKey
|
||||
: stripeKey
|
||||
const stripePromise = key
|
||||
? getStripePromise(key, getMedusaPaymentsAccount(paymentSession))
|
||||
: null
|
||||
|
||||
return (
|
||||
<StripeWrapper
|
||||
paymentSession={paymentSession}
|
||||
stripeKey={key}
|
||||
stripePromise={stripePromise}
|
||||
>
|
||||
{children}
|
||||
</StripeWrapper>
|
||||
)
|
||||
}
|
||||
|
||||
return <div>{children}</div>
|
||||
}
|
||||
|
||||
export default PaymentWrapper
|
||||
@@ -0,0 +1,54 @@
|
||||
"use client"
|
||||
|
||||
import { Stripe, StripeElementsOptions } from "@stripe/stripe-js"
|
||||
import { Elements } from "@stripe/react-stripe-js"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import { createContext } from "react"
|
||||
|
||||
type StripeWrapperProps = {
|
||||
paymentSession: HttpTypes.StorePaymentSession
|
||||
stripeKey?: string
|
||||
stripePromise: Promise<Stripe | null> | null
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
export const StripeContext = createContext(false)
|
||||
|
||||
const StripeWrapper: React.FC<StripeWrapperProps> = ({
|
||||
paymentSession,
|
||||
stripeKey,
|
||||
stripePromise,
|
||||
children,
|
||||
}) => {
|
||||
const options: StripeElementsOptions = {
|
||||
clientSecret: paymentSession!.data?.client_secret as string | undefined,
|
||||
}
|
||||
|
||||
if (!stripeKey) {
|
||||
throw new Error(
|
||||
"Stripe key is missing. Set the NEXT_PUBLIC_STRIPE_KEY (Stripe) or NEXT_PUBLIC_MEDUSA_PAYMENTS_PUBLISHABLE_KEY (Medusa Payments) environment variable."
|
||||
)
|
||||
}
|
||||
|
||||
if (!stripePromise) {
|
||||
throw new Error(
|
||||
"Stripe promise is missing. Make sure you have provided a valid Stripe key."
|
||||
)
|
||||
}
|
||||
|
||||
if (!paymentSession?.data?.client_secret) {
|
||||
throw new Error(
|
||||
"Stripe client secret is missing. Cannot initialize Stripe."
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<StripeContext.Provider value={true}>
|
||||
<Elements options={options} stripe={stripePromise}>
|
||||
{children}
|
||||
</Elements>
|
||||
</StripeContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export default StripeWrapper
|
||||
@@ -0,0 +1,258 @@
|
||||
"use client"
|
||||
import { RadioGroup } from "@headlessui/react"
|
||||
import { getPaymentInfo, isStripeLike } from "@lib/constants"
|
||||
import { initiatePaymentSession } from "@lib/data/cart"
|
||||
import { CheckCircle2 as CheckCircleSolid, CreditCard } from "lucide-react"
|
||||
import ErrorMessage from "@modules/checkout/components/error-message"
|
||||
import PaymentContainer, {
|
||||
StripePaymentContainer,
|
||||
} from "@modules/checkout/components/payment-container"
|
||||
import Divider from "@modules/common/components/divider"
|
||||
import {
|
||||
Button,
|
||||
Container,
|
||||
Heading,
|
||||
Text,
|
||||
clx,
|
||||
} from "@modules/common/components/ui"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation"
|
||||
import { useCallback, useEffect, useState } from "react"
|
||||
|
||||
const Payment = ({
|
||||
cart,
|
||||
availablePaymentMethods,
|
||||
}: {
|
||||
cart: HttpTypes.StoreCart
|
||||
availablePaymentMethods: { id: string }[]
|
||||
}) => {
|
||||
const activeSession = cart.payment_collection?.payment_sessions?.find(
|
||||
(paymentSession) => paymentSession.status === "pending"
|
||||
)
|
||||
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [paymentComplete, setPaymentComplete] = useState(false)
|
||||
const [selectedPaymentMethod, setSelectedPaymentMethod] = useState(
|
||||
activeSession?.provider_id ?? ""
|
||||
)
|
||||
|
||||
const searchParams = useSearchParams()
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
|
||||
const isOpen = searchParams.get("step") === "payment"
|
||||
|
||||
const setPaymentMethod = async (method: string) => {
|
||||
setError(null)
|
||||
setSelectedPaymentMethod(method)
|
||||
if (isStripeLike(method)) {
|
||||
await initiatePaymentSession(cart, {
|
||||
provider_id: method,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const paidByGiftcard = !!(
|
||||
(cart as unknown as Record<string, unknown>)?.gift_cards && ((cart as unknown as Record<string, unknown>)?.gift_cards as unknown[])?.length > 0 && cart?.total === 0
|
||||
)
|
||||
|
||||
const paymentReady =
|
||||
(activeSession && (cart?.shipping_methods?.length ?? 0) !== 0) || paidByGiftcard
|
||||
|
||||
const createQueryString = useCallback(
|
||||
(name: string, value: string) => {
|
||||
const params = new URLSearchParams(searchParams)
|
||||
params.set(name, value)
|
||||
|
||||
return params.toString()
|
||||
},
|
||||
[searchParams]
|
||||
)
|
||||
|
||||
const handleEdit = () => {
|
||||
router.push(pathname + "?" + createQueryString("step", "payment"), {
|
||||
scroll: false,
|
||||
})
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const shouldInputPaymentDetails =
|
||||
isStripeLike(selectedPaymentMethod) && !activeSession
|
||||
|
||||
const checkActiveSession =
|
||||
activeSession?.provider_id === selectedPaymentMethod
|
||||
|
||||
if (!checkActiveSession) {
|
||||
await initiatePaymentSession(cart, {
|
||||
provider_id: selectedPaymentMethod,
|
||||
})
|
||||
}
|
||||
|
||||
if (!shouldInputPaymentDetails) {
|
||||
return router.push(
|
||||
pathname + "?" + createQueryString("step", "review"),
|
||||
{
|
||||
scroll: false,
|
||||
}
|
||||
)
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err))
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setError(null)
|
||||
}, [isOpen])
|
||||
|
||||
return (
|
||||
<div className="bg-white">
|
||||
<div className="flex flex-row items-center justify-between mb-6">
|
||||
<Heading
|
||||
level="h2"
|
||||
className={clx(
|
||||
"flex flex-row text-3xl-regular gap-x-2 items-baseline",
|
||||
{
|
||||
"opacity-50 pointer-events-none select-none":
|
||||
!isOpen && !paymentReady,
|
||||
}
|
||||
)}
|
||||
>
|
||||
Payment
|
||||
{!isOpen && paymentReady && <CheckCircleSolid />}
|
||||
</Heading>
|
||||
{!isOpen && paymentReady && (
|
||||
<Text>
|
||||
<button
|
||||
onClick={handleEdit}
|
||||
className="text-ui-fg-interactive hover:text-ui-fg-interactive-hover"
|
||||
data-testid="edit-payment-button"
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
</Text>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<div className={isOpen ? "block" : "hidden"}>
|
||||
{!paidByGiftcard && availablePaymentMethods?.length && (
|
||||
<>
|
||||
<RadioGroup
|
||||
value={selectedPaymentMethod}
|
||||
onChange={(value: string) => setPaymentMethod(value)}
|
||||
>
|
||||
{availablePaymentMethods.map((paymentMethod) => (
|
||||
<div key={paymentMethod.id}>
|
||||
{isStripeLike(paymentMethod.id) ? (
|
||||
<StripePaymentContainer
|
||||
paymentProviderId={paymentMethod.id}
|
||||
selectedPaymentOptionId={selectedPaymentMethod}
|
||||
setError={setError}
|
||||
setPaymentComplete={setPaymentComplete}
|
||||
/>
|
||||
) : (
|
||||
<PaymentContainer
|
||||
paymentProviderId={paymentMethod.id}
|
||||
selectedPaymentOptionId={selectedPaymentMethod}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</RadioGroup>
|
||||
</>
|
||||
)}
|
||||
|
||||
{paidByGiftcard && (
|
||||
<div className="flex flex-col w-1/3">
|
||||
<Text className="txt-medium-plus text-ui-fg-base mb-1">
|
||||
Payment method
|
||||
</Text>
|
||||
<Text
|
||||
className="txt-medium text-ui-fg-subtle"
|
||||
data-testid="payment-method-summary"
|
||||
>
|
||||
Gift card
|
||||
</Text>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ErrorMessage
|
||||
error={error}
|
||||
data-testid="payment-method-error-message"
|
||||
/>
|
||||
|
||||
<Button
|
||||
size="large"
|
||||
className="mt-6"
|
||||
onClick={handleSubmit}
|
||||
isLoading={isLoading}
|
||||
disabled={
|
||||
(isStripeLike(selectedPaymentMethod) && !paymentComplete) ||
|
||||
(!selectedPaymentMethod && !paidByGiftcard)
|
||||
}
|
||||
data-testid="submit-payment-button"
|
||||
>
|
||||
{!activeSession && isStripeLike(selectedPaymentMethod)
|
||||
? "Enter payment details"
|
||||
: "Continue to review"}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className={isOpen ? "hidden" : "block"}>
|
||||
{cart && paymentReady && activeSession ? (
|
||||
<div className="flex items-start gap-x-1 w-full">
|
||||
<div className="flex flex-col w-1/3">
|
||||
<Text className="txt-medium-plus text-ui-fg-base mb-1">
|
||||
Payment method
|
||||
</Text>
|
||||
<Text
|
||||
className="txt-medium text-ui-fg-subtle"
|
||||
data-testid="payment-method-summary"
|
||||
>
|
||||
{getPaymentInfo(activeSession?.provider_id)?.title ||
|
||||
activeSession?.provider_id}
|
||||
</Text>
|
||||
</div>
|
||||
<div className="flex flex-col w-1/3">
|
||||
<Text className="txt-medium-plus text-ui-fg-base mb-1">
|
||||
Payment details
|
||||
</Text>
|
||||
<div
|
||||
className="flex gap-2 txt-medium text-ui-fg-subtle items-center"
|
||||
data-testid="payment-details-summary"
|
||||
>
|
||||
<Container className="flex items-center h-7 w-fit p-2 bg-ui-button-neutral-hover">
|
||||
{getPaymentInfo(selectedPaymentMethod)?.icon || (
|
||||
<CreditCard />
|
||||
)}
|
||||
</Container>
|
||||
<Text>Another step will appear</Text>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : paidByGiftcard ? (
|
||||
<div className="flex flex-col w-1/3">
|
||||
<Text className="txt-medium-plus text-ui-fg-base mb-1">
|
||||
Payment method
|
||||
</Text>
|
||||
<Text
|
||||
className="txt-medium text-ui-fg-subtle"
|
||||
data-testid="payment-method-summary"
|
||||
>
|
||||
Gift card
|
||||
</Text>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<Divider className="mt-8" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Payment
|
||||
@@ -0,0 +1,57 @@
|
||||
"use client"
|
||||
|
||||
import { Heading, Text, clx } from "@modules/common/components/ui"
|
||||
|
||||
import PaymentButton from "../payment-button"
|
||||
import { useSearchParams } from "next/navigation"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
|
||||
const Review = ({ cart }: { cart: HttpTypes.StoreCart }) => {
|
||||
const searchParams = useSearchParams()
|
||||
|
||||
const isOpen = searchParams.get("step") === "review"
|
||||
|
||||
const paidByGiftcard = !!(
|
||||
(cart as unknown as Record<string, unknown>)?.gift_cards && ((cart as unknown as Record<string, unknown>)?.gift_cards as unknown[])?.length > 0 && cart?.total === 0
|
||||
)
|
||||
|
||||
const previousStepsCompleted =
|
||||
cart.shipping_address &&
|
||||
(cart.shipping_methods?.length ?? 0) > 0 &&
|
||||
(cart.payment_collection || paidByGiftcard)
|
||||
|
||||
return (
|
||||
<div className="bg-white">
|
||||
<div className="flex flex-row items-center justify-between mb-6">
|
||||
<Heading
|
||||
level="h2"
|
||||
className={clx(
|
||||
"flex flex-row text-3xl-regular gap-x-2 items-baseline",
|
||||
{
|
||||
"opacity-50 pointer-events-none select-none": !isOpen,
|
||||
}
|
||||
)}
|
||||
>
|
||||
Review
|
||||
</Heading>
|
||||
</div>
|
||||
{isOpen && previousStepsCompleted && (
|
||||
<>
|
||||
<div className="flex items-start gap-x-1 w-full mb-6">
|
||||
<div className="w-full">
|
||||
<Text className="txt-medium-plus text-ui-fg-base mb-1">
|
||||
By clicking the Place Order button, you confirm that you have
|
||||
read, understand and accept our Terms of Use, Terms of Sale and
|
||||
Returns Policy and acknowledge that you have read Medusa
|
||||
Store's Privacy Policy.
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
<PaymentButton cart={cart} data-testid="submit-order-button" />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Review
|
||||
@@ -0,0 +1,258 @@
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import { Container } from "@modules/common/components/ui"
|
||||
import Checkbox from "@modules/common/components/checkbox"
|
||||
import Input from "@modules/common/components/input"
|
||||
import { mapKeys } from "lodash"
|
||||
import React, { useEffect, useMemo, useState } from "react"
|
||||
import AddressSelect from "../address-select"
|
||||
import CountrySelect from "../country-select"
|
||||
|
||||
const ShippingAddress = ({
|
||||
customer,
|
||||
cart,
|
||||
checked,
|
||||
onChange,
|
||||
}: {
|
||||
customer: HttpTypes.StoreCustomer | null
|
||||
cart: HttpTypes.StoreCart | null
|
||||
checked: boolean
|
||||
onChange: () => void
|
||||
}) => {
|
||||
const [formData, setFormData] = useState<Record<string, string>>({
|
||||
"shipping_address.first_name": cart?.shipping_address?.first_name || "",
|
||||
"shipping_address.last_name": cart?.shipping_address?.last_name || "",
|
||||
"shipping_address.address_1": cart?.shipping_address?.address_1 || "",
|
||||
"shipping_address.company": cart?.shipping_address?.company || "",
|
||||
"shipping_address.postal_code": cart?.shipping_address?.postal_code || "",
|
||||
"shipping_address.city": cart?.shipping_address?.city || "",
|
||||
"shipping_address.country_code": cart?.shipping_address?.country_code || "",
|
||||
"shipping_address.province": cart?.shipping_address?.province || "",
|
||||
"shipping_address.phone": cart?.shipping_address?.phone || "",
|
||||
email: cart?.email || "",
|
||||
})
|
||||
|
||||
const [isBusiness, setIsBusiness] = useState(
|
||||
Boolean((cart?.shipping_address?.metadata as any)?.is_business)
|
||||
)
|
||||
const [jib, setJib] = useState(
|
||||
((cart?.shipping_address?.metadata as any)?.jib as string) || ""
|
||||
)
|
||||
const [pdv, setPdv] = useState(
|
||||
((cart?.shipping_address?.metadata as any)?.pdv as string) || ""
|
||||
)
|
||||
|
||||
const countriesInRegion = useMemo(
|
||||
() => cart?.region?.countries?.map((c) => c.iso_2),
|
||||
[cart?.region]
|
||||
)
|
||||
|
||||
// check if customer has saved addresses that are in the current region
|
||||
const addressesInRegion = useMemo(
|
||||
() =>
|
||||
customer?.addresses.filter(
|
||||
(a) => a.country_code && countriesInRegion?.includes(a.country_code)
|
||||
),
|
||||
[customer?.addresses, countriesInRegion]
|
||||
)
|
||||
|
||||
const setFormAddress = (
|
||||
address?: HttpTypes.StoreCartAddress,
|
||||
email?: string
|
||||
) => {
|
||||
if (address) {
|
||||
setFormData((prevState: Record<string, string>) => ({
|
||||
...prevState,
|
||||
"shipping_address.first_name": address?.first_name || "",
|
||||
"shipping_address.last_name": address?.last_name || "",
|
||||
"shipping_address.address_1": address?.address_1 || "",
|
||||
"shipping_address.company": address?.company || "",
|
||||
"shipping_address.postal_code": address?.postal_code || "",
|
||||
"shipping_address.city": address?.city || "",
|
||||
"shipping_address.country_code": address?.country_code || "",
|
||||
"shipping_address.province": address?.province || "",
|
||||
"shipping_address.phone": address?.phone || "",
|
||||
}))
|
||||
}
|
||||
|
||||
if (email) {
|
||||
setFormData((prevState: Record<string, string>) => ({
|
||||
...prevState,
|
||||
email: email,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
// Ensure cart is not null and has a shipping_address before setting form data
|
||||
if (cart && cart.shipping_address) {
|
||||
setFormAddress(cart?.shipping_address, cart?.email)
|
||||
}
|
||||
|
||||
if (cart && !cart.email && customer?.email) {
|
||||
setFormAddress(undefined, customer.email)
|
||||
}
|
||||
}, [cart]) // Add cart as a dependency
|
||||
|
||||
const handleChange = (
|
||||
e: React.ChangeEvent<
|
||||
HTMLInputElement | HTMLInputElement | HTMLSelectElement
|
||||
>
|
||||
) => {
|
||||
setFormData({
|
||||
...formData,
|
||||
[e.target.name]: e.target.value,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{customer && (addressesInRegion?.length || 0) > 0 && (
|
||||
<Container className="mb-6 flex flex-col gap-y-4 p-5">
|
||||
<p className="text-small-regular">
|
||||
{`Hi ${customer.first_name}, do you want to use one of your saved addresses?`}
|
||||
</p>
|
||||
<AddressSelect
|
||||
addresses={customer.addresses}
|
||||
addressInput={
|
||||
mapKeys(formData, (_, key) =>
|
||||
key.replace("shipping_address.", "")
|
||||
) as unknown as HttpTypes.StoreCartAddress
|
||||
}
|
||||
onSelect={setFormAddress}
|
||||
/>
|
||||
</Container>
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Input
|
||||
label="First name"
|
||||
name="shipping_address.first_name"
|
||||
autoComplete="given-name"
|
||||
value={formData["shipping_address.first_name"]}
|
||||
onChange={handleChange}
|
||||
required
|
||||
data-testid="shipping-first-name-input"
|
||||
/>
|
||||
<Input
|
||||
label="Last name"
|
||||
name="shipping_address.last_name"
|
||||
autoComplete="family-name"
|
||||
value={formData["shipping_address.last_name"]}
|
||||
onChange={handleChange}
|
||||
required
|
||||
data-testid="shipping-last-name-input"
|
||||
/>
|
||||
<Input
|
||||
label="Address"
|
||||
name="shipping_address.address_1"
|
||||
autoComplete="address-line1"
|
||||
value={formData["shipping_address.address_1"]}
|
||||
onChange={handleChange}
|
||||
required
|
||||
data-testid="shipping-address-input"
|
||||
/>
|
||||
<Input
|
||||
label="Company"
|
||||
name="shipping_address.company"
|
||||
value={formData["shipping_address.company"]}
|
||||
onChange={handleChange}
|
||||
autoComplete="organization"
|
||||
data-testid="shipping-company-input"
|
||||
/>
|
||||
<div className="col-span-full my-2 p-4 rounded-xl border border-border bg-muted/30 space-y-3">
|
||||
<Checkbox
|
||||
label="Kupujem kao pravno lice (R1 račun)"
|
||||
name="is_business"
|
||||
checked={isBusiness}
|
||||
onChange={() => setIsBusiness(!isBusiness)}
|
||||
/>
|
||||
{isBusiness && (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 pt-2">
|
||||
<Input
|
||||
label="ID broj / JIB (13 cifara)"
|
||||
name="company_jib"
|
||||
placeholder="4200000000000"
|
||||
value={jib}
|
||||
onChange={(e) => setJib(e.target.value)}
|
||||
required={isBusiness}
|
||||
/>
|
||||
<Input
|
||||
label="PDV broj (12 cifara, opcionalno)"
|
||||
name="company_pdv"
|
||||
placeholder="200000000000"
|
||||
value={pdv}
|
||||
onChange={(e) => setPdv(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Input
|
||||
label="Postal code"
|
||||
name="shipping_address.postal_code"
|
||||
autoComplete="postal-code"
|
||||
value={formData["shipping_address.postal_code"]}
|
||||
onChange={handleChange}
|
||||
required
|
||||
data-testid="shipping-postal-code-input"
|
||||
/>
|
||||
<Input
|
||||
label="City"
|
||||
name="shipping_address.city"
|
||||
autoComplete="address-level2"
|
||||
value={formData["shipping_address.city"]}
|
||||
onChange={handleChange}
|
||||
required
|
||||
data-testid="shipping-city-input"
|
||||
/>
|
||||
<CountrySelect
|
||||
name="shipping_address.country_code"
|
||||
autoComplete="country"
|
||||
region={cart?.region}
|
||||
value={formData["shipping_address.country_code"]}
|
||||
onChange={handleChange}
|
||||
required
|
||||
data-testid="shipping-country-select"
|
||||
/>
|
||||
<Input
|
||||
label="State / Province"
|
||||
name="shipping_address.province"
|
||||
autoComplete="address-level1"
|
||||
value={formData["shipping_address.province"]}
|
||||
onChange={handleChange}
|
||||
data-testid="shipping-province-input"
|
||||
/>
|
||||
</div>
|
||||
<div className="my-8">
|
||||
<Checkbox
|
||||
label="Billing address same as shipping address"
|
||||
name="same_as_billing"
|
||||
checked={checked}
|
||||
onChange={onChange}
|
||||
data-testid="billing-address-checkbox"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4 mb-4">
|
||||
<Input
|
||||
label="Email"
|
||||
name="email"
|
||||
type="email"
|
||||
title="Enter a valid email address."
|
||||
autoComplete="email"
|
||||
value={formData.email}
|
||||
onChange={handleChange}
|
||||
required
|
||||
data-testid="shipping-email-input"
|
||||
/>
|
||||
<Input
|
||||
label="Phone"
|
||||
name="shipping_address.phone"
|
||||
autoComplete="tel"
|
||||
value={formData["shipping_address.phone"]}
|
||||
onChange={handleChange}
|
||||
data-testid="shipping-phone-input"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default ShippingAddress
|
||||
@@ -0,0 +1,411 @@
|
||||
"use client"
|
||||
import { Radio, RadioGroup } from "@headlessui/react"
|
||||
import { setShippingMethod } from "@lib/data/cart"
|
||||
import { calculatePriceForShippingOption } from "@lib/data/fulfillment"
|
||||
import { convertToLocale } from "@lib/util/money"
|
||||
import { CheckCircle2 as CheckCircleSolid, Loader2 as Loader } from "lucide-react"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import ErrorMessage from "@modules/checkout/components/error-message"
|
||||
import Divider from "@modules/common/components/divider"
|
||||
import MedusaRadio from "@modules/common/components/radio"
|
||||
import { Button, clx, Heading, Text } from "@modules/common/components/ui"
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation"
|
||||
import { useEffect, useState } from "react"
|
||||
|
||||
const PICKUP_OPTION_ON = "__PICKUP_ON"
|
||||
const PICKUP_OPTION_OFF = "__PICKUP_OFF"
|
||||
|
||||
type ShippingProps = {
|
||||
cart: HttpTypes.StoreCart
|
||||
availableShippingMethods: HttpTypes.StoreCartShippingOption[] | null
|
||||
}
|
||||
|
||||
function formatAddress(address: HttpTypes.StoreCartAddress) {
|
||||
if (!address) {
|
||||
return ""
|
||||
}
|
||||
|
||||
let ret = ""
|
||||
|
||||
if (address.address_1) {
|
||||
ret += ` ${address.address_1}`
|
||||
}
|
||||
|
||||
if (address.address_2) {
|
||||
ret += `, ${address.address_2}`
|
||||
}
|
||||
|
||||
if (address.postal_code) {
|
||||
ret += `, ${address.postal_code} ${address.city}`
|
||||
}
|
||||
|
||||
if (address.country_code) {
|
||||
ret += `, ${address.country_code.toUpperCase()}`
|
||||
}
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
const Shipping: React.FC<ShippingProps> = ({
|
||||
cart,
|
||||
availableShippingMethods,
|
||||
}) => {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [isLoadingPrices, setIsLoadingPrices] = useState(true)
|
||||
|
||||
const [showPickupOptions, setShowPickupOptions] =
|
||||
useState<string>(PICKUP_OPTION_OFF)
|
||||
const [calculatedPricesMap, setCalculatedPricesMap] = useState<
|
||||
Record<string, number>
|
||||
>({})
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [shippingMethodId, setShippingMethodId] = useState<string | null>(
|
||||
cart.shipping_methods?.at(-1)?.shipping_option_id || null
|
||||
)
|
||||
|
||||
const searchParams = useSearchParams()
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
|
||||
const isOpen = searchParams.get("step") === "delivery"
|
||||
|
||||
const _shippingMethods = availableShippingMethods?.filter(
|
||||
(sm) => (sm as unknown as { service_zone?: { fulfillment_set?: { type?: string; location?: { address: HttpTypes.StoreCartAddress } } } }).service_zone?.fulfillment_set?.type !== "pickup"
|
||||
)
|
||||
|
||||
const _pickupMethods = availableShippingMethods?.filter(
|
||||
(sm) => (sm as unknown as { service_zone?: { fulfillment_set?: { type?: string; location?: { address: HttpTypes.StoreCartAddress } } } }).service_zone?.fulfillment_set?.type === "pickup"
|
||||
)
|
||||
|
||||
const hasPickupOptions = !!_pickupMethods?.length
|
||||
|
||||
useEffect(() => {
|
||||
setIsLoadingPrices(true)
|
||||
|
||||
if (_shippingMethods?.length) {
|
||||
const promises = _shippingMethods
|
||||
.filter((sm) => sm.price_type === "calculated")
|
||||
.map((sm) => calculatePriceForShippingOption(sm.id, cart.id))
|
||||
|
||||
if (promises.length) {
|
||||
Promise.allSettled(promises).then((res) => {
|
||||
const pricesMap: Record<string, number> = {}
|
||||
res
|
||||
.filter((r) => r.status === "fulfilled")
|
||||
.forEach((p) => {
|
||||
if (p.value?.id) {
|
||||
pricesMap[p.value.id] = p.value.amount ?? 0
|
||||
}
|
||||
})
|
||||
|
||||
setCalculatedPricesMap(pricesMap)
|
||||
setIsLoadingPrices(false)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (_pickupMethods?.find((m) => m.id === shippingMethodId)) {
|
||||
setShowPickupOptions(PICKUP_OPTION_ON)
|
||||
}
|
||||
}, [availableShippingMethods])
|
||||
|
||||
const handleEdit = () => {
|
||||
router.push(pathname + "?step=delivery", { scroll: false })
|
||||
}
|
||||
|
||||
const handleSubmit = () => {
|
||||
router.push(pathname + "?step=payment", { scroll: false })
|
||||
}
|
||||
|
||||
const handleSetShippingMethod = async (
|
||||
id: string,
|
||||
variant: "shipping" | "pickup"
|
||||
) => {
|
||||
setError(null)
|
||||
|
||||
if (variant === "pickup") {
|
||||
setShowPickupOptions(PICKUP_OPTION_ON)
|
||||
} else {
|
||||
setShowPickupOptions(PICKUP_OPTION_OFF)
|
||||
}
|
||||
|
||||
let currentId: string | null = null
|
||||
setIsLoading(true)
|
||||
setShippingMethodId((prev) => {
|
||||
currentId = prev
|
||||
return id
|
||||
})
|
||||
|
||||
await setShippingMethod({ cartId: cart.id, shippingMethodId: id })
|
||||
.catch((err) => {
|
||||
setShippingMethodId(currentId)
|
||||
|
||||
setError(err.message)
|
||||
})
|
||||
.finally(() => {
|
||||
setIsLoading(false)
|
||||
})
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setError(null)
|
||||
}, [isOpen])
|
||||
|
||||
return (
|
||||
<div className="bg-white">
|
||||
<div className="flex flex-row items-center justify-between mb-6">
|
||||
<Heading
|
||||
level="h2"
|
||||
className={clx(
|
||||
"flex flex-row text-3xl-regular gap-x-2 items-baseline",
|
||||
{
|
||||
"opacity-50 pointer-events-none select-none":
|
||||
!isOpen && cart.shipping_methods?.length === 0,
|
||||
}
|
||||
)}
|
||||
>
|
||||
Delivery
|
||||
{!isOpen && (cart.shipping_methods?.length ?? 0) > 0 && (
|
||||
<CheckCircleSolid />
|
||||
)}
|
||||
</Heading>
|
||||
{!isOpen &&
|
||||
cart?.shipping_address &&
|
||||
cart?.billing_address &&
|
||||
cart?.email && (
|
||||
<Text>
|
||||
<button
|
||||
onClick={handleEdit}
|
||||
className="text-ui-fg-interactive hover:text-ui-fg-interactive-hover"
|
||||
data-testid="edit-delivery-button"
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
</Text>
|
||||
)}
|
||||
</div>
|
||||
{isOpen ? (
|
||||
<>
|
||||
<div className="grid">
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium txt-medium text-ui-fg-base">
|
||||
Shipping method
|
||||
</span>
|
||||
<span className="mb-4 text-ui-fg-muted txt-medium">
|
||||
How would you like you order delivered
|
||||
</span>
|
||||
</div>
|
||||
<div data-testid="delivery-options-container">
|
||||
<div className="pb-8 md:pt-0 pt-2">
|
||||
{hasPickupOptions && (
|
||||
<RadioGroup
|
||||
value={showPickupOptions}
|
||||
onChange={(_value) => {
|
||||
const id = _pickupMethods.find(
|
||||
(option) => !option.insufficient_inventory
|
||||
)?.id
|
||||
|
||||
if (id) {
|
||||
handleSetShippingMethod(id, "pickup")
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Radio
|
||||
value={PICKUP_OPTION_ON}
|
||||
data-testid="delivery-option-radio"
|
||||
className={clx(
|
||||
"flex items-center justify-between text-small-regular cursor-pointer py-4 border rounded-rounded px-8 mb-2 hover:shadow-borders-interactive-with-active",
|
||||
{
|
||||
"border-ui-border-interactive":
|
||||
showPickupOptions === PICKUP_OPTION_ON,
|
||||
}
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-x-4">
|
||||
<MedusaRadio
|
||||
checked={showPickupOptions === PICKUP_OPTION_ON}
|
||||
/>
|
||||
<span className="text-base-regular">
|
||||
Pick up your order
|
||||
</span>
|
||||
</div>
|
||||
<span className="justify-self-end text-ui-fg-base">
|
||||
-
|
||||
</span>
|
||||
</Radio>
|
||||
</RadioGroup>
|
||||
)}
|
||||
<RadioGroup
|
||||
value={shippingMethodId}
|
||||
onChange={(v) => {
|
||||
if (v) {
|
||||
return handleSetShippingMethod(v, "shipping")
|
||||
}
|
||||
}}
|
||||
>
|
||||
{_shippingMethods?.map((option) => {
|
||||
const isDisabled =
|
||||
option.price_type === "calculated" &&
|
||||
!isLoadingPrices &&
|
||||
typeof calculatedPricesMap[option.id] !== "number"
|
||||
|
||||
return (
|
||||
<Radio
|
||||
key={option.id}
|
||||
value={option.id}
|
||||
data-testid="delivery-option-radio"
|
||||
disabled={isDisabled}
|
||||
className={clx(
|
||||
"flex items-center justify-between text-small-regular cursor-pointer py-4 border rounded-rounded px-8 mb-2 hover:shadow-borders-interactive-with-active",
|
||||
{
|
||||
"border-ui-border-interactive":
|
||||
option.id === shippingMethodId,
|
||||
"hover:shadow-brders-none cursor-not-allowed":
|
||||
isDisabled,
|
||||
}
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-x-4">
|
||||
<MedusaRadio
|
||||
checked={option.id === shippingMethodId}
|
||||
/>
|
||||
<span className="text-base-regular">
|
||||
{option.name}
|
||||
</span>
|
||||
</div>
|
||||
<span className="justify-self-end text-ui-fg-base">
|
||||
{option.price_type === "flat" ? (
|
||||
convertToLocale({
|
||||
amount: option.amount!,
|
||||
currency_code: cart?.currency_code,
|
||||
})
|
||||
) : calculatedPricesMap[option.id] ? (
|
||||
convertToLocale({
|
||||
amount: calculatedPricesMap[option.id],
|
||||
currency_code: cart?.currency_code,
|
||||
})
|
||||
) : isLoadingPrices ? (
|
||||
<Loader />
|
||||
) : (
|
||||
"-"
|
||||
)}
|
||||
</span>
|
||||
</Radio>
|
||||
)
|
||||
})}
|
||||
</RadioGroup>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showPickupOptions === PICKUP_OPTION_ON && (
|
||||
<div className="grid">
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium txt-medium text-ui-fg-base">
|
||||
Store
|
||||
</span>
|
||||
<span className="mb-4 text-ui-fg-muted txt-medium">
|
||||
Choose a store near you
|
||||
</span>
|
||||
</div>
|
||||
<div data-testid="delivery-options-container">
|
||||
<div className="pb-8 md:pt-0 pt-2">
|
||||
<RadioGroup
|
||||
value={shippingMethodId}
|
||||
onChange={(v) => {
|
||||
if (v) {
|
||||
return handleSetShippingMethod(v, "pickup")
|
||||
}
|
||||
}}
|
||||
>
|
||||
{_pickupMethods?.map((option) => {
|
||||
return (
|
||||
<Radio
|
||||
key={option.id}
|
||||
value={option.id}
|
||||
disabled={option.insufficient_inventory}
|
||||
data-testid="delivery-option-radio"
|
||||
className={clx(
|
||||
"flex items-center justify-between text-small-regular cursor-pointer py-4 border rounded-rounded px-8 mb-2 hover:shadow-borders-interactive-with-active",
|
||||
{
|
||||
"border-ui-border-interactive":
|
||||
option.id === shippingMethodId,
|
||||
"hover:shadow-brders-none cursor-not-allowed":
|
||||
option.insufficient_inventory,
|
||||
}
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start gap-x-4">
|
||||
<MedusaRadio
|
||||
checked={option.id === shippingMethodId}
|
||||
/>
|
||||
<div className="flex flex-col">
|
||||
<span className="text-base-regular">
|
||||
{option.name}
|
||||
</span>
|
||||
<span className="text-base-regular text-ui-fg-muted">
|
||||
{formatAddress(
|
||||
(option as unknown as { service_zone?: { fulfillment_set?: { location?: { address: HttpTypes.StoreCartAddress } } } }).service_zone?.fulfillment_set?.location
|
||||
?.address as HttpTypes.StoreCartAddress
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<span className="justify-self-end text-ui-fg-base">
|
||||
{convertToLocale({
|
||||
amount: option.amount!,
|
||||
currency_code: cart?.currency_code,
|
||||
})}
|
||||
</span>
|
||||
</Radio>
|
||||
)
|
||||
})}
|
||||
</RadioGroup>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<ErrorMessage
|
||||
error={error}
|
||||
data-testid="delivery-option-error-message"
|
||||
/>
|
||||
<Button
|
||||
size="large"
|
||||
className="mt"
|
||||
onClick={handleSubmit}
|
||||
isLoading={isLoading}
|
||||
disabled={!cart.shipping_methods?.[0]}
|
||||
data-testid="submit-delivery-option-button"
|
||||
>
|
||||
Continue to payment
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div>
|
||||
<div className="text-small-regular">
|
||||
{cart && (cart.shipping_methods?.length ?? 0) > 0 && (
|
||||
<div className="flex flex-col w-1/3">
|
||||
<Text className="txt-medium-plus text-ui-fg-base mb-1">
|
||||
Method
|
||||
</Text>
|
||||
<Text className="txt-medium text-ui-fg-subtle">
|
||||
{cart.shipping_methods!.at(-1)!.name}{" "}
|
||||
{convertToLocale({
|
||||
amount: cart.shipping_methods!.at(-1)!.amount!,
|
||||
currency_code: cart?.currency_code,
|
||||
})}
|
||||
</Text>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<Divider className="mt-8" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Shipping
|
||||
@@ -0,0 +1,34 @@
|
||||
"use client"
|
||||
|
||||
import { Button } from "@modules/common/components/ui"
|
||||
import React from "react"
|
||||
import { useFormStatus } from "react-dom"
|
||||
|
||||
export function SubmitButton({
|
||||
children,
|
||||
variant = "primary",
|
||||
size = "medium",
|
||||
className,
|
||||
"data-testid": dataTestId,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
variant?: "primary" | "secondary" | "transparent" | null
|
||||
size?: "small" | "medium" | "large"
|
||||
className?: string
|
||||
"data-testid"?: string
|
||||
}) {
|
||||
const { pending } = useFormStatus()
|
||||
|
||||
return (
|
||||
<Button
|
||||
size={size}
|
||||
className={className}
|
||||
type="submit"
|
||||
isLoading={pending}
|
||||
variant={variant || "primary"}
|
||||
data-testid={dataTestId}
|
||||
>
|
||||
{children}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user