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

mendersoftware / gui / 1315496247

03 Jun 2024 07:49AM UTC coverage: 83.437% (-16.5%) from 99.964%
1315496247

Pull #4434

gitlab-ci

mzedel
chore: aligned snapshots with updated mui version

Signed-off-by: Manuel Zedel <manuel.zedel@northern.tech>
Pull Request #4434: chore: Bump the mui group with 3 updates

4476 of 6391 branches covered (70.04%)

8488 of 10173 relevant lines covered (83.44%)

140.36 hits per line

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

80.41
/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, { useCallback, useEffect, useRef, useState } from 'react';
15
import { useDispatch, useSelector } from 'react-redux';
16

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

20
import moment from 'moment';
21

22
import historyImage from '../../../assets/img/history.png';
23
import { getAuditLogs, getAuditLogsCsvLink, setAuditlogsState } from '../../actions/organizationActions';
24
import { getUserList } from '../../actions/userActions';
25
import { BEGINNING_OF_TIME, BENEFITS, SORTING_OPTIONS, TIMEOUTS } from '../../constants/appConstants';
26
import { AUDIT_LOGS_TYPES } from '../../constants/organizationConstants';
27
import { createDownload, getISOStringBoundaries } from '../../helpers';
28
import {
29
  getAuditLog,
30
  getAuditLogEntry,
31
  getAuditLogSelectionState,
32
  getCurrentSession,
33
  getGroupNames,
34
  getTenantCapabilities,
35
  getUserCapabilities
36
} from '../../selectors';
37
import { useLocationParams } from '../../utils/liststatehook';
38
import EnterpriseNotification, { DefaultUpgradeNotification } from '../common/enterpriseNotification';
39
import { ControlledAutoComplete } from '../common/forms/autocomplete';
40
import ClickFilter from '../common/forms/clickfilter';
41
import Filters from '../common/forms/filters';
42
import TimeframePicker from '../common/forms/timeframe-picker';
43
import { InfoHintContainer } from '../common/info-hint';
44
import Loader from '../common/loader';
45
import { HELPTOOLTIPS, MenderHelpTooltip } from '../helptips/helptooltips';
46
import AuditLogsList from './auditlogslist';
47

48
const detailsMap = {
3✔
49
  Deployment: 'to device group',
50
  User: 'email'
51
};
52

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

68
const getOptionLabel = option => option.title ?? option.email ?? option;
78✔
69

70
const renderOption = (props, option) => <li {...props}>{getOptionLabel(option)}</li>;
5✔
71

72
const isUserOptionEqualToValue = ({ email, id }, value) => id === value || email === value || email === value?.email;
3!
73

74
const autoSelectProps = {
3✔
75
  autoSelect: true,
76
  filterSelectedOptions: true,
77
  getOptionLabel,
78
  handleHomeEndKeys: true,
79
  renderOption
80
};
81

82
const locationDefaults = { sort: { direction: SORTING_OPTIONS.desc } };
3✔
83

84
export const AuditLogs = props => {
3✔
85
  const [csvLoading, setCsvLoading] = useState(false);
11✔
86

87
  const [date] = useState(getISOStringBoundaries(new Date()));
10✔
88
  const { start: today, end: tonight } = date;
10✔
89

90
  const isInitialized = useRef();
10✔
91
  const [locationParams, setLocationParams] = useLocationParams('auditlogs', { today, tonight, defaults: locationDefaults });
10✔
92
  const { classes } = useStyles();
10✔
93
  const dispatch = useDispatch();
10✔
94
  const events = useSelector(getAuditLog);
10✔
95
  const eventItem = useSelector(getAuditLogEntry);
10✔
96
  const groups = useSelector(getGroupNames);
10✔
97
  const selectionState = useSelector(getAuditLogSelectionState);
10✔
98
  const userCapabilities = useSelector(getUserCapabilities);
10✔
99
  const tenantCapabilities = useSelector(getTenantCapabilities);
10✔
100
  const users = useSelector(state => state.users.byId);
24✔
101
  const { canReadUsers } = userCapabilities;
10✔
102
  const { hasAuditlogs } = tenantCapabilities;
10✔
103
  const [detailsReset, setDetailsReset] = useState('');
10✔
104
  const [dirtyField, setDirtyField] = useState('');
10✔
105
  const { token } = useSelector(getCurrentSession);
10✔
106

107
  const { detail, isLoading, perPage, endDate, user, sort, startDate, total, type } = selectionState;
10✔
108

109
  useEffect(() => {
10✔
110
    if (!hasAuditlogs || !isInitialized.current) {
6!
111
      return;
6✔
112
    }
113
    setLocationParams({ pageState: selectionState });
×
114
    // eslint-disable-next-line react-hooks/exhaustive-deps
115
  }, [detail, endDate, hasAuditlogs, perPage, selectionState.page, selectionState.selectedId, setLocationParams, startDate, type, user]);
116

117
  useEffect(() => {
10✔
118
    if (!isInitialized.current) {
3!
119
      return;
3✔
120
    }
121
    setDetailsReset('detail');
×
122
    setTimeout(() => setDetailsReset(''), TIMEOUTS.debounceShort);
×
123
  }, [type?.value]);
124

125
  useEffect(() => {
10✔
126
    if (canReadUsers) {
3!
127
      dispatch(getUserList());
3✔
128
    }
129
  }, [canReadUsers, dispatch]);
130

131
  const initAuditlogState = useCallback(
10✔
132
    (result, state) => {
133
      const { detail, endDate, startDate, type, user } = state;
2✔
134
      const resultList = result ? Object.values(result.events) : [];
2!
135
      if (resultList.length && startDate === today) {
2✔
136
        let newStartDate = new Date(resultList[resultList.length - 1].time);
1✔
137
        const { start } = getISOStringBoundaries(newStartDate);
1✔
138
        state.startDate = start;
1✔
139
      }
140
      dispatch(setAuditlogsState(state));
2✔
141
      setTimeout(() => {
2✔
142
        let field = Object.entries({ detail, type, user }).reduce((accu, [key, value]) => (accu || value ? key : accu), '');
6!
143
        field = field || (endDate !== tonight ? 'endDate' : field);
2!
144
        field = field || (state.startDate !== today ? 'startDate' : field);
2!
145
        setDirtyField(field);
2✔
146
      }, TIMEOUTS.debounceDefault);
147
      // the timeout here is slightly longer than the debounce in the filter component, otherwise the population of the filters with the url state would trigger a reset to page 1
148
      setTimeout(() => (isInitialized.current = true), TIMEOUTS.oneSecond + TIMEOUTS.debounceDefault);
2✔
149
    },
150
    [dispatch, today, tonight]
151
  );
152

153
  useEffect(() => {
10✔
154
    if (!hasAuditlogs || isInitialized.current !== undefined) {
3✔
155
      return;
1✔
156
    }
157
    isInitialized.current = false;
2✔
158
    const { id, open, detail, endDate, startDate, type, user } = locationParams;
2✔
159
    let state = { ...locationParams };
2✔
160
    if (id && Boolean(open)) {
2!
161
      state.selectedId = id[0];
×
162
      const [eventAction, eventTime] = atob(state.selectedId).split('|');
×
163
      if (eventTime && !events.some(item => item.time === eventTime && item.action === eventAction)) {
×
164
        const { start, end } = getISOStringBoundaries(new Date(eventTime));
×
165
        state.endDate = end;
×
166
        state.startDate = start;
×
167
      }
168
      let field = endDate !== tonight ? 'endDate' : '';
×
169
      field = field || (startDate !== today ? 'startDate' : field);
×
170
      setDirtyField(field);
×
171
      // the timeout here is slightly longer than the debounce in the filter component, otherwise the population of the filters with the url state would trigger a reset to page 1
172
      dispatch(setAuditlogsState(state)).then(() => setTimeout(() => (isInitialized.current = true), TIMEOUTS.oneSecond + TIMEOUTS.debounceDefault));
×
173
      return;
×
174
    }
175
    dispatch(
2✔
176
      getAuditLogs({ page: state.page ?? 1, perPage: 50, startDate: startDate !== today ? startDate : BEGINNING_OF_TIME, endDate, user, type, detail })
6✔
177
    ).then(result => initAuditlogState(result, state));
2✔
178
    // eslint-disable-next-line react-hooks/exhaustive-deps
179
  }, [dispatch, hasAuditlogs, JSON.stringify(events), JSON.stringify(locationParams), initAuditlogState, today, tonight]);
180

181
  const createCsvDownload = () => {
10✔
182
    setCsvLoading(true);
1✔
183
    dispatch(getAuditLogsCsvLink()).then(address => {
1✔
184
      createDownload(
1✔
185
        encodeURI(address),
186
        `Mender-AuditLog-${moment(startDate).format(moment.HTML5_FMT.DATE)}-${moment(endDate).format(moment.HTML5_FMT.DATE)}.csv`,
187
        token
188
      );
189
      setCsvLoading(false);
1✔
190
    });
191
  };
192

193
  const onChangeSorting = () => {
10✔
194
    const currentSorting = sort.direction === SORTING_OPTIONS.desc ? SORTING_OPTIONS.asc : SORTING_OPTIONS.desc;
×
195
    dispatch(setAuditlogsState({ page: 1, sort: { direction: currentSorting } }));
×
196
  };
197

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

200
  const onFiltersChange = useCallback(
10✔
201
    ({ endDate, detail, startDate, user, type }) => {
202
      if (!isInitialized.current) {
3!
203
        return;
3✔
204
      }
205
      const selectedUser = Object.values(users).find(item => isUserOptionEqualToValue(item, user));
×
206
      dispatch(setAuditlogsState({ page: 1, detail, startDate, endDate, user: selectedUser, type }));
×
207
    },
208
    // eslint-disable-next-line react-hooks/exhaustive-deps
209
    [dispatch, JSON.stringify(users)]
210
  );
211

212
  const typeOptionsMap = {
10✔
213
    Deployment: groups,
214
    User: Object.values(users)
215
  };
216
  const detailOptions = typeOptionsMap[type?.title] ?? [];
10✔
217

218
  return (
10✔
219
    <div className="fadeIn margin-left flexbox column" style={{ marginRight: '5%' }}>
220
      <div className="flexbox center-aligned">
221
        <h3 className="margin-right-small">Audit log</h3>
222
        <InfoHintContainer>
223
          <EnterpriseNotification id={BENEFITS.auditlog.id} />
224
        </InfoHintContainer>
225
      </div>
226
      <ClickFilter disabled={!hasAuditlogs}>
227
        <Filters
228
          initialValues={{ startDate, endDate, user, type, detail }}
229
          defaultValues={{ startDate: today, endDate: tonight, user: '', type: null, detail: '' }}
230
          fieldResetTrigger={detailsReset}
231
          dirtyField={dirtyField}
232
          clearDirty={setDirtyField}
233
          filters={[
234
            {
235
              key: 'user',
236
              title: 'By user',
237
              Component: ControlledAutoComplete,
238
              componentProps: {
239
                ...autoSelectProps,
240
                freeSolo: true,
241
                isOptionEqualToValue: isUserOptionEqualToValue,
242
                options: Object.values(users),
243
                renderInput: params => <TextField {...params} placeholder="Select a user" InputProps={{ ...params.InputProps }} />
20✔
244
              }
245
            },
246
            {
247
              key: 'type',
248
              title: 'Change type',
249
              Component: ControlledAutoComplete,
250
              componentProps: {
251
                ...autoSelectProps,
252
                options: AUDIT_LOGS_TYPES,
253
                isOptionEqualToValue: (option, value) => option.value === value.value && option.object_type === value.object_type,
2✔
254
                renderInput: params => <TextField {...params} placeholder="Type" InputProps={{ ...params.InputProps }} />
25✔
255
              }
256
            },
257
            {
258
              key: 'detail',
259
              title: '',
260
              Component: ControlledAutoComplete,
261
              componentProps: {
262
                ...autoSelectProps,
263
                freeSolo: true,
264
                options: detailOptions,
265
                disabled: !type,
266
                renderInput: params => <TextField {...params} placeholder={detailsMap[type] || '-'} InputProps={{ ...params.InputProps }} />
20✔
267
              }
268
            },
269
            {
270
              key: 'timeframe',
271
              title: 'Start time',
272
              Component: TimeframePicker,
273
              componentProps: {
274
                tonight
275
              }
276
            }
277
          ]}
278
          onChange={onFiltersChange}
279
        />
280
      </ClickFilter>
281
      <div className="flexbox center-aligned" style={{ justifyContent: 'flex-end' }}>
282
        <Loader show={csvLoading} />
283
        <Button variant="contained" color="secondary" disabled={csvLoading || !total} onClick={createCsvDownload} style={{ marginLeft: 15 }}>
18✔
284
          Download results as csv
285
        </Button>
286
      </div>
287
      {!!total && (
20✔
288
        <AuditLogsList
289
          {...props}
290
          items={events}
291
          eventItem={eventItem}
292
          loading={isLoading}
293
          onChangePage={onChangePagination}
294
          onChangeRowsPerPage={newPerPage => onChangePagination(1, newPerPage)}
×
295
          onChangeSorting={onChangeSorting}
296
          selectionState={selectionState}
297
          setAuditlogsState={state => dispatch(setAuditlogsState(state))}
1✔
298
          userCapabilities={userCapabilities}
299
        />
300
      )}
301
      {!(isLoading || total) && hasAuditlogs && (
28!
302
        <div className="dashboard-placeholder">
303
          <p>No log entries were found.</p>
304
          <p>Try adjusting the filters.</p>
305
          <img src={historyImage} alt="Past" />
306
        </div>
307
      )}
308
      {!hasAuditlogs && (
11✔
309
        <div className={`dashboard-placeholder flexbox ${classes.upgradeNote}`}>
310
          <DefaultUpgradeNotification className="margin-right-small" />
311
          <MenderHelpTooltip id={HELPTOOLTIPS.auditlogExplanation.id} />
312
        </div>
313
      )}
314
    </div>
315
  );
316
};
317

318
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