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

mendersoftware / gui / 913068613

pending completion
913068613

Pull #3803

gitlab-ci

web-flow
Merge pull request #3801 from mzedel/men-6383

MEN-6383 - device check in time
Pull Request #3803: staging alignment

4418 of 6435 branches covered (68.66%)

178 of 246 new or added lines in 27 files covered. (72.36%)

8352 of 10138 relevant lines covered (82.38%)

160.95 hits per line

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

82.06
/src/js/actions/appActions.js
1
// Copyright 2019 Northern.tech AS
2
//
3
//    Licensed under the Apache License, Version 2.0 (the "License");
4
//    you may not use this file except in compliance with the License.
5
//    You may obtain a copy of the License at
6
//
7
//        http://www.apache.org/licenses/LICENSE-2.0
8
//
9
//    Unless required by applicable law or agreed to in writing, software
10
//    distributed under the License is distributed on an "AS IS" BASIS,
11
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
//    See the License for the specific language governing permissions and
13
//    limitations under the License.
14
import Cookies from 'universal-cookie';
15

16
import GeneralApi from '../api/general-api';
17
import { getToken } from '../auth';
18
import {
19
  SET_ENVIRONMENT_DATA,
20
  SET_FEATURES,
21
  SET_FIRST_LOGIN_AFTER_SIGNUP,
22
  SET_OFFLINE_THRESHOLD,
23
  SET_SEARCH_STATE,
24
  SET_SNACKBAR,
25
  SET_VERSION_INFORMATION,
26
  TIMEOUTS
27
} from '../constants/appConstants';
28
import { DEPLOYMENT_STATES } from '../constants/deploymentConstants';
29
import { DEVICE_STATES } from '../constants/deviceConstants';
30
import { onboardingSteps } from '../constants/onboardingConstants';
31
import { SET_SHOW_HELP } from '../constants/userConstants';
32
import { deepCompare, extractErrorMessage, preformatWithRequestID, stringToBoolean } from '../helpers';
33
import { getCurrentUser, getFeatures, getIsEnterprise, getOfflineThresholdSettings, getUserSettings as getUserSettingsSelector } from '../selectors';
34
import { getOnboardingComponentFor } from '../utils/onboardingmanager';
35
import { getDeploymentsByStatus } from './deploymentActions';
36
import {
37
  getDeviceAttributes,
38
  getDeviceById,
39
  getDeviceLimit,
40
  getDevicesByStatus,
41
  getDynamicGroups,
42
  getGroups,
43
  searchDevices,
44
  setDeviceListState
45
} from './deviceActions';
46
import { getOnboardingState, setDemoArtifactPort, setOnboardingComplete } from './onboardingActions';
47
import { getIntegrations, getUserOrganization } from './organizationActions';
48
import { getReleases } from './releaseActions';
49
import { getGlobalSettings, getRoles, getUserSettings, saveGlobalSettings, saveUserSettings } from './userActions';
50

51
const cookies = new Cookies();
190✔
52

53
export const commonErrorFallback = 'Please check your connection.';
190✔
54
export const commonErrorHandler = (err, errorContext, dispatch, fallback, mightBeAuthRelated = false) => {
190✔
55
  const errMsg = extractErrorMessage(err, fallback);
4✔
56
  if (mightBeAuthRelated || getToken()) {
4!
57
    dispatch(setSnackbar(preformatWithRequestID(err.response, `${errorContext} ${errMsg}`), null, 'Copy to clipboard'));
4✔
58
  }
59
  return Promise.reject(err);
4✔
60
};
61

62
const getComparisonCompatibleVersion = version => (isNaN(version.charAt(0)) && version !== 'next' ? 'master' : version);
190✔
63

64
const featureFlags = [
190✔
65
  'hasAddons',
66
  'hasAuditlogs',
67
  'hasMultitenancy',
68
  'hasDeltaProgress',
69
  'hasDeviceConfig',
70
  'hasDeviceConnect',
71
  'hasReleaseTags',
72
  'hasReporting',
73
  'hasMonitor',
74
  'isEnterprise'
75
];
76
export const parseEnvironmentInfo = () => (dispatch, getState) => {
190✔
77
  const state = getState();
9✔
78
  let onboardingComplete = state.onboarding.complete || !!JSON.parse(window.localStorage.getItem('onboardingComplete') ?? 'false');
9✔
79
  let demoArtifactPort = 85;
9✔
80
  let environmentData = {};
9✔
81
  let environmentFeatures = {};
9✔
82
  let versionInfo = {};
9✔
83
  if (mender_environment) {
9!
84
    const {
85
      features = {},
×
86
      demoArtifactPort: port,
87
      disableOnboarding,
88
      hostAddress,
89
      hostedAnnouncement,
90
      integrationVersion,
91
      isDemoMode,
92
      menderVersion,
93
      menderArtifactVersion,
94
      metaMenderVersion,
95
      recaptchaSiteKey,
96
      services = {},
×
97
      stripeAPIKey,
98
      trackerCode
99
    } = mender_environment;
9✔
100
    onboardingComplete = stringToBoolean(features.isEnterprise) || stringToBoolean(disableOnboarding) || onboardingComplete;
9✔
101
    demoArtifactPort = port || demoArtifactPort;
9✔
102
    environmentData = {
9✔
103
      hostedAnnouncement: hostedAnnouncement || state.app.hostedAnnouncement,
18✔
104
      hostAddress: hostAddress || state.app.hostAddress,
18✔
105
      recaptchaSiteKey: recaptchaSiteKey || state.app.recaptchaSiteKey,
18✔
106
      stripeAPIKey: stripeAPIKey || state.app.stripeAPIKey,
18✔
107
      trackerCode: trackerCode || state.app.trackerCode
18✔
108
    };
109
    environmentFeatures = {
9✔
110
      ...featureFlags.reduce((accu, flag) => ({ ...accu, [flag]: stringToBoolean(features[flag]) }), {}),
90✔
111
      isHosted: stringToBoolean(features.isHosted) || window.location.hostname.includes('hosted.mender.io'),
18✔
112
      isDemoMode: stringToBoolean(isDemoMode || features.isDemoMode)
18✔
113
    };
114
    versionInfo = {
9✔
115
      docs: isNaN(integrationVersion.charAt(0)) ? '' : integrationVersion.split('.').slice(0, 2).join('.'),
9!
116
      remainder: {
117
        Integration: getComparisonCompatibleVersion(integrationVersion),
118
        'Mender-Client': getComparisonCompatibleVersion(menderVersion),
119
        'Mender-Artifact': menderArtifactVersion,
120
        'Meta-Mender': metaMenderVersion,
121
        Deployments: services.deploymentsVersion,
122
        Deviceauth: services.deviceauthVersion,
123
        Inventory: services.inventoryVersion,
124
        GUI: services.guiVersion
125
      }
126
    };
127
  }
128
  return Promise.all([
9✔
129
    dispatch(setOnboardingComplete(onboardingComplete)),
130
    dispatch(setDemoArtifactPort(demoArtifactPort)),
131
    dispatch({ type: SET_FEATURES, value: environmentFeatures }),
132
    dispatch({ type: SET_VERSION_INFORMATION, docsVersion: versionInfo.docs, value: versionInfo.remainder }),
133
    dispatch({ type: SET_ENVIRONMENT_DATA, value: environmentData }),
134
    dispatch(getLatestReleaseInfo())
135
  ]);
136
};
137

138
const maybeAddOnboardingTasks = ({ devicesByStatus, dispatch, showHelptips, onboardingState, tasks }) => {
190✔
139
  if (!(showHelptips && onboardingState.showTips) || onboardingState.complete) {
4!
140
    return tasks;
4✔
141
  }
142
  const welcomeTip = getOnboardingComponentFor(onboardingSteps.ONBOARDING_START, {
×
143
    progress: onboardingState.progress,
144
    complete: onboardingState.complete,
145
    showHelptips,
146
    showTips: onboardingState.showTips
147
  });
148
  if (welcomeTip) {
×
149
    tasks.push(dispatch(setSnackbar('open', TIMEOUTS.refreshDefault, '', welcomeTip, () => {}, true)));
×
150
  }
151
  // try to retrieve full device details for onboarding devices to ensure ips etc. are available
152
  // we only load the first few/ 20 devices, as it is possible the onboarding is left dangling
153
  // and a lot of devices are present and we don't want to flood the backend for this
154
  return devicesByStatus[DEVICE_STATES.accepted].deviceIds.reduce((accu, id) => {
×
155
    accu.push(dispatch(getDeviceById(id)));
×
156
    return accu;
×
157
  }, tasks);
158
};
159

160
const processUserCookie = (user, showHelptips) => {
190✔
161
  const userCookie = cookies.get(user.id);
4✔
162
  if (userCookie && userCookie.help !== 'undefined') {
4!
163
    const { help, ...crumbles } = userCookie;
×
164
    // got user cookie with pre-existing value
165
    showHelptips = help;
×
166
    // store only remaining cookie values, to allow relying on stored settings from now on
167
    if (!Object.keys(crumbles).length) {
×
168
      cookies.remove(user.id);
×
169
    } else {
170
      cookies.set(user.id, crumbles);
×
171
    }
172
  }
173
  return showHelptips;
4✔
174
};
175

176
const interpretAppData = () => (dispatch, getState) => {
190✔
177
  const state = getState();
4✔
178
  const user = getCurrentUser(state);
4✔
179
  let tasks = [];
4✔
180
  let { columnSelection = [], showHelptips = state.users.showHelptips, trackingConsentGiven: hasTrackingEnabled } = getUserSettingsSelector(state);
4!
181
  tasks.push(dispatch(setDeviceListState({ selectedAttributes: columnSelection.map(column => ({ attribute: column.key, scope: column.scope })) })));
4✔
182
  // checks if user id is set and if cookie for helptips exists for that user
183
  showHelptips = processUserCookie(user, showHelptips);
4✔
184
  tasks = maybeAddOnboardingTasks({ devicesByStatus: state.devices.byStatus, dispatch, tasks, onboardingState: state.onboarding, showHelptips });
4✔
185
  tasks.push(Promise.resolve(dispatch({ type: SET_SHOW_HELP, show: showHelptips })));
4✔
186
  let settings = { showHelptips };
4✔
187
  if (cookies.get('_ga') && typeof hasTrackingEnabled === 'undefined') {
4!
NEW
188
    settings.trackingConsentGiven = true;
×
189
  }
190
  tasks.push(dispatch(saveUserSettings(settings)));
4✔
191
  // the following is used as a migration and initialization of the stored identity attribute
192
  // changing the default device attribute to the first non-deviceId attribute, unless a stored
193
  // id attribute setting exists
194
  const identityOptions = state.devices.filteringAttributes.identityAttributes.filter(attribute => !['id', 'Device ID', 'status'].includes(attribute));
5✔
195
  const { id_attribute } = state.users.globalSettings;
4✔
196
  if (!id_attribute && identityOptions.length) {
4✔
197
    tasks.push(dispatch(saveGlobalSettings({ id_attribute: { attribute: identityOptions[0], scope: 'identity' } })));
2✔
198
  } else if (typeof id_attribute === 'string') {
2!
NEW
199
    let attribute = id_attribute;
×
NEW
200
    if (attribute === 'Device ID') {
×
NEW
201
      attribute = 'id';
×
202
    }
NEW
203
    tasks.push(dispatch(saveGlobalSettings({ id_attribute: { attribute, scope: 'identity' } })));
×
204
  }
205
  return Promise.all(tasks);
4✔
206
};
207

208
const retrieveAppData = () => (dispatch, getState) => {
190✔
209
  let tasks = [
4✔
210
    dispatch(parseEnvironmentInfo()),
211
    dispatch(getUserSettings()),
212
    dispatch(getGlobalSettings()),
213
    dispatch(getDeviceAttributes()),
214
    dispatch(getDeploymentsByStatus(DEPLOYMENT_STATES.finished, undefined, undefined, undefined, undefined, undefined, undefined, false)),
215
    dispatch(getDeploymentsByStatus(DEPLOYMENT_STATES.inprogress)),
216
    dispatch(getDevicesByStatus(DEVICE_STATES.accepted)),
217
    dispatch(getDevicesByStatus(DEVICE_STATES.pending)),
218
    dispatch(getDevicesByStatus(DEVICE_STATES.preauth)),
219
    dispatch(getDevicesByStatus(DEVICE_STATES.rejected)),
220
    dispatch(getDynamicGroups()),
221
    dispatch(getGroups()),
222
    dispatch(getIntegrations()),
223
    dispatch(getReleases()),
224
    dispatch(getDeviceLimit()),
225
    dispatch(getRoles()),
226
    dispatch(setFirstLoginAfterSignup(cookies.get('firstLoginAfterSignup')))
227
  ];
228
  const { hasMultitenancy, isHosted } = getFeatures(getState());
4✔
229
  const multitenancy = hasMultitenancy || isHosted || getIsEnterprise(getState());
4✔
230
  if (multitenancy) {
4✔
231
    tasks.push(dispatch(getUserOrganization()));
3✔
232
  }
233
  return Promise.all(tasks);
4✔
234
};
235

236
export const initializeAppData = () => dispatch =>
190✔
237
  dispatch(retrieveAppData())
4✔
238
    .then(() => dispatch(interpretAppData()))
4✔
239
    // this is allowed to fail if no user information are available
NEW
240
    .catch(err => console.log(extractErrorMessage(err)))
×
241
    .then(() => dispatch(getOnboardingState()));
4✔
242

243
/*
244
  General
245
*/
246
export const setSnackbar = (message, autoHideDuration, action, children, onClick, onClose) => dispatch =>
190✔
247
  dispatch({
114✔
248
    type: SET_SNACKBAR,
249
    snackbar: {
250
      open: message ? true : false,
114✔
251
      message,
252
      maxWidth: '900px',
253
      autoHideDuration,
254
      action,
255
      children,
256
      onClick,
257
      onClose
258
    }
259
  });
260

261
export const setFirstLoginAfterSignup = firstLoginAfterSignup => dispatch => {
190✔
262
  cookies.set('firstLoginAfterSignup', !!firstLoginAfterSignup, { maxAge: 60, path: '/', domain: '.mender.io', sameSite: false });
8✔
263
  dispatch({ type: SET_FIRST_LOGIN_AFTER_SIGNUP, firstLoginAfterSignup: !!firstLoginAfterSignup });
8✔
264
};
265

266
const dateFunctionMap = {
190✔
267
  getDays: 'getDate',
268
  setDays: 'setDate'
269
};
270
export const setOfflineThreshold = () => (dispatch, getState) => {
190✔
271
  const { interval, intervalUnit } = getOfflineThresholdSettings(getState());
16✔
272
  const today = new Date();
16✔
273
  const intervalName = `${intervalUnit.charAt(0).toUpperCase()}${intervalUnit.substring(1)}`;
16✔
274
  const setter = dateFunctionMap[`set${intervalName}`] ?? `set${intervalName}`;
16✔
275
  const getter = dateFunctionMap[`get${intervalName}`] ?? `get${intervalName}`;
16✔
276
  today[setter](today[getter]() - interval);
16✔
277
  let value;
278
  try {
16✔
279
    value = today.toISOString();
16✔
280
  } catch {
281
    return Promise.resolve(dispatch(setSnackbar('There was an error saving the offline threshold, please check your settings.')));
×
282
  }
283
  return Promise.resolve(dispatch({ type: SET_OFFLINE_THRESHOLD, value }));
16✔
284
};
285

286
export const setVersionInfo = info => (dispatch, getState) =>
190✔
287
  Promise.resolve(
2✔
288
    dispatch({
289
      type: SET_VERSION_INFORMATION,
290
      docsVersion: getState().app.docsVersion,
291
      value: {
292
        ...getState().app.versionInformation,
293
        ...info
294
      }
295
    })
296
  );
297

298
const versionRegex = new RegExp(/\d+\.\d+/);
190✔
299
const getLatestRelease = thing => {
190✔
300
  const latestKey = Object.keys(thing)
8✔
301
    .filter(key => versionRegex.test(key))
20✔
302
    .sort()
303
    .reverse()[0];
304
  return thing[latestKey];
8✔
305
};
306

307
const repoKeyMap = {
190✔
308
  integration: 'Integration',
309
  mender: 'Mender-Client',
310
  'mender-artifact': 'Mender-Artifact'
311
};
312

313
const deductSaasState = (latestRelease, guiTags, saasReleases) => {
190✔
314
  const latestGuiTag = guiTags[0].name;
4✔
315
  const latestSaasRelease = latestGuiTag.startsWith('saas-v') ? { date: latestGuiTag.split('-v')[1].replaceAll('.', '-'), tag: latestGuiTag } : saasReleases[0];
4!
316
  return latestSaasRelease.date > latestRelease.release_date ? latestSaasRelease.tag : latestRelease.release;
4!
317
};
318

319
export const getLatestReleaseInfo = () => (dispatch, getState) => {
190✔
320
  if (!getState().app.features.isHosted) {
13✔
321
    return Promise.resolve();
9✔
322
  }
323
  return Promise.all([GeneralApi.get('/versions.json'), GeneralApi.get('/tags.json')]).then(([{ data }, { data: guiTags }]) => {
4✔
324
    const { releases, saas } = data;
4✔
325
    const latestRelease = getLatestRelease(getLatestRelease(releases));
4✔
326
    const { latestRepos, latestVersions } = latestRelease.repos.reduce(
4✔
327
      (accu, item) => {
328
        if (repoKeyMap[item.name]) {
20✔
329
          accu.latestVersions[repoKeyMap[item.name]] = getComparisonCompatibleVersion(item.version);
12✔
330
        }
331
        accu.latestRepos[item.name] = getComparisonCompatibleVersion(item.version);
20✔
332
        return accu;
20✔
333
      },
334
      { latestVersions: { ...getState().app.versionInformation }, latestRepos: {} }
335
    );
336
    const info = deductSaasState(latestRelease, guiTags, saas);
4✔
337
    return Promise.resolve(
4✔
338
      dispatch({
339
        type: SET_VERSION_INFORMATION,
340
        docsVersion: getState().app.docsVersion,
341
        value: {
342
          ...latestVersions,
343
          backend: info,
344
          GUI: info,
345
          latestRelease: {
346
            releaseDate: latestRelease.release_date,
347
            repos: latestRepos
348
          }
349
        }
350
      })
351
    );
352
  });
353
};
354

355
export const setSearchState = searchState => (dispatch, getState) => {
190✔
356
  const currentState = getState().app.searchState;
4✔
357
  let nextState = {
4✔
358
    ...currentState,
359
    ...searchState,
360
    sort: {
361
      ...currentState.sort,
362
      ...searchState.sort
363
    }
364
  };
365
  let tasks = [];
4✔
366
  // eslint-disable-next-line no-unused-vars
367
  const { isSearching: currentSearching, deviceIds: currentDevices, searchTotal: currentTotal, ...currentRequestState } = currentState;
4✔
368
  // eslint-disable-next-line no-unused-vars
369
  const { isSearching: nextSearching, deviceIds: nextDevices, searchTotal: nextTotal, ...nextRequestState } = nextState;
4✔
370
  if (nextRequestState.searchTerm && !deepCompare(currentRequestState, nextRequestState)) {
4✔
371
    nextState.isSearching = true;
2✔
372
    tasks.push(
2✔
373
      dispatch(searchDevices(nextState))
374
        .then(results => {
375
          const searchResult = results[results.length - 1];
2✔
376
          return dispatch(setSearchState({ ...searchResult, isSearching: false }));
2✔
377
        })
378
        .catch(() => dispatch(setSearchState({ isSearching: false, searchTotal: 0 })))
×
379
    );
380
  }
381
  tasks.push(dispatch({ type: SET_SEARCH_STATE, state: nextState }));
4✔
382
  return Promise.all(tasks);
4✔
383
};
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