drf-react-by-schema 0.2.2 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/api.d.ts +84 -0
  2. package/dist/api.js +613 -0
  3. package/dist/components/DataGridBySchemaEditable/ConfirmDialog.d.ts +8 -0
  4. package/dist/components/DataGridBySchemaEditable/ConfirmDialog.js +21 -0
  5. package/dist/components/DataGridBySchemaEditable/CustomToolbar.d.ts +16 -0
  6. package/dist/components/DataGridBySchemaEditable/CustomToolbar.js +77 -0
  7. package/dist/components/DataGridBySchemaEditable/FooterToolbar.d.ts +16 -0
  8. package/dist/components/DataGridBySchemaEditable/FooterToolbar.js +41 -0
  9. package/dist/components/DataGridBySchemaEditable/GridDecimalInput.d.ts +8 -0
  10. package/dist/components/DataGridBySchemaEditable/GridDecimalInput.js +32 -0
  11. package/dist/components/DataGridBySchemaEditable/GridPatternInput.d.ts +8 -0
  12. package/dist/components/DataGridBySchemaEditable/GridPatternInput.js +30 -0
  13. package/dist/components/DataGridBySchemaEditable/InputInterval.d.ts +3 -0
  14. package/dist/components/DataGridBySchemaEditable/InputInterval.js +105 -0
  15. package/dist/components/DataGridBySchemaEditable/SelectEditInputCell.d.ts +33 -0
  16. package/dist/components/DataGridBySchemaEditable/SelectEditInputCell.js +140 -0
  17. package/dist/components/DataGridBySchemaEditable/utils.d.ts +15 -0
  18. package/{src/components/DataGridBySchemaEditable/utils.ts → dist/components/DataGridBySchemaEditable/utils.js} +32 -50
  19. package/dist/components/DataGridBySchemaEditable.d.ts +34 -0
  20. package/dist/components/DataGridBySchemaEditable.js +549 -0
  21. package/dist/components/DataTotals.d.ts +14 -0
  22. package/dist/components/DataTotals.js +23 -0
  23. package/dist/components/DialogActions.d.ts +10 -0
  24. package/dist/components/DialogActions.js +17 -0
  25. package/dist/components/DialogJSONSchemaForm.d.ts +12 -0
  26. package/dist/components/DialogJSONSchemaForm.js +20 -0
  27. package/dist/components/FormButtons.d.ts +14 -0
  28. package/dist/components/FormButtons.js +39 -0
  29. package/dist/components/GenericModelList.d.ts +19 -0
  30. package/dist/components/GenericModelList.js +113 -0
  31. package/dist/components/GenericRelatedModelList.d.ts +25 -0
  32. package/dist/components/GenericRelatedModelList.js +111 -0
  33. package/dist/components/TextFieldBySchema.js +39 -0
  34. package/dist/context/APIWrapper.d.ts +12 -0
  35. package/dist/context/APIWrapper.js +341 -0
  36. package/dist/context/APIWrapperContext.d.ts +75 -0
  37. package/dist/context/APIWrapperContext.js +15 -0
  38. package/dist/context/DRFReactBySchemaContext.d.ts +20 -0
  39. package/dist/context/DRFReactBySchemaContext.js +19 -0
  40. package/dist/context/DRFReactBySchemaProvider.d.ts +13 -0
  41. package/dist/context/DRFReactBySchemaProvider.js +53 -0
  42. package/dist/context/Form.d.ts +11 -0
  43. package/dist/context/Form.js +82 -0
  44. package/dist/context/Overlays.d.ts +4 -0
  45. package/dist/context/Overlays.js +87 -0
  46. package/dist/index.d.ts +11 -0
  47. package/dist/index.js +14 -27
  48. package/{src/styles/index.ts → dist/styles/index.d.ts} +0 -1
  49. package/dist/styles/index.js +28 -0
  50. package/dist/styles/layout.d.ts +107 -0
  51. package/dist/styles/layout.js +56 -0
  52. package/dist/styles/theme.d.ts +21 -0
  53. package/dist/styles/theme.js +139 -0
  54. package/dist/utils.d.ts +75 -0
  55. package/dist/utils.js +268 -0
  56. package/package.json +15 -2
  57. package/.eslintrc.js +0 -14
  58. package/.gitlab-ci.yml +0 -14
  59. package/src/api.ts +0 -733
  60. package/src/components/DataGridBySchemaEditable/ConfirmDialog.tsx +0 -41
  61. package/src/components/DataGridBySchemaEditable/CustomToolbar.tsx +0 -93
  62. package/src/components/DataGridBySchemaEditable/FooterToolbar.tsx +0 -77
  63. package/src/components/DataGridBySchemaEditable/GridDecimalInput.tsx +0 -41
  64. package/src/components/DataGridBySchemaEditable/GridPatternInput.tsx +0 -37
  65. package/src/components/DataGridBySchemaEditable/InputInterval.tsx +0 -194
  66. package/src/components/DataGridBySchemaEditable/SelectEditInputCell.tsx +0 -153
  67. package/src/components/DataGridBySchemaEditable.md +0 -50
  68. package/src/components/DataGridBySchemaEditable.tsx +0 -747
  69. package/src/components/DataTotals.tsx +0 -56
  70. package/src/components/GenericModelList.tsx +0 -155
  71. package/src/context/DRFReactBySchemaProvider.md +0 -50
  72. package/src/context/DRFReactBySchemaProvider.tsx +0 -78
  73. package/src/index.ts +0 -64
  74. package/src/styles/layout.ts +0 -104
  75. package/src/styles/theme.ts +0 -190
  76. package/src/utils.ts +0 -321
  77. package/styleguide.config.js +0 -13
  78. package/tsconfig.json +0 -104
  79. package/webpack.config.js +0 -24
@@ -0,0 +1,549 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __rest = (this && this.__rest) || function (s, e) {
35
+ var t = {};
36
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
37
+ t[p] = s[p];
38
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
39
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
40
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
41
+ t[p[i]] = s[p[i]];
42
+ }
43
+ return t;
44
+ };
45
+ var __importDefault = (this && this.__importDefault) || function (mod) {
46
+ return (mod && mod.__esModule) ? mod : { "default": mod };
47
+ };
48
+ Object.defineProperty(exports, "__esModule", { value: true });
49
+ const react_1 = __importStar(require("react"));
50
+ const moment_1 = __importDefault(require("moment"));
51
+ const x_data_grid_1 = require("@mui/x-data-grid");
52
+ const Box_1 = __importDefault(require("@mui/material/Box"));
53
+ const CircularProgress_1 = __importDefault(require("@mui/material/CircularProgress"));
54
+ const Edit_1 = __importDefault(require("@mui/icons-material/Edit"));
55
+ const Clear_1 = __importDefault(require("@mui/icons-material/Clear"));
56
+ const Check_1 = __importDefault(require("@mui/icons-material/Check"));
57
+ const Undo_1 = __importDefault(require("@mui/icons-material/Undo"));
58
+ const Snackbar_1 = __importDefault(require("@mui/material/Snackbar"));
59
+ const Alert_1 = __importDefault(require("@mui/material/Alert"));
60
+ const styles_1 = require("../styles");
61
+ const api_1 = require("../api");
62
+ const utils_1 = require("../utils");
63
+ const DRFReactBySchemaContext_1 = require("../context/DRFReactBySchemaContext");
64
+ const utils_2 = require("./DataGridBySchemaEditable/utils");
65
+ const CustomToolbar_1 = require("./DataGridBySchemaEditable/CustomToolbar");
66
+ const SelectEditInputCell_1 = require("./DataGridBySchemaEditable/SelectEditInputCell");
67
+ const GridDecimalInput_1 = require("./DataGridBySchemaEditable/GridDecimalInput");
68
+ const GridPatternInput_1 = require("./DataGridBySchemaEditable/GridPatternInput");
69
+ const FooterToolbar_1 = require("./DataGridBySchemaEditable/FooterToolbar");
70
+ const ConfirmDialog_1 = require("./DataGridBySchemaEditable/ConfirmDialog");
71
+ const APIWrapperContext_1 = require("../context/APIWrapperContext");
72
+ const stringMask = require('string-mask');
73
+ ;
74
+ const DataGridBySchemaEditable = (0, react_1.forwardRef)((_a, ref) => {
75
+ var { schema, data, columns, model, fieldKey, labelKey = 'nome', index, name = Math.floor(Math.random() * 1000000).toString(), indexField = 'nome', addExistingModel, indexFieldMinWidth = 350, indexFieldBasePath = '', stateToLink = {}, minWidth = 80, modelParent, modelParentId, customColumnOperations, customLinkDestination, LinkComponent, onProcessRow, onDataChange, isEditable = false, sx = { mr: 2 }, isAutoHeight = false, defaultValues = {}, hideFooterPagination = false, setVisibleRows } = _a, other = __rest(_a, ["schema", "data", "columns", "model", "fieldKey", "labelKey", "index", "name", "indexField", "addExistingModel", "indexFieldMinWidth", "indexFieldBasePath", "stateToLink", "minWidth", "modelParent", "modelParentId", "customColumnOperations", "customLinkDestination", "LinkComponent", "onProcessRow", "onDataChange", "isEditable", "sx", "isAutoHeight", "defaultValues", "hideFooterPagination", "setVisibleRows"]);
76
+ const { serverEndPoint } = DRFReactBySchemaContext_1.DRFReactBySchemaContext
77
+ ? react_1.default.useContext(DRFReactBySchemaContext_1.DRFReactBySchemaContext)
78
+ : { serverEndPoint: null };
79
+ const apiContext = react_1.default.useContext(APIWrapperContext_1.APIWrapperContext);
80
+ const initialSnackBar = {
81
+ open: false,
82
+ msg: '',
83
+ severity: 'info'
84
+ };
85
+ const [snackBar, setSnackBar] = (0, react_1.useState)(initialSnackBar);
86
+ const [dataGrid, setDataGrid] = (0, react_1.useState)({ data: [] });
87
+ const [preparedColumns, setPreparedColumns] = (0, react_1.useState)(null);
88
+ const [dataGridLoading, setDataGridLoading] = (0, react_1.useState)(false);
89
+ const [rowModesModel, setRowModesModel] = (0, react_1.useState)({});
90
+ const [dialogOpen, setDialogOpen] = (0, react_1.useState)(false);
91
+ const optionsAC = (0, react_1.useRef)(null);
92
+ const emptyItem = (0, react_1.useRef)({});
93
+ const yupValidationSchema = (0, react_1.useRef)(null);
94
+ const processingRow = (0, react_1.useRef)(null);
95
+ const idToRemove = (0, react_1.useRef)(null);
96
+ const visibleRows = (0, react_1.useRef)('');
97
+ const updateOptionsAC = () => __awaiter(void 0, void 0, void 0, function* () {
98
+ optionsAC.current = {};
99
+ for (const col of columns) {
100
+ if (!schema[col.field]) {
101
+ continue;
102
+ }
103
+ if (['field', 'nested object'].includes(schema[col.field].type) && !(col.field in optionsAC.current)) {
104
+ const options = yield (0, api_1.getAutoComplete)({ model: col.field, serverEndPoint });
105
+ if (options) {
106
+ optionsAC.current[col.field] = options;
107
+ continue;
108
+ }
109
+ console.log(`Couldn't load autocomplete options from '${col.field}'`);
110
+ continue;
111
+ }
112
+ if (schema[col.field].type === 'choice' && !(col.field in optionsAC.current)) {
113
+ optionsAC.current[col.field] = schema[col.field].choices;
114
+ continue;
115
+ }
116
+ if (col.field === indexField && addExistingModel && !optionsAC.current[col.field]) {
117
+ const options = yield (0, api_1.getAutoComplete)({ model: addExistingModel, serverEndPoint });
118
+ if (options) {
119
+ optionsAC.current[col.field] = options;
120
+ continue;
121
+ }
122
+ if (!(col.field in optionsAC.current)) {
123
+ delete optionsAC.current[col.field];
124
+ }
125
+ }
126
+ }
127
+ });
128
+ const initColumns = () => {
129
+ let cols = [];
130
+ if (isEditable) {
131
+ cols.push({
132
+ field: 'actions',
133
+ headerName: '',
134
+ type: 'actions',
135
+ getActions: ({ id }) => {
136
+ var _a;
137
+ const isInEditMode = ((_a = rowModesModel[id]) === null || _a === void 0 ? void 0 : _a.mode) === x_data_grid_1.GridRowModes.Edit;
138
+ if (isInEditMode) {
139
+ return [
140
+ react_1.default.createElement(x_data_grid_1.GridActionsCellItem, { key: `save_${id}`, icon: react_1.default.createElement(Check_1.default, null), label: "Salvar", onClick: handleSaveClick(id), color: "success" }),
141
+ react_1.default.createElement(x_data_grid_1.GridActionsCellItem, { key: `cancel_${id}`, icon: react_1.default.createElement(Undo_1.default, null), label: "Cancelar", onClick: handleCancelClick(id), color: "inherit" })
142
+ ];
143
+ }
144
+ return [
145
+ react_1.default.createElement(x_data_grid_1.GridActionsCellItem, { key: `edit_${id}`, icon: react_1.default.createElement(Edit_1.default, null), label: "Edit", onClick: handleEditClick(id), color: "inherit" }),
146
+ react_1.default.createElement(x_data_grid_1.GridActionsCellItem, { key: `remove_${id}`, icon: react_1.default.createElement(Clear_1.default, null), label: "Delete", onClick: handleDeleteClick(id), color: "error" })
147
+ ];
148
+ }
149
+ });
150
+ }
151
+ cols = [...cols, ...columns];
152
+ cols = cols.map(col => {
153
+ if (!schema[col.field]) {
154
+ return col;
155
+ }
156
+ const isIndexField = (indexField !== '' && (col.field === indexField));
157
+ let column = col;
158
+ if (isIndexField) {
159
+ col.isIndexField = true;
160
+ }
161
+ column.editable = (isEditable) && (!schema[col.field].read_only || ['field', 'nested object'].includes(schema[col.field].type));
162
+ switch (schema[col.field].type) {
163
+ case 'date':
164
+ column.type = 'date';
165
+ column.valueFormatter = params => params.value
166
+ ? (0, moment_1.default)(params.value).format('DD/MM/YYYY')
167
+ : '';
168
+ column.filterOperators = (0, utils_2.quantityOnlyOperators)({ type: 'date' });
169
+ break;
170
+ case 'datetime':
171
+ column.type = 'dateTime';
172
+ column.minWidth = 180;
173
+ column.valueFormatter = params => params.value
174
+ ? (0, moment_1.default)(params.value).format('DD/MM/YYYY HH:mm')
175
+ : '';
176
+ break;
177
+ case 'nested object':
178
+ column.minWidth = 150;
179
+ if (isEditable) {
180
+ column.valueFormatter = params => {
181
+ return (!params.value) ? '' : params.value.label;
182
+ };
183
+ column.filterable = false;
184
+ column.sortComparator = (v1, v2, param1, param2) => {
185
+ return (0, x_data_grid_1.gridStringOrNumberComparator)(v1.label, v2.label, param1, param2);
186
+ };
187
+ column.renderEditCell = (params) => react_1.default.createElement(SelectEditInputCell_1.SelectEditInputCell, Object.assign({}, params, { column: column, type: schema[col.field].type, optionsAC: optionsAC, isIndexField: isIndexField }));
188
+ break;
189
+ }
190
+ column.valueGetter = params => {
191
+ return (!params.value) ? '' : params.value.label;
192
+ };
193
+ break;
194
+ case 'field':
195
+ column.orderable = false;
196
+ if (isEditable) {
197
+ column.minWidth = 300;
198
+ column.valueFormatter = params => {
199
+ return (!params.value || !Array.isArray(params.value))
200
+ ? ''
201
+ : params.value.map(val => val.label).join(', ');
202
+ };
203
+ column.filterable = false;
204
+ column.renderEditCell = (params) => react_1.default.createElement(SelectEditInputCell_1.SelectEditInputCell, Object.assign({}, params, { column: column, type: schema[col.field].type, optionsAC: optionsAC, isIndexField: isIndexField, multiple: true }));
205
+ break;
206
+ }
207
+ column.valueGetter = params => {
208
+ return (!params.value || !Array.isArray(params.value))
209
+ ? ''
210
+ : params.value.map(val => val.label).join(', ');
211
+ };
212
+ break;
213
+ case 'choice':
214
+ if (isEditable) {
215
+ column.minWidth = 150;
216
+ column.valueFormatter = params => {
217
+ return (!params.value) ? '' : params.value.display_name;
218
+ };
219
+ column.filterable = false;
220
+ column.sortComparator = (v1, v2, param1, param2) => {
221
+ return (0, x_data_grid_1.gridStringOrNumberComparator)(v1.display_name, v2.display_name, param1, param2);
222
+ };
223
+ column.renderEditCell = (params) => react_1.default.createElement(SelectEditInputCell_1.SelectEditInputCell, Object.assign({}, params, { column: column, type: schema[col.field].type, optionsAC: optionsAC, isIndexField: isIndexField }));
224
+ break;
225
+ }
226
+ column.valueGetter = params => {
227
+ return (!params.value) ? '' : params.value.display_name;
228
+ };
229
+ break;
230
+ case 'decimal':
231
+ case 'float':
232
+ column.type = 'number';
233
+ column.valueFormatter = params => {
234
+ return (!params.value)
235
+ ? ''
236
+ : parseFloat(params.value).toLocaleString('pt-BR', {
237
+ minimumFractionDigits: 2,
238
+ maximumFractionDigits: 2
239
+ });
240
+ };
241
+ if (isEditable) {
242
+ column.renderEditCell = (params) => react_1.default.createElement(GridDecimalInput_1.GridDecimalInput, Object.assign({}, params, { column: column }));
243
+ }
244
+ column.filterOperators = (0, utils_2.quantityOnlyOperators)({ type: 'float' });
245
+ break;
246
+ case 'number':
247
+ case 'integer':
248
+ column.type = 'number';
249
+ column.filterOperators = (0, utils_2.quantityOnlyOperators)({ type: 'number' });
250
+ break;
251
+ }
252
+ if (indexFieldMinWidth && !column.minWidth) {
253
+ column.minWidth = (col.field === indexField) ? indexFieldMinWidth : minWidth;
254
+ }
255
+ if (indexField) {
256
+ if (col.field === indexField) {
257
+ column.flex = 1;
258
+ column.renderCell = params => {
259
+ if (LinkComponent && customLinkDestination) {
260
+ return (react_1.default.createElement(LinkComponent, { to: `${customLinkDestination(params)}`, state: stateToLink }, params.formattedValue));
261
+ }
262
+ if (!LinkComponent ||
263
+ !indexFieldBasePath ||
264
+ (['field', 'nested object'].includes(schema[col.field].type) &&
265
+ (!params.row[col.field] || !params.row[col.field].id))) {
266
+ return (react_1.default.createElement(react_1.default.Fragment, null, params.formattedValue));
267
+ }
268
+ const targetId = (['field', 'nested object'].includes(schema[col.field].type))
269
+ ? params.row[col.field].id.toString()
270
+ : params.row.id.toString();
271
+ return (react_1.default.createElement(LinkComponent, { to: `${indexFieldBasePath}${targetId}`, state: stateToLink }, params.formattedValue));
272
+ };
273
+ if (isEditable &&
274
+ optionsAC.current &&
275
+ col.field in optionsAC.current &&
276
+ addExistingModel) {
277
+ column.renderEditCell = (params) => {
278
+ if (!(0, utils_1.isTmpId)(params.id)) {
279
+ return (react_1.default.createElement(x_data_grid_1.GridEditInputCell, Object.assign({}, params)));
280
+ }
281
+ return (react_1.default.createElement(SelectEditInputCell_1.SelectEditInputCell, Object.assign({}, params, { column: column, type: schema[col.field].type, optionsAC: optionsAC, isIndexField: true })));
282
+ };
283
+ }
284
+ }
285
+ }
286
+ // Custom column operations:
287
+ if (customColumnOperations) {
288
+ column = customColumnOperations(column);
289
+ }
290
+ // format numbers:
291
+ if (column.patternFormat) {
292
+ column.valueFormatter = params => {
293
+ if (!params.value || typeof params.value !== 'string') {
294
+ return params.value;
295
+ }
296
+ const formattedValue = new stringMask(column.patternFormat, {}).apply(params.value);
297
+ return formattedValue;
298
+ };
299
+ if (isEditable) {
300
+ column.renderEditCell = params => react_1.default.createElement(GridPatternInput_1.GridPatternInput, Object.assign({}, params, { patternFormat: column.patternFormat }));
301
+ }
302
+ }
303
+ // Finally!
304
+ return column;
305
+ });
306
+ setPreparedColumns(cols);
307
+ };
308
+ const handleDialogClose = () => {
309
+ setDialogOpen(false);
310
+ };
311
+ const handleRowEditStart = (params, event) => {
312
+ event.defaultMuiPrevented = true;
313
+ };
314
+ const handleRowEditStop = (params, event) => {
315
+ event.defaultMuiPrevented = true;
316
+ };
317
+ const handleEditClick = (id) => () => {
318
+ setRowModesModel(Object.assign(Object.assign({}, rowModesModel), { [id]: { mode: x_data_grid_1.GridRowModes.Edit } }));
319
+ };
320
+ const handleSaveClick = (id) => () => {
321
+ setRowModesModel(Object.assign(Object.assign({}, rowModesModel), { [id]: { mode: x_data_grid_1.GridRowModes.View } }));
322
+ };
323
+ const handleDeleteClick = (id) => () => {
324
+ idToRemove.current = id;
325
+ setDialogOpen(true);
326
+ };
327
+ const handleDeleteSave = () => {
328
+ if (idToRemove.current === null) {
329
+ setDialogOpen(false);
330
+ return;
331
+ }
332
+ const newData = dataGrid.data.filter(row => row.id !== idToRemove.current);
333
+ setDataGrid(Object.assign(Object.assign({}, dataGrid), { data: newData }));
334
+ if (modelParent && modelParentId && apiContext) {
335
+ apiContext.onDeleteRelatedModel({
336
+ model: modelParent,
337
+ id: modelParentId,
338
+ relatedModel: model,
339
+ relatedModelId: idToRemove.current
340
+ });
341
+ }
342
+ // Reflect changes to the outside, for example for doing global calculations over multiple rows:
343
+ if (onDataChange) {
344
+ onDataChange(newData);
345
+ }
346
+ idToRemove.current = null;
347
+ setDialogOpen(false);
348
+ };
349
+ const handleCancelClick = (id) => () => {
350
+ setRowModesModel(Object.assign(Object.assign({}, rowModesModel), { [id]: { mode: x_data_grid_1.GridRowModes.View, ignoreModifications: true } }));
351
+ const editedRow = dataGrid.data.find(row => row.id === id);
352
+ if (editedRow && editedRow.isNew) {
353
+ setDataGrid(Object.assign(Object.assign({}, dataGrid), { data: dataGrid.data.filter(row => row.id !== id) }));
354
+ }
355
+ };
356
+ (0, react_1.useEffect)(() => {
357
+ if (!columns) {
358
+ setDataGrid({ data: [] });
359
+ return;
360
+ }
361
+ if (isEditable) {
362
+ for (const col of columns) {
363
+ if (schema[col.field].model_default) {
364
+ emptyItem.current[col.field] = schema[col.field].model_default;
365
+ continue;
366
+ }
367
+ if (Object.prototype.hasOwnProperty.call(defaultValues, col.field)) {
368
+ emptyItem.current[col.field] = defaultValues[col.field];
369
+ continue;
370
+ }
371
+ emptyItem.current[col.field] = (schema[col.field])
372
+ ? (0, utils_1.emptyByType)(schema[col.field])
373
+ : null;
374
+ }
375
+ }
376
+ const skipFields = [];
377
+ if (indexField && addExistingModel) {
378
+ skipFields.push(indexField);
379
+ }
380
+ yupValidationSchema.current = (0, utils_1.buildGenericYupValidationSchema)({
381
+ data: emptyItem.current,
382
+ schema,
383
+ skipFields
384
+ });
385
+ setDataGrid({
386
+ data
387
+ });
388
+ }, [data]);
389
+ (0, react_1.useEffect)(() => {
390
+ if (optionsAC.current) {
391
+ initColumns();
392
+ return;
393
+ }
394
+ updateOptionsAC().then(() => {
395
+ initColumns();
396
+ });
397
+ }, [rowModesModel]);
398
+ const processRowUpdate = (newRow) => __awaiter(void 0, void 0, void 0, function* () {
399
+ if (!preparedColumns || !yupValidationSchema.current) {
400
+ return false;
401
+ }
402
+ setDataGridLoading(true);
403
+ const indexCol = preparedColumns.find(col => col.field === indexField);
404
+ processingRow.current = newRow.id;
405
+ yield yupValidationSchema.current.validate(newRow);
406
+ const onlyAddExisting = (indexField &&
407
+ (0, utils_1.isTmpId)(newRow.id) &&
408
+ (newRow[indexField] && !(0, utils_1.isTmpId)(newRow[indexField].id)) &&
409
+ (!indexCol || !indexCol.valueFormatter));
410
+ const createNewItem = (indexField && (0, utils_1.isTmpId)(newRow.id) && newRow[indexField] && (0, utils_1.isTmpId)(newRow[indexField].id));
411
+ if (onlyAddExisting) {
412
+ const row = {};
413
+ row.id_to_add = newRow[indexField].id;
414
+ for (const [key, value] of Object.entries(newRow[indexField])) {
415
+ if (key === 'id') {
416
+ row[key] = newRow.id;
417
+ continue;
418
+ }
419
+ row[key] = value;
420
+ }
421
+ newRow = Object.assign({}, row);
422
+ }
423
+ if (createNewItem && newRow[indexField]) {
424
+ if (newRow[indexField].inputValue) {
425
+ newRow[indexField] = newRow[indexField].inputValue;
426
+ }
427
+ if (addExistingModel) {
428
+ newRow[indexField] = newRow[indexField].label;
429
+ }
430
+ }
431
+ if (modelParent && modelParentId && apiContext) {
432
+ const response = yield apiContext.onEditRelatedModelSave({
433
+ model: modelParent,
434
+ id: modelParentId,
435
+ relatedModel: model,
436
+ relatedModelId: newRow.id,
437
+ newRow,
438
+ schema,
439
+ onlyAddExisting
440
+ });
441
+ const responseAsData = response;
442
+ if ((onlyAddExisting && typeof response != 'boolean') ||
443
+ (parseInt(response) && (createNewItem || !onlyAddExisting))) {
444
+ updateOptionsAC();
445
+ const data = [...dataGrid.data];
446
+ for (const i in data) {
447
+ if (data[i].id === newRow.id) {
448
+ data[i] = onlyAddExisting ? responseAsData.data : newRow;
449
+ if ((0, utils_1.isTmpId)(newRow.id)) {
450
+ const newId = parseInt(response);
451
+ data[i].id = newId || responseAsData.data.id;
452
+ }
453
+ // This is for cases where users want to do custom operations after saving the row,
454
+ // like for example make calculations among columns.
455
+ if (onProcessRow) {
456
+ onProcessRow(data[i]);
457
+ }
458
+ // Reflect the changes to the outside, for example for global calculations over all data
459
+ if (onDataChange) {
460
+ onDataChange(data);
461
+ }
462
+ setDataGrid({ data });
463
+ break;
464
+ }
465
+ }
466
+ setDataGridLoading(false);
467
+ return newRow;
468
+ }
469
+ }
470
+ setDataGridLoading(false);
471
+ return false;
472
+ });
473
+ const customPaddings = (isAutoHeight)
474
+ ? {
475
+ '&.MuiDataGrid-root--densityCompact .MuiDataGrid-cell': { py: '8px' },
476
+ '&.MuiDataGrid-root--densityStandard .MuiDataGrid-cell': { py: '15px' },
477
+ '&.MuiDataGrid-root--densityComfortable .MuiDataGrid-cell': { py: '22px' }
478
+ }
479
+ : undefined;
480
+ return (react_1.default.createElement(Box_1.default, { className: `dataGrid_${name}`, sx: { height: '100%' } },
481
+ preparedColumns === null
482
+ ? react_1.default.createElement(Box_1.default, { sx: styles_1.Layout.loadingBox },
483
+ react_1.default.createElement(CircularProgress_1.default, null))
484
+ : react_1.default.createElement(x_data_grid_1.DataGrid, { rows: dataGrid.data, columns: preparedColumns, onStateChange: (state) => {
485
+ if (setVisibleRows) {
486
+ const newVisibleRows = Object.entries(state.filter.visibleRowsLookup)
487
+ .filter(entry => { return entry[1] === true; })
488
+ .map((entry) => { return entry[0]; });
489
+ const newVisibleRowsJSON = JSON.stringify(newVisibleRows);
490
+ if (newVisibleRowsJSON !== visibleRows.current) {
491
+ setVisibleRows(newVisibleRows);
492
+ visibleRows.current = newVisibleRowsJSON;
493
+ }
494
+ }
495
+ }, editMode: "row", loading: dataGridLoading, hideFooterPagination: hideFooterPagination, getRowHeight: () => {
496
+ if (isAutoHeight) {
497
+ return 'auto';
498
+ }
499
+ return null;
500
+ }, isCellEditable: params => {
501
+ var _a;
502
+ return (((_a = rowModesModel[params.row.id]) === null || _a === void 0 ? void 0 : _a.mode) === x_data_grid_1.GridRowModes.Edit &&
503
+ (!(0, utils_1.isTmpId)(params.row.id) ||
504
+ ((0, utils_1.isTmpId)(params.row.id) &&
505
+ (params.field === indexField ||
506
+ !optionsAC.current ||
507
+ !Object.prototype.hasOwnProperty.call(optionsAC.current, indexField) ||
508
+ (preparedColumns.find(col => col.field === indexField) &&
509
+ Object.prototype.hasOwnProperty.call(preparedColumns.find(col => col.field === indexField), 'valueFormatter'))))));
510
+ }, rowModesModel: rowModesModel, onRowEditStart: handleRowEditStart, onRowEditStop: handleRowEditStop, processRowUpdate: processRowUpdate, onProcessRowUpdateError: (e) => {
511
+ setDataGridLoading(false);
512
+ if (processingRow.current) {
513
+ setRowModesModel(Object.assign(Object.assign({}, rowModesModel), { [processingRow.current]: { mode: x_data_grid_1.GridRowModes.Edit } }));
514
+ }
515
+ const msg = `Erro em "${e.path}": ${e.errors}`;
516
+ setSnackBar({
517
+ open: true,
518
+ severity: 'error',
519
+ msg
520
+ });
521
+ console.log(e);
522
+ }, components: { Toolbar: CustomToolbar_1.CustomToolbar, Footer: FooterToolbar_1.FooterToolbar }, componentsProps: {
523
+ toolbar: {
524
+ preparedColumns,
525
+ setPreparedColumns,
526
+ showQuickFilter: true,
527
+ quickFilterProps: { debounceMs: 500 }
528
+ },
529
+ footer: {
530
+ name,
531
+ setRowModesModel,
532
+ dataGrid,
533
+ setDataGrid,
534
+ emptyItem,
535
+ indexField,
536
+ isEditable
537
+ },
538
+ filterPanel: {
539
+ sx: {
540
+ '& .MuiDataGrid-filterFormValueInput': { width: 300 }
541
+ }
542
+ }
543
+ }, experimentalFeatures: { newEditingApi: isEditable }, sx: customPaddings }),
544
+ react_1.default.createElement(ConfirmDialog_1.ConfirmDialog, { open: dialogOpen, onClose: handleDialogClose, onConfirm: handleDeleteSave }),
545
+ react_1.default.createElement(Snackbar_1.default, { open: snackBar.open, autoHideDuration: 5000, onClose: () => { setSnackBar(Object.assign(Object.assign({}, initialSnackBar), { open: false })); }, anchorOrigin: { vertical: 'top', horizontal: 'center' } },
546
+ react_1.default.createElement(Alert_1.default, { severity: snackBar.severity }, snackBar.msg))));
547
+ });
548
+ DataGridBySchemaEditable.displayName = 'DataGridBySchemaEditable';
549
+ exports.default = DataGridBySchemaEditable;
@@ -0,0 +1,14 @@
1
+ import { AlertColor } from '@mui/material/Alert';
2
+ import { GridRowId } from '@mui/x-data-grid';
3
+ import { Item } from '../utils';
4
+ export interface SumRowsType {
5
+ rows: Item[];
6
+ severity?: AlertColor;
7
+ }
8
+ interface DataTotalsProps {
9
+ data?: Item[];
10
+ sumRows?: SumRowsType;
11
+ visibleRows: GridRowId[];
12
+ }
13
+ declare const DataTotals: ({ data, sumRows, visibleRows }: DataTotalsProps) => JSX.Element;
14
+ export default DataTotals;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const react_1 = __importDefault(require("react"));
7
+ const Alert_1 = __importDefault(require("@mui/material/Alert"));
8
+ const List_1 = __importDefault(require("@mui/material/List"));
9
+ const ListItem_1 = __importDefault(require("@mui/material/ListItem"));
10
+ const react_number_format_1 = require("react-number-format");
11
+ ;
12
+ const DataTotals = ({ data, sumRows, visibleRows }) => {
13
+ return (react_1.default.createElement(react_1.default.Fragment, null, data && sumRows && sumRows.rows.length > 0 &&
14
+ react_1.default.createElement(Alert_1.default, { severity: sumRows.severity || 'info' },
15
+ react_1.default.createElement(List_1.default, { dense: true }, sumRows.rows.map(row => (react_1.default.createElement(ListItem_1.default, { key: `sumRows_${row.field}` },
16
+ react_1.default.createElement(react_number_format_1.NumericFormat, { value: data.reduce((total, item) => {
17
+ if (parseFloat(item[row.field]) && visibleRows.includes(`${item.id}`)) {
18
+ return total + parseFloat(item[row.field]);
19
+ }
20
+ return total;
21
+ }, 0), thousandSeparator: '.', decimalSeparator: ',', displayType: 'text', decimalScale: row.isCount ? 0 : 2, fixedDecimalScale: true, prefix: row.prefix, suffix: row.suffix }))))))));
22
+ };
23
+ exports.default = DataTotals;
@@ -0,0 +1,10 @@
1
+ import React from 'react';
2
+ import { DialogType } from '../context/APIWrapperContext';
3
+ interface DialogActionsProps {
4
+ setDialog: React.Dispatch<React.SetStateAction<DialogType>>;
5
+ handleSave: (p: any) => Promise<boolean | undefined>;
6
+ btnCancel?: string;
7
+ btnConfirm?: string;
8
+ }
9
+ export default function DialogActions({ setDialog, handleSave, btnCancel, btnConfirm }: DialogActionsProps): JSX.Element;
10
+ export {};
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const react_1 = __importDefault(require("react"));
7
+ const Button_1 = __importDefault(require("@mui/material/Button"));
8
+ ;
9
+ function DialogActions({ setDialog, handleSave, btnCancel = 'Cancelar', btnConfirm = 'Salvar' }) {
10
+ return (react_1.default.createElement(react_1.default.Fragment, null,
11
+ react_1.default.createElement(Button_1.default, { onClick: () => {
12
+ setDialog({ open: false });
13
+ } }, btnCancel),
14
+ react_1.default.createElement(Button_1.default, { onClick: handleSave }, btnConfirm)));
15
+ }
16
+ exports.default = DialogActions;
17
+ ;
@@ -0,0 +1,12 @@
1
+ import { Item, SchemaType } from '../utils';
2
+ interface DialogJSONSchemaFormProps {
3
+ jsonSchemaFormRef: any;
4
+ schema: SchemaType;
5
+ uiSchema: SchemaType;
6
+ formData: Item;
7
+ onSubmit: ({ formData }: {
8
+ formData: Item;
9
+ }) => void;
10
+ }
11
+ export default function DialogJSONSchemaForm({ jsonSchemaFormRef, schema, uiSchema, formData, onSubmit }: DialogJSONSchemaFormProps): JSX.Element;
12
+ export {};
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const react_1 = __importDefault(require("react"));
7
+ const Button_1 = __importDefault(require("@mui/material/Button"));
8
+ const validator_ajv8_1 = __importDefault(require("@rjsf/validator-ajv8"));
9
+ const mui_1 = __importDefault(require("@rjsf/mui"));
10
+ ;
11
+ function DialogJSONSchemaForm({ jsonSchemaFormRef, schema, uiSchema, formData, onSubmit }) {
12
+ return (react_1.default.createElement(mui_1.default
13
+ // @ts-ignore
14
+ , {
15
+ // @ts-ignore
16
+ ref: jsonSchemaFormRef, schema: schema, uiSchema: uiSchema, validator: validator_ajv8_1.default, formData: formData, onSubmit: onSubmit },
17
+ react_1.default.createElement(Button_1.default, { type: "submit", sx: { display: 'none' } }, "Salvar")));
18
+ }
19
+ exports.default = DialogJSONSchemaForm;
20
+ ;
@@ -0,0 +1,14 @@
1
+ import PropTypes from 'prop-types';
2
+ import { SxProps } from '@mui/material';
3
+ interface FormButtonsProps {
4
+ title: string;
5
+ objId?: string | number;
6
+ formDisabled: boolean;
7
+ cancelBtn?: PropTypes.func;
8
+ bottom?: boolean;
9
+ borderBottom?: boolean;
10
+ saveAndContinue?: boolean;
11
+ sx?: SxProps;
12
+ }
13
+ export default function FormButtons({ title, objId, formDisabled, cancelBtn, sx, bottom, borderBottom, saveAndContinue }: FormButtonsProps): JSX.Element;
14
+ export {};