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

mendersoftware / gui / 1350829378

27 Jun 2024 01:46PM UTC coverage: 83.494% (-16.5%) from 99.965%
1350829378

Pull #4465

gitlab-ci

mzedel
chore: test fixes

Signed-off-by: Manuel Zedel <manuel.zedel@northern.tech>
Pull Request #4465: MEN-7169 - feat: added multi sorting capabilities to devices view

4506 of 6430 branches covered (70.08%)

81 of 100 new or added lines in 14 files covered. (81.0%)

1661 existing lines in 163 files now uncovered.

8574 of 10269 relevant lines covered (83.49%)

160.6 hits per line

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

80.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, { 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;
94✔
69

70
const renderOption = (props, option) => <li {...props}>{getOptionLabel(option)}</li>;
13✔
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
export const AuditLogs = props => {
3✔
83
  const [csvLoading, setCsvLoading] = useState(false);
11✔
84

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

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

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

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

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

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

129
  const initAuditlogState = useCallback(
10✔
130
    (result, state) => {
131
      const { detail, endDate, startDate, type, user } = state;
2✔
132
      const resultList = result ? Object.values(result.events) : [];
2!
133
      if (resultList.length && startDate === today) {
2✔
134
        let newStartDate = new Date(resultList[resultList.length - 1].time);
1✔
135
        const { start } = getISOStringBoundaries(newStartDate);
1✔
136
        state.startDate = start;
1✔
137
      }
138
      dispatch(setAuditlogsState(state));
2✔
139
      setTimeout(() => {
2✔
140
        let field = Object.entries({ detail, type, user }).reduce((accu, [key, value]) => (accu || value ? key : accu), '');
6!
141
        field = field || (endDate !== tonight ? 'endDate' : field);
2!
142
        field = field || (state.startDate !== today ? 'startDate' : field);
2!
143
        setDirtyField(field);
2✔
144
      }, TIMEOUTS.debounceDefault);
145
      // 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
146
      setTimeout(() => (isInitialized.current = true), TIMEOUTS.oneSecond + TIMEOUTS.debounceDefault);
2✔
147
    },
148
    [dispatch, today, tonight]
149
  );
150

151
  useEffect(() => {
10✔
152
    if (!hasAuditlogs || isInitialized.current !== undefined) {
3✔
153
      return;
1✔
154
    }
155
    isInitialized.current = false;
2✔
156
    const { id, open, detail, endDate, startDate, type, user } = locationParams;
2✔
157
    let state = { ...locationParams };
2✔
158
    if (id && Boolean(open)) {
2!
UNCOV
159
      state.selectedId = id[0];
×
UNCOV
160
      const [eventAction, eventTime] = atob(state.selectedId).split('|');
×
UNCOV
161
      if (eventTime && !events.some(item => item.time === eventTime && item.action === eventAction)) {
×
UNCOV
162
        const { start, end } = getISOStringBoundaries(new Date(eventTime));
×
UNCOV
163
        state.endDate = end;
×
UNCOV
164
        state.startDate = start;
×
165
      }
UNCOV
166
      let field = endDate !== tonight ? 'endDate' : '';
×
UNCOV
167
      field = field || (startDate !== today ? 'startDate' : field);
×
UNCOV
168
      setDirtyField(field);
×
169
      // 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
UNCOV
170
      dispatch(setAuditlogsState(state)).then(() => setTimeout(() => (isInitialized.current = true), TIMEOUTS.oneSecond + TIMEOUTS.debounceDefault));
×
UNCOV
171
      return;
×
172
    }
173
    dispatch(
2✔
174
      getAuditLogs({ page: state.page ?? 1, perPage: 50, startDate: startDate !== today ? startDate : BEGINNING_OF_TIME, endDate, user, type, detail })
6✔
175
    ).then(result => initAuditlogState(result, state));
2✔
176
    // eslint-disable-next-line react-hooks/exhaustive-deps
177
  }, [dispatch, hasAuditlogs, JSON.stringify(events), JSON.stringify(locationParams), initAuditlogState, today, tonight]);
178

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

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

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

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

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

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

316
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