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

mendersoftware / gui / 897326496

pending completion
897326496

Pull #3752

gitlab-ci

mzedel
chore(e2e): made use of shared timeout & login checking values to remove code duplication

Signed-off-by: Manuel Zedel <manuel.zedel@northern.tech>
Pull Request #3752: chore(e2e-tests): slightly simplified log in test + separated log out test

4395 of 6392 branches covered (68.76%)

8060 of 9780 relevant lines covered (82.41%)

126.17 hits per line

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

57.62
/src/js/components/auditlogs/auditlogs.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 React, { useEffect, useState } from 'react';
15
import { connect } from 'react-redux';
16
import { useNavigate } from 'react-router-dom';
17

18
import { Autocomplete, Button, TextField } from '@mui/material';
19
import { makeStyles } from 'tss-react/mui';
20

21
import moment from 'moment';
22

23
import historyImage from '../../../assets/img/history.png';
24
import { getAuditLogsCsvLink, setAuditlogsState } from '../../actions/organizationActions';
25
import { getUserList } from '../../actions/userActions';
26
import { SORTING_OPTIONS, TIMEOUTS } from '../../constants/appConstants';
27
import { ALL_DEVICES, UNGROUPED_GROUP } from '../../constants/deviceConstants';
28
import { AUDIT_LOGS_TYPES } from '../../constants/organizationConstants';
29
import { createDownload, getISOStringBoundaries, toggle } from '../../helpers';
30
import { getTenantCapabilities, getUserCapabilities } from '../../selectors';
31
import { useDebounce } from '../../utils/debouncehook';
32
import { useLocationParams } from '../../utils/liststatehook';
33
import Loader from '../common/loader';
34
import TimeframePicker from '../common/timeframe-picker';
35
import TimerangePicker from '../common/timerange-picker';
36
import AuditLogsList from './auditlogslist';
37

38
const detailsMap = {
4✔
39
  Deployment: 'to device group',
40
  User: 'email'
41
};
42

43
const useStyles = makeStyles()(theme => ({
4✔
44
  filters: {
45
    backgroundColor: theme.palette.background.lightgrey
46
  }
47
}));
48

49
const getOptionLabel = option => option.title || option.email || option;
4!
50

51
const renderOption = (props, option) => <li {...props}>{getOptionLabel(option)}</li>;
4✔
52

53
const autoSelectProps = {
4✔
54
  autoSelect: true,
55
  filterSelectedOptions: true,
56
  getOptionLabel,
57
  handleHomeEndKeys: true,
58
  renderOption
59
};
60

61
export const AuditLogs = ({
4✔
62
  events,
63
  getAuditLogsCsvLink,
64
  getUserList,
65
  groups,
66
  selectionState,
67
  setAuditlogsState,
68
  tenantCapabilities,
69
  userCapabilities,
70
  users,
71
  ...props
72
}) => {
73
  const navigate = useNavigate();
10✔
74
  const [csvLoading, setCsvLoading] = useState(false);
10✔
75
  const [filterReset, setFilterReset] = useState(false);
10✔
76

77
  const [date] = useState(getISOStringBoundaries(new Date()));
10✔
78
  const { start: today, end: tonight } = date;
10✔
79

80
  const [detailValue, setDetailValue] = useState('');
10✔
81
  const [userValue, setUserValue] = useState('');
10✔
82
  const [typeValue, setTypeValue] = useState('');
10✔
83
  const [locationParams, setLocationParams] = useLocationParams('auditlogs', { today, tonight, defaults: { sort: { direction: SORTING_OPTIONS.desc } } });
10✔
84
  const { canReadUsers } = userCapabilities;
10✔
85
  const { hasAuditlogs } = tenantCapabilities;
10✔
86
  const { classes } = useStyles();
10✔
87

88
  const debouncedDetail = useDebounce(detailValue, TIMEOUTS.debounceDefault);
10✔
89
  const debouncedType = useDebounce(typeValue, TIMEOUTS.debounceDefault);
10✔
90
  const debouncedUser = useDebounce(userValue, TIMEOUTS.debounceDefault);
10✔
91

92
  const { detail, isLoading, perPage, endDate, user, reset: resetList, sort, startDate, total, type } = selectionState;
10✔
93

94
  useEffect(() => {
10✔
95
    if (!hasAuditlogs) {
3!
96
      return;
×
97
    }
98
    let state = { ...locationParams, reset: !resetList };
3✔
99
    if (locationParams.id && Boolean(locationParams.open)) {
3!
100
      state.selectedId = locationParams.id[0];
×
101
      const [eventAction, eventTime] = atob(state.selectedId).split('|');
×
102
      if (eventTime && !events.some(item => item.time === eventTime && item.action === eventAction)) {
×
103
        const { start, end } = getISOStringBoundaries(new Date(eventTime));
×
104
        state.endDate = end;
×
105
        state.startDate = start;
×
106
      }
107
    }
108
    setAuditlogsState(state);
3✔
109
    Object.entries({ detail: setDetailValue, user: setUserValue, type: setTypeValue }).map(([key, setter]) => (state[key] ? setter(state[key]) : undefined));
9!
110
  }, [hasAuditlogs]);
111

112
  useEffect(() => {
10✔
113
    if (!hasAuditlogs) {
3!
114
      return;
×
115
    }
116
    setAuditlogsState({ page: 1, detail: debouncedDetail, type: debouncedType, user: debouncedUser });
3✔
117
  }, [debouncedDetail, debouncedType, debouncedUser, hasAuditlogs]);
118

119
  useEffect(() => {
10✔
120
    if (canReadUsers) {
3!
121
      getUserList();
3✔
122
    }
123
  }, [canReadUsers]);
124

125
  useEffect(() => {
10✔
126
    if (!hasAuditlogs) {
3!
127
      return;
×
128
    }
129
    setLocationParams({ pageState: selectionState });
3✔
130
  }, [detail, endDate, hasAuditlogs, JSON.stringify(sort), perPage, selectionState.page, selectionState.selectedId, startDate, type, user]);
131

132
  const reset = () => {
10✔
133
    setAuditlogsState({
2✔
134
      detail: '',
135
      endDate: tonight,
136
      page: 1,
137
      reset: !resetList,
138
      startDate: today,
139
      type: '',
140
      user: ''
141
    });
142
    setFilterReset(toggle);
2✔
143
    navigate('/auditlog');
2✔
144
  };
145

146
  const createCsvDownload = () => {
10✔
147
    setCsvLoading(true);
1✔
148
    getAuditLogsCsvLink().then(address => {
1✔
149
      createDownload(
1✔
150
        encodeURI(address),
151
        `Mender-AuditLog-${moment(startDate).format(moment.HTML5_FMT.DATE)}-${moment(endDate).format(moment.HTML5_FMT.DATE)}.csv`
152
      );
153
      setCsvLoading(false);
1✔
154
    });
155
  };
156

157
  const onChangeSorting = () => {
10✔
158
    const currentSorting = sort.direction === SORTING_OPTIONS.desc ? SORTING_OPTIONS.asc : SORTING_OPTIONS.desc;
×
159
    setAuditlogsState({ page: 1, sort: { direction: currentSorting } });
×
160
  };
161

162
  const onUserFilterChange = (e, value, reason) => {
10✔
163
    if (!e || reason === 'blur') {
×
164
      return;
×
165
    }
166
    setUserValue(value || '');
×
167
  };
168

169
  const onTypeFilterChange = (e, value, reason) => {
10✔
170
    if (!e || reason === 'blur') {
×
171
      return;
×
172
    }
173
    if (!value) {
×
174
      setDetailValue('');
×
175
    }
176
    setTypeValue(value || '');
×
177
  };
178

179
  const onDetailFilterChange = (e, value) => {
10✔
180
    if (!e) {
×
181
      return;
×
182
    }
183
    setDetailValue(value || '');
×
184
  };
185

186
  const onTimeFilterChange = (currentStartDate = startDate, currentEndDate = endDate) =>
10!
187
    setAuditlogsState({ page: 1, startDate: currentStartDate, endDate: currentEndDate });
1✔
188

189
  const onChangePagination = (page, currentPerPage = perPage) => setAuditlogsState({ page, perPage: currentPerPage });
10!
190

191
  const typeOptionsMap = {
10✔
192
    Deployment: groups,
193
    User: Object.values(users),
194
    Device: []
195
  };
196
  const detailOptions = typeOptionsMap[type?.title] ?? [];
10✔
197

198
  return (
10✔
199
    <div className="fadeIn margin-left flexbox column" style={{ marginRight: '5%' }}>
200
      <h3>Audit log</h3>
201
      <div className={`auditlogs-filters margin-bottom margin-top-small ${classes.filters}`}>
202
        <Autocomplete
203
          {...autoSelectProps}
204
          id="audit-log-user-selection"
205
          freeSolo
206
          options={Object.values(users)}
207
          onChange={onUserFilterChange}
208
          value={user}
209
          renderInput={params => (
210
            <TextField
10✔
211
              {...params}
212
              label="Filter by user"
213
              placeholder="Select a user"
214
              InputLabelProps={{ shrink: true }}
215
              InputProps={{ ...params.InputProps }}
216
            />
217
          )}
218
          style={{ maxWidth: 250 }}
219
        />
220
        <Autocomplete
221
          {...autoSelectProps}
222
          id="audit-log-type-selection"
223
          key={`audit-log-type-selection-${filterReset}`}
224
          onChange={onTypeFilterChange}
225
          options={AUDIT_LOGS_TYPES}
226
          renderInput={params => (
227
            <TextField {...params} label="Filter by change" placeholder="Type" InputLabelProps={{ shrink: true }} InputProps={{ ...params.InputProps }} />
12✔
228
          )}
229
          style={{ marginLeft: 7.5 }}
230
          value={type}
231
        />
232
        <Autocomplete
233
          {...autoSelectProps}
234
          id="audit-log-type-details-selection"
235
          disabled={!type}
236
          inputValue={detail}
237
          onInputChange={onDetailFilterChange}
238
          options={detailOptions}
239
          renderInput={params => <TextField {...params} placeholder={detailsMap[type] || '-'} InputProps={{ ...params.InputProps }} />}
10✔
240
          style={{ marginRight: 15, marginTop: 16 }}
241
        />
242
        <div />
243
        <TimerangePicker endDate={endDate} onChange={onTimeFilterChange} startDate={startDate} />
244
        <div style={{ gridColumnStart: 2, gridColumnEnd: 4, marginLeft: 7.5 }}>
245
          <TimeframePicker onChange={onTimeFilterChange} endDate={endDate} startDate={startDate} tonight={tonight} />
246
        </div>
247
        {!!(user || type || detail || startDate !== today || endDate !== tonight) && (
60!
248
          <span className="link margin-bottom-small" onClick={reset} style={{ alignSelf: 'flex-end' }}>
249
            clear filter
250
          </span>
251
        )}
252
      </div>
253
      <div className="flexbox center-aligned" style={{ justifyContent: 'flex-end' }}>
254
        <Loader show={csvLoading} />
255
        <Button variant="contained" color="secondary" disabled={csvLoading || !total} onClick={createCsvDownload} style={{ marginLeft: 15 }}>
19✔
256
          Download results as csv
257
        </Button>
258
      </div>
259
      {!!total && (
20✔
260
        <AuditLogsList
261
          {...props}
262
          items={events}
263
          loading={isLoading}
264
          onChangePage={onChangePagination}
265
          onChangeRowsPerPage={newPerPage => onChangePagination(1, newPerPage)}
×
266
          onChangeSorting={onChangeSorting}
267
          selectionState={selectionState}
268
          setAuditlogsState={setAuditlogsState}
269
          userCapabilities={userCapabilities}
270
        />
271
      )}
272
      {!(isLoading || total) && (
30!
273
        <div className="dashboard-placeholder">
274
          <p>No log entries were found.</p>
275
          <p>Try adjusting the filters.</p>
276
          <img src={historyImage} alt="Past" />
277
        </div>
278
      )}
279
    </div>
280
  );
281
};
282

283
const actionCreators = { getAuditLogsCsvLink, getUserList, setAuditlogsState };
4✔
284

285
const mapStateToProps = state => {
4✔
286
  // eslint-disable-next-line no-unused-vars
287
  const { [UNGROUPED_GROUP.id]: ungrouped, ...groups } = state.devices.groups.byId;
3✔
288
  return {
3✔
289
    events: state.organization.auditlog.events,
290
    groups: [ALL_DEVICES, ...Object.keys(groups).sort()],
291
    selectionState: state.organization.auditlog.selectionState,
292
    userCapabilities: getUserCapabilities(state),
293
    tenantCapabilities: getTenantCapabilities(state),
294
    users: state.users.byId
295
  };
296
};
297

298
export default connect(mapStateToProps, actionCreators)(AuditLogs);
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