@bento-core/table 1.0.1-ccdihub.25 → 1.0.1-ccdihub.26

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.
@@ -8,6 +8,7 @@ var _react = _interopRequireWildcard(require("react"));
8
8
  var _client = require("@apollo/client");
9
9
  var _core = require("@material-ui/core");
10
10
  var _icons = require("@material-ui/icons");
11
+ var _downloadTable = require("../../util/downloadTable");
11
12
  function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
12
13
  function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
13
14
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
@@ -31,6 +32,7 @@ const DownloadButton = _ref => {
31
32
  });
32
33
  }
33
34
  const client = (0, _client.useApolloClient)();
35
+ const downloadFileName = 'CCDI Inventory';
34
36
  async function downloadSCSVFile() {
35
37
  const {
36
38
  query,
@@ -48,7 +50,7 @@ const DownloadButton = _ref => {
48
50
  }
49
51
  return response.data;
50
52
  });
51
- console.log('result:', result);
53
+ (0, _downloadTable.downloadJson)(result, table, downloadFileName);
52
54
  }
53
55
  const downloadTableCSV = (0, _react.useCallback)(() => {
54
56
  downloadSCSVFile();
@@ -4,6 +4,12 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.formatBytes = formatBytes;
7
+ exports.formatColumnValues = void 0;
8
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
9
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
10
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
11
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
12
+ function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
7
13
  /* eslint-disable import/prefer-default-export */
8
14
  function formatBytes(bytes) {
9
15
  let decimals = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
@@ -12,4 +18,38 @@ function formatBytes(bytes) {
12
18
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
13
19
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
14
20
  return "".concat(parseFloat((bytes / 1024 ** i).toFixed(dm)), " ").concat(sizes[i]);
15
- }
21
+ }
22
+
23
+ /**
24
+ * convert zero (0) value to custom val
25
+ * @param {*} columns
26
+ * @param {*} data
27
+ * @returns
28
+ */
29
+ const formatColumnValues = (columns, data) => {
30
+ const formatColumns = columns.filter(_ref => {
31
+ let {
32
+ columnDefaultValues
33
+ } = _ref;
34
+ return columnDefaultValues;
35
+ });
36
+ if (formatColumns.length > 0) {
37
+ const formatCoumnData = [...data].reduce((acc, item) => {
38
+ const updateRow = _objectSpread({}, item);
39
+ formatColumns.forEach(col => {
40
+ const {
41
+ columnDefaultValues,
42
+ dataField
43
+ } = col;
44
+ if (columnDefaultValues[item[dataField]]) {
45
+ updateRow[dataField] = columnDefaultValues[item[dataField]];
46
+ }
47
+ });
48
+ acc.push(updateRow);
49
+ return acc;
50
+ }, []);
51
+ return formatCoumnData;
52
+ }
53
+ return data;
54
+ };
55
+ exports.formatColumnValues = formatColumnValues;
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.convertToCSV = convertToCSV;
7
+ exports.createFileName = createFileName;
8
+ exports.downloadJson = downloadJson;
9
+ var _Dataformat = require("./Dataformat");
10
+ var _Types = require("./Types");
11
+ function createFileName(fileName) {
12
+ const date = new Date();
13
+ const yyyy = date.getFullYear();
14
+ let dd = date.getDate();
15
+ let mm = date.getMonth() + 1;
16
+ if (dd < 10) {
17
+ dd = "0".concat(dd);
18
+ }
19
+ if (mm < 10) {
20
+ mm = "0".concat(mm);
21
+ }
22
+ const todaysDate = "".concat(yyyy, "-").concat(mm, "-").concat(dd);
23
+ let hours = date.getHours();
24
+ let minutes = date.getMinutes();
25
+ let seconds = date.getSeconds();
26
+ if (hours < 10) {
27
+ hours = "0".concat(hours);
28
+ }
29
+ if (minutes < 10) {
30
+ minutes = "0".concat(minutes);
31
+ }
32
+ if (seconds < 10) {
33
+ seconds = "0".concat(seconds);
34
+ }
35
+ return "".concat(fileName, " ").concat(todaysDate, " ").concat(hours, "-").concat(minutes, "-").concat(seconds, '.csv');
36
+ }
37
+ function convertToCSV(jsonse, keysToInclude, header) {
38
+ const objArray = jsonse;
39
+ // To Do empty object just print headers
40
+ const array = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
41
+ let str = header.join(',');
42
+ array.map((entry, index) => {
43
+ let line = '';
44
+ keysToInclude.map(keyName => {
45
+ if (line !== '') line += ',';
46
+ if (keyName === 'file_size') {
47
+ line += entry[keyName] !== null ? "\"".concat((0, _Dataformat.formatBytes)(entry[keyName]), "\"") : ' ';
48
+ } else {
49
+ line += entry[keyName] !== null ? "\"".concat(entry[keyName], "\"") : ' ';
50
+ }
51
+ return line;
52
+ });
53
+ if (index === 0) {
54
+ // str = header.join(',');
55
+ str += "\r\n".concat(line, "\r\n");
56
+ } else {
57
+ str += "".concat(line, "\r\n");
58
+ }
59
+ return str;
60
+ });
61
+ return str;
62
+ }
63
+ function downloadJson(tableData, table, downloadFileName) {
64
+ const {
65
+ columns = []
66
+ } = table;
67
+ const filterColumns = columns.filter(_ref => {
68
+ let {
69
+ cellType
70
+ } = _ref;
71
+ return !_Types.actionCellTypes.includes(cellType);
72
+ });
73
+ const formatDataVal = (0, _Dataformat.formatColumnValues)(filterColumns, tableData);
74
+ const jsonse = JSON.stringify(formatDataVal);
75
+ const keysToInclude = columns.filter(_ref2 => {
76
+ let {
77
+ dataField
78
+ } = _ref2;
79
+ return dataField;
80
+ }).map(_ref3 => {
81
+ let {
82
+ dataField
83
+ } = _ref3;
84
+ return dataField;
85
+ });
86
+ const headers = columns.filter(_ref4 => {
87
+ let {
88
+ dataField
89
+ } = _ref4;
90
+ return dataField;
91
+ }).map(_ref5 => {
92
+ let {
93
+ header
94
+ } = _ref5;
95
+ return header;
96
+ });
97
+ const csv = convertToCSV(jsonse, keysToInclude, headers);
98
+ const exportData = new Blob([csv], {
99
+ type: 'text/csv'
100
+ });
101
+ const JsonURL = window.URL.createObjectURL(exportData);
102
+ let tempLink = '';
103
+ tempLink = document.createElement('a');
104
+ tempLink.setAttribute('href', JsonURL);
105
+ tempLink.setAttribute('download', createFileName(downloadFileName || ''));
106
+ document.body.appendChild(tempLink);
107
+ tempLink.click();
108
+ document.body.removeChild(tempLink);
109
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bento-core/table",
3
- "version": "1.0.1-ccdihub.25",
3
+ "version": "1.0.1-ccdihub.26",
4
4
  "main": "dist/index.js",
5
5
  "scripts": {
6
6
  "build": "npm run lint && cross-env-shell rm -rf dist && NODE_ENV=production BABEL_ENV=es babel src --out-dir dist --copy-files",
@@ -5,6 +5,7 @@ import {
5
5
  Tooltip,
6
6
  } from '@material-ui/core';
7
7
  import { CloudDownload } from '@material-ui/icons';
8
+ import { downloadJson } from '../../util/downloadTable';
8
9
 
9
10
  const downloadButtonStyle = {
10
11
  color: '#d1d2d3',
@@ -22,6 +23,8 @@ const DownloadButton = ({
22
23
 
23
24
  const client = useApolloClient();
24
25
 
26
+ const downloadFileName = 'CCDI Inventory';
27
+
25
28
  async function downloadSCSVFile() {
26
29
  const {
27
30
  query,
@@ -42,7 +45,7 @@ const DownloadButton = ({
42
45
  }
43
46
  return response.data;
44
47
  });
45
- console.log('result:', result);
48
+ downloadJson(result, table, downloadFileName);
46
49
  }
47
50
 
48
51
  const downloadTableCSV = useCallback(() => {
@@ -6,3 +6,28 @@ export function formatBytes(bytes, decimals = 2) {
6
6
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
7
7
  return `${parseFloat((bytes / (1024 ** i)).toFixed(dm))} ${sizes[i]}`;
8
8
  }
9
+
10
+ /**
11
+ * convert zero (0) value to custom val
12
+ * @param {*} columns
13
+ * @param {*} data
14
+ * @returns
15
+ */
16
+ export const formatColumnValues = (columns, data) => {
17
+ const formatColumns = columns.filter(({ columnDefaultValues }) => columnDefaultValues);
18
+ if (formatColumns.length > 0) {
19
+ const formatCoumnData = [...data].reduce((acc, item) => {
20
+ const updateRow = { ...item };
21
+ formatColumns.forEach((col) => {
22
+ const { columnDefaultValues, dataField } = col;
23
+ if (columnDefaultValues[item[dataField]]) {
24
+ updateRow[dataField] = columnDefaultValues[item[dataField]];
25
+ }
26
+ });
27
+ acc.push(updateRow);
28
+ return acc;
29
+ }, []);
30
+ return formatCoumnData;
31
+ }
32
+ return data;
33
+ };
@@ -0,0 +1,74 @@
1
+ import { formatBytes, formatColumnValues } from './Dataformat';
2
+ import { actionCellTypes } from './Types';
3
+
4
+ export function createFileName(fileName) {
5
+ const date = new Date();
6
+ const yyyy = date.getFullYear();
7
+ let dd = date.getDate();
8
+ let mm = (date.getMonth() + 1);
9
+
10
+ if (dd < 10) { dd = `0${dd}`; }
11
+
12
+ if (mm < 10) { mm = `0${mm}`; }
13
+
14
+ const todaysDate = `${yyyy}-${mm}-${dd}`;
15
+
16
+ let hours = date.getHours();
17
+ let minutes = date.getMinutes();
18
+ let seconds = date.getSeconds();
19
+
20
+ if (hours < 10) { hours = `0${hours}`; }
21
+
22
+ if (minutes < 10) { minutes = `0${minutes}`; }
23
+
24
+ if (seconds < 10) { seconds = `0${seconds}`; }
25
+
26
+ return `${fileName} ${todaysDate} ${hours}-${minutes}-${seconds}${'.csv'}`;
27
+ }
28
+
29
+ export function convertToCSV(jsonse, keysToInclude, header) {
30
+ const objArray = jsonse;
31
+ // To Do empty object just print headers
32
+ const array = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
33
+ let str = header.join(',');
34
+ array.map((entry, index) => {
35
+ let line = '';
36
+ keysToInclude.map((keyName) => {
37
+ if (line !== '') line += ',';
38
+ if (keyName === 'file_size') {
39
+ line += entry[keyName] !== null ? `"${formatBytes(entry[keyName])}"` : ' ';
40
+ } else {
41
+ line += entry[keyName] !== null ? `"${entry[keyName]}"` : ' ';
42
+ }
43
+ return line;
44
+ });
45
+ if (index === 0) {
46
+ // str = header.join(',');
47
+ str += `\r\n${line}\r\n`;
48
+ } else {
49
+ str += `${line}\r\n`;
50
+ }
51
+ return str;
52
+ });
53
+ return str;
54
+ }
55
+
56
+ export function downloadJson(tableData, table, downloadFileName) {
57
+ const { columns = [] } = table;
58
+ const filterColumns = columns.filter(({ cellType }) => !actionCellTypes.includes(cellType));
59
+ const formatDataVal = formatColumnValues(filterColumns, tableData);
60
+ const jsonse = JSON.stringify(formatDataVal);
61
+ const keysToInclude = columns.filter(({ dataField }) => dataField)
62
+ .map(({ dataField }) => dataField);
63
+ const headers = columns.filter(({ dataField }) => dataField).map(({ header }) => header);
64
+ const csv = convertToCSV(jsonse, keysToInclude, headers);
65
+ const exportData = new Blob([csv], { type: 'text/csv' });
66
+ const JsonURL = window.URL.createObjectURL(exportData);
67
+ let tempLink = '';
68
+ tempLink = document.createElement('a');
69
+ tempLink.setAttribute('href', JsonURL);
70
+ tempLink.setAttribute('download', createFileName(downloadFileName || ''));
71
+ document.body.appendChild(tempLink);
72
+ tempLink.click();
73
+ document.body.removeChild(tempLink);
74
+ }