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

mendersoftware / gui / 1057188406

01 Nov 2023 04:24AM UTC coverage: 82.824% (-17.1%) from 99.964%
1057188406

Pull #4134

gitlab-ci

web-flow
chore: Bump uuid from 9.0.0 to 9.0.1

Bumps [uuid](https://github.com/uuidjs/uuid) from 9.0.0 to 9.0.1.
- [Changelog](https://github.com/uuidjs/uuid/blob/main/CHANGELOG.md)
- [Commits](https://github.com/uuidjs/uuid/compare/v9.0.0...v9.0.1)

---
updated-dependencies:
- dependency-name: uuid
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Pull Request #4134: chore: Bump uuid from 9.0.0 to 9.0.1

4349 of 6284 branches covered (0.0%)

8313 of 10037 relevant lines covered (82.82%)

200.97 hits per line

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

86.4
/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_TOOLTIPS_STATE } from '../constants/userConstants';
32
import { deepCompare, extractErrorMessage, preformatWithRequestID, stringToBoolean } from '../helpers';
33
import { 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();
184✔
52

53
export const commonErrorFallback = 'Please check your connection.';
184✔
54
export const commonErrorHandler = (err, errorContext, dispatch, fallback, mightBeAuthRelated = false) => {
184✔
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);
184✔
63

64
const featureFlags = [
184✔
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) => {
184✔
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, onboardingState, tasks }) => {
184✔
140
  if (!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
    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 interpretAppData = () => (dispatch, getState) => {
184✔
161
  const state = getState();
4✔
162
  let { columnSelection = [], trackingConsentGiven: hasTrackingEnabled, tooltips = {} } = getUserSettingsSelector(state);
4!
163
  let settings = {};
4✔
164
  if (cookies.get('_ga') && typeof hasTrackingEnabled === 'undefined') {
4!
165
    settings.trackingConsentGiven = true;
×
166
  }
167
  let tasks = [
4✔
168
    dispatch(setDeviceListState({ selectedAttributes: columnSelection.map(column => ({ attribute: column.key, scope: column.scope })) })),
×
169
    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
170
    dispatch(saveUserSettings(settings))
171
  ];
172
  tasks = maybeAddOnboardingTasks({ devicesByStatus: state.devices.byStatus, dispatch, tasks, onboardingState: state.onboarding });
4✔
173
  // the following is used as a migration and initialization of the stored identity attribute
174
  // changing the default device attribute to the first non-deviceId attribute, unless a stored
175
  // id attribute setting exists
176
  const identityOptions = state.devices.filteringAttributes.identityAttributes.filter(attribute => !['id', 'Device ID', 'status'].includes(attribute));
5✔
177
  const { id_attribute } = state.users.globalSettings;
4✔
178
  if (!id_attribute && identityOptions.length) {
4✔
179
    tasks.push(dispatch(saveGlobalSettings({ id_attribute: { attribute: identityOptions[0], scope: 'identity' } })));
2✔
180
  } else if (typeof id_attribute === 'string') {
2!
181
    let attribute = id_attribute;
×
182
    if (attribute === 'Device ID') {
×
183
      attribute = 'id';
×
184
    }
185
    tasks.push(dispatch(saveGlobalSettings({ id_attribute: { attribute, scope: 'identity' } })));
×
186
  }
187
  return Promise.all(tasks);
4✔
188
};
189

190
const retrieveAppData = () => (dispatch, getState) => {
184✔
191
  let tasks = [
6✔
192
    dispatch(parseEnvironmentInfo()),
193
    dispatch(getUserSettings()),
194
    dispatch(getGlobalSettings()),
195
    dispatch(getDeviceAttributes()),
196
    dispatch(getDeploymentsByStatus(DEPLOYMENT_STATES.finished, undefined, undefined, undefined, undefined, undefined, undefined, false)),
197
    dispatch(getDeploymentsByStatus(DEPLOYMENT_STATES.inprogress)),
198
    dispatch(getDevicesByStatus(DEVICE_STATES.accepted)),
199
    dispatch(getDevicesByStatus(DEVICE_STATES.pending)),
200
    dispatch(getDevicesByStatus(DEVICE_STATES.preauth)),
201
    dispatch(getDevicesByStatus(DEVICE_STATES.rejected)),
202
    dispatch(getDynamicGroups()),
203
    dispatch(getGroups()),
204
    dispatch(getIntegrations()),
205
    dispatch(getReleases()),
206
    dispatch(getDeviceLimit()),
207
    dispatch(getRoles()),
208
    dispatch(setFirstLoginAfterSignup(stringToBoolean(cookies.get('firstLoginAfterSignup'))))
209
  ];
210
  const { hasMultitenancy, isHosted } = getFeatures(getState());
6✔
211
  const multitenancy = hasMultitenancy || isHosted || getIsEnterprise(getState());
6✔
212
  if (multitenancy) {
6✔
213
    tasks.push(dispatch(getUserOrganization()));
5✔
214
  }
215
  return Promise.all(tasks);
6✔
216
};
217

218
export const initializeAppData = () => dispatch =>
184✔
219
  dispatch(retrieveAppData())
6✔
220
    .then(() => dispatch(interpretAppData()))
4✔
221
    // this is allowed to fail if no user information are available
222
    .catch(err => console.log(extractErrorMessage(err)))
2✔
223
    .then(() => dispatch(getOnboardingState()));
6✔
224

225
/*
226
  General
227
*/
228
export const setSnackbar = (message, autoHideDuration, action, children, onClick, onClose) => dispatch =>
184✔
229
  dispatch({
139✔
230
    type: SET_SNACKBAR,
231
    snackbar: {
232
      open: message ? true : false,
139✔
233
      message,
234
      maxWidth: '900px',
235
      autoHideDuration,
236
      action,
237
      children,
238
      onClick,
239
      onClose
240
    }
241
  });
242

243
export const setFirstLoginAfterSignup = firstLoginAfterSignup => dispatch => {
184✔
244
  cookies.set('firstLoginAfterSignup', !!firstLoginAfterSignup, { maxAge: 60, path: '/', domain: '.mender.io', sameSite: false });
10✔
245
  dispatch({ type: SET_FIRST_LOGIN_AFTER_SIGNUP, firstLoginAfterSignup: !!firstLoginAfterSignup });
10✔
246
};
247

248
const dateFunctionMap = {
184✔
249
  getDays: 'getDate',
250
  setDays: 'setDate'
251
};
252
export const setOfflineThreshold = () => (dispatch, getState) => {
184✔
253
  const { interval, intervalUnit } = getOfflineThresholdSettings(getState());
17✔
254
  const today = new Date();
17✔
255
  const intervalName = `${intervalUnit.charAt(0).toUpperCase()}${intervalUnit.substring(1)}`;
17✔
256
  const setter = dateFunctionMap[`set${intervalName}`] ?? `set${intervalName}`;
17✔
257
  const getter = dateFunctionMap[`get${intervalName}`] ?? `get${intervalName}`;
17✔
258
  today[setter](today[getter]() - interval);
17✔
259
  let value;
260
  try {
17✔
261
    value = today.toISOString();
17✔
262
  } catch {
263
    return Promise.resolve(dispatch(setSnackbar('There was an error saving the offline threshold, please check your settings.')));
×
264
  }
265
  return Promise.resolve(dispatch({ type: SET_OFFLINE_THRESHOLD, value }));
17✔
266
};
267

268
export const setVersionInfo = info => (dispatch, getState) =>
184✔
269
  Promise.resolve(
2✔
270
    dispatch({
271
      type: SET_VERSION_INFORMATION,
272
      docsVersion: getState().app.docsVersion,
273
      value: {
274
        ...getState().app.versionInformation,
275
        ...info
276
      }
277
    })
278
  );
279

280
const versionRegex = new RegExp(/\d+\.\d+/);
184✔
281
const getLatestRelease = thing => {
184✔
282
  const latestKey = Object.keys(thing)
8✔
283
    .filter(key => versionRegex.test(key))
20✔
284
    .sort()
285
    .reverse()[0];
286
  return thing[latestKey];
8✔
287
};
288

289
const repoKeyMap = {
184✔
290
  integration: 'Integration',
291
  mender: 'Mender-Client',
292
  'mender-artifact': 'Mender-Artifact'
293
};
294

295
const deductSaasState = (latestRelease, guiTags, saasReleases) => {
184✔
296
  const latestGuiTag = guiTags.length ? guiTags[0].name : '';
4!
297
  const latestSaasRelease = latestGuiTag.startsWith('saas-v') ? { date: latestGuiTag.split('-v')[1].replaceAll('.', '-'), tag: latestGuiTag } : saasReleases[0];
4!
298
  return latestSaasRelease.date > latestRelease.release_date ? latestSaasRelease.tag : latestRelease.release;
4!
299
};
300

301
export const getLatestReleaseInfo = () => (dispatch, getState) => {
184✔
302
  if (!getState().app.features.isHosted) {
14✔
303
    return Promise.resolve();
10✔
304
  }
305
  return Promise.all([GeneralApi.get('/versions.json'), GeneralApi.get('/tags.json')])
4✔
306
    .catch(err => {
307
      console.log('init error:', extractErrorMessage(err));
×
308
      return Promise.resolve([{ data: {} }, { data: [] }]);
×
309
    })
310
    .then(([{ data }, { data: guiTags }]) => {
311
      if (!guiTags.length) {
4!
312
        return Promise.resolve();
×
313
      }
314
      const { releases, saas } = data;
4✔
315
      const latestRelease = getLatestRelease(getLatestRelease(releases));
4✔
316
      const { latestRepos, latestVersions } = latestRelease.repos.reduce(
4✔
317
        (accu, item) => {
318
          if (repoKeyMap[item.name]) {
20✔
319
            accu.latestVersions[repoKeyMap[item.name]] = getComparisonCompatibleVersion(item.version);
12✔
320
          }
321
          accu.latestRepos[item.name] = getComparisonCompatibleVersion(item.version);
20✔
322
          return accu;
20✔
323
        },
324
        { latestVersions: { ...getState().app.versionInformation }, latestRepos: {} }
325
      );
326
      const info = deductSaasState(latestRelease, guiTags, saas);
4✔
327
      return Promise.resolve(
4✔
328
        dispatch({
329
          type: SET_VERSION_INFORMATION,
330
          docsVersion: getState().app.docsVersion,
331
          value: {
332
            ...latestVersions,
333
            backend: info,
334
            GUI: info,
335
            latestRelease: {
336
              releaseDate: latestRelease.release_date,
337
              repos: latestRepos
338
            }
339
          }
340
        })
341
      );
342
    });
343
};
344

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