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

mendersoftware / gui / 944676341

pending completion
944676341

Pull #3875

gitlab-ci

mzedel
chore: aligned snapshots with updated design

Signed-off-by: Manuel Zedel <manuel.zedel@northern.tech>
Pull Request #3875: MEN-5414

4469 of 6446 branches covered (69.33%)

230 of 266 new or added lines in 43 files covered. (86.47%)

1712 existing lines in 161 files now uncovered.

8406 of 10170 relevant lines covered (82.65%)

196.7 hits per line

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

60.82
/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 { 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
export const AuditLogs = props => {
4✔
74
  const navigate = useNavigate();
20✔
75
  const [csvLoading, setCsvLoading] = useState(false);
19✔
76

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

80
  const [detailValue, setDetailValue] = useState(null);
19✔
81
  const [userValue, setUserValue] = useState(null);
19✔
82
  const [typeValue, setTypeValue] = useState(null);
19✔
83
  const [locationParams, setLocationParams] = useLocationParams('auditlogs', { today, tonight, defaults: { sort: { direction: SORTING_OPTIONS.desc } } });
19✔
84
  const { classes } = useStyles();
19✔
85
  const dispatch = useDispatch();
19✔
86
  const events = useSelector(state => state.organization.auditlog.events);
32✔
87
  const groups = useSelector(getGroupNames);
19✔
88
  const selectionState = useSelector(state => state.organization.auditlog.selectionState);
32✔
89
  const userCapabilities = useSelector(getUserCapabilities);
19✔
90
  const tenantCapabilities = useSelector(getTenantCapabilities);
19✔
91
  const users = useSelector(state => state.users.byId);
32✔
92
  const { canReadUsers } = userCapabilities;
19✔
93
  const { hasAuditlogs } = tenantCapabilities;
19✔
94

95
  const debouncedDetail = useDebounce(detailValue, TIMEOUTS.debounceDefault);
19✔
96
  const debouncedType = useDebounce(typeValue, TIMEOUTS.debounceDefault);
19✔
97
  const debouncedUser = useDebounce(userValue, TIMEOUTS.debounceDefault);
19✔
98

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

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

119
  useEffect(() => {
19✔
120
    if (!hasAuditlogs) {
3!
UNCOV
121
      return;
×
122
    }
123
    dispatch(setAuditlogsState({ page: 1, detail: debouncedDetail, type: debouncedType, user: debouncedUser }));
3✔
124
  }, [debouncedDetail, debouncedType, debouncedUser, hasAuditlogs]);
125

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

132
  useEffect(() => {
19✔
133
    if (!hasAuditlogs) {
10!
UNCOV
134
      return;
×
135
    }
136
    setLocationParams({ pageState: selectionState });
10✔
137
  }, [detail, endDate, hasAuditlogs, JSON.stringify(sort), perPage, selectionState.page, selectionState.selectedId, startDate, type, user]);
138

139
  useEffect(() => {
19✔
140
    const user = users[debouncedUser];
3✔
141
    if (debouncedUser?.id || !user) {
3!
142
      return;
3✔
143
    }
UNCOV
144
    setUserValue(user);
×
145
  }, [debouncedUser, JSON.stringify(users)]);
146

147
  const reset = () => {
19✔
148
    dispatch(
2✔
149
      setAuditlogsState({
150
        detail: null,
151
        endDate: tonight,
152
        page: 1,
153
        reset: !resetList,
154
        startDate: today,
155
        type: null,
156
        user: null
157
      })
158
    );
159
    setDetailValue(null);
2✔
160
    setTypeValue(null);
2✔
161
    setUserValue(null);
2✔
162
    navigate('/auditlog');
2✔
163
  };
164

165
  const createCsvDownload = () => {
19✔
166
    setCsvLoading(true);
1✔
167
    dispatch(getAuditLogsCsvLink()).then(address => {
1✔
168
      createDownload(
1✔
169
        encodeURI(address),
170
        `Mender-AuditLog-${moment(startDate).format(moment.HTML5_FMT.DATE)}-${moment(endDate).format(moment.HTML5_FMT.DATE)}.csv`
171
      );
172
      setCsvLoading(false);
1✔
173
    });
174
  };
175

176
  const onChangeSorting = () => {
19✔
UNCOV
177
    const currentSorting = sort.direction === SORTING_OPTIONS.desc ? SORTING_OPTIONS.asc : SORTING_OPTIONS.desc;
×
UNCOV
178
    dispatch(setAuditlogsState({ page: 1, sort: { direction: currentSorting } }));
×
179
  };
180

181
  const onUserFilterChange = (e, value, reason) => {
19✔
UNCOV
182
    if (!e || reason === 'blur') {
×
UNCOV
183
      return;
×
184
    }
UNCOV
185
    setUserValue(value);
×
186
  };
187

188
  const onTypeFilterChange = (e, value, reason) => {
19✔
UNCOV
189
    if (!e || reason === 'blur') {
×
UNCOV
190
      return;
×
191
    }
UNCOV
192
    if (!value) {
×
UNCOV
193
      setDetailValue(null);
×
194
    }
UNCOV
195
    setTypeValue(value);
×
196
  };
197

198
  const onDetailFilterChange = (e, value) => {
19✔
UNCOV
199
    if (!e) {
×
UNCOV
200
      return;
×
201
    }
UNCOV
202
    setDetailValue(value);
×
203
  };
204

205
  const onTimeFilterChange = (currentStartDate = startDate, currentEndDate = endDate) =>
19!
206
    dispatch(setAuditlogsState({ page: 1, startDate: currentStartDate, endDate: currentEndDate }));
1✔
207

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

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

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

319
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