1 import { HttpTypes } from "@medusajs/types"
2 import { DataTableCommand, toast, usePrompt } from "@medusajs/ui"
3 import { useMemo } from "react"
4 import { useTranslation } from "react-i18next"
5
6 import { ConfigurableDataTable } from "../../../../../components/table/configurable-data-table"
7 import { useBatchCustomerCustomerGroups } from "../../../../../hooks/api"
8 import { useCustomerGroups } from "../../../../../hooks/api/customer-groups"
9 import { useCustomerPermissions } from "../../../../../hooks/use-resource-permissions"
10 import { createTableAdapter } from "../../../../../lib/table/table-adapters"
11 import { CustomerGroupRowActions } from "./customer-group-section"
12
13 export const ConfigurableCustomerGroupSection = ({
14 customer,
15 }: {
16 customer: HttpTypes.AdminCustomer
17 }) => {
18 const { t } = useTranslation()
19 const prompt = usePrompt()
20 const { canUpdate } = useCustomerPermissions()
21
22 const { mutateAsync } = useBatchCustomerCustomerGroups(customer.id)
23
24 const commands = useMemo<DataTableCommand[]>(() => {
25 if (!canUpdate) {
26 return []
27 }
28 return [
29 {
30 label: t("actions.remove"),
31 shortcut: "r",
32 action: async (selection) => {
33 const ids = Object.keys(selection)
34 const res = await prompt({
35 title: t("general.areYouSure"),
36 description: t("customers.groups.removeMany", {
37 groups: ids.join(","),
38 }),
39 confirmText: t("actions.remove"),
40 cancelText: t("actions.cancel"),
41 })
42 if (!res) {
43 return
44 }
45 await mutateAsync(
46 { remove: ids },
47 { onError: (e) => toast.error(e.message) }
48 )
49 },
50 },
51 ]
52 }, [t, prompt, mutateAsync, canUpdate])
53
54 const adapter = useMemo(
55 () =>
56 createTableAdapter<HttpTypes.AdminCustomerGroup>({
57 entity: "customer-groups",
58 viewConfigurationKey: "customer-groups-customer",
59 queryPrefix: "cusgr",
60 pageSize: 10,
61 enableRowSelection: canUpdate,
62 commands,
63 emptyState: {
64 empty: {
65 heading: t("customers.groups.list.noRecordsMessage"),
66 },
67 filtered: {
68 heading: t("general.noRecordsMessage"),
69 description: t("general.noRecordsMessageFiltered"),
70 },
71 },
72 useData: (fields, params) => {
73 const { customer_groups, count, isError, error, isLoading } =
74 useCustomerGroups({
75 fields: fields + ",+customers.id",
76 ...params,
77 customers: { id: customer.id },
78 })
79 return { data: customer_groups, count, isLoading, isError, error }
80 },
81 getRowHref: (row) => `/customer-groups/${row.id}`,
82 renderRowActions: (row) => (
83 <CustomerGroupRowActions group={row} customerId={customer.id} />
84 ),
85 }),
86 [t, customer.id, canUpdate, commands]
87 )
88
89 return (
90 <ConfigurableDataTable
91 adapter={adapter}
92 heading={t("customerGroups.domain")}
93 actions={
94 canUpdate
95 ? [{ label: t("general.add"), to: `add-customer-groups` }]
96 : []
97 }
98 />
99 )
100 }