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

mendersoftware / gui / 908425489

pending completion
908425489

Pull #3799

gitlab-ci

mzedel
chore: aligned loader usage in devices list with deployment devices list

Signed-off-by: Manuel Zedel <manuel.zedel@northern.tech>
Pull Request #3799: MEN-6553

4406 of 6423 branches covered (68.6%)

18 of 19 new or added lines in 3 files covered. (94.74%)

1777 existing lines in 167 files now uncovered.

8329 of 10123 relevant lines covered (82.28%)

144.7 hits per line

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

82.98
/src/js/components/deployments/pastdeployments.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 { Autocomplete, TextField } from '@mui/material';
19
import { makeStyles } from 'tss-react/mui';
20

21
import historyImage from '../../../assets/img/history.png';
22
import { setSnackbar } from '../../actions/appActions';
23
import { getDeploymentsByStatus, setDeploymentsState } from '../../actions/deploymentActions';
24
import { advanceOnboarding } from '../../actions/onboardingActions';
25
import { BEGINNING_OF_TIME, SORTING_OPTIONS, TIMEOUTS } from '../../constants/appConstants';
26
import { DEPLOYMENT_STATES, DEPLOYMENT_TYPES } from '../../constants/deploymentConstants';
27
import { onboardingSteps } from '../../constants/onboardingConstants';
28
import { getISOStringBoundaries, tryMapDeployments } from '../../helpers';
29
import { getGroupNames, getIdAttribute, getOnboardingState, getUserCapabilities } from '../../selectors';
30
import { useDebounce } from '../../utils/debouncehook';
31
import { getOnboardingComponentFor } from '../../utils/onboardingmanager';
32
import useWindowSize from '../../utils/resizehook';
33
import { clearAllRetryTimers, clearRetryTimer, setRetryTimer } from '../../utils/retrytimer';
34
import Loader from '../common/loader';
35
import TimeframePicker from '../common/timeframe-picker';
36
import TimerangePicker from '../common/timerange-picker';
37
import { DeploymentSize, DeploymentStatus } from './deploymentitem';
38
import { defaultRefreshDeploymentsLength as refreshDeploymentsLength } from './deployments';
39
import DeploymentsList, { defaultHeaders } from './deploymentslist';
40

41
const headers = [
7✔
42
  ...defaultHeaders.slice(0, defaultHeaders.length - 1),
43
  { title: 'Status', renderer: DeploymentStatus },
44
  { title: 'Data downloaded', renderer: DeploymentSize }
45
];
46

47
const type = DEPLOYMENT_STATES.finished;
7✔
48

49
const useStyles = makeStyles()(theme => ({
7✔
50
  datepickerContainer: {
51
    backgroundColor: theme.palette.background.lightgrey
52
  }
53
}));
54

55
export const Past = props => {
7✔
56
  const { createClick, isShowingDetails } = props;
67✔
57
  // eslint-disable-next-line no-unused-vars
58
  const size = useWindowSize();
66✔
59
  const [tonight] = useState(getISOStringBoundaries(new Date()).end);
66✔
60
  const [loading, setLoading] = useState(false);
66✔
61
  const deploymentsRef = useRef();
66✔
62
  const timer = useRef();
66✔
63
  const [searchValue, setSearchValue] = useState('');
66✔
64
  const [typeValue, setTypeValue] = useState('');
66✔
65
  const { classes } = useStyles();
66✔
66

67
  const dispatch = useDispatch();
66✔
68
  const dispatchedSetSnackbar = (...args) => dispatch(setSnackbar(...args));
66✔
69

70
  const past = useSelector(state => state.deployments.selectionState.finished.selection.reduce(tryMapDeployments, { state, deployments: [] }).deployments);
119✔
71
  const { canConfigure, canDeploy } = useSelector(getUserCapabilities);
66✔
72
  const { attribute: idAttribute } = useSelector(getIdAttribute);
66✔
73
  const onboardingState = useSelector(getOnboardingState);
66✔
74
  const pastSelectionState = useSelector(state => state.deployments.selectionState.finished);
119✔
75
  const devices = useSelector(state => state.devices.byId);
119✔
76
  const groupNames = useSelector(getGroupNames);
66✔
77

78
  const debouncedSearch = useDebounce(searchValue, TIMEOUTS.debounceDefault);
66✔
79
  const debouncedType = useDebounce(typeValue, TIMEOUTS.debounceDefault);
66✔
80

81
  const { endDate, page, perPage, search: deviceGroup, startDate, total: count, type: deploymentType } = pastSelectionState;
66✔
82

83
  useEffect(() => {
66✔
84
    const roundedStartDate = Math.round(Date.parse(startDate || BEGINNING_OF_TIME) / 1000);
3✔
85
    const roundedEndDate = Math.round(Date.parse(endDate) / 1000);
3✔
86
    setLoading(true);
3✔
87
    dispatch(getDeploymentsByStatus(type, page, perPage, roundedStartDate, roundedEndDate, deviceGroup, deploymentType, true, SORTING_OPTIONS.desc))
3✔
88
      .then(deploymentsAction => {
89
        const deploymentsList = deploymentsAction ? Object.values(deploymentsAction[0].deployments) : [];
2!
90
        if (deploymentsList.length) {
2!
91
          let newStartDate = new Date(deploymentsList[deploymentsList.length - 1].created);
2✔
92
          const { start: startDate } = getISOStringBoundaries(newStartDate);
2✔
93
          dispatch(setDeploymentsState({ [DEPLOYMENT_STATES.finished]: { startDate } }));
2✔
94
        }
95
      })
96
      .finally(() => setLoading(false));
2✔
97
    return () => {
3✔
98
      clearAllRetryTimers(dispatchedSetSnackbar);
3✔
99
    };
100
  }, []);
101

102
  useEffect(() => {
66✔
103
    clearInterval(timer.current);
4✔
104
    timer.current = setInterval(refreshPast, refreshDeploymentsLength);
4✔
105
    refreshPast();
4✔
106
    return () => {
4✔
107
      clearInterval(timer.current);
4✔
108
    };
109
  }, [page, perPage, startDate, endDate, deviceGroup, deploymentType]);
110

111
  useEffect(() => {
66✔
112
    if (!past.length || onboardingState.complete) {
4✔
113
      return;
2✔
114
    }
115
    const pastDeploymentsFailed = past.reduce(
2✔
116
      (accu, item) =>
117
        item.status === 'failed' ||
3✔
118
        (item.statistics?.status &&
119
          item.statistics.status.noartifact + item.statistics.status.failure + item.statistics.status['already-installed'] + item.statistics.status.aborted >
120
            0) ||
121
        accu,
122
      false
123
    );
124
    let onboardingStep = onboardingSteps.DEPLOYMENTS_PAST_COMPLETED_NOTIFICATION;
2✔
125
    if (pastDeploymentsFailed) {
2!
UNCOV
126
      onboardingStep = onboardingSteps.DEPLOYMENTS_PAST_COMPLETED_FAILURE;
×
127
    }
128
    dispatch(advanceOnboarding(onboardingStep));
2✔
129
    setTimeout(() => {
2✔
130
      let notification = getOnboardingComponentFor(onboardingSteps.DEPLOYMENTS_PAST_COMPLETED_NOTIFICATION, onboardingState, {
2✔
131
        setSnackbar: dispatchedSetSnackbar
132
      });
133
      // the following extra check is needed since this component will still be mounted if a user returns to the initial tab after the first
134
      // onboarding deployment & thus the effects will still run, so only ever consider the notification for the second deployment
135
      notification =
2✔
136
        past.length > 1
2✔
137
          ? getOnboardingComponentFor(onboardingSteps.ONBOARDING_FINISHED_NOTIFICATION, onboardingState, { setSnackbar: dispatchedSetSnackbar }, notification)
138
          : notification;
139
      !!notification && dispatch(setSnackbar('open', TIMEOUTS.refreshDefault, '', notification, () => {}, true));
2!
140
    }, 400);
141
  }, [past.length, onboardingState.complete]);
142

143
  useEffect(() => {
66✔
144
    dispatch(setDeploymentsState({ [DEPLOYMENT_STATES.finished]: { page: 1, search: debouncedSearch, type: debouncedType } }));
3✔
145
  }, [debouncedSearch, debouncedType]);
146

147
  /*
148
  / refresh only finished deployments
149
  /
150
  */
151
  const refreshPast = (
66✔
152
    currentPage = page,
4✔
153
    currentPerPage = perPage,
4✔
154
    currentStartDate = startDate,
4✔
155
    currentEndDate = endDate,
4✔
156
    currentDeviceGroup = deviceGroup,
4✔
157
    currentType = deploymentType
4✔
158
  ) => {
159
    const roundedStartDate = Math.round(Date.parse(currentStartDate) / 1000);
4✔
160
    const roundedEndDate = Math.round(Date.parse(currentEndDate) / 1000);
4✔
161
    return dispatch(getDeploymentsByStatus(type, currentPage, currentPerPage, roundedStartDate, roundedEndDate, currentDeviceGroup, currentType))
4✔
162
      .then(deploymentsAction => {
163
        clearRetryTimer(type, dispatchedSetSnackbar);
3✔
164
        const { total, deploymentIds } = deploymentsAction[deploymentsAction.length - 1];
3✔
165
        if (total && !deploymentIds.length) {
3!
UNCOV
166
          return refreshPast(currentPage, currentPerPage, currentStartDate, currentEndDate, currentDeviceGroup);
×
167
        }
168
      })
UNCOV
169
      .catch(err => setRetryTimer(err, 'deployments', `Couldn't load deployments.`, refreshDeploymentsLength, dispatchedSetSnackbar));
×
170
  };
171

172
  let onboardingComponent = null;
66✔
173
  if (deploymentsRef.current) {
66✔
174
    const detailsButtons = deploymentsRef.current.getElementsByClassName('MuiButton-contained');
33✔
175
    const left = detailsButtons.length
33!
176
      ? deploymentsRef.current.offsetLeft + detailsButtons[0].offsetLeft + detailsButtons[0].offsetWidth / 2 + 15
177
      : deploymentsRef.current.offsetWidth;
178
    let anchor = { left: deploymentsRef.current.offsetWidth / 2, top: deploymentsRef.current.offsetTop };
33✔
179
    onboardingComponent = getOnboardingComponentFor(onboardingSteps.DEPLOYMENTS_PAST_COMPLETED, onboardingState, {
33✔
180
      anchor,
181
      setSnackbar: dispatchedSetSnackbar
182
    });
183
    onboardingComponent = getOnboardingComponentFor(
33✔
184
      onboardingSteps.DEPLOYMENTS_PAST_COMPLETED_FAILURE,
185
      onboardingState,
186
      { anchor: { left, top: detailsButtons[0].parentElement.offsetTop + detailsButtons[0].parentElement.offsetHeight } },
187
      onboardingComponent
188
    );
189
    onboardingComponent = getOnboardingComponentFor(onboardingSteps.ONBOARDING_FINISHED, onboardingState, { anchor }, onboardingComponent);
33✔
190
  }
191

192
  const onGroupFilterChange = (e, value) => {
66✔
UNCOV
193
    if (!e) {
×
UNCOV
194
      return;
×
195
    }
UNCOV
196
    setSearchValue(value);
×
197
  };
198

199
  const onTypeFilterChange = (e, value) => {
66✔
UNCOV
200
    if (!e) {
×
UNCOV
201
      return;
×
202
    }
UNCOV
203
    setTypeValue(value);
×
204
  };
205

206
  const onTimeFilterChange = (startDate, endDate) => dispatch(setDeploymentsState({ [DEPLOYMENT_STATES.finished]: { page: 1, startDate, endDate } }));
66✔
207

208
  return (
66✔
209
    <div className="fadeIn margin-left margin-top-large">
210
      <div className={`datepicker-container ${classes.datepickerContainer}`}>
211
        <TimerangePicker endDate={endDate} onChange={onTimeFilterChange} startDate={startDate} />
212
        <TimeframePicker onChange={onTimeFilterChange} endDate={endDate} startDate={startDate} tonight={tonight} />
213
        <Autocomplete
214
          id="device-group-selection"
215
          autoHighlight
216
          autoSelect
217
          filterSelectedOptions
218
          freeSolo
219
          handleHomeEndKeys
220
          inputValue={deviceGroup}
221
          options={groupNames}
222
          onInputChange={onGroupFilterChange}
223
          renderInput={params => (
224
            <TextField {...params} label="Filter by device group" placeholder="Select a group" InputProps={{ ...params.InputProps }} style={{ marginTop: 0 }} />
66✔
225
          )}
226
        />
227
        <Autocomplete
228
          id="deployment-type-selection"
229
          autoHighlight
230
          autoSelect
231
          filterSelectedOptions
232
          handleHomeEndKeys
233
          classes={{ input: deploymentType ? 'capitalized' : '', option: 'capitalized' }}
66!
234
          inputValue={deploymentType}
235
          onInputChange={onTypeFilterChange}
236
          options={Object.keys(DEPLOYMENT_TYPES)}
237
          renderInput={params => (
238
            <TextField {...params} label="Filter by type" placeholder="Select a type" InputProps={{ ...params.InputProps }} style={{ marginTop: 0 }} />
66✔
239
          )}
240
        />
241
      </div>
242
      <div className="deploy-table-contain">
243
        <Loader show={loading} />
244
        {/* TODO: fix status retrieval for past deployments to decide what to show here - */}
245
        {!loading && !!past.length && !!onboardingComponent && !isShowingDetails && onboardingComponent}
130!
246
        {!!past.length && (
101✔
247
          <DeploymentsList
248
            {...props}
249
            canConfigure={canConfigure}
250
            canDeploy={canDeploy}
251
            devices={devices}
252
            idAttribute={idAttribute}
253
            componentClass="margin-left-small"
254
            count={count}
255
            headers={headers}
256
            items={past}
257
            page={page}
UNCOV
258
            onChangeRowsPerPage={perPage => dispatch(setDeploymentsState({ [DEPLOYMENT_STATES.finished]: { page: 1, perPage } }))}
×
UNCOV
259
            onChangePage={page => dispatch(setDeploymentsState({ [DEPLOYMENT_STATES.finished]: { page } }))}
×
260
            pageSize={perPage}
261
            rootRef={deploymentsRef}
262
            showPagination
263
            type={type}
264
          />
265
        )}
266
        {!(loading || past.length) && (
167✔
267
          <div className="dashboard-placeholder">
268
            <p>No finished deployments were found.</p>
269
            <p>
270
              Try adjusting the filters, or <a onClick={createClick}>Create a new deployment</a> to get started
271
            </p>
272
            <img src={historyImage} alt="Past" />
273
          </div>
274
        )}
275
      </div>
276
    </div>
277
  );
278
};
279

280
export default Past;
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