Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(REFERENCE) Add gift certificates page with purchase, check, and redeem tabs #1486

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 88 additions & 2 deletions core/app/[locale]/(default)/cart/_components/cart-item.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { FragmentOf, graphql } from '~/client/graphql';
import { BcImage } from '~/components/bc-image';

import { ItemQuantity } from './item-quantity';
import { RemoveItem } from './remove-item';
import { RemoveGiftCertificate, RemoveItem } from './remove-item';

const PhysicalItemFragment = graphql(`
fragment PhysicalItemFragment on CartPhysicalItem {
Expand Down Expand Up @@ -122,6 +122,28 @@ const DigitalItemFragment = graphql(`
}
`);

const GiftCertificateItemFragment = graphql(`
fragment GiftCertificateItemFragment on CartGiftCertificate {
entityId
name
theme
amount {
currencyCode
value
}
isTaxable
sender {
email
name
}
recipient {
email
name
}
message
}
`);

export const CartItemFragment = graphql(
`
fragment CartItemFragment on CartLineItems {
Expand All @@ -131,14 +153,18 @@ export const CartItemFragment = graphql(
digitalItems {
...DigitalItemFragment
}
giftCertificates {
...GiftCertificateItemFragment
}
}
`,
[PhysicalItemFragment, DigitalItemFragment],
[PhysicalItemFragment, DigitalItemFragment, GiftCertificateItemFragment],
);

type FragmentResult = FragmentOf<typeof CartItemFragment>;
type PhysicalItem = FragmentResult['physicalItems'][number];
type DigitalItem = FragmentResult['digitalItems'][number];
type GiftCertificateItem = FragmentResult['giftCertificates'][number];

export type Product = PhysicalItem | DigitalItem;

Expand Down Expand Up @@ -263,3 +289,63 @@ export const CartItem = ({ currencyCode, product }: Props) => {
</li>
);
};

interface GiftCertificateProps {
giftCertificate: GiftCertificateItem;
currencyCode: string;
}

export const CartGiftCertificate = ({ currencyCode, giftCertificate }: GiftCertificateProps) => {
const format = useFormatter();

return (
<li>
<div className="flex gap-4 border-t border-t-gray-200 py-4 md:flex-row">
<div className="flex w-24 items-center justify-center md:w-[144px]">
<h2 className="text-lg font-bold">{giftCertificate.theme}</h2>
</div>

<div className="flex-1">
<div className="flex flex-col gap-2 md:flex-row">
<div className="flex flex-1 flex-col gap-2">
<p className="text-xl font-bold md:text-2xl">
{format.number(giftCertificate.amount.value, {
style: 'currency',
currency: currencyCode,
})}{' '}
Gift Certificate
</p>

<p className="text-md text-gray-500">{giftCertificate.message}</p>
<p className="text-sm text-gray-500">
To: {giftCertificate.recipient.name} ({giftCertificate.recipient.email})
</p>
<p className="text-sm text-gray-500">
From: {giftCertificate.sender.name} ({giftCertificate.sender.email})
</p>

<div className="hidden md:block">
<RemoveGiftCertificate currency={currencyCode} giftCertificate={giftCertificate} />
</div>
</div>

<div className="flex flex-col gap-2 md:items-end">
<div>
<p className="text-lg font-bold">
{format.number(giftCertificate.amount.value, {
style: 'currency',
currency: currencyCode,
})}
</p>
</div>
</div>
</div>

<div className="mt-4 md:hidden">
<RemoveGiftCertificate currency={currencyCode} giftCertificate={giftCertificate} />
</div>
</div>
</div>
</li>
);
};
52 changes: 52 additions & 0 deletions core/app/[locale]/(default)/cart/_components/remove-item.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { RemoveFromCartButton } from './remove-from-cart-button';
type FragmentResult = FragmentOf<typeof CartItemFragment>;
type PhysicalItem = FragmentResult['physicalItems'][number];
type DigitalItem = FragmentResult['digitalItems'][number];
type GiftCertificate = FragmentResult['giftCertificates'][number];

export type Product = PhysicalItem | DigitalItem;

Expand Down Expand Up @@ -68,3 +69,54 @@ export const RemoveItem = ({ currency, product }: Props) => {
</form>
);
};

interface GiftCertificateProps {
currency: string;
giftCertificate: GiftCertificate;
}

const giftCertificateTransform = (item: GiftCertificate) => {
return {
product_id: item.entityId.toString(),
product_name: `${item.theme} Gift Certificate`,
brand_name: undefined,
sku: undefined,
sale_price: undefined,
purchase_price: item.amount.value,
base_price: undefined,
retail_price: undefined,
currency: item.amount.currencyCode,
variant_id: undefined,
quantity: 1,
};
};

export const RemoveGiftCertificate = ({ currency, giftCertificate }: GiftCertificateProps) => {
const t = useTranslations('Cart.SubmitRemoveItem');

const onSubmitRemoveItem = async () => {
const { status } = await removeItem({
lineItemEntityId: giftCertificate.entityId,
});

if (status === 'error') {
toast.error(t('errorMessage'), {
icon: <AlertCircle className="text-error-secondary" />,
});

return;
}

bodl.cart.productRemoved({
currency,
product_value: giftCertificate.amount.value,
line_items: [giftCertificateTransform(giftCertificate)],
});
};

return (
<form action={onSubmitRemoveItem}>
<RemoveFromCartButton />
</form>
);
};
10 changes: 9 additions & 1 deletion core/app/[locale]/(default)/cart/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { client } from '~/client';
import { graphql } from '~/client/graphql';
import { TAGS } from '~/client/tags';

import { CartItem, CartItemFragment } from './_components/cart-item';
import { CartGiftCertificate, CartItem, CartItemFragment } from './_components/cart-item';
import { CartViewed } from './_components/cart-viewed';
import { CheckoutButton } from './_components/checkout-button';
import { CheckoutSummary, CheckoutSummaryFragment } from './_components/checkout-summary';
Expand Down Expand Up @@ -76,6 +76,7 @@ export default async function Cart() {
}

const lineItems = [...cart.lineItems.physicalItems, ...cart.lineItems.digitalItems];
const giftCertificates = [...cart.lineItems.giftCertificates];

return (
<div>
Expand All @@ -85,6 +86,13 @@ export default async function Cart() {
{lineItems.map((product) => (
<CartItem currencyCode={cart.currencyCode} key={product.entityId} product={product} />
))}
{giftCertificates.map((giftCertificate) => (
<CartGiftCertificate
currencyCode={cart.currencyCode}
giftCertificate={giftCertificate}
key={giftCertificate.name}
/>
))}
</ul>

<div className="col-span-1 col-start-2 lg:col-start-3">
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
'use server';

import { revalidateTag } from 'next/cache';
import { cookies } from 'next/headers';
import { getFormatter, getTranslations } from 'next-intl/server';
import { z } from 'zod';

import { addCartLineItem } from '~/client/mutations/add-cart-line-item';
import { getCart } from '~/client/queries/get-cart';
import { TAGS } from '~/client/tags';

import { createCartWithGiftCertificate } from '../_mutations/create-cart-with-gift-certificate';

const giftCertificateThemes = [
'GENERAL',
'BIRTHDAY',
'BOY',
'CELEBRATION',
'CHRISTMAS',
'GIRL',
'NONE',
] as const;

const GiftCertificateThemeSchema = z.enum(giftCertificateThemes);

const ValidatedFormDataSchema = z.object({
theme: GiftCertificateThemeSchema,
amount: z.number().positive(),
senderEmail: z.string().email(),
senderName: z.string().min(1),
recipientEmail: z.string().email(),
recipientName: z.string().min(1),
message: z.string().nullable(),
});

type ValidatedFormData = z.infer<typeof ValidatedFormDataSchema>;

const CartResponseSchema = z.object({
status: z.enum(['success', 'error']),
data: z.unknown().optional(),
error: z.string().optional(),
});

type CartResponse = z.infer<typeof CartResponseSchema>;

function parseFormData(data: FormData): ValidatedFormData {
const theme = data.get('theme');
const amount = data.get('amount');
const senderEmail = data.get('senderEmail');
const senderName = data.get('senderName');
const recipientEmail = data.get('recipientEmail');
const recipientName = data.get('recipientName');
const message = data.get('message');

// Parse and validate the form data
const validatedData = ValidatedFormDataSchema.parse({
theme,
amount: amount ? Number(amount) : undefined,
senderEmail,
senderName,
recipientEmail,
recipientName,
message: message ? String(message) : null,
});

return validatedData;
}

export async function addGiftCertificateToCart(data: FormData): Promise<CartResponse> {
const format = await getFormatter();
const t = await getTranslations('GiftCertificate.Actions.AddToCart');

try {
const validatedData = parseFormData(data);

const giftCertificate = {
name: t('certificateName', {
amount: format.number(validatedData.amount, {
style: 'currency',
currency: 'USD',
}),
}),
theme: validatedData.theme,
amount: validatedData.amount,
quantity: 1,
sender: {
email: validatedData.senderEmail,
name: validatedData.senderName,
},
recipient: {
email: validatedData.recipientEmail,
name: validatedData.recipientName,
},
message: validatedData.message,
};

const cartId = cookies().get('cartId')?.value;
let cart;

if (cartId) {
cart = await getCart(cartId);
}

if (cart) {
cart = await addCartLineItem(cart.entityId, {
giftCertificates: [giftCertificate],
});

if (!cart?.entityId) {
return CartResponseSchema.parse({
status: 'error',
error: t('error'),
});
}

revalidateTag(TAGS.cart);

return CartResponseSchema.parse({
status: 'success',
data: cart,
});
}

cart = await createCartWithGiftCertificate([giftCertificate]);

if (!cart?.entityId) {
return CartResponseSchema.parse({
status: 'error',
error: t('error'),
});
}

cookies().set({
name: 'cartId',
value: cart.entityId,
httpOnly: true,
sameSite: 'lax',
secure: true,
path: '/',
});

revalidateTag(TAGS.cart);

return CartResponseSchema.parse({
status: 'success',
data: cart,
});
} catch (error: unknown) {
if (error instanceof z.ZodError) {
// Handle validation errors
const errorMessage = error.errors
.map((err) => `${err.path.join('.')}: ${err.message}`)
.join(', ');

return CartResponseSchema.parse({
status: 'error',
error: errorMessage,
});
}

if (error instanceof Error) {
return CartResponseSchema.parse({
status: 'error',
error: error.message,
});
}

return CartResponseSchema.parse({
status: 'error',
error: t('error'),
});
}
}
Loading
Loading