-
Notifications
You must be signed in to change notification settings - Fork 220
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(core): allow applying coupons to cart
- Loading branch information
Showing
9 changed files
with
300 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
"@bigcommerce/catalyst-core": minor | ||
--- | ||
|
||
Allow applying and removing coupons in cart |
34 changes: 34 additions & 0 deletions
34
apps/core/app/[locale]/(default)/cart/_actions/apply-coupon-code.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
'use server'; | ||
|
||
import { revalidateTag } from 'next/cache'; | ||
import { z } from 'zod'; | ||
|
||
import { applyCheckoutCoupon } from '~/client/mutations/apply-checkout-coupon'; | ||
|
||
const ApplyCouponCodeSchema = z.object({ | ||
couponCode: z.string(), | ||
}); | ||
|
||
export async function applyCouponCode(formData: FormData, checkoutEntityId: string) { | ||
try { | ||
const parsedData = ApplyCouponCodeSchema.parse({ | ||
couponCode: formData.get('couponCode'), | ||
}); | ||
|
||
const checkout = await applyCheckoutCoupon(checkoutEntityId, parsedData.couponCode); | ||
|
||
if (!checkout?.entityId) { | ||
return { status: 'error', error: 'Coupon code is invalid' }; | ||
} | ||
|
||
revalidateTag('checkout'); | ||
|
||
return { status: 'success', data: checkout }; | ||
} catch (e: unknown) { | ||
if (e instanceof Error || e instanceof z.ZodError) { | ||
return { status: 'error', error: e.message }; | ||
} | ||
|
||
return { status: 'error' }; | ||
} | ||
} |
34 changes: 34 additions & 0 deletions
34
apps/core/app/[locale]/(default)/cart/_actions/remove-coupon-code.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
'use server'; | ||
|
||
import { revalidateTag } from 'next/cache'; | ||
import { z } from 'zod'; | ||
|
||
import { unapplyCheckoutCoupon } from '~/client/mutations/unapply-checkout-coupon'; | ||
|
||
const RemoveCouponCodeSchema = z.object({ | ||
couponCode: z.string(), | ||
}); | ||
|
||
export async function removeCouponCode(formData: FormData, checkoutEntityId: string) { | ||
try { | ||
const parsedData = RemoveCouponCodeSchema.parse({ | ||
couponCode: formData.get('couponCode'), | ||
}); | ||
|
||
const checkout = await unapplyCheckoutCoupon(checkoutEntityId, parsedData.couponCode); | ||
|
||
if (!checkout?.entityId) { | ||
return { status: 'error', error: 'Error ocurred removing coupon' }; | ||
} | ||
|
||
revalidateTag('checkout'); | ||
|
||
return { status: 'success', data: checkout }; | ||
} catch (e: unknown) { | ||
if (e instanceof Error || e instanceof z.ZodError) { | ||
return { status: 'error', error: e.message }; | ||
} | ||
|
||
return { status: 'error' }; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
129 changes: 129 additions & 0 deletions
129
apps/core/app/[locale]/(default)/cart/_components/coupon-codes.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,129 @@ | ||
'use client'; | ||
|
||
import { Button } from '@bigcommerce/components/button'; | ||
import { Field, FieldControl, FieldMessage, Form, FormSubmit } from '@bigcommerce/components/form'; | ||
import { Input } from '@bigcommerce/components/input'; | ||
import { AlertCircle, Loader2 as Spinner } from 'lucide-react'; | ||
import { useTranslations } from 'next-intl'; | ||
import { useEffect, useState } from 'react'; | ||
import { useFormStatus } from 'react-dom'; | ||
import { toast } from 'react-hot-toast'; | ||
|
||
import { getCheckout } from '~/client/queries/get-checkout'; | ||
import { ExistingResultType } from '~/client/util'; | ||
|
||
import { applyCouponCode } from '../_actions/apply-coupon-code'; | ||
import { removeCouponCode } from '../_actions/remove-coupon-code'; | ||
|
||
type Checkout = ExistingResultType<typeof getCheckout>; | ||
|
||
const SubmitButton = () => { | ||
const t = useTranslations('Cart.SubmitCouponCode'); | ||
const { pending } = useFormStatus(); | ||
|
||
return ( | ||
<Button className="items-center px-8 py-2" disabled={pending} variant="secondary"> | ||
{pending ? ( | ||
<> | ||
<Spinner aria-hidden="true" className="animate-spin" /> | ||
<span className="sr-only">{t('spinnerText')}</span> | ||
</> | ||
) : ( | ||
<span>{t('submitText')}</span> | ||
)} | ||
</Button> | ||
); | ||
}; | ||
|
||
export const CouponCodes = ({ checkout }: { checkout: ExistingResultType<typeof getCheckout> }) => { | ||
const t = useTranslations('Cart.CheckoutSummary'); | ||
const [showAddCoupon, setShowAddCoupon] = useState(false); | ||
const [selectedCoupon, setSelectedCoupon] = useState<Checkout['coupons'][number] | null>( | ||
checkout.coupons[0] || null, | ||
); | ||
|
||
const currencyFormatter = new Intl.NumberFormat('en-US', { | ||
style: 'currency', | ||
currency: checkout.cart?.currencyCode, | ||
}); | ||
|
||
useEffect(() => { | ||
if (checkout.coupons[0]) { | ||
setSelectedCoupon(checkout.coupons[0]); | ||
|
||
return; | ||
} | ||
|
||
setSelectedCoupon(null); | ||
}, [checkout]); | ||
|
||
const onSubmitApplyCouponCode = async (formData: FormData) => { | ||
const { status } = await applyCouponCode(formData, checkout.entityId); | ||
|
||
if (status === 'error') { | ||
toast.error(t('couponCodeInvalid'), { | ||
icon: <AlertCircle className="text-error-secondary" />, | ||
}); | ||
} | ||
}; | ||
|
||
const onSubmitRemoveCouponCode = async (formData: FormData) => { | ||
const { status } = await removeCouponCode(formData, checkout.entityId); | ||
|
||
if (status === 'error') { | ||
toast.error(t('couponCodeRemoveFailed'), { | ||
icon: <AlertCircle className="text-error-secondary" />, | ||
}); | ||
} | ||
}; | ||
|
||
return selectedCoupon ? ( | ||
<div className="flex flex-col gap-2 border-t border-t-gray-200 py-4"> | ||
<div className="flex justify-between"> | ||
<span className="font-semibold"> | ||
{t('coupon')} ({selectedCoupon.code}) | ||
</span> | ||
<span>{currencyFormatter.format(selectedCoupon.discountedAmount.value * -1)}</span> | ||
</div> | ||
<form action={onSubmitRemoveCouponCode}> | ||
<input name="couponCode" type="hidden" value={selectedCoupon.code} /> | ||
<Button | ||
className="w-fit p-0 text-primary hover:bg-transparent" | ||
type="submit" | ||
variant="subtle" | ||
> | ||
{t('remove')} | ||
</Button> | ||
</form> | ||
</div> | ||
) : ( | ||
<div className="flex flex-col gap-2 border-t border-t-gray-200 py-4"> | ||
<div className="flex justify-between"> | ||
<span className="font-semibold">{t('couponCode')}</span> | ||
<Button | ||
className="w-fit p-0 text-primary hover:bg-transparent" | ||
onClick={() => setShowAddCoupon((open) => !open)} | ||
type="submit" | ||
variant="subtle" | ||
> | ||
{showAddCoupon ? t('cancel') : t('add')} | ||
</Button> | ||
</div> | ||
{showAddCoupon && ( | ||
<Form action={onSubmitApplyCouponCode} className="my-4 flex flex-col gap-2"> | ||
<Field name="couponCode"> | ||
<FieldControl asChild> | ||
<Input aria-label="" placeholder={t('enterCouponCode')} required type="text" /> | ||
</FieldControl> | ||
<FieldMessage className="text-xs text-error" match="valueMissing"> | ||
{t('couponCodeRequired')} | ||
</FieldMessage> | ||
</Field> | ||
<FormSubmit asChild> | ||
<SubmitButton /> | ||
</FormSubmit> | ||
</Form> | ||
)} | ||
</div> | ||
); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import { getSessionCustomerId } from '~/auth'; | ||
|
||
import { client } from '..'; | ||
import { graphql } from '../graphql'; | ||
|
||
const APPLY_CHECKOUT_COUPON = graphql(` | ||
mutation ApplyCheckoutCoupon($applyCheckoutCouponInput: ApplyCheckoutCouponInput!) { | ||
checkout { | ||
applyCheckoutCoupon(input: $applyCheckoutCouponInput) { | ||
checkout { | ||
entityId | ||
} | ||
} | ||
} | ||
} | ||
`); | ||
|
||
export const applyCheckoutCoupon = async (checkoutEntityId: string, couponCode: string) => { | ||
const customerId = await getSessionCustomerId(); | ||
|
||
const response = await client.fetch({ | ||
document: APPLY_CHECKOUT_COUPON, | ||
variables: { | ||
applyCheckoutCouponInput: { | ||
checkoutEntityId, | ||
data: { | ||
couponCode, | ||
}, | ||
}, | ||
}, | ||
customerId: Number(customerId), | ||
fetchOptions: { cache: 'no-store' }, | ||
}); | ||
|
||
return response.data.checkout.applyCheckoutCoupon?.checkout; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import { getSessionCustomerId } from '~/auth'; | ||
|
||
import { client } from '..'; | ||
import { graphql } from '../graphql'; | ||
|
||
const UNAPPLY_CHECKOUT_COUPON = graphql(` | ||
mutation UnapplyCheckoutCoupon($unapplyCheckoutCouponInput: UnapplyCheckoutCouponInput!) { | ||
checkout { | ||
unapplyCheckoutCoupon(input: $unapplyCheckoutCouponInput) { | ||
checkout { | ||
entityId | ||
} | ||
} | ||
} | ||
} | ||
`); | ||
|
||
export const unapplyCheckoutCoupon = async (checkoutEntityId: string, couponCode: string) => { | ||
const customerId = await getSessionCustomerId(); | ||
|
||
const response = await client.fetch({ | ||
document: UNAPPLY_CHECKOUT_COUPON, | ||
variables: { | ||
unapplyCheckoutCouponInput: { | ||
checkoutEntityId, | ||
data: { | ||
couponCode, | ||
}, | ||
}, | ||
}, | ||
customerId: Number(customerId), | ||
fetchOptions: { cache: 'no-store' }, | ||
}); | ||
|
||
return response.data.checkout.unapplyCheckoutCoupon?.checkout; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters