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

mendersoftware / gui / 951400782

pending completion
951400782

Pull #3900

gitlab-ci

web-flow
chore: bump @testing-library/jest-dom from 5.16.5 to 5.17.0

Bumps [@testing-library/jest-dom](https://github.com/testing-library/jest-dom) from 5.16.5 to 5.17.0.
- [Release notes](https://github.com/testing-library/jest-dom/releases)
- [Changelog](https://github.com/testing-library/jest-dom/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/jest-dom/compare/v5.16.5...v5.17.0)

---
updated-dependencies:
- dependency-name: "@testing-library/jest-dom"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Pull Request #3900: chore: bump @testing-library/jest-dom from 5.16.5 to 5.17.0

4446 of 6414 branches covered (69.32%)

8342 of 10084 relevant lines covered (82.73%)

186.0 hits per line

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

61.35
/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 { useDispatch, useSelector } 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 { AUDIT_LOGS_TYPES } from '../../constants/organizationConstants';
28
import { createDownload, getISOStringBoundaries } from '../../helpers';
29
import { getGroupNames, getTenantCapabilities, getUserCapabilities } from '../../selectors';
30
import { useDebounce } from '../../utils/debouncehook';
31
import { useLocationParams } from '../../utils/liststatehook';
32
import Loader from '../common/loader';
33
import TimeframePicker from '../common/timeframe-picker';
34
import TimerangePicker from '../common/timerange-picker';
35
import AuditLogsList from './auditlogslist';
36

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

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

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

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

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

60
export const AuditLogs = props => {
4✔
61
  const navigate = useNavigate();
20✔
62
  const [csvLoading, setCsvLoading] = useState(false);
19✔
63

64
  const [date] = useState(getISOStringBoundaries(new Date()));
19✔
65
  const { start: today, end: tonight } = date;
19✔
66

67
  const [detailValue, setDetailValue] = useState(null);
19✔
68
  const [userValue, setUserValue] = useState(null);
19✔
69
  const [typeValue, setTypeValue] = useState(null);
19✔
70
  const [locationParams, setLocationParams] = useLocationParams('auditlogs', { today, tonight, defaults: { sort: { direction: SORTING_OPTIONS.desc } } });
19✔
71
  const { classes } = useStyles();
19✔
72
  const dispatch = useDispatch();
19✔
73
  const events = useSelector(state => state.organization.auditlog.events);
32✔
74
  const groups = useSelector(getGroupNames);
19✔
75
  const selectionState = useSelector(state => state.organization.auditlog.selectionState);
32✔
76
  const userCapabilities = useSelector(getUserCapabilities);
19✔
77
  const tenantCapabilities = useSelector(getTenantCapabilities);
19✔
78
  const users = useSelector(state => state.users.byId);
32✔
79
  const { canReadUsers } = userCapabilities;
19✔
80
  const { hasAuditlogs } = tenantCapabilities;
19✔
81

82
  const debouncedDetail = useDebounce(detailValue, TIMEOUTS.debounceDefault);
19✔
83
  const debouncedType = useDebounce(typeValue, TIMEOUTS.debounceDefault);
19✔
84
  const debouncedUser = useDebounce(userValue, TIMEOUTS.debounceDefault);
19✔
85

86
  const { detail, isLoading, perPage, endDate, user, reset: resetList, sort, startDate, total, type } = selectionState;
19✔
87

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

106
  useEffect(() => {
19✔
107
    if (!hasAuditlogs) {
3!
108
      return;
×
109
    }
110
    dispatch(setAuditlogsState({ page: 1, detail: debouncedDetail, type: debouncedType, user: debouncedUser }));
3✔
111
  }, [debouncedDetail, debouncedType, debouncedUser, hasAuditlogs]);
112

113
  useEffect(() => {
19✔
114
    if (canReadUsers) {
3!
115
      dispatch(getUserList());
3✔
116
    }
117
  }, [canReadUsers]);
118

119
  useEffect(() => {
19✔
120
    if (!hasAuditlogs) {
10!
121
      return;
×
122
    }
123
    setLocationParams({ pageState: selectionState });
10✔
124
  }, [detail, endDate, hasAuditlogs, JSON.stringify(sort), perPage, selectionState.page, selectionState.selectedId, startDate, type, user]);
125

126
  useEffect(() => {
19✔
127
    const user = users[debouncedUser];
3✔
128
    if (debouncedUser?.id || !user) {
3!
129
      return;
3✔
130
    }
131
    setUserValue(user);
×
132
  }, [debouncedUser, JSON.stringify(users)]);
133

134
  const reset = () => {
19✔
135
    dispatch(
2✔
136
      setAuditlogsState({
137
        detail: null,
138
        endDate: tonight,
139
        page: 1,
140
        reset: !resetList,
141
        startDate: today,
142
        type: null,
143
        user: null
144
      })
145
    );
146
    setDetailValue(null);
2✔
147
    setTypeValue(null);
2✔
148
    setUserValue(null);
2✔
149
    navigate('/auditlog');
2✔
150
  };
151

152
  const createCsvDownload = () => {
19✔
153
    setCsvLoading(true);
1✔
154
    dispatch(getAuditLogsCsvLink()).then(address => {
1✔
155
      createDownload(
1✔
156
        encodeURI(address),
157
        `Mender-AuditLog-${moment(startDate).format(moment.HTML5_FMT.DATE)}-${moment(endDate).format(moment.HTML5_FMT.DATE)}.csv`
158
      );
159
      setCsvLoading(false);
1✔
160
    });
161
  };
162

163
  const onChangeSorting = () => {
19✔
164
    const currentSorting = sort.direction === SORTING_OPTIONS.desc ? SORTING_OPTIONS.asc : SORTING_OPTIONS.desc;
×
165
    dispatch(setAuditlogsState({ page: 1, sort: { direction: currentSorting } }));
×
166
  };
167

168
  const onUserFilterChange = (e, value, reason) => {
19✔
169
    if (!e || reason === 'blur') {
×
170
      return;
×
171
    }
172
    setUserValue(value);
×
173
  };
174

175
  const onTypeFilterChange = (e, value, reason) => {
19✔
176
    if (!e || reason === 'blur') {
×
177
      return;
×
178
    }
179
    if (!value) {
×
180
      setDetailValue(null);
×
181
    }
182
    setTypeValue(value);
×
183
  };
184

185
  const onDetailFilterChange = (e, value) => {
19✔
186
    if (!e) {
×
187
      return;
×
188
    }
189
    setDetailValue(value);
×
190
  };
191

192
  const onTimeFilterChange = (currentStartDate = startDate, currentEndDate = endDate) =>
19!
193
    dispatch(setAuditlogsState({ page: 1, startDate: currentStartDate, endDate: currentEndDate }));
1✔
194

195
  const onChangePagination = (page, currentPerPage = perPage) => dispatch(setAuditlogsState({ page, perPage: currentPerPage }));
19!
196

197
  const typeOptionsMap = {
19✔
198
    Deployment: groups,
199
    User: Object.values(users),
200
    Device: []
201
  };
202
  const detailOptions = typeOptionsMap[type?.title] ?? [];
19✔
203

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

291
export default 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