The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.
TypeScript b2b-marketplacecomposable-commerceecommerceenterpriseheadless-commercemarketplacemedusamedusajsmulti-vendortypescript
refactor(admin): migrate all loader.ts files to new route-based SDK and add customer-group hooks
vholik7ad54d299a3c
diff --git a/packages/admin/src/hooks/api/customer-groups.tsx b/packages/admin/src/hooks/api/customer-groups.tsxindex a2e2cc82d..6d07b8892 100644--- a/packages/admin/src/hooks/api/customer-groups.tsx+++ b/packages/admin/src/hooks/api/customer-groups.tsx@@ -170,6 +170,60 @@ export const useRemoveCustomersFromGroup = (})}+export const useDeleteCustomerGroupLazy = (+ options?: UseMutationOptions<+ InferClientOutput<typeof sdk.admin.customerGroups.$id.delete>,+ ClientError,+ { id: string }+ >+) => {+ return useMutation({+ mutationFn: ({ id }) => sdk.admin.customerGroups.$id.delete({ $id: id }),+ onSuccess: (data, variables, context) => {+ queryClient.invalidateQueries({+ queryKey: customerGroupsQueryKeys.lists(),+ })+ queryClient.invalidateQueries({+ queryKey: customerGroupsQueryKeys.detail(variables.id),+ })++ options?.onSuccess?.(data, variables, context)+ },+ ...options,+ })+}++export const useAddCustomersToGroup = (+ id: string,+ options?: UseMutationOptions<+ InferClientOutput<typeof sdk.admin.customerGroups.$id.customers.mutate>,+ ClientError,+ HttpTypes.AdminBatchLink["add"]+ >+) => {+ return useMutation({+ mutationFn: (payload) =>+ sdk.admin.customerGroups.$id.customers.mutate({+ $id: id,+ add: payload,+ }),+ onSuccess: (data, variables, context) => {+ queryClient.invalidateQueries({+ queryKey: customerGroupsQueryKeys.lists(),+ })+ queryClient.invalidateQueries({+ queryKey: customerGroupsQueryKeys.detail(id),+ })+ queryClient.invalidateQueries({+ queryKey: customersQueryKeys.lists(),+ })++ options?.onSuccess?.(data, variables, context)+ },+ ...options,+ })+}+export const useCustomerGroupCustomers = (id: string,query?: Omit<diff --git a/packages/admin/src/pages/campaigns/campaign-detail/loader.ts b/packages/admin/src/pages/campaigns/campaign-detail/loader.tsindex 852f79af0..c153be340 100644--- a/packages/admin/src/pages/campaigns/campaign-detail/loader.ts+++ b/packages/admin/src/pages/campaigns/campaign-detail/loader.ts@@ -8,9 +8,7 @@ import { CAMPAIGN_DETAIL_FIELDS } from "./constants"const campaignDetailQuery = (id: string) => ({queryKey: campaignsQueryKeys.detail(id),queryFn: async () =>- sdk.admin.campaign.retrieve(id, {- fields: CAMPAIGN_DETAIL_FIELDS,- }),+ sdk.admin.campaigns.$id.query({ $id: id, fields: CAMPAIGN_DETAIL_FIELDS }),})export const campaignLoader = async ({ params }: LoaderFunctionArgs) => {diff --git a/packages/admin/src/pages/categories/category-detail/loader.ts b/packages/admin/src/pages/categories/category-detail/loader.tsindex 27c62b556..e4fe308b7 100644--- a/packages/admin/src/pages/categories/category-detail/loader.ts+++ b/packages/admin/src/pages/categories/category-detail/loader.ts@@ -6,7 +6,7 @@ import { queryClient } from "../../../lib/query-client"const categoryDetailQuery = (id: string) => ({queryKey: categoriesQueryKeys.detail(id),- queryFn: async () => sdk.admin.productCategory.retrieve(id),+ queryFn: async () => sdk.admin.productCategories.$id.query({ $id: id }),})export const categoryLoader = async ({ params }: LoaderFunctionArgs) => {diff --git a/packages/admin/src/pages/collections/collection-detail/loader.ts b/packages/admin/src/pages/collections/collection-detail/loader.tsindex e92255726..f790e7652 100644--- a/packages/admin/src/pages/collections/collection-detail/loader.ts+++ b/packages/admin/src/pages/collections/collection-detail/loader.ts@@ -6,7 +6,7 @@ import { queryClient } from "../../../lib/query-client"const collectionDetailQuery = (id: string) => ({queryKey: collectionsQueryKeys.detail(id),- queryFn: async () => sdk.admin.productCollection.retrieve(id),+ queryFn: async () => sdk.admin.collections.$id.query({ $id: id }),})export const collectionLoader = async ({ params }: LoaderFunctionArgs) => {diff --git a/packages/admin/src/pages/customer-groups/customer-group-add-customers/components/add-customers-form/add-customers-form.tsx b/packages/admin/src/pages/customer-groups/customer-group-add-customers/components/add-customers-form/add-customers-form.tsxnew file mode 100644index 000000000..c9e1abcb2--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-add-customers/components/add-customers-form/add-customers-form.tsx@@ -0,0 +1,247 @@+import { zodResolver } from "@hookform/resolvers/zod"+import { Button, Checkbox, Hint, Tooltip, toast } from "@medusajs/ui"+import {+ OnChangeFn,+ RowSelectionState,+ createColumnHelper,+} from "@tanstack/react-table"+import { useEffect, useMemo, useState } from "react"+import { useForm } from "react-hook-form"+import { useTranslation } from "react-i18next"+import * as zod from "zod"++import { HttpTypes } from "@medusajs/types"+import {+ RouteFocusModal,+ useRouteModal,+} from "../../../../../components/modals"+import { _DataTable } from "../../../../../components/table/data-table"+import { KeyboundForm } from "../../../../../components/utilities/keybound-form"+import { useAddCustomersToGroup } from "../../../../../hooks/api/customer-groups"+import { useCustomers } from "../../../../../hooks/api/customers"+import { useCustomerTableColumns } from "../../../../../hooks/table/columns/use-customer-table-columns"+import { useCustomerTableFilters } from "../../../../../hooks/table/filters/use-customer-table-filters"+import { useCustomerTableQuery } from "../../../../../hooks/table/query/use-customer-table-query"+import { useDataTable } from "../../../../../hooks/use-data-table"++type AddCustomersFormProps = {+ customerGroupId: string+}++export const AddCustomersSchema = zod.object({+ customer_ids: zod.array(zod.string()).min(1),+})++const PAGE_SIZE = 10++export const AddCustomersForm = ({+ customerGroupId,+}: AddCustomersFormProps) => {+ const { t } = useTranslation()+ const { handleSuccess } = useRouteModal()++ const form = useForm<zod.infer<typeof AddCustomersSchema>>({+ defaultValues: {+ customer_ids: [],+ },+ resolver: zodResolver(AddCustomersSchema),+ })++ const { setValue } = form++ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})++ useEffect(() => {+ setValue(+ "customer_ids",+ Object.keys(rowSelection).filter((k) => rowSelection[k]),+ {+ shouldDirty: true,+ shouldTouch: true,+ }+ )+ }, [rowSelection, setValue])++ const { searchParams, raw } = useCustomerTableQuery({ pageSize: PAGE_SIZE })+ const filters = useCustomerTableFilters()++ const { customers, count, isLoading, isError, error } = useCustomers({+ fields: "id,email,first_name,last_name,has_account,*groups",+ ...searchParams,+ })++ const updater: OnChangeFn<RowSelectionState> = (fn) => {+ const state = typeof fn === "function" ? fn(rowSelection) : fn++ const ids = Object.keys(state)++ setValue("customer_ids", ids, {+ shouldDirty: true,+ shouldTouch: true,+ })++ setRowSelection(state)+ }++ const columns = useColumns()++ const { table } = useDataTable({+ data: customers ?? [],+ columns,+ count,+ enablePagination: true,+ enableRowSelection: (row) => {+ return !row.original.groups?.map((gc) => gc.id).includes(customerGroupId)+ },+ getRowId: (row) => row.id,+ pageSize: PAGE_SIZE,+ rowSelection: {+ state: rowSelection,+ updater,+ },+ })++ const { mutateAsync, isPending } = useAddCustomersToGroup(customerGroupId)++ const handleSubmit = form.handleSubmit(async (data) => {+ await mutateAsync(data.customer_ids, {+ onSuccess: () => {+ toast.success(+ t("customerGroups.customers.add.successToast", {+ count: data.customer_ids.length,+ })+ )++ handleSuccess(`/customer-groups/${customerGroupId}`)+ },+ onError: (error) => {+ toast.error(error.message)+ },+ })+ })++ if (isError) {+ throw error+ }++ return (+ <RouteFocusModal.Form form={form} data-testid="add-customers-form">+ <KeyboundForm+ className="flex h-full flex-col overflow-hidden"+ onSubmit={handleSubmit}+ data-testid="add-customers-form-keybound"+ >+ <RouteFocusModal.Header data-testid="add-customers-form-header">+ <div className="flex items-center justify-end gap-x-2" data-testid="add-customers-form-header-errors">+ {form.formState.errors.customer_ids && (+ <Hint variant="error" data-testid="add-customers-form-error-hint">+ {form.formState.errors.customer_ids.message}+ </Hint>+ )}+ </div>+ </RouteFocusModal.Header>+ <RouteFocusModal.Body className="size-full overflow-hidden" data-testid="add-customers-form-body">+ <_DataTable+ table={table}+ columns={columns}+ pageSize={PAGE_SIZE}+ count={count}+ filters={filters}+ orderBy={[+ { key: "email", label: t("fields.email") },+ { key: "first_name", label: t("fields.firstName") },+ { key: "last_name", label: t("fields.lastName") },+ { key: "has_account", label: t("customers.hasAccount") },+ { key: "created_at", label: t("fields.createdAt") },+ { key: "updated_at", label: t("fields.updatedAt") },+ ]}+ isLoading={isLoading}+ layout="fill"+ search="autofocus"+ queryObject={raw}+ noRecords={{+ message: t("customerGroups.customers.add.list.noRecordsMessage"),+ }}+ />+ </RouteFocusModal.Body>+ <RouteFocusModal.Footer data-testid="add-customers-form-footer">+ <RouteFocusModal.Close asChild>+ <Button variant="secondary" size="small" data-testid="add-customers-form-cancel-button">+ {t("actions.cancel")}+ </Button>+ </RouteFocusModal.Close>+ <Button+ type="submit"+ variant="primary"+ size="small"+ isLoading={isPending}+ data-testid="add-customers-form-submit-button"+ >+ {t("actions.save")}+ </Button>+ </RouteFocusModal.Footer>+ </KeyboundForm>+ </RouteFocusModal.Form>+ )+}++const columnHelper = createColumnHelper<HttpTypes.AdminCustomer>()++const useColumns = () => {+ const { t } = useTranslation()+ const base = useCustomerTableColumns()++ const columns = useMemo(+ () => [+ columnHelper.display({+ id: "select",+ header: ({ table }) => {+ return (+ <Checkbox+ checked={+ table.getIsSomePageRowsSelected()+ ? "indeterminate"+ : table.getIsAllPageRowsSelected()+ }+ onCheckedChange={(value) =>+ table.toggleAllPageRowsSelected(!!value)+ }+ />+ )+ },+ cell: ({ row }) => {+ const isPreSelected = !row.getCanSelect()+ const isSelected = row.getIsSelected() || isPreSelected++ const Component = (+ <Checkbox+ checked={isSelected}+ disabled={isPreSelected}+ onCheckedChange={(value) => row.toggleSelected(!!value)}+ onClick={(e) => {+ e.stopPropagation()+ }}+ />+ )++ if (isPreSelected) {+ return (+ <Tooltip+ content={t("customerGroups.customers.alreadyAddedTooltip")}+ side="right"+ >+ {Component}+ </Tooltip>+ )+ }++ return Component+ },+ }),+ ...base,+ ],+ [t, base]+ )++ return columns+}diff --git a/packages/admin/src/pages/customer-groups/customer-group-add-customers/components/add-customers-form/index.ts b/packages/admin/src/pages/customer-groups/customer-group-add-customers/components/add-customers-form/index.tsnew file mode 100644index 000000000..512d1edf6--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-add-customers/components/add-customers-form/index.ts@@ -0,0 +1 @@+export * from "./add-customers-form"diff --git a/packages/admin/src/pages/customer-groups/customer-group-add-customers/customer-group-add-customers.tsx b/packages/admin/src/pages/customer-groups/customer-group-add-customers/customer-group-add-customers.tsxnew file mode 100644index 000000000..6eede341f--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-add-customers/customer-group-add-customers.tsx@@ -0,0 +1,13 @@+import { useParams } from "react-router-dom"+import { RouteFocusModal } from "../../../components/modals"+import { AddCustomersForm } from "./components/add-customers-form"++export const CustomerGroupAddCustomers = () => {+ const { id } = useParams()++ return (+ <RouteFocusModal>+ <AddCustomersForm customerGroupId={id!} />+ </RouteFocusModal>+ )+}diff --git a/packages/admin/src/pages/customer-groups/customer-group-add-customers/index.ts b/packages/admin/src/pages/customer-groups/customer-group-add-customers/index.tsnew file mode 100644index 000000000..3b39c9e78--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-add-customers/index.ts@@ -0,0 +1 @@+export { CustomerGroupAddCustomers as Component } from "./customer-group-add-customers"diff --git a/packages/admin/src/pages/customer-groups/customer-group-create/components/create-customer-group-form/create-customer-group-form.tsx b/packages/admin/src/pages/customer-groups/customer-group-create/components/create-customer-group-form/create-customer-group-form.tsxnew file mode 100644index 000000000..2f96762a5--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-create/components/create-customer-group-form/create-customer-group-form.tsx@@ -0,0 +1,114 @@+import { zodResolver } from "@hookform/resolvers/zod"+import { Button, Heading, Input, Text, toast } from "@medusajs/ui"+import { useForm } from "react-hook-form"+import { useTranslation } from "react-i18next"+import * as zod from "zod"++import { Form } from "../../../../../components/common/form"+import {+ RouteFocusModal,+ useRouteModal,+} from "../../../../../components/modals"+import { KeyboundForm } from "../../../../../components/utilities/keybound-form"+import { useCreateCustomerGroup } from "../../../../../hooks/api/customer-groups"++export const CreateCustomerGroupSchema = zod.object({+ name: zod.string().min(1),+})++export const CreateCustomerGroupForm = () => {+ const { t } = useTranslation()+ const { handleSuccess } = useRouteModal()++ const form = useForm<zod.infer<typeof CreateCustomerGroupSchema>>({+ defaultValues: {+ name: "",+ },+ resolver: zodResolver(CreateCustomerGroupSchema),+ })++ const { mutateAsync, isPending } = useCreateCustomerGroup()++ const handleSubmit = form.handleSubmit(async (data) => {+ await mutateAsync(+ {+ name: data.name,+ },+ {+ onSuccess: ({ customer_group }) => {+ toast.success(+ t("customerGroups.create.successToast", {+ name: customer_group.name,+ })+ )++ handleSuccess(`/customer-groups/${customer_group.id}`)+ },+ onError: (error) => {+ toast.error(error.message)+ },+ }+ )+ })++ return (+ <RouteFocusModal.Form form={form} data-testid="create-customer-group-form">+ <KeyboundForm+ className="flex h-full flex-col overflow-hidden"+ onSubmit={handleSubmit}+ data-testid="create-customer-group-form-keybound"+ >+ <RouteFocusModal.Header data-testid="create-customer-group-form-header" />+ <RouteFocusModal.Body className="flex flex-col items-center pt-[72px]" data-testid="create-customer-group-form-body">+ <div className="flex size-full max-w-[720px] flex-col gap-y-8" data-testid="create-customer-group-form-content">+ <div data-testid="create-customer-group-form-header-section">+ <RouteFocusModal.Title asChild>+ <Heading data-testid="create-customer-group-form-title">{t("customerGroups.create.header")}</Heading>+ </RouteFocusModal.Title>+ <RouteFocusModal.Description asChild>+ <Text size="small" className="text-ui-fg-subtle" data-testid="create-customer-group-form-hint">+ {t("customerGroups.create.hint")}+ </Text>+ </RouteFocusModal.Description>+ </div>+ <div className="grid grid-cols-2 gap-4" data-testid="create-customer-group-form-fields">+ <Form.Field+ control={form.control}+ name="name"+ render={({ field }) => {+ return (+ <Form.Item data-testid="create-customer-group-form-name-item">+ <Form.Label data-testid="create-customer-group-form-name-label">{t("fields.name")}</Form.Label>+ <Form.Control data-testid="create-customer-group-form-name-control">+ <Input {...field} data-testid="create-customer-group-form-name-input" />+ </Form.Control>+ <Form.ErrorMessage data-testid="create-customer-group-form-name-error" />+ </Form.Item>+ )+ }}+ />+ </div>+ </div>+ </RouteFocusModal.Body>+ <RouteFocusModal.Footer data-testid="create-customer-group-form-footer">+ <div className="flex items-center justify-end gap-x-2" data-testid="create-customer-group-form-footer-actions">+ <RouteFocusModal.Close asChild>+ <Button variant="secondary" size="small" data-testid="create-customer-group-form-cancel-button">+ {t("actions.cancel")}+ </Button>+ </RouteFocusModal.Close>+ <Button+ type="submit"+ variant="primary"+ size="small"+ isLoading={isPending}+ data-testid="create-customer-group-form-submit-button"+ >+ {t("actions.create")}+ </Button>+ </div>+ </RouteFocusModal.Footer>+ </KeyboundForm>+ </RouteFocusModal.Form>+ )+}diff --git a/packages/admin/src/pages/customer-groups/customer-group-create/components/create-customer-group-form/index.ts b/packages/admin/src/pages/customer-groups/customer-group-create/components/create-customer-group-form/index.tsnew file mode 100644index 000000000..960232c9c--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-create/components/create-customer-group-form/index.ts@@ -0,0 +1 @@+export * from "./create-customer-group-form"diff --git a/packages/admin/src/pages/customer-groups/customer-group-create/customer-group-create.tsx b/packages/admin/src/pages/customer-groups/customer-group-create/customer-group-create.tsxnew file mode 100644index 000000000..a9ab7b7b2--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-create/customer-group-create.tsx@@ -0,0 +1,10 @@+import { RouteFocusModal } from "../../../components/modals"+import { CreateCustomerGroupForm } from "./components/create-customer-group-form"++export const CustomerGroupCreate = () => {+ return (+ <RouteFocusModal>+ <CreateCustomerGroupForm />+ </RouteFocusModal>+ )+}diff --git a/packages/admin/src/pages/customer-groups/customer-group-create/index.ts b/packages/admin/src/pages/customer-groups/customer-group-create/index.tsnew file mode 100644index 000000000..9bab0611a--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-create/index.ts@@ -0,0 +1 @@+export { CustomerGroupCreate as Component } from "./customer-group-create"diff --git a/packages/admin/src/pages/customer-groups/customer-group-detail/breadcrumb.tsx b/packages/admin/src/pages/customer-groups/customer-group-detail/breadcrumb.tsxnew file mode 100644index 000000000..de9232747--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-detail/breadcrumb.tsx@@ -0,0 +1,31 @@+import { HttpTypes } from "@medusajs/types"+import { UIMatch } from "react-router-dom"++import { useCustomerGroup } from "../../../hooks/api"+import { CUSTOMER_GROUP_DETAIL_FIELDS } from "./constants"++type CustomerGroupDetailBreadcrumbProps =+ UIMatch<HttpTypes.AdminCustomerGroupResponse>++export const CustomerGroupDetailBreadcrumb = (+ props: CustomerGroupDetailBreadcrumbProps+) => {+ const { id } = props.params || {}++ const { customer_group } = useCustomerGroup(+ id!,+ {+ fields: CUSTOMER_GROUP_DETAIL_FIELDS,+ },+ {+ initialData: props.data,+ enabled: Boolean(id),+ }+ )++ if (!customer_group) {+ return null+ }++ return <span>{customer_group.name}</span>+}diff --git a/packages/admin/src/pages/customer-groups/customer-group-detail/components/customer-group-customer-section/customer-group-customer-section.tsx b/packages/admin/src/pages/customer-groups/customer-group-detail/components/customer-group-customer-section/customer-group-customer-section.tsxnew file mode 100644index 000000000..308d1ffdf--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-detail/components/customer-group-customer-section/customer-group-customer-section.tsx@@ -0,0 +1,244 @@+import { PencilSquare, Trash } from "@medusajs/icons"+import { HttpTypes } from "@medusajs/types"+import { Button, Checkbox, Container, Heading, usePrompt } from "@medusajs/ui"+import { RowSelectionState, createColumnHelper } from "@tanstack/react-table"+import { useMemo, useState } from "react"+import { useTranslation } from "react-i18next"+import { Link } from "react-router-dom"++import { ActionMenu } from "../../../../../components/common/action-menu"+import { _DataTable } from "../../../../../components/table/data-table"+import { useRemoveCustomersFromGroup } from "../../../../../hooks/api/customer-groups"+import { useCustomers } from "../../../../../hooks/api/customers"+import { useCustomerTableColumns } from "../../../../../hooks/table/columns/use-customer-table-columns"+import { useCustomerTableFilters } from "../../../../../hooks/table/filters/use-customer-table-filters"+import { useCustomerTableQuery } from "../../../../../hooks/table/query/use-customer-table-query"+import { useDataTable } from "../../../../../hooks/use-data-table"++type CustomerGroupCustomerSectionProps = {+ group: HttpTypes.AdminCustomerGroup+}++const PAGE_SIZE = 10++export const CustomerGroupCustomerSection = ({+ group,+}: CustomerGroupCustomerSectionProps) => {+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})+ const { t } = useTranslation()+ const prompt = usePrompt()++ const { searchParams, raw } = useCustomerTableQuery({ pageSize: PAGE_SIZE })+ const { customers, count, isLoading, isError, error } = useCustomers({+ ...searchParams,+ groups: group.id,+ })++ const columns = useColumns()+ const filters = useCustomerTableFilters(["groups"])++ const { table } = useDataTable({+ data: customers ?? [],+ columns,+ count,+ getRowId: (row) => row.id,+ enablePagination: true,+ enableRowSelection: true,+ pageSize: PAGE_SIZE,+ rowSelection: {+ state: rowSelection,+ updater: setRowSelection,+ },+ meta: {+ customerGroupId: group.id,+ },+ })++ if (isError) {+ throw error+ }++ const { mutateAsync } = useRemoveCustomersFromGroup(group.id)++ const handleRemove = async () => {+ const keys = Object.keys(rowSelection)++ const res = await prompt({+ title: t("customerGroups.customers.remove.title", {+ count: keys.length,+ }),+ description: t("customerGroups.customers.remove.description", {+ count: keys.length,+ }),+ confirmText: t("actions.continue"),+ cancelText: t("actions.cancel"),+ })++ if (!res) {+ return+ }++ await mutateAsync(keys, {+ onSuccess: () => {+ setRowSelection({})+ },+ })+ }++ return (+ <Container className="divide-y p-0" data-testid="customer-group-customer-section">+ <div className="flex items-center justify-between px-6 py-4" data-testid="customer-group-customer-section-header">+ <Heading level="h2" data-testid="customer-group-customer-section-heading">{t("customers.domain")}</Heading>+ <Link to={`/customer-groups/${group.id}/add-customers`} data-testid="customer-group-customer-section-add-link">+ <Button variant="secondary" size="small" data-testid="customer-group-customer-section-add-button">+ {t("general.add")}+ </Button>+ </Link>+ </div>+ <_DataTable+ table={table}+ columns={columns}+ pageSize={PAGE_SIZE}+ isLoading={isLoading}+ count={count}+ navigateTo={(row) => `/customers/${row.id}`}+ filters={filters}+ search+ pagination+ orderBy={[+ { key: "email", label: t("fields.email") },+ { key: "first_name", label: t("fields.firstName") },+ { key: "last_name", label: t("fields.lastName") },+ { key: "has_account", label: t("customers.hasAccount") },+ { key: "created_at", label: t("fields.createdAt") },+ { key: "updated_at", label: t("fields.updatedAt") },+ ]}+ queryObject={raw}+ commands={[+ {+ action: handleRemove,+ label: t("actions.remove"),+ shortcut: "r",+ },+ ]}+ noRecords={{+ message: t("customerGroups.customers.list.noRecordsMessage"),+ }}+ />+ </Container>+ )+}++const CustomerActions = ({+ customer,+ customerGroupId,+}: {+ customer: HttpTypes.AdminCustomer+ customerGroupId: string+}) => {+ const { t } = useTranslation()+ const { mutateAsync } = useRemoveCustomersFromGroup(customerGroupId)++ const prompt = usePrompt()++ const handleRemove = async () => {+ const res = await prompt({+ title: t("customerGroups.customers.remove.title", {+ count: 1,+ }),+ description: t("customerGroups.customers.remove.description", {+ count: 1,+ }),+ confirmText: t("actions.continue"),+ cancelText: t("actions.cancel"),+ })++ if (!res) {+ return+ }++ await mutateAsync([customer.id])+ }++ return (+ <ActionMenu+ data-testid={`customer-group-customer-section-row-actions-${customer.id}`}+ groups={[+ {+ actions: [+ {+ icon: <PencilSquare />,+ label: t("actions.edit"),+ to: `/customers/${customer.id}/edit`,+ },+ ],+ },+ {+ actions: [+ {+ icon: <Trash />,+ label: t("actions.remove"),+ onClick: handleRemove,+ },+ ],+ },+ ]}+ />+ )+}++const columnHelper = createColumnHelper<HttpTypes.AdminCustomer>()++const useColumns = () => {+ const columns = useCustomerTableColumns()++ return useMemo(+ () => [+ columnHelper.display({+ id: "select",+ header: ({ table }) => {+ return (+ <Checkbox+ checked={+ table.getIsSomePageRowsSelected()+ ? "indeterminate"+ : table.getIsAllPageRowsSelected()+ }+ onCheckedChange={(value) =>+ table.toggleAllPageRowsSelected(!!value)+ }+ />+ )+ },+ cell: ({ row }) => {+ return (+ <Checkbox+ checked={row.getIsSelected()}+ onCheckedChange={(value) => row.toggleSelected(!!value)}+ onClick={(e) => {+ e.stopPropagation()+ }}+ />+ )+ },+ }),+ ...columns,+ columnHelper.display({+ id: "actions",+ cell: ({ row, table }) => {+ const { customerGroupId } = table.options.meta as {+ customerGroupId: string+ }++ return (+ <CustomerActions+ customer={row.original}+ customerGroupId={customerGroupId}+ />+ )+ },+ }),+ ],+ [columns]+ )+}diff --git a/packages/admin/src/pages/customer-groups/customer-group-detail/components/customer-group-customer-section/index.ts b/packages/admin/src/pages/customer-groups/customer-group-detail/components/customer-group-customer-section/index.tsnew file mode 100644index 000000000..3098ff7ac--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-detail/components/customer-group-customer-section/index.ts@@ -0,0 +1 @@+export * from "./customer-group-customer-section"diff --git a/packages/admin/src/pages/customer-groups/customer-group-detail/components/customer-group-general-section/customer-group-general-section.tsx b/packages/admin/src/pages/customer-groups/customer-group-detail/components/customer-group-general-section/customer-group-general-section.tsxnew file mode 100644index 000000000..4cb5595aa--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-detail/components/customer-group-general-section/customer-group-general-section.tsx@@ -0,0 +1,91 @@+import { PencilSquare, Trash } from "@medusajs/icons"+import { HttpTypes } from "@medusajs/types"+import { Container, Heading, Text, toast, usePrompt } from "@medusajs/ui"+import { useTranslation } from "react-i18next"+import { useNavigate } from "react-router-dom"++import { ActionMenu } from "../../../../../components/common/action-menu"+import { useDeleteCustomerGroup } from "../../../../../hooks/api/customer-groups"++type CustomerGroupGeneralSectionProps = {+ group: HttpTypes.AdminCustomerGroup+}++export const CustomerGroupGeneralSection = ({+ group,+}: CustomerGroupGeneralSectionProps) => {+ const { t } = useTranslation()+ const prompt = usePrompt()+ const navigate = useNavigate()++ const { mutateAsync } = useDeleteCustomerGroup(group.id)++ const handleDelete = async () => {+ const res = await prompt({+ title: t("customerGroups.delete.title"),+ description: t("customerGroups.delete.description", {+ name: group.name,+ }),+ confirmText: t("actions.delete"),+ cancelText: t("actions.cancel"),+ })++ if (!res) {+ return+ }++ await mutateAsync(undefined, {+ onSuccess: () => {+ toast.success(+ t("customerGroups.delete.successToast", {+ name: group.name,+ })+ )++ navigate("/customer-groups", { replace: true })+ },+ onError: (error) => {+ toast.error(error.message)+ },+ })+ }++ return (+ <Container className="divide-y p-0" data-testid="customer-group-general-section">+ <div className="flex items-center justify-between px-6 py-4" data-testid="customer-group-general-section-header">+ <Heading data-testid="customer-group-general-section-name">{group.name}</Heading>+ <ActionMenu+ data-testid="customer-group-general-section-action-menu"+ groups={[+ {+ actions: [+ {+ icon: <PencilSquare />,+ label: t("actions.edit"),+ to: `/customer-groups/${group.id}/edit`,+ },+ ],+ },+ {+ actions: [+ {+ icon: <Trash />,+ label: t("actions.delete"),+ onClick: handleDelete,+ },+ ],+ },+ ]}+ />+ </div>+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4" data-testid="customer-group-general-section-customers-row">+ <Text size="small" leading="compact" weight="plus" data-testid="customer-group-general-section-customers-label">+ {t("customers.domain")}+ </Text>+ <Text size="small" leading="compact" data-testid="customer-group-general-section-customers-value">+ {group.customers?.length || "-"}+ </Text>+ </div>+ </Container>+ )+}diff --git a/packages/admin/src/pages/customer-groups/customer-group-detail/components/customer-group-general-section/index.ts b/packages/admin/src/pages/customer-groups/customer-group-detail/components/customer-group-general-section/index.tsnew file mode 100644index 000000000..dfe709902--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-detail/components/customer-group-general-section/index.ts@@ -0,0 +1 @@+export * from "./customer-group-general-section"diff --git a/packages/admin/src/pages/customer-groups/customer-group-detail/constants.ts b/packages/admin/src/pages/customer-groups/customer-group-detail/constants.tsnew file mode 100644index 000000000..bd1ebdf4b--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-detail/constants.ts@@ -0,0 +1 @@+export const CUSTOMER_GROUP_DETAIL_FIELDS = "+customers.id"diff --git a/packages/admin/src/pages/customer-groups/customer-group-detail/customer-group-detail.tsx b/packages/admin/src/pages/customer-groups/customer-group-detail/customer-group-detail.tsxnew file mode 100644index 000000000..a1219cb51--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-detail/customer-group-detail.tsx@@ -0,0 +1,40 @@+import { useLoaderData, useParams } from "react-router-dom";++import { SingleColumnPage } from "../../../components/layout/pages";+import { useCustomerGroup } from "../../../hooks/api/customer-groups";+import { CustomerGroupCustomerSection } from "./components/customer-group-customer-section";+import { CustomerGroupGeneralSection } from "./components/customer-group-general-section";+import { customerGroupLoader } from "./loader";++import { SingleColumnPageSkeleton } from "../../../components/common/skeleton";+import { CUSTOMER_GROUP_DETAIL_FIELDS } from "./constants";++export const CustomerGroupDetail = () => {+ const initialData = useLoaderData() as Awaited<+ ReturnType<typeof customerGroupLoader>+ >;++ const { id } = useParams();+ const { customer_group, isLoading, isError, error } = useCustomerGroup(+ id!,+ {+ fields: CUSTOMER_GROUP_DETAIL_FIELDS,+ },+ { initialData },+ );++ if (isLoading || !customer_group) {+ return <SingleColumnPageSkeleton sections={2} showJSON showMetadata />;+ }++ if (isError) {+ throw error;+ }++ return (+ <SingleColumnPage showJSON showMetadata data={customer_group}>+ <CustomerGroupGeneralSection group={customer_group} />+ <CustomerGroupCustomerSection group={customer_group} />+ </SingleColumnPage>+ );+};diff --git a/packages/admin/src/pages/customer-groups/customer-group-detail/index.ts b/packages/admin/src/pages/customer-groups/customer-group-detail/index.tsnew file mode 100644index 000000000..2765f2827--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-detail/index.ts@@ -0,0 +1,3 @@+export { CustomerGroupDetailBreadcrumb as Breadcrumb } from "./breadcrumb"+export { CustomerGroupDetail as Component } from "./customer-group-detail"+export { customerGroupLoader as loader } from "./loader"diff --git a/packages/admin/src/pages/customer-groups/customer-group-detail/loader.ts b/packages/admin/src/pages/customer-groups/customer-group-detail/loader.tsnew file mode 100644index 000000000..a99be33dc--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-detail/loader.ts@@ -0,0 +1,21 @@+import { LoaderFunctionArgs } from "react-router-dom"+import { productsQueryKeys } from "../../../hooks/api/products"+import { sdk } from "../../../lib/client"+import { queryClient } from "../../../lib/query-client"+import { CUSTOMER_GROUP_DETAIL_FIELDS } from "./constants"++const customerGroupDetailQuery = (id: string) => ({+ queryKey: productsQueryKeys.detail(id),+ queryFn: async () =>+ sdk.admin.customerGroups.$id.query({+ $id: id,+ fields: CUSTOMER_GROUP_DETAIL_FIELDS,+ }),+})++export const customerGroupLoader = async ({ params }: LoaderFunctionArgs) => {+ const id = params.id+ const query = customerGroupDetailQuery(id!)++ return queryClient.ensureQueryData(query)+}diff --git a/packages/admin/src/pages/customer-groups/customer-group-edit/components/edit-customer-group-form/edit-customer-group-form.tsx b/packages/admin/src/pages/customer-groups/customer-group-edit/components/edit-customer-group-form/edit-customer-group-form.tsxnew file mode 100644index 000000000..9ee8fbdb3--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-edit/components/edit-customer-group-form/edit-customer-group-form.tsx@@ -0,0 +1,91 @@+import { zodResolver } from "@hookform/resolvers/zod"+import { HttpTypes } from "@medusajs/types"+import { Button, Input, toast } from "@medusajs/ui"+import { useForm } from "react-hook-form"+import { useTranslation } from "react-i18next"+import * as z from "zod"+import { Form } from "../../../../../components/common/form"+import { RouteDrawer, useRouteModal } from "../../../../../components/modals"+import { KeyboundForm } from "../../../../../components/utilities/keybound-form"+import { useUpdateCustomerGroup } from "../../../../../hooks/api/customer-groups"++type EditCustomerGroupFormProps = {+ group: HttpTypes.AdminCustomerGroup+}++export const EditCustomerGroupSchema = z.object({+ name: z.string().min(1),+})++export const EditCustomerGroupForm = ({+ group,+}: EditCustomerGroupFormProps) => {+ const { t } = useTranslation()+ const { handleSuccess } = useRouteModal()++ const form = useForm<z.infer<typeof EditCustomerGroupSchema>>({+ defaultValues: {+ name: group.name || "",+ },+ resolver: zodResolver(EditCustomerGroupSchema),+ })++ const { mutateAsync, isPending } = useUpdateCustomerGroup(group.id)++ const handleSubmit = form.handleSubmit(async (data) => {+ await mutateAsync(data, {+ onSuccess: ({ customer_group }) => {+ toast.success(+ t("customerGroups.edit.successToast", {+ name: customer_group.name,+ })+ )++ handleSuccess()+ },+ onError: (error) => {+ toast.error(error.message)+ },+ })+ })++ return (+ <RouteDrawer.Form form={form} data-testid="edit-customer-group-form">+ <KeyboundForm+ onSubmit={handleSubmit}+ className="flex flex-1 flex-col overflow-hidden"+ data-testid="edit-customer-group-form-keybound"+ >+ <RouteDrawer.Body className="flex max-w-full flex-1 flex-col gap-y-8 overflow-y-auto" data-testid="edit-customer-group-form-body">+ <Form.Field+ control={form.control}+ name="name"+ render={({ field }) => {+ return (+ <Form.Item data-testid="edit-customer-group-form-name-item">+ <Form.Label data-testid="edit-customer-group-form-name-label">{t("fields.name")}</Form.Label>+ <Form.Control data-testid="edit-customer-group-form-name-control">+ <Input {...field} size="small" data-testid="edit-customer-group-form-name-input" />+ </Form.Control>+ <Form.ErrorMessage data-testid="edit-customer-group-form-name-error" />+ </Form.Item>+ )+ }}+ />+ </RouteDrawer.Body>+ <RouteDrawer.Footer data-testid="edit-customer-group-form-footer">+ <div className="flex items-center justify-end gap-x-2" data-testid="edit-customer-group-form-footer-actions">+ <RouteDrawer.Close asChild>+ <Button size="small" variant="secondary" data-testid="edit-customer-group-form-cancel-button">+ {t("actions.cancel")}+ </Button>+ </RouteDrawer.Close>+ <Button size="small" type="submit" isLoading={isPending} data-testid="edit-customer-group-form-submit-button">+ {t("actions.save")}+ </Button>+ </div>+ </RouteDrawer.Footer>+ </KeyboundForm>+ </RouteDrawer.Form>+ )+}diff --git a/packages/admin/src/pages/customer-groups/customer-group-edit/components/edit-customer-group-form/index.ts b/packages/admin/src/pages/customer-groups/customer-group-edit/components/edit-customer-group-form/index.tsnew file mode 100644index 000000000..3062389f7--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-edit/components/edit-customer-group-form/index.ts@@ -0,0 +1 @@+export * from "./edit-customer-group-form"diff --git a/packages/admin/src/pages/customer-groups/customer-group-edit/customer-group-edit.tsx b/packages/admin/src/pages/customer-groups/customer-group-edit/customer-group-edit.tsxnew file mode 100644index 000000000..0b92d402b--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-edit/customer-group-edit.tsx@@ -0,0 +1,28 @@+import { Heading } from "@medusajs/ui"+import { useTranslation } from "react-i18next"+import { useParams } from "react-router-dom"+import { RouteDrawer } from "../../../components/modals"+import { useCustomerGroup } from "../../../hooks/api/customer-groups"+import { EditCustomerGroupForm } from "./components/edit-customer-group-form"++export const CustomerGroupEdit = () => {+ const { id } = useParams()+ const { customer_group, isLoading, isError, error } = useCustomerGroup(id!)++ const { t } = useTranslation()++ if (isError) {+ throw error+ }++ return (+ <RouteDrawer>+ <RouteDrawer.Header>+ <Heading>{t("customerGroups.edit.header")}</Heading>+ </RouteDrawer.Header>+ {!isLoading && customer_group && (+ <EditCustomerGroupForm group={customer_group} />+ )}+ </RouteDrawer>+ )+}diff --git a/packages/admin/src/pages/customer-groups/customer-group-edit/index.ts b/packages/admin/src/pages/customer-groups/customer-group-edit/index.tsnew file mode 100644index 000000000..edb805c0a--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-edit/index.ts@@ -0,0 +1 @@+export { CustomerGroupEdit as Component } from "./customer-group-edit"diff --git a/packages/admin/src/pages/customer-groups/customer-group-list/components/customer-group-list-table/customer-group-list-table.tsx b/packages/admin/src/pages/customer-groups/customer-group-list/components/customer-group-list-table/customer-group-list-table.tsxnew file mode 100644index 000000000..ddb38618a--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-list/components/customer-group-list-table/customer-group-list-table.tsx@@ -0,0 +1,222 @@+import { PencilSquare, Trash } from "@medusajs/icons";+import { HttpTypes } from "@medusajs/types";+import {+ Container,+ createDataTableColumnHelper,+ toast,+ usePrompt,+} from "@medusajs/ui";+import { keepPreviousData } from "@tanstack/react-query";+import { useCallback, useMemo } from "react";+import { useTranslation } from "react-i18next";+import { useNavigate } from "react-router-dom";++import { DataTable } from "../../../../../components/data-table";+import { useDataTableDateFilters } from "../../../../../components/data-table/helpers/general/use-data-table-date-filters";+import { SingleColumnPage } from "../../../../../components/layout/pages";+import {+ useCustomerGroups,+ useDeleteCustomerGroupLazy,+} from "../../../../../hooks/api";+import { useDate } from "../../../../../hooks/use-date";+import { useQueryParams } from "../../../../../hooks/use-query-params";++const PAGE_SIZE = 10;++export const CustomerGroupListTable = () => {+ const { t } = useTranslation();++ const { q, order, offset, created_at, updated_at } = useQueryParams([+ "q",+ "order",+ "offset",+ "created_at",+ "updated_at",+ ]);++ const columns = useColumns();+ const filters = useFilters();++ const { customer_groups, count, isPending, isError, error } =+ useCustomerGroups(+ {+ q,+ order,+ offset: offset ? parseInt(offset) : undefined,+ limit: PAGE_SIZE,+ created_at: created_at ? JSON.parse(created_at) : undefined,+ updated_at: updated_at ? JSON.parse(updated_at) : undefined,+ fields: "id,name,created_at,updated_at,customers.id",+ },+ {+ placeholderData: keepPreviousData,+ },+ );++ if (isError) {+ throw error;+ }++ return (+ <SingleColumnPage>+ <Container+ className="overflow-hidden p-0"+ data-testid="customer-group-list-container"+ >+ <div data-testid="customer-group-list-table">+ <DataTable+ data={customer_groups}+ columns={columns}+ filters={filters}+ heading={t("customerGroups.domain")}+ rowCount={count}+ getRowId={(row) => row.id}+ rowHref={(row) => `/customer-groups/${row.id}`}+ action={{+ label: t("actions.create"),+ to: "/customer-groups/create",+ }}+ emptyState={{+ empty: {+ heading: t("customerGroups.list.empty.heading"),+ description: t("customerGroups.list.empty.description"),+ },+ filtered: {+ heading: t("customerGroups.list.filtered.heading"),+ description: t("customerGroups.list.filtered.description"),+ },+ }}+ pageSize={PAGE_SIZE}+ isLoading={isPending}+ />+ </div>+ </Container>+ </SingleColumnPage>+ );+};++const columnHelper =+ createDataTableColumnHelper<HttpTypes.AdminCustomerGroup>();++const useColumns = () => {+ const { t } = useTranslation();+ const { getFullDate } = useDate();+ const navigate = useNavigate();+ const prompt = usePrompt();++ const { mutateAsync: deleteCustomerGroup } = useDeleteCustomerGroupLazy();++ const handleDeleteCustomerGroup = useCallback(+ async ({ id, name }: { id: string; name: string }) => {+ const res = await prompt({+ title: t("customerGroups.delete.title"),+ description: t("customerGroups.delete.description", {+ name,+ }),+ verificationText: name,+ verificationInstruction: t("general.typeToConfirm"),+ confirmText: t("actions.delete"),+ cancelText: t("actions.cancel"),+ });++ if (!res) {+ return;+ }++ await deleteCustomerGroup(+ { id },+ {+ onSuccess: () => {+ toast.success(t("customerGroups.delete.successToast", { name }));+ },+ onError: (e) => {+ toast.error(e.message);+ },+ },+ );+ },+ [t, prompt, deleteCustomerGroup],+ );++ return useMemo(() => {+ return [+ columnHelper.accessor("name", {+ header: t("fields.name"),+ enableSorting: true,+ sortAscLabel: t("filters.sorting.alphabeticallyAsc"),+ sortDescLabel: t("filters.sorting.alphabeticallyDesc"),+ }),+ columnHelper.accessor("customers", {+ header: t("customers.domain"),+ cell: ({ row }) => {+ return <span>{row.original.customers?.length ?? 0}</span>;+ },+ }),+ columnHelper.accessor("created_at", {+ header: t("fields.createdAt"),+ cell: ({ row }) => {+ return (+ <span>+ {getFullDate({+ date: row.original.created_at,+ includeTime: true,+ })}+ </span>+ );+ },+ enableSorting: true,+ sortAscLabel: t("filters.sorting.dateAsc"),+ sortDescLabel: t("filters.sorting.dateDesc"),+ }),+ columnHelper.accessor("updated_at", {+ header: t("fields.updatedAt"),+ cell: ({ row }) => {+ return (+ <span>+ {getFullDate({+ date: row.original.updated_at,+ includeTime: true,+ })}+ </span>+ );+ },+ enableSorting: true,+ sortAscLabel: t("filters.sorting.dateAsc"),+ sortDescLabel: t("filters.sorting.dateDesc"),+ }),+ columnHelper.action({+ actions: [+ [+ {+ icon: <PencilSquare />,+ label: t("actions.edit"),+ onClick: (row) => {+ navigate(`/customer-groups/${row.row.original.id}/edit`);+ },+ },+ ],+ [+ {+ icon: <Trash />,+ label: t("actions.delete"),+ onClick: (row) => {+ handleDeleteCustomerGroup({+ id: row.row.original.id,+ name: row.row.original.name ?? "",+ });+ },+ },+ ],+ ],+ }),+ ];+ }, [t, navigate, getFullDate, handleDeleteCustomerGroup]);+};++const useFilters = () => {+ const dateFilters = useDataTableDateFilters();++ return useMemo(() => {+ return dateFilters;+ }, [dateFilters]);+};diff --git a/packages/admin/src/pages/customer-groups/customer-group-list/components/customer-group-list-table/index.ts b/packages/admin/src/pages/customer-groups/customer-group-list/components/customer-group-list-table/index.tsnew file mode 100644index 000000000..ead4d7474--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-list/components/customer-group-list-table/index.ts@@ -0,0 +1 @@+export * from "./customer-group-list-table"diff --git a/packages/admin/src/pages/customer-groups/customer-group-list/customer-group-list.tsx b/packages/admin/src/pages/customer-groups/customer-group-list/customer-group-list.tsxnew file mode 100644index 000000000..4e1ab3964--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-list/customer-group-list.tsx@@ -0,0 +1,10 @@+import { SingleColumnPage } from "../../../components/layout/pages";+import { CustomerGroupListTable } from "./components/customer-group-list-table";++export const CustomerGroupsList = () => {+ return (+ <SingleColumnPage>+ <CustomerGroupListTable />+ </SingleColumnPage>+ );+};diff --git a/packages/admin/src/pages/customer-groups/customer-group-list/index.ts b/packages/admin/src/pages/customer-groups/customer-group-list/index.tsnew file mode 100644index 000000000..f04a72f6d--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-list/index.ts@@ -0,0 +1 @@+export { CustomerGroupsList as Component } from "./customer-group-list"diff --git a/packages/admin/src/pages/customer-groups/customer-group-metadata/customer-metadata.tsx b/packages/admin/src/pages/customer-groups/customer-group-metadata/customer-metadata.tsxnew file mode 100644index 000000000..83a8293c8--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-metadata/customer-metadata.tsx@@ -0,0 +1,49 @@+import { useParams } from "react-router-dom";++import { useCustomerGroup, useUpdateCustomerGroup } from "@hooks/api";+import { MetadataForm } from "@components/forms/metadata-form";+import { ClientError } from "@mercurjs/client";++export const CustomerGroupMetadata = () => {+ const { id } = useParams();++ const { customer_group, isPending, isError, error } = useCustomerGroup(id!);+ const { mutateAsync, isPending: isMutating } = useUpdateCustomerGroup(id!);++ if (isError) {+ throw error;+ }++ const handleSubmit = async (+ params: { metadata?: Record<string, unknown> | null },+ callbacks: {+ onSuccess?: () => void;+ onError?: (error: ClientError | string) => void;+ },+ ) => {+ try {+ const result = await mutateAsync({+ metadata: params.metadata === undefined ? undefined : params.metadata,+ });+ callbacks.onSuccess?.();++ return result;+ } catch (error) {+ const message =+ error instanceof ClientError ? error.message : "An error occurred";+ callbacks.onError?.(message);+ throw error;+ }+ };++ return (+ <div data-testid="customer-group-metadata">+ <MetadataForm+ metadata={customer_group?.metadata}+ hook={handleSubmit}+ isPending={isPending}+ isMutating={isMutating}+ />+ </div>+ );+};diff --git a/packages/admin/src/pages/customer-groups/customer-group-metadata/index.ts b/packages/admin/src/pages/customer-groups/customer-group-metadata/index.tsnew file mode 100644index 000000000..f61cc9562--- /dev/null+++ b/packages/admin/src/pages/customer-groups/customer-group-metadata/index.ts@@ -0,0 +1 @@+export { CustomerGroupMetadata as Component } from "./customer-metadata"diff --git a/packages/admin/src/pages/customers/customer-detail/loader.ts b/packages/admin/src/pages/customers/customer-detail/loader.tsindex 301e21403..114f584bc 100644--- a/packages/admin/src/pages/customers/customer-detail/loader.ts+++ b/packages/admin/src/pages/customers/customer-detail/loader.ts@@ -6,9 +6,7 @@ import { queryClient } from "../../../lib/query-client"const customerDetailQuery = (id: string) => ({queryKey: productsQueryKeys.detail(id),queryFn: async () =>- sdk.admin.customer.retrieve(id, {- fields: "+*addresses",- }),+ sdk.admin.customers.$id.query({ $id: id, fields: "+*addresses" }),})export const customerLoader = async ({ params }: LoaderFunctionArgs) => {diff --git a/packages/admin/src/pages/inventory/inventory-detail/loader.ts b/packages/admin/src/pages/inventory/inventory-detail/loader.tsindex 499acb20d..1800abf96 100644--- a/packages/admin/src/pages/inventory/inventory-detail/loader.ts+++ b/packages/admin/src/pages/inventory/inventory-detail/loader.ts@@ -8,7 +8,8 @@ import type { ExtendedAdminInventoryItemResponse } from "@custom-types/inventoryconst inventoryDetailQuery = (id: string) => ({queryKey: inventoryItemsQueryKeys.detail(id),queryFn: async () =>- sdk.admin.inventoryItem.retrieve(id, {+ sdk.admin.inventoryItems.$id.query({+ $id: id,fields: INVENTORY_DETAIL_FIELDS,}) as Promise<ExtendedAdminInventoryItemResponse>,})diff --git a/packages/admin/src/pages/locations/location-detail/loader.ts b/packages/admin/src/pages/locations/location-detail/loader.tsindex 7c1bc859a..f40d7d7f0 100644--- a/packages/admin/src/pages/locations/location-detail/loader.ts+++ b/packages/admin/src/pages/locations/location-detail/loader.ts@@ -10,7 +10,8 @@ const locationQuery = (id: string) => ({fields: LOCATION_DETAILS_FIELD,}),queryFn: async () =>- sdk.admin.stockLocation.retrieve(id, {+ sdk.admin.stockLocations.$id.query({+ $id: id,fields: LOCATION_DETAILS_FIELD,}),})diff --git a/packages/admin/src/pages/marketplace/marketplace-detail/loader.ts b/packages/admin/src/pages/marketplace/marketplace-detail/loader.tsindex 53a585ea6..23388b081 100644--- a/packages/admin/src/pages/marketplace/marketplace-detail/loader.ts+++ b/packages/admin/src/pages/marketplace/marketplace-detail/loader.ts@@ -1,5 +1,3 @@-import { HttpTypes } from "@medusajs/types"-import { retrieveActiveStore, storeQueryKeys } from "../../../hooks/api/store"import { queryClient } from "../../../lib/query-client"@@ -12,7 +10,7 @@ export const storeLoader = async () => {const query = storeDetailQuery()return (- queryClient.getQueryData<HttpTypes.AdminStoreResponse>(query.queryKey) ??+ queryClient.getQueryData(query.queryKey) ??(await queryClient.fetchQuery(query)))}diff --git a/packages/admin/src/pages/orders/order-detail/loader.ts b/packages/admin/src/pages/orders/order-detail/loader.tsindex 036cb5aec..351020e92 100644--- a/packages/admin/src/pages/orders/order-detail/loader.ts+++ b/packages/admin/src/pages/orders/order-detail/loader.ts@@ -8,9 +8,7 @@ import { DEFAULT_FIELDS } from "./constants"const orderDetailQuery = (id: string) => ({queryKey: ordersQueryKeys.detail(id),queryFn: async () =>- sdk.admin.order.retrieve(id, {- fields: DEFAULT_FIELDS,- }),+ sdk.admin.orders.$id.query({ $id: id, fields: DEFAULT_FIELDS }),})export const orderLoader = async ({ params }: LoaderFunctionArgs) => {diff --git a/packages/admin/src/pages/price-lists/price-list-detail/loader.ts b/packages/admin/src/pages/price-lists/price-list-detail/loader.tsindex 4a03d3467..b03a9a06d 100644--- a/packages/admin/src/pages/price-lists/price-list-detail/loader.ts+++ b/packages/admin/src/pages/price-lists/price-list-detail/loader.ts@@ -5,7 +5,7 @@ import { queryClient } from "../../../lib/query-client"const pricingDetailQuery = (id: string) => ({queryKey: priceListsQueryKeys.detail(id),- queryFn: async () => sdk.admin.priceList.retrieve(id),+ queryFn: async () => sdk.admin.priceLists.$id.query({ $id: id }),})export const pricingLoader = async ({ params }: LoaderFunctionArgs) => {diff --git a/packages/admin/src/pages/product-tags/product-tag-detail/loader.ts b/packages/admin/src/pages/product-tags/product-tag-detail/loader.tsindex d11a3a7f2..aed0271ae 100644--- a/packages/admin/src/pages/product-tags/product-tag-detail/loader.ts+++ b/packages/admin/src/pages/product-tags/product-tag-detail/loader.ts@@ -6,7 +6,7 @@ import { queryClient } from "../../../lib/query-client"const productTagDetailQuery = (id: string) => ({queryKey: productTagsQueryKeys.detail(id),- queryFn: async () => sdk.admin.productTag.retrieve(id),+ queryFn: async () => sdk.admin.productTags.$id.query({ $id: id }),})export const productTagLoader = async ({ params }: LoaderFunctionArgs) => {diff --git a/packages/admin/src/pages/product-tags/product-tag-list/loader.ts b/packages/admin/src/pages/product-tags/product-tag-list/loader.tsindex e1e9f5850..4e6fd84fb 100644--- a/packages/admin/src/pages/product-tags/product-tag-list/loader.ts+++ b/packages/admin/src/pages/product-tags/product-tag-list/loader.ts@@ -1,13 +1,13 @@-import { HttpTypes } from "@medusajs/types"import { LoaderFunctionArgs } from "react-router-dom"import { productTagsQueryKeys } from "../../../hooks/api"import { sdk } from "../../../lib/client"import { queryClient } from "../../../lib/query-client"+import { InferClientInput } from "@mercurjs/client"-const productTagListQuery = (query?: HttpTypes.AdminProductTagListParams) => ({+const productTagListQuery = (query?: InferClientInput<typeof sdk.admin.productTags.query>) => ({queryKey: productTagsQueryKeys.list(query),- queryFn: async () => sdk.admin.productTag.list(query),+ queryFn: async () => sdk.admin.productTags.query({ ...query }),})export const productTagListLoader = async ({ request }: LoaderFunctionArgs) => {@@ -24,7 +24,7 @@ export const productTagListLoader = async ({ request }: LoaderFunctionArgs) => {})const query = productTagListQuery(- queryObject as HttpTypes.AdminProductTagListParams+ queryObject as InferClientInput<typeof sdk.admin.productTags.query>)return (diff --git a/packages/admin/src/pages/product-types/product-type-detail/loader.ts b/packages/admin/src/pages/product-types/product-type-detail/loader.tsindex 9bdbd5595..f8a2fe7ad 100644--- a/packages/admin/src/pages/product-types/product-type-detail/loader.ts+++ b/packages/admin/src/pages/product-types/product-type-detail/loader.ts@@ -6,7 +6,7 @@ import { queryClient } from "../../../lib/query-client"const productTypeDetailQuery = (id: string) => ({queryKey: productTypesQueryKeys.detail(id),- queryFn: async () => sdk.admin.productType.retrieve(id),+ queryFn: async () => sdk.admin.productTypes.$id.query({ $id: id }),})export const productTypeLoader = async ({ params }: LoaderFunctionArgs) => {diff --git a/packages/admin/src/pages/product-variants/product-variant-detail/loader.ts b/packages/admin/src/pages/product-variants/product-variant-detail/loader.tsindex 973bcb3a9..fd83db245 100644--- a/packages/admin/src/pages/product-variants/product-variant-detail/loader.ts+++ b/packages/admin/src/pages/product-variants/product-variant-detail/loader.ts@@ -10,7 +10,9 @@ const variantDetailQuery = (productId: string, variantId: string) => ({fields: VARIANT_DETAIL_FIELDS,}),queryFn: async () =>- sdk.admin.product.retrieveVariant(productId, variantId, {+ sdk.admin.products.$id.variants.$variantId.query({+ $id: productId,+ $variantId: variantId,fields: VARIANT_DETAIL_FIELDS,}),})diff --git a/packages/admin/src/pages/product-variants/product-variant-edit/loader.ts b/packages/admin/src/pages/product-variants/product-variant-edit/loader.tsindex c42c76428..5eaf53501 100644--- a/packages/admin/src/pages/product-variants/product-variant-edit/loader.ts+++ b/packages/admin/src/pages/product-variants/product-variant-edit/loader.ts@@ -5,7 +5,10 @@ import { sdk } from "../../../lib/client"import { queryClient } from "../../../lib/query-client"const queryFn = async (id: string, variantId: string) => {- return await sdk.admin.product.retrieveVariant(id, variantId)+ return await sdk.admin.products.$id.variants.$variantId.query({+ $id: id,+ $variantId: variantId,+ })}const editProductVariantQuery = (id: string, variantId: string) => ({diff --git a/packages/admin/src/pages/products/product-list/loader.ts b/packages/admin/src/pages/products/product-list/loader.tsindex 60eb724f9..36f2ec90f 100644--- a/packages/admin/src/pages/products/product-list/loader.ts+++ b/packages/admin/src/pages/products/product-list/loader.ts@@ -1,6 +1,5 @@import { QueryClient } from "@tanstack/react-query"-import { HttpTypes } from "@medusajs/types"import { productsQueryKeys } from "../../../hooks/api/products"import { sdk } from "../../../lib/client"import { queryClient } from "../../../lib/query-client"@@ -12,7 +11,7 @@ const productsListQuery = () => ({is_giftcard: false,}),queryFn: async () =>- sdk.admin.product.list({ limit: 20, offset: 0, is_giftcard: false }),+ sdk.admin.products.query({ limit: 20, offset: 0, is_giftcard: false }),})export const productsLoader = (client: QueryClient) => {@@ -20,9 +19,8 @@ export const productsLoader = (client: QueryClient) => {const query = productsListQuery()return (- queryClient.getQueryData<HttpTypes.AdminProductListResponse>(- query.queryKey- ) ?? (await client.fetchQuery(query))+ queryClient.getQueryData(query.queryKey) ??+ (await client.fetchQuery(query)))}}diff --git a/packages/admin/src/pages/products/product-stock/loader.ts b/packages/admin/src/pages/products/product-stock/loader.tsindex e3275c803..189a9e123 100644--- a/packages/admin/src/pages/products/product-stock/loader.ts+++ b/packages/admin/src/pages/products/product-stock/loader.ts@@ -1,4 +1,3 @@-import { HttpTypes } from "@medusajs/types"import { LoaderFunctionArgs } from "react-router-dom"import { sdk } from "../../../lib/client"import { PRODUCT_VARIANT_IDS_KEY } from "../common/constants"@@ -8,26 +7,24 @@ async function getProductStockData(id: string, productVariantIds?: string[]) {let offset = 0let totalCount = 0- let allVariants: HttpTypes.AdminProductVariant[] = []+ let allVariants: any[] = []do {- const { variants: chunk, count } = await sdk.admin.product.listVariants(- id,- {- id: productVariantIds,- offset,- limit: CHUNK_SIZE,- fields:- "id,title,sku,inventory_items,inventory_items.*,inventory_items.inventory,inventory_items.inventory.id,inventory_items.inventory.title,inventory_items.inventory.sku,*inventory_items.inventory.location_levels,product.thumbnail",- }- )+ const { variants: chunk, count } = await sdk.admin.products.$id.variants.query({+ $id: id,+ id: productVariantIds,+ offset,+ limit: CHUNK_SIZE,+ fields:+ "id,title,sku,inventory_items,inventory_items.*,inventory_items.inventory,inventory_items.inventory.id,inventory_items.inventory.title,inventory_items.inventory.sku,*inventory_items.inventory.location_levels,product.thumbnail",+ })allVariants = [...allVariants, ...chunk]totalCount = countoffset += CHUNK_SIZE} while (allVariants.length < totalCount)- const { stock_locations } = await sdk.admin.stockLocation.list({+ const { stock_locations } = await sdk.admin.stockLocations.query({limit: 9999,fields: "id,name",})diff --git a/packages/admin/src/pages/promotions/promotion-detail/loader.ts b/packages/admin/src/pages/promotions/promotion-detail/loader.tsindex 49d53da68..2588f5e0b 100644--- a/packages/admin/src/pages/promotions/promotion-detail/loader.ts+++ b/packages/admin/src/pages/promotions/promotion-detail/loader.ts@@ -5,7 +5,7 @@ import { queryClient } from "../../../lib/query-client"const promotionDetailQuery = (id: string) => ({queryKey: promotionsQueryKeys.detail(id),- queryFn: async () => sdk.admin.promotion.retrieve(id),+ queryFn: async () => sdk.admin.promotions.$id.query({ $id: id }),})export const promotionLoader = async ({ params }: LoaderFunctionArgs) => {diff --git a/packages/admin/src/pages/promotions/promotion-list/loader.ts b/packages/admin/src/pages/promotions/promotion-list/loader.tsindex 42ee44914..d007d7779 100644--- a/packages/admin/src/pages/promotions/promotion-list/loader.ts+++ b/packages/admin/src/pages/promotions/promotion-list/loader.ts@@ -1,4 +1,3 @@-import { HttpTypes } from "@medusajs/types"import { QueryClient } from "@tanstack/react-query"import { promotionsQueryKeys } from "../../../hooks/api/promotions"import { sdk } from "../../../lib/client"@@ -11,7 +10,7 @@ const params = {const promotionsListQuery = () => ({queryKey: promotionsQueryKeys.list(params),- queryFn: async () => sdk.admin.promotion.list(params),+ queryFn: async () => sdk.admin.promotions.query(params),})export const promotionsLoader = (client: QueryClient) => {@@ -19,9 +18,8 @@ export const promotionsLoader = (client: QueryClient) => {const query = promotionsListQuery()return (- queryClient.getQueryData<HttpTypes.AdminPromotionListResponse>(- query.queryKey- ) ?? (await client.fetchQuery(query))+ queryClient.getQueryData(query.queryKey) ??+ (await client.fetchQuery(query)))}}diff --git a/packages/admin/src/pages/refund-reasons/refund-reason-list/loader.ts b/packages/admin/src/pages/refund-reasons/refund-reason-list/loader.tsindex 05a7c6f41..77243867c 100644--- a/packages/admin/src/pages/refund-reasons/refund-reason-list/loader.ts+++ b/packages/admin/src/pages/refund-reasons/refund-reason-list/loader.ts@@ -4,7 +4,7 @@ import { queryClient } from "../../../lib/query-client"const refundReasonListQuery = () => ({queryKey: refundReasonsQueryKeys.list(),- queryFn: async () => sdk.admin.refundReason.list(),+ queryFn: async () => sdk.admin.refundReasons.query({}),})export const refundReasonListLoader = async () => {diff --git a/packages/admin/src/pages/regions/region-detail/loader.ts b/packages/admin/src/pages/regions/region-detail/loader.tsindex 470d78c7e..8b58df8b1 100644--- a/packages/admin/src/pages/regions/region-detail/loader.ts+++ b/packages/admin/src/pages/regions/region-detail/loader.ts@@ -1,4 +1,3 @@-import { HttpTypes } from "@medusajs/types"import { LoaderFunctionArgs } from "react-router-dom"import { regionsQueryKeys } from "../../../hooks/api/regions"import { sdk } from "../../../lib/client"@@ -8,9 +7,7 @@ import { REGION_DETAIL_FIELDS } from "./constants"const regionQuery = (id: string) => ({queryKey: regionsQueryKeys.detail(id),queryFn: async () =>- sdk.admin.region.retrieve(id, {- fields: REGION_DETAIL_FIELDS,- }),+ sdk.admin.regions.$id.query({ $id: id, fields: REGION_DETAIL_FIELDS }),})export const regionLoader = async ({ params }: LoaderFunctionArgs) => {@@ -18,8 +15,7 @@ export const regionLoader = async ({ params }: LoaderFunctionArgs) => {const query = regionQuery(id!)return (- queryClient.getQueryData<{ region: HttpTypes.AdminRegion }>(- query.queryKey- ) ?? (await queryClient.fetchQuery(query))+ queryClient.getQueryData(query.queryKey) ??+ (await queryClient.fetchQuery(query)))}diff --git a/packages/admin/src/pages/reservations/reservation-detail/loader.ts b/packages/admin/src/pages/reservations/reservation-detail/loader.tsindex 1088cfb4f..ba807de80 100644--- a/packages/admin/src/pages/reservations/reservation-detail/loader.ts+++ b/packages/admin/src/pages/reservations/reservation-detail/loader.ts@@ -5,7 +5,7 @@ import { queryClient } from "../../../lib/query-client"const reservationDetailQuery = (id: string) => ({queryKey: reservationItemsQueryKeys.detail(id),- queryFn: async () => sdk.admin.reservation.retrieve(id),+ queryFn: async () => sdk.admin.reservations.$id.query({ $id: id }),})export const reservationItemLoader = async ({ params }: LoaderFunctionArgs) => {diff --git a/packages/admin/src/pages/return-reasons/return-reason-list/loader.ts b/packages/admin/src/pages/return-reasons/return-reason-list/loader.tsindex 8caf38e1f..1af62324f 100644--- a/packages/admin/src/pages/return-reasons/return-reason-list/loader.ts+++ b/packages/admin/src/pages/return-reasons/return-reason-list/loader.ts@@ -1,21 +1,17 @@-import {- AdminReturnReasonListParams,- AdminReturnReasonListResponse,-} from "@medusajs/types"-import { returnReasonsQueryKeys } from "../../../hooks/api/return-reasons"import { sdk } from "../../../lib/client"import { queryClient } from "../../../lib/query-client"+import { InferClientInput } from "@mercurjs/client"-const returnReasonListQuery = (query?: AdminReturnReasonListParams) => ({+const returnReasonListQuery = (query?: InferClientInput<typeof sdk.admin.returnReasons.query>) => ({queryKey: returnReasonsQueryKeys.list(query),- queryFn: async () => sdk.admin.returnReason.list(query),+ queryFn: async () => sdk.admin.returnReasons.query({ ...query }),})export const returnReasonListLoader = async () => {const query = returnReasonListQuery()return (- queryClient.getQueryData<AdminReturnReasonListResponse>(query.queryKey) ??+ queryClient.getQueryData(query.queryKey) ??(await queryClient.fetchQuery(query)))}diff --git a/packages/admin/src/pages/sales-channels/sales-channel-detail/loader.ts b/packages/admin/src/pages/sales-channels/sales-channel-detail/loader.tsindex 7fdea88a5..b18f73464 100644--- a/packages/admin/src/pages/sales-channels/sales-channel-detail/loader.ts+++ b/packages/admin/src/pages/sales-channels/sales-channel-detail/loader.ts@@ -6,7 +6,7 @@ import { queryClient } from "../../../lib/query-client"const salesChannelDetailQuery = (id: string) => ({queryKey: productsQueryKeys.detail(id),- queryFn: async () => sdk.admin.salesChannel.retrieve(id),+ queryFn: async () => sdk.admin.salesChannels.$id.query({ $id: id }),})export const salesChannelLoader = async ({ params }: LoaderFunctionArgs) => {diff --git a/packages/admin/src/pages/shipping-option-types/shipping-option-type-detail/loader.ts b/packages/admin/src/pages/shipping-option-types/shipping-option-type-detail/loader.tsindex 65380f996..f8a3dbb19 100644--- a/packages/admin/src/pages/shipping-option-types/shipping-option-type-detail/loader.ts+++ b/packages/admin/src/pages/shipping-option-types/shipping-option-type-detail/loader.ts@@ -6,7 +6,7 @@ import { queryClient } from "../../../lib/query-client"const shippingOptionTypeDetailQuery = (id: string) => ({queryKey: shippingOptionTypesQueryKeys.detail(id),- queryFn: async () => sdk.admin.shippingOptionType.retrieve(id),+ queryFn: async () => sdk.admin.shippingOptionTypes.$id.query({ $id: id }),})export const shippingOptionTypeLoader = async ({diff --git a/packages/admin/src/pages/shipping-profiles/shipping-profile-detail/loader.ts b/packages/admin/src/pages/shipping-profiles/shipping-profile-detail/loader.tsindex 9e215a59c..2901677e4 100644--- a/packages/admin/src/pages/shipping-profiles/shipping-profile-detail/loader.ts+++ b/packages/admin/src/pages/shipping-profiles/shipping-profile-detail/loader.ts@@ -6,7 +6,7 @@ import { queryClient } from "../../../lib/query-client"const shippingProfileQuery = (id: string) => ({queryKey: shippingProfileQueryKeys.detail(id),- queryFn: async () => sdk.admin.shippingProfile.retrieve(id),+ queryFn: async () => sdk.admin.shippingProfiles.$id.query({ $id: id }),})export const shippingProfileLoader = async ({ params }: LoaderFunctionArgs) => {diff --git a/packages/admin/src/pages/tax-regions/tax-region-detail/loader.ts b/packages/admin/src/pages/tax-regions/tax-region-detail/loader.tsindex e7a57fbd7..f25a93a58 100644--- a/packages/admin/src/pages/tax-regions/tax-region-detail/loader.ts+++ b/packages/admin/src/pages/tax-regions/tax-region-detail/loader.ts@@ -5,7 +5,7 @@ import { queryClient } from "../../../lib/query-client"const taxRegionDetailQuery = (id: string) => ({queryKey: taxRegionsQueryKeys.detail(id),- queryFn: async () => sdk.admin.taxRegion.retrieve(id),+ queryFn: async () => sdk.admin.taxRegions.$id.query({ $id: id }),})export const taxRegionLoader = async ({ params }: LoaderFunctionArgs) => {diff --git a/packages/admin/src/pages/tax-regions/tax-region-province-detail/loader.ts b/packages/admin/src/pages/tax-regions/tax-region-province-detail/loader.tsindex 84d2f4d18..24f10d8dc 100644--- a/packages/admin/src/pages/tax-regions/tax-region-province-detail/loader.ts+++ b/packages/admin/src/pages/tax-regions/tax-region-province-detail/loader.ts@@ -5,7 +5,7 @@ import { queryClient } from "../../../lib/query-client"const taxRegionDetailQuery = (id: string) => ({queryKey: taxRegionsQueryKeys.detail(id),- queryFn: async () => sdk.admin.taxRegion.retrieve(id),+ queryFn: async () => sdk.admin.taxRegions.$id.query({ $id: id }),})export const taxRegionLoader = async ({ params }: LoaderFunctionArgs) => {diff --git a/packages/admin/src/pages/users/user-detail/loader.ts b/packages/admin/src/pages/users/user-detail/loader.tsindex 1f4ed8789..a83a59a2c 100644--- a/packages/admin/src/pages/users/user-detail/loader.ts+++ b/packages/admin/src/pages/users/user-detail/loader.ts@@ -6,7 +6,7 @@ import { queryClient } from "../../../lib/query-client"const userDetailQuery = (id: string) => ({queryKey: productsQueryKeys.detail(id),- queryFn: async () => sdk.admin.user.retrieve(id),+ queryFn: async () => sdk.admin.users.$id.query({ $id: id }),})export const userLoader = async ({ params }: LoaderFunctionArgs) => {