• 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

71.43
/src/js/components/settings/global.js
1
// Copyright 2018 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, Checkbox, FormControl, FormControlLabel, FormHelperText, InputLabel, MenuItem, Select, Switch, TextField, Typography } from '@mui/material';
18
import { makeStyles } from 'tss-react/mui';
19

20
import { getDeviceAttributes } from '../../actions/deviceActions';
21
import { changeNotificationSetting } from '../../actions/monitorActions';
22
import { getGlobalSettings, saveGlobalSettings } from '../../actions/userActions';
23
import { TIMEOUTS } from '../../constants/appConstants';
24
import { DEVICE_ONLINE_CUTOFF } from '../../constants/deviceConstants';
25
import { alertChannels } from '../../constants/monitorConstants';
26
import { settingsKeys } from '../../constants/userConstants';
27
import {
28
  getDeviceIdentityAttributes,
29
  getFeatures,
30
  getGlobalSettings as getGlobalSettingsSelector,
31
  getIdAttribute,
32
  getOfflineThresholdSettings,
33
  getTenantCapabilities,
34
  getUserCapabilities,
35
  getUserRoles
36
} from '../../selectors';
37
import { useDebounce } from '../../utils/debouncehook';
38
import DocsLink from '../common/docslink';
39
import { HELPTOOLTIPS, MenderHelpTooltip } from '../helptips/helptooltips';
40
import ArtifactGenerationSettings from './artifactgeneration';
41
import ReportingLimits from './reportinglimits';
42

43
const maxWidth = 750;
5✔
44

45
const useStyles = makeStyles()(theme => ({
5✔
46
  threshold: {
47
    alignItems: 'baseline',
48
    columnGap: theme.spacing(2),
49
    display: 'grid',
50
    gridTemplateColumns: '100px 100px'
51
  },
52
  textInput: {
53
    marginTop: 0,
54
    minWidth: 'initial'
55
  }
56
}));
57

58
export const IdAttributeSelection = ({ attributes, dialog = false, onCloseClick, onSaveClick, selectedAttribute = '' }) => {
5!
59
  const [attributeSelection, setAttributeSelection] = useState('name');
3✔
60

61
  useEffect(() => {
3✔
62
    setAttributeSelection(selectedAttribute);
1✔
63
  }, [selectedAttribute]);
64

65
  const changed = selectedAttribute !== attributeSelection;
3✔
66

67
  const onChangeIdAttribute = ({ target: { value: attributeSelection } }) => {
3✔
UNCOV
68
    setAttributeSelection(attributeSelection);
×
UNCOV
69
    if (dialog) {
×
UNCOV
70
      return;
×
71
    }
UNCOV
72
    onSaveClick(undefined, { attribute: attributeSelection, scope: attributes.find(({ value }) => value === attributeSelection).scope });
×
73
  };
74

75
  const undoChanges = e => {
3✔
UNCOV
76
    setAttributeSelection(selectedAttribute);
×
UNCOV
77
    if (dialog) {
×
UNCOV
78
      onCloseClick(e);
×
79
    }
80
  };
81

82
  const saveSettings = e => onSaveClick(e, { attribute: attributeSelection, scope: attributes.find(({ value }) => value === attributeSelection).scope });
3✔
83

84
  return (
3✔
85
    <div className="flexbox space-between" style={{ alignItems: 'flex-start', maxWidth }}>
86
      <FormControl>
87
        <InputLabel shrink id="device-id">
88
          Device identity attribute
89
        </InputLabel>
90
        <Select value={attributeSelection} onChange={onChangeIdAttribute}>
91
          {attributes.map(item => (
92
            <MenuItem key={item.value} value={item.value}>
10✔
93
              {item.label}
94
            </MenuItem>
95
          ))}
96
        </Select>
97
        <FormHelperText className="info" component="div">
98
          <div className="margin-top-small margin-bottom-small">Choose a device identity attribute to use to identify your devices throughout the UI.</div>
99
          <div className="margin-top-small margin-bottom-small">
100
            <DocsLink path="client-installation/identity" title="Learn how to add custom identity attributes" /> to your devices.
101
          </div>
102
        </FormHelperText>
103
      </FormControl>
104
      {dialog && (
3!
105
        <div className="margin-left margin-top flexbox">
106
          <Button onClick={undoChanges} style={{ marginRight: 10 }}>
107
            Cancel
108
          </Button>
109
          <Button variant="contained" onClick={saveSettings} disabled={!changed} color="primary">
110
            Save
111
          </Button>
112
        </div>
113
      )}
114
    </div>
115
  );
116
};
117

118
export const GlobalSettingsDialog = ({
5✔
119
  attributes,
120
  hasReporting,
121
  isAdmin,
122
  notificationChannelSettings,
123
  offlineThresholdSettings,
124
  onChangeNotificationSetting,
125
  onCloseClick,
126
  onSaveClick,
127
  saveGlobalSettings,
128
  selectedAttribute,
129
  settings,
130
  tenantCapabilities,
131
  userCapabilities
132
}) => {
133
  const [channelSettings, setChannelSettings] = useState(notificationChannelSettings);
4✔
134
  const [currentInterval, setCurrentInterval] = useState(offlineThresholdSettings.interval);
4✔
135
  const [intervalErrorText, setIntervalErrorText] = useState('');
4✔
136
  const debouncedOfflineThreshold = useDebounce(currentInterval, TIMEOUTS.threeSeconds);
4✔
137
  const timer = useRef(false);
4✔
138
  const { classes } = useStyles();
4✔
139
  const { needsDeploymentConfirmation = false } = settings;
4✔
140
  const { canDelta, hasMonitor } = tenantCapabilities;
4✔
141
  const { canManageReleases } = userCapabilities;
4✔
142

143
  useEffect(() => {
4✔
144
    setChannelSettings(notificationChannelSettings);
1✔
145
  }, [notificationChannelSettings]);
146

147
  useEffect(() => {
4✔
148
    setCurrentInterval(offlineThresholdSettings.interval);
1✔
149
  }, [offlineThresholdSettings.interval]);
150

151
  useEffect(() => {
4✔
152
    if (!window.sessionStorage.getItem(settingsKeys.initialized) || !timer.current) {
1!
153
      return;
1✔
154
    }
UNCOV
155
    saveGlobalSettings({ offlineThreshold: { interval: debouncedOfflineThreshold, intervalUnit: DEVICE_ONLINE_CUTOFF.intervalName } }, false, true);
×
156
    // eslint-disable-next-line react-hooks/exhaustive-deps
157
  }, [debouncedOfflineThreshold, saveGlobalSettings]);
158

159
  useEffect(() => {
4✔
160
    const initTimer = setTimeout(() => (timer.current = true), TIMEOUTS.fiveSeconds);
1✔
161
    return () => {
1✔
162
      clearTimeout(initTimer);
1✔
163
    };
164
  }, []);
165

166
  const onNotificationSettingsClick = ({ target: { checked } }, channel) => {
4✔
UNCOV
167
    setChannelSettings({ ...channelSettings, channel: { enabled: !checked } });
×
UNCOV
168
    onChangeNotificationSetting(!checked, channel);
×
169
  };
170

171
  const onChangeOfflineInterval = ({ target: { validity, value } }) => {
4✔
UNCOV
172
    if (validity.valid) {
×
UNCOV
173
      setCurrentInterval(value || 1);
×
UNCOV
174
      return setIntervalErrorText('');
×
175
    }
UNCOV
176
    setIntervalErrorText('Please enter a valid number between 1 and 1000.');
×
177
  };
178

179
  const toggleDeploymentConfirmation = () => {
4✔
UNCOV
180
    saveGlobalSettings({ needsDeploymentConfirmation: !needsDeploymentConfirmation });
×
181
  };
182

183
  return (
4✔
184
    <div style={{ maxWidth }} className="margin-top-small">
185
      <div className="flexbox center-aligned">
186
        <h2 className="margin-top-small margin-right-small">Global settings</h2>
187
        <MenderHelpTooltip id={HELPTOOLTIPS.globalSettings.id} placement="top" />
188
      </div>
189
      <IdAttributeSelection attributes={attributes} onCloseClick={onCloseClick} onSaveClick={onSaveClick} selectedAttribute={selectedAttribute} />
190
      {hasReporting && <ReportingLimits />}
8✔
191
      <InputLabel className="margin-top" shrink>
192
        Deployments
193
      </InputLabel>
194
      <div className="clickable flexbox center-aligned" onClick={toggleDeploymentConfirmation}>
195
        <p className="help-content">Require confirmation on deployment creation</p>
196
        <Switch checked={needsDeploymentConfirmation} />
197
      </div>
198
      {canManageReleases && canDelta && <ArtifactGenerationSettings />}
12✔
199
      {isAdmin &&
8!
200
        hasMonitor &&
201
        Object.keys(alertChannels).map(channel => (
UNCOV
202
          <FormControl key={channel}>
×
203
            <InputLabel className="capitalized-start" shrink id={`${channel}-notifications`}>
204
              {channel} notifications
205
            </InputLabel>
206
            <FormControlLabel
UNCOV
207
              control={<Checkbox checked={!channelSettings[channel].enabled} onChange={e => onNotificationSettingsClick(e, channel)} />}
×
208
              label={`Mute ${channel} notifications`}
209
            />
210
            <FormHelperText className="info" component="div">
211
              Mute {channel} notifications for deployment and monitoring issues for all users
212
            </FormHelperText>
213
          </FormControl>
214
        ))}
215

216
      <InputLabel className="margin-top" shrink id="offline-theshold">
217
        Offline threshold
218
      </InputLabel>
219
      <div className={classes.threshold}>
220
        <TextField
221
          className={classes.textInput}
222
          type="number"
223
          onChange={onChangeOfflineInterval}
224
          inputProps={{ min: '1', max: '1000' }}
225
          error={!!intervalErrorText}
226
          value={currentInterval}
227
        />
228
        <Typography className="capitalized-start" variant="body1">
229
          {DEVICE_ONLINE_CUTOFF.intervalName}
230
        </Typography>
231
      </div>
232
      {!!intervalErrorText && (
4!
233
        <FormHelperText className="warning" component="div">
234
          {intervalErrorText}
235
        </FormHelperText>
236
      )}
237
      <FormHelperText className="info" component="div">
238
        Choose how long a device can go without reporting to the server before it is considered “offline”.
239
      </FormHelperText>
240
    </div>
241
  );
242
};
243

244
export const GlobalSettingsContainer = ({ closeDialog, dialog }) => {
5✔
245
  const dispatch = useDispatch();
3✔
246
  const attributes = useSelector(getDeviceIdentityAttributes);
3✔
247
  const { hasReporting } = useSelector(getFeatures);
3✔
248
  const { isAdmin } = useSelector(getUserRoles);
3✔
249
  const notificationChannelSettings = useSelector(state => state.monitor.settings.global.channels);
7✔
250
  const offlineThresholdSettings = useSelector(getOfflineThresholdSettings);
3✔
251
  const { attribute: selectedAttribute } = useSelector(getIdAttribute);
3✔
252
  const settings = useSelector(getGlobalSettingsSelector);
3✔
253
  const tenantCapabilities = useSelector(getTenantCapabilities);
3✔
254
  const userCapabilities = useSelector(getUserCapabilities);
3✔
255

256
  const [updatedSettings, setUpdatedSettings] = useState({ ...settings });
3✔
257

258
  useEffect(() => {
3✔
259
    if (!settings) {
1!
UNCOV
260
      dispatch(getGlobalSettings());
×
261
    }
262
    dispatch(getDeviceAttributes());
1✔
263
    // eslint-disable-next-line react-hooks/exhaustive-deps
264
  }, [dispatch, JSON.stringify(settings)]);
265

266
  useEffect(() => {
3✔
267
    setUpdatedSettings(current => ({ ...current, ...settings }));
1✔
268
    // eslint-disable-next-line react-hooks/exhaustive-deps
269
  }, [JSON.stringify(settings)]);
270

271
  const onCloseClick = e => {
3✔
UNCOV
272
    if (dialog) {
×
UNCOV
273
      return closeDialog(e);
×
274
    }
275
  };
276

277
  const onChangeNotificationSetting = useCallback((...args) => dispatch(changeNotificationSetting(...args)), [dispatch]);
3✔
278
  const onSaveGlobalSettings = useCallback((...args) => dispatch(saveGlobalSettings(...args)), [dispatch]);
3✔
279

280
  const saveAttributeSetting = (e, id_attribute) =>
3✔
UNCOV
281
    onSaveGlobalSettings({ ...updatedSettings, id_attribute }, false, true).then(() => {
×
UNCOV
282
      if (dialog) {
×
UNCOV
283
        closeDialog(e);
×
284
      }
285
    });
286

287
  if (dialog) {
3!
UNCOV
288
    return (
×
289
      <IdAttributeSelection
290
        attributes={attributes}
291
        dialog
292
        onCloseClick={onCloseClick}
293
        onSaveClick={saveAttributeSetting}
294
        selectedAttribute={selectedAttribute}
295
      />
296
    );
297
  }
298
  return (
3✔
299
    <GlobalSettingsDialog
300
      attributes={attributes}
301
      hasReporting={hasReporting}
302
      isAdmin={isAdmin}
303
      notificationChannelSettings={notificationChannelSettings}
304
      offlineThresholdSettings={offlineThresholdSettings}
305
      onChangeNotificationSetting={onChangeNotificationSetting}
306
      onCloseClick={onCloseClick}
307
      onSaveClick={saveAttributeSetting}
308
      saveGlobalSettings={onSaveGlobalSettings}
309
      settings={settings}
310
      selectedAttribute={selectedAttribute}
311
      tenantCapabilities={tenantCapabilities}
312
      userCapabilities={userCapabilities}
313
    />
314
  );
315
};
316
export default GlobalSettingsContainer;
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