• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mendersoftware / gui / 988636079

01 Sep 2023 04:03AM UTC coverage: 82.384% (-17.6%) from 99.964%
988636079

Pull #3968

gitlab-ci

web-flow
chore: Bump @babel/plugin-transform-runtime from 7.22.9 to 7.22.10

Bumps [@babel/plugin-transform-runtime](https://github.com/babel/babel/tree/HEAD/packages/babel-plugin-transform-runtime) from 7.22.9 to 7.22.10.
- [Release notes](https://github.com/babel/babel/releases)
- [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md)
- [Commits](https://github.com/babel/babel/commits/v7.22.10/packages/babel-plugin-transform-runtime)

---
updated-dependencies:
- dependency-name: "@babel/plugin-transform-runtime"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Pull Request #3968: chore: Bump @babel/plugin-transform-runtime from 7.22.9 to 7.22.10

4346 of 6321 branches covered (0.0%)

8259 of 10025 relevant lines covered (82.38%)

192.71 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

89.95
/src/js/actions/deviceActions.js
1
/*eslint import/namespace: ['error', { allowComputed: true }]*/
2
import React from 'react';
3
import { Link } from 'react-router-dom';
4

5
import { isCancel } from 'axios';
6
import pluralize from 'pluralize';
7
import { v4 as uuid } from 'uuid';
8

9
import { commonErrorFallback, commonErrorHandler, setSnackbar } from '../actions/appActions';
10
import { getSingleDeployment } from '../actions/deploymentActions';
11
import { auditLogsApiUrl } from '../actions/organizationActions';
12
import { cleanUpUpload, progress } from '../actions/releaseActions';
13
import { saveGlobalSettings } from '../actions/userActions';
14
import GeneralApi, { MAX_PAGE_SIZE, apiUrl, headerNames } from '../api/general-api';
15
import { routes, sortingAlternatives } from '../components/devices/base-devices';
16
import { SORTING_OPTIONS, TIMEOUTS, UPLOAD_PROGRESS, emptyChartSelection, yes } from '../constants/appConstants';
17
import * as DeviceConstants from '../constants/deviceConstants';
18
import { rootfsImageVersion } from '../constants/releaseConstants';
19
import { attributeDuplicateFilter, deepCompare, extractErrorMessage, getSnackbarMessage, mapDeviceAttributes } from '../helpers';
20
import {
21
  getDeviceById as getDeviceByIdSelector,
22
  getDeviceFilters,
23
  getDeviceTwinIntegrations,
24
  getGroups as getGroupsSelector,
25
  getIdAttribute,
26
  getTenantCapabilities,
27
  getUserCapabilities,
28
  getUserSettings
29
} from '../selectors';
30
import { chartColorPalette } from '../themes/Mender';
31
import { getDeviceMonitorConfig, getLatestDeviceAlerts } from './monitorActions';
32
import { filtersFilter } from '../components/devices/widgets/filters';
33

34
const { DEVICE_FILTERING_OPTIONS, DEVICE_STATES, DEVICE_LIST_DEFAULTS, UNGROUPED_GROUP, emptyFilter } = DeviceConstants;
185✔
35
const { page: defaultPage, perPage: defaultPerPage } = DEVICE_LIST_DEFAULTS;
185✔
36

37
export const deviceAuthV2 = `${apiUrl.v2}/devauth`;
185✔
38
export const deviceConnect = `${apiUrl.v1}/deviceconnect`;
185✔
39
export const inventoryApiUrl = `${apiUrl.v1}/inventory`;
185✔
40
export const inventoryApiUrlV2 = `${apiUrl.v2}/inventory`;
185✔
41
export const deviceConfig = `${apiUrl.v1}/deviceconfig/configurations/device`;
185✔
42
export const reportingApiUrl = `${apiUrl.v1}/reporting`;
185✔
43
export const iotManagerBaseURL = `${apiUrl.v1}/iot-manager`;
185✔
44

45
const defaultAttributes = [
185✔
46
  { scope: 'identity', attribute: 'status' },
47
  { scope: 'inventory', attribute: 'artifact_name' },
48
  { scope: 'inventory', attribute: 'device_type' },
49
  { scope: 'inventory', attribute: 'mender_is_gateway' },
50
  { scope: 'inventory', attribute: 'mender_gateway_system_id' },
51
  { scope: 'inventory', attribute: rootfsImageVersion },
52
  { scope: 'monitor', attribute: 'alerts' },
53
  { scope: 'system', attribute: 'created_ts' },
54
  { scope: 'system', attribute: 'updated_ts' },
55
  { scope: 'system', attribute: 'check_in_time' },
56
  { scope: 'system', attribute: 'group' },
57
  { scope: 'tags', attribute: 'name' }
58
];
59

60
export const getSearchEndpoint = hasReporting => (hasReporting ? `${reportingApiUrl}/devices/search` : `${inventoryApiUrlV2}/filters/search`);
486!
61

62
const getAttrsEndpoint = hasReporting => (hasReporting ? `${reportingApiUrl}/devices/search/attributes` : `${inventoryApiUrlV2}/filters/attributes`);
185✔
63

64
export const getGroups = () => (dispatch, getState) =>
185✔
65
  GeneralApi.get(`${inventoryApiUrl}/groups`).then(res => {
27✔
66
    const state = getState().devices.groups.byId;
27✔
67
    const dynamicGroups = Object.entries(state).reduce((accu, [id, group]) => {
27✔
68
      if (group.id || (group.filters?.length && id !== UNGROUPED_GROUP.id)) {
51✔
69
        accu[id] = group;
25✔
70
      }
71
      return accu;
51✔
72
    }, {});
73
    const groups = res.data.reduce((accu, group) => {
27✔
74
      accu[group] = { deviceIds: [], filters: [], total: 0, ...state[group] };
27✔
75
      return accu;
27✔
76
    }, dynamicGroups);
77
    const filters = [{ key: 'group', value: res.data, operator: DEVICE_FILTERING_OPTIONS.$nin.key, scope: 'system' }];
27✔
78
    return Promise.all([
27✔
79
      dispatch({ type: DeviceConstants.RECEIVE_GROUPS, groups }),
80
      dispatch(getDevicesByStatus(undefined, { filterSelection: filters, group: 0, page: 1, perPage: 1 }))
81
    ]).then(promises => {
82
      const ungroupedDevices = promises[promises.length - 1] || [];
27!
83
      const result = ungroupedDevices[ungroupedDevices.length - 1] || {};
27!
84
      if (!result.total) {
27!
85
        return Promise.resolve();
×
86
      }
87
      return Promise.resolve(
27✔
88
        dispatch({
89
          type: DeviceConstants.ADD_DYNAMIC_GROUP,
90
          groupName: UNGROUPED_GROUP.id,
91
          group: {
92
            deviceIds: [],
93
            total: 0,
94
            ...getState().devices.groups.byId[UNGROUPED_GROUP.id],
95
            filters: [{ key: 'group', value: res.data, operator: DEVICE_FILTERING_OPTIONS.$nin.key, scope: 'system' }]
96
          }
97
        })
98
      );
99
    });
100
  });
101

102
export const addDevicesToGroup = (group, deviceIds, isCreation) => dispatch =>
185✔
103
  GeneralApi.patch(`${inventoryApiUrl}/groups/${group}/devices`, deviceIds)
2✔
104
    .then(() => dispatch({ type: DeviceConstants.ADD_TO_GROUP, group, deviceIds }))
2✔
105
    .finally(() => (isCreation ? Promise.resolve(dispatch(getGroups())) : {}));
2✔
106

107
export const removeDevicesFromGroup = (group, deviceIds) => dispatch =>
185✔
108
  GeneralApi.delete(`${inventoryApiUrl}/groups/${group}/devices`, deviceIds).then(() =>
1✔
109
    Promise.all([
1✔
110
      dispatch({
111
        type: DeviceConstants.REMOVE_FROM_GROUP,
112
        group,
113
        deviceIds
114
      }),
115
      dispatch(setSnackbar(`The ${pluralize('devices', deviceIds.length)} ${pluralize('were', deviceIds.length)} removed from the group`, TIMEOUTS.fiveSeconds))
116
    ])
117
  );
118

119
const getGroupNotification = (newGroup, selectedGroup) => {
185✔
120
  const successMessage = 'The group was updated successfully';
3✔
121
  if (newGroup === selectedGroup) {
3✔
122
    return [successMessage, TIMEOUTS.fiveSeconds];
1✔
123
  }
124
  return [
2✔
125
    <>
126
      {successMessage} - <Link to={`/devices?inventory=group:eq:${newGroup}`}>click here</Link> to see it.
127
    </>,
128
    5000,
129
    undefined,
130
    undefined,
131
    () => {}
132
  ];
133
};
134

135
export const addStaticGroup = (group, devices) => (dispatch, getState) =>
185✔
136
  Promise.resolve(
1✔
137
    dispatch(
138
      addDevicesToGroup(
139
        group,
140
        devices.map(({ id }) => id),
1✔
141
        true
142
      )
143
    )
144
  )
145
    .then(() =>
146
      Promise.resolve(
1✔
147
        dispatch({
148
          type: DeviceConstants.ADD_STATIC_GROUP,
149
          group: { deviceIds: [], total: 0, filters: [], ...getState().devices.groups.byId[group] },
150
          groupName: group
151
        })
152
      ).then(() =>
153
        Promise.all([
1✔
154
          dispatch(setDeviceListState({ selectedId: undefined, setOnly: true })),
155
          dispatch(getGroups()),
156
          dispatch(setSnackbar(...getGroupNotification(group, getState().devices.groups.selectedGroup)))
157
        ])
158
      )
159
    )
160
    .catch(err => commonErrorHandler(err, `Group could not be updated:`, dispatch));
×
161

162
export const removeStaticGroup = groupName => (dispatch, getState) => {
185✔
163
  return GeneralApi.delete(`${inventoryApiUrl}/groups/${groupName}`).then(() => {
1✔
164
    const selectedGroup = getState().devices.groups.selectedGroup === groupName ? undefined : getState().devices.groups.selectedGroup;
1!
165
    // eslint-disable-next-line no-unused-vars
166
    const { [groupName]: removal, ...groups } = getState().devices.groups.byId;
1✔
167
    return Promise.all([
1✔
168
      dispatch({
169
        type: DeviceConstants.REMOVE_STATIC_GROUP,
170
        groups
171
      }),
172
      dispatch(getGroups()),
173
      dispatch(selectGroup(selectedGroup)),
174
      dispatch(setSnackbar('Group was removed successfully', TIMEOUTS.fiveSeconds))
175
    ]);
176
  });
177
};
178

179
// for some reason these functions can not be stored in the deviceConstants...
180
const filterProcessors = {
185✔
181
  $gt: val => Number(val) || val,
×
182
  $gte: val => Number(val) || val,
×
183
  $lt: val => Number(val) || val,
5✔
184
  $lte: val => Number(val) || val,
×
185
  $in: val => ('' + val).split(',').map(i => i.trim()),
×
186
  $nin: val => ('' + val).split(',').map(i => i.trim()),
28✔
187
  $exists: yes,
188
  $nexists: () => false
×
189
};
190
const filterAliases = {
185✔
191
  $nexists: { alias: DEVICE_FILTERING_OPTIONS.$exists.key, value: false }
192
};
193
const mapFiltersToTerms = filters =>
185✔
194
  filters.map(filter => ({
497✔
195
    scope: filter.scope,
196
    attribute: filter.key,
197
    type: filterAliases[filter.operator]?.alias || filter.operator,
994✔
198
    value: filterProcessors.hasOwnProperty(filter.operator) ? filterProcessors[filter.operator](filter.value) : filter.value
497✔
199
  }));
200
const mapTermsToFilters = terms =>
185✔
201
  terms.map(term => {
23✔
202
    const aliasedFilter = Object.entries(filterAliases).find(
69✔
203
      aliasDefinition => aliasDefinition[1].alias === term.type && aliasDefinition[1].value === term.value
69✔
204
    );
205
    const operator = aliasedFilter ? aliasedFilter[0] : term.type;
69✔
206
    return { scope: term.scope, key: term.attribute, operator, value: term.value };
69✔
207
  });
208

209
export const getDynamicGroups = () => (dispatch, getState) =>
185✔
210
  GeneralApi.get(`${inventoryApiUrlV2}/filters?per_page=${MAX_PAGE_SIZE}`)
23✔
211
    .then(({ data: filters }) => {
212
      const state = getState().devices.groups.byId;
23✔
213
      const staticGroups = Object.entries(state).reduce((accu, [id, group]) => {
23✔
214
        if (!(group.id || group.filters?.length)) {
44✔
215
          accu[id] = group;
23✔
216
        }
217
        return accu;
44✔
218
      }, {});
219
      const groups = (filters || []).reduce((accu, filter) => {
23!
220
        accu[filter.name] = {
23✔
221
          deviceIds: [],
222
          total: 0,
223
          ...state[filter.name],
224
          id: filter.id,
225
          filters: mapTermsToFilters(filter.terms)
226
        };
227
        return accu;
23✔
228
      }, staticGroups);
229
      return Promise.resolve(dispatch({ type: DeviceConstants.RECEIVE_DYNAMIC_GROUPS, groups }));
23✔
230
    })
231
    .catch(() => console.log('Dynamic group retrieval failed - likely accessing a non-enterprise backend'));
×
232

233
export const addDynamicGroup = (groupName, filterPredicates) => (dispatch, getState) =>
185✔
234
  GeneralApi.post(`${inventoryApiUrlV2}/filters`, { name: groupName, terms: mapFiltersToTerms(filterPredicates) })
2✔
235
    .then(res =>
236
      Promise.resolve(
2✔
237
        dispatch({
238
          type: DeviceConstants.ADD_DYNAMIC_GROUP,
239
          groupName,
240
          group: {
241
            deviceIds: [],
242
            total: 0,
243
            ...getState().devices.groups.byId[groupName],
244
            id: res.headers[headerNames.location].substring(res.headers[headerNames.location].lastIndexOf('/') + 1),
245
            filters: filterPredicates
246
          }
247
        })
248
      ).then(() => {
249
        const { cleanedFilters } = getGroupFilters(groupName, getState().devices.groups);
2✔
250
        return Promise.all([
2✔
251
          dispatch(setDeviceFilters(cleanedFilters)),
252
          dispatch(setSnackbar(...getGroupNotification(groupName, getState().devices.groups.selectedGroup))),
253
          dispatch(getDynamicGroups())
254
        ]);
255
      })
256
    )
257
    .catch(err => commonErrorHandler(err, `Group could not be updated:`, dispatch));
×
258

259
export const updateDynamicGroup = (groupName, filterPredicates) => (dispatch, getState) => {
185✔
260
  const filterId = getState().devices.groups.byId[groupName].id;
1✔
261
  return GeneralApi.delete(`${inventoryApiUrlV2}/filters/${filterId}`).then(() => Promise.resolve(dispatch(addDynamicGroup(groupName, filterPredicates))));
1✔
262
};
263

264
export const removeDynamicGroup = groupName => (dispatch, getState) => {
185✔
265
  let groups = { ...getState().devices.groups.byId };
1✔
266
  const filterId = groups[groupName].id;
1✔
267
  const selectedGroup = getState().devices.groups.selectedGroup === groupName ? undefined : getState().devices.groups.selectedGroup;
1!
268
  return Promise.all([GeneralApi.delete(`${inventoryApiUrlV2}/filters/${filterId}`), dispatch(selectGroup(selectedGroup))]).then(() => {
1✔
269
    delete groups[groupName];
1✔
270
    return Promise.all([
1✔
271
      dispatch({
272
        type: DeviceConstants.REMOVE_DYNAMIC_GROUP,
273
        groups
274
      }),
275
      dispatch(setSnackbar('Group was removed successfully', TIMEOUTS.fiveSeconds))
276
    ]);
277
  });
278
};
279
/*
280
 * Device inventory functions
281
 */
282
const getGroupFilters = (group, groupsState, filters = []) => {
185✔
283
  const groupName = group === UNGROUPED_GROUP.id || group === UNGROUPED_GROUP.name ? UNGROUPED_GROUP.id : group;
11!
284
  const selectedGroup = groupsState.byId[groupName];
11✔
285
  const groupFilterLength = selectedGroup?.filters?.length || 0;
11✔
286
  const cleanedFilters = groupFilterLength ? [...filters, ...selectedGroup.filters].filter(filtersFilter) : filters;
11✔
287
  return { cleanedFilters, groupName, selectedGroup, groupFilterLength };
11✔
288
};
289

290
export const selectGroup =
291
  (group, filters = []) =>
185✔
292
  (dispatch, getState) => {
5✔
293
    const { cleanedFilters, groupName, selectedGroup, groupFilterLength } = getGroupFilters(group, getState().devices.groups, filters);
5✔
294
    const state = getState();
5✔
295
    if (state.devices.groups.selectedGroup === groupName && ((filters.length === 0 && !groupFilterLength) || filters.length === cleanedFilters.length)) {
5!
296
      return Promise.resolve();
2✔
297
    }
298
    let tasks = [];
3✔
299
    if (groupFilterLength) {
3✔
300
      tasks.push(dispatch(setDeviceFilters(cleanedFilters)));
2✔
301
    } else {
302
      tasks.push(dispatch(setDeviceFilters(filters)));
1✔
303
      tasks.push(dispatch(getGroupDevices(groupName, { perPage: 1, shouldIncludeAllStates: true })));
1✔
304
    }
305
    const selectedGroupName = selectedGroup || !Object.keys(state.devices.groups.byId).length ? groupName : undefined;
3!
306
    tasks.push(dispatch({ type: DeviceConstants.SELECT_GROUP, group: selectedGroupName }));
3✔
307
    return Promise.all(tasks);
3✔
308
  };
309
const getEarliestTs = (dateA = '', dateB = '') => (!dateA || !dateB ? dateA || dateB : dateA < dateB ? dateA : dateB);
292!
310
const getLatestTs = (dateA = '', dateB = '') => (!dateA || !dateB ? dateA || dateB : dateA >= dateB ? dateA : dateB);
438✔
311

312
const reduceReceivedDevices = (devices, ids, state, status) =>
185✔
313
  devices.reduce(
143✔
314
    (accu, device) => {
315
      const stateDevice = getDeviceByIdSelector(state, device.id);
146✔
316
      const {
317
        attributes: storedAttributes = {},
2✔
318
        identity_data: storedIdentity = {},
2✔
319
        monitor: storedMonitor = {},
100✔
320
        tags: storedTags = {},
100✔
321
        group: storedGroup
322
      } = stateDevice;
146✔
323
      const { identity, inventory, monitor, system = {}, tags } = mapDeviceAttributes(device.attributes);
146!
324
      // all the other mapped attributes return as empty objects if there are no attributes to map, but identity will be initialized with an empty state
325
      // for device_type and artifact_name, potentially overwriting existing info, so rely on stored information instead if there are no attributes
326
      device.attributes = device.attributes ? { ...storedAttributes, ...inventory } : storedAttributes;
146✔
327
      device.tags = { ...storedTags, ...tags };
146✔
328
      device.group = system.group ?? storedGroup;
146✔
329
      device.monitor = { ...storedMonitor, ...monitor };
146✔
330
      device.identity_data = { ...storedIdentity, ...identity, ...(device.identity_data ? device.identity_data : {}) };
146✔
331
      device.status = status ? status : device.status || identity.status;
146✔
332
      device.created_ts = getEarliestTs(getEarliestTs(system.created_ts, device.created_ts), stateDevice.created_ts);
146✔
333
      device.updated_ts = getLatestTs(getLatestTs(getLatestTs(device.check_in_time, device.updated_ts), system.updated_ts), stateDevice.updated_ts);
146✔
334
      device.isNew = new Date(device.created_ts) > new Date(state.app.newThreshold);
146✔
335
      device.isOffline = new Date(device.updated_ts) < new Date(state.app.offlineThreshold);
146✔
336
      accu.devicesById[device.id] = { ...stateDevice, ...device };
146✔
337
      accu.ids.push(device.id);
146✔
338
      return accu;
146✔
339
    },
340
    { ids, devicesById: {} }
341
  );
342

343
export const getGroupDevices =
344
  (group, options = {}) =>
185✔
345
  (dispatch, getState) => {
4✔
346
    const { shouldIncludeAllStates, ...remainder } = options;
4✔
347
    const { cleanedFilters: filterSelection } = getGroupFilters(group, getState().devices.groups);
4✔
348
    return Promise.resolve(
4✔
349
      dispatch(getDevicesByStatus(shouldIncludeAllStates ? undefined : DEVICE_STATES.accepted, { ...remainder, filterSelection, group }))
4✔
350
    ).then(results => {
351
      if (!group) {
4✔
352
        return Promise.resolve();
2✔
353
      }
354
      const { deviceAccu, total } = results[results.length - 1];
2✔
355
      const stateGroup = getState().devices.groups.byId[group];
2✔
356
      if (!stateGroup && !total && !deviceAccu.ids.length) {
2!
357
        return Promise.resolve();
×
358
      }
359
      return Promise.resolve(
2✔
360
        dispatch({
361
          type: DeviceConstants.RECEIVE_GROUP_DEVICES,
362
          group: {
363
            filters: [],
364
            ...stateGroup,
365
            deviceIds: deviceAccu.ids.length === total || deviceAccu.ids.length > stateGroup?.deviceIds ? deviceAccu.ids : stateGroup.deviceIds,
6!
366
            total
367
          },
368
          groupName: group
369
        })
370
      );
371
    });
372
  };
373

374
export const getAllGroupDevices = (group, shouldIncludeAllStates) => (dispatch, getState) => {
185✔
375
  if (!group || (!!group && (!getState().devices.groups.byId[group] || getState().devices.groups.byId[group].filters.length))) {
13✔
376
    return Promise.resolve();
12✔
377
  }
378
  const { attributes, filterTerms } = prepareSearchArguments({
1✔
379
    filters: [],
380
    group,
381
    state: getState(),
382
    status: shouldIncludeAllStates ? undefined : DEVICE_STATES.accepted
1!
383
  });
384
  const getAllDevices = (perPage = MAX_PAGE_SIZE, page = defaultPage, devices = []) =>
1✔
385
    GeneralApi.post(getSearchEndpoint(getState().app.features.hasReporting), {
1✔
386
      page,
387
      per_page: perPage,
388
      filters: filterTerms,
389
      attributes
390
    }).then(res => {
391
      const state = getState();
1✔
392
      const deviceAccu = reduceReceivedDevices(res.data, devices, state);
1✔
393
      dispatch({
1✔
394
        type: DeviceConstants.RECEIVE_DEVICES,
395
        devicesById: deviceAccu.devicesById
396
      });
397
      const total = Number(res.headers[headerNames.total]);
1✔
398
      if (total > perPage * page) {
1!
399
        return getAllDevices(perPage, page + 1, deviceAccu.ids);
×
400
      }
401
      return Promise.resolve(
1✔
402
        dispatch({
403
          type: DeviceConstants.RECEIVE_GROUP_DEVICES,
404
          group: {
405
            filters: [],
406
            ...state.devices.groups.byId[group],
407
            deviceIds: deviceAccu.ids,
408
            total: deviceAccu.ids.length
409
          },
410
          groupName: group
411
        })
412
      );
413
    });
414
  return getAllDevices();
1✔
415
};
416

417
export const getAllDynamicGroupDevices = group => (dispatch, getState) => {
185✔
418
  if (!!group && (!getState().devices.groups.byId[group] || !getState().devices.groups.byId[group].filters.length)) {
13✔
419
    return Promise.resolve();
12✔
420
  }
421
  const { attributes, filterTerms: filters } = prepareSearchArguments({
1✔
422
    filters: getState().devices.groups.byId[group].filters,
423
    state: getState(),
424
    status: DEVICE_STATES.accepted
425
  });
426
  const getAllDevices = (perPage = MAX_PAGE_SIZE, page = defaultPage, devices = []) =>
1✔
427
    GeneralApi.post(getSearchEndpoint(getState().app.features.hasReporting), { page, per_page: perPage, filters, attributes }).then(res => {
1✔
428
      const state = getState();
1✔
429
      const deviceAccu = reduceReceivedDevices(res.data, devices, state);
1✔
430
      dispatch({
1✔
431
        type: DeviceConstants.RECEIVE_DEVICES,
432
        devicesById: deviceAccu.devicesById
433
      });
434
      const total = Number(res.headers[headerNames.total]);
1✔
435
      if (total > deviceAccu.ids.length) {
1!
436
        return getAllDevices(perPage, page + 1, deviceAccu.ids);
×
437
      }
438
      return Promise.resolve(
1✔
439
        dispatch({
440
          type: DeviceConstants.RECEIVE_GROUP_DEVICES,
441
          group: {
442
            ...state.devices.groups.byId[group],
443
            deviceIds: deviceAccu.ids,
444
            total
445
          },
446
          groupName: group
447
        })
448
      );
449
    });
450
  return getAllDevices();
1✔
451
};
452

453
export const setDeviceFilters = filters => (dispatch, getState) => {
185✔
454
  if (deepCompare(filters, getDeviceFilters(getState()))) {
6✔
455
    return Promise.resolve();
2✔
456
  }
457
  return Promise.resolve(dispatch({ type: DeviceConstants.SET_DEVICE_FILTERS, filters }));
4✔
458
};
459

460
export const getDeviceById = id => (dispatch, getState) =>
185✔
461
  GeneralApi.get(`${inventoryApiUrl}/devices/${id}`)
6✔
462
    .then(res => {
463
      const device = reduceReceivedDevices([res.data], [], getState()).devicesById[id];
5✔
464
      device.etag = res.headers.etag;
5✔
465
      dispatch({ type: DeviceConstants.RECEIVE_DEVICE, device });
5✔
466
      return Promise.resolve(device);
5✔
467
    })
468
    .catch(err => {
469
      const errMsg = extractErrorMessage(err);
×
470
      if (errMsg.includes('Not Found')) {
×
471
        console.log(`${id} does not have any inventory information`);
×
472
        const device = reduceReceivedDevices(
×
473
          [
474
            {
475
              id,
476
              attributes: [
477
                { name: 'status', value: 'decomissioned', scope: 'identity' },
478
                { name: 'decomissioned', value: 'true', scope: 'inventory' }
479
              ]
480
            }
481
          ],
482
          [],
483
          getState()
484
        ).devicesById[id];
485
        dispatch({ type: DeviceConstants.RECEIVE_DEVICE, device });
×
486
      }
487
    });
488

489
export const getDeviceInfo = deviceId => (dispatch, getState) => {
185✔
490
  const device = getState().devices.byId[deviceId] || {};
2!
491
  const { hasDeviceConfig, hasDeviceConnect, hasMonitor } = getTenantCapabilities(getState());
2✔
492
  const { canConfigure } = getUserCapabilities(getState());
2✔
493
  const integrations = getDeviceTwinIntegrations(getState());
2✔
494
  let tasks = [dispatch(getDeviceAuth(deviceId)), ...integrations.map(integration => dispatch(getDeviceTwin(deviceId, integration)))];
2✔
495
  if (hasDeviceConfig && canConfigure && [DEVICE_STATES.accepted, DEVICE_STATES.preauth].includes(device.status)) {
2✔
496
    tasks.push(dispatch(getDeviceConfig(deviceId)));
1✔
497
  }
498
  if (device.status === DEVICE_STATES.accepted) {
2!
499
    // Get full device identity details for single selected device
500
    tasks.push(dispatch(getDeviceById(deviceId)));
2✔
501
    if (hasDeviceConnect) {
2!
502
      tasks.push(dispatch(getDeviceConnect(deviceId)));
2✔
503
    }
504
    if (hasMonitor) {
2✔
505
      tasks.push(dispatch(getLatestDeviceAlerts(deviceId)));
1✔
506
      tasks.push(dispatch(getDeviceMonitorConfig(deviceId)));
1✔
507
    }
508
  }
509
  return Promise.all(tasks);
2✔
510
};
511

512
const deriveInactiveDevices = deviceIds => (dispatch, getState) => {
185✔
513
  const yesterday = new Date();
1✔
514
  yesterday.setDate(yesterday.getDate() - 1);
1✔
515
  const yesterdaysIsoString = yesterday.toISOString();
1✔
516
  const state = getState().devices;
1✔
517
  // now boil the list down to the ones that were not updated since yesterday
518
  const devices = deviceIds.reduce(
1✔
519
    (accu, id) => {
520
      const device = state.byId[id];
2✔
521
      if (device && device.updated_ts > yesterdaysIsoString) {
2!
522
        accu.active.push(id);
×
523
      } else {
524
        accu.inactive.push(id);
2✔
525
      }
526
      return accu;
2✔
527
    },
528
    { active: [], inactive: [] }
529
  );
530
  return dispatch({
1✔
531
    type: DeviceConstants.SET_INACTIVE_DEVICES,
532
    activeDeviceTotal: devices.active.length,
533
    inactiveDeviceTotal: devices.inactive.length
534
  });
535
};
536

537
/*
538
    Device Auth + admission
539
  */
540
export const getDeviceCount = status => (dispatch, getState) =>
398✔
541
  GeneralApi.post(getSearchEndpoint(getState().app.features.hasReporting), {
398✔
542
    page: 1,
543
    per_page: 1,
544
    filters: mapFiltersToTerms([{ key: 'status', value: status, operator: DEVICE_FILTERING_OPTIONS.$eq.key, scope: 'identity' }]),
545
    attributes: defaultAttributes
546
  }).then(response => {
547
    const count = Number(response.headers[headerNames.total]);
394✔
548
    switch (status) {
394!
549
      case DEVICE_STATES.accepted:
550
      case DEVICE_STATES.pending:
551
      case DEVICE_STATES.preauth:
552
      case DEVICE_STATES.rejected:
553
        return dispatch({ type: DeviceConstants[`SET_${status.toUpperCase()}_DEVICES_COUNT`], count, status });
394✔
554
      default:
555
        return dispatch({ type: DeviceConstants.SET_TOTAL_DEVICES, count });
×
556
    }
557
  });
558

559
export const getAllDeviceCounts = () => dispatch =>
185✔
560
  Promise.all([DEVICE_STATES.accepted, DEVICE_STATES.pending].map(status => dispatch(getDeviceCount(status))));
362✔
561

562
export const getDeviceLimit = () => dispatch =>
185✔
563
  GeneralApi.get(`${deviceAuthV2}/limits/max_devices`).then(res =>
7✔
564
    dispatch({
7✔
565
      type: DeviceConstants.SET_DEVICE_LIMIT,
566
      limit: res.data.limit
567
    })
568
  );
569

570
export const setDeviceListState =
571
  (selectionState, shouldSelectDevices = true, forceRefresh) =>
185✔
572
  (dispatch, getState) => {
16✔
573
    const currentState = getState().devices.deviceList;
16✔
574
    const refreshTrigger = forceRefresh ? !currentState.refreshTrigger : selectionState.refreshTrigger;
16!
575
    let nextState = {
16✔
576
      ...currentState,
577
      setOnly: false,
578
      refreshTrigger,
579
      ...selectionState,
580
      sort: { ...currentState.sort, ...selectionState.sort }
581
    };
582
    let tasks = [];
16✔
583
    // eslint-disable-next-line no-unused-vars
584
    const { isLoading: currentLoading, deviceIds: currentDevices, selection: currentSelection, ...currentRequestState } = currentState;
16✔
585
    // eslint-disable-next-line no-unused-vars
586
    const { isLoading: nextLoading, deviceIds: nextDevices, selection: nextSelection, ...nextRequestState } = nextState;
16✔
587
    if (!nextState.setOnly && !deepCompare(currentRequestState, nextRequestState)) {
16✔
588
      const { direction: sortDown = SORTING_OPTIONS.desc, key: sortCol, scope: sortScope } = nextState.sort ?? {};
13!
589
      const sortBy = sortCol ? [{ attribute: sortCol, order: sortDown, scope: sortScope }] : undefined;
13!
590
      if (sortCol && sortingAlternatives[sortCol]) {
13!
591
        sortBy.push({ ...sortBy[0], attribute: sortingAlternatives[sortCol] });
×
592
      }
593
      const applicableSelectedState = nextState.state === routes.allDevices.key ? undefined : nextState.state;
13!
594
      nextState.isLoading = true;
13✔
595
      tasks.push(
13✔
596
        dispatch(getDevicesByStatus(applicableSelectedState, { ...nextState, sortOptions: sortBy }))
597
          .then(results => {
598
            const { deviceAccu, total } = results[results.length - 1];
11✔
599
            const devicesState = shouldSelectDevices
11!
600
              ? { ...getState().devices.deviceList, deviceIds: deviceAccu.ids, total, isLoading: false }
601
              : { ...getState().devices.deviceList, isLoading: false };
602
            return Promise.resolve(dispatch({ type: DeviceConstants.SET_DEVICE_LIST_STATE, state: devicesState }));
11✔
603
          })
604
          // whatever happens, change "loading" back to null
605
          .catch(() =>
606
            Promise.resolve(dispatch({ type: DeviceConstants.SET_DEVICE_LIST_STATE, state: { ...getState().devices.deviceList, isLoading: false } }))
×
607
          )
608
      );
609
    }
610
    tasks.push(dispatch({ type: DeviceConstants.SET_DEVICE_LIST_STATE, state: nextState }));
16✔
611
    return Promise.all(tasks);
16✔
612
  };
613

614
const convertIssueOptionsToFilters = (issuesSelection, filtersState = {}) =>
185!
615
  issuesSelection.map(item => {
85✔
616
    if (typeof DeviceConstants.DEVICE_ISSUE_OPTIONS[item].filterRule.value === 'function') {
11✔
617
      return { ...DeviceConstants.DEVICE_ISSUE_OPTIONS[item].filterRule, value: DeviceConstants.DEVICE_ISSUE_OPTIONS[item].filterRule.value(filtersState) };
5✔
618
    }
619
    return DeviceConstants.DEVICE_ISSUE_OPTIONS[item].filterRule;
6✔
620
  });
621

622
export const convertDeviceListStateToFilters = ({ filters = [], group, groups = { byId: {} }, offlineThreshold, selectedIssues = [], status }) => {
185!
623
  let applicableFilters = [...filters];
85✔
624
  if (typeof group === 'string' && !(groups.byId[group]?.filters || applicableFilters).length) {
85✔
625
    applicableFilters.push({ key: 'group', value: group, operator: DEVICE_FILTERING_OPTIONS.$eq.key, scope: 'system' });
4✔
626
  }
627
  const nonMonitorFilters = applicableFilters.filter(
85✔
628
    filter =>
629
      !Object.values(DeviceConstants.DEVICE_ISSUE_OPTIONS).some(
40✔
630
        ({ filterRule }) => filter.scope !== 'inventory' && filterRule.scope === filter.scope && filterRule.key === filter.key
240✔
631
      )
632
  );
633
  const deviceIssueFilters = convertIssueOptionsToFilters(selectedIssues, { offlineThreshold });
85✔
634
  applicableFilters = [...nonMonitorFilters, ...deviceIssueFilters];
85✔
635
  const effectiveFilters = status
85✔
636
    ? [...applicableFilters, { key: 'status', value: status, operator: DEVICE_FILTERING_OPTIONS.$eq.key, scope: 'identity' }]
637
    : applicableFilters;
638
  return { applicableFilters: nonMonitorFilters, filterTerms: mapFiltersToTerms(effectiveFilters) };
85✔
639
};
640

641
// get devices from inventory
642
export const getDevicesByStatus =
643
  (status, options = {}) =>
185✔
644
  (dispatch, getState) => {
71✔
645
    const { filterSelection, group, selectedIssues = [], page = defaultPage, perPage = defaultPerPage, sortOptions = [], selectedAttributes = [] } = options;
71✔
646
    const { applicableFilters, filterTerms } = convertDeviceListStateToFilters({
71✔
647
      filters: filterSelection ?? getDeviceFilters(getState()),
111✔
648
      group: group ?? getState().devices.groups.selectedGroup,
113✔
649
      groups: getState().devices.groups,
650
      offlineThreshold: getState().app.offlineThreshold,
651
      selectedIssues,
652
      status
653
    });
654
    const attributes = [...defaultAttributes, { scope: 'identity', attribute: getIdAttribute(getState()).attribute || 'id' }, ...selectedAttributes];
71!
655
    return GeneralApi.post(getSearchEndpoint(getState().app.features.hasReporting), {
71✔
656
      page,
657
      per_page: perPage,
658
      filters: filterTerms,
659
      sort: sortOptions,
660
      attributes
661
    })
662
      .then(response => {
663
        const state = getState();
69✔
664
        const deviceAccu = reduceReceivedDevices(response.data, [], state, status);
69✔
665
        let total = !applicableFilters.length ? Number(response.headers[headerNames.total]) : null;
69✔
666
        if (status && state.devices.byStatus[status].total === deviceAccu.ids.length) {
69✔
667
          total = deviceAccu.ids.length;
36✔
668
        }
669
        let tasks = [
69✔
670
          dispatch({
671
            type: DeviceConstants.RECEIVE_DEVICES,
672
            devicesById: deviceAccu.devicesById
673
          })
674
        ];
675
        if (status) {
69✔
676
          tasks.push(
41✔
677
            dispatch({
678
              type: DeviceConstants[`SET_${status.toUpperCase()}_DEVICES`],
679
              deviceIds: deviceAccu.ids,
680
              status,
681
              total
682
            })
683
          );
684
        }
685
        // for each device, get device identity info
686
        const receivedDevices = Object.values(deviceAccu.devicesById);
69✔
687
        if (receivedDevices.length) {
69✔
688
          tasks.push(dispatch(getDevicesWithAuth(receivedDevices)));
57✔
689
        }
690
        tasks.push(Promise.resolve({ deviceAccu, total: Number(response.headers[headerNames.total]) }));
69✔
691
        return Promise.all(tasks);
69✔
692
      })
693
      .catch(err => commonErrorHandler(err, `${status} devices couldn't be loaded.`, dispatch, commonErrorFallback));
×
694
  };
695

696
export const getAllDevicesByStatus = status => (dispatch, getState) => {
185✔
697
  const attributes = [...defaultAttributes, { scope: 'identity', attribute: getIdAttribute(getState()).attribute || 'id' }];
1!
698
  const getAllDevices = (perPage = MAX_PAGE_SIZE, page = 1, devices = []) =>
1✔
699
    GeneralApi.post(getSearchEndpoint(getState().app.features.hasReporting), {
1✔
700
      page,
701
      per_page: perPage,
702
      filters: mapFiltersToTerms([{ key: 'status', value: status, operator: DEVICE_FILTERING_OPTIONS.$eq.key, scope: 'identity' }]),
703
      attributes
704
    }).then(res => {
705
      const state = getState();
1✔
706
      const deviceAccu = reduceReceivedDevices(res.data, devices, state, status);
1✔
707
      dispatch({
1✔
708
        type: DeviceConstants.RECEIVE_DEVICES,
709
        devicesById: deviceAccu.devicesById
710
      });
711
      const total = Number(res.headers[headerNames.total]);
1✔
712
      if (total > state.deployments.deploymentDeviceLimit) {
1!
713
        return Promise.resolve();
×
714
      }
715
      if (total > perPage * page) {
1!
716
        return getAllDevices(perPage, page + 1, deviceAccu.ids);
×
717
      }
718
      let tasks = [
1✔
719
        dispatch({
720
          type: DeviceConstants[`SET_${status.toUpperCase()}_DEVICES`],
721
          deviceIds: deviceAccu.ids,
722
          forceUpdate: true,
723
          status,
724
          total: deviceAccu.ids.length
725
        })
726
      ];
727
      if (status === DEVICE_STATES.accepted && deviceAccu.ids.length === total) {
1!
728
        tasks.push(dispatch(deriveInactiveDevices(deviceAccu.ids)));
1✔
729
      }
730
      return Promise.all(tasks);
1✔
731
    });
732
  return getAllDevices();
1✔
733
};
734

735
export const searchDevices =
736
  (passedOptions = {}) =>
185!
737
  (dispatch, getState) => {
2✔
738
    const state = getState();
2✔
739
    let options = { ...state.app.searchState, ...passedOptions };
2✔
740
    const { page = defaultPage, searchTerm, sortOptions = [] } = options;
2✔
741
    const { columnSelection = [] } = getUserSettings(state);
2!
742
    const selectedAttributes = columnSelection.map(column => ({ attribute: column.key, scope: column.scope }));
2✔
743
    const attributes = attributeDuplicateFilter(
2✔
744
      [...defaultAttributes, { scope: 'identity', attribute: getIdAttribute(state).attribute }, ...selectedAttributes],
745
      'attribute'
746
    );
747
    return GeneralApi.post(getSearchEndpoint(state.app.features.hasReporting), {
2✔
748
      page,
749
      per_page: 10,
750
      filters: [],
751
      sort: sortOptions,
752
      text: searchTerm,
753
      attributes
754
    })
755
      .then(response => {
756
        const deviceAccu = reduceReceivedDevices(response.data, [], getState());
2✔
757
        return Promise.all([
2✔
758
          dispatch({ type: DeviceConstants.RECEIVE_DEVICES, devicesById: deviceAccu.devicesById }),
759
          Promise.resolve({ deviceIds: deviceAccu.ids, searchTotal: Number(response.headers[headerNames.total]) })
760
        ]);
761
      })
762
      .catch(err => commonErrorHandler(err, `devices couldn't be searched.`, dispatch, commonErrorFallback));
×
763
  };
764

765
const ATTRIBUTE_LIST_CUTOFF = 100;
185✔
766
const attributeReducer = (attributes = []) =>
185!
767
  attributes.slice(0, ATTRIBUTE_LIST_CUTOFF).reduce(
18✔
768
    (accu, { name, scope }) => {
769
      if (!accu[scope]) {
360!
770
        accu[scope] = [];
×
771
      }
772
      accu[scope].push(name);
360✔
773
      return accu;
360✔
774
    },
775
    { identity: [], inventory: [], system: [], tags: [] }
776
  );
777

778
export const getDeviceAttributes = () => (dispatch, getState) =>
185✔
779
  GeneralApi.get(getAttrsEndpoint(getState().app.features.hasReporting)).then(({ data }) => {
19✔
780
    // TODO: remove the array fallback once the inventory attributes endpoint is fixed
781
    const { identity: identityAttributes, inventory: inventoryAttributes, system: systemAttributes, tags: tagAttributes } = attributeReducer(data || []);
17!
782
    return dispatch({
17✔
783
      type: DeviceConstants.SET_FILTER_ATTRIBUTES,
784
      attributes: { identityAttributes, inventoryAttributes, systemAttributes, tagAttributes }
785
    });
786
  });
787

788
export const getReportingLimits = () => dispatch =>
185✔
789
  GeneralApi.get(`${reportingApiUrl}/devices/attributes`)
2✔
790
    .catch(err => commonErrorHandler(err, `filterable attributes limit & usage could not be retrieved.`, dispatch, commonErrorFallback))
×
791
    .then(({ data }) => {
792
      const { attributes, count, limit } = data;
1✔
793
      const groupedAttributes = attributeReducer(attributes);
1✔
794
      return Promise.resolve(dispatch({ type: DeviceConstants.SET_FILTERABLES_CONFIG, count, limit, attributes: groupedAttributes }));
1✔
795
    });
796

797
export const ensureVersionString = (software, fallback) =>
185✔
798
  software.length && software !== 'artifact_name' ? (software.endsWith('.version') ? software : `${software}.version`) : fallback;
1!
799

800
const getSingleReportData = (reportConfig, groups) => {
185✔
801
  const { attribute, group, software = '' } = reportConfig;
1!
802
  const filters = [{ key: 'status', scope: 'identity', operator: DEVICE_FILTERING_OPTIONS.$eq.key, value: 'accepted' }];
1✔
803
  if (group) {
1!
804
    const staticGroupFilter = { key: 'group', scope: 'system', operator: DEVICE_FILTERING_OPTIONS.$eq.key, value: group };
×
805
    const { cleanedFilters: groupFilters } = getGroupFilters(group, groups);
×
806
    filters.push(...(groupFilters.length ? groupFilters : [staticGroupFilter]));
×
807
  }
808
  const aggregationAttribute = ensureVersionString(software, attribute);
1✔
809
  return GeneralApi.post(`${reportingApiUrl}/devices/aggregate`, {
1✔
810
    aggregations: [{ attribute: aggregationAttribute, name: '*', scope: 'inventory', size: chartColorPalette.length }],
811
    filters: mapFiltersToTerms(filters)
812
  }).then(({ data }) => ({ data, reportConfig }));
1✔
813
};
814

815
export const defaultReportType = 'distribution';
185✔
816
export const defaultReports = [{ ...emptyChartSelection, group: null, attribute: 'artifact_name', type: defaultReportType }];
185✔
817

818
export const getReportsData = () => (dispatch, getState) => {
185✔
819
  const state = getState();
1✔
820
  const reports =
821
    getUserSettings(state).reports ||
1✔
822
    state.users.globalSettings[`${state.users.currentUser}-reports`] ||
823
    (Object.keys(state.devices.byId).length ? defaultReports : []);
1!
824
  return Promise.all(reports.map(report => getSingleReportData(report, getState().devices.groups))).then(results => {
1✔
825
    const devicesState = getState().devices;
1✔
826
    const totalDeviceCount = devicesState.byStatus.accepted.total;
1✔
827
    const newReports = results.map(({ data, reportConfig }) => {
1✔
828
      let { items, other_count } = data[0];
1✔
829
      const { attribute, group, software = '' } = reportConfig;
1!
830
      const dataCount = items.reduce((accu, item) => accu + item.count, 0);
2✔
831
      // the following is needed to show reports including both old (artifact_name) & current style (rootfs-image.version) device software
832
      const otherCount = !group && (software === rootfsImageVersion || attribute === 'artifact_name') ? totalDeviceCount - dataCount : other_count;
1!
833
      return { items, otherCount, total: otherCount + dataCount };
1✔
834
    });
835
    return Promise.resolve(dispatch({ type: DeviceConstants.SET_DEVICE_REPORTS, reports: newReports }));
1✔
836
  });
837
};
838

839
const initializeDistributionData = (report, groups, devices, totalDeviceCount) => {
185✔
840
  const { attribute, group = '', software = '' } = report;
12!
841
  const effectiveAttribute = software ? software : attribute;
12!
842
  const { deviceIds, total = 0 } = groups[group] || {};
12✔
843
  const relevantDevices = groups[group] ? deviceIds.map(id => devices[id]) : Object.values(devices);
12!
844
  const distributionByAttribute = relevantDevices.reduce((accu, item) => {
12✔
845
    if (!item.attributes || item.status !== DEVICE_STATES.accepted) return accu;
28✔
846
    if (!accu[item.attributes[effectiveAttribute]]) {
20!
847
      accu[item.attributes[effectiveAttribute]] = 0;
20✔
848
    }
849
    accu[item.attributes[effectiveAttribute]] = accu[item.attributes[effectiveAttribute]] + 1;
20✔
850
    return accu;
20✔
851
  }, {});
852
  const distributionByAttributeSorted = Object.entries(distributionByAttribute).sort((pairA, pairB) => pairB[1] - pairA[1]);
12✔
853
  const items = distributionByAttributeSorted.map(([key, count]) => ({ key, count }));
20✔
854
  const dataCount = items.reduce((accu, item) => accu + item.count, 0);
20✔
855
  // the following is needed to show reports including both old (artifact_name) & current style (rootfs-image.version) device software
856
  const otherCount = (groups[group] ? total : totalDeviceCount) - dataCount;
12!
857
  return { items, otherCount, total: otherCount + dataCount };
12✔
858
};
859

860
export const deriveReportsData = () => (dispatch, getState) =>
185✔
861
  Promise.all([dispatch(getGroups()), dispatch(getDynamicGroups())]).then(() => {
12✔
862
    const { dynamic: dynamicGroups, static: staticGroups } = getGroupsSelector(getState());
12✔
863
    return Promise.all([
12✔
864
      ...staticGroups.map(group => dispatch(getAllGroupDevices(group))),
12✔
865
      ...dynamicGroups.map(group => dispatch(getAllDynamicGroupDevices(group)))
12✔
866
    ]).then(() => {
867
      const state = getState();
12✔
868
      const {
869
        groups: { byId: groupsById },
870
        byId,
871
        byStatus: {
872
          accepted: { total }
873
        }
874
      } = state.devices;
12✔
875
      const reports =
876
        getUserSettings(state).reports || state.users.globalSettings[`${state.users.currentUser}-reports`] || (Object.keys(byId).length ? defaultReports : []);
12!
877
      const newReports = reports.map(report => initializeDistributionData(report, groupsById, byId, total));
12✔
878
      return Promise.resolve(dispatch({ type: DeviceConstants.SET_DEVICE_REPORTS, reports: newReports }));
12✔
879
    });
880
  });
881

882
export const getDeviceConnect = id => dispatch =>
185✔
883
  GeneralApi.get(`${deviceConnect}/devices/${id}`).then(({ data }) => {
2✔
884
    let tasks = [
1✔
885
      dispatch({
886
        type: DeviceConstants.RECEIVE_DEVICE_CONNECT,
887
        device: { connect_status: data.status, connect_updated_ts: data.updated_ts, id }
888
      })
889
    ];
890
    tasks.push(Promise.resolve(data));
1✔
891
    return Promise.all(tasks);
1✔
892
  });
893

894
export const getSessionDetails = (sessionId, deviceId, userId, startDate, endDate) => () => {
185✔
895
  const createdAfter = startDate ? `&created_after=${Math.round(Date.parse(startDate) / 1000)}` : '';
5✔
896
  const createdBefore = endDate ? `&created_before=${Math.round(Date.parse(endDate) / 1000)}` : '';
5✔
897
  const objectSearch = `&object_id=${deviceId}`;
5✔
898
  return GeneralApi.get(`${auditLogsApiUrl}/logs?per_page=500${createdAfter}${createdBefore}&actor_id=${userId}${objectSearch}`).then(
5✔
899
    ({ data: auditLogEntries }) => {
900
      const { start, end } = auditLogEntries.reduce(
4✔
901
        (accu, item) => {
902
          if (item.meta?.session_id?.includes(sessionId)) {
4!
903
            accu.start = new Date(item.action.startsWith('open') ? item.time : accu.start);
4!
904
            accu.end = new Date(item.action.startsWith('close') ? item.time : accu.end);
4!
905
          }
906
          return accu;
4✔
907
        },
908
        { start: startDate || endDate, end: endDate || startDate }
12✔
909
      );
910
      return Promise.resolve({ start, end });
4✔
911
    }
912
  );
913
};
914

915
export const getDeviceFileDownloadLink = (deviceId, path) => () =>
185✔
916
  Promise.resolve(`${deviceConnect}/devices/${deviceId}/download?path=${encodeURIComponent(path)}`);
1✔
917

918
export const deviceFileUpload = (deviceId, path, file) => (dispatch, getState) => {
185✔
919
  var formData = new FormData();
1✔
920
  formData.append('path', path);
1✔
921
  formData.append('file', file);
1✔
922
  const uploadId = uuid();
1✔
923
  const cancelSource = new AbortController();
1✔
924
  const uploads = { ...getState().app.uploads, [uploadId]: { inprogress: true, uploadProgress: 0, cancelSource } };
1✔
925
  return Promise.all([
1✔
926
    dispatch(setSnackbar('Uploading file')),
927
    dispatch({ type: UPLOAD_PROGRESS, uploads }),
928
    GeneralApi.uploadPut(`${deviceConnect}/devices/${deviceId}/upload`, formData, e => dispatch(progress(e, uploadId)), cancelSource.signal)
×
929
  ])
930
    .then(() => Promise.resolve(dispatch(setSnackbar('Upload successful', TIMEOUTS.fiveSeconds))))
1✔
931
    .catch(err => {
932
      if (isCancel(err)) {
×
933
        return dispatch(setSnackbar('The upload has been cancelled', TIMEOUTS.fiveSeconds));
×
934
      }
935
      return commonErrorHandler(err, `Error uploading file to device.`, dispatch);
×
936
    })
937
    .finally(() => dispatch(cleanUpUpload(uploadId)));
1✔
938
};
939

940
export const getDeviceAuth = id => dispatch =>
185✔
941
  Promise.resolve(dispatch(getDevicesWithAuth([{ id }]))).then(results => {
6✔
942
    if (results[results.length - 1]) {
5!
943
      return Promise.resolve(results[results.length - 1][0]);
5✔
944
    }
945
    return Promise.resolve();
×
946
  });
947

948
export const getDevicesWithAuth = devices => (dispatch, getState) =>
185✔
949
  devices.length
65✔
950
    ? GeneralApi.get(`${deviceAuthV2}/devices?id=${devices.map(device => device.id).join('&id=')}`)
65✔
951
        .then(({ data: receivedDevices }) => {
952
          const { devicesById } = reduceReceivedDevices(receivedDevices, [], getState());
62✔
953
          return Promise.all([dispatch({ type: DeviceConstants.RECEIVE_DEVICES, devicesById }), Promise.resolve(receivedDevices)]);
62✔
954
        })
955
        .catch(err => commonErrorHandler(err, `Error: ${err}`, dispatch))
×
956
    : Promise.resolve([[], []]);
957

958
const maybeUpdateDevicesByStatus = (deviceId, authId) => (dispatch, getState) => {
185✔
959
  const devicesState = getState().devices;
4✔
960
  const device = devicesState.byId[deviceId];
4✔
961
  const hasMultipleAuthSets = authId ? device.auth_sets.filter(authset => authset.id !== authId).length > 0 : false;
4✔
962
  if (!hasMultipleAuthSets && Object.values(DEVICE_STATES).includes(device.status)) {
4!
963
    const deviceIds = devicesState.byStatus[device.status].deviceIds.filter(id => id !== deviceId);
8✔
964
    return Promise.resolve(
4✔
965
      dispatch({
966
        type: DeviceConstants[`SET_${device.status.toUpperCase()}_DEVICES`],
967
        deviceIds,
968
        forceUpdate: true,
969
        status: device.status,
970
        total: Math.max(0, devicesState.byStatus[device.status].total - 1)
971
      })
972
    );
973
  }
974
  return Promise.resolve();
×
975
};
976

977
export const updateDeviceAuth = (deviceId, authId, status) => (dispatch, getState) =>
185✔
978
  GeneralApi.put(`${deviceAuthV2}/devices/${deviceId}/auth/${authId}/status`, { status })
2✔
979
    .then(() => Promise.all([dispatch(getDeviceAuth(deviceId)), dispatch(setSnackbar('Device authorization status was updated successfully'))]))
2✔
980
    .catch(err => commonErrorHandler(err, 'There was a problem updating the device authorization status:', dispatch))
×
981
    .then(() => Promise.resolve(dispatch(maybeUpdateDevicesByStatus(deviceId, authId))))
2✔
982
    .finally(() => dispatch(setDeviceListState({ refreshTrigger: !getState().devices.deviceList.refreshTrigger })));
2✔
983

984
export const updateDevicesAuth = (deviceIds, status) => (dispatch, getState) => {
185✔
985
  let devices = getState().devices.byId;
1✔
986
  const deviceIdsWithoutAuth = deviceIds.reduce((accu, id) => (devices[id].auth_sets ? accu : [...accu, { id }]), []);
2!
987
  return dispatch(getDevicesWithAuth(deviceIdsWithoutAuth)).then(() => {
1✔
988
    devices = getState().devices.byId;
1✔
989
    // for each device, get id and id of authset & make api call to accept
990
    // if >1 authset, skip instead
991
    const deviceAuthUpdates = deviceIds.map(id => {
1✔
992
      const device = devices[id];
2✔
993
      if (device.auth_sets.length !== 1) {
2✔
994
        return Promise.reject();
1✔
995
      }
996
      // api call device.id and device.authsets[0].id
997
      return dispatch(updateDeviceAuth(device.id, device.auth_sets[0].id, status)).catch(err =>
1✔
998
        commonErrorHandler(err, 'The action was stopped as there was a problem updating a device authorization status: ', dispatch)
×
999
      );
1000
    });
1001
    return Promise.allSettled(deviceAuthUpdates).then(results => {
1✔
1002
      const { skipped, count } = results.reduce(
1✔
1003
        (accu, item) => {
1004
          if (item.status === 'rejected') {
2✔
1005
            accu.skipped = accu.skipped + 1;
1✔
1006
          } else {
1007
            accu.count = accu.count + 1;
1✔
1008
          }
1009
          return accu;
2✔
1010
        },
1011
        { skipped: 0, count: 0 }
1012
      );
1013
      const message = getSnackbarMessage(skipped, count);
1✔
1014
      // break if an error occurs, display status up til this point before error message
1015
      return dispatch(setSnackbar(message));
1✔
1016
    });
1017
  });
1018
};
1019

1020
export const deleteAuthset = (deviceId, authId) => (dispatch, getState) =>
185✔
1021
  GeneralApi.delete(`${deviceAuthV2}/devices/${deviceId}/auth/${authId}`)
1✔
1022
    .then(() => Promise.all([dispatch(setSnackbar('Device authorization status was updated successfully'))]))
1✔
1023
    .catch(err => commonErrorHandler(err, 'There was a problem updating the device authorization status:', dispatch))
×
1024
    .then(() => Promise.resolve(dispatch(maybeUpdateDevicesByStatus(deviceId, authId))))
1✔
1025
    .finally(() => dispatch(setDeviceListState({ refreshTrigger: !getState().devices.deviceList.refreshTrigger })));
1✔
1026

1027
export const preauthDevice = authset => dispatch =>
185✔
1028
  GeneralApi.post(`${deviceAuthV2}/devices`, authset)
4✔
1029
    .catch(err => {
1030
      if (err.response.status === 409) {
1!
1031
        return Promise.reject('A device with a matching identity data set already exists');
1✔
1032
      }
1033
      commonErrorHandler(err, 'The device could not be added:', dispatch);
×
1034
      return Promise.reject();
×
1035
    })
1036
    .then(() => Promise.resolve(dispatch(setSnackbar('Device was successfully added to the preauthorization list', TIMEOUTS.fiveSeconds))));
3✔
1037

1038
export const decommissionDevice = (deviceId, authId) => (dispatch, getState) =>
185✔
1039
  GeneralApi.delete(`${deviceAuthV2}/devices/${deviceId}`)
1✔
1040
    .then(() => Promise.resolve(dispatch(setSnackbar('Device was decommissioned successfully'))))
1✔
1041
    .catch(err => commonErrorHandler(err, 'There was a problem decommissioning the device:', dispatch))
×
1042
    .then(() => Promise.resolve(dispatch(maybeUpdateDevicesByStatus(deviceId, authId))))
1✔
1043
    // trigger reset of device list list!
1044
    .finally(() => dispatch(setDeviceListState({ refreshTrigger: !getState().devices.deviceList.refreshTrigger })));
1✔
1045

1046
export const getDeviceConfig = deviceId => dispatch =>
185✔
1047
  GeneralApi.get(`${deviceConfig}/${deviceId}`)
5✔
1048
    .then(({ data }) => {
1049
      let tasks = [
2✔
1050
        dispatch({
1051
          type: DeviceConstants.RECEIVE_DEVICE_CONFIG,
1052
          device: { id: deviceId, config: data }
1053
        })
1054
      ];
1055
      tasks.push(Promise.resolve(data));
2✔
1056
      return Promise.all(tasks);
2✔
1057
    })
1058
    .catch(err => {
1059
      // if we get a proper error response we most likely queried a device without an existing config check-in and we can just ignore the call
1060
      if (err.response?.data?.error.status_code !== 404) {
1!
1061
        return commonErrorHandler(err, `There was an error retrieving the configuration for device ${deviceId}.`, dispatch, commonErrorFallback);
×
1062
      }
1063
    });
1064

1065
export const setDeviceConfig = (deviceId, config) => dispatch =>
185✔
1066
  GeneralApi.put(`${deviceConfig}/${deviceId}`, config)
4✔
1067
    .catch(err => commonErrorHandler(err, `There was an error setting the configuration for device ${deviceId}.`, dispatch, commonErrorFallback))
2✔
1068
    .then(() => Promise.resolve(dispatch(getDeviceConfig(deviceId))));
2✔
1069

1070
export const applyDeviceConfig = (deviceId, configDeploymentConfiguration, isDefault, config) => (dispatch, getState) =>
185✔
1071
  GeneralApi.post(`${deviceConfig}/${deviceId}/deploy`, configDeploymentConfiguration)
2✔
1072
    .catch(err => commonErrorHandler(err, `There was an error deploying the configuration to device ${deviceId}.`, dispatch, commonErrorFallback))
×
1073
    .then(({ data }) => {
1074
      const device = getDeviceByIdSelector(getState(), deviceId);
2✔
1075
      let tasks = [
2✔
1076
        dispatch({ type: DeviceConstants.RECEIVE_DEVICE, device: { ...device, config: { ...device.config, deployment_id: '' } } }),
1077
        new Promise(resolve => setTimeout(() => resolve(dispatch(getSingleDeployment(data.deployment_id))), TIMEOUTS.oneSecond))
2✔
1078
      ];
1079
      if (isDefault) {
2!
1080
        const { previous } = getState().users.globalSettings.defaultDeviceConfig ?? {};
×
1081
        tasks.push(dispatch(saveGlobalSettings({ defaultDeviceConfig: { current: config, previous } })));
×
1082
      }
1083
      return Promise.all(tasks);
2✔
1084
    });
1085

1086
export const setDeviceTags = (deviceId, tags) => dispatch =>
185✔
1087
  // to prevent tag set failures, retrieve the device & use the freshest etag we can get
1088
  Promise.resolve(dispatch(getDeviceById(deviceId))).then(device => {
3✔
1089
    const headers = device.etag ? { 'If-Match': device.etag } : {};
3!
1090
    return GeneralApi.put(
3✔
1091
      `${inventoryApiUrl}/devices/${deviceId}/tags`,
1092
      Object.entries(tags).map(([name, value]) => ({ name, value })),
3✔
1093
      { headers }
1094
    )
1095
      .catch(err => commonErrorHandler(err, `There was an error setting tags for device ${deviceId}.`, dispatch, 'Please check your connection.'))
×
1096
      .then(() => Promise.all([dispatch({ type: DeviceConstants.RECEIVE_DEVICE, device: { ...device, tags } }), dispatch(setSnackbar('Device name changed'))]));
2✔
1097
  });
1098

1099
export const getDeviceTwin = (deviceId, integration) => (dispatch, getState) => {
185✔
1100
  let providerResult = {};
3✔
1101
  return GeneralApi.get(`${iotManagerBaseURL}/devices/${deviceId}/state`)
3✔
1102
    .then(({ data }) => {
1103
      providerResult = { ...data, twinError: '' };
2✔
1104
    })
1105
    .catch(err => {
1106
      providerResult = {
×
1107
        twinError: `There was an error getting the ${DeviceConstants.EXTERNAL_PROVIDER[
1108
          integration.provider
1109
        ].twinTitle.toLowerCase()} for device ${deviceId}. ${err}`
1110
      };
1111
    })
1112
    .finally(() =>
1113
      Promise.resolve(
2✔
1114
        dispatch({
1115
          type: DeviceConstants.RECEIVE_DEVICE,
1116
          device: {
1117
            ...getState().devices.byId[deviceId],
1118
            twinsByIntegration: {
1119
              ...getState().devices.byId[deviceId].twinsByIntegration,
1120
              ...providerResult
1121
            }
1122
          }
1123
        })
1124
      )
1125
    );
1126
};
1127

1128
export const setDeviceTwin = (deviceId, integration, settings) => (dispatch, getState) =>
185✔
1129
  GeneralApi.put(`${iotManagerBaseURL}/devices/${deviceId}/state/${integration.id}`, { desired: settings })
1✔
1130
    .catch(err =>
1131
      commonErrorHandler(
×
1132
        err,
1133
        `There was an error updating the ${DeviceConstants.EXTERNAL_PROVIDER[integration.provider].twinTitle.toLowerCase()} for device ${deviceId}.`,
1134
        dispatch
1135
      )
1136
    )
1137
    .then(() => {
1138
      const { twinsByIntegration = {} } = getState().devices.byId[deviceId];
1✔
1139
      const { [integration.id]: currentState = {} } = twinsByIntegration;
1✔
1140
      return Promise.resolve(
1✔
1141
        dispatch({
1142
          type: DeviceConstants.RECEIVE_DEVICE,
1143
          device: {
1144
            ...getState().devices.byId[deviceId],
1145
            twinsByIntegration: {
1146
              ...twinsByIntegration,
1147
              [integration.id]: {
1148
                ...currentState,
1149
                desired: settings
1150
              }
1151
            }
1152
          }
1153
        })
1154
      );
1155
    });
1156

1157
const prepareSearchArguments = ({ filters, group, state, status }) => {
185✔
1158
  const { filterTerms } = convertDeviceListStateToFilters({ filters, group, offlineThreshold: state.app.offlineThreshold, selectedIssues: [], status });
4✔
1159
  const { columnSelection = [] } = getUserSettings(state);
4!
1160
  const selectedAttributes = columnSelection.map(column => ({ attribute: column.key, scope: column.scope }));
4✔
1161
  const attributes = [...defaultAttributes, { scope: 'identity', attribute: getIdAttribute(state).attribute }, ...selectedAttributes];
4✔
1162
  return { attributes, filterTerms };
4✔
1163
};
1164

1165
export const getSystemDevices =
1166
  (id, options = {}) =>
185✔
1167
  (dispatch, getState) => {
1✔
1168
    const { page = defaultPage, perPage = defaultPerPage, sortOptions = [] } = options;
1✔
1169
    const state = getState();
1✔
1170
    let device = getDeviceByIdSelector(state, id);
1✔
1171
    const { attributes: deviceAttributes = {} } = device;
1!
1172
    const { mender_gateway_system_id = '' } = deviceAttributes;
1✔
1173
    const { hasFullFiltering } = getTenantCapabilities(state);
1✔
1174
    if (!hasFullFiltering) {
1!
1175
      return Promise.resolve();
×
1176
    }
1177
    const filters = [
1✔
1178
      { ...emptyFilter, key: 'mender_is_gateway', operator: DEVICE_FILTERING_OPTIONS.$ne.key, value: 'true', scope: 'inventory' },
1179
      { ...emptyFilter, key: 'mender_gateway_system_id', value: mender_gateway_system_id, scope: 'inventory' }
1180
    ];
1181
    const { attributes, filterTerms } = prepareSearchArguments({ filters, state });
1✔
1182

1183
    return GeneralApi.post(getSearchEndpoint(state.app.features.hasReporting), {
1✔
1184
      page,
1185
      per_page: perPage,
1186
      filters: filterTerms,
1187
      sort: sortOptions,
1188
      attributes
1189
    })
1190
      .catch(err => commonErrorHandler(err, `There was an error getting system devices device ${id}.`, dispatch, 'Please check your connection.'))
×
1191
      .then(({ data, headers }) => {
1192
        const state = getState();
1✔
1193
        const { devicesById, ids } = reduceReceivedDevices(data, [], state);
1✔
1194
        const device = {
1✔
1195
          ...state.devices.byId[id],
1196
          systemDeviceIds: ids,
1197
          systemDeviceTotal: Number(headers[headerNames.total])
1198
        };
1199
        return Promise.resolve(
1✔
1200
          dispatch({
1201
            type: DeviceConstants.RECEIVE_DEVICES,
1202
            devicesById: {
1203
              ...devicesById,
1204
              [id]: device
1205
            }
1206
          })
1207
        );
1208
      });
1209
  };
1210

1211
export const getGatewayDevices = deviceId => (dispatch, getState) => {
185✔
1212
  const state = getState();
1✔
1213
  let device = getDeviceByIdSelector(state, deviceId);
1✔
1214
  const { attributes = {} } = device;
1!
1215
  const { mender_gateway_system_id = '' } = attributes;
1!
1216
  const filters = [
1✔
1217
    { ...emptyFilter, key: 'id', operator: DEVICE_FILTERING_OPTIONS.$ne.key, value: deviceId, scope: 'identity' },
1218
    { ...emptyFilter, key: 'mender_is_gateway', value: 'true', scope: 'inventory' },
1219
    { ...emptyFilter, key: 'mender_gateway_system_id', value: mender_gateway_system_id, scope: 'inventory' }
1220
  ];
1221
  const { attributes: attributeSelection, filterTerms } = prepareSearchArguments({ filters, state });
1✔
1222
  return GeneralApi.post(getSearchEndpoint(state.app.features.hasReporting), {
1✔
1223
    page: 1,
1224
    per_page: MAX_PAGE_SIZE,
1225
    filters: filterTerms,
1226
    attributes: attributeSelection
1227
  }).then(({ data }) => {
1228
    const { ids } = reduceReceivedDevices(data, [], getState());
1✔
1229
    let tasks = ids.map(deviceId => dispatch(getDeviceInfo(deviceId)));
1✔
1230
    tasks.push(dispatch({ type: DeviceConstants.RECEIVE_DEVICE, device: { ...getState().devices.byId[deviceId], gatewayIds: ids } }));
1✔
1231
    return Promise.all(tasks);
1✔
1232
  });
1233
};
1234

1235
export const geoAttributes = ['geo-lat', 'geo-lon'].map(attribute => ({ attribute, scope: 'inventory' }));
370✔
1236
export const getDevicesInBounds = (bounds, group) => (dispatch, getState) => {
185✔
1237
  const state = getState();
×
1238
  const { filterTerms } = convertDeviceListStateToFilters({
×
1239
    group: group === DeviceConstants.ALL_DEVICES ? undefined : group,
×
1240
    groups: state.devices.groups,
1241
    status: DEVICE_STATES.accepted
1242
  });
1243
  return GeneralApi.post(getSearchEndpoint(state.app.features.hasReporting), {
×
1244
    page: 1,
1245
    per_page: MAX_PAGE_SIZE,
1246
    filters: filterTerms,
1247
    attributes: geoAttributes,
1248
    geo_bounding_box_filter: {
1249
      geo_bounding_box: {
1250
        location: {
1251
          top_left: { lat: bounds._northEast.lat, lon: bounds._southWest.lng },
1252
          bottom_right: { lat: bounds._southWest.lat, lon: bounds._northEast.lng }
1253
        }
1254
      }
1255
    }
1256
  }).then(({ data }) => {
1257
    const { devicesById } = reduceReceivedDevices(data, [], getState());
×
1258
    return Promise.resolve(dispatch({ type: DeviceConstants.RECEIVE_DEVICES, devicesById }));
×
1259
  });
1260
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc