• 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

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 } 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 { offlineThresholds, timeUnits } 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
    display: 'grid',
48
    gridTemplateColumns: '100px 100px',
49
    columnGap: theme.spacing(2)
50
  },
51
  textInput: {
52
    marginTop: 0,
53
    minWidth: 'initial'
54
  }
55
}));
56

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

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

64
  const changed = selectedAttribute !== attributeSelection;
4✔
65

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

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

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

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

117
export const GlobalSettingsDialog = ({
5✔
118
  attributes,
119
  hasReporting,
120
  isAdmin,
121
  notificationChannelSettings,
122
  offlineThresholdSettings,
123
  onChangeNotificationSetting,
124
  onCloseClick,
125
  onSaveClick,
126
  saveGlobalSettings,
127
  selectedAttribute,
128
  settings,
129
  tenantCapabilities,
130
  userCapabilities
131
}) => {
132
  const [channelSettings, setChannelSettings] = useState(notificationChannelSettings);
4✔
133
  const [currentInterval, setCurrentInterval] = useState(offlineThresholdSettings.interval);
4✔
134
  const [currentIntervalUnit, setCurrentIntervalUnit] = useState(offlineThresholdSettings.intervalUnit);
4✔
135
  const [intervalErrorText, setIntervalErrorText] = useState('');
4✔
136
  const debouncedOfflineThreshold = useDebounce({ interval: currentInterval, intervalUnit: currentIntervalUnit }, 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
    setCurrentIntervalUnit(offlineThresholdSettings.intervalUnit);
1✔
150
  }, [offlineThresholdSettings.interval, offlineThresholdSettings.intervalUnit]);
151

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

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

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

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

181
  const toggleDeploymentConfirmation = () => {
4✔
182
    saveGlobalSettings({ needsDeploymentConfirmation: !needsDeploymentConfirmation });
×
183
  };
184
  // sets interval to one day whenever disabled interval unit is used (MEN-6831). Should be removed later
185
  if (currentIntervalUnit && currentIntervalUnit !== timeUnits.days) {
4!
186
    setCurrentIntervalUnit(timeUnits.days);
×
187
    setCurrentInterval(1);
×
188
  }
189
  return (
4✔
190
    <div style={{ maxWidth }} className="margin-top-small">
191
      <div className="flexbox center-aligned">
192
        <h2 className="margin-top-small margin-right-small">Global settings</h2>
193
        <MenderHelpTooltip id={HELPTOOLTIPS.globalSettings.id} placement="top" />
194
      </div>
195
      <IdAttributeSelection attributes={attributes} onCloseClick={onCloseClick} onSaveClick={onSaveClick} selectedAttribute={selectedAttribute} />
196
      {hasReporting && <ReportingLimits />}
8✔
197
      <InputLabel className="margin-top" shrink>
198
        Deployments
199
      </InputLabel>
200
      <div className="clickable flexbox center-aligned" onClick={toggleDeploymentConfirmation}>
201
        <p className="help-content">Require confirmation on deployment creation</p>
202
        <Switch checked={needsDeploymentConfirmation} />
203
      </div>
204
      {canManageReleases && canDelta && <ArtifactGenerationSettings />}
12✔
205
      {isAdmin &&
8!
206
        hasMonitor &&
207
        Object.keys(alertChannels).map(channel => (
208
          <FormControl key={channel}>
×
209
            <InputLabel className="capitalized-start" shrink id={`${channel}-notifications`}>
210
              {channel} notifications
211
            </InputLabel>
212
            <FormControlLabel
213
              control={<Checkbox checked={!channelSettings[channel].enabled} onChange={e => onNotificationSettingsClick(e, channel)} />}
×
214
              label={`Mute ${channel} notifications`}
215
            />
216
            <FormHelperText className="info" component="div">
217
              Mute {channel} notifications for deployment and monitoring issues for all users
218
            </FormHelperText>
219
          </FormControl>
220
        ))}
221

222
      <InputLabel className="margin-top" shrink id="offline-theshold">
223
        Offline threshold
224
      </InputLabel>
225
      <div className={classes.threshold}>
226
        <Select onChange={onChangeOfflineIntervalUnit} value={currentIntervalUnit}>
227
          {offlineThresholds.map(value => (
228
            <MenuItem key={value} value={value}>
4✔
229
              <div className="capitalized-start">{value}</div>
230
            </MenuItem>
231
          ))}
232
        </Select>
233
        <TextField
234
          className={classes.textInput}
235
          type="number"
236
          onChange={onChangeOfflineInterval}
237
          inputProps={{ min: '1', max: '1000' }}
238
          error={!!intervalErrorText}
239
          value={currentInterval}
240
        />
241
      </div>
242
      {!!intervalErrorText && (
4!
243
        <FormHelperText className="warning" component="div">
244
          {intervalErrorText}
245
        </FormHelperText>
246
      )}
247
      <FormHelperText className="info" component="div">
248
        Choose how long a device can go without reporting to the server before it is considered “offline”.
249
      </FormHelperText>
250
    </div>
251
  );
252
};
253

254
export const GlobalSettingsContainer = ({ closeDialog, dialog }) => {
5✔
255
  const dispatch = useDispatch();
3✔
256
  const attributes = useSelector(getDeviceIdentityAttributes);
3✔
257
  const { hasReporting } = useSelector(getFeatures);
3✔
258
  const { isAdmin } = useSelector(getUserRoles);
3✔
259
  const notificationChannelSettings = useSelector(state => state.monitor.settings.global.channels);
7✔
260
  const offlineThresholdSettings = useSelector(getOfflineThresholdSettings);
3✔
261
  const { attribute: selectedAttribute } = useSelector(getIdAttribute);
3✔
262
  const settings = useSelector(getGlobalSettingsSelector);
3✔
263
  const tenantCapabilities = useSelector(getTenantCapabilities);
3✔
264
  const userCapabilities = useSelector(getUserCapabilities);
3✔
265

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

268
  useEffect(() => {
3✔
269
    if (!settings) {
1!
270
      dispatch(getGlobalSettings());
×
271
    }
272
    dispatch(getDeviceAttributes());
1✔
273
    // eslint-disable-next-line react-hooks/exhaustive-deps
274
  }, [dispatch, JSON.stringify(settings)]);
275

276
  useEffect(() => {
3✔
277
    setUpdatedSettings(current => ({ ...current, ...settings }));
1✔
278
    // eslint-disable-next-line react-hooks/exhaustive-deps
279
  }, [JSON.stringify(settings)]);
280

281
  const onCloseClick = e => {
3✔
282
    if (dialog) {
×
283
      return closeDialog(e);
×
284
    }
285
  };
286

287
  const saveAttributeSetting = (e, id_attribute) => {
3✔
288
    return dispatch(saveGlobalSettings({ ...updatedSettings, id_attribute }, false, true)).then(() => {
×
289
      if (dialog) {
×
290
        closeDialog(e);
×
291
      }
292
    });
293
  };
294

295
  const onChangeNotificationSetting = useCallback((...args) => dispatch(changeNotificationSetting(...args)), [dispatch]);
3✔
296
  const onSaveGlobalSettings = useCallback((...args) => dispatch(saveGlobalSettings(...args)), [dispatch]);
3✔
297

298
  if (dialog) {
3!
299
    return (
×
300
      <IdAttributeSelection
301
        attributes={attributes}
302
        dialog
303
        onCloseClick={onCloseClick}
304
        onSaveClick={saveAttributeSetting}
305
        selectedAttribute={selectedAttribute}
306
      />
307
    );
308
  }
309
  return (
3✔
310
    <GlobalSettingsDialog
311
      attributes={attributes}
312
      hasReporting={hasReporting}
313
      isAdmin={isAdmin}
314
      notificationChannelSettings={notificationChannelSettings}
315
      offlineThresholdSettings={offlineThresholdSettings}
316
      onChangeNotificationSetting={onChangeNotificationSetting}
317
      onCloseClick={onCloseClick}
318
      onSaveClick={saveAttributeSetting}
319
      saveGlobalSettings={onSaveGlobalSettings}
320
      settings={settings}
321
      selectedAttribute={selectedAttribute}
322
      tenantCapabilities={tenantCapabilities}
323
      userCapabilities={userCapabilities}
324
    />
325
  );
326
};
327
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