• 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

61.21
/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 { ALL_DEVICES, UNGROUPED_GROUP } from '../../constants/deviceConstants';
28
import { AUDIT_LOGS_TYPES } from '../../constants/organizationConstants';
29
import { createDownload, getISOStringBoundaries } 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 = props => {
4✔
62
  const navigate = useNavigate();
11✔
63
  const [csvLoading, setCsvLoading] = useState(false);
10✔
64

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

68
  const [detailValue, setDetailValue] = useState(null);
10✔
69
  const [userValue, setUserValue] = useState(null);
10✔
70
  const [typeValue, setTypeValue] = useState(null);
10✔
71
  const [locationParams, setLocationParams] = useLocationParams('auditlogs', { today, tonight, defaults: { sort: { direction: SORTING_OPTIONS.desc } } });
10✔
72
  const { classes } = useStyles();
10✔
73
  const dispatch = useDispatch();
10✔
74
  const events = useSelector(state => state.organization.auditlog.events);
10✔
75
  const groups = useSelector(state => {
10✔
76
    // eslint-disable-next-line no-unused-vars
77
    const { [UNGROUPED_GROUP.id]: ungrouped, ...groups } = state.devices.groups.byId;
10✔
78
    return [ALL_DEVICES, ...Object.keys(groups).sort()];
10✔
79
  });
80
  const selectionState = useSelector(state => state.organization.auditlog.selectionState);
10✔
81
  const userCapabilities = useSelector(getUserCapabilities);
10✔
82
  const tenantCapabilities = useSelector(getTenantCapabilities);
10✔
83
  const users = useSelector(state => state.users.byId);
10✔
84
  const { canReadUsers } = userCapabilities;
10✔
85
  const { hasAuditlogs } = tenantCapabilities;
10✔
86

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

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

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

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

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

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

131
  useEffect(() => {
10✔
132
    const user = users[debouncedUser];
3✔
133
    if (debouncedUser?.id || !user) {
3!
134
      return;
3✔
135
    }
UNCOV
136
    setUserValue(user);
×
137
  }, [debouncedUser, JSON.stringify(users)]);
138

139
  const reset = () => {
10✔
140
    dispatch(
2✔
141
      setAuditlogsState({
142
        detail: null,
143
        endDate: tonight,
144
        page: 1,
145
        reset: !resetList,
146
        startDate: today,
147
        type: null,
148
        user: null
149
      })
150
    );
151
    setDetailValue(null);
2✔
152
    setTypeValue(null);
2✔
153
    setUserValue(null);
2✔
154
    navigate('/auditlog');
2✔
155
  };
156

157
  const createCsvDownload = () => {
10✔
158
    setCsvLoading(true);
1✔
159
    dispatch(getAuditLogsCsvLink()).then(address => {
1✔
160
      createDownload(
1✔
161
        encodeURI(address),
162
        `Mender-AuditLog-${moment(startDate).format(moment.HTML5_FMT.DATE)}-${moment(endDate).format(moment.HTML5_FMT.DATE)}.csv`
163
      );
164
      setCsvLoading(false);
1✔
165
    });
166
  };
167

168
  const onChangeSorting = () => {
10✔
UNCOV
169
    const currentSorting = sort.direction === SORTING_OPTIONS.desc ? SORTING_OPTIONS.asc : SORTING_OPTIONS.desc;
×
UNCOV
170
    dispatch(setAuditlogsState({ page: 1, sort: { direction: currentSorting } }));
×
171
  };
172

173
  const onUserFilterChange = (e, value, reason) => {
10✔
UNCOV
174
    if (!e || reason === 'blur') {
×
UNCOV
175
      return;
×
176
    }
UNCOV
177
    setUserValue(value);
×
178
  };
179

180
  const onTypeFilterChange = (e, value, reason) => {
10✔
UNCOV
181
    if (!e || reason === 'blur') {
×
UNCOV
182
      return;
×
183
    }
UNCOV
184
    if (!value) {
×
UNCOV
185
      setDetailValue(null);
×
186
    }
UNCOV
187
    setTypeValue(value);
×
188
  };
189

190
  const onDetailFilterChange = (e, value) => {
10✔
UNCOV
191
    if (!e) {
×
UNCOV
192
      return;
×
193
    }
UNCOV
194
    setDetailValue(value);
×
195
  };
196

197
  const onTimeFilterChange = (currentStartDate = startDate, currentEndDate = endDate) =>
10!
198
    dispatch(setAuditlogsState({ page: 1, startDate: currentStartDate, endDate: currentEndDate }));
1✔
199

200
  const onChangePagination = (page, currentPerPage = perPage) => dispatch(setAuditlogsState({ page, perPage: currentPerPage }));
10!
201

202
  const typeOptionsMap = {
10✔
203
    Deployment: groups,
204
    User: Object.values(users),
205
    Device: []
206
  };
207
  const detailOptions = typeOptionsMap[type?.title] ?? [];
10✔
208

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

296
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