• 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

83.22
/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 { ALL_DEVICES, UNGROUPED_GROUP } from '../../constants/deviceConstants';
28
import { onboardingSteps } from '../../constants/onboardingConstants';
29
import { getISOStringBoundaries, tryMapDeployments } from '../../helpers';
30
import { getIdAttribute, getOnboardingState, getUserCapabilities } from '../../selectors';
31
import { useDebounce } from '../../utils/debouncehook';
32
import { getOnboardingComponentFor } from '../../utils/onboardingmanager';
33
import useWindowSize from '../../utils/resizehook';
34
import { clearAllRetryTimers, clearRetryTimer, setRetryTimer } from '../../utils/retrytimer';
35
import Loader from '../common/loader';
36
import TimeframePicker from '../common/timeframe-picker';
37
import TimerangePicker from '../common/timerange-picker';
38
import { DeploymentSize, DeploymentStatus } from './deploymentitem';
39
import { defaultRefreshDeploymentsLength as refreshDeploymentsLength } from './deployments';
40
import DeploymentsList, { defaultHeaders } from './deploymentslist';
41

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

48
const type = DEPLOYMENT_STATES.finished;
7✔
49

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

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

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

71
  const past = useSelector(state => state.deployments.selectionState.finished.selection.reduce(tryMapDeployments, { state, deployments: [] }).deployments);
119✔
72
  const groups = useSelector(state => {
66✔
73
    // eslint-disable-next-line no-unused-vars
74
    const { [UNGROUPED_GROUP.id]: ungrouped, ...groups } = state.devices.groups.byId;
119✔
75
    return [ALL_DEVICES, ...Object.keys(groups)];
119✔
76
  });
77
  const { canConfigure, canDeploy } = useSelector(getUserCapabilities);
66✔
78
  const { attribute: idAttribute } = useSelector(getIdAttribute);
66✔
79
  const onboardingState = useSelector(getOnboardingState);
66✔
80
  const pastSelectionState = useSelector(state => state.deployments.selectionState.finished);
119✔
81
  const devices = useSelector(state => state.devices.byId);
119✔
82

83
  const debouncedSearch = useDebounce(searchValue, TIMEOUTS.debounceDefault);
66✔
84
  const debouncedType = useDebounce(typeValue, TIMEOUTS.debounceDefault);
66✔
85

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

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

107
  useEffect(() => {
66✔
108
    clearInterval(timer.current);
4✔
109
    timer.current = setInterval(refreshPast, refreshDeploymentsLength);
4✔
110
    refreshPast();
4✔
111
    return () => {
4✔
112
      clearInterval(timer.current);
4✔
113
    };
114
  }, [page, perPage, startDate, endDate, deviceGroup, deploymentType]);
115

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

148
  useEffect(() => {
66✔
149
    dispatch(setDeploymentsState({ [DEPLOYMENT_STATES.finished]: { page: 1, search: debouncedSearch, type: debouncedType } }));
3✔
150
  }, [debouncedSearch, debouncedType]);
151

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

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

197
  const onGroupFilterChange = (e, value) => {
66✔
UNCOV
198
    if (!e) {
×
UNCOV
199
      return;
×
200
    }
UNCOV
201
    setSearchValue(value);
×
202
  };
203

204
  const onTypeFilterChange = (e, value) => {
66✔
UNCOV
205
    if (!e) {
×
UNCOV
206
      return;
×
207
    }
UNCOV
208
    setTypeValue(value);
×
209
  };
210

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

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

285
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