drf-react-by-schema 0.3.0 → 0.4.0

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