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

mendersoftware / gui / 995616460

07 Sep 2023 08:29AM UTC coverage: 82.384% (-17.6%) from 99.964%
995616460

Pull #4023

gitlab-ci

mender-test-bot
chore: Types update

Signed-off-by: Mender Test Bot <mender@northern.tech>
Pull Request #4023: chore: Types update

4346 of 6321 branches covered (0.0%)

8259 of 10025 relevant lines covered (82.38%)

194.41 hits per line

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

75.25
/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, useRef, 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 { BENEFITS, 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 EnterpriseNotification, { DefaultUpgradeNotification } from '../common/enterpriseNotification';
33
import ClickFilter from '../common/forms/clickfilter';
34
import { InfoHintContainer } from '../common/info-hint';
35
import Loader from '../common/loader';
36
import TimeframePicker from '../common/timeframe-picker';
37
import TimerangePicker from '../common/timerange-picker';
38
import { HELPTOOLTIPS, MenderHelpTooltip } from '../helptips/helptooltips';
39
import AuditLogsList from './auditlogslist';
40

41
const detailsMap = {
4✔
42
  Deployment: 'to device group',
43
  User: 'email'
44
};
45

46
const useStyles = makeStyles()(theme => ({
4✔
47
  filters: {
48
    backgroundColor: theme.palette.background.lightgrey,
49
    padding: '0px 25px 5px',
50
    display: 'grid',
51
    gridTemplateColumns: '400px 250px 250px 1fr',
52
    gridColumnGap: theme.spacing(2),
53
    gridRowGap: theme.spacing(2)
54
  },
55
  filterReset: { alignSelf: 'flex-end', marginBottom: 5 },
56
  timeframe: { gridColumnStart: 2, gridColumnEnd: 4, marginLeft: 7.5 },
57
  typeDetails: { marginRight: 15, marginTop: theme.spacing(2) },
58
  upgradeNote: { marginTop: '5vh', placeSelf: 'center' }
59
}));
60

61
const getOptionLabel = option => option.title || option.email || option;
4!
62

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

65
const autoSelectProps = {
4✔
66
  autoSelect: true,
67
  filterSelectedOptions: true,
68
  getOptionLabel,
69
  handleHomeEndKeys: true,
70
  renderOption
71
};
72

73
const locationDefaults = { sort: { direction: SORTING_OPTIONS.desc } };
4✔
74

75
export const AuditLogs = props => {
4✔
76
  const navigate = useNavigate();
14✔
77
  const [csvLoading, setCsvLoading] = useState(false);
13✔
78

79
  const [date] = useState(getISOStringBoundaries(new Date()));
13✔
80
  const { start: today, end: tonight } = date;
13✔
81

82
  const [detailValue, setDetailValue] = useState(null);
13✔
83
  const [userValue, setUserValue] = useState(null);
13✔
84
  const [typeValue, setTypeValue] = useState(null);
13✔
85
  const isInitialized = useRef();
13✔
86
  const [locationParams, setLocationParams] = useLocationParams('auditlogs', { today, tonight, defaults: locationDefaults });
13✔
87
  const { classes } = useStyles();
13✔
88
  const dispatch = useDispatch();
13✔
89
  const events = useSelector(state => state.organization.auditlog.events);
24✔
90
  const groups = useSelector(getGroupNames);
13✔
91
  const selectionState = useSelector(state => state.organization.auditlog.selectionState);
24✔
92
  const userCapabilities = useSelector(getUserCapabilities);
13✔
93
  const tenantCapabilities = useSelector(getTenantCapabilities);
13✔
94
  const users = useSelector(state => state.users.byId);
24✔
95
  const { canReadUsers } = userCapabilities;
13✔
96
  const { hasAuditlogs } = tenantCapabilities;
13✔
97

98
  const debouncedDetail = useDebounce(detailValue, TIMEOUTS.debounceDefault);
13✔
99
  const debouncedType = useDebounce(typeValue, TIMEOUTS.debounceDefault);
13✔
100
  const debouncedUser = useDebounce(userValue, TIMEOUTS.debounceDefault);
13✔
101

102
  const { detail, isLoading, perPage, endDate, user, reset: resetList, sort, startDate, total, type } = selectionState;
13✔
103

104
  useEffect(() => {
13✔
105
    if (!hasAuditlogs || !isInitialized.current) {
10!
106
      return;
10✔
107
    }
108
    setLocationParams({ pageState: selectionState });
×
109
    // eslint-disable-next-line react-hooks/exhaustive-deps
110
  }, [detail, endDate, hasAuditlogs, perPage, selectionState.page, selectionState.selectedId, setLocationParams, startDate, type, user]);
111

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

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

125
  useEffect(() => {
13✔
126
    const user = users[debouncedUser?.id];
3✔
127
    if (debouncedUser?.id || !user) {
3!
128
      return;
3✔
129
    }
130
    setUserValue(user);
×
131
    // eslint-disable-next-line react-hooks/exhaustive-deps
132
  }, [debouncedUser, JSON.stringify(users)]);
133

134
  useEffect(() => {
13✔
135
    if (!hasAuditlogs) {
4!
136
      return;
×
137
    }
138
    isInitialized.current = false;
4✔
139
    let state = { ...locationParams };
4✔
140
    if (locationParams.id && Boolean(locationParams.open)) {
4!
141
      state.selectedId = locationParams.id[0];
×
142
      const [eventAction, eventTime] = atob(state.selectedId).split('|');
×
143
      if (eventTime && !events.some(item => item.time === eventTime && item.action === eventAction)) {
×
144
        const { start, end } = getISOStringBoundaries(new Date(eventTime));
×
145
        state.endDate = end;
×
146
        state.startDate = start;
×
147
      }
148
    }
149
    dispatch(setAuditlogsState(state));
4✔
150
    Object.entries({ detail: setDetailValue, user: setUserValue, type: setTypeValue }).map(([key, setter]) => (state[key] ? setter(state[key]) : undefined));
12!
151
    setTimeout(() => (isInitialized.current = true), TIMEOUTS.debounceDefault);
4✔
152
    // eslint-disable-next-line react-hooks/exhaustive-deps
153
  }, [dispatch, hasAuditlogs, JSON.stringify(events), JSON.stringify(locationParams)]);
154

155
  const reset = () => {
13✔
156
    dispatch(
2✔
157
      setAuditlogsState({
158
        detail: null,
159
        endDate: tonight,
160
        page: 1,
161
        reset: !resetList,
162
        startDate: today,
163
        type: null,
164
        user: null
165
      })
166
    );
167
    setDetailValue(null);
2✔
168
    setTypeValue(null);
2✔
169
    setUserValue(null);
2✔
170
    navigate('/auditlog');
2✔
171
  };
172

173
  const createCsvDownload = () => {
13✔
174
    setCsvLoading(true);
1✔
175
    dispatch(getAuditLogsCsvLink()).then(address => {
1✔
176
      createDownload(
1✔
177
        encodeURI(address),
178
        `Mender-AuditLog-${moment(startDate).format(moment.HTML5_FMT.DATE)}-${moment(endDate).format(moment.HTML5_FMT.DATE)}.csv`
179
      );
180
      setCsvLoading(false);
1✔
181
    });
182
  };
183

184
  const onChangeSorting = () => {
13✔
185
    const currentSorting = sort.direction === SORTING_OPTIONS.desc ? SORTING_OPTIONS.asc : SORTING_OPTIONS.desc;
×
186
    dispatch(setAuditlogsState({ page: 1, sort: { direction: currentSorting } }));
×
187
  };
188

189
  const onUserFilterChange = (e, value, reason) => {
13✔
190
    if (!e || reason === 'blur') {
×
191
      return;
×
192
    }
193
    setUserValue(value);
×
194
  };
195

196
  const onTypeFilterChange = (e, value, reason) => {
13✔
197
    if (!e || reason === 'blur') {
×
198
      return;
×
199
    }
200
    if (!value) {
×
201
      setDetailValue(null);
×
202
    }
203
    setTypeValue(value);
×
204
  };
205

206
  const onDetailFilterChange = (e, value) => {
13✔
207
    if (!e) {
×
208
      return;
×
209
    }
210
    setDetailValue(value);
×
211
  };
212

213
  const onTimeFilterChange = (currentStartDate = startDate, currentEndDate = endDate) =>
13!
214
    dispatch(setAuditlogsState({ page: 1, startDate: currentStartDate, endDate: currentEndDate }));
1✔
215

216
  const onChangePagination = (page, currentPerPage = perPage) => dispatch(setAuditlogsState({ page, perPage: currentPerPage }));
13!
217

218
  const typeOptionsMap = {
13✔
219
    Deployment: groups,
220
    User: Object.values(users),
221
    Device: []
222
  };
223
  const detailOptions = typeOptionsMap[type?.title] ?? [];
13✔
224

225
  return (
13✔
226
    <div className="fadeIn margin-left flexbox column" style={{ marginRight: '5%' }}>
227
      <div className="flexbox center-aligned">
228
        <h3 className="margin-right-small">Audit log</h3>
229
        <InfoHintContainer>
230
          <EnterpriseNotification id={BENEFITS.auditlog.id} />
231
        </InfoHintContainer>
232
      </div>
233
      <ClickFilter disabled={!hasAuditlogs}>
234
        <div className={`margin-bottom margin-top-small ${classes.filters}`}>
235
          <Autocomplete
236
            {...autoSelectProps}
237
            disabled={!hasAuditlogs}
238
            id="audit-log-user-selection"
239
            freeSolo
240
            options={Object.values(users)}
241
            onChange={onUserFilterChange}
242
            isOptionEqualToValue={({ email, id }, value) => id === value || email === value || email === value.email}
×
243
            value={userValue}
244
            renderInput={params => (
245
              <TextField
13✔
246
                {...params}
247
                label="Filter by user"
248
                placeholder="Select a user"
249
                InputLabelProps={{ shrink: true }}
250
                InputProps={{ ...params.InputProps }}
251
              />
252
            )}
253
            style={{ maxWidth: 250 }}
254
          />
255
          <Autocomplete
256
            {...autoSelectProps}
257
            disabled={!hasAuditlogs}
258
            id="audit-log-type-selection"
259
            onChange={onTypeFilterChange}
260
            options={AUDIT_LOGS_TYPES}
261
            renderInput={params => (
262
              <TextField {...params} label="Filter by change" placeholder="Type" InputLabelProps={{ shrink: true }} InputProps={{ ...params.InputProps }} />
13✔
263
            )}
264
            style={{ marginLeft: 7.5 }}
265
            value={typeValue}
266
          />
267
          <Autocomplete
268
            {...autoSelectProps}
269
            className={classes.typeDetails}
270
            id="audit-log-type-details-selection"
271
            key={`audit-log-type-details-selection-${type}`}
272
            disabled={!type || !hasAuditlogs}
13!
273
            freeSolo
274
            value={detailValue}
275
            onInputChange={onDetailFilterChange}
276
            options={detailOptions}
277
            renderInput={params => <TextField {...params} placeholder={detailsMap[type] || '-'} InputProps={{ ...params.InputProps }} />}
16✔
278
          />
279
          <div />
280
          <TimerangePicker disabled={!hasAuditlogs} endDate={endDate} onChange={onTimeFilterChange} startDate={startDate} />
281
          <div className={classes.timeframe}>
282
            <TimeframePicker disabled={!hasAuditlogs} onChange={onTimeFilterChange} endDate={endDate} startDate={startDate} tonight={tonight} />
283
          </div>
284
          {hasAuditlogs && !!(user || type || detail || startDate !== today || endDate !== tonight) && (
91✔
285
            <span className={`link ${classes.filterReset} ${hasAuditlogs ? '' : 'muted'}`} onClick={reset}>
5!
286
              clear filter
287
            </span>
288
          )}
289
        </div>
290
      </ClickFilter>
291
      <div className="flexbox center-aligned" style={{ justifyContent: 'flex-end' }}>
292
        <Loader show={csvLoading} />
293
        <Button variant="contained" color="secondary" disabled={csvLoading || !total} onClick={createCsvDownload} style={{ marginLeft: 15 }}>
25✔
294
          Download results as csv
295
        </Button>
296
      </div>
297
      {!!total && (
26✔
298
        <AuditLogsList
299
          {...props}
300
          items={events}
301
          loading={isLoading}
302
          onChangePage={onChangePagination}
303
          onChangeRowsPerPage={newPerPage => onChangePagination(1, newPerPage)}
×
304
          onChangeSorting={onChangeSorting}
305
          selectionState={selectionState}
306
          setAuditlogsState={state => dispatch(setAuditlogsState(state))}
1✔
307
          userCapabilities={userCapabilities}
308
        />
309
      )}
310
      {!(isLoading || total) && hasAuditlogs && (
29!
311
        <div className="dashboard-placeholder">
312
          <p>No log entries were found.</p>
313
          <p>Try adjusting the filters.</p>
314
          <img src={historyImage} alt="Past" />
315
        </div>
316
      )}
317
      {!hasAuditlogs && (
13!
318
        <div className={`dashboard-placeholder flexbox ${classes.upgradeNote}`}>
319
          <DefaultUpgradeNotification className="margin-right-small" />
320
          <MenderHelpTooltip id={HELPTOOLTIPS.auditlogExplanation.id} />
321
        </div>
322
      )}
323
    </div>
324
  );
325
};
326

327
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