mirror of
https://github.com/vercel/commerce.git
synced 2025-05-12 12:47:50 +00:00
feat: core charge shouldn't be treated as a separate product
Signed-off-by: Chloe <pinkcloudvnn@gmail.com>
This commit is contained in:
parent
e2ba024761
commit
1a0d183681
@ -34,7 +34,7 @@ export async function addItem(prevState: any, selectedVariantIds: Array<string>)
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeItem(prevState: any, lineId: string) {
|
||||
export async function removeItem(prevState: any, lineIds: string[]) {
|
||||
const cartId = cookies().get('cartId')?.value;
|
||||
|
||||
if (!cartId) {
|
||||
@ -42,7 +42,7 @@ export async function removeItem(prevState: any, lineId: string) {
|
||||
}
|
||||
|
||||
try {
|
||||
await removeFromCart(cartId, [lineId]);
|
||||
await removeFromCart(cartId, lineIds);
|
||||
revalidateTag(TAGS.cart);
|
||||
} catch (e) {
|
||||
return 'Error removing item from cart';
|
||||
@ -55,7 +55,7 @@ export async function updateItemQuantity(
|
||||
lineId: string;
|
||||
variantId: string;
|
||||
quantity: number;
|
||||
}
|
||||
}[]
|
||||
) {
|
||||
const cartId = cookies().get('cartId')?.value;
|
||||
|
||||
@ -63,24 +63,28 @@ export async function updateItemQuantity(
|
||||
return 'Missing cart ID';
|
||||
}
|
||||
|
||||
const { lineId, variantId, quantity } = payload;
|
||||
const itemsToRemove = payload.filter((item) => item.quantity === 0);
|
||||
|
||||
try {
|
||||
if (quantity === 0) {
|
||||
await removeFromCart(cartId, [lineId]);
|
||||
if (itemsToRemove.length > 0) {
|
||||
await removeFromCart(
|
||||
cartId,
|
||||
itemsToRemove.map((item) => item.lineId)
|
||||
);
|
||||
revalidateTag(TAGS.cart);
|
||||
return;
|
||||
}
|
||||
|
||||
await updateCart(cartId, [
|
||||
{
|
||||
await updateCart(
|
||||
cartId,
|
||||
payload.map(({ lineId, variantId, quantity }) => ({
|
||||
id: lineId,
|
||||
merchandiseId: variantId,
|
||||
quantity
|
||||
}
|
||||
]);
|
||||
}))
|
||||
);
|
||||
revalidateTag(TAGS.cart);
|
||||
} catch (e) {
|
||||
return 'Error updating item quantity';
|
||||
return 'Error updating items quantity';
|
||||
}
|
||||
}
|
||||
|
@ -36,8 +36,11 @@ function SubmitButton() {
|
||||
|
||||
export function DeleteItemButton({ item }: { item: CartItem }) {
|
||||
const [message, formAction] = useFormState(removeItem, null);
|
||||
const itemId = item.id;
|
||||
const actionWithVariant = formAction.bind(null, itemId);
|
||||
const { id: itemId, coreCharge } = item;
|
||||
const actionWithVariant = formAction.bind(null, [
|
||||
itemId,
|
||||
...(coreCharge?.lineId ? [coreCharge.lineId] : [])
|
||||
]);
|
||||
|
||||
return (
|
||||
<form action={actionWithVariant}>
|
||||
|
@ -39,11 +39,23 @@ function SubmitButton({ type }: { type: 'plus' | 'minus' }) {
|
||||
|
||||
export function EditItemQuantityButton({ item, type }: { item: CartItem; type: 'plus' | 'minus' }) {
|
||||
const [message, formAction] = useFormState(updateItemQuantity, null);
|
||||
const payload = {
|
||||
lineId: item.id,
|
||||
variantId: item.merchandise.id,
|
||||
quantity: type === 'plus' ? item.quantity + 1 : item.quantity - 1
|
||||
};
|
||||
const quantity = type === 'plus' ? item.quantity + 1 : item.quantity - 1;
|
||||
const payload = [
|
||||
{
|
||||
lineId: item.id,
|
||||
variantId: item.merchandise.id,
|
||||
quantity
|
||||
}
|
||||
];
|
||||
|
||||
if (item.coreCharge?.lineId) {
|
||||
payload.push({
|
||||
lineId: item.coreCharge.lineId,
|
||||
variantId: item.coreCharge.id,
|
||||
quantity
|
||||
});
|
||||
}
|
||||
|
||||
const actionWithVariant = formAction.bind(null, payload);
|
||||
|
||||
return (
|
||||
|
108
components/cart/line-item.tsx
Normal file
108
components/cart/line-item.tsx
Normal file
@ -0,0 +1,108 @@
|
||||
import { PlusIcon } from '@heroicons/react/16/solid';
|
||||
import Price from 'components/price';
|
||||
import { DEFAULT_OPTION } from 'lib/constants';
|
||||
import { CartItem } from 'lib/shopify/types';
|
||||
import { createUrl } from 'lib/utils';
|
||||
import Image from 'next/image';
|
||||
import Link from 'next/link';
|
||||
import { DeleteItemButton } from './delete-item-button';
|
||||
import { EditItemQuantityButton } from './edit-item-quantity-button';
|
||||
|
||||
type LineItemProps = {
|
||||
item: CartItem;
|
||||
closeCart: () => void;
|
||||
};
|
||||
|
||||
type MerchandiseSearchParams = {
|
||||
[key: string]: string;
|
||||
};
|
||||
|
||||
const CoreCharge = ({
|
||||
coreCharge,
|
||||
quantity
|
||||
}: {
|
||||
coreCharge: CartItem['coreCharge'];
|
||||
quantity: number;
|
||||
}) => {
|
||||
if (!coreCharge) return null;
|
||||
|
||||
return (
|
||||
<div className="ml-20 mt-2 flex flex-row items-center">
|
||||
<PlusIcon className="mr-1.5 size-3" />
|
||||
<div className="flex flex-row items-center justify-start gap-2">
|
||||
{coreCharge.selectedOptions[0] ? (
|
||||
<Price
|
||||
className="text-xs font-medium"
|
||||
amount={coreCharge.selectedOptions[0].value}
|
||||
currencyCode="USD"
|
||||
/>
|
||||
) : (
|
||||
<span>Included</span>
|
||||
)}
|
||||
<span className="text-xs font-medium text-gray-700">{`x ${quantity}`}</span>
|
||||
<div className="ml-0.5 text-xs font-medium text-neutral-500">(Core Charge)</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
const LineItem = ({ item, closeCart }: LineItemProps) => {
|
||||
const merchandiseSearchParams = {} as MerchandiseSearchParams;
|
||||
|
||||
item.merchandise.selectedOptions.forEach(({ name, value }) => {
|
||||
if (value !== DEFAULT_OPTION) {
|
||||
merchandiseSearchParams[name.toLowerCase()] = value;
|
||||
}
|
||||
});
|
||||
|
||||
const merchandiseUrl = createUrl(
|
||||
`/product/${item.merchandise.product.handle}`,
|
||||
new URLSearchParams(merchandiseSearchParams)
|
||||
);
|
||||
|
||||
return (
|
||||
<li className="flex w-full flex-col border-b border-neutral-300 pb-3">
|
||||
<div className="relative flex w-full flex-row justify-between px-1 py-4">
|
||||
<div className="absolute z-40 -mt-2 ml-[55px]">
|
||||
<DeleteItemButton item={item} />
|
||||
</div>
|
||||
<Link href={merchandiseUrl} onClick={closeCart} className="z-30 flex flex-row space-x-4">
|
||||
<div className="relative h-16 w-16 cursor-pointer overflow-hidden rounded-md border border-neutral-300 bg-neutral-300 dark:border-neutral-700 dark:bg-neutral-900 dark:hover:bg-neutral-800">
|
||||
<Image
|
||||
className="h-full w-full object-cover"
|
||||
width={64}
|
||||
height={64}
|
||||
alt={item.merchandise.product.featuredImage.altText || item.merchandise.product.title}
|
||||
src={item.merchandise.product.featuredImage.url}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-1 flex-col gap-1 text-base">
|
||||
<span className="leading-tight">{item.merchandise.product.title}</span>
|
||||
{item.merchandise.title !== DEFAULT_OPTION ? (
|
||||
<p className="text-sm text-neutral-500 dark:text-neutral-400">
|
||||
{item.merchandise.title}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
<div className="ml-20 flex items-center justify-between gap-2">
|
||||
<Price
|
||||
className="font-semibold"
|
||||
amount={item.cost.totalAmount.amount}
|
||||
currencyCode={item.cost.totalAmount.currencyCode}
|
||||
/>
|
||||
<div className="flex h-9 w-fit flex-row items-center rounded-sm border border-neutral-300 dark:border-neutral-700">
|
||||
<EditItemQuantityButton item={item} type="minus" />
|
||||
<p className="w-6 text-center">
|
||||
<span className="w-full text-sm">{item.quantity}</span>
|
||||
</p>
|
||||
<EditItemQuantityButton item={item} type="plus" />
|
||||
</div>
|
||||
</div>
|
||||
<CoreCharge coreCharge={item.coreCharge} quantity={item.quantity} />
|
||||
</li>
|
||||
);
|
||||
};
|
||||
|
||||
export default LineItem;
|
@ -1,23 +1,14 @@
|
||||
'use client';
|
||||
|
||||
import { Dialog, Transition } from '@headlessui/react';
|
||||
import { Dialog, DialogPanel, Transition, TransitionChild } from '@headlessui/react';
|
||||
import { ShoppingCartIcon } from '@heroicons/react/24/outline';
|
||||
import Price from 'components/price';
|
||||
import { DEFAULT_OPTION } from 'lib/constants';
|
||||
import type { Cart } from 'lib/shopify/types';
|
||||
import { createUrl } from 'lib/utils';
|
||||
import Image from 'next/image';
|
||||
import Link from 'next/link';
|
||||
import { Fragment, useEffect, useRef, useState } from 'react';
|
||||
import CloseCart from './close-cart';
|
||||
import { DeleteItemButton } from './delete-item-button';
|
||||
import { EditItemQuantityButton } from './edit-item-quantity-button';
|
||||
import LineItem from './line-item';
|
||||
import OpenCart from './open-cart';
|
||||
|
||||
type MerchandiseSearchParams = {
|
||||
[key: string]: string;
|
||||
};
|
||||
|
||||
export default function CartModal({ cart }: { cart: Cart | undefined }) {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const quantityRef = useRef(cart?.totalQuantity);
|
||||
@ -44,7 +35,7 @@ export default function CartModal({ cart }: { cart: Cart | undefined }) {
|
||||
</button>
|
||||
<Transition show={isOpen} as={Fragment}>
|
||||
<Dialog onClose={closeCart} className="relative z-50">
|
||||
<Transition.Child
|
||||
<TransitionChild
|
||||
as={Fragment}
|
||||
enter="transition-all ease-in-out duration-300"
|
||||
enterFrom="opacity-0 backdrop-blur-none"
|
||||
@ -54,8 +45,8 @@ export default function CartModal({ cart }: { cart: Cart | undefined }) {
|
||||
leaveTo="opacity-0 backdrop-blur-none"
|
||||
>
|
||||
<div className="fixed inset-0 bg-black/30" aria-hidden="true" />
|
||||
</Transition.Child>
|
||||
<Transition.Child
|
||||
</TransitionChild>
|
||||
<TransitionChild
|
||||
as={Fragment}
|
||||
enter="transition-all ease-in-out duration-300"
|
||||
enterFrom="translate-x-full"
|
||||
@ -64,7 +55,7 @@ export default function CartModal({ cart }: { cart: Cart | undefined }) {
|
||||
leaveFrom="translate-x-0"
|
||||
leaveTo="translate-x-full"
|
||||
>
|
||||
<Dialog.Panel className="fixed bottom-0 right-0 top-0 flex h-full w-full flex-col border-l border-neutral-200 bg-white/80 p-6 text-black backdrop-blur-xl md:w-[390px] dark:border-neutral-700 dark:bg-black/80 dark:text-white">
|
||||
<DialogPanel className="fixed bottom-0 right-0 top-0 flex h-full w-full flex-col border-l border-neutral-200 bg-white/80 p-6 text-black backdrop-blur-xl dark:border-neutral-700 dark:bg-black/80 dark:text-white md:w-[390px]">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-lg font-semibold">My Cart</p>
|
||||
|
||||
@ -81,75 +72,8 @@ export default function CartModal({ cart }: { cart: Cart | undefined }) {
|
||||
) : (
|
||||
<div className="flex h-full flex-col justify-between overflow-hidden p-1">
|
||||
<ul className="flex-grow overflow-auto py-4">
|
||||
{cart.lines.map((item, i) => {
|
||||
const merchandiseSearchParams = {} as MerchandiseSearchParams;
|
||||
|
||||
item.merchandise.selectedOptions.forEach(({ name, value }) => {
|
||||
if (value !== DEFAULT_OPTION) {
|
||||
merchandiseSearchParams[name.toLowerCase()] = value;
|
||||
}
|
||||
});
|
||||
|
||||
const merchandiseUrl = createUrl(
|
||||
`/product/${item.merchandise.product.handle}`,
|
||||
new URLSearchParams(merchandiseSearchParams)
|
||||
);
|
||||
|
||||
return (
|
||||
<li
|
||||
key={i}
|
||||
className="flex w-full flex-col border-b border-neutral-300 pb-3 dark:border-neutral-700"
|
||||
>
|
||||
<div className="relative flex w-full flex-row justify-between px-1 py-4">
|
||||
<div className="absolute z-40 -mt-2 ml-[55px]">
|
||||
<DeleteItemButton item={item} />
|
||||
</div>
|
||||
<Link
|
||||
href={merchandiseUrl}
|
||||
onClick={closeCart}
|
||||
className="z-30 flex flex-row space-x-4"
|
||||
>
|
||||
<div className="relative h-16 w-16 cursor-pointer overflow-hidden rounded-md border border-neutral-300 bg-neutral-300 dark:border-neutral-700 dark:bg-neutral-900 dark:hover:bg-neutral-800">
|
||||
<Image
|
||||
className="h-full w-full object-cover"
|
||||
width={64}
|
||||
height={64}
|
||||
alt={
|
||||
item.merchandise.product.featuredImage.altText ||
|
||||
item.merchandise.product.title
|
||||
}
|
||||
src={item.merchandise.product.featuredImage.url}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-1 flex-col gap-1 text-base">
|
||||
<span className="leading-tight">
|
||||
{item.merchandise.product.title}
|
||||
</span>
|
||||
{item.merchandise.title !== DEFAULT_OPTION ? (
|
||||
<p className="text-sm text-neutral-500 dark:text-neutral-400">
|
||||
{item.merchandise.title}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
<div className="ml-20 flex flex-col gap-2">
|
||||
<Price
|
||||
className="font-semibold"
|
||||
amount={item.cost.totalAmount.amount}
|
||||
currencyCode={item.cost.totalAmount.currencyCode}
|
||||
/>
|
||||
<div className="flex h-9 w-fit flex-row items-center rounded-sm border border-neutral-300 dark:border-neutral-700">
|
||||
<EditItemQuantityButton item={item} type="minus" />
|
||||
<p className="w-6 text-center">
|
||||
<span className="w-full text-sm">{item.quantity}</span>
|
||||
</p>
|
||||
<EditItemQuantityButton item={item} type="plus" />
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
{cart.lines.map((item) => {
|
||||
return <LineItem item={item} closeCart={closeCart} key={item.id} />;
|
||||
})}
|
||||
</ul>
|
||||
<div className="py-4 text-sm text-neutral-500 dark:text-neutral-400">
|
||||
@ -182,8 +106,8 @@ export default function CartModal({ cart }: { cart: Cart | undefined }) {
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</Dialog.Panel>
|
||||
</Transition.Child>
|
||||
</DialogPanel>
|
||||
</TransitionChild>
|
||||
</Dialog>
|
||||
</Transition>
|
||||
</>
|
||||
|
@ -34,10 +34,13 @@ import { getPageQuery, getPagesQuery } from './queries/page';
|
||||
import {
|
||||
getProductQuery,
|
||||
getProductRecommendationsQuery,
|
||||
getProductVariantQuery,
|
||||
getProductsQuery
|
||||
} from './queries/product';
|
||||
import {
|
||||
Cart,
|
||||
CartItem,
|
||||
CartProductVariant,
|
||||
Collection,
|
||||
Connection,
|
||||
Filter,
|
||||
@ -49,6 +52,7 @@ import {
|
||||
PageInfo,
|
||||
Product,
|
||||
ProductVariant,
|
||||
ProductVariantOperation,
|
||||
ShopifyAddToCartOperation,
|
||||
ShopifyCart,
|
||||
ShopifyCartOperation,
|
||||
@ -377,7 +381,55 @@ export async function getCart(cartId: string): Promise<Cart | undefined> {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return reshapeCart(res.body.data.cart);
|
||||
const cart = reshapeCart(res.body.data.cart);
|
||||
|
||||
let extendedCartLines = cart.lines;
|
||||
|
||||
const lineIdMap = {} as { [key: string]: string };
|
||||
// get product variants details including core charge variant data
|
||||
const productVariantPromises =
|
||||
cart?.lines.map((line) => {
|
||||
lineIdMap[line.merchandise.id] = line.id;
|
||||
return getProductVariant(line?.merchandise.id);
|
||||
}) || [];
|
||||
|
||||
if (productVariantPromises.length) {
|
||||
const coreVariantIds = [] as string[];
|
||||
const productVariantsById = (await Promise.allSettled(productVariantPromises))
|
||||
.filter((result) => result.status === 'fulfilled')
|
||||
.reduce(
|
||||
(acc, result) => {
|
||||
const _result = result as PromiseFulfilledResult<CartProductVariant>;
|
||||
return {
|
||||
...acc,
|
||||
[_result.value.id]: { ..._result.value, lineId: lineIdMap[_result.value.id] }
|
||||
};
|
||||
},
|
||||
{} as { [key: string]: CartProductVariant & { lineId?: string } }
|
||||
);
|
||||
|
||||
// add core charge field to cart line item if any
|
||||
extendedCartLines = cart?.lines
|
||||
.reduce((lines, item) => {
|
||||
const productVariant = productVariantsById[item.merchandise.id];
|
||||
if (productVariant && productVariant.coreVariantId) {
|
||||
const coreCharge = productVariantsById[productVariant.coreVariantId];
|
||||
coreVariantIds.push(productVariant.coreVariantId);
|
||||
return lines.concat([
|
||||
{
|
||||
...item,
|
||||
coreCharge
|
||||
}
|
||||
]);
|
||||
}
|
||||
return lines;
|
||||
}, [] as CartItem[])
|
||||
.filter((item) => !coreVariantIds.includes(item.merchandise.id)); // remove core charge items from cart lines as it's not a separate line item
|
||||
}
|
||||
|
||||
const totalQuantity = extendedCartLines.reduce((sum, line) => sum + line.quantity, 0);
|
||||
|
||||
return { ...cart, totalQuantity, lines: extendedCartLines };
|
||||
}
|
||||
|
||||
export async function getCollection({
|
||||
@ -567,16 +619,17 @@ export async function getProduct(handle: string): Promise<Product | undefined> {
|
||||
return reshapeProduct(res.body.data.product, false);
|
||||
}
|
||||
|
||||
export async function getProductVariant(handle: string): Promise<Product | undefined> {
|
||||
const res = await shopifyFetch<ShopifyProductOperation>({
|
||||
query: getProductQuery,
|
||||
export async function getProductVariant(id: string) {
|
||||
const res = await shopifyFetch<ProductVariantOperation>({
|
||||
query: getProductVariantQuery,
|
||||
tags: [TAGS.products],
|
||||
variables: {
|
||||
handle
|
||||
id
|
||||
}
|
||||
});
|
||||
|
||||
return reshapeProduct(res.body.data.product, false);
|
||||
const variant = res.body.data.node;
|
||||
return { ...variant, coreVariantId: variant.coreVariantId?.value || null };
|
||||
}
|
||||
|
||||
export async function getProductRecommendations(productId: string): Promise<Product[]> {
|
||||
|
@ -35,3 +35,21 @@ export const getProductRecommendationsQuery = /* GraphQL */ `
|
||||
}
|
||||
${productFragment}
|
||||
`;
|
||||
|
||||
export const getProductVariantQuery = /* GraphQL */ `
|
||||
query getProductVariant($id: ID!) {
|
||||
node(id: $id) {
|
||||
... on ProductVariant {
|
||||
id
|
||||
title
|
||||
selectedOptions {
|
||||
name
|
||||
value
|
||||
}
|
||||
coreVariantId: metafield(namespace: "custom", key: "coreVariant") {
|
||||
value
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
@ -27,6 +27,15 @@ export type CartItem = {
|
||||
}[];
|
||||
product: Product;
|
||||
};
|
||||
coreCharge?: {
|
||||
id: string;
|
||||
title: string;
|
||||
lineId?: string;
|
||||
selectedOptions: {
|
||||
name: string;
|
||||
value: string;
|
||||
}[];
|
||||
};
|
||||
};
|
||||
|
||||
export type Collection = ShopifyCollection & {
|
||||
@ -128,6 +137,20 @@ export type ProductVariant = {
|
||||
condition: string | null;
|
||||
};
|
||||
|
||||
export type ShopifyCartProductVariant = {
|
||||
title: string;
|
||||
id: string;
|
||||
selectedOptions: {
|
||||
name: string;
|
||||
value: string;
|
||||
}[];
|
||||
coreVariantId: { value: string } | null;
|
||||
};
|
||||
|
||||
export type CartProductVariant = Omit<ShopifyCartProductVariant, 'coreVariantId'> & {
|
||||
coreVariantId: string | null;
|
||||
};
|
||||
|
||||
export type ShopifyProductVariant = Omit<
|
||||
ProductVariant,
|
||||
'coreCharge' | 'waiverAvailable' | 'coreVariantId' | 'mileage' | 'estimatedDelivery' | 'condition'
|
||||
@ -334,6 +357,13 @@ export type ShopifyProductOperation = {
|
||||
};
|
||||
};
|
||||
|
||||
export type ProductVariantOperation = {
|
||||
data: { node: ShopifyCartProductVariant };
|
||||
variables: {
|
||||
id: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type ShopifyProductRecommendationsOperation = {
|
||||
data: {
|
||||
productRecommendations: ShopifyProduct[];
|
||||
|
Loading…
x
Reference in New Issue
Block a user