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

mendersoftware / gui / 995616460

07 Sep 2023 08:29AM UTC coverage: 82.384% (-17.6%) from 99.964%
995616460

Pull #4023

gitlab-ci

mender-test-bot
chore: Types update

Signed-off-by: Mender Test Bot <mender@northern.tech>
Pull Request #4023: chore: Types update

4346 of 6321 branches covered (0.0%)

8259 of 10025 relevant lines covered (82.38%)

194.41 hits per line

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

88.06
/src/js/components/header/header.js
1
// Copyright 2015 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
import { Link } from 'react-router-dom';
17

18
import {
19
  AccountCircle as AccountCircleIcon,
20
  ArrowDropDown as ArrowDropDownIcon,
21
  ArrowDropUp as ArrowDropUpIcon,
22
  ExitToApp as ExitIcon
23
} from '@mui/icons-material';
24
import { Button, IconButton, ListItemSecondaryAction, ListItemText, Menu, MenuItem, Toolbar } from '@mui/material';
25
import { makeStyles } from 'tss-react/mui';
26

27
import moment from 'moment';
28
import Cookies from 'universal-cookie';
29

30
import enterpriseLogo from '../../../assets/img/headerlogo-enterprise.png';
31
import logo from '../../../assets/img/headerlogo.png';
32
import whiteEnterpriseLogo from '../../../assets/img/whiteheaderlogo-enterprise.png';
33
import whiteLogo from '../../../assets/img/whiteheaderlogo.png';
34
import { setFirstLoginAfterSignup, setSearchState } from '../../actions/appActions';
35
import { getAllDeviceCounts } from '../../actions/deviceActions';
36
import { initializeSelf, logoutUser, setAllTooltipsReadState, setHideAnnouncement } from '../../actions/userActions';
37
import { getToken } from '../../auth';
38
import { TIMEOUTS } from '../../constants/appConstants';
39
import { READ_STATES } from '../../constants/userConstants';
40
import { decodeSessionToken, isDarkMode } from '../../helpers';
41
import {
42
  getAcceptedDevices,
43
  getCurrentUser,
44
  getDeviceCountsByStatus,
45
  getDeviceLimit,
46
  getFeatures,
47
  getIsEnterprise,
48
  getOrganization,
49
  getTooltipsById,
50
  getUserCapabilities,
51
  getUserSettings
52
} from '../../selectors';
53
import Tracking from '../../tracking';
54
import { useDebounce } from '../../utils/debouncehook';
55
import Search from '../common/search';
56
import Announcement from './announcement';
57
import DemoNotification from './demonotification';
58
import DeploymentNotifications from './deploymentnotifications';
59
import DeviceNotifications from './devicenotifications';
60
import OfferHeader from './offerheader';
61
import TrialNotification from './trialnotification';
62

63
// Change this when a new feature/offer is introduced
64
const currentOffer = {
3✔
65
  name: 'add-ons',
66
  expires: '2021-12-30',
67
  trial: true,
68
  os: true,
69
  professional: true,
70
  enterprise: true
71
};
72

73
const cookies = new Cookies();
3✔
74

75
const useStyles = makeStyles()(theme => ({
23✔
76
  header: {
77
    minHeight: 'unset',
78
    paddingLeft: theme.spacing(4),
79
    paddingRight: theme.spacing(5),
80
    width: '100%',
81
    borderBottom: `1px solid ${theme.palette.grey[100]}`,
82
    display: 'grid'
83
  },
84
  banner: { gridTemplateRows: `1fr ${theme.mixins.toolbar.minHeight}px` },
85
  buttonColor: { color: theme.palette.grey[600] },
86
  dropDown: { height: '100%', marginLeft: theme.spacing(0.5), textTransform: 'none' },
87
  exitIcon: { color: theme.palette.grey[600], fill: theme.palette.grey[600] },
88
  demoTrialAnnouncement: {
89
    fontSize: 14,
90
    height: 'auto'
91
  },
92
  demoAnnouncementIcon: {
93
    height: 16,
94
    color: theme.palette.primary.main,
95
    '&.MuiButton-textPrimary': {
96
      color: theme.palette.primary.main,
97
      height: 'inherit'
98
    }
99
  },
100
  redAnnouncementIcon: {
101
    color: theme.palette.error.dark
102
  }
103
}));
104

105
export const Header = ({ mode }) => {
3✔
106
  const { classes } = useStyles();
428✔
107
  const [anchorEl, setAnchorEl] = useState(null);
428✔
108
  const [loggingOut, setLoggingOut] = useState(false);
428✔
109
  const [gettingUser, setGettingUser] = useState(false);
428✔
110
  const [hasOfferCookie, setHasOfferCookie] = useState(false);
428✔
111
  const sessionId = useDebounce(getToken(), TIMEOUTS.debounceDefault);
428✔
112

113
  const organization = useSelector(getOrganization);
428✔
114
  const { canManageUsers: allowUserManagement } = useSelector(getUserCapabilities);
428✔
115
  const { total: acceptedDevices = 0 } = useSelector(getAcceptedDevices);
428!
116
  const announcement = useSelector(state => state.app.hostedAnnouncement);
1,468✔
117
  const deviceLimit = useSelector(getDeviceLimit);
428✔
118
  const firstLoginAfterSignup = useSelector(state => state.app.firstLoginAfterSignup);
1,468✔
119
  const { trackingConsentGiven: hasTrackingEnabled } = useSelector(getUserSettings);
428✔
120
  const inProgress = useSelector(state => state.deployments.byStatus.inprogress.total);
1,468✔
121
  const isEnterprise = useSelector(getIsEnterprise);
428✔
122
  const { isDemoMode: demo, hasMultitenancy, isHosted } = useSelector(getFeatures);
428✔
123
  const { isSearching, searchTerm, refreshTrigger } = useSelector(state => state.app.searchState);
1,468✔
124
  const multitenancy = hasMultitenancy || isEnterprise || isHosted;
428✔
125
  const tooltips = useSelector(getTooltipsById);
428✔
126
  const { pending: pendingDevices } = useSelector(getDeviceCountsByStatus);
428✔
127
  const user = useSelector(getCurrentUser);
428✔
128
  const dispatch = useDispatch();
428✔
129
  const deviceTimer = useRef();
428✔
130
  const showHelptips = Object.values(tooltips).reduce((accu, { readState }) => accu || readState === READ_STATES.unread, false);
428!
131

132
  const updateUsername = useCallback(() => {
428✔
133
    const userId = decodeSessionToken(getToken());
3✔
134
    if (gettingUser || !userId) {
3✔
135
      return;
1✔
136
    }
137
    setGettingUser(true);
2✔
138
    // get current user
139
    return dispatch(initializeSelf()).finally(() => setGettingUser(false));
2✔
140
  }, [dispatch, gettingUser]);
141

142
  useEffect(() => {
428✔
143
    if ((!sessionId || !user?.id || !user.email.length) && !gettingUser && !loggingOut) {
12✔
144
      updateUsername();
3✔
145
      return;
3✔
146
    }
147
    Tracking.setTrackingEnabled(hasTrackingEnabled);
9✔
148
    if (hasTrackingEnabled && user.id && organization.id) {
9!
149
      Tracking.setOrganizationUser(organization, user);
×
150
      if (firstLoginAfterSignup) {
×
151
        Tracking.pageview('/signup/complete');
×
152
        dispatch(setFirstLoginAfterSignup(false));
×
153
      }
154
    }
155
  }, [sessionId, user.id, user.email, gettingUser, loggingOut, user, hasTrackingEnabled, organization, updateUsername, firstLoginAfterSignup, dispatch]);
156

157
  useEffect(() => {
428✔
158
    const showOfferCookie = cookies.get('offer') === currentOffer.name;
5✔
159
    setHasOfferCookie(showOfferCookie);
5✔
160
    clearInterval(deviceTimer.current);
5✔
161
    deviceTimer.current = setInterval(() => dispatch(getAllDeviceCounts()), TIMEOUTS.refreshDefault);
180✔
162
    return () => {
5✔
163
      clearInterval(deviceTimer.current);
5✔
164
    };
165
  }, [dispatch]);
166

167
  const onLogoutClick = () => {
428✔
168
    setGettingUser(false);
1✔
169
    setLoggingOut(true);
1✔
170
    setAnchorEl(null);
1✔
171
    dispatch(logoutUser());
1✔
172
  };
173

174
  const onSearch = useCallback((searchTerm, refreshTrigger) => dispatch(setSearchState({ refreshTrigger, searchTerm, page: 1 })), [dispatch]);
428✔
175

176
  const onToggleTooltips = () => dispatch(setAllTooltipsReadState(showHelptips ? READ_STATES.read : READ_STATES.unread));
428!
177

178
  const setHideOffer = () => {
428✔
179
    cookies.set('offer', currentOffer.name, { path: '/', maxAge: 2629746 });
×
180
    setHasOfferCookie(true);
×
181
  };
182

183
  const showOffer =
184
    isHosted && moment().isBefore(currentOffer.expires) && (organization.trial ? currentOffer.trial : currentOffer[organization.plan]) && !hasOfferCookie;
428!
185

186
  const headerLogo = isDarkMode(mode) ? (isEnterprise ? whiteEnterpriseLogo : whiteLogo) : isEnterprise ? enterpriseLogo : logo;
428!
187

188
  return (
428✔
189
    <Toolbar id="fixedHeader" className={showOffer ? `${classes.header} ${classes.banner}` : classes.header}>
428!
190
      {!!announcement && (
444✔
191
        <Announcement
192
          announcement={announcement}
193
          errorIconClassName={classes.redAnnouncementIcon}
194
          iconClassName={classes.demoAnnouncementIcon}
195
          sectionClassName={classes.demoTrialAnnouncement}
196
          onHide={() => dispatch(setHideAnnouncement(true))}
×
197
        />
198
      )}
199
      {showOffer && <OfferHeader onHide={setHideOffer} />}
428!
200
      <div className="flexbox space-between">
201
        <div className="flexbox center-aligned">
202
          <Link to="/">
203
            <img id="logo" src={headerLogo} />
204
          </Link>
205
          {demo && <DemoNotification iconClassName={classes.demoAnnouncementIcon} sectionClassName={classes.demoTrialAnnouncement} />}
428!
206
          {organization.trial && (
428!
207
            <TrialNotification
208
              expiration={organization.trial_expiration}
209
              iconClassName={classes.demoAnnouncementIcon}
210
              sectionClassName={classes.demoTrialAnnouncement}
211
            />
212
          )}
213
        </div>
214
        <Search isSearching={isSearching} searchTerm={searchTerm} onSearch={onSearch} trigger={refreshTrigger} />
215
        <div className="flexbox center-aligned">
216
          <DeviceNotifications pending={pendingDevices} total={acceptedDevices} limit={deviceLimit} />
217
          <DeploymentNotifications inprogress={inProgress} />
218
          <Button
219
            className={`header-dropdown ${classes.dropDown}`}
220
            onClick={e => setAnchorEl(e.currentTarget)}
1✔
221
            startIcon={<AccountCircleIcon className={classes.buttonColor} />}
222
            endIcon={anchorEl ? <ArrowDropUpIcon /> : <ArrowDropDownIcon />}
428✔
223
          >
224
            {user.email}
225
          </Button>
226
          <Menu
227
            anchorEl={anchorEl}
228
            onClose={() => setAnchorEl(null)}
×
229
            open={Boolean(anchorEl)}
230
            anchorOrigin={{
231
              vertical: 'center',
232
              horizontal: 'center'
233
            }}
234
            transformOrigin={{
235
              vertical: 'bottom',
236
              horizontal: 'center'
237
            }}
238
          >
239
            <MenuItem component={Link} to="/settings">
240
              Settings
241
            </MenuItem>
242
            <MenuItem component={Link} to="/settings/my-profile">
243
              My profile
244
            </MenuItem>
245
            {multitenancy && (
847✔
246
              <MenuItem component={Link} to="/settings/organization-and-billing">
247
                My organization
248
              </MenuItem>
249
            )}
250
            {allowUserManagement && (
659✔
251
              <MenuItem component={Link} to="/settings/user-management">
252
                User management
253
              </MenuItem>
254
            )}
255
            <MenuItem onClick={onToggleTooltips}>{`Mark help tips as ${showHelptips ? '' : 'un'}read`}</MenuItem>
428!
256
            <MenuItem component={Link} to="/help/get-started">
257
              Help & support
258
            </MenuItem>
259
            <MenuItem onClick={onLogoutClick}>
260
              <ListItemText primary="Log out" />
261
              <ListItemSecondaryAction>
262
                <IconButton>
263
                  <ExitIcon className={classes.exitIcon} />
264
                </IconButton>
265
              </ListItemSecondaryAction>
266
            </MenuItem>
267
          </Menu>
268
        </div>
269
      </div>
270
    </Toolbar>
271
  );
272
};
273

274
export default Header;
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