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

mendersoftware / gui / 914712491

pending completion
914712491

Pull #3798

gitlab-ci

mzedel
refac: refactored signup page to make better use of form capabilities

Signed-off-by: Manuel Zedel <manuel.zedel@northern.tech>
Pull Request #3798: MEN-3530 - refactored forms

4359 of 6322 branches covered (68.95%)

92 of 99 new or added lines in 11 files covered. (92.93%)

1715 existing lines in 159 files now uncovered.

8203 of 9941 relevant lines covered (82.52%)

150.06 hits per line

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

69.93
/src/js/components/deployments/report.js
1
// Copyright 2015 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 React, { useEffect, useRef, useState } from 'react';
15
import { useDispatch, useSelector } from 'react-redux';
16

17
// material ui
18
import {
19
  Block as BlockIcon,
20
  CheckCircleOutline as CheckCircleOutlineIcon,
21
  Close as CloseIcon,
22
  Link as LinkIcon,
23
  Refresh as RefreshIcon
24
} from '@mui/icons-material';
25
import { Button, Divider, Drawer, IconButton, Tooltip } from '@mui/material';
26
import { makeStyles } from 'tss-react/mui';
27

28
import copy from 'copy-to-clipboard';
29
import moment from 'moment';
30
import momentDurationFormatSetup from 'moment-duration-format';
31

32
import { setSnackbar } from '../../actions/appActions';
33
import { getDeploymentDevices, getDeviceLog, getSingleDeployment, updateDeploymentControlMap } from '../../actions/deploymentActions';
34
import { getDeviceAuth, getDeviceById } from '../../actions/deviceActions';
35
import { getAuditLogs } from '../../actions/organizationActions';
36
import { getRelease } from '../../actions/releaseActions';
37
import { TIMEOUTS } from '../../constants/appConstants';
38
import { DEPLOYMENT_STATES, DEPLOYMENT_TYPES, deploymentStatesToSubstates } from '../../constants/deploymentConstants';
39
import { AUDIT_LOGS_TYPES } from '../../constants/organizationConstants';
40
import { statCollector, toggle } from '../../helpers';
41
import { getDevicesById, getIdAttribute, getTenantCapabilities, getUserCapabilities } from '../../selectors';
42
import ConfigurationObject from '../common/configurationobject';
43
import Confirm from '../common/confirm';
44
import LogDialog from '../common/dialogs/log';
45
import LinedHeader from '../common/lined-header';
46
import DeploymentStatus, { DeploymentPhaseNotification } from './deployment-report/deploymentstatus';
47
import DeviceList from './deployment-report/devicelist';
48
import DeploymentOverview from './deployment-report/overview';
49
import RolloutSchedule from './deployment-report/rolloutschedule';
50

51
momentDurationFormatSetup(moment);
11✔
52

53
const useStyles = makeStyles()(theme => ({
11✔
54
  divider: { marginTop: theme.spacing(2) },
55
  header: {
56
    ['&.dashboard-header span']: {
57
      backgroundColor: theme.palette.background.paper,
58
      backgroundImage: 'linear-gradient(rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0.15))'
59
    }
60
  }
61
}));
62

63
export const defaultColumnDataProps = {
11✔
64
  chipLikeKey: false,
65
  style: { alignItems: 'center', alignSelf: 'flex-start', gridTemplateColumns: 'minmax(140px, 1fr) minmax(220px, 1fr)', maxWidth: '25vw' }
66
};
67

68
export const DeploymentAbortButton = ({ abort, deployment }) => {
11✔
69
  const [aborting, setAborting] = useState(false);
4✔
70

71
  const toggleAborting = () => setAborting(toggle);
4✔
72

73
  return aborting ? (
4!
UNCOV
74
    <Confirm cancel={toggleAborting} action={() => abort(deployment.id)} type="abort" />
×
75
  ) : (
76
    <Tooltip
77
      title="Devices that have not yet started the deployment will not start the deployment.&#10;Devices that have already completed the deployment are not affected by the abort.&#10;Devices that are in the middle of the deployment at the time of abort will finish deployment normally, but will perform a rollback."
78
      placement="bottom"
79
    >
80
      <Button color="secondary" startIcon={<BlockIcon fontSize="small" />} onClick={toggleAborting}>
81
        {deployment.filters?.length ? 'Stop' : 'Abort'} deployment
4!
82
      </Button>
83
    </Tooltip>
84
  );
85
};
86

87
export const DeploymentReport = ({ abort, open, onClose, past, retry, type }) => {
11✔
88
  const [deviceId, setDeviceId] = useState('');
276✔
89
  const rolloutSchedule = useRef();
276✔
90
  const timer = useRef();
276✔
91
  const { classes } = useStyles();
276✔
92
  const dispatch = useDispatch();
276✔
93
  const { deployment, selectedDevices, selectedDeviceIds } = useSelector(state => {
276✔
94
    const deployment = state.deployments.byId[state.deployments.selectionState.selectedId] || {};
489✔
95
    const { devices = {} } = deployment;
489✔
96
    const { selectedDeviceIds } = state.deployments;
489✔
97
    return {
489✔
98
      deployment,
99
      selectedDevices: selectedDeviceIds.map(deviceId => ({ ...state.devices.byId[deviceId], ...devices[deviceId] })),
1✔
100
      selectedDeviceIds
101
    };
102
  });
103
  const devicesById = useSelector(getDevicesById);
276✔
104
  const { attribute: idAttribute } = useSelector(getIdAttribute);
276✔
105
  const release = useSelector(state => {
276✔
106
    const deployment = state.deployments.byId[state.deployments.selectionState.selectedId] || {};
489✔
107
    return deployment.artifact_name && state.releases.byId[deployment.artifact_name]
489✔
108
      ? state.releases.byId[deployment.artifact_name]
109
      : { device_types_compatible: [] };
110
  });
111
  const tenantCapabilities = useSelector(getTenantCapabilities);
276✔
112
  const userCapabilities = useSelector(getUserCapabilities);
276✔
113
  // we can't filter by auditlog action via the api, so
114
  // - fall back to the following filter
115
  // - hope the deployment creation event is retrieved with the call to auditlogs api on report open
116
  // - otherwise no creator will be shown
117
  const { actor = {} } =
276✔
118
    useSelector(state =>
276✔
119
      state.organization.auditlog.events.find(event => event.object.id === state.deployments.selectionState.selectedId && event.action === 'create')
1,467!
120
    ) || {};
121
  const creator = actor.email;
276✔
122

123
  const { canAuditlog } = userCapabilities;
276✔
124
  const { hasAuditlogs } = tenantCapabilities;
276✔
125
  const { devices = {}, device_count, statistics = {}, type: deploymentType } = deployment;
276✔
126
  const { status: stats = {} } = statistics;
276✔
127

128
  useEffect(() => {
276✔
129
    if (!open) {
8✔
130
      return;
6✔
131
    }
132
    clearInterval(timer.current);
2✔
133
    if (!(deployment.finished || deployment.status === DEPLOYMENT_STATES.finished)) {
2!
134
      timer.current = past ? null : setInterval(refreshDeployment, TIMEOUTS.fiveSeconds);
2!
135
    }
136
    if ((deployment.type === DEPLOYMENT_TYPES.software || !release.device_types_compatible.length) && deployment.artifact_name) {
2!
UNCOV
137
      dispatch(getRelease(deployment.artifact_name));
×
138
    }
139
    if (hasAuditlogs && canAuditlog) {
2!
UNCOV
140
      dispatch(
×
141
        getAuditLogs({
142
          page: 1,
143
          perPage: 100,
144
          startDate: undefined,
145
          endDate: undefined,
146
          user: undefined,
UNCOV
147
          type: AUDIT_LOGS_TYPES.find(item => item.value === 'deployment'),
×
148
          detail: deployment.name
149
        })
150
      );
151
    }
152
    return () => {
2✔
153
      clearInterval(timer.current);
2✔
154
    };
155
  }, [deployment.id, open]);
156

157
  useEffect(() => {
276✔
158
    const progressCount =
159
      statCollector(deploymentStatesToSubstates.paused, stats) +
8✔
160
      statCollector(deploymentStatesToSubstates.pending, stats) +
161
      statCollector(deploymentStatesToSubstates.inprogress, stats);
162

163
    if (!!device_count && progressCount <= 0 && timer.current) {
8!
164
      // if no more devices in "progress" statuses, deployment has finished, stop counter
UNCOV
165
      clearInterval(timer.current);
×
UNCOV
166
      timer.current = setTimeout(refreshDeployment, TIMEOUTS.oneSecond);
×
UNCOV
167
      return () => {
×
UNCOV
168
        clearTimeout(timer.current);
×
169
      };
170
    }
171
  }, [deployment.id, device_count, JSON.stringify(stats)]);
172

173
  const scrollToBottom = () => {
276✔
UNCOV
174
    rolloutSchedule.current?.scrollIntoView({ behavior: 'smooth' });
×
175
  };
176

177
  const refreshDeployment = () => {
276✔
178
    if (!deployment.id) {
1!
UNCOV
179
      return;
×
180
    }
181
    return dispatch(getSingleDeployment(deployment.id));
1✔
182
  };
183

184
  const viewLog = id => dispatch(getDeviceLog(deployment.id, id)).then(() => setDeviceId(id));
276✔
185

186
  const copyLinkToClipboard = () => {
276✔
UNCOV
187
    const location = window.location.href.substring(0, window.location.href.indexOf('/deployments') + '/deployments'.length);
×
UNCOV
188
    copy(`${location}?open=true&id=${deployment.id}`);
×
UNCOV
189
    dispatch(setSnackbar('Link copied to clipboard'));
×
190
  };
191

192
  const { log: logData } = devices[deviceId] || {};
276✔
193
  const finished = deployment.finished || deployment.status === DEPLOYMENT_STATES.finished;
276✔
194
  const isConfigurationDeployment = deploymentType === DEPLOYMENT_TYPES.configuration;
276✔
195
  let config = {};
276✔
196
  if (isConfigurationDeployment) {
276!
UNCOV
197
    try {
×
UNCOV
198
      config = JSON.parse(atob(deployment.configuration));
×
199
    } catch (error) {
UNCOV
200
      config = {};
×
201
    }
202
  }
203

204
  const onUpdateControlChange = (updatedMap = {}) => {
276!
UNCOV
205
    const { id, update_control_map = {} } = deployment;
×
UNCOV
206
    const { states } = update_control_map;
×
UNCOV
207
    const { states: updatedStates } = updatedMap;
×
UNCOV
208
    dispatch(updateDeploymentControlMap(id, { states: { ...states, ...updatedStates } }));
×
209
  };
210

211
  const props = {
276✔
212
    deployment,
213
    getDeploymentDevices: (id, options) => dispatch(getDeploymentDevices(id, options)),
1✔
214
    getDeviceAuth: id => dispatch(getDeviceAuth(id)),
1✔
215
    getDeviceById: id => dispatch(getDeviceById(id)),
1✔
216
    idAttribute,
217
    selectedDeviceIds,
218
    selectedDevices,
219
    userCapabilities,
220
    viewLog
221
  };
222

223
  return (
276✔
224
    <Drawer className={`${open ? 'fadeIn' : 'fadeOut'}`} anchor="right" open={open} onClose={onClose} PaperProps={{ style: { minWidth: '75vw' } }}>
276✔
225
      <div className="flexbox margin-bottom-small space-between">
226
        <div className="flexbox">
227
          <h3>{`Deployment ${type !== DEPLOYMENT_STATES.scheduled ? 'details' : 'report'}`}</h3>
276!
228
          <h4 className="margin-left-small margin-right-small">ID: {deployment.id}</h4>
229
          <IconButton onClick={copyLinkToClipboard} style={{ alignSelf: 'center' }} size="large">
230
            <LinkIcon />
231
          </IconButton>
232
        </div>
233
        <div className="flexbox center-aligned">
234
          {!finished ? (
276!
235
            <DeploymentAbortButton abort={abort} deployment={deployment} />
236
          ) : (stats.failure || stats.aborted) && !isConfigurationDeployment ? (
×
237
            <Tooltip
238
              title="This will create a new deployment with the same device group and Release.&#10;Devices with this Release already installed will be skipped, all others will be updated."
239
              placement="bottom"
240
            >
UNCOV
241
              <Button color="secondary" startIcon={<RefreshIcon fontSize="small" />} onClick={() => retry(deployment, Object.keys(devices))}>
×
242
                Recreate deployment?
243
              </Button>
244
            </Tooltip>
245
          ) : (
246
            <div className="flexbox centered margin-right">
247
              <CheckCircleOutlineIcon fontSize="small" className="green margin-right-small" />
248
              <h3>Finished</h3>
249
            </div>
250
          )}
251
          <IconButton onClick={onClose} aria-label="close" size="large">
252
            <CloseIcon />
253
          </IconButton>
254
        </div>
255
      </div>
256
      <Divider />
257
      <div>
258
        <DeploymentPhaseNotification deployment={deployment} onReviewClick={scrollToBottom} />
259
        <DeploymentOverview
260
          creator={creator}
261
          deployment={deployment}
262
          devicesById={devicesById}
263
          idAttribute={idAttribute}
264
          onScheduleClick={scrollToBottom}
265
          tenantCapabilities={tenantCapabilities}
266
        />
267
        {isConfigurationDeployment && (
276!
268
          <>
269
            <LinedHeader className={classes.header} heading="Configuration" />
270
            <ConfigurationObject className="margin-top-small margin-bottom-large" config={config} />
271
          </>
272
        )}
273
        <LinedHeader className={classes.header} heading="Status" />
274
        <DeploymentStatus deployment={deployment} />
275
        <LinedHeader className={classes.header} heading="Devices" />
276
        <DeviceList {...props} viewLog={viewLog} />
277
        <RolloutSchedule
278
          deployment={deployment}
279
          headerClass={classes.header}
280
          onUpdateControlChange={onUpdateControlChange}
281
          onAbort={abort}
282
          innerRef={rolloutSchedule}
283
        />
UNCOV
284
        {Boolean(deviceId.length) && <LogDialog logData={logData} onClose={() => setDeviceId('')} />}
×
285
      </div>
286
      <Divider className={classes.divider} light />
287
    </Drawer>
288
  );
289
};
290
export default DeploymentReport;
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