Skip to content
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
72 changes: 2 additions & 70 deletions src/hooks/api/products.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -388,16 +388,7 @@ export const useProducts = (
QueryKey
>,
"queryFn" | "queryKey"
>,
filter?: HttpTypes.AdminProductListParams & {
tagId?: string | string[]
categoryId?: string | string[]
collectionId?: string | string[]
typeId?: string | string[]
status?: string | string[]
q?: string
sort?: string
}
>
) => {
const { data, ...rest } = useQuery({
queryFn: () =>
Expand All @@ -409,66 +400,7 @@ export const useProducts = (
...options,
})

let products = data?.products || []

// Apply filters if any exist
if (
filter?.q ||
filter?.categoryId ||
filter?.tagId ||
filter?.collectionId ||
filter?.typeId ||
filter?.status
) {
products = products.filter((item) => {
if (filter.q) {
return item.title.toLowerCase().includes(filter.q.toLowerCase())
}

return (
(filter.categoryId &&
checkCategoryMatch(item?.categories, filter.categoryId)) ||
(filter.tagId && checkTagMatch(item?.tags, filter.tagId)) ||
(filter.collectionId &&
checkCollectionMatch(item?.collection, filter.collectionId)) ||
(filter.typeId && checkTypeMatch(item?.type_id, filter.typeId)) ||
(filter.status && checkStatusMatch(item?.status, filter.status))
)
})
}

// Apply sorting if specified
if (filter?.sort) {
const isDescending = filter.sort.startsWith("-")
const field = isDescending ? filter.sort.slice(1) : filter.sort

if (["title", "created_at", "updated_at"].includes(field)) {
products = [...products].sort((a, b) => {
const aValue = a[field as keyof HttpTypes.AdminProduct]
const bValue = b[field as keyof HttpTypes.AdminProduct]

if (field === "title") {
const titleA = String(aValue || "")
const titleB = String(bValue || "")
return isDescending
? titleB.localeCompare(titleA)
: titleA.localeCompare(titleB)
}

// For dates
const dateA = new Date((aValue as string) || new Date()).getTime()
const dateB = new Date((bValue as string) || new Date()).getTime()
return isDescending ? dateB - dateA : dateA - dateB
})
}
}

return {
...data,
products: productsImagesFormatter(products?.slice(0, filter?.limit)) || [],
count: products?.length || 0,
...rest,
}
return { ...data, ...rest }
}

export const useCreateProduct = (
Expand Down
18 changes: 5 additions & 13 deletions src/lib/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const sdk = new Medusa({

// useful when you want to call the BE from the console and try things out quickly
if (typeof window !== "undefined") {
;(window as any).__sdk = sdk
; (window as any).__sdk = sdk
}

export const importProductsQuery = async (file: File) => {
Expand Down Expand Up @@ -65,18 +65,10 @@ export const fetchQuery = async (
}
) => {
const bearer = (await window.localStorage.getItem("medusa_auth_token")) || ""
const params = Object.entries(query || {}).reduce(
(acc, [key, value], index) => {
if (value && value !== undefined) {
const queryLength = Object.values(query || {}).filter(
(i) => i && i !== undefined
).length
acc += `${key}=${value}${index + 1 <= queryLength ? "&" : ""}`
}
return acc
},
""
)
const params = Object.entries(query || {})
.filter(([, value]) => value !== undefined && value !== null && value !== '')
.map(([key, value]) => `${key}=${value}`)
.join('&')
const response = await fetch(`${backendUrl}${url}${params && `?${params}`}`, {
method: method,
headers: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import { useProductTableQuery } from "../../../../../hooks/table/query/use-produ
import { useDataTable } from "../../../../../hooks/use-data-table"
import { PriceListCreateProductsSchema } from "../../../common/schemas"
import { PricingCreateSchemaType } from "./schema"
import { useLoaderData } from "react-router-dom"
import { productsLoader } from "../../../../products/product-list/loader"

type PriceListProductsFormProps = {
form: UseFormReturn<PricingCreateSchemaType>
Expand Down Expand Up @@ -54,12 +56,20 @@ export const PriceListProductsForm = ({ form }: PriceListProductsFormProps) => {
const { searchParams, raw } = useProductTableQuery({
pageSize: PAGE_SIZE,
prefix: PREFIX,

})

const initialData = useLoaderData() as Awaited<
ReturnType<ReturnType<typeof productsLoader>>
>

const options = {
initialData,
placeholderData: keepPreviousData,
}
const { products, count, isLoading, isError, error } = useProducts(
{ ...searchParams, fields: "+thumbnail" },
{
placeholderData: keepPreviousData,
}
{ ...searchParams, fields: "+thumbnail,+created_at,+updated_at,+status" },
options
)

const updater: OnChangeFn<RowSelectionState> = (fn) => {
Expand Down Expand Up @@ -101,7 +111,7 @@ export const PriceListProductsForm = ({ form }: PriceListProductsFormProps) => {
const { table } = useDataTable({
data: products || [],
columns,
count,
count: count,
enablePagination: true,
enableRowSelection: (row) => {
return !!row.original.variants?.length
Expand All @@ -112,6 +122,7 @@ export const PriceListProductsForm = ({ form }: PriceListProductsFormProps) => {
updater,
},
pageSize: PAGE_SIZE,
prefix: PREFIX,
})

if (isError) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ export const PriceListPricesAddProductIdsForm = ({
updater,
},
pageSize: PAGE_SIZE,
prefix: PREFIX,
meta: {
variantIdMap,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,49 +55,24 @@ export const ProductListTable = () => {
pageSize: PAGE_SIZE,
})

const query = {
limit: 100,
offset: 0,
fields: "+thumbnail,*categories,+status",
}

const options = {
initialData,
placeholderData: keepPreviousData,
}

const filter = {
collectionId: searchParams.collection_id,
categoryId: searchParams.category_id,
typeId: searchParams.type_id,
tagId: searchParams.tagId,
status: searchParams.status,
q: searchParams.q,
sort: searchParams.order,
}

const { products, count, isLoading, isError, error } = useProducts(
query,
{ ...searchParams, fields: "+thumbnail,*categories,+status,+created_at,+updated_at" },
options,
filter
)

const offset = searchParams.offset || 0

const processedProducts = (products as HttpTypes.AdminProduct[])?.slice(
offset,
offset + PAGE_SIZE
)
const processedCount =
count < (products?.length || 0) ? count : products?.length || 0

const filters = useProductTableFilters()
const columns = useColumns()

const { table } = useDataTable({
data: processedProducts,
data: products || [],
columns,
count: processedCount,
count: count,
enablePagination: true,
enableRowSelection: true,
pageSize: PAGE_SIZE,
Expand Down Expand Up @@ -171,7 +146,7 @@ export const ProductListTable = () => {
<_DataTable
table={table}
columns={columns}
count={processedCount}
count={count}
pageSize={PAGE_SIZE}
filters={filters}
search
Expand Down