Skip to content

Commit

Permalink
Now you can use only Date and not necessarily DateTime to import the …
Browse files Browse the repository at this point in the history
…data
  • Loading branch information
juliarobles committed Dec 13, 2024
1 parent 632831d commit b0f9bc9
Show file tree
Hide file tree
Showing 6 changed files with 44 additions and 29 deletions.
32 changes: 20 additions & 12 deletions src/components/editors/modelForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,6 @@ export const ModelForm: React.FC<Props> = ({ model, updateFunction, deleteFuncti
const [code, setCode] = useState<string>("")
const [disabled, setDisabled] = useState(false)
const [scaler, setScaler] = useState("")
const [listValues, setListValues] = useState<boolean>(false)
const [transposeList, setTransposeList] = useState<boolean>(false)

const updateCurrentState = () => {
setCurrentModel(model)
Expand All @@ -61,8 +59,6 @@ export const ModelForm: React.FC<Props> = ({ model, updateFunction, deleteFuncti
setSelectedQuotesListItems({ label: model.formatTags, value: model.formatTags })
setCode((model.preprocess) ? model.preprocess : "")
setScaler((model.scaler) ? JSON.stringify(model.scaler, undefined, 4) : "")
setListValues(model.isListValues)
setTransposeList(model.isTransposeList)
}


Expand All @@ -73,6 +69,14 @@ export const ModelForm: React.FC<Props> = ({ model, updateFunction, deleteFuncti
})
}

const handleOnChangeModelCheckBox = (key: string, ) => {
let k = key as keyof IModel
setCurrentModel({
...currentModel,
[k]: !currentModel[k]
})
}

const handleOnChangeCredentials = (event: ChangeEvent<HTMLInputElement>) => {
const oldCredentials: ICredentials = (currentModel.credentials) ? { ...currentModel.credentials } : { username: "", password: "" }
setCurrentModel({
Expand Down Expand Up @@ -101,9 +105,7 @@ export const ModelForm: React.FC<Props> = ({ model, updateFunction, deleteFuncti
format: selectedFormat?.value,
extraCalc: selectedExtraCalc?.value,
preprocess: code,
credentials: credentials,
isListValues: listValues,
isTransposeList: transposeList
credentials: credentials
}
newModel.scaler = (scaler.trim() !== "") ? JSON.parse(scaler) : undefined
//console.log(newModel)
Expand Down Expand Up @@ -308,20 +310,23 @@ export const ModelForm: React.FC<Props> = ({ model, updateFunction, deleteFuncti
name="query"
/>
</InlineField>
<InlineField label="Select date only" labelWidth={20} disabled={disabled} grow style={{ display: 'flex', alignItems: 'center' }}>
<Checkbox {...register("onlyDate")} disabled={disabled} value={currentModel.onlyDate} onChange={() => handleOnChangeModelCheckBox('onlyDate')} />
</InlineField>
<InlineField label="Tags column" labelWidth={20} grow disabled={disabled} required>
<Input {...register("columnTag")} disabled={disabled} required value={currentModel.columnTag} onChange={handleOnChangeModel} />
</InlineField>
<InlineField label="Values column" labelWidth={20} grow disabled={disabled} required>
<Input {...register("columnValue")} disabled={disabled} required value={currentModel.columnValue} onChange={handleOnChangeModel} />
</InlineField>
<InlineField label="Returns a list of values" labelWidth={20} disabled={disabled} grow style={{ display: 'flex', alignItems: 'center' }}>
<Checkbox {...register("listValues")} disabled={disabled} value={listValues} onChange={() => setListValues(!listValues)} />
<Checkbox {...register("listValues")} disabled={disabled} value={currentModel.isListValues} onChange={() => handleOnChangeModelCheckBox('isListValues')} />
</InlineField>
<InlineField label="Transpose values table" labelWidth={20} disabled={disabled || !listValues} grow style={{ display: 'flex', alignItems: 'center' }}>
<Checkbox {...register("transposeList")} disabled={disabled || !listValues} value={transposeList} onChange={() => setTransposeList(!transposeList)} />
<InlineField label="Transpose values table" labelWidth={20} disabled={disabled || !currentModel.isListValues} grow style={{ display: 'flex', alignItems: 'center' }}>
<Checkbox {...register("transposeList")} disabled={disabled || !currentModel.isListValues} value={currentModel.isTransposeList} onChange={() => handleOnChangeModelCheckBox('isTransposeList')} />
</InlineField>
<InlineField label="Fixed number of values" labelWidth={20} disabled={disabled || !listValues} grow>
<Input {...register("numberOfValues")} disabled={disabled || !listValues} value={currentModel.numberOfValues} onChange={handleOnChangeModel} type='number' />
<InlineField label="Fixed number of values" labelWidth={20} disabled={disabled || !currentModel.isListValues} grow>
<Input {...register("numberOfValues")} disabled={disabled || !currentModel.isListValues} value={currentModel.numberOfValues} onChange={handleOnChangeModel} type='number' />
</InlineField>
<p style={{ marginBottom: '5px', marginTop: '15px' }}>Extra info query</p>
<InlineField label="Extra info" labelWidth={20} disabled={disabled} grow>
Expand Down Expand Up @@ -380,6 +385,9 @@ export const ModelForm: React.FC<Props> = ({ model, updateFunction, deleteFuncti
name="varTimeRange"
/>
</InlineField>
<InlineField label="Select date only" labelWidth={20} disabled={disabled} grow style={{ display: 'flex', alignItems: 'center' }}>
<Checkbox {...register("onlyDateRange")} disabled={disabled} value={currentModel.onlyDateRange} onChange={() => handleOnChangeModelCheckBox('onlyDateRange')} />
</InlineField>
</Collapse>
<Collapse label="Connection with model" collapsible={false} isOpen={true} className={css({ color: useTheme2().colors.text.primary })}>
<InlineFieldRow>
Expand Down
30 changes: 17 additions & 13 deletions src/components/step2_ImportData.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Button, DatePickerWithInput, InlineLabel, Select, TimeOfDayPicker, useTheme2, VerticalGroup } from '@grafana/ui'
import React, { FormEvent, useContext, useEffect, useState } from 'react'
import { Context, dateTimeLocalToString, dateTimeToString, dateTimeToTimestamp, disabledByJS } from 'utils/utils'
import { Context, dateTimeLocalToString, dateTimeToString, dateTimeToTimestamp, dateToString, disabledByJS } from 'utils/utils'
import { IData, IDataCollection, IInterval, IModel } from 'utils/types'
import { getArrayOfData, getExtraInfo, saveVariableValue } from 'utils/datasources/grafana'
import { AppEvents, dateTime, DateTime, LoadingState, PanelData, SelectableValue } from '@grafana/data'
import { AppEvents, DataQueryError, dateTime, DateTime, LoadingState, PanelData, SelectableValue } from '@grafana/data'
import Papa, { ParseError } from 'papaparse'
import { DefaultImportData, ImportDataEnum, ImportDataOptions, Steps, VariablesGrafanaOptions } from 'utils/constants'
import { IntervalDefault, ModelDefault } from 'utils/default'
Expand Down Expand Up @@ -68,15 +68,16 @@ export const ImportData: React.FC<Props> = ({ model, collections, addCollection,
const importDataFromDateTime = (dt?: DateTime) => {
if (dt !== undefined && model !== undefined) {
setHasToSaveNewData(dt)
saveVariableValue(locationService, model.varTime, dateTimeToString(dt))
let dateStr = (model.onlyDate) ? dateToString(dt.toDate()) : dateTimeToString(dt)
saveVariableValue(locationService, model.varTime, dateStr)
}
}

const importDataFromDateTimeRange = (start: DateTime, stop: DateTime) => {
if (model !== undefined && model.varTimeStart !== undefined) {
saveVariableValue(locationService, model.varTimeStart, dateTimeToString(start))
saveVariableValue(locationService, model.varTimeStart, ((model.onlyDateRange) ? dateToString(start.toDate()) : dateTimeToString(start)))
setHasToSaveNewData(stop)
saveVariableValue(locationService, model.varTime, dateTimeToString(stop))
saveVariableValue(locationService, model.varTime, ((model.onlyDateRange) ? dateToString(stop.toDate()) : dateTimeToString(stop)))
}
}

Expand Down Expand Up @@ -208,19 +209,19 @@ export const ImportData: React.FC<Props> = ({ model, collections, addCollection,
&& (hasToSaveNewData === dateTimeInput || (selectedGrafanaVariable && hasToSaveNewData === selectedGrafanaVariable.value))
&& model !== undefined
&& (data.state === LoadingState.Done || data.state === LoadingState.Error)) {

if (data.state === LoadingState.Done) {
console.log("Done")
console.log("Data", data)
let extraInfo = undefined
let arrayData: IData[] = []
let name = dateTimeLocalToString(hasToSaveNewData)
let name = ((model.onlyDate && mode.value === ImportDataEnum.DATETIME_SET)
|| (model.onlyDateRange && mode.value === ImportDataEnum.DATETIME_RANGE)) ? dateToString(hasToSaveNewData.toDate()) : dateTimeLocalToString(hasToSaveNewData)
let text = "DateTime"
let key = dateTimeToTimestamp(hasToSaveNewData).toString()
let dtStart: DateTime | undefined = undefined
if(mode.value === ImportDataEnum.DATETIME_RANGE && model.queryRangeId) {
arrayData = getArrayOfData(data, model.queryRangeId, fieldTag, model.isListValues, model.numberOfValues)
name = dateTimeLocalToString(dateTimeInputStart) + " to " + name
name = ((model.onlyDateRange) ? dateToString(dateTimeInputStart.toDate()) : dateTimeLocalToString(dateTimeInputStart)) + " to " + name
text = text + " range"
dtStart = dateTimeInputStart
key = dateTimeToTimestamp(dateTimeInputStart).toString() + "+" + key
Expand All @@ -239,13 +240,16 @@ export const ImportData: React.FC<Props> = ({ model, collections, addCollection,
})
}
} else {
console.log("ERROR")
console.log("Data", data)
const appEvents = getAppEvents();
const msgsError = data.errors?.map((v: DataQueryError) => v.message)
appEvents.publish({
type: AppEvents.alertError.name,
payload: [data.error]
payload: msgsError
})
}
saveVariableValue(locationService, model.varTime, dateTimeToString(dateTime()))
saveVariableValue(locationService, model.varTime, dateToString(new Date()))
setHasToSaveNewData(undefined)
}
}, [data])
Expand All @@ -272,7 +276,7 @@ export const ImportData: React.FC<Props> = ({ model, collections, addCollection,
className='fullWidth'
closeOnSelect
/>
<div className='timePicker fullWidth' style={{ marginTop: '8px' }}>
<div className='timePicker fullWidth' style={{ marginTop: '8px' }} hidden={model?.onlyDate || disabled}>
<TimeOfDayPicker
onChange={(d) => handleOnChangeTime(d, dateTimeInput, setDateTimeInput)}
showSeconds={false}
Expand All @@ -287,14 +291,14 @@ export const ImportData: React.FC<Props> = ({ model, collections, addCollection,
<div style={{ width: '50%' }}>
<InlineLabel transparent style={{ justifyContent: 'center' }}>{context.messages._panel._step2.startRange}</InlineLabel>
<DatePickerWithInput onChange={(d) => handleOnChangeDate(d, dateTimeInputStart, setDateTimeInputStart)} value={dateTimeInputStart?.toDate()} maxDate={new Date()} disabled={disabled} className='fullWidth' closeOnSelect />
<div className='timePicker fullWidth' style={{ marginTop: '8px' }}>
<div className='timePicker fullWidth' style={{ marginTop: '8px' }} hidden={model?.onlyDateRange || disabled}>
<TimeOfDayPicker onChange={(d) => handleOnChangeTime(d, dateTimeInputStart, setDateTimeInputStart)} showSeconds={false} value={dateTimeInputStart.local()} size='auto' disabled={disabled} />
</div>
</div>
<div style={{ width: '50%' }}>
<InlineLabel transparent style={{ justifyContent: 'center' }}>{context.messages._panel._step2.stopRange}</InlineLabel>
<DatePickerWithInput onChange={(d) => handleOnChangeDate(d, dateTimeInput, setDateTimeInput)} value={dateTimeInput?.toDate()} maxDate={new Date()} disabled={disabled} className='fullWidth' closeOnSelect />
<div className='timePicker fullWidth' style={{ marginTop: '8px' }}>
<div className='timePicker fullWidth' style={{ marginTop: '8px' }} hidden={model?.onlyDateRange || disabled}>
<TimeOfDayPicker onChange={(d) => handleOnChangeTime(d, dateTimeInput, setDateTimeInput)} showSeconds={false} value={dateTimeInput.local()} size='auto' disabled={disabled} />
</div>
</div>
Expand Down
6 changes: 3 additions & 3 deletions src/components/step3_ModifyData.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { AppEvents, SelectableValue, dateTime } from '@grafana/data';
import { AppEvents, SelectableValue } from '@grafana/data';
import { Checkbox, Field, HorizontalGroup, Icon, Input, Select, CustomScrollbar, useTheme2, ToolbarButton, ButtonGroup, InlineField, InlineSwitch, ConfirmButton, Button } from '@grafana/ui';
import React, { useContext, useState, useEffect, ChangeEvent } from 'react';
import { Context, defaultIfUndefined, collectionsToSelect, groupBy, dateTimeToString, deepCopy } from '../utils/utils'
import { Context, defaultIfUndefined, collectionsToSelect, groupBy, deepCopy, dateToString } from '../utils/utils'
import { ICategory, IModel, ISelect, ITag, IInterval, IDataCollection, IData, Colors, IntervalColors, IntervalTypeEnum } from '../utils/types'
import { Steps } from 'utils/constants';
import { CollectionDefault, IntervalDefault } from 'utils/default';
Expand Down Expand Up @@ -166,7 +166,7 @@ export const ModifyData: React.FC<Props> = ({ model, collections, deleteCollecti
context.setActualStep(Steps.step_2)
setSelectCollection(undefined)
setcollectionsOptions([])
if (model !== undefined) saveVariableValue(locationService, model.varTime, dateTimeToString(dateTime()))
if (model !== undefined) saveVariableValue(locationService, model.varTime, dateToString(new Date()))
}
if (currentCollIdx !== undefined && collections && currentCollIdx < collections.length) {
deleteCollection(collections[currentCollIdx].id)
Expand Down
1 change: 0 additions & 1 deletion src/utils/datasources/grafana.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ export const checkIfVariableExists = (templateSrv: TemplateSrv, id?: string) =>
export const saveVariableValue = (locationService: LocationService, id: string, value: string) => {
let queryObj: any = {}
queryObj[("var-" + id)] = value

locationService.partial(queryObj, true)
}

Expand Down
2 changes: 2 additions & 0 deletions src/utils/default.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ export const ModelDefault: IModel = {
url: "",
description: "",
queryId: "",
onlyDate: false,
method: Method.POST,
onlyDateRange: false,
tags: [],
format: FormatDefault,
preprocess: PreprocessCodeDefault,
Expand Down
2 changes: 2 additions & 0 deletions src/utils/types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,9 @@ export interface IModel {
method: Method,
credentials?: ICredentials
queryId: string,
onlyDate?: boolean,
queryRangeId?: string,
onlyDateRange?: boolean,
tags: ITag[],
preprocess?: string,
scaler?: IScaler,
Expand Down

0 comments on commit b0f9bc9

Please sign in to comment.