|
1
|
import { useMemo, useState } from "react" |
|
2
|
import { HttpTypes } from "@medusajs/types" |
|
3
|
import { Container, Button, DataTableRowSelectionState } from "@medusajs/ui" |
|
4
|
import { useTranslation } from "react-i18next" |
|
5
|
import { DataTable } from "../../data-table" |
|
6
|
import { SaveViewDialog } from "../save-view-dialog" |
|
7
|
import { SaveViewDropdown } from "./save-view-dropdown" |
|
8
|
import { useTableConfiguration } from "../../../hooks/table/use-table-configuration" |
|
9
|
import { useConfigurableTableColumns } from "../../../hooks/table/columns/use-configurable-table-columns" |
|
10
|
import { parseFilterParam } from "../../../hooks/table/query" |
|
11
|
import { |
|
12
|
createActionsColumn, |
|
13
|
createSelectColumn, |
|
14
|
TableAdapter, |
|
15
|
} from "../../../lib/table/table-adapters" |
|
16
|
|
|
17
|
type DataTableActionProps = { |
|
18
|
label: string |
|
19
|
disabled?: boolean |
|
20
|
} & ( |
|
21
|
| { |
|
22
|
to: string |
|
23
|
} |
|
24
|
| { |
|
25
|
onClick: () => void |
|
26
|
} |
|
27
|
) |
|
28
|
|
|
29
|
/** |
|
30
|
* Expand dotted param keys into nested objects so the SDK's qs serializer emits |
|
31
|
* bracket notation the endpoint's nested filter schema expects, e.g. |
|
32
|
* `{ "location_levels.location_id": ["x"] }` -> `{ location_levels: { location_id: ["x"] } }` |
|
33
|
* -> `location_levels[location_id][0]=x`. Keys without a dot pass through. |
|
34
|
*/ |
|
35
|
function expandDottedKeys(params: Record<string, any>): Record<string, any> { |
|
36
|
const result: Record<string, any> = {} |
|
37
|
for (const [key, value] of Object.entries(params)) { |
|
38
|
if (!key.includes(".")) { |
|
39
|
result[key] = value |
|
40
|
continue |
|
41
|
} |
|
42
|
const parts = key.split(".") |
|
43
|
let node = result |
|
44
|
for (let i = 0; i < parts.length - 1; i++) { |
|
45
|
if (typeof node[parts[i]] !== "object" || node[parts[i]] === null) { |
|
46
|
node[parts[i]] = {} |
|
47
|
} |
|
48
|
node = node[parts[i]] |
|
49
|
} |
|
50
|
node[parts[parts.length - 1]] = value |
|
51
|
} |
|
52
|
return result |
|
53
|
} |
|
54
|
|
|
55
|
export interface ConfigurableDataTableProps<TData> { |
|
56
|
adapter: TableAdapter<TData> |
|
57
|
heading?: string |
|
58
|
subHeading?: string |
|
59
|
pageSize?: number |
|
60
|
queryPrefix?: string |
|
61
|
layout?: "fill" | "auto" |
|
62
|
actions?: DataTableActionProps[] |
|
63
|
} |
|
64
|
|
|
65
|
export function ConfigurableDataTable<TData>({ |
|
66
|
adapter, |
|
67
|
heading, |
|
68
|
subHeading, |
|
69
|
pageSize: pageSizeProp, |
|
70
|
queryPrefix: queryPrefixProp, |
|
71
|
layout = "fill", |
|
72
|
actions, |
|
73
|
}: ConfigurableDataTableProps<TData>) { |
|
74
|
const { t } = useTranslation() |
|
75
|
const [saveDialogOpen, setSaveDialogOpen] = useState(false) |
|
76
|
const [editingView, setEditingView] = useState<any>(null) |
|
77
|
const [rowSelection, setRowSelection] = useState<DataTableRowSelectionState>( |
|
78
|
{} |
|
79
|
) |
|
80
|
|
|
81
|
const entity = adapter.entity |
|
82
|
const viewConfigKey = adapter.viewConfigurationKey ?? adapter.entity |
|
83
|
const entityName = adapter.entityName |
|
84
|
const pageSize = pageSizeProp || adapter.pageSize || 20 |
|
85
|
const queryPrefix = queryPrefixProp || adapter.queryPrefix || "" |
|
86
|
|
|
87
|
// Inject virtual columns (selection + actions) as API-shaped columns so they |
|
88
|
// flow through column ordering/visibility state. Their default_order keeps |
|
89
|
// selection first and actions last. |
|
90
|
const extraColumns = useMemo(() => { |
|
91
|
const cols = [ |
|
92
|
adapter.enableRowSelection ? createSelectColumn() : null, |
|
93
|
adapter.renderRowActions |
|
94
|
? createActionsColumn(t("fields.actions")) |
|
95
|
: null, |
|
96
|
].filter((c): c is HttpTypes.AdminColumn => c !== null) |
|
97
|
return cols.length ? cols : undefined |
|
98
|
}, [adapter, t]) |
|
99
|
|
|
100
|
const { |
|
101
|
activeView, |
|
102
|
createView, |
|
103
|
updateView, |
|
104
|
isViewConfigEnabled, |
|
105
|
visibleColumns, |
|
106
|
columnOrder, |
|
107
|
currentColumns, |
|
108
|
setColumnOrder, |
|
109
|
handleColumnVisibilityChange, |
|
110
|
currentConfiguration, |
|
111
|
hasConfigurationChanged, |
|
112
|
handleClearConfiguration, |
|
113
|
isLoadingColumns, |
|
114
|
isLoadingFilterOptions, |
|
115
|
apiColumns, |
|
116
|
filters, |
|
117
|
requiredFields, |
|
118
|
queryParams, |
|
119
|
} = useTableConfiguration({ |
|
120
|
entity, |
|
121
|
pageSize, |
|
122
|
queryPrefix, |
|
123
|
transformColumns: adapter.transformColumns, |
|
124
|
extraColumns, |
|
125
|
defaultFilters: adapter.defaultFilters, |
|
126
|
viewConfigurationKey: viewConfigKey, |
|
127
|
}) |
|
128
|
|
|
129
|
const parsedQueryParams: Record<string, any> = { ...queryParams } |
|
130
|
filters.forEach((filter) => { |
|
131
|
const filterKey = filter.id |
|
132
|
if (!filterKey || parsedQueryParams[filterKey] === undefined) { |
|
133
|
return |
|
134
|
} |
|
135
|
const value = parseFilterParam(parsedQueryParams[filterKey]) |
|
136
|
|
|
137
|
const paramKey = adapter.filterParamMap?.[filterKey] ?? filterKey |
|
138
|
if (paramKey !== filterKey) { |
|
139
|
delete parsedQueryParams[filterKey] |
|
140
|
} |
|
141
|
if (value === undefined) { |
|
142
|
delete parsedQueryParams[paramKey] |
|
143
|
} else { |
|
144
|
parsedQueryParams[paramKey] = value |
|
145
|
} |
|
146
|
}) |
|
147
|
|
|
148
|
const searchParams = { |
|
149
|
...expandDottedKeys(parsedQueryParams), |
|
150
|
fields: requiredFields, |
|
151
|
limit: pageSize, |
|
152
|
offset: parsedQueryParams.offset ? Number(parsedQueryParams.offset) : 0, |
|
153
|
} |
|
154
|
|
|
155
|
const fetchResult = adapter.useData(requiredFields, searchParams) |
|
156
|
|
|
157
|
const generatedColumns = useConfigurableTableColumns( |
|
158
|
apiColumns || [], |
|
159
|
adapter |
|
160
|
) |
|
161
|
const columns = generatedColumns |
|
162
|
|
|
163
|
if (fetchResult.isError) { |
|
164
|
throw fetchResult.error |
|
165
|
} |
|
166
|
|
|
167
|
const handleSaveAsDefault = async () => { |
|
168
|
try { |
|
169
|
if (activeView?.is_system_default) { |
|
170
|
await updateView.mutateAsync({ |
|
171
|
name: activeView.name || null, |
|
172
|
configuration: { |
|
173
|
visible_columns: currentColumns.visible, |
|
174
|
column_order: currentColumns.order, |
|
175
|
filters: currentConfiguration.filters || {}, |
|
176
|
sorting: currentConfiguration.sorting || null, |
|
177
|
search: currentConfiguration.search || "", |
|
178
|
}, |
|
179
|
}) |
|
180
|
} else { |
|
181
|
await createView.mutateAsync({ |
|
182
|
name: "Default", |
|
183
|
is_system_default: true, |
|
184
|
set_active: true, |
|
185
|
configuration: { |
|
186
|
visible_columns: currentColumns.visible, |
|
187
|
column_order: currentColumns.order, |
|
188
|
filters: currentConfiguration.filters || {}, |
|
189
|
sorting: currentConfiguration.sorting || null, |
|
190
|
search: currentConfiguration.search || "", |
|
191
|
}, |
|
192
|
}) |
|
193
|
} |
|
194
|
} catch (_) { |
|
195
|
// Error is handled by the hook |
|
196
|
} |
|
197
|
} |
|
198
|
|
|
199
|
const handleUpdateExisting = async () => { |
|
200
|
if (!activeView) { |
|
201
|
return |
|
202
|
} |
|
203
|
|
|
204
|
try { |
|
205
|
await updateView.mutateAsync({ |
|
206
|
name: activeView.name, |
|
207
|
configuration: { |
|
208
|
visible_columns: currentColumns.visible, |
|
209
|
column_order: currentColumns.order, |
|
210
|
filters: currentConfiguration.filters || {}, |
|
211
|
sorting: currentConfiguration.sorting || null, |
|
212
|
search: currentConfiguration.search || "", |
|
213
|
}, |
|
214
|
}) |
|
215
|
} catch (_) { |
|
216
|
// Error is handled by the hook |
|
217
|
} |
|
218
|
} |
|
219
|
|
|
220
|
const handleSaveAsNew = () => { |
|
221
|
setSaveDialogOpen(true) |
|
222
|
setEditingView(null) |
|
223
|
} |
|
224
|
|
|
225
|
// Filter bar content with save controls |
|
226
|
const filterBarContent = hasConfigurationChanged ? ( |
|
227
|
<> |
|
228
|
<Button |
|
229
|
variant="secondary" |
|
230
|
size="small" |
|
231
|
type="button" |
|
232
|
onClick={handleClearConfiguration} |
|
233
|
> |
|
234
|
{t("actions.clear")} |
|
235
|
</Button> |
|
236
|
<SaveViewDropdown |
|
237
|
isDefaultView={activeView?.is_system_default || !activeView} |
|
238
|
currentViewId={activeView?.id} |
|
239
|
currentViewName={activeView?.name} |
|
240
|
onSaveAsDefault={handleSaveAsDefault} |
|
241
|
onUpdateExisting={handleUpdateExisting} |
|
242
|
onSaveAsNew={handleSaveAsNew} |
|
243
|
/> |
|
244
|
</> |
|
245
|
) : null |
|
246
|
|
|
247
|
return ( |
|
248
|
<Container className="divide-y p-0"> |
|
249
|
<DataTable |
|
250
|
data={fetchResult.data || []} |
|
251
|
columns={columns} |
|
252
|
filters={filters} |
|
253
|
getRowId={adapter.getRowId || ((row: any) => row.id)} |
|
254
|
rowCount={fetchResult.count} |
|
255
|
enablePagination |
|
256
|
enableSearch |
|
257
|
pageSize={pageSize} |
|
258
|
isLoading={ |
|
259
|
fetchResult.isLoading || isLoadingColumns || isLoadingFilterOptions |
|
260
|
} |
|
261
|
layout={layout} |
|
262
|
heading={ |
|
263
|
heading || entityName || (entity ? t(`${entity}.domain` as any) : "") |
|
264
|
} |
|
265
|
subHeading={subHeading} |
|
266
|
enableColumnVisibility={isViewConfigEnabled} |
|
267
|
initialColumnVisibility={visibleColumns} |
|
268
|
onColumnVisibilityChange={handleColumnVisibilityChange} |
|
269
|
columnOrder={columnOrder} |
|
270
|
onColumnOrderChange={setColumnOrder} |
|
271
|
enableViewSelector={isViewConfigEnabled} |
|
272
|
entity={viewConfigKey} |
|
273
|
currentColumns={currentColumns} |
|
274
|
filterBarContent={filterBarContent} |
|
275
|
rowHref={adapter.getRowHref as ((row: any) => string) | undefined} |
|
276
|
emptyState={ |
|
277
|
adapter.emptyState || { |
|
278
|
empty: { |
|
279
|
heading: t( |
|
280
|
`${entity}.list.noRecordsMessage` as any, |
|
281
|
"There are no records to show" |
|
282
|
), |
|
283
|
}, |
|
284
|
} |
|
285
|
} |
|
286
|
prefix={queryPrefix} |
|
287
|
actions={actions} |
|
288
|
commands={adapter.commands} |
|
289
|
rowSelection={ |
|
290
|
adapter.enableRowSelection |
|
291
|
? { |
|
292
|
state: rowSelection, |
|
293
|
onRowSelectionChange: setRowSelection, |
|
294
|
enableRowSelection: true, |
|
295
|
} |
|
296
|
: undefined |
|
297
|
} |
|
298
|
/> |
|
299
|
|
|
300
|
{saveDialogOpen && ( |
|
301
|
<SaveViewDialog |
|
302
|
entity={viewConfigKey} |
|
303
|
currentColumns={currentColumns} |
|
304
|
currentConfiguration={currentConfiguration} |
|
305
|
editingView={editingView} |
|
306
|
onClose={() => { |
|
307
|
setSaveDialogOpen(false) |
|
308
|
setEditingView(null) |
|
309
|
}} |
|
310
|
onSaved={() => { |
|
311
|
setSaveDialogOpen(false) |
|
312
|
setEditingView(null) |
|
313
|
}} |
|
314
|
/> |
|
315
|
)} |
|
316
|
</Container> |
|
317
|
) |
|
318
|
} |