Skip to content

Commit

Permalink
feat(asset): resolve minion id (#73)
Browse files Browse the repository at this point in the history
Co-authored-by: rmilea <robert.milea@ni.com>
  • Loading branch information
MileaRobertStefan and robertMileaNi authored Oct 3, 2024
1 parent fa0d90b commit 75972dd
Show file tree
Hide file tree
Showing 3 changed files with 108 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,16 @@ import {
CalibrationForecastResponse,
ColumnDescriptorType,
} from "./types";
import { SystemMetadata } from "datasources/system/types";

let datastore: AssetCalibrationDataSource, backendServer: MockProxy<BackendSrv>

beforeEach(() => {
[datastore, backendServer] = setupDataSource(AssetCalibrationDataSource);

backendServer.fetch
.calledWith(requestMatching({ url: '/nisysmgmt/v1/query-systems' }))
.mockReturnValue(createFetchResponse({ data: fakeSystems }));
});

const monthGroupCalibrationForecastResponseMock: CalibrationForecastResponse =
Expand Down Expand Up @@ -63,6 +68,18 @@ const locationGroupCalibrationForecastResponseMock: CalibrationForecastResponse
}
}

const minionIdLocationGroupCalibrationForecastResponseMock: CalibrationForecastResponse =
{
calibrationForecast: {
columns: [
{ name: "", values: [1], columnDescriptors: [{ value: "Minion1", type: ColumnDescriptorType.MinionId }] },
{ name: "", values: [2], columnDescriptors: [{ value: "Minion2", type: ColumnDescriptorType.MinionId }] },
{ name: "", values: [3], columnDescriptors: [{ value: "Minion3", type: ColumnDescriptorType.MinionId }] }
]
}
}


const modelGroupCalibrationForecastResponseMock: CalibrationForecastResponse =
{
calibrationForecast: {
Expand Down Expand Up @@ -143,6 +160,21 @@ const buildCalibrationForecastQuery = getQueryBuilder<AssetCalibrationQuery>()({
groupBy: []
});

const fakeSystems: SystemMetadata[] = [
{
id: 'Minion1',
alias: 'Minion1-alias',
state: 'CONNECTED',
workspace: '1',
},
{
id: 'Minion2',
alias: undefined,
state: 'DISCONNECTED',
workspace: '2',
},
];

describe('testDatasource', () => {
test('returns success', async () => {
backendServer.fetch
Expand Down Expand Up @@ -204,6 +236,16 @@ describe('queries', () => {
expect(result.data).toMatchSnapshot()
})

test('calibration forecast with minion ID location groupBy', async () => {
backendServer.fetch
.calledWith(requestMatching({ url: '/niapm/v1/assets/calibration-forecast' }))
.mockReturnValue(createFetchResponse(minionIdLocationGroupCalibrationForecastResponseMock as CalibrationForecastResponse))

const result = await datastore.query(buildCalibrationForecastQuery(locationBasedCalibrationForecastQueryMock))

expect(result.data).toMatchSnapshot()
})

test('calibration forecast with model groupBy', async () => {
backendServer.fetch
.calledWith(requestMatching({ url: '/niapm/v1/assets/calibration-forecast' }))
Expand Down
41 changes: 40 additions & 1 deletion src/datasources/asset-calibration/AssetCalibrationDataSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,16 @@ import {
AssetCalibrationQuery,
AssetCalibrationTimeBasedGroupByType,
CalibrationForecastResponse,
ColumnDescriptorType,
FieldDTOWithDescriptor,
} from './types';
import { transformComputedFieldsQuery } from 'core/query-builder.utils';
import { AssetComputedDataFields } from './constants';
import { AssetModel, AssetsResponse } from 'datasources/asset-common/types';
import TTLCache from '@isaacs/ttlcache';
import { metadataCacheTTL } from 'datasources/data-frame/constants';
import { SystemMetadata } from 'datasources/system/types';
import { defaultOrderBy, defaultProjection } from 'datasources/system/constants';

export class AssetCalibrationDataSource extends DataSourceBase<AssetCalibrationQuery> {
public defaultQuery = {
Expand All @@ -34,7 +39,11 @@ export class AssetCalibrationDataSource extends DataSourceBase<AssetCalibrationQ

baseUrl = this.instanceSettings.url + '/niapm/v1';

systemAliasCache: TTLCache<string, SystemMetadata> = new TTLCache<string, SystemMetadata>({ ttl: metadataCacheTTL });

async runQuery(query: AssetCalibrationQuery, options: DataQueryRequest): Promise<DataFrameDTO> {
await this.loadSystems();

if (query.filter) {
query.filter = this.templateSrv.replace(transformComputedFieldsQuery(query.filter, AssetComputedDataFields), options.scopedVars);
}
Expand Down Expand Up @@ -100,7 +109,14 @@ export class AssetCalibrationDataSource extends DataSourceBase<AssetCalibrationQ
}

createColumnNameFromDescriptor(field: FieldDTOWithDescriptor): string {
return field.columnDescriptors.map(descriptor => descriptor.value).join(' - ');
return field.columnDescriptors.map(descriptor => {
if (descriptor.type === ColumnDescriptorType.MinionId && this.systemAliasCache) {
const system = this.systemAliasCache.get(descriptor.value);

return system?.alias || descriptor.value
}
return descriptor.value
}).join(' - ');
}

formatDateForDay(date: string): string {
Expand Down Expand Up @@ -142,6 +158,29 @@ export class AssetCalibrationDataSource extends DataSourceBase<AssetCalibrationQ
}
}

async querySystems(filter = '', projection = defaultProjection): Promise<SystemMetadata[]> {
try {
let response = await this.getSystems({
filter: filter,
projection: `new(${projection.join()})`,
orderBy: defaultOrderBy,
})

return response.data;
} catch (error) {
throw new Error(`An error occurred while querying systems: ${error}`);
}
}

private async loadSystems(): Promise<void> {
if (this.systemAliasCache.size > 0) {
return;
}

const systems = await this.querySystems('', ['id', 'alias','connected.data.state', 'workspace']);
systems.forEach(system => this.systemAliasCache.set(system.id, system));
}

async testDatasource(): Promise<TestDataSourceResponse> {
await this.get(this.baseUrl + '/assets?take=1');
return { status: 'success', message: 'Data source connected and authentication successful!' };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,32 @@ exports[`queries calibration forecast with location groupBy 1`] = `
]
`;

exports[`queries calibration forecast with minion ID location groupBy 1`] = `
[
{
"fields": [
{
"name": "Group",
"values": [
"Minion1-alias",
"Minion2",
"Minion3",
],
},
{
"name": "Assets",
"values": [
1,
2,
3,
],
},
],
"refId": "A",
},
]
`;

exports[`queries calibration forecast with model and location groupBy 1`] = `
[
{
Expand Down

0 comments on commit 75972dd

Please sign in to comment.