@ssplib/react-components 0.0.280 → 0.0.282

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.
@@ -1,8 +1,8 @@
1
1
  import React from 'react';
2
- import { TableProps } from './types';
2
+ import { TableProps2 } from './types';
3
3
  /**
4
4
  * Tabela cujo dados devem ser passados via props
5
5
  */
6
- export declare function GenericTable<T>({ mediaQueryLG, columns, emptyMsg, dataPath, tableName, csv, columnSize, action, useKC, statusKeyName, csvExcludeKeys, csvExcludeKeysCSV, csvExcludeKeysAll, csvCustomKeyNames, csvExcludeValidate, csvButtonTitle, csvNoZipText, csvAllButtonTitle, removeQuotes, normalize, csvShowAllButton, csvWithoutZip, itemCount, csvUpper, csvZipFileNamesKey, generateCsvZip, hideTitleCSV, csvExcludeUpper, multipleDataPath, expandTextMaxLength, collapsedSize, customMargin, customMarginMobile, filtersFunc, filters, orderBy, customErrorMsg, customTableStyle, id, initialData, isLoading, }: TableProps): JSX.Element;
6
+ export declare function GenericTable<T>({ mediaQueryLG, columns, emptyMsg, dataPath, tableName, csv, columnSize, action, useKC, statusKeyName, csvExcludeKeys, csvExcludeKeysCSV, csvExcludeKeysAll, csvCustomKeyNames, csvExcludeValidate, csvButtonTitle, csvNoZipText, csvAllButtonTitle, removeQuotes, normalize, csvShowAllButton, csvWithoutZip, itemCount, csvUpper, csvZipFileNamesKey, generateCsvZip, hideTitleCSV, csvExcludeUpper, multipleDataPath, expandTextMaxLength, collapsedSize, customMargin, customMarginMobile, filtersFunc, filters, orderBy, customErrorMsg, customTableStyle, id, initialData, isLoading, }: TableProps2): JSX.Element;
7
7
  declare const _default: React.MemoExoticComponent<typeof GenericTable>;
8
8
  export default _default;
@@ -1,5 +1,5 @@
1
1
  import React from 'react';
2
2
  import { TableProps } from './types';
3
- export declare function Table({ mediaQueryLG, columns, fetchFunc, emptyMsg, dataPath, tableName, csv, columnSize, action, useKC, statusKeyName, csvExcludeKeys, csvExcludeKeysCSV, csvExcludeKeysAll, csvCustomKeyNames, csvExcludeValidate, csvButtonTitle, csvNoZipText, csvAllButtonTitle, removeQuotes, normalize, csvShowAllButton, csvWithoutZip, itemCount, csvUpper, csvZipFileNamesKey, generateCsvZip, hideTitleCSV, csvExcludeUpper, multipleDataPath, expandTextMaxLength, collapsedSize, customMargin, customMarginMobile, filtersFunc, filters, orderBy, customErrorMsg, customTableStyle, id, initialData, isExpandable, }: TableProps): JSX.Element;
3
+ export declare function Table({ mediaQueryLG, columns, fetchFunc, emptyMsg, dataPath, tableName, csvConfig, csv, columnSize, action, useKC, itemCount, expandTextMaxLength, collapsedSize, customMargin, customMarginMobile, filtersFunc, filters, orderBy, customErrorMsg, customTableStyle, id, initialData, isExpandable, }: TableProps): JSX.Element;
4
4
  declare const _default: React.MemoExoticComponent<typeof Table>;
5
5
  export default _default;
@@ -53,8 +53,11 @@ let localTableNameCache = '';
53
53
  function Table({ mediaQueryLG, columns, fetchFunc, emptyMsg = {
54
54
  user: 'Nenhum dado encontrado',
55
55
  public: 'Nenhum dado encontrado',
56
- }, dataPath = '', tableName = 'Dado', csv, columnSize, action, useKC = true, statusKeyName = '', csvExcludeKeys = [], csvExcludeKeysCSV = [], csvExcludeKeysAll = [], csvCustomKeyNames = {}, csvExcludeValidate = (key, value) => false, csvButtonTitle = 'Salvar .CSV', csvNoZipText = 'Salvar .CSV', csvAllButtonTitle = 'Salvar todos em CSV', removeQuotes = false, normalize = false, csvShowAllButton = false, csvWithoutZip = false, itemCount = 10, csvUpper = false, csvZipFileNamesKey = '', generateCsvZip = false, hideTitleCSV = false, csvExcludeUpper = [], multipleDataPath = '', expandTextMaxLength = 50, collapsedSize = 53, customMargin = 4, customMarginMobile = 0, filtersFunc, filters = [], orderBy = [], customErrorMsg = undefined, customTableStyle = {}, id, initialData = null, isExpandable = true, }) {
57
- var _a;
56
+ }, dataPath = '', tableName = 'Dado', csvConfig = {
57
+ fileName: tableName,
58
+ map: []
59
+ }, csv, columnSize, action, useKC = true, itemCount = 10, expandTextMaxLength = 50, collapsedSize = 53, customMargin = 4, customMarginMobile = 0, filtersFunc, filters = [], orderBy = [], customErrorMsg = undefined, customTableStyle = {}, id, initialData = null, isExpandable = true, }) {
60
+ var _a, _b;
58
61
  const [isLoading, setIsLoading] = (0, react_1.useState)(false);
59
62
  const [error, setError] = (0, react_1.useState)(null);
60
63
  const [data, setData] = (0, react_1.useState)(initialData);
@@ -299,27 +302,9 @@ function Table({ mediaQueryLG, columns, fetchFunc, emptyMsg = {
299
302
  localStorage.removeItem(localTableName);
300
303
  setFilterKey(new Date().getTime().toString());
301
304
  }
302
- const handleCSVDownload = (e, zip = false) => {
303
- (0, utils_1.downloadCSVFile)(e, zip, {
304
- list,
305
- csvUpper,
306
- csvExcludeUpper,
307
- csvExcludeKeys,
308
- csvExcludeKeysCSV,
309
- csvCustomKeyNames,
310
- csvExcludeValidate,
311
- csv,
312
- multipleDataPath,
313
- normalize,
314
- removeQuotes,
315
- hideTitleCSV,
316
- generateCsvZip,
317
- csvZipFileNamesKey,
318
- });
319
- };
320
- const handleDownloadAll = (e) => {
321
- const keys = Object.keys(list[0]).filter((k) => !csvExcludeKeysAll.includes(k));
322
- (0, utils_1.downloadCSVAll)(e, list, keys, (csv === null || csv === void 0 ? void 0 : csv.fileName) || 'dados');
305
+ const handleCSVDownload = (list) => {
306
+ var _a;
307
+ (0, utils_1.downloadCSVFile)(list, csvConfig, JSON.parse((_a = localStorage.getItem(localTableName)) !== null && _a !== void 0 ? _a : '[]') || []);
323
308
  };
324
309
  const handleFiltrarDados = (dt) => {
325
310
  (0, utils_1.filtrarDados)({
@@ -484,9 +469,10 @@ function Table({ mediaQueryLG, columns, fetchFunc, emptyMsg = {
484
469
  xs: 'column',
485
470
  md: 'row',
486
471
  }, justifyContent: 'flex-end', spacing: 1 },
487
- csvWithoutZip && (react_1.default.createElement(material_1.Button, { startIcon: react_1.default.createElement(FileDownload_1.default, null), variant: 'contained', size: 'small', onClick: handleCSVDownload, sx: { backgroundColor: '#5a88b0', marginRight: { xs: 2, md: 0 }, width: { xs: '100%', md: 'fit-content' } } }, csvNoZipText)),
488
- csvShowAllButton && (react_1.default.createElement(material_1.Button, { startIcon: react_1.default.createElement(FileDownload_1.default, null), variant: 'contained', size: 'small', onClick: handleDownloadAll, sx: { backgroundColor: '#64748B', marginRight: { xs: 2, md: 0 }, width: { xs: '100%', md: 'fit-content' } } }, csvAllButtonTitle)),
489
- react_1.default.createElement(material_1.Button, { startIcon: react_1.default.createElement(FileDownload_1.default, null), variant: 'contained', size: 'small', onClick: (e) => handleCSVDownload(e, true), sx: { backgroundColor: '#22C55E', marginRight: { xs: 2, md: 0 }, width: { xs: '100%', md: 'fit-content' } } }, csvButtonTitle)))))),
472
+ JSON.parse((_b = localStorage.getItem(localTableName)) !== null && _b !== void 0 ? _b : '[]')
473
+ .filter((x) => x.value || (x.operator === 'entre' && (x.value || x.value2))).length > 0 &&
474
+ react_1.default.createElement(material_1.Button, { startIcon: react_1.default.createElement(FileDownload_1.default, null), variant: 'contained', size: 'small', onClick: (e) => handleCSVDownload(list), sx: { backgroundColor: '#a5a5a5', marginRight: { xs: 2, md: 0 }, width: { xs: '100%', md: 'fit-content' } } }, "Baixar Filtrados"),
475
+ react_1.default.createElement(material_1.Button, { startIcon: react_1.default.createElement(FileDownload_1.default, null), variant: 'contained', size: 'small', onClick: (e) => handleCSVDownload(startData.current), sx: { backgroundColor: '#22C55E', marginRight: { xs: 2, md: 0 }, width: { xs: '100%', md: 'fit-content' } } }, "Baixar Tabela")))))),
490
476
  react_1.default.createElement(material_1.Stack, { direction: 'row', justifyContent: 'center', paddingY: 1, paddingTop: 2 },
491
477
  react_1.default.createElement(material_1.Stack, { direction: 'row', justifyContent: 'center', alignItems: 'center', spacing: 2 },
492
478
  react_1.default.createElement(material_1.Button, { onClick: (e) => setListPage((s) => {
@@ -27,10 +27,87 @@ export interface FilterValue {
27
27
  }[];
28
28
  customFunc?: string;
29
29
  }
30
+ export interface CsvMapProps {
31
+ name: string;
32
+ key: string;
33
+ useFilterValue?: {
34
+ label: string;
35
+ operators: FilterOperators[];
36
+ };
37
+ }
38
+ export interface CsvConfigProp {
39
+ fileName: string;
40
+ map: CsvMapProps[];
41
+ }
30
42
  /**
31
43
  * Interface para as propriedades do componente Table.
32
44
  */
33
45
  export interface TableProps {
46
+ /** ID único da tabela */
47
+ id: string;
48
+ /** Configurações de largura para telas grandes */
49
+ mediaQueryLG?: {
50
+ all: number;
51
+ action: number;
52
+ };
53
+ /** Funções de transformação para filtros */
54
+ filtersFunc?: {
55
+ [key: string]: (value: string) => any;
56
+ };
57
+ /** Filtros disponíveis */
58
+ filters?: FilterValue[];
59
+ /** Ordenação por colunas */
60
+ orderBy?: OrderBy[];
61
+ /** Margem personalizada (desktop) */
62
+ customMargin?: number;
63
+ /** Margem personalizada (mobile) */
64
+ customMarginMobile?: number;
65
+ /** Estilo customizado da tabela */
66
+ customTableStyle?: BoxProps;
67
+ /** Mensagem de erro personalizada */
68
+ customErrorMsg?: string | ReactNode;
69
+ /** Colunas da tabela */
70
+ columns: any[];
71
+ /** Nome da tabela */
72
+ tableName: string;
73
+ csvConfig?: CsvConfigProp;
74
+ /** Altura da célula colapsada */
75
+ collapsedSize?: number;
76
+ /** Validação para exclusão de chaves no CSV */
77
+ csvExcludeValidate?: (key: string, value: string | number) => boolean;
78
+ /** Tamanho máximo do texto antes de colapsar */
79
+ expandTextMaxLength?: number;
80
+ /** Ações por linha */
81
+ action: (prop: any) => JSX.Element;
82
+ /** Configuração para exportação CSV */
83
+ csv?: {
84
+ fileName: string;
85
+ };
86
+ /** Quantidade de itens por página */
87
+ itemCount?: number;
88
+ /** Número de colunas da tabela */
89
+ columnSize: number;
90
+ /** Função para buscar dados */
91
+ fetchFunc?: () => Promise<Response>;
92
+ /** Mensagens para quando não há dados */
93
+ emptyMsg?: {
94
+ user: string;
95
+ public: string;
96
+ };
97
+ /** Caminho dos dados no JSON da resposta */
98
+ dataPath?: string;
99
+ /** Usa autenticação via Keycloak */
100
+ useKC?: boolean;
101
+ /** Dados iniciais da tabela */
102
+ initialData?: Array<{
103
+ [key: string]: any;
104
+ }> | null;
105
+ /** Flag de carregamento dos dados da tabela */
106
+ isLoading?: boolean;
107
+ /** Flag para mostrar ou não o botão de expandir a Linha */
108
+ isExpandable?: boolean;
109
+ }
110
+ export interface TableProps2 {
34
111
  /** ID único da tabela */
35
112
  id: string;
36
113
  /** Configurações de largura para telas grandes */
@@ -1,5 +1,5 @@
1
1
  /// <reference types="react" />
2
- import { FilterValue, OrderBy } from './types';
2
+ import { CsvConfigProp, FilterValue, OrderBy } from './types';
3
3
  export declare const getCount: (countData: any[], itemsCount: number) => number;
4
4
  export declare function transformArrayObjectInString(o: Object): String;
5
5
  export declare function removePunctuationAndAccents(text: string): string;
@@ -25,27 +25,6 @@ interface OrdenarDadosProps {
25
25
  orderAsc: boolean;
26
26
  }
27
27
  export declare function ordenarDados({ order, list, orderAsc }: OrdenarDadosProps): any[];
28
- export interface CsvExportOptions {
29
- list: any[];
30
- csvUpper?: boolean;
31
- csvExcludeUpper?: string[];
32
- csvExcludeKeys?: string[];
33
- csvExcludeKeysCSV?: string[];
34
- csvExcludeKeysAll?: string[];
35
- csvCustomKeyNames?: {
36
- [key: string]: string;
37
- };
38
- csvExcludeValidate?: (key: string, value: any) => boolean;
39
- csv?: {
40
- fileName: string;
41
- };
42
- multipleDataPath?: string;
43
- normalize?: boolean;
44
- removeQuotes?: boolean;
45
- hideTitleCSV?: boolean;
46
- generateCsvZip?: boolean;
47
- csvZipFileNamesKey?: string;
48
- }
49
- export declare function downloadCSVFile(e: React.MouseEvent, zip: boolean, options: CsvExportOptions): Promise<void>;
28
+ export declare function downloadCSVFile(list: any[], config: CsvConfigProp, filters: FilterValue[]): Promise<void>;
50
29
  export declare function downloadCSVAll(e: React.MouseEvent, list: any[], keys: string[], fileName: string): void;
51
30
  export {};
@@ -1,4 +1,27 @@
1
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
+ };
2
25
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
26
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
27
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -15,8 +38,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
15
38
  exports.downloadCSVAll = exports.downloadCSVFile = exports.ordenarDados = exports.filtrarDados = exports.formatarString = exports.removePunctuationAndAccents = exports.transformArrayObjectInString = exports.getCount = void 0;
16
39
  const lodash_get_1 = __importDefault(require("lodash.get"));
17
40
  const dayjs_1 = __importDefault(require("dayjs"));
18
- const jszip_1 = __importDefault(require("jszip"));
19
41
  const lodash_clonedeep_1 = __importDefault(require("lodash.clonedeep"));
42
+ const XLSX = __importStar(require("xlsx"));
20
43
  const getCount = (countData, itemsCount) => {
21
44
  if (countData.length <= 0)
22
45
  return 1;
@@ -273,84 +296,29 @@ function ordenarDados({ order, list, orderAsc = false }) {
273
296
  return sortedList;
274
297
  }
275
298
  exports.ordenarDados = ordenarDados;
276
- function downloadCSVFile(e, zip = false, options) {
299
+ function downloadCSVFile(list, config, filters) {
277
300
  return __awaiter(this, void 0, void 0, function* () {
278
- e.preventDefault();
279
- const { list, csvUpper = false, csvExcludeUpper = [], csvExcludeKeys = [], csvExcludeKeysCSV = [], csvCustomKeyNames = {}, csvExcludeValidate = () => false, csv, multipleDataPath = '', normalize = false, removeQuotes = false, hideTitleCSV = false, generateCsvZip = false, csvZipFileNamesKey = '', } = options;
280
301
  if (list.length <= 0)
281
302
  return;
282
- const originalKeys = Object.keys(list[0]);
283
- if (generateCsvZip && zip) {
284
- const keys = originalKeys.filter((k) => !csvExcludeKeys.includes(k));
285
- const header = keys.map((k) => csvCustomKeyNames[k] || k).join(',') + '\n';
286
- const zip = new jszip_1.default();
303
+ // definindo os campos especificados do csv
304
+ const newData = list.map(x => {
287
305
  const obj = {};
288
- list.forEach((item) => {
289
- const key = item[csvZipFileNamesKey];
290
- if (!obj[key])
291
- obj[key] = [];
292
- obj[key].push(item);
293
- });
294
- for (const [fileName, items] of Object.entries(obj)) {
295
- const values = [];
296
- for (const x of items) {
297
- if (originalKeys.some((k) => csvExcludeValidate(k, x[k])))
298
- continue;
299
- const value = keys.map((k) => formatCell(x[k], k)).join(',');
300
- values.push(value);
301
- }
302
- const csvData = hideTitleCSV ? values.join('\n') : '\uFEFF' + header + values.join('\n');
303
- if (values.length > 0) {
304
- zip.file(`${normalizeString(fileName)}.csv`, csvData);
305
- }
306
- }
307
- const link = document.createElement('a');
308
- const base = yield zip.generateAsync({ type: 'base64' });
309
- link.href = 'data:application/zip;base64,' + base;
310
- link.download = `${csv === null || csv === void 0 ? void 0 : csv.fileName}.zip`;
311
- link.click();
312
- }
313
- else {
314
- let keys = originalKeys.filter((k) => !csvExcludeKeysCSV.includes(k));
315
- if (multipleDataPath)
316
- keys = ['dtInicio', 'hrInicio', ...keys.map((k) => (k === multipleDataPath ? 'hrTermino' : k))];
317
- const header = keys.map((k) => csvCustomKeyNames[k] || k).join(',') + '\n';
318
- const values = [];
319
- for (const x of list) {
320
- if (originalKeys.some((k) => csvExcludeValidate(k, x[k])))
321
- continue;
322
- const value = keys.map((k) => formatCell(x[k], k)).join(',');
323
- if (multipleDataPath && x[multipleDataPath]) {
324
- for (const d of x[multipleDataPath]) {
325
- values.push(value.replace('{dtInicio}', d.dtInicio).replace('{hrInicio}', d.hrInicio).replace('{hrTermino}', d.hrTermino));
326
- }
327
- }
328
- else {
329
- values.push(value);
306
+ config.map.forEach(m => {
307
+ // opção de usar o valor do filtro no próprio campo
308
+ if (m.useFilterValue) {
309
+ const filterValueList = filters.filter(f => f.label == m.useFilterValue.label && m.useFilterValue.operators.includes(f.operator));
310
+ const filterValue = filterValueList.length > 0 ? (filterValueList.reduce(r => r.value).value || undefined) : undefined;
311
+ obj[m.name] = filterValue || (0, lodash_get_1.default)(x, m.key);
312
+ return;
330
313
  }
331
- }
332
- const csvData = header + values.join('\n');
333
- const link = document.createElement('a');
334
- link.href = 'data:text/csv;charset=utf-8,%EF%BB%BF' + encodeURI(csvData);
335
- link.download = `${csv === null || csv === void 0 ? void 0 : csv.fileName}.csv`;
336
- link.click();
337
- }
338
- function formatCell(cell, key) {
339
- let item = typeof cell === 'object' && cell !== null && !Array.isArray(cell) ? transformArrayObjectInString(cell).slice(1, -1) : cell;
340
- if (csvUpper && typeof item === 'string' && !csvExcludeUpper.includes(key)) {
341
- item = item.toUpperCase();
342
- }
343
- if (normalize && typeof item === 'string') {
344
- item = normalizeString(item);
345
- }
346
- if (typeof item === 'string') {
347
- return removeQuotes ? `${item}` : `"${item}"`;
348
- }
349
- return item;
350
- }
351
- function normalizeString(str) {
352
- return str.normalize('NFD').replace(/[̀-ͯ]/g, '');
353
- }
314
+ obj[m.name] = (0, lodash_get_1.default)(x, m.key);
315
+ });
316
+ return obj;
317
+ });
318
+ const worksheet = XLSX.utils.json_to_sheet(newData);
319
+ const workbook = XLSX.utils.book_new();
320
+ XLSX.utils.book_append_sheet(workbook, worksheet, config.fileName);
321
+ XLSX.writeFile(workbook, `${config.fileName}.xlsx`);
354
322
  });
355
323
  }
356
324
  exports.downloadCSVFile = downloadCSVFile;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ssplib/react-components",
3
- "version": "0.0.280",
3
+ "version": "0.0.282",
4
4
  "description": "SSP React Components",
5
5
  "main": "index.js",
6
6
  "author": "Pedro Henrique <sr.hudrick@gmail.com>",
@@ -24,7 +24,8 @@
24
24
  "react-dropzone": "^14.3.8",
25
25
  "leaflet": "^1.9.4",
26
26
  "leaflet-defaulticon-compatibility": "^0.1.2",
27
- "react-leaflet": "^4.2.1"
27
+ "react-leaflet": "^4.2.1",
28
+ "xlsx": "^0.18.5"
28
29
  },
29
30
  "devDependencies": {
30
31
  "@types/lodash.clonedeep": "^4.5.9",