@vixoniccom/kpi-chart 0.0.1 → 0.0.2-dev.0

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,191 +0,0 @@
1
- import React, { useState, useEffect } from "react";
2
- import axios from "axios";
3
- import localforage from "localforage";
4
- import { Circles } from "react-loader-spinner";
5
- import { FontLoader } from "./FontLoader";
6
- import { ChartContainer } from "./ChartContainer";
7
- import { FormattedText } from "./FormattedText";
8
- import "../style.css";
9
- import {
10
- checkDataHealth,
11
- dataToSeries,
12
- getCleanData,
13
- nameInHeaders,
14
- sliceFeatures,
15
- sliceRecords,
16
- } from "./utils";
17
-
18
- interface Props {
19
- data: VixonicData;
20
- start: boolean;
21
- }
22
-
23
- // Definición de paths de las fuentes provenientes de la configuración
24
- const fontPaths = [
25
- "titleTextFormat.font",
26
- "legendTextFormat.font",
27
- "customMessageTextFormat.font",
28
- ];
29
-
30
- /**
31
- * Componente principal que muestra la aplicación y el gráfico.
32
- * Es llamada una vez ha sido inicializada (start == true).
33
- * Obtiene los datos según tiempo de actualización definido en la configuración.
34
- */
35
- export const App: React.FunctionComponent<Props> = ({ data, start }) => {
36
- let updateTimer: any;
37
- const params = data.parameters;
38
- const appPadding = params?.appPadding ?? "0px";
39
- const updateTime = params?.updateTime ?? 3600000;
40
- const backgroundImageState = params?.backgroundImage
41
- ? `url("${data.downloadsPath}/${params?.backgroundImage.filename}")`
42
- : "";
43
- const [loading, setLoading] = useState<boolean>(false);
44
- // Definición de variable que contiene los datos procesados provenientes de la URL
45
- const [sheetData, setSheetData] = useState<Series[]>([]);
46
- // Definición de mensaje del sistema
47
- const [systemMessage, setSystemMessage] = useState<string>(
48
- "Sin datos disponibles"
49
- );
50
- // Definición de nombre fijo de columna de categoría
51
- const categoryColumnName = "category";
52
- // Definición de cantidad máxima de columnas y filas para procesar desde Google
53
- const fixedMaxRows = 100;
54
- const fixedMaxColumns = 10; // 10 máx, no usar más, a menos que sea agreguen más colores en ChartContainer
55
- // Definición de cantidad de columnas y filas para mostrar en la aplicación
56
- const rowsNumber = params?.maxRowsNumber ?? 6;
57
- const columnsNumber = params?.maxColumnsNumber ?? 3;
58
-
59
- // Función para hacer request de Google y almacenar los datos procesados en localforage
60
- const getData = async () => {
61
- setLoading(true);
62
- const googleID = params?.url?.split("/")[5];
63
- const key = getStorageKey(googleID);
64
- localforage.clear();
65
- const storedData: any = await localforage.getItem(key);
66
- if (!storedData?.items || storedData?.items?.length === 0) {
67
- const data = await requestData(googleID);
68
- localforage.setItem(key, { items: data, date: Date.now() });
69
- setDataAndTime(data, updateTime);
70
- } else {
71
- const now = Date.now();
72
- const targetDate = storedData.date + updateTime;
73
- if (now >= targetDate) {
74
- const data = await requestData(googleID);
75
- setDataAndTime(data, targetDate - now);
76
- localforage.setItem(key, { items: data, date: now });
77
- } else {
78
- setDataAndTime(storedData.items, targetDate - now);
79
- }
80
- }
81
- setLoading(false);
82
- };
83
-
84
- // Función para actualizar el estado de los datos y el tiempo de actualización
85
- const setDataAndTime = (data: Series[], time: number) => {
86
- setSheetData(
87
- // Slice de columnas
88
- sliceFeatures(
89
- columnsNumber,
90
- // Slice de filas
91
- sliceRecords(rowsNumber, data)
92
- )
93
- );
94
- setUpdateTime(time);
95
- };
96
-
97
- const setUpdateTime = (milliseconds: number) => {
98
- clearTimeout(updateTimer);
99
- if (milliseconds === null) return;
100
- updateTimer = setTimeout(getData, milliseconds);
101
- };
102
-
103
- const requestData = async (googleID?: string) => {
104
- const URL = `https://sheets.googleapis.com/v4/spreadsheets/${googleID}/values`;
105
- try {
106
- const response = await axios.get(`${URL}/data`, {
107
- params: { key: "AIzaSyDQcTlxfd5IyjbeSJooRtNt6OF04DLykqc" },
108
- });
109
- return processData(response.data.values);
110
- } catch (error: unknown) {
111
- if (error instanceof Error) {
112
- setSystemMessage(error.message);
113
- } else {
114
- setSystemMessage("Error al cargar los datos");
115
- }
116
- return [];
117
- }
118
- };
119
-
120
- // Función para procesar datos (slice de filas, revisar integridad de datos y
121
- // limpiar los datos)
122
- const processData = (data: string[][]) => {
123
- const [rawHeaders, ...rawRows] = data;
124
- const rows = rawRows.slice(-fixedMaxRows);
125
- if (isDataHealthy(rawHeaders, rows)) {
126
- const cleanedData = getCleanData(categoryColumnName, fixedMaxColumns, [
127
- rawHeaders,
128
- ...rows,
129
- ]);
130
- // Si hay datos limpios, convertirlos a un arreglo de Series
131
- if (cleanedData.length !== 0) {
132
- return dataToSeries(categoryColumnName, cleanedData);
133
- }
134
- setSystemMessage("Después de limpieza, no hay datos para mostrar");
135
- }
136
- return [];
137
- };
138
-
139
- // Función para verificar si existe la columna de categoría y revisar la integridad de datos
140
- const isDataHealthy = (headers: string[], rows: string[][]) => {
141
- if (!nameInHeaders(categoryColumnName, headers)) {
142
- setSystemMessage(`Columna '${categoryColumnName}' no existente`);
143
- return false;
144
- }
145
- if (!checkDataHealth(headers, rows)) {
146
- setSystemMessage("Falta de registros o columna con datos");
147
- return false;
148
- }
149
- return true;
150
- };
151
-
152
- const getStorageKey = (googleID?: string) => {
153
- const key = googleID?.replace(/[^a-z0-9]/gi, "");
154
- return `sheets${key?.toLowerCase()}`;
155
- };
156
-
157
- useEffect(() => {
158
- if (!start) return;
159
- getData();
160
- }, [params.url, params.maxRowsNumber, params.maxColumnsNumber, start]);
161
-
162
- return (
163
- <div
164
- className="app-container"
165
- style={{
166
- padding: appPadding,
167
- backgroundImage: `${backgroundImageState}`,
168
- }}
169
- >
170
- {/* Carga de fuentes de texto */}
171
- <FontLoader
172
- paths={fontPaths}
173
- parameters={params}
174
- downloadsPath={data.downloadsPath}
175
- />
176
- {/* Render de chart o mensaje del sistema/personalizado */}
177
- {loading ? (
178
- <div className="loading-container">
179
- <Circles ariaLabel="loading-indicator" color="gray" />
180
- </div>
181
- ) : sheetData.length > 0 ? (
182
- <ChartContainer data={sheetData} parameters={params} />
183
- ) : (
184
- <FormattedText
185
- text={params?.customMessage || systemMessage}
186
- format={params?.systemMessageTextFormat}
187
- />
188
- )}
189
- </div>
190
- );
191
- };
@@ -1,181 +0,0 @@
1
- import React from "react";
2
- import { Chart, AxisOptions, Position } from "react-charts";
3
- import { FormattedText } from "../FormattedText";
4
- import { ChartLegend } from "../ChartLegend";
5
- import { getFontColor } from "../utils";
6
-
7
- type Props = {
8
- data: Series[];
9
- parameters: VixonicParameters;
10
- };
11
-
12
- type elementType = "area" | "line" | "bar" | "bubble";
13
-
14
- type AxisConfig = {
15
- position: string;
16
- show: boolean;
17
- showLine: boolean;
18
- stacked: boolean;
19
- type: string;
20
- };
21
-
22
- // Definición de colores que se utilizarán en el gráfico y leyenda
23
- const defaultColors = [
24
- "#1F77B4", // Azul
25
- "#FF7F0E", // Naranja
26
- "#D62728", // Rojo
27
- "#2CA02C", // Verde
28
- "#9467BD", // Morado
29
- "#17BECF", // Cian
30
- "#8C564B", // Marrón
31
- "#E377C2", // Rosa
32
- "#BCBD22", // Amarillo oliva
33
- "#7F7F7F", // Gris
34
- ];
35
-
36
- // Obtener configuraciones de ejes según parámetros de configuración
37
- const getAxisConfig = (parameters: VixonicParameters) => {
38
-
39
- const chartType = parameters?.chartType ?? "bar";
40
- const isBarChart = chartType === "bar";
41
- const barOrientation = parameters?.barOrientation ?? "vertical";
42
- const isHorizontalBar = isBarChart && barOrientation === "horizontal";
43
-
44
- const defaultConfig: AxisConfig = {
45
- position: "left",
46
- show: true,
47
- showLine: true,
48
- stacked: false,
49
- type: chartType,
50
- };
51
-
52
- const xConfig = {
53
- position: isHorizontalBar ? "left" : "bottom",
54
- show: parameters?.xAxisEnabled ?? defaultConfig.show,
55
- showLine: parameters?.showVerticalGrid ?? defaultConfig.showLine,
56
- };
57
-
58
- const yConfig = {
59
- position: isHorizontalBar ? "bottom" : "left",
60
- show: parameters?.yAxisEnabled ?? defaultConfig.show,
61
- showLine: parameters?.showHorizontalGrid ?? defaultConfig.showLine,
62
- stacked: isBarChart && (parameters?.barStacked ?? false),
63
- };
64
-
65
- return {
66
- xAxisConfig: { ...defaultConfig, ...xConfig },
67
- yAxisConfig: { ...defaultConfig, ...yConfig },
68
- };
69
- };
70
-
71
- /**
72
- * Componente para renderizar el gráfico, su título y su leyenda.
73
- * Se definen ejes principal y secundario en Memo para evitar problemas
74
- de renderización.
75
- */
76
- export const ChartContainer: React.FunctionComponent<Props> = ({
77
- data,
78
- parameters,
79
- }) => {
80
- const chartTitle = parameters?.title ?? "";
81
- const legendGap = parameters?.legendMargin ?? 0;
82
- const titleMargin = parameters?.titlePadding ?? "0px";
83
- const legendPosition = parameters?.legendPosition ?? "left";
84
- const titleFontColor = getFontColor(parameters);
85
- const { xAxisConfig, yAxisConfig } = getAxisConfig(parameters);
86
-
87
- // Definición eje x
88
- const primaryAxis = React.useMemo(
89
- (): AxisOptions<KeyIndicator> => ({
90
- getValue: (datum: KeyIndicator) => datum.category,
91
- // Tipo band para variables categóricas
92
- scaleType: "band",
93
- show: xAxisConfig.show,
94
- showGrid: xAxisConfig.showLine,
95
- position: xAxisConfig.position as Position,
96
- }),
97
- [xAxisConfig]
98
- );
99
-
100
- // Definición eje y
101
- const secondaryAxes = React.useMemo(
102
- (): AxisOptions<KeyIndicator>[] => [
103
- {
104
- getValue: (datum: KeyIndicator) => datum.performance,
105
- elementType: yAxisConfig.type as elementType,
106
- // Muestra de valores en número decimal
107
- formatters: {
108
- scale: (value) => value.toFixed(1),
109
- },
110
- position: yAxisConfig.position as Position,
111
- scaleType: "linear",
112
- show: yAxisConfig.show,
113
- showGrid: yAxisConfig.showLine,
114
- stacked: yAxisConfig.stacked,
115
- },
116
- ],
117
- [parameters.darkMode, yAxisConfig]
118
- );
119
-
120
- return (
121
- <div className="chart-container">
122
- {parameters?.titleEnabled && (
123
- // Renderización del título del gráfico
124
- <div
125
- className="title-container"
126
- style={{
127
- padding: titleMargin,
128
- }}
129
- >
130
- <FormattedText
131
- text={chartTitle}
132
- format={{
133
- ...parameters?.titleTextFormat,
134
- ...{ fontColor: titleFontColor },
135
- }}
136
- />
137
- </div>
138
- )}
139
- {/* Renderización de leyenda y gráfico */}
140
- <div
141
- className="chart-elements"
142
- style={{
143
- flexDirection: legendPosition === "left" ? "row" : "row-reverse",
144
- }}
145
- >
146
- {parameters?.legendEnabled && (
147
- <ChartLegend
148
- data={{
149
- labels: data.map((series) => series.label),
150
- colors: defaultColors,
151
- parameters: {
152
- textFormat: parameters?.legendTextFormat,
153
- circleSize: parameters?.circleSize,
154
- darkMode: parameters?.darkMode ?? false,
155
- legendGap: legendGap,
156
- legendPosition: legendPosition,
157
- },
158
- }}
159
- />
160
- )}
161
- <div className="chart">
162
- <Chart<KeyIndicator>
163
- options={{
164
- data,
165
- primaryAxis,
166
- secondaryAxes,
167
- dark: parameters?.darkMode,
168
- defaultColors: defaultColors,
169
- // Esconder leyenda por defecto e interacciones con cursor
170
- tooltip: {
171
- show: false,
172
- },
173
- primaryCursor: false,
174
- secondaryCursor: false,
175
- }}
176
- />
177
- </div>
178
- </div>
179
- </div>
180
- );
181
- };
@@ -1,66 +0,0 @@
1
- import React from "react";
2
- import { TextFormat } from "@vixoniccom/modules";
3
- import { FormattedText } from "../FormattedText";
4
- import { getFontColor } from "../utils";
5
-
6
- type Props = {
7
- data: {
8
- labels: string[];
9
- colors: string[];
10
- parameters: {
11
- textFormat?: TextFormat.Value;
12
- circleSize?: number;
13
- darkMode: boolean;
14
- legendPosition: string;
15
- legendGap: number;
16
- };
17
- };
18
- };
19
-
20
- /**
21
- * Componente para renderizar la leyenda del gráfico según los labels de
22
- los datos y los colores por defecto definidos.
23
- */
24
- export const ChartLegend: React.FunctionComponent<Props> = ({ data }) => {
25
- const params = data.parameters;
26
- const circleSize = params?.circleSize ?? 8;
27
- const fontColor = getFontColor({
28
- titleTextFormat: params?.textFormat,
29
- darkMode: params.darkMode,
30
- });
31
- return (
32
- // Renderizar contenedor con margen dependiendo de la posición provista en la config.
33
- <div
34
- className="legend-box"
35
- style={{
36
- marginLeft:
37
- params?.legendPosition === "left" ? "0px" : `${params?.legendGap}px`,
38
- marginRight:
39
- params?.legendPosition === "right" ? "0px" : `${params?.legendGap}px`,
40
- }}
41
- >
42
- {data.labels.map((label, index) => (
43
- // Contenedor con círculo de color y label
44
- <div key={index} className="label-container">
45
- <div
46
- className="label-color"
47
- style={{
48
- width: `${circleSize}px`,
49
- height: `${circleSize}px`,
50
- backgroundColor: data.colors[index],
51
- }}
52
- ></div>
53
- <div className="label-text">
54
- <FormattedText
55
- text={label}
56
- format={{
57
- ...params?.textFormat,
58
- ...{ fontColor: fontColor },
59
- }}
60
- />
61
- </div>
62
- </div>
63
- ))}
64
- </div>
65
- );
66
- };
@@ -1,47 +0,0 @@
1
- import React from "react";
2
-
3
- interface Props {
4
- paths: Array<string>;
5
- parameters: VixonicParameters;
6
- downloadsPath: string;
7
- }
8
-
9
- /**
10
- * Componente que carga a través de <style> las fuentes obtenidas
11
- desde la configuración
12
- */
13
- export const FontLoader: React.FunctionComponent<Props> = ({
14
- paths,
15
- parameters,
16
- downloadsPath,
17
- }: Props) => {
18
- const _getValueByPath = (path: any, obj: any): any => {
19
- const pathsArray = path.split(".");
20
- const propertyName = pathsArray[0];
21
- if (pathsArray.length === 1) return obj[propertyName];
22
- else {
23
- pathsArray.splice(0, 1);
24
- return _getValueByPath(pathsArray.join("."), obj[propertyName]);
25
- }
26
- };
27
-
28
- const fonts = paths.map((path: any) => {
29
- try {
30
- const fontParam = _getValueByPath(path, parameters);
31
- const font = {
32
- family: fontParam.filename.replace(".", "-"),
33
- src: `${downloadsPath}/${fontParam.filename}`,
34
- };
35
- return `
36
- @font-face {
37
- font-family: "${font.family}";
38
- src: url("${font.src}");
39
- }
40
- `;
41
- } catch (err) {
42
- return "";
43
- }
44
- });
45
-
46
- return <style>{fonts}</style>;
47
- };
@@ -1,88 +0,0 @@
1
- import React from "react";
2
-
3
- // Objeto con los tipos de alineaciones de texto
4
- const alignments = {
5
- center: "center",
6
- left: "flex-start",
7
- right: "flex-end",
8
- };
9
-
10
- // Tipado de alineación
11
- type aligment = {
12
- horizontal: keyof typeof alignments;
13
- vertical: keyof typeof alignments;
14
- };
15
-
16
- interface Props {
17
- format?: any;
18
- lineHeight?: number;
19
- style?: number;
20
- text: string;
21
- }
22
-
23
- /**
24
- * Componente para mostrar, a través de <span>, un texto que considera todo
25
- el formato indicado en la configuración
26
- */
27
- export const FormattedText: React.FunctionComponent<Props> = ({
28
- text,
29
- format,
30
- lineHeight,
31
- style,
32
- }: Props) => {
33
- // Función para verificar si propiedad pertenece al objeto
34
- const checkNested = (obj: any, path: string): boolean => {
35
- const arr = path.split(".");
36
- return arr.every((key, index) => {
37
- if (index === arr.length - 1) return key in obj;
38
- obj = obj[key];
39
- return obj && typeof obj === "object";
40
- });
41
- };
42
-
43
- // Función para obtener la alineación de texto basada en la configuración
44
- const getHorizontalAlignment = (alignment: aligment) => {
45
- if (alignment) {
46
- const hA = alignment.horizontal;
47
- return alignments.hasOwnProperty(hA)
48
- ? alignments[alignment.horizontal]
49
- : "flex-start";
50
- }
51
- return "flex-start";
52
- };
53
-
54
- const containerStyle = Object.assign(
55
- {
56
- display: "flex",
57
- justifyContent: getHorizontalAlignment(format?.alignment),
58
- flex: format?.flex || 0,
59
- },
60
- style
61
- );
62
-
63
- return (
64
- <div style={containerStyle}>
65
- <span
66
- style={{
67
- display: "inline-flex",
68
- color: format?.fontColor || "white",
69
- fontWeight: format?.fontWeight || "normal",
70
- fontFamily: format && checkNested(format, "font.filename")
71
- ? `"${format?.font?.filename?.replace(".", "-")}"`
72
- : "",
73
- fontSize: `${format?.fontSize || 18}px`,
74
- textAlign: format && checkNested(format, "alignment.horizontal")
75
- ? format?.alignment?.horizontal
76
- : "left",
77
- lineHeight: lineHeight ?? 1,
78
- marginTop: format?.marginTop || 0,
79
- marginLeft: format?.marginLeft || 0,
80
- marginBottom: format?.marginBottom || 0,
81
- marginRight: format?.marginRight || 0,
82
- }}
83
- >
84
- {text}
85
- </span>
86
- </div>
87
- );
88
- };