drf-react-by-schema 0.5.1 → 0.5.3

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;
@@ -377,7 +377,7 @@ const getDataGridColumns = (schema, columnFields = [], hiddenFields = [], creata
377
377
  field,
378
378
  headerName: schema[field].label,
379
379
  hide: (hiddenFields.includes(field)),
380
- creatable: (creatableFields.includes(field)),
380
+ creatable: (creatableFields.includes(field) || schema[field].creatable),
381
381
  width: 100
382
382
  };
383
383
  return column;
@@ -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;
@@ -74,7 +74,8 @@ function SelectEditInputCell({ field, id, value, column, type, optionsAC, isInde
74
74
  ? 'id'
75
75
  : 'value';
76
76
  let creatableProps = {};
77
- if (column.creatable || isIndexField) {
77
+ // if (column.creatable || isIndexField) {
78
+ if (column.creatable) {
78
79
  creatableProps = {
79
80
  freesolo: 'true',
80
81
  filterOptions: (options, params) => {
@@ -117,7 +118,8 @@ function SelectEditInputCell({ field, id, value, column, type, optionsAC, isInde
117
118
  }, getOptionLabel: (option) => {
118
119
  return option[labelKey];
119
120
  }, onChange: (e, value) => {
120
- if (!column.creatable && !isIndexField) {
121
+ // if (!column.creatable && !isIndexField) {
122
+ if (!column.creatable) {
121
123
  handleChange(value);
122
124
  return;
123
125
  }
@@ -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;
@@ -72,11 +72,14 @@ function APIWrapper({ setLoading, handleLoading, setSnackBar, setDialog, childre
72
72
  const [pageForm, setPageForm] = (0, react_1.useReducer)(utils_1.reducer, initialPageForm);
73
73
  const editModel = (0, react_1.useRef)({});
74
74
  const jsonSchemaFormRef = (0, react_1.useRef)(null);
75
- (0, react_1.useEffect)(() => {
75
+ const updateUsuaria = () => {
76
76
  setUsuaria(null);
77
77
  (0, api_1.isLoggedIn)(serverEndPoint).then(usuaria => {
78
78
  setUsuaria(usuaria || { erro: 'token inválido' });
79
79
  });
80
+ };
81
+ (0, react_1.useEffect)(() => {
82
+ updateUsuaria();
80
83
  }, []);
81
84
  (0, react_1.useEffect)(() => {
82
85
  setPageForm(initialPageForm);
@@ -88,7 +91,7 @@ function APIWrapper({ setLoading, handleLoading, setSnackBar, setDialog, childre
88
91
  severity
89
92
  });
90
93
  };
91
- const loadSinglePageData = ({ model, objId, optionsACModels, extraValidators = {} }) => __awaiter(this, void 0, void 0, function* () {
94
+ const loadSinglePageData = ({ model, objId, optionsACModels, defaults = {}, extraValidators = {} }) => __awaiter(this, void 0, void 0, function* () {
92
95
  setLoading(true);
93
96
  if (!objId || objId === 'novo') {
94
97
  objId = (0, utils_1.getTmpId)();
@@ -105,6 +108,11 @@ function APIWrapper({ setLoading, handleLoading, setSnackBar, setDialog, childre
105
108
  }
106
109
  setLoading(false);
107
110
  populateOptionsAC(optionsACModels);
111
+ for (const [field, value] of Object.entries(defaults)) {
112
+ if (!object.data[field]) {
113
+ object.data[field] = value;
114
+ }
115
+ }
108
116
  const values = populateInitialValues(Object.assign({ model, id: objId, extraValidators }, object));
109
117
  return values;
110
118
  });
@@ -326,6 +334,7 @@ function APIWrapper({ setLoading, handleLoading, setSnackBar, setDialog, childre
326
334
  });
327
335
  return (react_1.default.createElement(APIWrapperContext_1.APIWrapperContext.Provider, { value: {
328
336
  usuaria,
337
+ updateUsuaria,
329
338
  onSubmit,
330
339
  loadSinglePageData,
331
340
  handleLoading,
@@ -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;
@@ -57,6 +58,7 @@ export interface DialogType {
57
58
  export type DRFReactBySchemaSubmitHandler = (...args: [...[model: string, id: Id], ...Parameters<SubmitHandler<FieldValues>>]) => ReturnType<SubmitHandler<FieldValues>>;
58
59
  export interface APIWrapperContextType {
59
60
  usuaria: Item | null;
61
+ updateUsuaria: () => void;
60
62
  onSubmit: DRFReactBySchemaSubmitHandler;
61
63
  loadSinglePageData: (p: LoadSinglePageDataProps) => Promise<boolean | FieldValues>;
62
64
  handleLoading: (p: boolean) => void;
package/dist/utils.d.ts CHANGED
@@ -16,8 +16,15 @@ 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;
26
+ creatable?: boolean;
27
+ validators_regex?: Item[];
21
28
  }
22
29
  interface GridBySchemaColDef extends GridColDef {
23
30
  isIndexField?: boolean;
package/dist/utils.js CHANGED
@@ -51,6 +51,8 @@ const emptyByType = (field, forDatabase = false) => {
51
51
  return 0;
52
52
  case 'array':
53
53
  return [];
54
+ case 'boolean':
55
+ return false;
54
56
  default:
55
57
  return null;
56
58
  }
@@ -69,8 +71,7 @@ const getChoiceByValue = (value, choices) => {
69
71
  exports.getChoiceByValue = getChoiceByValue;
70
72
  const populateValues = ({ data, schema }) => {
71
73
  const values = {};
72
- for (const entry of Object.entries(schema)) {
73
- const [key, field] = entry;
74
+ for (const [key, field] of Object.entries(schema)) {
74
75
  if (key === 'id' && (0, exports.isTmpId)(data[key])) {
75
76
  continue;
76
77
  }
@@ -141,6 +142,7 @@ const getYupValidator = (type) => {
141
142
  yupFunc = Yup.string();
142
143
  break;
143
144
  case 'number':
145
+ case 'decimal':
144
146
  yupFunc = Yup.number();
145
147
  break;
146
148
  case 'boolean':
@@ -206,6 +208,20 @@ const buildGenericYupValidationSchema = ({ data, schema, many = false, skipField
206
208
  if (field.max_length) {
207
209
  yupValidator[key] = yupValidator[key].max(parseInt(field.max_length), `Este campo só pode ter no máximo ${field.max_length} caracteres`);
208
210
  }
211
+ if (field.max_digits && field.type === 'decimal') {
212
+ const maxDigits = field.max_digits;
213
+ yupValidator[key] = yupValidator[key].test('len', `Este número pode ter no máximo ${maxDigits} dígitos`, (val) => {
214
+ if (!val) {
215
+ return true;
216
+ }
217
+ return val.toString().length <= maxDigits;
218
+ });
219
+ }
220
+ if (field.validators_regex) {
221
+ for (const validator of field.validators_regex) {
222
+ yupValidator[key] = yupValidator[key].matches(validator.regex, validator.message);
223
+ }
224
+ }
209
225
  }
210
226
  // console.log({ yupValidator });
211
227
  return (many)
package/package.json CHANGED
@@ -1,13 +1,12 @@
1
1
  {
2
2
  "name": "drf-react-by-schema",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
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;