-
-
Notifications
You must be signed in to change notification settings - Fork 667
/
InvenTreeTable.tsx
682 lines (614 loc) · 20.4 KB
/
InvenTreeTable.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
import { t } from '@lingui/macro';
import {
ActionIcon,
Alert,
Box,
Indicator,
LoadingOverlay,
Space,
Stack,
Tooltip
} from '@mantine/core';
import { Group } from '@mantine/core';
import { modals } from '@mantine/modals';
import { showNotification } from '@mantine/notifications';
import { IconFilter, IconRefresh, IconTrash } from '@tabler/icons-react';
import { IconBarcode, IconPrinter } from '@tabler/icons-react';
import { useQuery } from '@tanstack/react-query';
import {
DataTable,
DataTableCellClickHandler,
DataTableSortStatus
} from 'mantine-datatable';
import { Fragment, useCallback, useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { api } from '../App';
import { ActionButton } from '../components/buttons/ActionButton';
import { ButtonMenu } from '../components/buttons/ButtonMenu';
import { ApiFormFieldSet } from '../components/forms/fields/ApiFormField';
import { ModelType } from '../enums/ModelType';
import { resolveItem } from '../functions/conversion';
import { extractAvailableFields, mapFields } from '../functions/forms';
import { getDetailUrl } from '../functions/urls';
import { TableState } from '../hooks/UseTable';
import { base_url } from '../main';
import { useLocalState } from '../states/LocalState';
import { TableColumn } from './Column';
import { TableColumnSelect } from './ColumnSelect';
import { DownloadAction } from './DownloadAction';
import { TableFilter } from './Filter';
import { FilterSelectDrawer } from './FilterSelectDrawer';
import { RowAction, RowActions } from './RowActions';
import { TableSearchInput } from './Search';
const defaultPageSize: number = 25;
/**
* Set of optional properties which can be passed to an InvenTreeTable component
*
* @param params : any - Base query parameters
* @param tableState : TableState - State manager for the table
* @param defaultSortColumn : string - Default column to sort by
* @param noRecordsText : string - Text to display when no records are found
* @param enableBulkDelete : boolean - Enable bulk deletion of records
* @param enableDownload : boolean - Enable download actions
* @param enableFilters : boolean - Enable filter actions
* @param enableSelection : boolean - Enable row selection
* @param enableSearch : boolean - Enable search actions
* @param enablePagination : boolean - Enable pagination
* @param enableRefresh : boolean - Enable refresh actions
* @param pageSize : number - Number of records per page
* @param barcodeActions : any[] - List of barcode actions
* @param tableFilters : TableFilter[] - List of custom filters
* @param tableActions : any[] - List of custom action groups
* @param printingActions : any[] - List of printing actions
* @param dataFormatter : (data: any) => any - Callback function to reformat data returned by server (if not in default format)
* @param rowActions : (record: any) => RowAction[] - Callback function to generate row actions
* @param onRowClick : (record: any, index: number, event: any) => void - Callback function when a row is clicked
* @param onCellClick : (event: any, record: any, recordIndex: number, column: any, columnIndex: number) => void - Callback function when a cell is clicked
* @param modelType: ModelType - The model type for the table
*/
export type InvenTreeTableProps<T = any> = {
params?: any;
defaultSortColumn?: string;
noRecordsText?: string;
enableBulkDelete?: boolean;
enableDownload?: boolean;
enableFilters?: boolean;
enableSelection?: boolean;
enableSearch?: boolean;
enablePagination?: boolean;
enableRefresh?: boolean;
pageSize?: number;
barcodeActions?: any[];
tableFilters?: TableFilter[];
tableActions?: React.ReactNode[];
printingActions?: any[];
rowExpansion?: any;
idAccessor?: string;
dataFormatter?: (data: any) => any;
rowActions?: (record: T) => RowAction[];
onRowClick?: (record: T, index: number, event: any) => void;
onCellClick?: DataTableCellClickHandler<T>;
modelType?: ModelType;
rowStyle?: (record: T, index: number) => any;
modelField?: string;
};
/**
* Default table properties (used if not specified)
*/
const defaultInvenTreeTableProps: InvenTreeTableProps = {
params: {},
noRecordsText: t`No records found`,
enableDownload: false,
enableFilters: true,
enablePagination: true,
enableRefresh: true,
enableSearch: true,
enableSelection: false,
pageSize: defaultPageSize,
defaultSortColumn: '',
printingActions: [],
barcodeActions: [],
tableFilters: [],
tableActions: [],
idAccessor: 'pk'
};
/**
* Table Component which extends DataTable with custom InvenTree functionality
*/
export function InvenTreeTable<T = any>({
url,
tableState,
columns,
props
}: {
url: string;
tableState: TableState;
columns: TableColumn<T>[];
props: InvenTreeTableProps<T>;
}) {
const { getTableColumnNames, setTableColumnNames } = useLocalState();
const [fieldNames, setFieldNames] = useState<Record<string, string>>({});
const navigate = useNavigate();
// Construct table filters - note that we can introspect filter labels from column names
const filters: TableFilter[] = useMemo(() => {
return (
props.tableFilters?.map((filter) => {
return {
...filter,
label: filter.label ?? fieldNames[filter.name] ?? `${filter.name}`
};
}) ?? []
);
}, [props.tableFilters, fieldNames]);
// Request OPTIONS data from the API, before we load the table
const tableOptionQuery = useQuery({
enabled: true,
queryKey: ['options', url, tableState.tableKey],
retry: 3,
refetchOnMount: true,
refetchOnWindowFocus: false,
queryFn: async () => {
return api
.options(url, {
params: tableProps.params
})
.then((response) => {
if (response.status == 200) {
// Extract field information from the API
let names: Record<string, string> = {};
let fields: ApiFormFieldSet =
extractAvailableFields(response, 'POST', true) || {};
// Extract flattened map of fields
mapFields(fields, (path, field) => {
if (field.label) {
names[path] = field.label;
}
});
const cacheKey = tableState.tableKey.split('-')[0];
setFieldNames(names);
setTableColumnNames(cacheKey)(names);
}
return null;
});
}
});
// Rebuild set of translated column names
useEffect(() => {
const cacheKey = tableState.tableKey.split('-')[0];
// First check the local cache
const cachedNames = getTableColumnNames(cacheKey);
if (Object.keys(cachedNames).length > 0) {
// Cached names are available - use them!
setFieldNames(cachedNames);
return;
}
// Otherwise, fetch the data from the API
tableOptionQuery.refetch();
}, [url, tableState.tableKey, props.params]);
// Build table properties based on provided props (and default props)
const tableProps: InvenTreeTableProps<T> = useMemo(() => {
return {
...defaultInvenTreeTableProps,
...props
};
}, [props]);
// Check if any columns are switchable (can be hidden)
const hasSwitchableColumns = columns.some(
(col: TableColumn) => col.switchable ?? true
);
const onSelectedRecordsChange = useCallback((records: any[]) => {
tableState.setSelectedRecords(records);
}, []);
// Update column visibility when hiddenColumns change
const dataColumns: any = useMemo(() => {
let cols = columns.map((col) => {
let hidden: boolean = col.hidden ?? false;
if (col.switchable ?? true) {
hidden = tableState.hiddenColumns.includes(col.accessor);
}
return {
...col,
hidden: hidden,
title: col.title ?? fieldNames[col.accessor] ?? `${col.accessor}`
};
});
// If row actions are available, add a column for them
if (tableProps.rowActions) {
cols.push({
accessor: 'actions',
title: ' ',
hidden: false,
switchable: false,
width: 50,
render: (record: any) => (
<RowActions
actions={tableProps.rowActions?.(record) ?? []}
disabled={tableState.selectedRecords.length > 0}
/>
)
});
}
return cols;
}, [
columns,
fieldNames,
tableProps.rowActions,
tableProps.enableSelection,
tableState.hiddenColumns,
tableState.selectedRecords
]);
// Callback when column visibility is toggled
function toggleColumn(columnName: string) {
let newColumns = [...dataColumns];
let colIdx = newColumns.findIndex((col) => col.accessor == columnName);
if (colIdx >= 0 && colIdx < newColumns.length) {
newColumns[colIdx].hidden = !newColumns[colIdx].hidden;
}
tableState.setHiddenColumns(
newColumns.filter((col) => col.hidden).map((col) => col.accessor)
);
}
// Filter list visibility
const [filtersVisible, setFiltersVisible] = useState<boolean>(false);
// Reset the pagination state when the search term changes
useEffect(() => {
tableState.setPage(1);
}, [tableState.searchTerm]);
/*
* Construct query filters for the current table
*/
function getTableFilters(paginate: boolean = false) {
let queryParams = {
...tableProps.params
};
// Add custom filters
if (tableState.activeFilters) {
tableState.activeFilters.forEach(
(flt) => (queryParams[flt.name] = flt.value)
);
}
// Add custom search term
if (tableState.searchTerm) {
queryParams.search = tableState.searchTerm;
}
// Pagination
if (tableProps.enablePagination && paginate) {
let pageSize = tableProps.pageSize ?? defaultPageSize;
queryParams.limit = pageSize;
queryParams.offset = (tableState.page - 1) * pageSize;
}
// Ordering
let ordering = getOrderingTerm();
if (ordering) {
if (sortStatus.direction == 'asc') {
queryParams.ordering = ordering;
} else {
queryParams.ordering = `-${ordering}`;
}
}
return queryParams;
}
// Data download callback
function downloadData(fileFormat: string) {
// Download entire dataset (no pagination)
let queryParams = getTableFilters(false);
// Specify file format
queryParams.export = fileFormat;
let downloadUrl = api.getUri({
url: url,
params: queryParams
});
// Download file in a new window (to force download)
window.open(downloadUrl, '_blank');
}
// Data Sorting
const [sortStatus, setSortStatus] = useState<DataTableSortStatus>({
columnAccessor: tableProps.defaultSortColumn ?? '',
direction: 'asc'
});
// Return the ordering parameter
function getOrderingTerm() {
let key = sortStatus.columnAccessor;
// Sorting column not specified
if (key == '') {
return '';
}
// Find matching column:
// If column provides custom ordering term, use that
let column = dataColumns.find((col: any) => col.accessor == key);
return column?.ordering || key;
}
// Missing records text (based on server response)
const [missingRecordsText, setMissingRecordsText] = useState<string>(
tableProps.noRecordsText ?? t`No records found`
);
const handleSortStatusChange = (status: DataTableSortStatus) => {
tableState.setPage(1);
setSortStatus(status);
};
// Function to perform API query to fetch required data
const fetchTableData = async () => {
let queryParams = getTableFilters(true);
return api
.get(url, {
params: queryParams,
timeout: 5 * 1000
})
.then(function (response) {
switch (response.status) {
case 200:
setMissingRecordsText(
tableProps.noRecordsText ?? t`No records found`
);
let results = response.data?.results ?? response.data ?? [];
if (props.dataFormatter) {
// Custom data formatter provided
results = props.dataFormatter(results);
}
if (!Array.isArray(results)) {
setMissingRecordsText(t`Server returned incorrect data type`);
results = [];
}
tableState.setRecordCount(response.data?.count ?? results.length);
return results;
case 400:
setMissingRecordsText(t`Bad request`);
break;
case 401:
setMissingRecordsText(t`Unauthorized`);
break;
case 403:
setMissingRecordsText(t`Forbidden`);
break;
case 404:
setMissingRecordsText(t`Not found`);
break;
default:
setMissingRecordsText(
t`Unknown error` + ': ' + response.statusText
);
break;
}
return [];
})
.catch(function (error) {
setMissingRecordsText(t`Error` + ': ' + error.message);
return [];
});
};
const { data, isFetching, refetch } = useQuery({
queryKey: [
tableState.page,
props.params,
sortStatus.columnAccessor,
sortStatus.direction,
tableState.tableKey,
tableState.activeFilters,
tableState.searchTerm
],
queryFn: fetchTableData,
refetchOnWindowFocus: false,
refetchOnMount: true
});
// Update tableState.records when new data received
useEffect(() => {
tableState.setRecords(data ?? []);
}, [data]);
// Callback function to delete the selected records in the table
const deleteSelectedRecords = useCallback(() => {
if (tableState.selectedRecords.length == 0) {
// Ignore if no records are selected
return;
}
modals.openConfirmModal({
title: t`Delete selected records`,
children: (
<Alert
color="red"
title={t`Are you sure you want to delete the selected records?`}
>
{t`This action cannot be undone!`}
</Alert>
),
labels: {
confirm: t`Delete`,
cancel: t`Cancel`
},
confirmProps: {
color: 'red'
},
onConfirm: () => {
// Delete the selected records
let selection = tableState.selectedRecords.map(
(record) => record.pk ?? record.id
);
api
.delete(url, {
data: {
items: selection
}
})
.then((_response) => {
// Refresh the table
refetch();
// Show notification
showNotification({
title: t`Deleted records`,
message: t`Records were deleted successfully`,
color: 'green'
});
})
.catch((_error) => {
console.warn(`Bulk delete operation failed at ${url}`);
showNotification({
title: t`Error`,
message: t`Failed to delete records`,
color: 'red'
});
});
}
});
}, [tableState.selectedRecords]);
// Callback when a row is clicked
const handleRowClick = useCallback(
(record: any, index: number, event: any) => {
if (props.onRowClick) {
// If a custom row click handler is provided, use that
props.onRowClick(record, index, event);
} else if (tableProps.modelType) {
const accessor = tableProps.modelField ?? 'pk';
const pk = resolveItem(record, accessor);
if (pk) {
// If a model type is provided, navigate to the detail view for that model
let url = getDetailUrl(tableProps.modelType, pk);
// Should it be opened in a new tab?
if (event?.ctrlKey || event?.shiftKey) {
// Open in a new tab
url = `/${base_url}${url}`;
window.open(url, '_blank');
} else {
// Navigate internally
navigate(url);
}
}
}
},
[props.onRowClick]
);
return (
<>
{tableProps.enableFilters && (filters.length ?? 0) > 0 && (
<FilterSelectDrawer
availableFilters={filters}
tableState={tableState}
opened={filtersVisible}
onClose={() => setFiltersVisible(false)}
/>
)}
<Stack spacing="sm">
<Group position="apart">
<Group position="left" key="custom-actions" spacing={5}>
{tableProps.tableActions?.map((group, idx) => (
<Fragment key={idx}>{group}</Fragment>
))}
{(tableProps.barcodeActions?.length ?? 0 > 0) && (
<ButtonMenu
key="barcode-actions"
icon={<IconBarcode />}
label={t`Barcode actions`}
tooltip={t`Barcode actions`}
actions={tableProps.barcodeActions ?? []}
/>
)}
{(tableProps.printingActions?.length ?? 0 > 0) && (
<ButtonMenu
key="printing-actions"
icon={<IconPrinter />}
label={t`Print actions`}
tooltip={t`Print actions`}
actions={tableProps.printingActions ?? []}
/>
)}
{(tableProps.enableBulkDelete ?? false) && (
<ActionButton
disabled={tableState.selectedRecords.length == 0}
icon={<IconTrash />}
color="red"
tooltip={t`Delete selected records`}
onClick={deleteSelectedRecords}
/>
)}
</Group>
<Space />
<Group position="right" spacing={5}>
{tableProps.enableSearch && (
<TableSearchInput
searchCallback={(term: string) =>
tableState.setSearchTerm(term)
}
/>
)}
{tableProps.enableRefresh && (
<ActionIcon>
<Tooltip label={t`Refresh data`}>
<IconRefresh onClick={() => refetch()} />
</Tooltip>
</ActionIcon>
)}
{hasSwitchableColumns && (
<TableColumnSelect
columns={dataColumns}
onToggleColumn={toggleColumn}
/>
)}
{tableProps.enableFilters && filters.length > 0 && (
<Indicator
size="xs"
label={tableState.activeFilters?.length ?? 0}
disabled={tableState.activeFilters?.length == 0}
>
<ActionIcon>
<Tooltip label={t`Table filters`}>
<IconFilter
onClick={() => setFiltersVisible(!filtersVisible)}
/>
</Tooltip>
</ActionIcon>
</Indicator>
)}
{tableProps.enableDownload && (
<DownloadAction
key="download-action"
downloadCallback={downloadData}
/>
)}
</Group>
</Group>
<Box pos="relative">
<LoadingOverlay
visible={tableOptionQuery.isLoading || tableOptionQuery.isFetching}
/>
<DataTable
withBorder
striped
highlightOnHover
loaderVariant="dots"
pinLastColumn={tableProps.rowActions != undefined}
idAccessor={tableProps.idAccessor}
minHeight={300}
totalRecords={tableState.recordCount}
recordsPerPage={tableProps.pageSize ?? defaultPageSize}
page={tableState.page}
onPageChange={tableState.setPage}
sortStatus={sortStatus}
onSortStatusChange={handleSortStatusChange}
selectedRecords={
tableProps.enableSelection
? tableState.selectedRecords
: undefined
}
onSelectedRecordsChange={
tableProps.enableSelection ? onSelectedRecordsChange : undefined
}
rowExpansion={tableProps.rowExpansion}
rowStyle={tableProps.rowStyle}
fetching={isFetching}
noRecordsText={missingRecordsText}
records={tableState.records}
columns={dataColumns}
onRowClick={handleRowClick}
onCellClick={tableProps.onCellClick}
defaultColumnProps={{
noWrap: true,
textAlignment: 'left',
cellsStyle: {
// TODO @SchrodingersGat : Need a better way of handling "wide" cells,
overflow: 'hidden'
}
}}
/>
</Box>
</Stack>
</>
);
}