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

mendersoftware / gui / 1350829378

27 Jun 2024 01:46PM UTC coverage: 83.494% (-16.5%) from 99.965%
1350829378

Pull #4465

gitlab-ci

mzedel
chore: test fixes

Signed-off-by: Manuel Zedel <manuel.zedel@northern.tech>
Pull Request #4465: MEN-7169 - feat: added multi sorting capabilities to devices view

4506 of 6430 branches covered (70.08%)

81 of 100 new or added lines in 14 files covered. (81.0%)

1661 existing lines in 163 files now uncovered.

8574 of 10269 relevant lines covered (83.49%)

160.6 hits per line

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

87.15
/src/js/actions/organizationActions.js
1
// Copyright 2020 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 { jwtDecode } from 'jwt-decode';
15
import hashString from 'md5';
16
import Cookies from 'universal-cookie';
17

18
import Api, { apiUrl, headerNames } from '../api/general-api';
19
import { SET_ANNOUNCEMENT, SORTING_OPTIONS, TIMEOUTS, locations } from '../constants/appConstants';
20
import { DEVICE_LIST_DEFAULTS } from '../constants/deviceConstants';
21
import {
22
  RECEIVE_AUDIT_LOGS,
23
  RECEIVE_CURRENT_CARD,
24
  RECEIVE_EXTERNAL_DEVICE_INTEGRATIONS,
25
  RECEIVE_SETUP_INTENT,
26
  RECEIVE_SSO_CONFIGS,
27
  RECEIVE_WEBHOOK_EVENTS,
28
  SET_AUDITLOG_STATE,
29
  SET_ORGANIZATION,
30
  SSO_TYPES
31
} from '../constants/organizationConstants';
32
import { deepCompare } from '../helpers';
33
import { getCurrentSession, getTenantCapabilities } from '../selectors';
34
import { commonErrorFallback, commonErrorHandler, setFirstLoginAfterSignup, setSnackbar } from './appActions';
35
import { deviceAuthV2, iotManagerBaseURL } from './deviceActions';
36

37
const cookies = new Cookies();
184✔
38
export const auditLogsApiUrl = `${apiUrl.v1}/auditlogs`;
184✔
39
export const tenantadmApiUrlv1 = `${apiUrl.v1}/tenantadm`;
184✔
40
export const tenantadmApiUrlv2 = `${apiUrl.v2}/tenantadm`;
184✔
41
export const ssoIdpApiUrlv1 = `${apiUrl.v1}/useradm/sso/idp/metadata`;
184✔
42

43
const { page: defaultPage, perPage: defaultPerPage } = DEVICE_LIST_DEFAULTS;
184✔
44

45
export const cancelRequest = (tenantId, reason) => dispatch =>
184✔
46
  Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/cancel`, { reason: reason }).then(() =>
1✔
47
    Promise.resolve(dispatch(setSnackbar('Deactivation request was sent successfully', TIMEOUTS.fiveSeconds, '')))
1✔
48
  );
49

50
export const getTargetLocation = key => {
184✔
51
  if (devLocations.includes(window.location.hostname)) {
14✔
52
    return '';
6✔
53
  }
54
  let subdomainSections = window.location.hostname.substring(0, window.location.hostname.indexOf(locations.us.location)).split('.');
8✔
55
  subdomainSections = subdomainSections.splice(0, subdomainSections.length - 1);
8✔
56
  if (!subdomainSections.find(section => section === key)) {
8✔
57
    subdomainSections = key === locations.us.key ? subdomainSections.filter(section => !locations[section]) : [...subdomainSections, key];
7✔
58
    return `https://${[...subdomainSections, ...locations.us.location.split('.')].join('.')}`;
7✔
59
  }
60
  return `https://${window.location.hostname}`;
1✔
61
};
62

63
const devLocations = ['localhost', 'docker.mender.io'];
184✔
64
export const createOrganizationTrial = data => dispatch => {
184✔
65
  const { key } = locations[data.location];
2✔
66
  const targetLocation = getTargetLocation(key);
2✔
67
  const target = `${targetLocation}${tenantadmApiUrlv2}/tenants/trial`;
2✔
68
  return Api.postUnauthorized(target, data)
2✔
69
    .catch(err => {
UNCOV
70
      if (err.response.status >= 400 && err.response.status < 500) {
×
UNCOV
71
        dispatch(setSnackbar(err.response.data.error, TIMEOUTS.fiveSeconds, ''));
×
UNCOV
72
        return Promise.reject(err);
×
73
      }
74
    })
75
    .then(({ headers }) => {
76
      cookies.remove('oauth');
2✔
77
      cookies.remove('externalID');
2✔
78
      cookies.remove('email');
2✔
79
      dispatch(setFirstLoginAfterSignup(true));
2✔
80
      return new Promise(resolve =>
2✔
81
        setTimeout(() => {
2✔
82
          window.location.assign(`${targetLocation}${headers.location || ''}`);
1✔
83
          return resolve();
1✔
84
        }, TIMEOUTS.fiveSeconds)
85
      );
86
    });
87
};
88

89
export const startCardUpdate = () => dispatch =>
184✔
90
  Api.post(`${tenantadmApiUrlv2}/billing/card`)
1✔
91
    .then(res => {
92
      dispatch({
1✔
93
        type: RECEIVE_SETUP_INTENT,
94
        intentId: res.data.intent_id
95
      });
96
      return Promise.resolve(res.data.secret);
1✔
97
    })
UNCOV
98
    .catch(err => commonErrorHandler(err, `Updating the card failed:`, dispatch));
×
99

100
export const confirmCardUpdate = () => (dispatch, getState) =>
184✔
101
  Api.post(`${tenantadmApiUrlv2}/billing/card/${getState().organization.intentId}/confirm`)
1✔
102
    .then(() =>
103
      Promise.all([
1✔
104
        dispatch(setSnackbar('Payment card was updated successfully')),
105
        dispatch({
106
          type: RECEIVE_SETUP_INTENT,
107
          intentId: null
108
        })
109
      ])
110
    )
UNCOV
111
    .catch(err => commonErrorHandler(err, `Updating the card failed:`, dispatch));
×
112

113
export const getCurrentCard = () => dispatch =>
184✔
114
  Api.get(`${tenantadmApiUrlv2}/billing`).then(res => {
2✔
115
    const { last4, exp_month, exp_year, brand } = res.data.card || {};
2!
116
    return Promise.resolve(
2✔
117
      dispatch({
118
        type: RECEIVE_CURRENT_CARD,
119
        card: {
120
          brand,
121
          last4,
122
          expiration: { month: exp_month, year: exp_year }
123
        }
124
      })
125
    );
126
  });
127

128
export const startUpgrade = tenantId => dispatch =>
184✔
129
  Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/upgrade/start`)
1✔
130
    .then(({ data }) => Promise.resolve(data.secret))
1✔
UNCOV
131
    .catch(err => commonErrorHandler(err, `There was an error upgrading your account:`, dispatch));
×
132

133
export const cancelUpgrade = tenantId => () => Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/upgrade/cancel`);
184✔
134

135
export const completeUpgrade = (tenantId, plan) => dispatch =>
184✔
136
  Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/upgrade/complete`, { plan })
1✔
UNCOV
137
    .catch(err => commonErrorHandler(err, `There was an error upgrading your account:`, dispatch))
×
138
    .then(() => Promise.resolve(dispatch(getUserOrganization())));
1✔
139

140
const prepareAuditlogQuery = ({ startDate, endDate, user: userFilter, type, detail: detailFilter, sort = {} }) => {
184✔
141
  const userId = userFilter?.id || userFilter;
8✔
142
  const detail = detailFilter?.id || detailFilter;
8✔
143
  const createdAfter = startDate ? `&created_after=${Math.round(Date.parse(startDate) / 1000)}` : '';
8✔
144
  const createdBefore = endDate ? `&created_before=${Math.round(Date.parse(endDate) / 1000)}` : '';
8✔
145
  const typeSearch = type ? `&object_type=${type.value}`.toLowerCase() : '';
8!
146
  const userSearch = userId ? `&actor_id=${userId}` : '';
8!
147
  const objectSearch = type && detail ? `&${type.queryParameter}=${encodeURIComponent(detail)}` : '';
8!
148
  const { direction = SORTING_OPTIONS.desc } = sort;
8✔
149
  return `${createdAfter}${createdBefore}${userSearch}${typeSearch}${objectSearch}&sort=${direction}`;
8✔
150
};
151

152
export const getAuditLogs = selectionState => (dispatch, getState) => {
184✔
153
  const { page, perPage } = selectionState;
7✔
154
  const { hasAuditlogs } = getTenantCapabilities(getState());
7✔
155
  if (!hasAuditlogs) {
7✔
156
    return Promise.resolve();
1✔
157
  }
158
  return Api.get(`${auditLogsApiUrl}/logs?page=${page}&per_page=${perPage}${prepareAuditlogQuery(selectionState)}`)
6✔
159
    .then(res => {
160
      let total = res.headers[headerNames.total];
6✔
161
      total = Number(total || res.data.length);
6!
162
      return Promise.resolve(dispatch({ type: RECEIVE_AUDIT_LOGS, events: res.data, total }));
6✔
163
    })
UNCOV
164
    .catch(err => commonErrorHandler(err, `There was an error retrieving audit logs:`, dispatch));
×
165
};
166

167
export const getAuditLogsCsvLink = () => (dispatch, getState) =>
184✔
168
  Promise.resolve(`${auditLogsApiUrl}/logs/export?limit=20000${prepareAuditlogQuery(getState().organization.auditlog.selectionState)}`);
2✔
169

170
export const setAuditlogsState = selectionState => (dispatch, getState) => {
184✔
171
  const currentState = getState().organization.auditlog.selectionState;
8✔
172
  let nextState = {
8✔
173
    ...currentState,
174
    ...selectionState,
175
    sort: { ...currentState.sort, ...selectionState.sort }
176
  };
177
  let tasks = [];
8✔
178
  // eslint-disable-next-line no-unused-vars
179
  const { isLoading: currentLoading, selectedIssue: currentIssue, ...currentRequestState } = currentState;
8✔
180
  // eslint-disable-next-line no-unused-vars
181
  const { isLoading: selectionLoading, selectedIssue: selectionIssue, ...selectionRequestState } = nextState;
8✔
182
  if (!deepCompare(currentRequestState, selectionRequestState)) {
8✔
183
    nextState.isLoading = true;
4✔
184
    tasks.push(dispatch(getAuditLogs(nextState)).finally(() => dispatch(setAuditlogsState({ isLoading: false }))));
4✔
185
  }
186
  tasks.push(dispatch({ type: SET_AUDITLOG_STATE, state: nextState }));
8✔
187
  return Promise.all(tasks);
8✔
188
};
189

190
/*
191
  Tenant management + Hosted Mender
192
*/
193
export const tenantDataDivergedMessage = 'The system detected there is a change in your plan or purchased add-ons. Please log out and log in again';
184✔
194
export const getUserOrganization = () => (dispatch, getState) =>
184✔
195
  Api.get(`${tenantadmApiUrlv1}/user/tenant`).then(res => {
15✔
196
    let tasks = [dispatch({ type: SET_ORGANIZATION, organization: res.data })];
14✔
197
    const { addons, plan, trial } = res.data;
14✔
198
    const { token } = getCurrentSession(getState());
14✔
199
    const jwt = jwtDecode(token);
14✔
200
    const jwtData = { addons: jwt['mender.addons'], plan: jwt['mender.plan'], trial: jwt['mender.trial'] };
14✔
201
    if (!deepCompare({ addons, plan, trial }, jwtData)) {
14!
202
      const hash = hashString(tenantDataDivergedMessage);
14✔
203
      cookies.remove(`${jwt.sub}${hash}`);
14✔
204
      tasks.push(dispatch({ type: SET_ANNOUNCEMENT, announcement: tenantDataDivergedMessage }));
14✔
205
    }
206
    return Promise.all(tasks);
14✔
207
  });
208

209
export const sendSupportMessage = content => dispatch =>
184✔
210
  Api.post(`${tenantadmApiUrlv2}/contact/support`, content)
1✔
UNCOV
211
    .catch(err => commonErrorHandler(err, 'There was an error sending your request', dispatch, commonErrorFallback))
×
212
    .then(() => Promise.resolve(dispatch(setSnackbar('Your request was sent successfully', TIMEOUTS.fiveSeconds, ''))));
1✔
213

214
export const requestPlanChange = (tenantId, content) => dispatch =>
184✔
215
  Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/plan`, content)
1✔
UNCOV
216
    .catch(err => commonErrorHandler(err, 'There was an error sending your request', dispatch, commonErrorFallback))
×
217
    .then(() => Promise.resolve(dispatch(setSnackbar('Your request was sent successfully', TIMEOUTS.fiveSeconds, ''))));
1✔
218

219
export const downloadLicenseReport = () => dispatch =>
184✔
220
  Api.get(`${deviceAuthV2}/reports/devices`)
1✔
UNCOV
221
    .catch(err => commonErrorHandler(err, 'There was an error downloading the report', dispatch, commonErrorFallback))
×
222
    .then(res => res.data);
1✔
223

224
export const createIntegration = integration => dispatch => {
184✔
225
  // eslint-disable-next-line no-unused-vars
226
  const { credentials, id, provider, ...remainder } = integration;
1✔
227
  return Api.post(`${iotManagerBaseURL}/integrations`, { provider, credentials, ...remainder })
1✔
UNCOV
228
    .catch(err => commonErrorHandler(err, 'There was an error creating the integration', dispatch, commonErrorFallback))
×
229
    .then(() => Promise.all([dispatch(setSnackbar('The integration was set up successfully')), dispatch(getIntegrations())]));
1✔
230
};
231

232
export const changeIntegration = integration => dispatch =>
184✔
233
  Api.put(`${iotManagerBaseURL}/integrations/${integration.id}/credentials`, integration.credentials)
1✔
UNCOV
234
    .catch(err => commonErrorHandler(err, 'There was an error updating the integration', dispatch, commonErrorFallback))
×
235
    .then(() => Promise.all([dispatch(setSnackbar('The integration was updated successfully')), dispatch(getIntegrations())]));
1✔
236

237
export const deleteIntegration = integration => (dispatch, getState) =>
184✔
238
  Api.delete(`${iotManagerBaseURL}/integrations/${integration.id}`, {})
1✔
UNCOV
239
    .catch(err => commonErrorHandler(err, 'There was an error removing the integration', dispatch, commonErrorFallback))
×
240
    .then(() => {
241
      const integrations = getState().organization.externalDeviceIntegrations.filter(item => integration.provider !== item.provider);
1✔
242
      return Promise.all([
1✔
243
        dispatch(setSnackbar('The integration was removed successfully')),
244
        dispatch({ type: RECEIVE_EXTERNAL_DEVICE_INTEGRATIONS, value: integrations })
245
      ]);
246
    });
247

248
export const getIntegrations = () => (dispatch, getState) =>
184✔
249
  Api.get(`${iotManagerBaseURL}/integrations`)
17✔
UNCOV
250
    .catch(err => commonErrorHandler(err, 'There was an error retrieving the integration', dispatch, commonErrorFallback))
×
251
    .then(({ data }) => {
252
      const existingIntegrations = getState().organization.externalDeviceIntegrations;
17✔
253
      const integrations = data.reduce((accu, item) => {
17✔
254
        const existingIntegration = existingIntegrations.find(integration => item.id === integration.id) ?? {};
34✔
255
        const integration = { ...existingIntegration, ...item };
34✔
256
        accu.push(integration);
34✔
257
        return accu;
34✔
258
      }, []);
259
      return Promise.resolve(dispatch({ type: RECEIVE_EXTERNAL_DEVICE_INTEGRATIONS, value: integrations }));
17✔
260
    });
261

262
export const getWebhookEvents =
263
  (config = {}) =>
184✔
264
  (dispatch, getState) => {
3✔
265
    const { isFollowUp, page = defaultPage, perPage = defaultPerPage } = config;
3✔
266
    return Api.get(`${iotManagerBaseURL}/events?page=${page}&per_page=${perPage}`)
3✔
UNCOV
267
      .catch(err => commonErrorHandler(err, 'There was an error retrieving activity for this integration', dispatch, commonErrorFallback))
×
268
      .then(({ data }) => {
269
        let tasks = [
3✔
270
          dispatch({
271
            type: RECEIVE_WEBHOOK_EVENTS,
272
            value: isFollowUp ? getState().organization.webhooks.events : data,
3✔
273
            total: (page - 1) * perPage + data.length
274
          })
275
        ];
276
        if (data.length >= perPage && !isFollowUp) {
3✔
277
          tasks.push(dispatch(getWebhookEvents({ isFollowUp: true, page: page + 1, perPage: 1 })));
1✔
278
        }
279
        return Promise.all(tasks);
3✔
280
      });
281
  };
282

283
const ssoConfigActions = {
184✔
284
  create: { success: 'stored', error: 'storing' },
285
  edit: { success: 'updated', error: 'updating' },
286
  read: { success: '', error: 'retrieving' },
287
  remove: { success: 'removed', error: 'removing' }
288
};
289

290
const ssoConfigActionErrorHandler = (err, type) => dispatch =>
184✔
UNCOV
291
  commonErrorHandler(err, `There was an error ${ssoConfigActions[type].error} the SSO configuration.`, dispatch, commonErrorFallback);
×
292

293
const ssoConfigActionSuccessHandler = type => dispatch => dispatch(setSnackbar(`The SSO configuration was ${ssoConfigActions[type].success} successfully`));
184✔
294

295
export const storeSsoConfig =
296
  ({ config, contentType }) =>
184✔
297
  dispatch =>
1✔
298
    Api.post(ssoIdpApiUrlv1, config, { headers: { 'Content-Type': contentType, Accept: 'application/json' } })
1✔
UNCOV
299
      .catch(err => dispatch(ssoConfigActionErrorHandler(err, 'create')))
×
300
      .then(() => Promise.all([dispatch(ssoConfigActionSuccessHandler('create')), dispatch(getSsoConfigs())]));
1✔
301

302
export const changeSsoConfig =
303
  ({ id, config, contentType }) =>
184✔
304
  dispatch =>
1✔
305
    Api.put(`${ssoIdpApiUrlv1}/${id}`, config, { headers: { 'Content-Type': contentType, Accept: 'application/json' } })
1✔
UNCOV
306
      .catch(err => dispatch(ssoConfigActionErrorHandler(err, 'edit')))
×
307
      .then(() => Promise.all([dispatch(ssoConfigActionSuccessHandler('edit')), dispatch(getSsoConfigs())]));
1✔
308

309
export const deleteSsoConfig =
310
  ({ id }) =>
184✔
311
  (dispatch, getState) =>
1✔
312
    Api.delete(`${ssoIdpApiUrlv1}/${id}`)
1✔
UNCOV
313
      .catch(err => dispatch(ssoConfigActionErrorHandler(err, 'remove')))
×
314
      .then(() => {
315
        const configs = getState().organization.ssoConfigs.filter(item => id !== item.id);
2✔
316
        return Promise.all([dispatch(ssoConfigActionSuccessHandler('remove')), dispatch({ type: RECEIVE_SSO_CONFIGS, value: configs })]);
1✔
317
      });
318

319
const getSsoConfigById = config => dispatch =>
184✔
320
  Api.get(`${ssoIdpApiUrlv1}/${config.id}`)
10✔
UNCOV
321
    .catch(err => dispatch(ssoConfigActionErrorHandler(err, 'read')))
×
322
    .then(({ data, headers }) => {
323
      const sso = Object.values(SSO_TYPES).find(({ contentType }) => contentType === headers['content-type']);
20✔
324
      return sso ? Promise.resolve({ ...config, config: data, type: sso.id }) : Promise.reject('Unsupported SSO config content type.');
10!
325
    });
326

327
export const getSsoConfigs = () => dispatch =>
184✔
328
  Api.get(ssoIdpApiUrlv1)
5✔
UNCOV
329
    .catch(err => commonErrorHandler(err, 'There was an error retrieving SSO configurations', dispatch, commonErrorFallback))
×
330
    .then(({ data }) =>
331
      Promise.all(data.map(config => Promise.resolve(dispatch(getSsoConfigById(config)))))
10✔
332
        .then(configs => dispatch({ type: RECEIVE_SSO_CONFIGS, value: configs }))
5✔
UNCOV
333
        .catch(err => commonErrorHandler(err, err, dispatch, ''))
×
334
    );
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