1
0
mirror of https://github.com/vercel/commerce.git synced 2025-03-16 07:22:32 +00:00

Correct Variant Added to Cart

This commit is contained in:
Belen Curcio 2021-01-11 16:16:00 -03:00
parent 9bbd7feed0
commit 287e690495
7 changed files with 63 additions and 78 deletions
components
product
wishlist/WishlistCard
framework
bigcommerce
types.d.ts

@ -11,7 +11,7 @@ import { Button, Container, Text } from '@components/ui'
import usePrice from '@framework/product/use-price' import usePrice from '@framework/product/use-price'
import { useAddItem } from '@framework/cart' import { useAddItem } from '@framework/cart'
import { getCurrentVariant, SelectedOptions } from '../helpers' import { getVariant, SelectedOptions } from '../helpers'
import WishlistButton from '@components/wishlist/WishlistButton' import WishlistButton from '@components/wishlist/WishlistButton'
interface Props { interface Props {
@ -27,23 +27,24 @@ const ProductView: FC<Props> = ({ product }) => {
baseAmount: product.price.retailValue, baseAmount: product.price.retailValue,
currencyCode: product.price.currencyCode!, currencyCode: product.price.currencyCode!,
}) })
const { openSidebar } = useUI() const { openSidebar } = useUI()
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const [choices, setChoices] = useState<SelectedOptions>({ const [choices, setChoices] = useState<SelectedOptions>({
size: null, size: null,
color: null, color: null,
}) })
// const variant = getCurrentVariant(product, choices) || product.variants[0] // Select the correct variant based on choices
console.log('PRODUCT VIEW', product) const variant = getVariant(product, choices)
const addToCart = async () => { const addToCart = async () => {
setLoading(true) setLoading(true)
try { try {
await addItem({ await addItem({
productId: Number(product.id), productId: Number(product.id),
variantId: Number(product.variants[0].id), // TODO(bc) send the correct variant variantId: variant
? Number(variant.id)
: Number(product.variants[0].id),
}) })
openSidebar() openSidebar()
setLoading(false) setLoading(false)
@ -108,11 +109,14 @@ const ProductView: FC<Props> = ({ product }) => {
<h2 className="uppercase font-medium">{opt.displayName}</h2> <h2 className="uppercase font-medium">{opt.displayName}</h2>
<div className="flex flex-row py-4"> <div className="flex flex-row py-4">
{opt.values.map((v, i: number) => { {opt.values.map((v, i: number) => {
const active = (choices as any)[opt.displayName] const active = (choices as any)[
opt.displayName.toLowerCase()
]
return ( return (
<Swatch <Swatch
key={`${opt.id}-${i}`} key={`${opt.id}-${i}`}
active={v.label === active} active={v.label.toLowerCase() === active}
variant={opt.displayName} variant={opt.displayName}
color={v.hexColors ? v.hexColors[0] : ''} color={v.hexColors ? v.hexColors[0] : ''}
label={v.label} label={v.label}
@ -120,7 +124,7 @@ const ProductView: FC<Props> = ({ product }) => {
setChoices((choices) => { setChoices((choices) => {
return { return {
...choices, ...choices,
[opt.displayName]: v.label, [opt.displayName.toLowerCase()]: v.label.toLowerCase(),
} }
}) })
}} }}
@ -142,6 +146,7 @@ const ProductView: FC<Props> = ({ product }) => {
className={s.button} className={s.button}
onClick={addToCart} onClick={addToCart}
loading={loading} loading={loading}
disabled={!variant}
> >
Add to Cart Add to Cart
</Button> </Button>

@ -1,5 +1,3 @@
import type { ProductNode } from '@framework/api/operations/get-product'
export type SelectedOptions = { export type SelectedOptions = {
size: string | null size: string | null
color: string | null color: string | null
@ -10,42 +8,18 @@ export type ProductOption = {
values: any values: any
} }
// Returns the available options of a product export function getVariant(product: Product, opts: SelectedOptions) {
export function getProductOptions(product: ProductNode) { const variant = product.variants.find((variant) => {
const options = product.productOptions.edges?.reduce<ProductOption[]>(
(arr, edge) => {
if (edge?.node.__typename === 'MultipleChoiceOption') {
arr.push({
displayName: edge.node.displayName.toLowerCase(),
values: edge.node.values.edges?.map((edge) => edge?.node),
})
}
return arr
},
[]
)
return options
}
// Finds a variant in the product that matches the selected options
export function getCurrentVariant(product: ProductNode, opts: SelectedOptions) {
const variant = product.variants.edges?.find((edge) => {
const { node } = edge ?? {}
return Object.entries(opts).every(([key, value]) => return Object.entries(opts).every(([key, value]) =>
node?.productOptions.edges?.find((edge) => { variant.options.find((option) => {
if ( if (
edge?.node.__typename === 'MultipleChoiceOption' && option.__typename === 'MultipleChoiceOption' &&
edge.node.displayName.toLowerCase() === key option.displayName.toLowerCase() === key.toLowerCase()
) { ) {
return edge.node.values.edges?.find( return option.values.find((v) => v.label.toLowerCase() === value)
(valueEdge) => valueEdge?.node.label === value
)
} }
}) })
) )
}) })
return variant return variant
} }

@ -2,21 +2,20 @@ import { FC, useState } from 'react'
import cn from 'classnames' import cn from 'classnames'
import Link from 'next/link' import Link from 'next/link'
import Image from 'next/image' import Image from 'next/image'
import type { WishlistItem } from '@framework/api/wishlist'
import usePrice from '@framework/product/use-price'
import useRemoveItem from '@framework/wishlist/use-remove-item'
import useAddItem from '@framework/cart/use-add-item'
import { useUI } from '@components/ui/context'
import { Button, Text } from '@components/ui'
import { Trash } from '@components/icons'
import s from './WishlistCard.module.css' import s from './WishlistCard.module.css'
import { Trash } from '@components/icons'
import { Button, Text } from '@components/ui'
import { useUI } from '@components/ui/context'
import usePrice from '@framework/product/use-price'
import useAddItem from '@framework/cart/use-add-item'
import useRemoveItem from '@framework/wishlist/use-remove-item'
interface Props { interface Props {
item: WishlistItem product: Product
} }
const WishlistCard: FC<Props> = ({ item }) => { const WishlistCard: FC<Props> = ({ product }) => {
const product = item.product!
const { price } = usePrice({ const { price } = usePrice({
amount: product.prices?.price?.value, amount: product.prices?.price?.value,
baseAmount: product.prices?.retailPrice?.value, baseAmount: product.prices?.retailPrice?.value,
@ -34,7 +33,7 @@ const WishlistCard: FC<Props> = ({ item }) => {
try { try {
// If this action succeeds then there's no need to do `setRemoving(true)` // If this action succeeds then there's no need to do `setRemoving(true)`
// because the component will be removed from the view // because the component will be removed from the view
await removeItem({ id: item.id! }) await removeItem({ id: product.id! })
} catch (error) { } catch (error) {
setRemoving(false) setRemoving(false)
} }
@ -43,8 +42,8 @@ const WishlistCard: FC<Props> = ({ item }) => {
setLoading(true) setLoading(true)
try { try {
await addItem({ await addItem({
productId: product.entityId, productId: Number(product.id),
variantId: product.variants.edges?.[0]?.node.entityId!, variantId: Number(product.variants[0].id),
}) })
openSidebar() openSidebar()
setLoading(false) setLoading(false)
@ -57,10 +56,10 @@ const WishlistCard: FC<Props> = ({ item }) => {
<div className={cn(s.root, { 'opacity-75 pointer-events-none': removing })}> <div className={cn(s.root, { 'opacity-75 pointer-events-none': removing })}>
<div className={`col-span-3 ${s.productBg}`}> <div className={`col-span-3 ${s.productBg}`}>
<Image <Image
src={product.images.edges?.[0]?.node.urlOriginal!} src={product.images[0].url}
width={400} width={400}
height={400} height={400}
alt={product.images.edges?.[0]?.node.altText || 'Product Image'} alt={product.images[0].alt || 'Product Image'}
/> />
</div> </div>

@ -21,7 +21,7 @@ export type ProductsHandlers = {
const METHODS = ['GET'] const METHODS = ['GET']
// TODO: a complete implementation should have schema validation for `req.body` // TODO(lf): a complete implementation should have schema validation for `req.body`
const productsApi: BigcommerceApiHandler< const productsApi: BigcommerceApiHandler<
SearchProductsData, SearchProductsData,
ProductsHandlers ProductsHandlers

@ -1,5 +1,19 @@
import { Product as BCProduct } from '@framework/schema' import { Product as BCProduct } from '@framework/schema'
function productOptionNormalize({
node: {
entityId,
values: { edges },
...rest
},
}: any) {
return {
id: entityId,
values: edges.map(({ node }: any) => node),
...rest,
}
}
export function normalizeProduct(productNode: BCProduct): Product { export function normalizeProduct(productNode: BCProduct): Product {
const { const {
entityId: id, entityId: id,
@ -10,6 +24,7 @@ export function normalizeProduct(productNode: BCProduct): Product {
path, path,
id: _, id: _,
options: _0, options: _0,
brand,
...rest ...rest
} = productNode } = productNode
@ -27,26 +42,21 @@ export function normalizeProduct(productNode: BCProduct): Product {
) )
: [], : [],
variants: variants.edges variants: variants.edges
? variants.edges.map(({ node: { entityId, ...rest } }: any) => ({ ? variants.edges.map(
id: entityId, ({ node: { entityId, productOptions, ...rest } }: any) => ({
...rest,
}))
: [],
options: productOptions.edges
? productOptions.edges.map(
({
node: {
entityId,
values: { edges },
...rest
},
}: any) => ({
id: entityId, id: entityId,
values: edges.map(({ node }: any) => node), options: productOptions.edges.map(productOptionNormalize),
...rest, ...rest,
}) })
) )
: [], : [],
options: productOptions.edges
? productOptions.edges.map(productOptionNormalize)
: [],
brand: {
id: brand?.entityId,
...brand,
},
price: { price: {
value: prices?.price.value, value: prices?.price.value,
currencyCode: prices?.price.currencyCode, currencyCode: prices?.price.currencyCode,

@ -46,7 +46,7 @@ export function extendHook(
const response = useCommerceWishlist( const response = useCommerceWishlist(
defaultOpts, defaultOpts,
[ [
['customerId', customer?.entityId], ['customerId', customer?.id],
['includeProducts', includeProducts], ['includeProducts', includeProducts],
], ],
customFetcher, customFetcher,

@ -31,6 +31,7 @@ interface ProductImage {
interface ProductVariant { interface ProductVariant {
id: string | number id: string | number
options: ProductOption[]
} }
interface ProductPrice { interface ProductPrice {
@ -51,21 +52,17 @@ interface Wishlist extends Entity {
interface Order {} interface Order {}
interface Customer extends Entity { interface Customer extends Entity {}
[prop: string]: any
}
type UseCustomerResponse = { type UseCustomerResponse = {
customer: Customer customer: Customer
} | null } | null
interface Category extends Entity { interface Category extends Entity {
id: string
name: string name: string
} }
interface Brand extends Entity { interface Brand extends Entity {
id: string
name: string name: string
} }