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

mendersoftware / gui / 993759026

05 Sep 2023 09:01PM UTC coverage: 82.384% (-17.6%) from 99.964%
993759026

Pull #4020

gitlab-ci

mender-test-bot
chore: Types update

Signed-off-by: Mender Test Bot <mender@northern.tech>
Pull Request #4020: chore: Types update

4346 of 6321 branches covered (0.0%)

8259 of 10025 relevant lines covered (82.38%)

192.76 hits per line

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

85.61
/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, SET_TOOLTIPS_STATE } 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();
185✔
52

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

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

64
const featureFlags = [
185✔
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) => {
185✔
77
  const state = getState();
10✔
78
  let onboardingComplete = state.onboarding.complete || !!JSON.parse(window.localStorage.getItem('onboardingComplete') ?? 'false');
10✔
79
  let demoArtifactPort = 85;
10✔
80
  let environmentData = {};
10✔
81
  let environmentFeatures = {};
10✔
82
  let versionInfo = {};
10✔
83
  if (mender_environment) {
10!
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;
10✔
100
    onboardingComplete = stringToBoolean(features.isEnterprise) || stringToBoolean(disableOnboarding) || onboardingComplete;
10✔
101
    demoArtifactPort = port || demoArtifactPort;
10✔
102
    environmentData = {
10✔
103
      hostedAnnouncement: hostedAnnouncement || state.app.hostedAnnouncement,
20✔
104
      hostAddress: hostAddress || state.app.hostAddress,
20✔
105
      recaptchaSiteKey: recaptchaSiteKey || state.app.recaptchaSiteKey,
20✔
106
      stripeAPIKey: stripeAPIKey || state.app.stripeAPIKey,
20✔
107
      trackerCode: trackerCode || state.app.trackerCode
20✔
108
    };
109
    environmentFeatures = {
10✔
110
      ...featureFlags.reduce((accu, flag) => ({ ...accu, [flag]: stringToBoolean(features[flag]) }), {}),
100✔
111
      // the check in features is purely kept as a local override, it shouldn't become relevant for production again
112
      isHosted: features.isHosted || window.location.hostname.includes('hosted.mender.io'),
20✔
113
      isDemoMode: stringToBoolean(isDemoMode || features.isDemoMode)
20✔
114
    };
115
    versionInfo = {
10✔
116
      docs: isNaN(integrationVersion.charAt(0)) ? '' : integrationVersion.split('.').slice(0, 2).join('.'),
10!
117
      remainder: {
118
        Integration: getComparisonCompatibleVersion(integrationVersion),
119
        'Mender-Client': getComparisonCompatibleVersion(menderVersion),
120
        'Mender-Artifact': menderArtifactVersion,
121
        'Meta-Mender': metaMenderVersion,
122
        Deployments: services.deploymentsVersion,
123
        Deviceauth: services.deviceauthVersion,
124
        Inventory: services.inventoryVersion,
125
        GUI: services.guiVersion
126
      }
127
    };
128
  }
129
  return Promise.all([
10✔
130
    dispatch(setOnboardingComplete(onboardingComplete)),
131
    dispatch(setDemoArtifactPort(demoArtifactPort)),
132
    dispatch({ type: SET_FEATURES, value: environmentFeatures }),
133
    dispatch({ type: SET_VERSION_INFORMATION, docsVersion: versionInfo.docs, value: versionInfo.remainder }),
134
    dispatch({ type: SET_ENVIRONMENT_DATA, value: environmentData }),
135
    dispatch(getLatestReleaseInfo())
136
  ]);
137
};
138

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

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

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

216
const retrieveAppData = () => (dispatch, getState) => {
185✔
217
  let tasks = [
6✔
218
    dispatch(parseEnvironmentInfo()),
219
    dispatch(getUserSettings()),
220
    dispatch(getGlobalSettings()),
221
    dispatch(getDeviceAttributes()),
222
    dispatch(getDeploymentsByStatus(DEPLOYMENT_STATES.finished, undefined, undefined, undefined, undefined, undefined, undefined, false)),
223
    dispatch(getDeploymentsByStatus(DEPLOYMENT_STATES.inprogress)),
224
    dispatch(getDevicesByStatus(DEVICE_STATES.accepted)),
225
    dispatch(getDevicesByStatus(DEVICE_STATES.pending)),
226
    dispatch(getDevicesByStatus(DEVICE_STATES.preauth)),
227
    dispatch(getDevicesByStatus(DEVICE_STATES.rejected)),
228
    dispatch(getDynamicGroups()),
229
    dispatch(getGroups()),
230
    dispatch(getIntegrations()),
231
    dispatch(getReleases()),
232
    dispatch(getDeviceLimit()),
233
    dispatch(getRoles()),
234
    dispatch(setFirstLoginAfterSignup(cookies.get('firstLoginAfterSignup')))
235
  ];
236
  const { hasMultitenancy, isHosted } = getFeatures(getState());
6✔
237
  const multitenancy = hasMultitenancy || isHosted || getIsEnterprise(getState());
6✔
238
  if (multitenancy) {
6✔
239
    tasks.push(dispatch(getUserOrganization()));
5✔
240
  }
241
  return Promise.all(tasks);
6✔
242
};
243

244
export const initializeAppData = () => dispatch =>
185✔
245
  dispatch(retrieveAppData())
6✔
246
    .then(() => dispatch(interpretAppData()))
4✔
247
    // this is allowed to fail if no user information are available
248
    .catch(err => console.log(extractErrorMessage(err)))
2✔
249
    .then(() => dispatch(getOnboardingState()));
6✔
250

251
/*
252
  General
253
*/
254
export const setSnackbar = (message, autoHideDuration, action, children, onClick, onClose) => dispatch =>
185✔
255
  dispatch({
135✔
256
    type: SET_SNACKBAR,
257
    snackbar: {
258
      open: message ? true : false,
135✔
259
      message,
260
      maxWidth: '900px',
261
      autoHideDuration,
262
      action,
263
      children,
264
      onClick,
265
      onClose
266
    }
267
  });
268

269
export const setFirstLoginAfterSignup = firstLoginAfterSignup => dispatch => {
185✔
270
  cookies.set('firstLoginAfterSignup', !!firstLoginAfterSignup, { maxAge: 60, path: '/', domain: '.mender.io', sameSite: false });
10✔
271
  dispatch({ type: SET_FIRST_LOGIN_AFTER_SIGNUP, firstLoginAfterSignup: !!firstLoginAfterSignup });
10✔
272
};
273

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

294
export const setVersionInfo = info => (dispatch, getState) =>
185✔
295
  Promise.resolve(
2✔
296
    dispatch({
297
      type: SET_VERSION_INFORMATION,
298
      docsVersion: getState().app.docsVersion,
299
      value: {
300
        ...getState().app.versionInformation,
301
        ...info
302
      }
303
    })
304
  );
305

306
const versionRegex = new RegExp(/\d+\.\d+/);
185✔
307
const getLatestRelease = thing => {
185✔
308
  const latestKey = Object.keys(thing)
8✔
309
    .filter(key => versionRegex.test(key))
20✔
310
    .sort()
311
    .reverse()[0];
312
  return thing[latestKey];
8✔
313
};
314

315
const repoKeyMap = {
185✔
316
  integration: 'Integration',
317
  mender: 'Mender-Client',
318
  'mender-artifact': 'Mender-Artifact'
319
};
320

321
const deductSaasState = (latestRelease, guiTags, saasReleases) => {
185✔
322
  const latestGuiTag = guiTags.length ? guiTags[0].name : '';
4!
323
  const latestSaasRelease = latestGuiTag.startsWith('saas-v') ? { date: latestGuiTag.split('-v')[1].replaceAll('.', '-'), tag: latestGuiTag } : saasReleases[0];
4!
324
  return latestSaasRelease.date > latestRelease.release_date ? latestSaasRelease.tag : latestRelease.release;
4!
325
};
326

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

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