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

feat: Revamp product details page and several product fixes and cleanups #6988

Merged
merged 1 commit into from
Apr 7, 2024
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./section-row"
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Text } from "@medusajs/ui"

export type SectionRowProps = {
title: string
value?: React.ReactNode | string | null
actions?: React.ReactNode
}

export const SectionRow = ({ title, value, actions }: SectionRowProps) => {
const isValueString = typeof value === "string" || !value

return (
<div
className={`text-ui-fg-subtle grid ${
!!actions ? "grid-cols-[1fr_1fr_28px]" : "grid-cols-2"
} items-center px-6 py-4`}
>
<Text size="small" weight="plus" leading="compact">
{title}
</Text>

{isValueString ? (
<Text size="small" leading="compact" className="text-pretty">
{value ?? "-"}
</Text>
) : (
<div className="flex flex-wrap gap-1">{value}</div>
)}

{actions && <div>{actions}</div>}
</div>
)
}
87 changes: 80 additions & 7 deletions packages/admin-next/dashboard/src/hooks/api/products.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,7 @@ import {
} from "@tanstack/react-query"
import { client } from "../../lib/client"
import { queryKeysFactory } from "../../lib/query-key-factory"
import {
ProductDeleteRes,
ProductListRes,
ProductRes,
} from "../../types/api-responses"
import { ProductDeleteRes, ProductRes } from "../../types/api-responses"
import { queryClient } from "../../lib/medusa"

const PRODUCTS_QUERY_KEY = "products" as const
Expand All @@ -20,6 +16,63 @@ export const productsQueryKeys = queryKeysFactory(PRODUCTS_QUERY_KEY)
const VARIANTS_QUERY_KEY = "product_variants" as const
export const variantsQueryKeys = queryKeysFactory(VARIANTS_QUERY_KEY)

const OPTIONS_QUERY_KEY = "product_options" as const
export const optionsQueryKeys = queryKeysFactory(OPTIONS_QUERY_KEY)

export const useCreateProductOption = (
productId: string,
options?: UseMutationOptions<any, Error, any>
) => {
return useMutation({
mutationFn: (payload: any) =>
client.products.createOption(productId, payload),
onSuccess: (data: any, variables: any, context: any) => {
queryClient.invalidateQueries({ queryKey: optionsQueryKeys.lists() })
options?.onSuccess?.(data, variables, context)
},
...options,
})
}

export const useUpdateProductOption = (
productId: string,
optionId: string,
options?: UseMutationOptions<any, Error, any>
) => {
return useMutation({
mutationFn: (payload: any) =>
client.products.updateOption(productId, optionId, payload),
onSuccess: (data: any, variables: any, context: any) => {
queryClient.invalidateQueries({ queryKey: optionsQueryKeys.lists() })
queryClient.invalidateQueries({
queryKey: optionsQueryKeys.detail(optionId),
})

options?.onSuccess?.(data, variables, context)
},
...options,
})
}

export const useDeleteProductOption = (
productId: string,
optionId: string,
options?: UseMutationOptions<any, Error, void>
) => {
return useMutation({
mutationFn: () => client.products.deleteOption(productId, optionId),
onSuccess: (data: any, variables: any, context: any) => {
queryClient.invalidateQueries({ queryKey: productsQueryKeys.lists() })
queryClient.invalidateQueries({
queryKey: productsQueryKeys.detail(optionId),
})

options?.onSuccess?.(data, variables, context)
},
...options,
})
}

export const useProductVariant = (
productId: string,
variantId: string,
Expand Down Expand Up @@ -55,6 +108,26 @@ export const useProductVariants = (
return { ...data, ...rest }
}

export const useUpdateProductVariant = (
productId: string,
variantId: string,
options?: UseMutationOptions<any, Error, any>
) => {
return useMutation({
mutationFn: (payload: any) =>
client.products.updateVariant(productId, variantId, payload),
onSuccess: (data: any, variables: any, context: any) => {
queryClient.invalidateQueries({ queryKey: variantsQueryKeys.lists() })
queryClient.invalidateQueries({
queryKey: variantsQueryKeys.detail(variantId),
})

options?.onSuccess?.(data, variables, context)
},
...options,
})
}

export const useDeleteVariant = (
productId: string,
variantId: string,
Expand All @@ -78,7 +151,7 @@ export const useProduct = (
id: string,
query?: Record<string, any>,
options?: Omit<
UseQueryOptions<ProductRes, Error, ProductRes, QueryKey>,
UseQueryOptions<any, Error, any, QueryKey>,
"queryFn" | "queryKey"
>
) => {
Expand All @@ -94,7 +167,7 @@ export const useProduct = (
export const useProducts = (
query?: Record<string, any>,
options?: Omit<
UseQueryOptions<ProductListRes, Error, ProductListRes, QueryKey>,
UseQueryOptions<any, Error, any, QueryKey>,
"queryFn" | "queryKey"
>
) => {
Expand Down
10 changes: 10 additions & 0 deletions packages/admin-next/dashboard/src/lib/addresses.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Address } from "@medusajs/medusa"
import { countries } from "./countries"

export const isSameAddress = (a: Address | null, b: Address | null) => {
if (!a || !b) {
Expand Down Expand Up @@ -75,3 +76,12 @@ export const getFormattedAddress = ({

return formattedAddress
}

export const getFormattedCountry = (countryCode: string | null | undefined) => {
if (!countryCode) {
return ""
}

const country = countries.find((c) => c.iso_2 === countryCode)
return country ? country.display_name : countryCode
}
42 changes: 34 additions & 8 deletions packages/admin-next/dashboard/src/lib/client/products.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
import {
ProductDeleteRes,
ProductListRes,
ProductRes,
} from "../../types/api-responses"
import { ProductDeleteRes, ProductListRes } from "../../types/api-responses"
import { deleteRequest, getRequest, postRequest } from "./common"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: add http response types to @medusajs/types

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@olivermrbl I've done a lot of any for now, I'll add all types in one go once I get everything working


async function retrieveProduct(id: string, query?: Record<string, any>) {
return getRequest<ProductRes>(`/admin/products/${id}`, query)
return getRequest<any>(`/admin/products/${id}`, query)
}

async function createProduct(payload: any) {
return postRequest<ProductRes>(`/admin/products`, payload)
return postRequest<any>(`/admin/products`, payload)
}

async function listProducts(query?: Record<string, any>) {
return getRequest<ProductListRes>(`/admin/products`, query)
}

async function updateProduct(id: string, payload: any) {
return postRequest<ProductRes>(`/admin/products/${id}`, payload)
return postRequest<any>(`/admin/products/${id}`, payload)
}

async function deleteProduct(id: string) {
Expand All @@ -40,12 +36,38 @@ async function listVariants(productId: string, query?: Record<string, any>) {
return getRequest<any>(`/admin/products/${productId}/variants`, query)
}

async function updateVariant(
productId: string,
variantId: string,
payload: any
) {
return postRequest<any>(
`/admin/products/${productId}/variants/${variantId}`,
payload
)
}

async function deleteVariant(productId: string, variantId: string) {
return deleteRequest<any>(
`/admin/products/${productId}/variants/${variantId}`
)
}

async function createOption(productId: string, payload: any) {
return postRequest<any>(`/admin/products/${productId}/options`, payload)
}

async function updateOption(productId: string, optionId: string, payload: any) {
return postRequest<any>(
`/admin/products/${productId}/options/${optionId}`,
payload
)
}

async function deleteOption(productId: string, optionId: string) {
return deleteRequest<any>(`/admin/products/${productId}/options/${optionId}`)
}

export const products = {
retrieve: retrieveProduct,
list: listProducts,
Expand All @@ -54,5 +76,9 @@ export const products = {
delete: deleteProduct,
retrieveVariant,
listVariants,
updateVariant,
deleteVariant,
createOption,
updateOption,
deleteOption,
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { zodResolver } from "@hookform/resolvers/zod"
import { Product } from "@medusajs/medusa"
import { Button, Input } from "@medusajs/ui"
import { useAdminCreateProductOption } from "medusa-react"
import { useForm } from "react-hook-form"
import { useTranslation } from "react-i18next"
import { z } from "zod"
Expand All @@ -10,6 +9,7 @@ import {
RouteDrawer,
useRouteModal,
} from "../../../../../components/route-modal"
import { useCreateProductOption } from "../../../../../hooks/api/products"

type EditProductOptionsFormProps = {
product: Product
Expand All @@ -32,7 +32,7 @@ export const CreateProductOptionForm = ({
resolver: zodResolver(CreateProductOptionSchema),
})

const { mutateAsync, isLoading } = useAdminCreateProductOption(product.id)
const { mutateAsync, isLoading } = useCreateProductOption(product.id)

const handleSubmit = form.handleSubmit(async (values) => {
mutateAsync(values, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export const CreateProductDetails = ({ form }: CreateProductPropsProps) => {
const { product_categories, isLoading: isLoadingCategories } = useCategories()

const options = form.watch("options")
const optionPermutations = permutations(options)
const optionPermutations = permutations(options ?? [])

// const { append } = useFieldArray({
// name: "images",
Expand Down Expand Up @@ -396,7 +396,7 @@ export const CreateProductDetails = ({ form }: CreateProductPropsProps) => {
control={form.control}
name="options"
render={({ field: { onChange, value } }) => {
const normalizedValue = value.map((v) => {
const normalizedValue = (value ?? []).map((v) => {
return {
key: v.title,
value: v.values.join(","),
Expand Down Expand Up @@ -443,7 +443,9 @@ export const CreateProductDetails = ({ form }: CreateProductPropsProps) => {
control={form.control}
name="variants"
render={({ field: { value, onChange, ...field } }) => {
const selectedOptions = value.map((v) => v.options)
const selectedOptions = (value ?? []).map(
(v) => v.options
)
return (
<Form.Item>
<Form.Label optional>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,6 @@ export const CreateProductForm = () => {

const form = useForm<Schema>({
defaultValues: {
title: "",
subtitle: "",
handle: "",
description: "",
discountable: true,
tags: [],
sales_channels: [],
Expand All @@ -83,11 +79,12 @@ export const CreateProductForm = () => {
length: values.length ? parseFloat(values.length) : undefined,
height: values.height ? parseFloat(values.height) : undefined,
weight: values.weight ? parseFloat(values.weight) : undefined,
variants: values.variants,
variants: values.variants.map((variant) => ({
...variant,
prices: [],
})),
} as any

delete reqData.sales_channels

await mutateAsync(reqData, {
onSuccess: ({ product }) => {
handleSuccess(`../${product.id}`)
Expand Down
Loading
Loading