drf-react-by-schema 0.6.2 → 0.6.4

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.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { serverEndPointType } from './context/DRFReactBySchemaContext';
2
2
  import { Item, SchemaType, modelOptionsType, DataSchemaColumnsType, ItemSchemaColumnsType, PaginatedResult } from './utils';
3
- import { GridFilterModel } from '@mui/x-data-grid';
3
+ import { GridFilterModel, GridSortModel } from '@mui/x-data-grid';
4
4
  import { AlertColor } from '@mui/material/Alert';
5
5
  type Id = string | number | null;
6
6
  interface TargetApiParams {
@@ -71,6 +71,7 @@ export interface getGenericModelListProps {
71
71
  loadedModelOptions?: modelOptionsType | boolean;
72
72
  page?: number;
73
73
  filter?: GridFilterModel;
74
+ sort?: GridSortModel;
74
75
  sumRows?: SumRowsType;
75
76
  }
76
77
  export interface SumRowsType {
@@ -83,7 +84,7 @@ interface SumRowsItem {
83
84
  suffix?: string;
84
85
  isCount?: boolean;
85
86
  }
86
- export declare const getGenericModelList: ({ model, serverEndPoint, id, relatedModel, relatedModelId, columnFields, hiddenFields, creatableFields, isInBatches, loadedSchema, loadedModelOptions, page, filter, sumRows, }: getGenericModelListProps) => Promise<false | DataSchemaColumnsType>;
87
+ export declare const getGenericModelList: ({ model, serverEndPoint, id, relatedModel, relatedModelId, columnFields, hiddenFields, creatableFields, isInBatches, loadedSchema, loadedModelOptions, page, filter, sort, sumRows, }: getGenericModelListProps) => Promise<false | DataSchemaColumnsType>;
87
88
  export declare const getGenericModel: ({ model, serverEndPoint, id, relatedModel, relatedModelId, }: {
88
89
  model: string;
89
90
  serverEndPoint: serverEndPointType | null;
package/dist/api.js CHANGED
@@ -540,7 +540,7 @@ const isLoggedIn = (serverEndPoint) => __awaiter(void 0, void 0, void 0, functio
540
540
  return usuaria;
541
541
  });
542
542
  exports.isLoggedIn = isLoggedIn;
543
- const getGenericModelList = ({ model, serverEndPoint, id = '', relatedModel = '', relatedModelId = '', columnFields, hiddenFields = ['id'], creatableFields = [], isInBatches = false, loadedSchema, loadedModelOptions, page, filter, sumRows, }) => __awaiter(void 0, void 0, void 0, function* () {
543
+ const getGenericModelList = ({ model, serverEndPoint, id = '', relatedModel = '', relatedModelId = '', columnFields, hiddenFields = ['id'], creatableFields = [], isInBatches = false, loadedSchema, loadedModelOptions, page, filter, sort, sumRows, }) => __awaiter(void 0, void 0, void 0, function* () {
544
544
  let path = `${model}/${id}`;
545
545
  let schemaPath = model;
546
546
  let schema = loadedSchema;
@@ -550,17 +550,16 @@ const getGenericModelList = ({ model, serverEndPoint, id = '', relatedModel = ''
550
550
  path += `/${relatedModel}/${relatedModelId}`;
551
551
  schemaPath += `/${id}/${relatedModel}`;
552
552
  }
553
- if (page || filter || sumRows) {
554
- path += '?';
555
- }
553
+ const queryParams = [];
554
+ // SERVER-SIDE TOTALS (sumRows):
556
555
  if (sumRows) {
557
556
  const sumRowsParams = sumRows.rows.map(row => row.field).join(',');
558
- path += `sum_rows=${sumRowsParams}`;
557
+ queryParams.push(`sum_rows=${sumRowsParams}`);
559
558
  }
559
+ // SERVER-SIDE FILTERING:
560
560
  if (filter) {
561
- const filtersArr = [];
562
561
  if (filter.quickFilterValues && filter.quickFilterValues.length > 0 && filter.quickFilterValues[0]) {
563
- filtersArr.push(`search=${filter.quickFilterValues[0]}`);
562
+ queryParams.push(`search=${filter.quickFilterValues[0]}`);
564
563
  }
565
564
  for (const item of filter.items) {
566
565
  if (!item.operatorValue) {
@@ -569,18 +568,23 @@ const getGenericModelList = ({ model, serverEndPoint, id = '', relatedModel = ''
569
568
  const queryParam = item.value
570
569
  ? `columnField=${item.columnField}&operatorValue=${item.operatorValue}&value=${item.value}`
571
570
  : `columnField=${item.columnField}&operatorValue=${item.operatorValue}`;
572
- filtersArr.push(queryParam);
571
+ queryParams.push(queryParam);
573
572
  }
574
- if (sumRows) {
575
- path += '&';
573
+ }
574
+ // SERVER-SIDE SORTING:
575
+ if (sort) {
576
+ const sortParams = [];
577
+ for (const item of sort) {
578
+ sortParams.push(item.sort === 'desc' ? `-${item.field}` : item.field);
576
579
  }
577
- path += filtersArr.join('&');
580
+ queryParams.push(`ordering=${sortParams.join(',')}`);
578
581
  }
582
+ // SERVER-SIDE PAGINATION:
579
583
  if (page) {
580
- if (sumRows || filter) {
581
- path += '&';
582
- }
583
- path += `page=${page + 1}`;
584
+ queryParams.push(`page=${page + 1}`);
585
+ }
586
+ if (queryParams.length > 0) {
587
+ path += `?${queryParams.join('&')}`;
584
588
  }
585
589
  // Only get schema and columns if not in batches or in first batch:
586
590
  if (!schema) {
@@ -0,0 +1,11 @@
1
+ /// <reference types="react" />
2
+ import { CalendarPickerView } from '@mui/x-date-pickers/CalendarPicker';
3
+ type GridDateInputProps = {
4
+ field: string;
5
+ id: number | string;
6
+ value?: any;
7
+ column: object;
8
+ dateViews?: CalendarPickerView[] | undefined;
9
+ };
10
+ export declare const GridDateInput: ({ id, value, field, dateViews, }: GridDateInputProps) => JSX.Element;
11
+ export {};
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.GridDateInput = void 0;
16
+ const react_1 = __importDefault(require("react"));
17
+ const x_data_grid_1 = require("@mui/x-data-grid");
18
+ const TextField_1 = __importDefault(require("@mui/material/TextField"));
19
+ const DesktopDatePicker_1 = require("@mui/x-date-pickers/DesktopDatePicker");
20
+ const utils_1 = require("../../utils");
21
+ function buildOpenTo(dateViews) {
22
+ if (!dateViews || dateViews.includes('day')) {
23
+ return 'day';
24
+ }
25
+ if (dateViews.includes('month')) {
26
+ return 'month';
27
+ }
28
+ return 'year';
29
+ }
30
+ const GridDateInput = ({ id, value, field, dateViews, }) => {
31
+ const apiRef = (0, x_data_grid_1.useGridApiContext)();
32
+ const inputFormat = (0, utils_1.buildDateFormatBySchema)(dateViews);
33
+ const handleChange = (newValue) => __awaiter(void 0, void 0, void 0, function* () {
34
+ yield apiRef.current.setEditCellValue({ id, field, value: newValue });
35
+ apiRef.current.stopCellEditMode({ id, field });
36
+ });
37
+ const openTo = buildOpenTo(dateViews);
38
+ return (react_1.default.createElement(DesktopDatePicker_1.DesktopDatePicker, { key: field, value: value, onChange: handleChange, views: dateViews, openTo: openTo, inputFormat: inputFormat, renderInput: (params) => (react_1.default.createElement(TextField_1.default, Object.assign({}, params, { margin: "normal" }))) }));
39
+ };
40
+ exports.GridDateInput = GridDateInput;
@@ -63,7 +63,6 @@ const filter = (0, Autocomplete_1.createFilterOptions)();
63
63
  function SelectEditInputCell({ field, id, value, column, type, optionsAC, isIndexField, multiple = false, onEditModel, sx = {}, }) {
64
64
  // TODO: allow edit option label, as in formautocomplete!
65
65
  const apiRef = (0, x_data_grid_1.useGridApiContext)();
66
- console.log(column);
67
66
  const handleChange = (newValue) => __awaiter(this, void 0, void 0, function* () {
68
67
  yield apiRef.current.setEditCellValue({ id, field, value: newValue });
69
68
  apiRef.current.stopCellEditMode({ id, field });
@@ -64,6 +64,7 @@ const DRFReactBySchemaContext_1 = require("../context/DRFReactBySchemaContext");
64
64
  const utils_2 = require("./DataGridBySchemaEditable/utils");
65
65
  const CustomToolbar_1 = require("./DataGridBySchemaEditable/CustomToolbar");
66
66
  const SelectEditInputCell_1 = require("./DataGridBySchemaEditable/SelectEditInputCell");
67
+ const GridDateInput_1 = require("./DataGridBySchemaEditable/GridDateInput");
67
68
  const GridDecimalInput_1 = require("./DataGridBySchemaEditable/GridDecimalInput");
68
69
  const GridPatternInput_1 = require("./DataGridBySchemaEditable/GridPatternInput");
69
70
  const BooleanInputCell_1 = require("./DataGridBySchemaEditable/BooleanInputCell");
@@ -180,10 +181,15 @@ const DataGridBySchemaEditable = (0, react_1.forwardRef)((_a, ref) => {
180
181
  switch (schema[col.field].type) {
181
182
  case 'date':
182
183
  column.type = 'date';
183
- column.valueFormatter = (params) => params.value ? (0, moment_1.default)(params.value).format('DD/MM/YYYY') : '';
184
+ const dateFormat = (0, utils_1.buildDateFormatBySchema)(schema[col.field].date_views);
185
+ column.valueFormatter = (params) => params.value ? (0, moment_1.default)(params.value).format(dateFormat) : '';
184
186
  column.filterOperators = (0, utils_2.quantityOnlyOperators)({
185
187
  type: 'date',
186
188
  });
189
+ if (isEditable) {
190
+ column.renderEditCell = (params) => (react_1.default.createElement(GridDateInput_1.GridDateInput, Object.assign({}, params, { column: column, dateViews: schema[col.field].date_views })));
191
+ break;
192
+ }
187
193
  break;
188
194
  case 'datetime':
189
195
  column.type = 'dateTime';
@@ -615,6 +621,12 @@ const DataGridBySchemaEditable = (0, react_1.forwardRef)((_a, ref) => {
615
621
  setPaginationModel(Object.assign(Object.assign({}, paginationModel), { filter: newFilter }));
616
622
  }
617
623
  }
624
+ : undefined, sortingMode: paginationModel ? 'server' : 'client', onSortModelChange: paginationModel
625
+ ? (newSorting) => {
626
+ if (setPaginationModel && paginationModel) {
627
+ setPaginationModel(Object.assign(Object.assign({}, paginationModel), { sort: newSorting }));
628
+ }
629
+ }
618
630
  : undefined })),
619
631
  react_1.default.createElement(ConfirmDialog_1.ConfirmDialog, { open: dialogOpen, onClose: handleDialogClose, onConfirm: handleDeleteSave }),
620
632
  react_1.default.createElement(Snackbar_1.default, { open: snackBar.open, autoHideDuration: 5000, onClose: () => {
@@ -103,6 +103,7 @@ const GenericModelList = ({ columnFields, hiddenFields = [], minWidthFields, ind
103
103
  hiddenFields,
104
104
  page: paginationModel ? paginationModel.page : 0,
105
105
  filter: paginationModel ? paginationModel.filter : undefined,
106
+ sort: paginationModel ? paginationModel.sort : undefined,
106
107
  sumRows,
107
108
  };
108
109
  const paginatedData = yield (0, api_1.getGenericModelList)(loadPaginatedParams);
package/dist/utils.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { GridActionsColDef, GridColDef, GridFilterModel } from '@mui/x-data-grid';
1
+ import { CalendarPickerView } from '@mui/x-date-pickers/CalendarPicker';
2
+ import { GridActionsColDef, GridColDef, GridFilterModel, GridSortModel } from '@mui/x-data-grid';
2
3
  export type Id = string | number;
3
4
  export type Item = Record<string, any>;
4
5
  export type PaginatedResult = {
@@ -12,6 +13,7 @@ export interface PaginationModel {
12
13
  page: number;
13
14
  pageSize: number;
14
15
  filter?: GridFilterModel;
16
+ sort?: GridSortModel;
15
17
  }
16
18
  export type SchemaType = Record<string, Field>;
17
19
  export type modelOptionsType = Record<string, string>;
@@ -39,6 +41,7 @@ export interface Field {
39
41
  related_editable?: boolean;
40
42
  validators_regex?: Item[];
41
43
  many?: boolean;
44
+ date_views?: CalendarPickerView[];
42
45
  }
43
46
  interface GridBySchemaColDef extends GridColDef {
44
47
  isIndexField?: boolean;
@@ -95,4 +98,5 @@ export declare const isTmpId: (id: string | number | undefined | null) => boolea
95
98
  export declare const reducer: (state: Record<string, any> | null, newState: Record<string, any>) => Record<string, any> | null;
96
99
  export declare const getPatternFormat: (type: string) => string;
97
100
  export type AddParametersToEnd<TFunction extends (...args: any) => any, TParameters extends [...args: any]> = (...args: [...Parameters<TFunction>, ...TParameters]) => ReturnType<TFunction>;
101
+ export declare function buildDateFormatBySchema(dateViews: string[] | null | undefined): "DD/MM/yyyy" | "MM/yyyy" | "yyyy" | "MM" | "DD";
98
102
  export {};
package/dist/utils.js CHANGED
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.getPatternFormat = exports.reducer = exports.isTmpId = exports.getTmpId = exports.errorProps = exports.buildGenericYupValidationSchema = exports.populateValues = exports.getChoiceByValue = exports.emptyByType = void 0;
26
+ exports.buildDateFormatBySchema = exports.getPatternFormat = exports.reducer = exports.isTmpId = exports.getTmpId = exports.errorProps = exports.buildGenericYupValidationSchema = exports.populateValues = exports.getChoiceByValue = exports.emptyByType = void 0;
27
27
  const Yup = __importStar(require("yup"));
28
28
  ;
29
29
  ;
@@ -288,3 +288,29 @@ const getPatternFormat = (type) => {
288
288
  return format;
289
289
  };
290
290
  exports.getPatternFormat = getPatternFormat;
291
+ function buildDateFormatBySchema(dateViews) {
292
+ const defaultFormat = 'DD/MM/yyyy';
293
+ if (!dateViews) {
294
+ return defaultFormat;
295
+ }
296
+ const hasDay = dateViews.includes('day');
297
+ const hasMonth = dateViews.includes('month');
298
+ const hasYear = dateViews.includes('year');
299
+ if (hasDay && hasMonth && hasYear) {
300
+ return defaultFormat;
301
+ }
302
+ if (!hasDay && hasMonth && hasYear) {
303
+ return 'MM/yyyy';
304
+ }
305
+ if (!hasDay && !hasMonth && hasYear) {
306
+ return 'yyyy';
307
+ }
308
+ if (!hasDay && hasMonth && !hasYear) {
309
+ return 'MM';
310
+ }
311
+ if (hasDay && !hasMonth && !hasYear) {
312
+ return 'DD';
313
+ }
314
+ return defaultFormat;
315
+ }
316
+ exports.buildDateFormatBySchema = buildDateFormatBySchema;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drf-react-by-schema",
3
- "version": "0.6.2",
3
+ "version": "0.6.4",
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",