diff --git a/.eslintrc b/.eslintrc index 01e61df..e8aba36 100644 --- a/.eslintrc +++ b/.eslintrc @@ -1,3 +1,13 @@ { - "extends": "./.config/.eslintrc" + "extends": "./.config/.eslintrc", + "rules": { + "react/jsx-key": "off", + "react/prop-types": "off", + "react-hooks/exhaustive-deps": "off", + "react-hooks/rules-of-hooks": "off", + "curly": "off", + "react/no-children-prop": "off", + "@typescript-eslint/naming-convention": "off", + "no-restricted-imports": "off" + } } \ No newline at end of file diff --git a/src/components/editors/formatEditor.tsx b/src/components/editors/formatEditor.tsx index 16fb0ea..0854d76 100644 --- a/src/components/editors/formatEditor.tsx +++ b/src/components/editors/formatEditor.tsx @@ -8,7 +8,7 @@ import { FormatDefault } from 'utils/default'; import { css } from '@emotion/css'; -interface Props extends StandardEditorProps {} +interface Props extends StandardEditorProps { } export const FormatEditor: React.FC = ({ value: elements, onChange, context }) => { @@ -16,39 +16,39 @@ export const FormatEditor: React.FC = ({ value: elements, onChange, conte elements = []; } - const addElement = (newFormat : IFormat) => { + const addElement = (newFormat: IFormat) => { const updated = [...elements, newFormat] onChange(updated) } - const updateElement = (idx : number, formatUpdated : IFormat) => { + const updateElement = (idx: number, formatUpdated: IFormat) => { const updated = [...elements] updated[idx] = formatUpdated onChange(updated) } - const deleteElement = (idx:number) => { + const deleteElement = (idx: number) => { const updated = [...elements] updated.splice(idx, 1) onChange(updated) } - const listFormats = elements.map((element:IFormat, idx:number) => { + const listFormats = elements.map((element: IFormat, idx: number) => { return
- updateElement(idx, m)} + updateElement(idx, m)} deleteFunction={() => deleteElement(idx)} - context={context}/> + context={context} />
}) - return (
+ return (
{listFormats} - - + +
) -} \ No newline at end of file +} diff --git a/src/components/editors/formatForm.tsx b/src/components/editors/formatForm.tsx index 10a427e..5f955c5 100644 --- a/src/components/editors/formatForm.tsx +++ b/src/components/editors/formatForm.tsx @@ -6,14 +6,14 @@ import { FormatDefault } from 'utils/default'; import { Mode } from 'utils/constants'; interface Props { - format : IFormat, - updateFunction : any, - deleteFunction ?: any, - mode : Mode, - context : StandardEditorContext + format: IFormat, + updateFunction: any, + deleteFunction?: any, + mode: Mode, + context: StandardEditorContext } -export const FormatForm: React.FC = ({ format, updateFunction, deleteFunction, mode, context }) => { +export const FormatForm: React.FC = ({ format, updateFunction, deleteFunction, mode, context }) => { const [currentFormat, setCurrentFormat] = useState(FormatDefault) const [codeInput, setCodeInput] = useState("") @@ -29,20 +29,20 @@ export const FormatForm: React.FC = ({ format, updateFunction, deleteFun const handleOnChangeFormat = (event: ChangeEvent) => { setCurrentFormat({ ...currentFormat, - [event.currentTarget.name] : event.target.value + [event.currentTarget.name]: event.target.value }) } const handleOnSubmitAddFormat = () => { const newFormat = { ...currentFormat, - output : codeOutput, - input : codeInput + output: codeOutput, + input: codeInput } updateFunction(newFormat) - if(mode == Mode.EDIT) { + if (mode === Mode.EDIT) { setDisabled(true) - } else { + } else { setCurrentFormat(FormatDefault) setCodeInput("") setCodeOutput("") @@ -61,11 +61,11 @@ export const FormatForm: React.FC = ({ format, updateFunction, deleteFun } const handleOnConfirmDeleteFormat = () => { - if(deleteFunction) deleteFunction() + if (deleteFunction) deleteFunction() } useEffect(() => { - if(mode == Mode.EDIT) setDisabled(true) + if (mode === Mode.EDIT) setDisabled(true) }, [mode]) useEffect(() => { @@ -76,42 +76,43 @@ export const FormatForm: React.FC = ({ format, updateFunction, deleteFun }, [currentFormat]) const buttonEdit = () => { - if(mode == Mode.CREATE) { + if (mode === Mode.CREATE) { return
} else { return ( -
- - - - -
) +
+ + + + +
) } } return
{buttonEdit()} - -
{({register, errors, control}:FormAPI) => { + + {({ register, errors, control }: FormAPI) => { return ( -
- - - -
- )}} +
+ + + +
+ ) + }} -
- + = ({ format, updateFunction, deleteFun
-
- + = ({ format, updateFunction, deleteFun
- - + +
-} \ No newline at end of file +} diff --git a/src/components/editors/modelEditor.tsx b/src/components/editors/modelEditor.tsx index d622daf..e94a465 100644 --- a/src/components/editors/modelEditor.tsx +++ b/src/components/editors/modelEditor.tsx @@ -8,7 +8,7 @@ import { Mode } from 'utils/constants'; import { css } from '@emotion/css'; -interface Props extends StandardEditorProps {} +interface Props extends StandardEditorProps { } export const ModelEditor: React.FC = ({ value: elements, onChange, context }) => { @@ -19,39 +19,39 @@ export const ModelEditor: React.FC = ({ value: elements, onChange, contex elements = []; } - const addElement = (newModel : IModel) => { + const addElement = (newModel: IModel) => { const updated = [...elements, newModel] onChange(updated) } - const updateElement = (idx : number, modelUpdated : IModel) => { + const updateElement = (idx: number, modelUpdated: IModel) => { const updated = [...elements] updated[idx] = modelUpdated onChange(updated) } - const deleteElement = (idx:number) => { + const deleteElement = (idx: number) => { const updated = [...elements] updated.splice(idx, 1) onChange(updated) } - const listModels = elements.map((element:IModel, idx:number) => { + const listModels = elements.map((element: IModel, idx: number) => { return
- updateElement(idx, m)} + updateElement(idx, m)} deleteFunction={() => deleteElement(idx)} - context={context}/> + context={context} />
}) - return (
+ return (
{listModels} - - + +
) -} \ No newline at end of file +} diff --git a/src/components/editors/modelForm.tsx b/src/components/editors/modelForm.tsx index 9aee8c5..aa1725a 100644 --- a/src/components/editors/modelForm.tsx +++ b/src/components/editors/modelForm.tsx @@ -33,7 +33,7 @@ export const ModelForm: React.FC = ({ model, updateFunction, deleteFuncti const [selectedFormat, setSelectedFormat] = useState>() const [selectedVarTime, setSelectedVarTime] = useState>() const [selectedVarTags, setSelectedVarTags] = useState>() - const [selectedQuotesListItems, setSelectedQuotesListItems] = useState>({ label:FormatTags.None, value: FormatTags['None'] }) + const [selectedQuotesListItems, setSelectedQuotesListItems] = useState>({ label: FormatTags.None, value: FormatTags['None'] }) const [queryOptions, setQueryOptions] = useState([]) const [formatOptions, setFormatOptions] = useState([]) const [code, setCode] = useState("") @@ -48,10 +48,10 @@ export const ModelForm: React.FC = ({ model, updateFunction, deleteFuncti setSelectedMethod({ label: model.method, value: model.method }) setSelectedQuery({ label: model.queryId, value: model.queryId }) if (model.extraInfo !== undefined) setSelectedExtraInfo({ label: model.extraInfo, value: model.extraInfo }) - if (model.format != undefined) setSelectedFormat({ label: model.format.id, value: model.format }) + if (model.format !== undefined) setSelectedFormat({ label: model.format.id, value: model.format }) setSelectedVarTags({ label: model.varTags, value: model.varTags }) setSelectedVarTime({ label: model.varTime, value: model.varTime }) - setSelectedQuotesListItems({ label: model.formatTags, value: model.formatTags}) + setSelectedQuotesListItems({ label: model.formatTags, value: model.formatTags }) setCode((model.preprocess) ? model.preprocess : "") setScaler((model.scaler) ? JSON.stringify(model.scaler, undefined, 4) : "") setListValues(model.isListValues) @@ -79,7 +79,7 @@ export const ModelForm: React.FC = ({ model, updateFunction, deleteFuncti const handleOnSubmitAddModel = () => { const cred = currentModel.credentials - const credentials = (cred && cred.password.trim() != '' && cred.username.trim() != '') ? cred : undefined + const credentials = (cred && cred.password.trim() !== '' && cred.username.trim() !== '') ? cred : undefined const newModel = { ...currentModel, tags: currentTags, @@ -95,11 +95,11 @@ export const ModelForm: React.FC = ({ model, updateFunction, deleteFuncti isListValues: listValues, isTransposeList: transposeList } - newModel.scaler = (scaler.trim() != "") ? JSON.parse(scaler) : undefined + newModel.scaler = (scaler.trim() !== "") ? JSON.parse(scaler) : undefined //console.log(newModel) console.log("New model", newModel) updateFunction(newModel) - if (mode == Mode.EDIT) { + if (mode === Mode.EDIT) { setDisabled(true) } else { setCurrentModel(ModelDefault) @@ -125,7 +125,7 @@ export const ModelForm: React.FC = ({ model, updateFunction, deleteFuncti const checkValueField = (value?: string) => { //console.log("valueField", value != undefined && value.trim() != "") - return value != undefined && value.trim() != "" + return value !== undefined && value.trim() !== "" } useEffect(() => { @@ -133,7 +133,7 @@ export const ModelForm: React.FC = ({ model, updateFunction, deleteFuncti }, []) useEffect(() => { - if (mode == Mode.EDIT) setDisabled(true) + if (mode === Mode.EDIT) setDisabled(true) }, [mode]) useEffect(() => { @@ -148,19 +148,19 @@ export const ModelForm: React.FC = ({ model, updateFunction, deleteFuncti }, [context.data]) useEffect(() => { - if (context.options.formats != undefined) { + if (context.options.formats !== undefined) { setFormatOptions(formatsToOptions(context.options.formats)) } else { setFormatOptions([]) } }, [context.options.formats]) - const checkVariableIsInvalid = (var1:any, var2:any) : boolean => { - return var1 == undefined || (var1 != undefined && var1.value != undefined && var1.value == var2?.value) + const checkVariableIsInvalid = (var1: any, var2: any): boolean => { + return var1 === undefined || (var1 !== undefined && var1.value !== undefined && var1.value === var2?.value) } const buttonEdit = () => { - if (mode == Mode.CREATE) { + if (mode === Mode.CREATE) { return
} else { return ( @@ -212,7 +212,7 @@ export const ModelForm: React.FC = ({ model, updateFunction, deleteFuncti -

Import data query

+

Import data query

@@ -234,19 +234,19 @@ export const ModelForm: React.FC = ({ model, updateFunction, deleteFuncti - - setListValues(!listValues)}/> + + setListValues(!listValues)} /> - - setTransposeList(!transposeList)}/> + + setTransposeList(!transposeList)} /> -

Extra info query

+

Extra info query

+ render={({ field }) => + - + -

Variables

+

Variables

@@ -388,8 +388,8 @@ export const ModelForm: React.FC = ({ model, updateFunction, deleteFuncti - - + +
-} \ No newline at end of file +} diff --git a/src/components/editors/tagsForm.tsx b/src/components/editors/tagsForm.tsx index 8d023f6..4763b50 100644 --- a/src/components/editors/tagsForm.tsx +++ b/src/components/editors/tagsForm.tsx @@ -1,26 +1,26 @@ -import { Button, CodeEditor, Form, HorizontalGroup, InlineSwitch, FormAPI, InlineFieldRow, InlineField, Input, DeleteButton } from '@grafana/ui' +import { Button, CodeEditor, Form, HorizontalGroup, InlineSwitch, FormAPI, InlineFieldRow, InlineField, Input, DeleteButton } from '@grafana/ui' import React, { ChangeEvent, useEffect, useState } from 'react' import { TagDefault } from 'utils/default' import { ITag } from 'utils/types' interface Props { - currentTags : ITag[] - setCurrentTags : any - disabled : boolean + currentTags: ITag[] + setCurrentTags: any + disabled: boolean } -export const TagsForm = ({ currentTags, setCurrentTags, disabled=false }:Props) => { +export const TagsForm = ({ currentTags, setCurrentTags, disabled = false }: Props) => { const [isTagsForm, setIsTagsForm] = useState(true) // true = Form, false = JSON - const handleOnConfirmDeleteTag = (idx:number) => { + const handleOnConfirmDeleteTag = (idx: number) => { const updatedTags = [...currentTags] updatedTags.splice(idx, 1) setCurrentTags(updatedTags) } const handleOnChangeTag = (event: ChangeEvent, idx: number) => { - const updatedTags:any[] = [...currentTags] + const updatedTags: any[] = [...currentTags] updatedTags[idx][event.currentTarget.name] = event.target.value setCurrentTags(updatedTags) } @@ -35,48 +35,48 @@ export const TagsForm = ({ currentTags, setCurrentTags, disabled=false }:Props) //console.log("AAA") //console.log(currentTags) }, [currentTags]) - + const tagsForm =
-
{({register, errors, control}:FormAPI) => { + {({ register, errors, control }: FormAPI) => { return (
- {currentTags.map((tag:ITag, idx: number) => { - return
- {idx+1} -
- - - ) => handleOnChangeTag(e, idx)}/> - - - ) => handleOnChangeTag(e, idx)}/> - - - - - ) => handleOnChangeTag(e, idx)}/> - - - ) => handleOnChangeTag(e, idx)}/> - - -
-
- { - handleOnConfirmDeleteTag(idx) - }} - /> + {currentTags.map((tag: ITag, idx: number) => { + return
+ {idx + 1} +
+ + + ) => handleOnChangeTag(e, idx)} /> + + + ) => handleOnChangeTag(e, idx)} /> + + + + + ) => handleOnChangeTag(e, idx)} /> + + + ) => handleOnChangeTag(e, idx)} /> + + +
+
+ { + handleOnConfirmDeleteTag(idx) + }} + /> +
-
- })} + })}
) }}
- - const tagsJson = return ( -
- - setIsTagsForm(!isTagsForm)} - transparent - style={{ marginBottom: '10px'}} - /> - - {(isTagsForm) ? tagsForm : tagsJson} -
+
+ + setIsTagsForm(!isTagsForm)} + transparent + style={{ marginBottom: '10px' }} + /> + + {(isTagsForm) ? tagsForm : tagsJson} +
) -} \ No newline at end of file +} diff --git a/src/components/main.tsx b/src/components/main.tsx index e06f8cf..acdd921 100644 --- a/src/components/main.tsx +++ b/src/components/main.tsx @@ -6,7 +6,7 @@ import { ModifyData } from './step3_ModifyData' import { PredictModel } from './step4_PredictModel' import { ExportData } from './step5_ExportData' import { Context, getMessagesByLanguage, tagsToString } from 'utils/utils' -import { IContext, IDataCollection, IModel, Options } from 'utils/types' +import { IContext, IDataCollection, IFormat, IModel, Options } from 'utils/types' import { Steps } from 'utils/constants' import { locationService } from '@grafana/runtime' import { saveVariableValue } from 'utils/datasources/grafana' @@ -39,7 +39,7 @@ export const Main: React.FC = ({ options, data, width, height, replaceVar } const deleteCollection = (id: string) => { - const idx = collections.findIndex((col) => col.id == id) + const idx = collections.findIndex((col) => col.id === id) if (idx >= 0) { setCurrentCollIdx(undefined) const updatedCollections: IDataCollection[] = [...collections] @@ -50,7 +50,7 @@ export const Main: React.FC = ({ options, data, width, height, replaceVar } const updateCollection = (updatedCollection: IDataCollection) => { - const idx = collections.findIndex((col) => col.id == updatedCollection.id) + const idx = collections.findIndex((col) => col.id === updatedCollection.id) if (idx >= 0) { const updatedCollections = [...collections] updatedCollections[idx] = updatedCollection @@ -85,13 +85,22 @@ export const Main: React.FC = ({ options, data, width, height, replaceVar }, [options])*/ useEffect(() => { - if (selectedModel != undefined) { + if (selectedModel !== undefined) { saveVariableValue(locationService, selectedModel.varTags, tagsToString(selectedModel.tags, selectedModel.formatTags)) } else { saveVariableValue(locationService, ModelDefault.varTags, "") } }, [selectedModel]) + useEffect(() => { + options.models.forEach((model: IModel) => { + if(model.format) { + model.format = options.formats.find((v: IFormat) => v.id === model.format?.id) + } + }) + }, [options.formats]) + + return
@@ -104,7 +113,7 @@ export const Main: React.FC = ({ options, data, width, height, replaceVar
- +
@@ -114,7 +123,7 @@ export const Main: React.FC = ({ options, data, width, height, replaceVar
- +
diff --git a/src/components/step1_SelectModel.tsx b/src/components/step1_SelectModel.tsx index af142a2..289e2bd 100644 --- a/src/components/step1_SelectModel.tsx +++ b/src/components/step1_SelectModel.tsx @@ -6,8 +6,8 @@ import { IModel, ISelect } from 'utils/types'; import { Context, modelsToSelect } from 'utils/utils'; interface Props { - models : IModel[], - setModel : any + models: IModel[], + setModel: any } export const SelectModel: React.FC = ({ models, setModel }) => { @@ -23,11 +23,11 @@ export const SelectModel: React.FC = ({ models, setModel }) => { useEffect(() => { setModelsOptions(modelsToSelect(models)) }, [models]) - + useEffect(() => { setModel(value?.value) - if(value != null && context.setActualStep){ + if (value != null && context.setActualStep) { context.setActualStep(Steps.step_2) } else { context.setActualStep(Steps.step_1) @@ -36,12 +36,12 @@ export const SelectModel: React.FC = ({ models, setModel }) => { useEffect(() => { }, [models]) - + // HTML // ------------------------------------------------------------------------------------------------------------- - - return
-

{context.messages._panel.step} 1

+ + return
+

{context.messages._panel.step} 1

{context.messages._panel._step1.selectModel}

- + @@ -341,25 +341,25 @@ export const ModifyData: React.FC = ({ model, collections, deleteCollecti
{msgs.interval} - - - + + variant={interval.type === IntervalTypeEnum.percentage ? 'primary' : 'default'} /> Abs. + variant={interval.type === IntervalTypeEnum.units ? 'primary' : 'default'}>Abs.
@@ -390,4 +390,4 @@ export const ModifyData: React.FC = ({ model, collections, deleteCollecti
-} \ No newline at end of file +} diff --git a/src/components/step4_PredictModel.tsx b/src/components/step4_PredictModel.tsx index a16d5ea..9e6173a 100644 --- a/src/components/step4_PredictModel.tsx +++ b/src/components/step4_PredictModel.tsx @@ -1,11 +1,10 @@ import { Button, HorizontalGroup, IconButton, Modal, Spinner, useTheme2, VerticalGroup } from '@grafana/ui' import React, { Fragment, useContext, useEffect, useState } from 'react' -import { Context, dateTimeLocalToString, getMean, round } from 'utils/utils' +import { Context, dateTimeLocalToString, getMean, round, groupBy } from 'utils/utils' import { IData, IDataCollection, IModel, IntervalTypeEnum, IResult, ITag } from 'utils/types' import { idDefault, idNew, Steps } from 'utils/constants' import { predictAllCollections } from 'utils/datasources/predictions' import Plot from 'react-plotly.js' -import { groupBy } from 'utils/utils' import { Config, Icons, Layout, ModeBarButtonAny, PlotlyHTMLElement, toImage } from 'plotly.js' import { getAppEvents } from '@grafana/runtime' import { AppEvents, isDateTime, PanelData } from '@grafana/data' @@ -38,18 +37,18 @@ export const PredictModel: React.FC = ({ model, collections, updateCollec const disabledModifyAgain = (context.actualStep) ? context.actualStep < Steps.step_4 : false const validate = () => { - let msg: string = "" + let msg = "" if (model) { collections.forEach((col: IDataCollection) => { - let error_tags: string[] = col.data.filter((d: IData) => d.default_value == undefined && (d.new_value == undefined || d.new_value.trim() == "")).map((d: IData) => d.id) - error_tags = error_tags.concat(model.tags.filter((t: ITag) => !col.data.some((d: IData) => d.id == t.id)).map((t: ITag) => t.id)) + let error_tags: string[] = col.data.filter((d: IData) => d.default_value === undefined && (d.new_value === undefined || d.new_value.trim() === "")).map((d: IData) => d.id) + error_tags = error_tags.concat(model.tags.filter((t: ITag) => !col.data.some((d: IData) => d.id === t.id)).map((t: ITag) => t.id)) if (error_tags.length > 0) { msg = msg + "Data missing in " + col.name + ": " + error_tags.join(", ") + "\n" } }) } - if (msg == "") { + if (msg === "") { return true } else { const appEvents = getAppEvents(); @@ -94,7 +93,7 @@ export const PredictModel: React.FC = ({ model, collections, updateCollec } useEffect(() => { - if (state == StatePredict.LOADING) { + if (state === StatePredict.LOADING) { setState(StatePredict.DONE) } }, [collections]) @@ -126,7 +125,7 @@ export const PredictModel: React.FC = ({ model, collections, updateCollec const showPlot = (col: IDataCollection) => { if (col.results) { - const results = col.results.filter((r: IResult) => r.id != idDefault && r.id != idNew && r.correspondsWith != undefined && r.result != 'ERROR' && r.result != undefined) + const results = col.results.filter((r: IResult) => r.id !== idDefault && r.id !== idNew && r.correspondsWith !== undefined && r.result !== 'ERROR' && r.result !== undefined) if (results.length < 1) return
const tagsGroup: { [tag: string]: IResult[] } = groupBy(results, "tag") @@ -134,9 +133,9 @@ export const PredictModel: React.FC = ({ model, collections, updateCollec const dataArray: any[] = Object.entries(tagsGroup).map(([tag, resultsOfTag]) => { // No pongo la x global por si alguna falla que no se rompa toda la grafica - var values_x: number[] = [], values_y: number[] = [], text: number[] = [] + let values_x: number[] = [], values_y: number[] = [], text: number[] = [] resultsOfTag.forEach((r: IResult) => { - if (r.result != undefined && r.result != 'ERROR' + if (r.result !== undefined && r.result !== 'ERROR' && r.correspondsWith !== undefined && r.data[r.correspondsWith.tag] !== undefined && typeof r.result === 'number') { values_x.push(r.correspondsWith.intervalValue) values_y.push(r.result) @@ -180,7 +179,7 @@ export const PredictModel: React.FC = ({ model, collections, updateCollec zerolinecolor: theme.colors.text.primary, gridcolor: theme.colors.text.primary, color: theme.colors.text.primary, - ticksuffix: (col.interval.type == IntervalTypeEnum.percentage) ? "%" : "" + ticksuffix: (col.interval.type === IntervalTypeEnum.percentage) ? "%" : "" }, yaxis: { tickcolor: theme.colors.text.primary, @@ -201,10 +200,10 @@ export const PredictModel: React.FC = ({ model, collections, updateCollec height: 900, format: 'png' }).then((img: string) => { - //var image = new Image() + //let image = new Image() //image.src = img - var w = window.open("") - if (w != null) w.document.write(''); + let w = window.open("") + if (w !== null) w.document.write(''); //w.document.write(image.outerHTML) }) @@ -224,9 +223,9 @@ export const PredictModel: React.FC = ({ model, collections, updateCollec } const defaultValue = (col: IDataCollection) => { - var res =
+ let res =
if (col.results) { - const def = col.results.find((r: IResult) => r.id == idDefault) + const def = col.results.find((r: IResult) => r.id === idDefault) if (def) res =

{msgs.originalValue}

{(typeof def.result === 'number') ? setDecimals(def.result) : 'ERROR'}

@@ -236,9 +235,9 @@ export const PredictModel: React.FC = ({ model, collections, updateCollec } const newValue = (col: IDataCollection) => { - var res =
+ let res =
if (col.results) { - const nw = col.results.find((r: IResult) => r.id == idNew) + const nw = col.results.find((r: IResult) => r.id === idNew) if (nw) res =

{msgs.newValue}

{(typeof nw.result === 'number') ? setDecimals(nw.result) : 'ERROR'}

@@ -252,7 +251,7 @@ export const PredictModel: React.FC = ({ model, collections, updateCollec Object.entries(extraInfo).map(([key, value]) => { if (isDateTime(value)) { value = dateTimeLocalToString(value) - } else if (!isNaN(value) && model != undefined && model.decimals) { + } else if (!isNaN(value) && model !== undefined && model.decimals) { value = round(value, model.decimals) } res.push(
{key + ": " + value}
) @@ -275,7 +274,7 @@ export const PredictModel: React.FC = ({ model, collections, updateCollec } const divExtraInfo = () => { - if (currentCollIdx != undefined && currentCollIdx < collections.length) { + if (currentCollIdx !== undefined && currentCollIdx < collections.length) { const col: IDataCollection = collections[currentCollIdx] if (col.extraInfo && Object.keys(col.extraInfo).length > 0) { return
@@ -290,13 +289,13 @@ export const PredictModel: React.FC = ({ model, collections, updateCollec return
} - const getButton = (currentCollIdx != undefined && currentCollIdx < collections.length && collections[currentCollIdx].results) ? + const getButton = (currentCollIdx !== undefined && currentCollIdx < collections.length && collections[currentCollIdx].results) ? : const showResults = () => { - if (currentCollIdx != undefined && currentCollIdx < collections.length && collections[currentCollIdx].results) { + if (currentCollIdx !== undefined && currentCollIdx < collections.length && collections[currentCollIdx].results) { const col: IDataCollection = collections[currentCollIdx] return
@@ -336,4 +335,4 @@ export const PredictModel: React.FC = ({ model, collections, updateCollec
{viewResults()} -} \ No newline at end of file +} diff --git a/src/components/step5_ExportData.tsx b/src/components/step5_ExportData.tsx index 803bfa7..0427919 100644 --- a/src/components/step5_ExportData.tsx +++ b/src/components/step5_ExportData.tsx @@ -7,25 +7,25 @@ import { Context } from 'utils/utils' import { saveAs } from 'file-saver' interface Props { - model ?: IModel, - collections : IDataCollection[], - currentCollection ?: IDataCollection + model?: IModel, + collections: IDataCollection[], + currentCollection?: IDataCollection } -export const ExportData: React.FC = ({model, collections, currentCollection}) => { +export const ExportData: React.FC = ({ model, collections, currentCollection }) => { const theme = useTheme2() const context = useContext(Context) const msgs = context.messages._panel._step5 const disabled_data = (context.actualStep) ? context.actualStep < Steps.step_3 : false - //|| !currentCollection?.data.some((d:IData) => d.new_value || d.set_percentage) + //|| !currentCollection?.data.some((d:IData) => d.new_value || d.set_percentage) //const disabled_results = (context.actualStep) ? context.actualStep < Steps.step_5 : false const text_button = (currentCollection && currentCollection.results) ? msgs.downloadResults : msgs.downloadData const handleOnClickDownloadData = () => { - if(currentCollection){ + if (currentCollection) { //console.log("CURRENTCOL", currentCollection) saveAs(dataToCSV(currentCollection), (currentCollection.id + ".csv").replace(/ /g, '_')) } @@ -33,11 +33,11 @@ export const ExportData: React.FC = ({model, collections, currentCollecti // - return
-

{context.messages._panel.step} 5

+ return
+

{context.messages._panel.step} 5

{msgs.exportData}

- +
-} \ No newline at end of file +} diff --git a/src/utils/constants.tsx b/src/utils/constants.tsx index 4452bee..4215a22 100644 --- a/src/utils/constants.tsx +++ b/src/utils/constants.tsx @@ -4,7 +4,9 @@ import { ISelect } from "./types" import { ILocalization } from "./localization/scheme" import { dateTimeLocalToString } from "./utils" -export const variableInput = '$input' +export const varInput = '$input' +export const varEachInput = '$each' +export const varEachInputEnd = '$end-each' export const variableOutput = '$output' export const idDefault = 'basic_defaultData' export const idNew = 'basic_newValue' diff --git a/src/utils/datasources/csv.tsx b/src/utils/datasources/csv.tsx index 961fd66..6ca8fd4 100644 --- a/src/utils/datasources/csv.tsx +++ b/src/utils/datasources/csv.tsx @@ -9,7 +9,7 @@ const compare = (a: IData, b: IData) => { if ((a.new_value !== undefined && b.new_value === undefined) || (a.set_percentage === true && b.set_percentage !== true && b.new_value === undefined && a.new_value === undefined)) { return -1 - } else if (a.set_percentage == b.set_percentage && (a.new_value === undefined) == (b.new_value === undefined)) { + } else if (a.set_percentage === b.set_percentage && (a.new_value === undefined) === (b.new_value === undefined)) { return 0 } else { return 1 @@ -44,8 +44,8 @@ export const dataToCSV = (collection: IDataCollection) => { //console.log("COLECCION?", collection) if (collection.results !== undefined) { - const def = collection.results.find((r: IResult) => r.id == idDefault) - const ne = collection.results.find((r: IResult) => r.id == idNew) + const def = collection.results.find((r: IResult) => r.id === idDefault) + const ne = collection.results.find((r: IResult) => r.id === idNew) _int = { _RESULT: "", ..._int } _def = { @@ -66,10 +66,10 @@ export const dataToCSV = (collection: IDataCollection) => { _RESULT: r.result } - Object.entries(r.data).forEach(([key, value]: [key: string, value: number|number[]]) => { + Object.entries(r.data).forEach(([key, value]: [key: string, value: number | number[]]) => { row = { ...row, - [key]: ((r.correspondsWith && r.correspondsWith.tag == key) || value !== _def[key]) ? value : "" + [key]: ((r.correspondsWith && r.correspondsWith.tag === key) || value !== _def[key]) ? value : "" } }) @@ -112,16 +112,16 @@ export const dataToCSV = (collection: IDataCollection) => { } export const stringToIntervalMode = (str: string) => { - return str.toLowerCase().trim() == "units" ? IntervalTypeEnum.units : IntervalTypeEnum.percentage + return str.toLowerCase().trim() === "units" ? IntervalTypeEnum.units : IntervalTypeEnum.percentage } export const intervalModeToString = (intMode: IntervalTypeEnum) => { - return intMode == IntervalTypeEnum.units ? "units" : "percentage" + return intMode === IntervalTypeEnum.units ? "units" : "percentage" } export const getIntervalCSV = (csv: string[][]): IInterval => { const comment: string[] | undefined = csv.find((v: string[]) => v.length > 0 && v.join("").replace(/ /g, '').toUpperCase().startsWith('#INTERVAL:')) - if (comment != undefined && comment.length > 0) { + if (comment !== undefined && comment.length > 0) { const interval: string[] = comment.join("").toUpperCase().replace("#", "").replace("INTERVAL", "").replace(":", "").trim().split(" ") if (interval.length >= 3) { return { @@ -137,7 +137,7 @@ export const getIntervalCSV = (csv: string[][]): IInterval => { export const getDateTimeCSV = (csv: string[][]): DateTime | undefined => { const comment: string[] | undefined = csv.find((v: string[]) => v.length > 0 && v.join("").replace(/ /g, '').toUpperCase().startsWith('#DATETIME:')) - if (comment != undefined && comment.length > 0) { + if (comment !== undefined && comment.length > 0) { const dt: string = comment.join("").toUpperCase().replace(/ /g, '').replace("#DATETIME:", "").trim() //console.log("getDateTime", dt) const timestamp = Date.parse(dt) @@ -158,30 +158,30 @@ export const CSVtoData = (csv: string[][], model: IModel): IData[] => { const fileData: IData[] = [] //const noComments:string[][] = csv.filter((v:string[]) => v.length > 0 && !v.join("").replace(/ /g,'').toUpperCase().startsWith('#')) - const ids: string[] | undefined = fixEnd(csv.find((v: string[]) => v.length > 0 && v[0].toUpperCase().trim() == "ID")) - const def: string[] | undefined = fixEnd(csv.find((v: string[]) => v.length > 0 && v[0].toUpperCase().trim() == "DEFAULT_VALUE")) - let nw: string[] | undefined = fixEnd(csv.find((v: string[]) => v.length > 0 && v[0].toUpperCase().trim() == "NEW_VALUE")) - let interval: string[] | undefined = fixEnd(csv.find((v: string[]) => v.length > 0 && v[0].toUpperCase().trim() == "_INTERVAL")) + const ids: string[] | undefined = fixEnd(csv.find((v: string[]) => v.length > 0 && v[0].toUpperCase().trim() === "ID")) + const def: string[] | undefined = fixEnd(csv.find((v: string[]) => v.length > 0 && v[0].toUpperCase().trim() === "DEFAULT_VALUE")) + let nw: string[] | undefined = fixEnd(csv.find((v: string[]) => v.length > 0 && v[0].toUpperCase().trim() === "NEW_VALUE")) + let interval: string[] | undefined = fixEnd(csv.find((v: string[]) => v.length > 0 && v[0].toUpperCase().trim() === "_INTERVAL")) - if (ids && def && ids.length == def.length) { - if (nw && nw.length != ids.length) nw = undefined - if (interval && interval.length != ids.length) interval = undefined + if (ids && def && ids.length === def.length) { + if (nw && nw.length !== ids.length) nw = undefined + if (interval && interval.length !== ids.length) interval = undefined ids.forEach((d: string, idx: number) => { - if (model.tags.some((t: ITag) => t.id == d)) { - let raw_values:number[] = [] - if (def[idx].trim() != "") { - raw_values = def[idx].split(",").map((v:string) => Number(v)) + if (model.tags.some((t: ITag) => t.id === d)) { + let raw_values: number[] = [] + if (def[idx].trim() !== "") { + raw_values = def[idx].split(",").map((v: string) => Number(v)) } fileData.push({ id: d, default_value: getMean(raw_values), raw_values: raw_values, - new_value: (nw && nw[idx].trim() != "") ? nw[idx] : undefined, - set_percentage: (interval) ? interval[idx] == "YES" : undefined + new_value: (nw && nw[idx].trim() !== "") ? nw[idx] : undefined, + set_percentage: (interval) ? interval[idx] === "YES" : undefined }) } }) } return fileData -} \ No newline at end of file +} diff --git a/src/utils/datasources/grafana.tsx b/src/utils/datasources/grafana.tsx index 3488f25..a7a3c0e 100644 --- a/src/utils/datasources/grafana.tsx +++ b/src/utils/datasources/grafana.tsx @@ -29,7 +29,7 @@ export const getOptionsVariable = (templateSrv: TemplateSrv): ISelect[] => { return { label: item.name, value: item.name, - description: (item.description == null) ? undefined : item.description + description: (item.description === null) ? undefined : item.description } }) } @@ -44,29 +44,29 @@ const applyType = (value: any) => { } } -export const getArrayOfData = (data: PanelData, idQuery: string, fieldTag: string, isListValues:boolean, hasSpecificNumberOfValues?: number) => { +export const getArrayOfData = (data: PanelData, idQuery: string, fieldTag: string, isListValues: boolean, hasSpecificNumberOfValues?: number) => { let res: IData[] = [] - const serieData: DataFrame | undefined = data.series.find((serie) => serie.refId == idQuery) + const serieData: DataFrame | undefined = data.series.find((serie) => serie.refId === idQuery) if (serieData) { - const fieldTagData = serieData.fields.find((field) => field.name == fieldTag) + const fieldTagData = serieData.fields.find((field) => field.name === fieldTag) if (fieldTagData && fieldTagData.values.length > 0) { - const allValues = serieData.fields.filter((field) => field.name != fieldTag) + const allValues = serieData.fields.filter((field) => field.name !== fieldTag) const arrValues = fieldTagData.values - if(arrValues != null && arrValues != undefined && arrValues.length > 0) { - for(let idx = 0; idx < arrValues.length; idx++){ + if (arrValues !== null && arrValues !== undefined && arrValues.length > 0) { + for (let idx = 0; idx < arrValues.length; idx++) { let values: number[] = [] allValues.forEach((field) => { values.push(field.values.get(idx)) }) let mean = getMean(values) - if (isListValues && hasSpecificNumberOfValues != undefined && hasSpecificNumberOfValues > 0) { - values = values.map((v) => (v == null) ? mean : v) + if (isListValues && hasSpecificNumberOfValues !== undefined && hasSpecificNumberOfValues > 0) { + values = values.map((v) => (v === null) ? mean : v) if (values.length < hasSpecificNumberOfValues) { - values = values.concat(Array(hasSpecificNumberOfValues-values.length).fill(null)) + values = values.concat(Array(hasSpecificNumberOfValues - values.length).fill(null)) } else if (values.length > hasSpecificNumberOfValues) { values = values.slice(0, hasSpecificNumberOfValues) } - } + } res.push({ id: arrValues.get(idx), raw_values: values, @@ -74,7 +74,7 @@ export const getArrayOfData = (data: PanelData, idQuery: string, fieldTag: strin }) } } - + } } console.log("Datos cargados", res) @@ -83,10 +83,10 @@ export const getArrayOfData = (data: PanelData, idQuery: string, fieldTag: strin export const getExtraInfo = (data: PanelData, idQuery: string, fieldName: string, fieldValue: string) => { let res: { [key: string]: any } = {} - const serieData: DataFrame | undefined = data.series.find((serie) => serie.refId == idQuery) + const serieData: DataFrame | undefined = data.series.find((serie) => serie.refId === idQuery) if (serieData) { - const fieldNameData = serieData.fields.find((field) => field.name == fieldName) - const fieldValueData = serieData.fields.find((field) => field.name == fieldValue) + const fieldNameData = serieData.fields.find((field) => field.name === fieldName) + const fieldValueData = serieData.fields.find((field) => field.name === fieldValue) if (fieldNameData && fieldValueData) { fieldNameData.values.toArray().forEach((name: string, idx: number) => { res = { @@ -97,4 +97,4 @@ export const getExtraInfo = (data: PanelData, idQuery: string, fieldName: string } } return res -} \ No newline at end of file +} diff --git a/src/utils/datasources/predictions.tsx b/src/utils/datasources/predictions.tsx index d92c397..8263f7e 100644 --- a/src/utils/datasources/predictions.tsx +++ b/src/utils/datasources/predictions.tsx @@ -1,7 +1,7 @@ import { PreprocessCodeDefault } from "../default"; import { IData, IDataCollection, IDataPred, IFormat, IInterval, IModel, IResult, IScaler, IntervalTypeEnum } from "../types" //import * as dfd from "danfojs" -import { idDefault, idNew, variableInput, variableOutput } from "../constants" +import { idDefault, idNew, varEachInput, varEachInputEnd, varInput, variableOutput } from "../constants" import vm from 'vm' import { decimalCount, deepCopy, getMean, round, transposeMatrix } from "../utils" import { Buffer } from 'buffer' @@ -35,21 +35,21 @@ const predictData = async (model: IModel, dataCollection: IDataCollection) => { dataToPredict.push(finalData) results[i] = { ...r, processedData: finalData } } - const predictions:any = await sendRequest(model, dataToPredict) + const predictions: any = await sendRequest(model, dataToPredict) return results.map((r: IResult, indx: number) => { return { ...r, result: predictions[indx] } }) } const getValuesFromInterval = (interval: IInterval): number[] => { - if (interval.max == undefined || interval.min == undefined || interval.steps == undefined) return [] + if (interval.max === undefined || interval.min === undefined || interval.steps === undefined) return [] - const min_interval: number = Number(interval.min), max_interval: number = Number(interval.max), step_interval: number = Number(interval.steps) + const min_interval = Number(interval.min), max_interval = Number(interval.max), step_interval = Number(interval.steps) const dec = decimalCount(step_interval) - //const porcentages_min:number[] = Array.from({ length: Math.ceil(min_interval / step_interval)}, (_, i:number) => { var num = 0 - ((i+1) * step_interval); return (num < -min_interval) ? -min_interval : num}) - //const porcentages_max:number[] = Array.from({ length: Math.ceil(max_interval / step_interval)}, (_, i:number) => { var num = (i+1) * step_interval; return (num > max_interval) ? max_interval : num}) + //const porcentages_min:number[] = Array.from({ length: Math.ceil(min_interval / step_interval)}, (_, i:number) => { let num = 0 - ((i+1) * step_interval); return (num < -min_interval) ? -min_interval : num}) + //const porcentages_max:number[] = Array.from({ length: Math.ceil(max_interval / step_interval)}, (_, i:number) => { let num = (i+1) * step_interval; return (num > max_interval) ? max_interval : num}) //return porcentages_min.concat(porcentages_max).sort((a,b)=>a-b) - return Array.from({ length: Math.ceil((max_interval - min_interval) / step_interval) + 1 }, (_, i: number) => { var num = round((i * step_interval) + min_interval, dec); return (num > max_interval) ? max_interval : num }) + return Array.from({ length: Math.ceil((max_interval - min_interval) / step_interval) + 1 }, (_, i: number) => { let num = round((i * step_interval) + min_interval, dec); return (num > max_interval) ? max_interval : num }) } @@ -57,17 +57,17 @@ const calculatePercentage = (percent: number, total: number) => { return (percent / 100) * total } -const getListValuesFromNew = (newValue:number, mean:number, rawValues:number[]) : number[] => { - let weights = rawValues.map((r:number) => Math.abs(r)/Math.abs(mean)) // Obtener PESOS - return weights.map((w:number) => w*newValue) // Otener nuevos valores a partir del nuevo y los pesos +const getListValuesFromNew = (newValue: number, mean: number, rawValues: number[]): number[] => { + let weights = rawValues.map((r: number) => Math.abs(r) / Math.abs(mean)) // Obtener PESOS + return weights.map((w: number) => w * newValue) // Otener nuevos valores a partir del nuevo y los pesos } const addResultsFromValues = (res: IResult[], rawData: IDataPred, values: number[], id: string, intervalType: IntervalTypeEnum) => { const mean: number = getMean(rawData[id]) // Cojo la media de todos los valores values.forEach((p: number) => { let newData = deepCopy(rawData) // Hago una copia del array de valores - let new_value = -1 - if (intervalType == IntervalTypeEnum.percentage) { // A partir de la media saco cada nuevo valor considerado en el intervalo + let new_value = -1 + if (intervalType === IntervalTypeEnum.percentage) { // A partir de la media saco cada nuevo valor considerado en el intervalo const v = calculatePercentage(Math.abs(p), Math.abs(mean)) new_value = (p < 0) ? mean - v : mean + v } else { @@ -88,23 +88,23 @@ const addResultsFromValues = (res: IResult[], rawData: IDataPred, values: number return res } -const defaultDataToObject = (data: IData[]) : IDataPred => { - var res: IDataPred = {} +const defaultDataToObject = (data: IData[]): IDataPred => { + let res: IDataPred = {} data.forEach((d: IData) => { res[d.id] = (d.raw_values) ? d.raw_values : [] }) // nunca deberia ser [] return res } -const newDataToObject = (data: IData[], hasInterval: boolean, numberOfElements: number = 1): IDataPred => { - var res: IDataPred = {} +const newDataToObject = (data: IData[], hasInterval: boolean, numberOfElements = 1): IDataPred => { + let res: IDataPred = {} data.forEach((d: IData) => { - let vals =(d.raw_values) ? d.raw_values : [] - if(d.new_value != undefined && !(hasInterval && d.set_percentage)) { + let vals = (d.raw_values) ? d.raw_values : [] + if (d.new_value !== undefined && !(hasInterval && d.set_percentage)) { //vals = Array.from({ length: ((numberOfElements != undefined && numberOfElements > 0) ? numberOfElements : 1) }, () => Number(d.new_value)) - if(vals.length > 0){ + if (vals.length > 0) { vals = getListValuesFromNew(Number(d.new_value), getMean(vals), vals) } else { - vals = Array.from({ length: ((numberOfElements != undefined && numberOfElements > 0) ? numberOfElements : 1) }, () => Number(d.new_value)) + vals = Array.from({ length: ((numberOfElements !== undefined && numberOfElements > 0) ? numberOfElements : 1) }, () => Number(d.new_value)) } } res[d.id] = vals @@ -113,13 +113,13 @@ const newDataToObject = (data: IData[], hasInterval: boolean, numberOfElements: return res } -const prepareData = (dataCollection: IDataCollection, numberOfValues?:number): IResult[] => { +const prepareData = (dataCollection: IDataCollection, numberOfValues?: number): IResult[] => { let res: IResult[] = [] - var baseData: IDataPred = {} + let baseData: IDataPred = {} const hasInterval = dataCollection.interval.max !== undefined && dataCollection.interval.min !== undefined && dataCollection.interval.steps !== undefined // Prediccion basica con los valores nuevos - if (!(dataCollection.data.some((d: IData) => d.default_value == undefined))) { // Solo se predice el default si estan todos los datos + if (!(dataCollection.data.some((d: IData) => d.default_value === undefined))) { // Solo se predice el default si estan todos los datos const defaultData: IDataPred = defaultDataToObject(dataCollection.data) //dataCollection.data.map((d:IData) => (d.default_value) ? d.default_value : 0) res.push({ id: idDefault, // ESTOY METIENDO LOS DATOS DEFAULT @@ -128,7 +128,7 @@ const prepareData = (dataCollection: IDataCollection, numberOfValues?:number): I baseData = defaultData } - if (dataCollection.data.some((d: IData) => d.new_value != undefined && d.new_value.trim() != '')) { + if (dataCollection.data.some((d: IData) => d.new_value !== undefined && d.new_value.trim() !== '')) { //const onlyNewData:number[] = dataCollection.data.map((d:IData) => (d.set_percentage == true || d.new_value == undefined) ? ((d.default_value) ? d.default_value : 0) : Number(d.new_value)) const onlyNewData: IDataPred = newDataToObject(dataCollection.data, hasInterval, numberOfValues) res.push({ @@ -140,7 +140,7 @@ const prepareData = (dataCollection: IDataCollection, numberOfValues?:number): I // Predicciones cambiando el intervalo const interval: IInterval = dataCollection.interval - if (interval.max != undefined && interval.min != undefined && interval.steps != undefined) { + if (interval.max !== undefined && interval.min !== undefined && interval.steps !== undefined) { const values: number[] = getValuesFromInterval(interval) dataCollection.data.filter((sData: IData) => sData.set_percentage).forEach((sData: IData) => { res = addResultsFromValues(res, baseData, values, sData.id, interval.type) @@ -151,54 +151,79 @@ const prepareData = (dataCollection: IDataCollection, numberOfValues?:number): I return res } -export const applyScaler = function (scaler: IScaler, data_dict: IDataPred) : IDataPred { +export const applyScaler = function (scaler: IScaler, data_dict: IDataPred): IDataPred { let scaled_data_dict: IDataPred = {} - Object.entries(data_dict).forEach(([key, l]: [string, number[]], idx:number) => { - scaled_data_dict[key] = (l != undefined && l != null && l.length > 0) ? l.map((v:number) => (v - scaler.mean[idx]) / scaler.scale[idx]) : l + Object.entries(data_dict).forEach(([key, l]: [string, number[]], idx: number) => { + scaled_data_dict[key] = (l !== undefined && l != null && l.length > 0) ? l.map((v: number) => (v - scaler.mean[idx]) / scaler.scale[idx]) : l //scaled_data_dict[key] = (value - scaler.mean[idx]) / scaler.scale[idx] }) return scaled_data_dict; } export const applyPreprocess = async (code: string, data: IDataPred) => { - if (code != PreprocessCodeDefault) { + if (code !== PreprocessCodeDefault) { try { - //var preprocess = new Function(code) // https://stackoverflow.com/a/9702401/16131308 + //let preprocess = new Function(code) // https://stackoverflow.com/a/9702401/16131308 const sandbox = { data: data } - var context = vm.createContext(sandbox) // https://stackoverflow.com/a/55056012/16131308 <--- te quiero + let context = vm.createContext(sandbox) // https://stackoverflow.com/a/55056012/16131308 <--- te quiero data = vm.runInContext(code, context) } catch (error) { - //console.log(error) + console.log(error) console.error("Preprocess failed") } } return data } -const objectWithFirstElement = (list:number[][]): number[] => { - return list.map((v:number[]) => v[0]) +const objectWithFirstElement = (list: number[][]): number[] => { + return list.map((v: number[]) => v[0]) } const addFormatInput = (data: IDataPred[], isListValues: boolean, isTransposeList: boolean, format?: IFormat): string => { - let body = "" const aux = data.map((d: IDataPred) => { - let dataPred:any = Object.values(d) - if(!isListValues) { + let dataPred: any = Object.values(d) + if (!isListValues) { dataPred = objectWithFirstElement(dataPred) - } else { - if (isTransposeList) dataPred = transposeMatrix(dataPred) + } else if (isTransposeList) { + dataPred = transposeMatrix(dataPred) } return dataPred }) - body = JSON.stringify(aux) - body = body.substring(1, body.length - 1) - if (format != undefined) body = format.input.replace(variableInput, body) + console.log("AUX", aux) + let body = "" + + if (format !== undefined) { + let allFormat = format.input + + const startIndex = format.input.indexOf(varEachInput) + const endIndex = format.input.indexOf(varEachInputEnd) + + if(startIndex !== -1 && endIndex !== -1){ + const eachFormat = format.input.slice(startIndex + varEachInput.length, endIndex).trim(); + let allInputs = aux.map((v: any) => { + let str = JSON.stringify(v) + str = str.substring(1, str.length - 1) + return eachFormat.replace(varInput, str) + }) + body = allInputs.join(",") + console.log(body) + allFormat = format.input.slice(0, startIndex) + " $input " + format.input.slice(endIndex + varEachInputEnd.length) + console.log(allFormat) + } else { + console.log("No hay each") + body = JSON.stringify(aux) + body = body.substring(1, body.length - 1) + } + body = allFormat.replace(varInput, body) + } else { + body = JSON.stringify(aux) + } console.log(body) return body } const removeFormatOutput = (result: string, format?: IFormat): number[] => { - if (format != undefined) { + if (format !== undefined) { const indx = format.output.indexOf(variableOutput) const res: string[] = result @@ -211,7 +236,7 @@ const removeFormatOutput = (result: string, format?: IFormat): number[] => { return [Number(result)] } -const sendRequest = async (model:IModel, data: IDataPred[]) => { +const sendRequest = async (model: IModel, data: IDataPred[]) => { let myHeaders = new Headers() myHeaders.append("Content-Type", "application/json") @@ -226,7 +251,7 @@ const sendRequest = async (model:IModel, data: IDataPred[]) => { } let response = await fetch(model.url, requestOptions) - if(response.ok){ + if (response.ok) { let text: string = await response.text() console.log(text) return removeFormatOutput(text, model.format) @@ -235,4 +260,4 @@ const sendRequest = async (model:IModel, data: IDataPred[]) => { return 'ERROR' } -} \ No newline at end of file +} diff --git a/src/utils/default.tsx b/src/utils/default.tsx index 305fd37..686d828 100644 --- a/src/utils/default.tsx +++ b/src/utils/default.tsx @@ -1,7 +1,7 @@ import { messages_en } from "./localization/en"; import { FormatTags, IContext, IDataCollection, IFormat, IModel, IInterval, ITag, Language, Method, IntervalTypeEnum } from "./types"; -export const PreprocessCodeDefault: string = "console.log('Preprocess')" +export const PreprocessCodeDefault = "console.log('Preprocess')" export const FormatDefault: IFormat = { id: "", @@ -120,4 +120,4 @@ export const sampleData: ITag[] = [ description: "descripcion1", category: "Categoria 3" } -] \ No newline at end of file +]