1 import { HttpTypes } from "@medusajs/types"
2 import { DataTableCommand, 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 { useRemoveCustomersFromGroup } from "../../../../../hooks/api/customer-groups"
8 import { useCustomers } from "../../../../../hooks/api/customers"
9 import { createTableAdapter } from "../../../../../lib/table/table-adapters"
10 import { CustomerActions } from "./customer-group-customer-section"
11
12 const ALLOWED_FILTERS = [
13 "email",
14 "first_name",
15 "last_name",
16 "has_account",
17 "created_at",
18 "updated_at",
19 "deleted_at",
20 ]
21
22 export const ConfigurableCustomerGroupCustomerSection = ({
23 group,
24 }: {
25 group: HttpTypes.AdminCustomerGroup
26 }) => {
27 const { t } = useTranslation()
28 const prompt = usePrompt()
29 const { mutateAsync } = useRemoveCustomersFromGroup(group.id)
30
31 const commands = useMemo<DataTableCommand[]>(
32 () => [
33 {
34 label: t("actions.remove"),
35 shortcut: "r",
36 action: async (selection) => {
37 const ids = Object.keys(selection)
38 const res = await prompt({
39 title: t("customerGroups.customers.remove.title", {
40 count: ids.length,
41 }),
42 description: t("customerGroups.customers.remove.description", {
43 count: ids.length,
44 }),
45 confirmText: t("actions.continue"),
46 cancelText: t("actions.cancel"),
47 })
48 if (!res) {
49 return
50 }
51 await mutateAsync(ids)
52 },
53 },
54 ],
55 [t, prompt, mutateAsync]
56 )
57
58 const adapter = useMemo(
59 () =>
60 createTableAdapter<HttpTypes.AdminCustomer>({
61 entity: "customers",
62 viewConfigurationKey: "customers-group",
63 queryPrefix: "cgcus",
64 pageSize: 10,
65 enableRowSelection: true,
66 commands,
67 emptyState: {
68 empty: {
69 heading: t("customerGroups.customers.list.noRecordsMessage"),
70 },
71 filtered: {
72 heading: t("general.noRecordsMessage"),
73 description: t("general.noRecordsMessageFiltered"),
74 },
75 },
76 useData: (fields, params) => {
77 const { customers, count, isError, error, isLoading } = useCustomers({
78 fields,
79 ...params,
80 groups: group.id,
81 })
82 return { data: customers, count, isLoading, isError, error }
83 },
84 getRowHref: (row) => `/customers/${row.id}`,
85 renderRowActions: (row) => (
86 <CustomerActions customer={row} customerGroupId={group.id} />
87 ),
88 transformColumns: (columns) =>
89 columns.map((column) => ({
90 ...column,
91 filter: !ALLOWED_FILTERS.includes(column.field)
92 ? { ...column.filter, enabled: false }
93 : column.filter,
94 })),
95 }),
96 [t, group.id, commands]
97 )
98
99 return (
100 <ConfigurableDataTable
101 adapter={adapter}
102 heading={t("customers.domain")}
103 actions={[{ label: t("general.add"), to: `add-customers` }]}
104 />
105 )
106 }