drf-react-by-schema 0.5.0 → 0.5.2

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.
package/dist/api.js CHANGED
@@ -333,12 +333,12 @@ const prepareDataBySchema = ({ data, schema, parentIsField = false }) => {
333
333
  return dbData;
334
334
  };
335
335
  const updateDataBySchema = ({ model, modelObjectId, serverEndPoint, data, schema, path = null }) => __awaiter(void 0, void 0, void 0, function* () {
336
- // console.log({
337
- // model,
338
- // modelObjectId,
339
- // data,
340
- // schema
341
- // });
336
+ /*console.log({
337
+ model,
338
+ modelObjectId,
339
+ data,
340
+ schema
341
+ });*/
342
342
  const dbData = prepareDataBySchema({ data, schema });
343
343
  if (!path) {
344
344
  path = model;
@@ -4,6 +4,10 @@ type GridDecimalInputProps = {
4
4
  id: number | string;
5
5
  value?: any;
6
6
  column: object;
7
+ decimalPlaces?: number;
8
+ prefix?: string;
9
+ suffix?: string;
10
+ isCurrency?: boolean;
7
11
  };
8
- export declare const GridDecimalInput: ({ id, value, field }: GridDecimalInputProps) => JSX.Element;
12
+ export declare const GridDecimalInput: ({ id, value, field, decimalPlaces, prefix, suffix, isCurrency, }: GridDecimalInputProps) => JSX.Element;
9
13
  export {};
@@ -17,16 +17,21 @@ const react_1 = __importDefault(require("react"));
17
17
  const x_data_grid_1 = require("@mui/x-data-grid");
18
18
  const react_number_format_1 = require("react-number-format");
19
19
  const TextField_1 = __importDefault(require("@mui/material/TextField"));
20
- const GridDecimalInput = ({ id, value, field }) => {
20
+ const GridDecimalInput = ({ id, value, field, decimalPlaces, prefix, suffix, isCurrency, }) => {
21
21
  const apiRef = (0, x_data_grid_1.useGridApiContext)();
22
- const decimalScale = 2;
23
- const disableCurrency = true;
22
+ const prefixFinal = isCurrency
23
+ ? 'R$ '
24
+ : prefix !== ''
25
+ ? `${prefix} `
26
+ : '';
27
+ const suffixFinal = suffix !== '' ? ` ${suffix}` : '';
28
+ const decimalScale = decimalPlaces || 2;
24
29
  const handleChange = (newValue) => __awaiter(void 0, void 0, void 0, function* () {
25
30
  yield apiRef.current.setEditCellValue({ id, field, value: newValue });
26
31
  apiRef.current.stopCellEditMode({ id, field });
27
32
  });
28
- return (react_1.default.createElement(react_number_format_1.NumericFormat, { key: field, id: field, onValueChange: (values, sourceInfo) => {
33
+ return (react_1.default.createElement(react_number_format_1.NumericFormat, { key: field, id: field, onValueChange: (values) => {
29
34
  handleChange(values.value);
30
- }, value: value, thousandSeparator: '.', decimalSeparator: ',', decimalScale: decimalScale, fixedDecimalScale: true, valueIsNumericString: true, prefix: disableCurrency ? '' : 'R$ ', customInput: TextField_1.default }));
35
+ }, value: value, thousandSeparator: '.', decimalSeparator: ',', decimalScale: decimalScale, fixedDecimalScale: true, valueIsNumericString: true, prefix: prefixFinal, suffix: suffixFinal, customInput: TextField_1.default }));
31
36
  };
32
37
  exports.GridDecimalInput = GridDecimalInput;
@@ -1,7 +1,7 @@
1
1
  import React from 'react';
2
2
  import { SxProps } from '@mui/material';
3
3
  import { GridEnrichedBySchemaColDef } from '../../utils';
4
- import { OptionsACType } from '../../context/APIWrapperContext';
4
+ import { OptionsACType, OnEditModelType } from '../../context/APIWrapperContext';
5
5
  interface SelectEditInputCellProps {
6
6
  field: string;
7
7
  id: number | string;
@@ -11,6 +11,7 @@ interface SelectEditInputCellProps {
11
11
  optionsAC: React.MutableRefObject<OptionsACType | null>;
12
12
  isIndexField: boolean;
13
13
  multiple?: boolean;
14
+ onEditModel?: (p: OnEditModelType) => void;
14
15
  sx?: SxProps;
15
16
  }
16
17
  /**
@@ -29,5 +30,5 @@ interface SelectEditInputCellProps {
29
30
  * }
30
31
  * @returns {*} {JSX.Element}
31
32
  */
32
- export declare function SelectEditInputCell({ field, id, value, column, type, optionsAC, isIndexField, multiple, sx }: SelectEditInputCellProps): JSX.Element;
33
+ export declare function SelectEditInputCell({ field, id, value, column, type, optionsAC, isIndexField, multiple, onEditModel, sx }: SelectEditInputCellProps): JSX.Element;
33
34
  export {};
@@ -39,6 +39,8 @@ exports.SelectEditInputCell = void 0;
39
39
  const react_1 = __importDefault(require("react"));
40
40
  const x_data_grid_1 = require("@mui/x-data-grid");
41
41
  const TextField_1 = __importDefault(require("@mui/material/TextField"));
42
+ const IconButton_1 = __importDefault(require("@mui/material/IconButton"));
43
+ const Edit_1 = __importDefault(require("@mui/icons-material/Edit"));
42
44
  const Autocomplete_1 = __importStar(require("@mui/material/Autocomplete"));
43
45
  const utils_1 = require("../../utils");
44
46
  const filter = (0, Autocomplete_1.createFilterOptions)();
@@ -58,7 +60,7 @@ const filter = (0, Autocomplete_1.createFilterOptions)();
58
60
  * }
59
61
  * @returns {*} {JSX.Element}
60
62
  */
61
- function SelectEditInputCell({ field, id, value, column, type, optionsAC, isIndexField, multiple = false, sx = {} }) {
63
+ function SelectEditInputCell({ field, id, value, column, type, optionsAC, isIndexField, multiple = false, onEditModel, sx = {} }) {
62
64
  // TODO: allow edit option label, as in formautocomplete!
63
65
  const apiRef = (0, x_data_grid_1.useGridApiContext)();
64
66
  const handleChange = (newValue) => __awaiter(this, void 0, void 0, function* () {
@@ -135,6 +137,17 @@ function SelectEditInputCell({ field, id, value, column, type, optionsAC, isInde
135
137
  };
136
138
  }
137
139
  handleChange(newValue);
138
- }, fullWidth: true, renderInput: params => (react_1.default.createElement(TextField_1.default, Object.assign({}, params, { sx: sx }))) }, creatableProps)));
140
+ }, fullWidth: true, renderInput: params => (react_1.default.createElement(react_1.default.Fragment, null, column.creatable
141
+ ? react_1.default.createElement(TextField_1.default, Object.assign({}, params, { margin: "normal", InputProps: Object.assign(Object.assign({}, params.InputProps), { endAdornment: (react_1.default.createElement(react_1.default.Fragment, null,
142
+ !multiple && onEditModel && value && (react_1.default.createElement(IconButton_1.default, { size: "small", onClick: () => {
143
+ onEditModel({
144
+ model: field,
145
+ id: value[valueKey],
146
+ labelKey,
147
+ });
148
+ } },
149
+ react_1.default.createElement(Edit_1.default, null))),
150
+ params.InputProps.endAdornment)) }) }))
151
+ : react_1.default.createElement(TextField_1.default, Object.assign({}, params, { sx: sx })))) }, creatableProps)));
139
152
  }
140
153
  exports.SelectEditInputCell = SelectEditInputCell;
@@ -1,6 +1,7 @@
1
1
  import React from 'react';
2
2
  import { Item, SchemaType, Id, GridEnrichedBySchemaColDef } from '../utils';
3
3
  import { SxProps } from '@mui/material';
4
+ import { OnEditModelType } from '../context/APIWrapperContext';
4
5
  interface DataGridBySchemaEditableProps {
5
6
  schema: SchemaType;
6
7
  data: Item[];
@@ -23,6 +24,7 @@ interface DataGridBySchemaEditableProps {
23
24
  LinkComponent?: any;
24
25
  onProcessRow?: (p: any) => void;
25
26
  onDataChange?: (p: any) => void;
27
+ onEditModel?: (p: OnEditModelType) => void;
26
28
  isEditable?: boolean;
27
29
  sx?: SxProps;
28
30
  isAutoHeight?: boolean;
@@ -73,7 +73,7 @@ const APIWrapperContext_1 = require("../context/APIWrapperContext");
73
73
  const stringMask = require('string-mask');
74
74
  ;
75
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"]);
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, onEditModel, 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", "onEditModel", "isEditable", "sx", "isAutoHeight", "defaultValues", "hideFooterPagination", "setVisibleRows"]);
77
77
  const { serverEndPoint } = DRFReactBySchemaContext_1.DRFReactBySchemaContext
78
78
  ? react_1.default.useContext(DRFReactBySchemaContext_1.DRFReactBySchemaContext)
79
79
  : { serverEndPoint: null };
@@ -185,7 +185,7 @@ const DataGridBySchemaEditable = (0, react_1.forwardRef)((_a, ref) => {
185
185
  column.sortComparator = (v1, v2, param1, param2) => {
186
186
  return (0, x_data_grid_1.gridStringOrNumberComparator)(v1.label, v2.label, param1, param2);
187
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 }));
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, onEditModel: onEditModel }));
189
189
  break;
190
190
  }
191
191
  column.valueGetter = params => {
@@ -202,7 +202,7 @@ const DataGridBySchemaEditable = (0, react_1.forwardRef)((_a, ref) => {
202
202
  : params.value.map(val => val.label).join(', ');
203
203
  };
204
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 }));
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: schema[col.field].many || false }));
206
206
  break;
207
207
  }
208
208
  column.valueGetter = params => {
@@ -242,17 +242,21 @@ const DataGridBySchemaEditable = (0, react_1.forwardRef)((_a, ref) => {
242
242
  break;
243
243
  case 'decimal':
244
244
  case 'float':
245
+ const decimalScale = schema[col.field].decimal_places || 2;
246
+ const prefix = schema[col.field].prefix || '';
247
+ const suffix = schema[col.field].suffix || '';
248
+ const isCurrency = schema[col.field].is_currency;
245
249
  column.type = 'number';
246
250
  column.valueFormatter = params => {
247
251
  return (!params.value)
248
252
  ? ''
249
253
  : parseFloat(params.value).toLocaleString('pt-BR', {
250
- minimumFractionDigits: 2,
251
- maximumFractionDigits: 2
254
+ minimumFractionDigits: decimalScale,
255
+ maximumFractionDigits: decimalScale
252
256
  });
253
257
  };
254
258
  if (isEditable) {
255
- column.renderEditCell = (params) => react_1.default.createElement(GridDecimalInput_1.GridDecimalInput, Object.assign({}, params, { column: column }));
259
+ column.renderEditCell = (params) => react_1.default.createElement(GridDecimalInput_1.GridDecimalInput, Object.assign({}, params, { decimalScale: decimalScale, isCurrency: isCurrency, prefix: prefix, suffix: suffix, column: column }));
256
260
  }
257
261
  column.filterOperators = (0, utils_2.quantityOnlyOperators)({ type: 'float' });
258
262
  break;
@@ -55,7 +55,6 @@ const GenericModelList = ({ columnFields, hiddenFields = [], minWidthFields, ind
55
55
  }
56
56
  const { serverEndPoint, isInBatches, firstBatchLength } = context;
57
57
  const { handleLoading } = apiContext;
58
- ;
59
58
  const [data, setData] = (0, react_1.useState)(false);
60
59
  const [visibleRows, setVisibleRows] = (0, react_1.useState)([]);
61
60
  const [hideFooterPagination, setHideFooterPagination] = (0, react_1.useState)(false);
@@ -88,7 +88,7 @@ function APIWrapper({ setLoading, handleLoading, setSnackBar, setDialog, childre
88
88
  severity
89
89
  });
90
90
  };
91
- const loadSinglePageData = ({ model, objId, optionsACModels, extraValidators = {} }) => __awaiter(this, void 0, void 0, function* () {
91
+ const loadSinglePageData = ({ model, objId, optionsACModels, defaults = {}, extraValidators = {} }) => __awaiter(this, void 0, void 0, function* () {
92
92
  setLoading(true);
93
93
  if (!objId || objId === 'novo') {
94
94
  objId = (0, utils_1.getTmpId)();
@@ -105,6 +105,11 @@ function APIWrapper({ setLoading, handleLoading, setSnackBar, setDialog, childre
105
105
  }
106
106
  setLoading(false);
107
107
  populateOptionsAC(optionsACModels);
108
+ for (const [field, value] of Object.entries(defaults)) {
109
+ if (!object.data[field]) {
110
+ object.data[field] = value;
111
+ }
112
+ }
108
113
  const values = populateInitialValues(Object.assign({ model, id: objId, extraValidators }, object));
109
114
  return values;
110
115
  });
@@ -7,6 +7,7 @@ export interface LoadSinglePageDataProps {
7
7
  objId?: Id;
8
8
  objTitleField?: string;
9
9
  optionsACModels: string[];
10
+ defaults?: Item;
10
11
  basePath?: string;
11
12
  formPath?: string | null;
12
13
  extraValidators?: Item;
@@ -19,13 +20,13 @@ export interface PageFormType {
19
20
  validationSchema: Item | null;
20
21
  }
21
22
  export interface OnEditModelType {
22
- fieldKey: string;
23
- index: string;
23
+ fieldKey?: string;
24
+ index?: string;
24
25
  model: string;
25
26
  id: Id;
26
27
  labelKey: string;
27
- setValue: (p: any) => void;
28
- getValues: (p: any) => any;
28
+ setValue?: (p: any) => void;
29
+ getValues?: (p: any) => any;
29
30
  }
30
31
  export interface OnEditRelatedModelType {
31
32
  model: string;
package/dist/utils.d.ts CHANGED
@@ -16,8 +16,13 @@ export interface Field {
16
16
  model_required?: boolean;
17
17
  choices?: Choice[];
18
18
  max_length?: number | string;
19
+ max_digits?: number;
20
+ decimal_places?: number;
19
21
  label: string;
20
22
  read_only?: boolean;
23
+ is_currency?: boolean;
24
+ prefix?: string;
25
+ suffix?: string;
21
26
  }
22
27
  interface GridBySchemaColDef extends GridColDef {
23
28
  isIndexField?: boolean;
package/dist/utils.js CHANGED
@@ -69,8 +69,7 @@ const getChoiceByValue = (value, choices) => {
69
69
  exports.getChoiceByValue = getChoiceByValue;
70
70
  const populateValues = ({ data, schema }) => {
71
71
  const values = {};
72
- for (const entry of Object.entries(schema)) {
73
- const [key, field] = entry;
72
+ for (const [key, field] of Object.entries(schema)) {
74
73
  if (key === 'id' && (0, exports.isTmpId)(data[key])) {
75
74
  continue;
76
75
  }
@@ -141,6 +140,7 @@ const getYupValidator = (type) => {
141
140
  yupFunc = Yup.string();
142
141
  break;
143
142
  case 'number':
143
+ case 'decimal':
144
144
  yupFunc = Yup.number();
145
145
  break;
146
146
  case 'boolean':
@@ -206,6 +206,15 @@ const buildGenericYupValidationSchema = ({ data, schema, many = false, skipField
206
206
  if (field.max_length) {
207
207
  yupValidator[key] = yupValidator[key].max(parseInt(field.max_length), `Este campo só pode ter no máximo ${field.max_length} caracteres`);
208
208
  }
209
+ if (field.max_digits && field.type === 'decimal') {
210
+ const maxDigits = field.max_digits;
211
+ yupValidator[key] = yupValidator[key].test('len', `Este número pode ter no máximo ${maxDigits} dígitos`, (val) => {
212
+ if (!val) {
213
+ return true;
214
+ }
215
+ return val.toString().length <= maxDigits;
216
+ });
217
+ }
209
218
  }
210
219
  // console.log({ yupValidator });
211
220
  return (many)
package/package.json CHANGED
@@ -1,13 +1,12 @@
1
1
  {
2
2
  "name": "drf-react-by-schema",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Components and Tools for building a React App having Django Rest Framework (DRF) as server",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "scripts": {
8
8
  "test": "echo \"There are (still) no tests in this package\"",
9
9
  "build": "tsc",
10
- "prepare": "install-peers",
11
10
  "styleguide": "styleguidist server",
12
11
  "styleguide:build": "styleguidist build",
13
12
  "release:major": "yarn version --version $(semver $npm_package_version -i major) && yarn publish --tag latest",
@@ -1,39 +0,0 @@
1
- "use strict";
2
- var __rest = (this && this.__rest) || function (s, e) {
3
- var t = {};
4
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
- t[p] = s[p];
6
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
- t[p[i]] = s[p[i]];
10
- }
11
- return t;
12
- };
13
- var __importDefault = (this && this.__importDefault) || function (mod) {
14
- return (mod && mod.__esModule) ? mod : { "default": mod };
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- const react_1 = __importDefault(require("react"));
18
- const TextField_1 = __importDefault(require("@mui/material/TextField"));
19
- const utils_1 = require("../utils");
20
- function TextFieldBySchema(_a) {
21
- var { Controller, name, schema, control, errors, multiline = false, fieldKey = null, index = null, sx = { mr: 2 } } = _a, other = __rest(_a, ["Controller", "name", "schema", "control", "errors", "multiline", "fieldKey", "index", "sx"]);
22
- const model = name;
23
- if (fieldKey && index >= 0) {
24
- name = `${fieldKey}.${index}.${name}`;
25
- }
26
- const { error, helperText } = (fieldKey && index >= 0)
27
- ? (0, utils_1.errorProps)({
28
- fieldKey,
29
- index,
30
- fieldKeyProp: name,
31
- errors
32
- })
33
- : {
34
- error: errors && Boolean(errors[name]),
35
- helperText: (errors && errors[name]) ? errors[name].message : ''
36
- };
37
- return (react_1.default.createElement(Controller, { name: name, control: control, render: ({ field }) => (react_1.default.createElement(TextField_1.default, Object.assign({}, field, other, { id: name, key: name, label: schema[model].label, margin: "normal", fullWidth: true, multiline: multiline, error: error, helperText: helperText, sx: sx }))) }));
38
- }
39
- exports.default = TextFieldBySchema;