@vixoniccom/kpi-chart 0.0.1-beta.1

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.
@@ -0,0 +1,238 @@
1
+ /**
2
+ * Archivo que contiene funciones para el corte de datos, limpieza de datos
3
+ * y otras verificaciones.
4
+ */
5
+
6
+ // Limitar columnas de datos procesados (de izq a der. leyendo la planilla)
7
+ export const sliceFeatures = (columnsNumber: number, data: Series[]) => {
8
+ return data.slice(0, columnsNumber);
9
+ };
10
+
11
+ // Limitar la cantidad de filas, con opción para considerar las primeras o últimas n
12
+ export const sliceRecords = (
13
+ rowsNumber: number,
14
+ data: Series[],
15
+ period: string = "newer"
16
+ ) => {
17
+ const nToSlice = period === "newer" ? -rowsNumber : rowsNumber;
18
+ return data.map((series) => ({
19
+ label: series.label,
20
+ data: series.data.slice(nToSlice),
21
+ }));
22
+ };
23
+
24
+ // Verificar si existe nombre de columnas en los datos
25
+ export const nameInHeaders = (name: string, headers: string[]) => {
26
+ return headers.map((h) => h.trim().toLocaleLowerCase()).includes(name);
27
+ };
28
+
29
+ // Verificar integridad de los datos
30
+ export const checkDataHealth = (headers: string[], rows: string[][]) => {
31
+ // Verificar si no hay registros
32
+ if (rows.length === 0) return false;
33
+
34
+ // Verificar si solo existe la columna de categoría
35
+ if (headers.length < 2) return false;
36
+
37
+ return true;
38
+ };
39
+
40
+ // Eliminar columnas (según el nombre) y filas duplicadas, conservando la primera aparición
41
+ export const removeDuplicates = (headers: string[], rows: string[][]) => {
42
+ const seenCol = new Set<string>();
43
+ const seenRow = new Set<string>();
44
+
45
+ const uniqueColumnIndices = headers
46
+ .map((col, i) => (seenCol.has(col) ? -1 : (seenCol.add(col), i)))
47
+ .filter((i) => i !== -1);
48
+
49
+ const filterColumns = (row: string[]) =>
50
+ uniqueColumnIndices.map((i) => row[i]);
51
+
52
+ const uniqueHeaders = filterColumns(headers);
53
+
54
+ const newRows = rows.map(filterColumns);
55
+ const uniqueRows = newRows.filter((row) => {
56
+ const rowString = JSON.stringify(row);
57
+ if (seenRow.has(rowString)) return false;
58
+ seenRow.add(rowString);
59
+ return true;
60
+ });
61
+
62
+ return [uniqueHeaders, ...uniqueRows];
63
+ };
64
+
65
+ // Eliminar columnas que no cumplan con una cantidad de datos
66
+ export const removePartialData = (
67
+ categoryIndex: number,
68
+ headers: string[],
69
+ rows: string[][],
70
+ threshold: number = 0.9
71
+ ) => {
72
+ const validColumnIndices = headers.map((_, colIndex) => {
73
+ if (colIndex === categoryIndex) return true;
74
+ const totalRows = rows.length;
75
+ const nonNullCount = rows.reduce((count, row) => {
76
+ const value = row[colIndex];
77
+ return count + (value !== undefined && value !== "" ? 1 : 0);
78
+ }, 0);
79
+ return nonNullCount / totalRows >= threshold;
80
+ });
81
+
82
+ const denseHeaders = headers.filter((_, i) => validColumnIndices[i]);
83
+ const denseRows = rows.map((row) =>
84
+ row.filter((_, i) => validColumnIndices[i])
85
+ );
86
+ return [denseHeaders, ...denseRows];
87
+ };
88
+
89
+ // Limitar columnas de datos provenientes de Google (de izq. a der. leyendo la planilla)
90
+ export const sliceColumns = (
91
+ categoryIndex: number,
92
+ maxColumnsNumber: number,
93
+ headers: string[],
94
+ rows: string[][]
95
+ ) => {
96
+ const selectedColumns = headers
97
+ .map((_, i) => i)
98
+ .filter((i) => i === categoryIndex || i <= maxColumnsNumber);
99
+ const filterColumns = (row: string[]) => selectedColumns.map((i) => row[i]);
100
+ const trimmedHeaders = filterColumns(headers);
101
+ const trimmedRows = rows.map(filterColumns);
102
+
103
+ return [trimmedHeaders, ...trimmedRows];
104
+ };
105
+
106
+ // Convertir datos a números, o bien, a fechas o string para la columna de categoría
107
+ export const castRecords = (categoryIndex: number, rows: string[][]) => {
108
+ return rows.map((row) =>
109
+ row.map((value: string, index) => {
110
+ if (value === "" || value === undefined) return 0;
111
+ const trimmedValue = value.trim();
112
+ const numberValue = parseFloat(trimmedValue);
113
+ if (index === categoryIndex) {
114
+ const date = new Date(trimmedValue);
115
+ if (!isNaN(date.getTime())) return date;
116
+ if (!isNaN(numberValue)) return numberValue;
117
+ return trimmedValue;
118
+ }
119
+ return numberValue;
120
+ })
121
+ );
122
+ };
123
+
124
+ // Ordenar datos según columna de categoría
125
+ export const sortRecordsByPeriod = (
126
+ categoryIndex: number,
127
+ rows: (string | number | Date)[][],
128
+ asc: boolean = true
129
+ ) => {
130
+ return rows.sort((a, b) => {
131
+ const valA = a[categoryIndex];
132
+ const valB = b[categoryIndex];
133
+
134
+ if (valA instanceof Date && valB instanceof Date) {
135
+ return asc
136
+ ? valA.getTime() - valB.getTime()
137
+ : valB.getTime() - valA.getTime();
138
+ } else if (typeof valA === "number" && typeof valB === "number") {
139
+ return asc ? valA - valB : valB - valA;
140
+ } else if (typeof valA === "string" && typeof valB === "string") {
141
+ return asc ? valA.localeCompare(valB) : valB.localeCompare(valA);
142
+ } else {
143
+ return 0;
144
+ }
145
+ });
146
+ };
147
+
148
+ // Limpieza de datos provenientes de Google
149
+ export const getCleanData = (
150
+ categoryColumnName: string,
151
+ maxColumnsNumber: number,
152
+ data: string[][]
153
+ ) => {
154
+ const [rawHeaders, ...rawRows] = data;
155
+
156
+ // Estandarización de headers
157
+ const standarizedHeaders = rawHeaders.map((h, index) => {
158
+ if (h === "" || h === undefined) {
159
+ return `nn-feature-${index}`;
160
+ }
161
+ return h.trim().toLocaleLowerCase().replace(/ /g, "-");
162
+ });
163
+
164
+ // Eliminación de duplicados (columnas y registros)
165
+ const [headers, ...rows] = removeDuplicates(standarizedHeaders, rawRows);
166
+ // Verificar integridad
167
+ if (!checkDataHealth(headers, rows)) return [];
168
+
169
+ // Identificación del índice de la columna de categoría
170
+ let categoryIndex = headers.indexOf(categoryColumnName);
171
+
172
+ // Conservar un máximo de columnas (sin considerar categoría)
173
+ const [trimmedHeaders, ...trimmedRows] = sliceColumns(
174
+ categoryIndex,
175
+ maxColumnsNumber,
176
+ headers,
177
+ rows
178
+ );
179
+
180
+ // Eliminar registros donde el valor en la columna de categoría es nulo
181
+ const filteredRows = trimmedRows.filter(
182
+ (row) => row && Array.isArray(row) && row[categoryIndex]?.trim() !== ""
183
+ );
184
+ // Verificar integridad de registros filtrados
185
+ if (filteredRows.length === 0) return [];
186
+
187
+ // Eliminar columnas que poseen menos del 90% de información (sin considerar categoría)
188
+ const [denseHeaders, ...denseRows] = removePartialData(
189
+ categoryIndex,
190
+ trimmedHeaders,
191
+ filteredRows
192
+ );
193
+ // Verificar integridad de headers
194
+ if (denseHeaders.length < 2) return [];
195
+
196
+ // Update del índice de la columna de categoría
197
+ categoryIndex = denseHeaders.indexOf(categoryColumnName);
198
+
199
+ // Inputación para datos nulos y conversión numérica
200
+ const nonNullRows = castRecords(categoryIndex, denseRows);
201
+
202
+ // Ordenar datos ordenados según categoría y retornar
203
+ const sortedRows = sortRecordsByPeriod(categoryIndex, nonNullRows);
204
+ return [denseHeaders, ...sortedRows];
205
+ };
206
+
207
+ // Conversión de datos procesados a arreglo de Series para mostrar en gráfico
208
+ export const dataToSeries = (
209
+ categoryColumnName: string,
210
+ data: any
211
+ ): Series[] => {
212
+ const [headers, ...rows] = data;
213
+ const categoryIndex = headers.indexOf(categoryColumnName);
214
+
215
+ const items: Series[] = [];
216
+
217
+ headers.forEach((header: string, index: number) => {
218
+ if (index !== categoryIndex) {
219
+ const indicators: KeyIndicator[] = rows.map((row: (number | Date)[]) => {
220
+ const categoryValue = row[categoryIndex];
221
+ const categoryString =
222
+ categoryValue instanceof Date
223
+ ? (categoryValue as Date).toISOString().substring(0, 10)
224
+ : String(categoryValue);
225
+ return {
226
+ category: categoryString,
227
+ performance: row[index],
228
+ };
229
+ });
230
+ items.push({
231
+ label: header,
232
+ data: indicators,
233
+ });
234
+ }
235
+ });
236
+
237
+ return items;
238
+ };
@@ -0,0 +1,9 @@
1
+ declare type KeyIndicator = {
2
+ category: string;
3
+ performance: number;
4
+ };
5
+
6
+ declare type Series = {
7
+ label: string;
8
+ data: KeyIndicator[];
9
+ };
package/src/index.html ADDED
@@ -0,0 +1,13 @@
1
+ <!DOCTYPE html>
2
+ <html style="position: absolute; height: 100%; width: 100%; overflow: hidden">
3
+ <head>
4
+ <title>KPI Charts</title>
5
+ <meta charset="utf-8" />
6
+ </head>
7
+ <body style="margin: 0">
8
+ <div
9
+ id="root"
10
+ style="position: absolute; top: 0; right: 0; bottom: 0; left: 0"
11
+ ></div>
12
+ </body>
13
+ </html>
package/src/main.ts ADDED
@@ -0,0 +1,37 @@
1
+ import ReactDOM from "react-dom";
2
+ import { App } from "./components/App";
3
+ import React from "react";
4
+ const { ipcRenderer } = require("electron");
5
+
6
+ // Variable para controlar el estado de inicio de la aplicación
7
+ let start: boolean = false;
8
+
9
+ // Se escucha el evento preload recibido por el proceso principal
10
+ ipcRenderer.on("preload", (_event: any, data: VixonicData) => {
11
+ render(data);
12
+ });
13
+
14
+ // Se escucha el evento start recibido por el proceso principal
15
+ ipcRenderer.on("start", (_event: any, data: VixonicData) => {
16
+ // Determinar el inicio de la aplicación
17
+ start = true;
18
+ render(data);
19
+ });
20
+
21
+ // Se escucha el evento update que indica la actualización de la configuración
22
+ ipcRenderer.on("update", (_event: any, data: VixonicData) => {
23
+ render(data);
24
+ });
25
+
26
+ // Se escucha el evento finish indicando que ha terminado el proceso
27
+ ipcRenderer.on("finish", (_event: VixonicData) => {
28
+ console.log("finish");
29
+ });
30
+
31
+ // Función para renderizar la aplicación a través de la renderización del componente App
32
+ function render(data: VixonicData) {
33
+ ReactDOM.render(
34
+ React.createElement(App, { data, start }),
35
+ document.getElementById("root")
36
+ );
37
+ }
@@ -0,0 +1,9 @@
1
+ declare type VixonicData = {
2
+ downloadsPath: string
3
+ services: { [key: string]: { data?: any, updatedAt?: number } }
4
+ parameters: VixonicParameters
5
+ }
6
+
7
+ declare type VixonicParameters = Partial<{
8
+ url: string, urlRedirectButton: string, maxColumnsNumber: number, maxRowsNumber: number, updateTime: 300000 | 600000 | 900000 | 1800000 | 3600000, chartType: 'bar' | 'line' | 'area' | 'bubble', barOrientation: 'vertical' | 'horizontal', barStacked: boolean, darkMode: boolean, titleEnabled: boolean, title: string, titleTextFormat: { fontSize?: number, fontColor?: string, alignment?: { horizontal?: 'left' | 'right' | 'center' }, font?: { filename: string, id: string, __isAsset: true } }, titlePadding: string, legendEnabled: boolean, legendTextFormat: { fontSize?: number, fontColor?: string, alignment?: { horizontal?: 'left' | 'right' | 'center' }, font?: { filename: string, id: string, __isAsset: true } }, legendPosition: 'left' | 'right', legendMargin: number, circleSize: number, yAxisEnabled: boolean, showVerticalGrid: boolean, xAxisEnabled: boolean, showHorizontalGrid: boolean, appPadding: string, backgroundImage: {id?: string, filename?: string, extension?: string}, customMessageEnabled: boolean, customMessage: string, systemMessageTextFormat: { fontSize?: number, fontColor?: string, alignment?: { horizontal?: 'left' | 'right' | 'center' }, font?: { filename: string, id: string, __isAsset: true } }
9
+ }>
package/src/style.css ADDED
@@ -0,0 +1,63 @@
1
+ /* ==========================================
2
+ Estilo del contenedor principal de la app
3
+ ========================================== */
4
+ .app-container {
5
+ height: 100vh;
6
+ width: 100vw;
7
+ /* Fondo */
8
+ background-size: cover;
9
+ background-position: 50% 50%;
10
+ box-sizing: border-box;
11
+ }
12
+
13
+ .chart-container {
14
+ height: 100%;
15
+ width: 100%;
16
+ /* Flexbox */
17
+ display: flex;
18
+ flex-direction: column;
19
+ align-items: stretch;
20
+ justify-content: stretch;
21
+ }
22
+
23
+ .chart-elements {
24
+ height: 100%;
25
+ width: 100%;
26
+ /* Flexbox */
27
+ display: flex;
28
+ flex-direction: row;
29
+ align-items: stretch;
30
+ justify-content: space-evenly;
31
+ flex: 1;
32
+ }
33
+
34
+ .chart {
35
+ height: 100%;
36
+ width: 100%;
37
+ }
38
+
39
+ .legend-box {
40
+ /* Flexbox */
41
+ display: flex;
42
+ flex-direction: column;
43
+ justify-content: center;
44
+ align-items: stretch;
45
+ }
46
+
47
+ .label-container {
48
+ margin-bottom: 10px;
49
+ /* Flexbox */
50
+ display: flex;
51
+ flex-direction: row;
52
+ align-items: center;
53
+ justify-content: flex-start;
54
+ }
55
+
56
+ .label-color {
57
+ border-radius: 50%;
58
+ margin-right: 10px;
59
+ }
60
+
61
+ .label-text {
62
+ width: 100%;
63
+ }
Binary file
@@ -0,0 +1,47 @@
1
+ {
2
+ "parameters": {
3
+ "url": "https://docs.google.com/spreadsheets/d/1IqRcXGIaPOamyMax1uS3-vurAzSI3QTKjABCAPNILGw/edit?usp=sharing",
4
+ "urlRedirectButton": "https://docs.google.com/spreadsheets/d/1IqRcXGIaPOamyMax1uS3-vurAzSI3QTKjABCAPNILGw/edit?usp=sharing",
5
+ "appPadding": "8vh 8vw 8vh 32vw",
6
+ "plotType": "bar",
7
+ "titleEnabled": false,
8
+ "title": "Título del gráfico",
9
+ "titlePadding": "0px 0px 20px 0px",
10
+ "titleTextFormat": {
11
+ "fontSize": 32,
12
+ "fontColor": "#000000",
13
+ "alignment": { "horizontal": "center" },
14
+ "font": {
15
+ "id": "default-font",
16
+ "filename": "monserrat.ttf",
17
+ "__isAsset": true
18
+ }
19
+ },
20
+ "legendEnabled": true,
21
+ "legendMargin": 20,
22
+ "legendTextFormat": {
23
+ "fontSize": 12,
24
+ "alignment": { "horizontal": "center" },
25
+ "font": {
26
+ "id": "default-font",
27
+ "filename": "monserrat.ttf",
28
+ "__isAsset": true
29
+ }
30
+ },
31
+ "systemMessageTextFormat": {
32
+ "fontSize": 36,
33
+ "fontColor": "#000000",
34
+ "alignment": { "horizontal": "center" },
35
+ "font": {
36
+ "id": "default-font",
37
+ "filename": "monserrat.ttf",
38
+ "__isAsset": true
39
+ }
40
+ },
41
+ "backgroundImage": {
42
+ "id": "background",
43
+ "filename": "background.jpg",
44
+ "__isAsset": true
45
+ }
46
+ }
47
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2015",
4
+ "module": "es2015",
5
+ "moduleResolution": "node",
6
+ "jsx": "preserve",
7
+ "allowJs": true,
8
+ "checkJs": true,
9
+ "allowSyntheticDefaultImports": true,
10
+ "emitDecoratorMetadata": true,
11
+ "experimentalDecorators": true,
12
+ "downlevelIteration": true,
13
+ "strict": true,
14
+ "forceConsistentCasingInFileNames": true,
15
+ "noFallthroughCasesInSwitch": true,
16
+ "noImplicitReturns": true,
17
+ "noImplicitAny": true,
18
+ "noImplicitThis": true,
19
+ "noUnusedLocals": true,
20
+ "noUnusedParameters": true,
21
+ "sourceMap": true,
22
+ "types": ["node"],
23
+ "typeRoots": ["./node_modules/@types", "./src", "./src/global.d.ts"]
24
+ },
25
+ "include": ["./src/**/*"],
26
+ "exclude": ["./node_modules/**/*"]
27
+ }