1 import { HttpTypes } from "@medusajs/types"
2 import {
3 Button,
4 Checkbox,
5 Container,
6 Heading,
7 toast,
8 usePrompt,
9 } from "@medusajs/ui"
10 import { RowSelectionState, createColumnHelper } from "@tanstack/react-table"
11 import { t } from "i18next"
12 import { useMemo, useState } from "react"
13
14 import { PencilSquare, Trash } from "@medusajs/icons"
15 import { keepPreviousData } from "@tanstack/react-query"
16 import { useTranslation } from "react-i18next"
17 import { Link } from "react-router-dom"
18
19 import {
20 Action,
21 ActionMenu,
22 } from "../../../../../components/common/action-menu"
23 import { PermissionGuard } from "../../../../../components/common/permission-guard"
24 import { _DataTable } from "../../../../../components/table/data-table"
25 import { useBatchCustomerCustomerGroups } from "../../../../../hooks/api"
26 import {
27 useCustomerGroups,
28 useRemoveCustomersFromGroup,
29 } from "../../../../../hooks/api/customer-groups"
30 import { useCustomerGroupTableColumns } from "../../../../../hooks/table/columns/use-customer-group-table-columns"
31 import { useCustomerGroupTableFilters } from "../../../../../hooks/table/filters/use-customer-group-table-filters"
32 import { useCustomerGroupTableQuery } from "../../../../../hooks/table/query/use-customer-group-table-query"
33 import { useDataTable } from "../../../../../hooks/use-data-table"
34 import { useCustomerPermissions } from "../../../../../hooks/use-resource-permissions"
35
36 type CustomerGroupSectionProps = {
37 customer: HttpTypes.AdminCustomer
38 }
39
40 const PAGE_SIZE = 10
41 const PREFIX = "cusgr"
42
43 export const CustomerGroupSection = ({
44 customer,
45 }: CustomerGroupSectionProps) => {
46 const prompt = usePrompt()
47 const { canUpdate } = useCustomerPermissions()
48
49 const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
50 const { raw, searchParams } = useCustomerGroupTableQuery({
51 pageSize: PAGE_SIZE,
52 prefix: PREFIX,
53 })
54
55 const { customer_groups, count, isLoading, isError, error } =
56 useCustomerGroups(
57 {
58 ...searchParams,
59 fields: "+customers.id",
60 customers: { id: customer.id },
61 },
62 {
63 placeholderData: keepPreviousData,
64 }
65 )
66
67 const { mutateAsync: batchCustomerCustomerGroups } =
68 useBatchCustomerCustomerGroups(customer.id)
69
70 const filters = useCustomerGroupTableFilters()
71 const columns = useColumns(customer.id)
72
73 const { table } = useDataTable({
74 data: customer_groups ?? [],
75 columns,
76 count,
77 getRowId: (row) => row.id,
78 enablePagination: true,
79 enableRowSelection: canUpdate, // Only allow selection if user can update
80 pageSize: PAGE_SIZE,
81 prefix: PREFIX,
82 rowSelection: {
83 state: rowSelection,
84 updater: setRowSelection,
85 },
86 })
87
88 const handleRemove = async () => {
89 const customerGroupIds = Object.keys(rowSelection)
90
91 const res = await prompt({
92 title: t("general.areYouSure"),
93 description: t("customers.groups.removeMany", {
94 groups: customer_groups
95 ?.filter((g) => customerGroupIds.includes(g.id))
96 .map((g) => g.name)
97 .join(","),
98 }),
99 confirmText: t("actions.remove"),
100 cancelText: t("actions.cancel"),
101 })
102
103 if (!res) {
104 return
105 }
106
107 await batchCustomerCustomerGroups(
108 { remove: customerGroupIds },
109 {
110 onSuccess: () => {
111 toast.success(
112 t("customers.groups.removed.success", {
113 groups: customer_groups!
114 .filter((cg) => customerGroupIds.includes(cg.id))
115 .map((cg) => cg?.name),
116 })
117 )
118 },
119 onError: (error) => {
120 toast.error(error.message)
121 },
122 }
123 )
124 }
125
126 if (isError) {
127 throw error
128 }
129
130 const commands = canUpdate
131 ? [
132 {
133 action: handleRemove,
134 label: t("actions.remove"),
135 shortcut: "r",
136 },
137 ]
138 : []
139
140 return (
141 <Container className="divide-y p-0">
142 <div className="flex items-center justify-between px-6 py-4">
143 <Heading level="h2">{t("customerGroups.domain")}</Heading>
144 <PermissionGuard resource="customer" operation="update">
145 <Link to={`/customers/${customer.id}/add-customer-groups`}>
146 <Button variant="secondary" size="small">
147 {t("general.add")}
148 </Button>
149 </Link>
150 </PermissionGuard>
151 </div>
152 <_DataTable
153 table={table}
154 columns={columns}
155 pageSize={PAGE_SIZE}
156 isLoading={isLoading}
157 count={count}
158 prefix={PREFIX}
159 navigateTo={(row) => `/customer-groups/${row.id}`}
160 filters={filters}
161 search
162 pagination
163 orderBy={[
164 { key: "name", label: t("fields.name") },
165 { key: "created_at", label: t("fields.createdAt") },
166 { key: "updated_at", label: t("fields.updatedAt") },
167 ]}
168 commands={commands}
169 queryObject={raw}
170 noRecords={{
171 message: t("customers.groups.list.noRecordsMessage"),
172 }}
173 />
174 </Container>
175 )
176 }
177
178 export const CustomerGroupRowActions = ({
179 group,
180 customerId,
181 }: {
182 group: HttpTypes.AdminCustomerGroup
183 customerId: string
184 }) => {
185 const prompt = usePrompt()
186 const { t } = useTranslation()
187 const { canUpdate } = useCustomerPermissions()
188
189 const { mutateAsync } = useRemoveCustomersFromGroup(group.id)
190
191 const onRemove = async () => {
192 const res = await prompt({
193 title: t("general.areYouSure"),
194 description: t("customers.groups.remove", {
195 name: group.name,
196 }),
197 confirmText: t("actions.remove"),
198 cancelText: t("actions.cancel"),
199 })
200
201 if (!res) {
202 return
203 }
204
205 await mutateAsync([customerId], {
206 onError: (error) => {
207 toast.error(error.message)
208 },
209 })
210 }
211
212 const actions: Action[] = []
213
214 actions.push({
215 label: t("actions.edit"),
216 icon: <PencilSquare />,
217 to: `/customer-groups/${group.id}/edit`,
218 })
219
220 if (canUpdate) {
221 actions.push({
222 label: t("actions.remove"),
223 onClick: onRemove,
224 icon: <Trash />,
225 })
226 }
227
228 if (!actions.length) {
229 return null
230 }
231
232 return (
233 <ActionMenu
234 groups={[
235 {
236 actions,
237 },
238 ]}
239 />
240 )
241 }
242
243 const columnHelper = createColumnHelper<HttpTypes.AdminCustomerGroup>()
244
245 const useColumns = (customerId: string) => {
246 const columns = useCustomerGroupTableColumns()
247 const { canUpdate } = useCustomerPermissions()
248
249 return useMemo(
250 () => [
251 // Only show select column if user can update
252 ...(canUpdate
253 ? [
254 columnHelper.display({
255 id: "select",
256 header: ({ table }) => {
257 return (
258 <Checkbox
259 checked={
260 table.getIsSomePageRowsSelected()
261 ? "indeterminate"
262 : table.getIsAllPageRowsSelected()
263 }
264 onCheckedChange={(value) =>
265 table.toggleAllPageRowsSelected(!!value)
266 }
267 />
268 )
269 },
270 cell: ({ row }) => {
271 return (
272 <Checkbox
273 checked={row.getIsSelected()}
274 onCheckedChange={(value) => row.toggleSelected(!!value)}
275 onClick={(e) => {
276 e.stopPropagation()
277 }}
278 />
279 )
280 },
281 }),
282 ]
283 : []),
284 ...columns,
285 columnHelper.display({
286 id: "actions",
287 cell: ({ row }) => (
288 <CustomerGroupRowActions
289 group={row.original}
290 customerId={customerId}
291 />
292 ),
293 }),
294 ],
295 [columns, customerId, canUpdate]
296 )
297 }