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

mendersoftware / gui / 1113439055

19 Dec 2023 09:01PM UTC coverage: 82.752% (-17.2%) from 99.964%
1113439055

Pull #4258

gitlab-ci

mender-test-bot
chore: Types update

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

4326 of 6319 branches covered (0.0%)

8348 of 10088 relevant lines covered (82.75%)

189.39 hits per line

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

83.33
/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 { TIMEOUTS } from '../../constants/appConstants';
38
import { READ_STATES } from '../../constants/userConstants';
39
import { isDarkMode } from '../../helpers';
40
import {
41
  getAcceptedDevices,
42
  getCurrentSession,
43
  getCurrentUser,
44
  getDeviceCountsByStatus,
45
  getDeviceLimit,
46
  getFeatures,
47
  getIsEnterprise,
48
  getOrganization,
49
  getShowHelptips,
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 = {
2✔
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();
2✔
74

75
const useStyles = makeStyles()(theme => ({
9✔
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 }) => {
2✔
106
  const { classes } = useStyles();
392✔
107
  const [anchorEl, setAnchorEl] = useState(null);
392✔
108
  const [gettingUser, setGettingUser] = useState(false);
392✔
109
  const [hasOfferCookie, setHasOfferCookie] = useState(false);
392✔
110

111
  const organization = useSelector(getOrganization);
392✔
112
  const { canManageUsers: allowUserManagement } = useSelector(getUserCapabilities);
392✔
113
  const { total: acceptedDevices = 0 } = useSelector(getAcceptedDevices);
392!
114
  const announcement = useSelector(state => state.app.hostedAnnouncement);
1,359✔
115
  const deviceLimit = useSelector(getDeviceLimit);
392✔
116
  const firstLoginAfterSignup = useSelector(state => state.app.firstLoginAfterSignup);
1,359✔
117
  const { trackingConsentGiven: hasTrackingEnabled } = useSelector(getUserSettings);
392✔
118
  const inProgress = useSelector(state => state.deployments.byStatus.inprogress.total);
1,359✔
119
  const isEnterprise = useSelector(getIsEnterprise);
392✔
120
  const { isDemoMode: demo, hasMultitenancy, isHosted } = useSelector(getFeatures);
392✔
121
  const { isSearching, searchTerm, refreshTrigger } = useSelector(state => state.app.searchState);
1,359✔
122
  const multitenancy = hasMultitenancy || isEnterprise || isHosted;
392✔
123
  const { pending: pendingDevices } = useSelector(getDeviceCountsByStatus);
392✔
124
  const userSettingInitialized = useSelector(state => state.users.settingsInitialized);
1,359✔
125
  const user = useSelector(getCurrentUser);
392✔
126
  const { token } = useSelector(getCurrentSession);
392✔
127
  const userId = useDebounce(user.id, TIMEOUTS.debounceDefault);
392✔
128

129
  const dispatch = useDispatch();
392✔
130
  const deviceTimer = useRef();
392✔
131
  const showHelptips = useSelector(getShowHelptips);
392✔
132

133
  useEffect(() => {
392✔
134
    if ((!userId || !user.email?.length || !userSettingInitialized) && !gettingUser && token) {
8!
135
      setGettingUser(true);
×
136
      dispatch(initializeSelf());
×
137
      return;
×
138
    }
139
    Tracking.setTrackingEnabled(hasTrackingEnabled);
8✔
140
    if (hasTrackingEnabled && user.id && organization.id) {
8!
141
      Tracking.setOrganizationUser(organization, user);
×
142
      if (firstLoginAfterSignup) {
×
143
        Tracking.pageview('/signup/complete');
×
144
        dispatch(setFirstLoginAfterSignup(false));
×
145
      }
146
    }
147
  }, [dispatch, firstLoginAfterSignup, gettingUser, hasTrackingEnabled, organization, token, user, user.email, userId, userSettingInitialized]);
148

149
  useEffect(() => {
392✔
150
    const showOfferCookie = cookies.get('offer') === currentOffer.name;
7✔
151
    setHasOfferCookie(showOfferCookie);
7✔
152
    clearInterval(deviceTimer.current);
7✔
153
    deviceTimer.current = setInterval(() => dispatch(getAllDeviceCounts()), TIMEOUTS.refreshDefault);
186✔
154
    return () => {
7✔
155
      clearInterval(deviceTimer.current);
7✔
156
    };
157
  }, [dispatch]);
158

159
  const onLogoutClick = () => {
392✔
160
    setAnchorEl(null);
4✔
161
    dispatch(logoutUser()).then(() => window.location.replace('/ui/'));
4✔
162
  };
163

164
  const onSearch = useCallback((searchTerm, refreshTrigger) => dispatch(setSearchState({ refreshTrigger, searchTerm, page: 1 })), [dispatch]);
392✔
165

166
  const onToggleTooltips = () => dispatch(setAllTooltipsReadState(showHelptips ? READ_STATES.read : READ_STATES.unread));
392!
167

168
  const setHideOffer = () => {
392✔
169
    cookies.set('offer', currentOffer.name, { path: '/', maxAge: 2629746 });
×
170
    setHasOfferCookie(true);
×
171
  };
172

173
  const handleClose = () => setAnchorEl(null);
392✔
174

175
  const showOffer =
176
    isHosted && moment().isBefore(currentOffer.expires) && (organization.trial ? currentOffer.trial : currentOffer[organization.plan]) && !hasOfferCookie;
392!
177

178
  const headerLogo = isDarkMode(mode) ? (isEnterprise ? whiteEnterpriseLogo : whiteLogo) : isEnterprise ? enterpriseLogo : logo;
392!
179

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

266
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