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

mendersoftware / mender-server / 1617695876

09 Jan 2025 10:24AM UTC coverage: 77.741% (+1.1%) from 76.61%
1617695876

Pull #253

gitlab-ci

mineralsfree
chore(gui): aligned tests with edit billing profile

Ticket: MEN-7466
Changelog: None

Signed-off-by: Mikita Pilinka <mikita.pilinka@northern.tech>
Pull Request #253: MEN-7466-feat: updated billing section in My Organization settings

4292 of 6243 branches covered (68.75%)

Branch coverage included in aggregate %.

46 of 68 new or added lines in 11 files covered. (67.65%)

1 existing line in 1 file now uncovered.

8543 of 10267 relevant lines covered (83.21%)

116.85 hits per line

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

80.0
/frontend/src/js/store/organizationSlice/thunks.ts
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
// @ts-nocheck
15
import storeActions from '@northern.tech/store/actions';
16
import Api from '@northern.tech/store/api/general-api';
17
import {
18
  AvailablePlans,
19
  DEVICE_LIST_DEFAULTS,
20
  SORTING_OPTIONS,
21
  TENANT_LIST_DEFAULT,
22
  TIMEOUTS,
23
  deviceAuthV2,
24
  headerNames,
25
  iotManagerBaseURL,
26
  locations
27
} from '@northern.tech/store/constants';
28
import { BillingProfile } from '@northern.tech/store/organizationSlice/types';
29
import { getCurrentSession, getTenantCapabilities, getTenantsList } from '@northern.tech/store/selectors';
30
import { commonErrorFallback, commonErrorHandler } from '@northern.tech/store/store';
31
import { getDeviceLimit, setFirstLoginAfterSignup } from '@northern.tech/store/thunks';
32
import { deepCompare } from '@northern.tech/utils/helpers';
33
import { createAsyncThunk } from '@reduxjs/toolkit';
34
import dayjs from 'dayjs';
35
import utc from 'dayjs/plugin/utc';
36
import { jwtDecode } from 'jwt-decode';
37
import hashString from 'md5';
38
import Cookies from 'universal-cookie';
39

40
import { actions, sliceName } from '.';
41
import { Tenant } from '../../components/tenants/types';
42
import { SSO_TYPES, auditLogsApiUrl, ssoIdpApiUrlv1, tenantadmApiUrlv1, tenantadmApiUrlv2 } from './constants';
43
import { getAuditlogState, getOrganization } from './selectors';
44

45
const cookies = new Cookies();
110✔
46

47
dayjs.extend(utc);
110✔
48
const { setAnnouncement, setSnackbar } = storeActions;
110✔
49
const { page: defaultPage, perPage: defaultPerPage } = DEVICE_LIST_DEFAULTS;
110✔
50

51
export const cancelRequest = createAsyncThunk(`${sliceName}/cancelRequest`, (reason, { dispatch, getState }) => {
110✔
52
  const { id: tenantId } = getOrganization(getState());
1✔
53
  return Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/cancel`, { reason }).then(() =>
1✔
54
    Promise.resolve(dispatch(setSnackbar({ message: 'Deactivation request was sent successfully', autoHideDuration: TIMEOUTS.fiveSeconds })))
1✔
55
  );
56
});
57

58
export const getTargetLocation = key => {
110✔
59
  if (devLocations.includes(window.location.hostname)) {
14✔
60
    return '';
6✔
61
  }
62
  let subdomainSections = window.location.hostname.substring(0, window.location.hostname.indexOf(locations.us.location)).split('.');
8✔
63
  subdomainSections = subdomainSections.splice(0, subdomainSections.length - 1);
8✔
64
  if (!subdomainSections.find(section => section === key)) {
8✔
65
    subdomainSections = key === locations.us.key ? subdomainSections.filter(section => !locations[section]) : [...subdomainSections, key];
7✔
66
    return `https://${[...subdomainSections, ...locations.us.location.split('.')].join('.')}`;
7✔
67
  }
68
  return `https://${window.location.hostname}`;
1✔
69
};
70

71
const devLocations = ['localhost', 'docker.mender.io'];
110✔
72
export const createOrganizationTrial = createAsyncThunk(`${sliceName}/createOrganizationTrial`, (data, { dispatch }) => {
110✔
73
  const { key } = locations[data.location];
2✔
74
  const targetLocation = getTargetLocation(key);
2✔
75
  const target = `${targetLocation}${tenantadmApiUrlv2}/tenants/trial`;
2✔
76
  return Api.postUnauthorized(target, data)
2✔
77
    .catch(err => {
78
      if (err.response.status >= 400 && err.response.status < 500) {
×
79
        dispatch(setSnackbar({ message: err.response.data.error, autoHideDuration: TIMEOUTS.fiveSeconds }));
×
80
        return Promise.reject(err);
×
81
      }
82
    })
83
    .then(({ headers }) => {
84
      cookies.remove('oauth');
2✔
85
      cookies.remove('externalID');
2✔
86
      cookies.remove('email');
2✔
87
      dispatch(setFirstLoginAfterSignup(true));
2✔
88
      return new Promise(resolve =>
2✔
89
        setTimeout(() => {
2✔
90
          window.location.assign(`${targetLocation}${headers.location || ''}`);
2✔
91
          return resolve();
2✔
92
        }, TIMEOUTS.fiveSeconds)
93
      );
94
    });
95
});
96

97
export const startCardUpdate = createAsyncThunk(`${sliceName}/startCardUpdate`, (_, { dispatch }) =>
110✔
98
  Api.post(`${tenantadmApiUrlv2}/billing/card`)
1✔
99
    .then(({ data }) => {
100
      dispatch(actions.receiveSetupIntent(data.intent_id));
1✔
101
      return Promise.resolve(data.secret);
1✔
102
    })
103
    .catch(err => commonErrorHandler(err, `Updating the card failed:`, dispatch))
×
104
);
105

106
export const confirmCardUpdate = createAsyncThunk(`${sliceName}/confirmCardUpdate`, (_, { dispatch, getState }) =>
110✔
107
  Api.post(`${tenantadmApiUrlv2}/billing/card/${getState().organization.intentId}/confirm`)
1✔
108
    .then(() => Promise.all([dispatch(setSnackbar('Payment card was updated successfully')), dispatch(actions.receiveSetupIntent(null))]))
1✔
109
    .catch(err => commonErrorHandler(err, `Updating the card failed:`, dispatch))
×
110
);
111

112
export const getCurrentCard = createAsyncThunk(`${sliceName}/getCurrentCard`, (_, { dispatch }) =>
110✔
113
  Api.get(`${tenantadmApiUrlv2}/billing`).then(res => {
3✔
114
    const { last4, exp_month, exp_year, brand } = res.data.card || {};
3!
115
    return Promise.resolve(dispatch(actions.receiveCurrentCard({ brand, last4, expiration: { month: exp_month, year: exp_year } })));
3✔
116
  })
117
);
118

119
export const startUpgrade = createAsyncThunk(`${sliceName}/startUpgrade`, (tenantId: string, { dispatch }) =>
110✔
120
  Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/upgrade/start`)
1✔
121
    .then(({ data }) => Promise.resolve(data.secret))
1✔
122
    .catch(err => commonErrorHandler(err, `There was an error upgrading your account:`, dispatch))
×
123
);
124

125
export const cancelUpgrade = createAsyncThunk(`${sliceName}/cancelUpgrade`, (tenantId: string) =>
110✔
126
  Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/upgrade/cancel`)
1✔
127
);
128

129
interface completeUpgradePayload {
130
  billing_profile: BillingProfile;
131
  plan: AvailablePlans;
132
  tenantId: string;
133
}
134
export const completeUpgrade = createAsyncThunk(`${sliceName}/completeUpgrade`, ({ tenantId, plan, billing_profile }: completeUpgradePayload, { dispatch }) =>
110✔
135
  Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/upgrade/complete`, { plan, billing_profile })
1✔
136
    .catch(err => commonErrorHandler(err, `There was an error upgrading your account:`, dispatch))
×
137
    .then(() => Promise.all([dispatch(getDeviceLimit()), dispatch(getUserOrganization())]))
1✔
138
);
139

140
const prepareAuditlogQuery = ({ startDate, endDate, user: userFilter, type, detail: detailFilter, sort = {} }) => {
110✔
141
  const userId = userFilter?.id || userFilter;
8✔
142
  const detail = detailFilter?.id || detailFilter;
8✔
143
  const createdAfter = startDate ? `&created_after=${dayjs.utc(startDate).unix()}` : '';
8✔
144
  const createdBefore = endDate ? `&created_before=${dayjs.utc(endDate).unix()}` : '';
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 = createAsyncThunk(`${sliceName}/getAuditLogs`, (selectionState, { dispatch, getState }) => {
110✔
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(({ data, headers }) => {
160
      let total = headers[headerNames.total];
6✔
161
      total = Number(total || data.length);
6!
162
      return Promise.resolve(dispatch(actions.receiveAuditLogs({ events: data, total })));
6✔
163
    })
164
    .catch(err => commonErrorHandler(err, `There was an error retrieving audit logs:`, dispatch));
×
165
});
166

167
export const getAuditLogsCsvLink = createAsyncThunk(`${sliceName}/getAuditLogsCsvLink`, (_, { getState }) =>
110✔
168
  Promise.resolve(`${window.location.origin}${auditLogsApiUrl}/logs/export?limit=20000${prepareAuditlogQuery(getAuditlogState(getState()))}`)
2✔
169
);
170

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

191
/*
192
  Tenant management + Hosted Mender
193
*/
194
export const tenantDataDivergedMessage = 'The system detected there is a change in your plan or purchased add-ons. Please log out and log in again';
110✔
195

196
export const addTenant = createAsyncThunk(`${sliceName}/createTenant`, (selectionState, { dispatch }) => {
110✔
197
  return Api.post(`${tenantadmApiUrlv2}/tenants`, selectionState)
4✔
198
    .then(() =>
199
      Promise.all([
3✔
200
        dispatch(setSnackbar('Tenant was created successfully.')),
201
        new Promise(resolve => setTimeout(() => resolve(dispatch(getTenants())), TIMEOUTS.oneSecond))
3✔
202
      ])
203
    )
204
    .catch(err => commonErrorHandler(err, 'There was an error creating tenant', dispatch, commonErrorFallback));
×
205
});
206

207
const tenantListRetrieval = async (config): Promise<[Tenant[], number]> => {
110✔
208
  const { page, perPage } = config;
6✔
209
  const params = new URLSearchParams({ page, per_page: perPage }).toString();
6✔
210
  const tenantList = await Api.get(`${tenantadmApiUrlv2}/tenants?${params}`);
6✔
211
  const totalCount = tenantList.headers[headerNames.total] || TENANT_LIST_DEFAULT.perPage;
6✔
212
  return [tenantList.data, Number(totalCount)];
4✔
213
};
214
export const getTenants = createAsyncThunk(`${sliceName}/getTenants`, async (_, { dispatch, getState }) => {
110✔
215
  const currentState = getTenantsList(getState());
6✔
216
  const [tenants, pageCount] = await tenantListRetrieval(currentState);
6✔
217
  dispatch(actions.setTenantListState({ ...currentState, total: pageCount, tenants }));
4✔
218
});
219

220
export const setTenantsListState = createAsyncThunk(`${sliceName}/setTenantsListState`, async (selectionState: any, { dispatch, getState }) => {
110✔
221
  const currentState = getTenantsList(getState());
×
222
  const nextState = {
×
223
    ...currentState,
224
    ...selectionState
225
  };
226
  if (!deepCompare(currentState, selectionState)) {
×
227
    const [tenants, pageCount] = await tenantListRetrieval(nextState);
×
228
    return dispatch(actions.setTenantListState({ ...nextState, tenants, total: pageCount }));
×
229
  }
230
  return dispatch(actions.setTenantListState({ ...nextState }));
×
231
});
232

233
interface editTenantBody {
234
  name: string;
235
  newLimit: number;
236
  id: string;
237
}
238
export const editTenantDeviceLimit = createAsyncThunk(`${sliceName}/editDeviceLimit`, ({ newLimit, id, name }: editTenantBody, { dispatch }) => {
110✔
239
  return Api.put(`${tenantadmApiUrlv2}/tenants/${id}/child`, { device_limit: newLimit, name })
2✔
240
    .catch(err => commonErrorHandler(err, `Device Limit cannot be changed`, dispatch))
×
241
    .then(() => {
242
      return Promise.all([
2✔
243
        dispatch(setSnackbar('Device Limit was changed successfully')),
244
        dispatch(getUserOrganization()),
245
        new Promise(resolve => setTimeout(() => resolve(dispatch(getTenants())), TIMEOUTS.oneSecond))
2✔
246
      ]);
247
    });
248
});
249
export const editBillingProfile = createAsyncThunk(
110✔
250
  `${sliceName}/editBillingProfileEmail`,
251
  ({ billingProfile }: { billingProfile: BillingProfile }, { dispatch }) =>
NEW
252
    Api.patch(`${tenantadmApiUrlv2}/billing/profile`, billingProfile)
×
NEW
253
      .catch(err => commonErrorHandler(err, `Failed to change billing profile`, dispatch))
×
NEW
254
      .then(() => Promise.all([dispatch(setSnackbar('Billing Profile was changed successfully')), dispatch(getUserBilling())]))
×
255
);
256
export const removeTenant = createAsyncThunk(`${sliceName}/editDeviceLimit`, ({ id }: { id: string }, { dispatch }) => {
110✔
257
  return Api.post(`${tenantadmApiUrlv2}/tenants/${id}/remove/start`)
×
258
    .catch(err => commonErrorHandler(err, `There was an error removing the tenant`, dispatch))
×
259
    .then(() =>
260
      Promise.all([
×
261
        dispatch(setSnackbar('The tenant was removed successfully')),
262
        dispatch(getUserOrganization()),
263
        new Promise(resolve => setTimeout(() => resolve(dispatch(getTenants())), TIMEOUTS.oneSecond))
×
264
      ])
265
    );
266
});
267
export const getUserOrganization = createAsyncThunk(`${sliceName}/getUserOrganization`, (_, { dispatch, getState }) => {
110✔
268
  return Api.get(`${tenantadmApiUrlv1}/user/tenant`).then(res => {
16✔
269
    let tasks = [dispatch(actions.setOrganization(res.data))];
15✔
270
    const { addons, plan, trial } = res.data;
10✔
271
    const { token } = getCurrentSession(getState());
10✔
272
    const jwt = jwtDecode(token);
10✔
273
    const jwtData = { addons: jwt['mender.addons'], plan: jwt['mender.plan'], trial: jwt['mender.trial'] };
10✔
274
    if (!deepCompare({ addons, plan, trial }, jwtData)) {
10!
275
      const hash = hashString(tenantDataDivergedMessage);
10✔
276
      cookies.remove(`${jwt.sub}${hash}`);
10✔
277
      tasks.push(dispatch(setAnnouncement(tenantDataDivergedMessage)));
10✔
278
    }
279
    return Promise.all(tasks);
10✔
280
  });
281
});
282
export const getUserBilling = createAsyncThunk(`${sliceName}/getUserBilling`, (_, { dispatch }) =>
110✔
283
  Api.get(`${tenantadmApiUrlv2}/billing/profile`).then(res => dispatch(actions.setBillingProfile(res.data)))
2✔
284
);
285

286
export const sendSupportMessage = createAsyncThunk(`${sliceName}/sendSupportMessage`, (content, { dispatch }) =>
110✔
287
  Api.post(`${tenantadmApiUrlv2}/contact/support`, content)
1✔
288
    .catch(err => commonErrorHandler(err, 'There was an error sending your request', dispatch, commonErrorFallback))
×
289
    .then(() => Promise.resolve(dispatch(setSnackbar({ message: 'Your request was sent successfully', autoHideDuration: TIMEOUTS.fiveSeconds }))))
1✔
290
);
291
interface requestPlanChangePayload {
292
  tenantId: string;
293
  content: {
294
    current_plan: string;
295
    requested_plan: string;
296
    current_addons: string;
297
    requested_addons: string;
298
    user_message: string;
299
  };
300
}
301
export const requestPlanChange = createAsyncThunk(
110✔
302
  `${sliceName}/requestPlanChange`,
303
  ({ content, tenantId }: requestPlanChangePayload, { dispatch, rejectWithValue }) =>
304
    Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/plan`, content)
5✔
305
      .catch(async err => {
306
        await commonErrorHandler(err, 'There was an error sending your request', dispatch, commonErrorFallback);
×
307
        rejectWithValue(err);
×
308
      })
309
      .then(() => Promise.resolve(dispatch(setSnackbar({ message: 'Your request was sent successfully', autoHideDuration: TIMEOUTS.fiveSeconds }))))
5✔
310
);
311

312
export const downloadLicenseReport = createAsyncThunk(`${sliceName}/downloadLicenseReport`, (_, { dispatch }) =>
110✔
313
  Api.get(`${deviceAuthV2}/reports/devices`)
1✔
314
    .catch(err => commonErrorHandler(err, 'There was an error downloading the report', dispatch, commonErrorFallback))
×
315
    .then(res => res.data)
1✔
316
);
317

318
// eslint-disable-next-line @typescript-eslint/no-unused-vars
319
export const createIntegration = createAsyncThunk(`${sliceName}/createIntegration`, ({ id, ...integration }, { dispatch }) =>
110✔
320
  Api.post(`${iotManagerBaseURL}/integrations`, integration)
1✔
321
    .catch(err => commonErrorHandler(err, 'There was an error creating the integration', dispatch, commonErrorFallback))
×
322
    .then(() => Promise.all([dispatch(setSnackbar('The integration was set up successfully')), dispatch(getIntegrations())]))
1✔
323
);
324

325
export const changeIntegration = createAsyncThunk(`${sliceName}/changeIntegration`, ({ id, credentials }, { dispatch }) =>
110✔
326
  Api.put(`${iotManagerBaseURL}/integrations/${id}/credentials`, credentials)
1✔
327
    .catch(err => commonErrorHandler(err, 'There was an error updating the integration', dispatch, commonErrorFallback))
×
328
    .then(() => Promise.all([dispatch(setSnackbar('The integration was updated successfully')), dispatch(getIntegrations())]))
1✔
329
);
330

331
export const deleteIntegration = createAsyncThunk(`${sliceName}/deleteIntegration`, ({ id, provider }, { dispatch, getState }) =>
110✔
332
  Api.delete(`${iotManagerBaseURL}/integrations/${id}`, {})
1✔
333
    .catch(err => commonErrorHandler(err, 'There was an error removing the integration', dispatch, commonErrorFallback))
×
334
    .then(() => {
335
      const integrations = getState().organization.externalDeviceIntegrations.filter(item => provider !== item.provider);
1✔
336
      return Promise.all([
1✔
337
        dispatch(setSnackbar('The integration was removed successfully')),
338
        dispatch(actions.receiveExternalDeviceIntegrations(integrations))
339
      ]);
340
    })
341
);
342

343
export const getIntegrations = createAsyncThunk(`${sliceName}/getIntegrations`, (_, { dispatch, getState }) =>
110✔
344
  Api.get(`${iotManagerBaseURL}/integrations`)
10✔
345
    .catch(err => commonErrorHandler(err, 'There was an error retrieving the integration', dispatch, commonErrorFallback))
×
346
    .then(({ data }) => {
347
      const existingIntegrations = getState().organization.externalDeviceIntegrations;
10✔
348
      const integrations = data.reduce((accu, item) => {
10✔
349
        const existingIntegration = existingIntegrations.find(integration => item.id === integration.id) ?? {};
20✔
350
        const integration = { ...existingIntegration, ...item };
20✔
351
        accu.push(integration);
20✔
352
        return accu;
20✔
353
      }, []);
354
      return Promise.resolve(dispatch(actions.receiveExternalDeviceIntegrations(integrations)));
10✔
355
    })
356
);
357

358
export const getWebhookEvents = createAsyncThunk(`${sliceName}/getWebhookEvents`, (config = {}, { dispatch, getState }) => {
110✔
359
  const { isFollowUp, page = defaultPage, perPage = defaultPerPage } = config;
4✔
360
  return Api.get(`${iotManagerBaseURL}/events?page=${page}&per_page=${perPage}`)
4✔
361
    .catch(err => commonErrorHandler(err, 'There was an error retrieving activity for this integration', dispatch, commonErrorFallback))
×
362
    .then(({ data }) => {
363
      let tasks = [
4✔
364
        dispatch(
365
          actions.receiveWebhookEvents({
366
            value: isFollowUp ? getState().organization.webhooks.events : data,
4✔
367
            total: (page - 1) * perPage + data.length
368
          })
369
        )
370
      ];
371
      if (data.length >= perPage && !isFollowUp) {
4✔
372
        tasks.push(dispatch(getWebhookEvents({ isFollowUp: true, page: page + 1, perPage: 1 })));
1✔
373
      }
374
      return Promise.all(tasks);
4✔
375
    });
376
});
377

378
const ssoConfigActions = {
110✔
379
  create: { success: 'stored', error: 'storing' },
380
  edit: { success: 'updated', error: 'updating' },
381
  read: { success: '', error: 'retrieving' },
382
  remove: { success: 'removed', error: 'removing' },
383
  readMultiple: { success: '', error: 'retrieving' }
384
};
385

386
const ssoConfigActionErrorHandler = (err, type) => dispatch =>
110✔
387
  commonErrorHandler(err, `There was an error ${ssoConfigActions[type].error} the SSO configuration.`, dispatch, commonErrorFallback);
×
388

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

391
export const storeSsoConfig = createAsyncThunk(`${sliceName}/storeSsoConfig`, ({ config, contentType }, { dispatch }) =>
110✔
392
  Api.post(ssoIdpApiUrlv1, config, { headers: { 'Content-Type': contentType, Accept: 'application/json' } })
1✔
393
    .catch(err => dispatch(ssoConfigActionErrorHandler(err, 'create')))
×
394
    .then(() => Promise.all([dispatch(ssoConfigActionSuccessHandler('create')), dispatch(getSsoConfigs())]))
1✔
395
);
396

397
export const changeSsoConfig = createAsyncThunk(`${sliceName}/changeSsoConfig`, ({ config, contentType }, { dispatch }) =>
110✔
398
  Api.put(`${ssoIdpApiUrlv1}/${config.id}`, config, { headers: { 'Content-Type': contentType, Accept: 'application/json' } })
1✔
399
    .catch(err => dispatch(ssoConfigActionErrorHandler(err, 'edit')))
×
400
    .then(() => Promise.all([dispatch(ssoConfigActionSuccessHandler('edit')), dispatch(getSsoConfigs())]))
1✔
401
);
402

403
export const deleteSsoConfig = createAsyncThunk(`${sliceName}/deleteSsoConfig`, ({ id }, { dispatch, getState }) =>
110✔
404
  Api.delete(`${ssoIdpApiUrlv1}/${id}`)
1✔
405
    .catch(err => dispatch(ssoConfigActionErrorHandler(err, 'remove')))
×
406
    .then(() => {
407
      const configs = getState().organization.ssoConfigs.filter(item => id !== item.id);
2✔
408
      return Promise.all([dispatch(ssoConfigActionSuccessHandler('remove')), dispatch(actions.receiveSsoConfigs(configs))]);
1✔
409
    })
410
);
411

412
export const getSsoConfigById = createAsyncThunk(`${sliceName}/getSsoConfigById`, (config, { dispatch }) =>
110✔
413
  Api.get(`${ssoIdpApiUrlv1}/${config.id}`)
10✔
414
    .catch(err => dispatch(ssoConfigActionErrorHandler(err, 'read')))
×
415
    .then(({ data, headers }) => {
416
      const sso = Object.values(SSO_TYPES).find(({ contentType }) => contentType === headers['content-type']);
20✔
417
      return sso ? Promise.resolve({ ...config, config: data, type: sso.id }) : Promise.reject('Unsupported SSO config content type.');
10!
418
    })
419
);
420

421
export const getSsoConfigs = createAsyncThunk(`${sliceName}/getSsoConfigs`, (_, { dispatch }) =>
110✔
422
  Api.get(ssoIdpApiUrlv1)
5✔
423
    .catch(err => dispatch(ssoConfigActionErrorHandler(err, 'readMultiple')))
×
424
    .then(({ data }) =>
425
      Promise.all(data.map(config => dispatch(getSsoConfigById(config)).unwrap()))
10✔
426
        .then(configs => dispatch(actions.receiveSsoConfigs(configs)))
5✔
427
        .catch(err => commonErrorHandler(err, err, dispatch, ''))
×
428
    )
429
);
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