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

mendersoftware / gui / 1213056175

14 Mar 2024 09:12AM UTC coverage: 83.598% (-16.4%) from 99.964%
1213056175

Pull #4355

gitlab-ci

mineralsfree
fix: Change minimal increment to 1 day, previous units updated automatically

Ticket: MEN-6831
Changelog: None

Signed-off-by: Mikita Pilinka <mikita.pilinka@northern.tech>
Pull Request #4355: MEN-6831: Change minimal increment to 1 day, previous units updated automatically

4439 of 6330 branches covered (70.13%)

3 of 5 new or added lines in 2 files covered. (60.0%)

1633 existing lines in 162 files now uncovered.

8410 of 10060 relevant lines covered (83.6%)

140.64 hits per line

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

85.6
/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 { getSessionInfo, 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, SUCCESSFULLY_LOGGED_IN } 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();
183✔
52

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

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

64
const featureFlags = [
183✔
65
  'hasAuditlogs',
66
  'hasMultitenancy',
67
  'hasDeltaProgress',
68
  'hasDeviceConfig',
69
  'hasDeviceConnect',
70
  'hasReleaseTags',
71
  'hasReporting',
72
  'hasMonitor',
73
  'isEnterprise'
74
];
75
export const parseEnvironmentInfo = () => (dispatch, getState) => {
183✔
76
  const state = getState();
9✔
77
  let onboardingComplete = state.onboarding.complete || !!JSON.parse(window.localStorage.getItem('onboardingComplete') ?? 'false');
9✔
78
  let demoArtifactPort = 85;
9✔
79
  let environmentData = {};
9✔
80
  let environmentFeatures = {};
9✔
81
  let versionInfo = {};
9✔
82
  if (mender_environment) {
9!
83
    const {
84
      features = {},
×
85
      demoArtifactPort: port,
86
      disableOnboarding,
87
      hostAddress,
88
      hostedAnnouncement,
89
      integrationVersion,
90
      isDemoMode,
91
      menderVersion,
92
      menderArtifactVersion,
93
      metaMenderVersion,
94
      recaptchaSiteKey,
95
      services = {},
×
96
      stripeAPIKey,
97
      trackerCode
98
    } = mender_environment;
9✔
99
    onboardingComplete = stringToBoolean(features.isEnterprise) || stringToBoolean(disableOnboarding) || onboardingComplete;
9✔
100
    demoArtifactPort = port || demoArtifactPort;
9✔
101
    environmentData = {
9✔
102
      hostedAnnouncement: hostedAnnouncement || state.app.hostedAnnouncement,
18✔
103
      hostAddress: hostAddress || state.app.hostAddress,
18✔
104
      recaptchaSiteKey: recaptchaSiteKey || state.app.recaptchaSiteKey,
18✔
105
      stripeAPIKey: stripeAPIKey || state.app.stripeAPIKey,
18✔
106
      trackerCode: trackerCode || state.app.trackerCode
18✔
107
    };
108
    environmentFeatures = {
9✔
109
      ...featureFlags.reduce((accu, flag) => ({ ...accu, [flag]: stringToBoolean(features[flag]) }), {}),
81✔
110
      // the check in features is purely kept as a local override, it shouldn't become relevant for production again
111
      isHosted: 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({ type: SUCCESSFULLY_LOGGED_IN, value: getSessionInfo() }),
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 }) => {
183✔
140
  if (!onboardingState.showTips || onboardingState.complete) {
4!
141
    return tasks;
4✔
142
  }
UNCOV
143
  const welcomeTip = getOnboardingComponentFor(onboardingSteps.ONBOARDING_START, {
×
144
    progress: onboardingState.progress,
145
    complete: onboardingState.complete,
146
    showTips: onboardingState.showTips
147
  });
UNCOV
148
  if (welcomeTip) {
×
UNCOV
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
UNCOV
154
  return devicesByStatus[DEVICE_STATES.accepted].deviceIds.reduce((accu, id) => {
×
UNCOV
155
    accu.push(dispatch(getDeviceById(id)));
×
UNCOV
156
    return accu;
×
157
  }, tasks);
158
};
159

160
const interpretAppData = () => (dispatch, getState) => {
183✔
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!
UNCOV
165
    settings.trackingConsentGiven = true;
×
166
  }
167
  let tasks = [
4✔
UNCOV
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!
UNCOV
181
    let attribute = id_attribute;
×
UNCOV
182
    if (attribute === 'Device ID') {
×
UNCOV
183
      attribute = 'id';
×
184
    }
UNCOV
185
    tasks.push(dispatch(saveGlobalSettings({ id_attribute: { attribute, scope: 'identity' } })));
×
186
  }
187
  return Promise.all(tasks);
4✔
188
};
189

190
const retrieveAppData = () => (dispatch, getState) => {
183✔
191
  let tasks = [
4✔
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());
4✔
211
  const multitenancy = hasMultitenancy || isHosted || getIsEnterprise(getState());
4✔
212
  if (multitenancy) {
4✔
213
    tasks.push(dispatch(getUserOrganization()));
3✔
214
  }
215
  return Promise.all(tasks);
4✔
216
};
217

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

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

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

248
const dateFunctionMap = {
183✔
249
  getDays: 'getDate',
250
  setDays: 'setDate'
251
};
252
export const setOfflineThreshold = () => (dispatch, getState) => {
183✔
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 {
UNCOV
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) =>
183✔
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+/);
183✔
281
const getLatestRelease = thing => {
183✔
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 = {
183✔
290
  integration: 'Integration',
291
  mender: 'Mender-Client',
292
  'mender-artifact': 'Mender-Artifact'
293
};
294

295
const deductSaasState = (latestRelease, guiTags, saasReleases) => {
183✔
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) => {
183✔
302
  if (!getState().app.features.isHosted) {
13✔
303
    return Promise.resolve();
9✔
304
  }
305
  return Promise.all([GeneralApi.get('/versions.json'), GeneralApi.get('/tags.json')])
4✔
306
    .catch(err => {
UNCOV
307
      console.log('init error:', extractErrorMessage(err));
×
UNCOV
308
      return Promise.resolve([{ data: {} }, { data: [] }]);
×
309
    })
310
    .then(([{ data }, { data: guiTags }]) => {
311
      if (!guiTags.length) {
4!
UNCOV
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) => {
183✔
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
        })
UNCOV
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