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

mendersoftware / gui / 1308594387

28 May 2024 12:32PM UTC coverage: 83.391% (-16.6%) from 99.964%
1308594387

Pull #4424

gitlab-ci

mzedel
feat: restructured account menu & added option to switch tenant in supporting setups

Ticket: MEN-6906
Changelog: Title
Signed-off-by: Manuel Zedel <manuel.zedel@northern.tech>
Pull Request #4424: MEN-6906 - tenant switching - wip

4466 of 6371 branches covered (70.1%)

27 of 31 new or added lines in 3 files covered. (87.1%)

1670 existing lines in 164 files now uncovered.

8480 of 10169 relevant lines covered (83.39%)

140.77 hits per line

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

86.3
/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 { AccountCircle as AccountCircleIcon, ExitToApp as ExitIcon, ExpandMore } from '@mui/icons-material';
19
import {
20
  Accordion,
21
  AccordionDetails,
22
  AccordionSummary,
23
  Button,
24
  Divider,
25
  IconButton,
26
  ListItemSecondaryAction,
27
  ListItemText,
28
  Menu,
29
  MenuItem,
30
  Toolbar,
31
  Typography,
32
  avatarClasses
33
} from '@mui/material';
34
import { makeStyles } from 'tss-react/mui';
35

36
import moment from 'moment';
37
import Cookies from 'universal-cookie';
38

39
import enterpriseLogo from '../../../assets/img/headerlogo-enterprise.png';
40
import logo from '../../../assets/img/headerlogo.png';
41
import whiteEnterpriseLogo from '../../../assets/img/whiteheaderlogo-enterprise.png';
42
import whiteLogo from '../../../assets/img/whiteheaderlogo.png';
43
import { setFirstLoginAfterSignup, setSearchState } from '../../actions/appActions';
44
import { getAllDeviceCounts } from '../../actions/deviceActions';
45
import { initializeSelf, logoutUser, setAllTooltipsReadState, setHideAnnouncement, switchUserOrganization } from '../../actions/userActions';
46
import { TIMEOUTS } from '../../constants/appConstants';
47
import { READ_STATES } from '../../constants/userConstants';
48
import { isDarkMode, toggle } from '../../helpers';
49
import {
50
  getAcceptedDevices,
51
  getCurrentSession,
52
  getCurrentUser,
53
  getDeviceCountsByStatus,
54
  getDeviceLimit,
55
  getFeatures,
56
  getIsEnterprise,
57
  getOrganization,
58
  getShowHelptips,
59
  getUserSettings
60
} from '../../selectors';
61
import Tracking from '../../tracking';
62
import { useDebounce } from '../../utils/debouncehook';
63
import Search from '../common/search';
64
import Announcement from './announcement';
65
import DemoNotification from './demonotification';
66
import DeploymentNotifications from './deploymentnotifications';
67
import DeviceNotifications from './devicenotifications';
68
import OfferHeader from './offerheader';
69
import TrialNotification from './trialnotification';
70

71
// Change this when a new feature/offer is introduced
72
const currentOffer = {
2✔
73
  name: 'add-ons',
74
  expires: '2021-12-30',
75
  trial: true,
76
  os: true,
77
  professional: true,
78
  enterprise: true
79
};
80

81
const cookies = new Cookies();
2✔
82

83
const useStyles = makeStyles()(theme => ({
24✔
84
  header: {
85
    minHeight: 'unset',
86
    paddingLeft: theme.spacing(4),
87
    paddingRight: theme.spacing(5),
88
    width: '100%',
89
    borderBottom: `1px solid ${theme.palette.grey[100]}`,
90
    display: 'grid'
91
  },
92
  banner: { gridTemplateRows: `1fr ${theme.mixins.toolbar.minHeight}px` },
93
  buttonColor: { color: theme.palette.grey[600] },
94
  dropDown: {
95
    height: '100%',
96
    textTransform: 'none',
97
    alignSelf: 'center',
98
    [`&.${avatarClasses.root}`]: {
99
      margin: 15,
100
      padding: 0
101
    }
102
  },
103
  exitIcon: { color: theme.palette.grey[600], fill: theme.palette.grey[600] },
104
  demoTrialAnnouncement: {
105
    fontSize: 14,
106
    height: 'auto'
107
  },
108
  demoAnnouncementIcon: {
109
    height: 16,
110
    color: theme.palette.primary.main,
111
    '&.MuiButton-textPrimary': {
112
      color: theme.palette.primary.main,
113
      height: 'inherit'
114
    }
115
  },
116
  redAnnouncementIcon: {
117
    color: theme.palette.error.dark
118
  }
119
}));
120

121
const AccountMenu = () => {
2✔
122
  const [anchorEl, setAnchorEl] = useState(null);
21✔
123
  const [tenantSwitcherShowing, setTenantSwitcherShowing] = useState(false);
21✔
124
  const showHelptips = useSelector(getShowHelptips);
21✔
125
  const {
126
    email,
127
    tenant_ids = [
21✔
128
      { id: '1239081239182309', name: 'foo' },
129
      { id: '1239081239182309123', name: 'bar' }
130
    ]
131
  } = useSelector(getCurrentUser);
21✔
132
  const { name } = useSelector(getOrganization);
21✔
133
  const isEnterprise = useSelector(getIsEnterprise);
21✔
134
  const { hasMultitenancy, isHosted } = useSelector(getFeatures);
21✔
135
  const multitenancy = hasMultitenancy || isEnterprise || isHosted;
21✔
136
  const dispatch = useDispatch();
21✔
137

138
  const { classes } = useStyles();
21✔
139

140
  const handleClose = () => {
21✔
NEW
141
    setAnchorEl(null);
×
NEW
142
    setTenantSwitcherShowing(false);
×
143
  };
144

145
  const handleSwitchTenant = id => dispatch(switchUserOrganization(id));
21✔
146

147
  const onLogoutClick = () => {
21✔
148
    setAnchorEl(null);
1✔
149
    dispatch(logoutUser()).then(() => window.location.replace('/ui/'));
1✔
150
  };
151

152
  const onToggleTooltips = () => dispatch(setAllTooltipsReadState(showHelptips ? READ_STATES.read : READ_STATES.unread));
21!
153

154
  return (
21✔
155
    <>
156
      <Button className={classes.dropDown} onClick={e => setAnchorEl(e.currentTarget)} startIcon={<AccountCircleIcon className={classes.buttonColor} />}>
1✔
157
        {email}
158
      </Button>
159
      <Menu
160
        anchorEl={anchorEl}
161
        onClose={handleClose}
162
        open={Boolean(anchorEl)}
163
        anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
164
        transformOrigin={{ horizontal: 'right', vertical: 'top' }}
165
      >
166
        <MenuItem component={Link} to="/settings/my-profile" onClick={handleClose}>
167
          My profile
168
        </MenuItem>
169
        <Divider />
170
        {!!(multitenancy && name) && (
62✔
171
          <MenuItem component={Link} dense to="/settings/organization-and-billing" onClick={handleClose}>
172
            <div>
173
              <Typography variant="caption" className="muted">
174
                My organization
175
              </Typography>
176
              <Typography variant="subtitle2">{name}</Typography>
177
            </div>
178
          </MenuItem>
179
        )}
180
        {tenant_ids.length > 1 && (
42✔
181
          <div>
182
            <Divider style={{ marginBottom: 0 }} />
NEW
183
            <Accordion square expanded={tenantSwitcherShowing} onChange={() => setTenantSwitcherShowing(toggle)}>
×
184
              <AccordionSummary expandIcon={<ExpandMore />}>Switch organization</AccordionSummary>
185
              <AccordionDetails>
186
                {tenant_ids.map(({ id, name }) => (
187
                  <MenuItem key={id} onClick={() => handleSwitchTenant(id)}>
42✔
188
                    {name}
189
                  </MenuItem>
190
                ))}
191
              </AccordionDetails>
192
            </Accordion>
193
          </div>
194
        )}
195
        <Divider />
196
        <MenuItem component={Link} to="/settings/global-settings" onClick={handleClose}>
197
          Settings
198
        </MenuItem>
199
        <MenuItem onClick={onToggleTooltips}>{`Mark help tips as ${showHelptips ? '' : 'un'}read`}</MenuItem>
21!
200
        <MenuItem component={Link} to="/help/get-started" onClick={handleClose}>
201
          Help & support
202
        </MenuItem>
203
        <MenuItem onClick={onLogoutClick}>
204
          <ListItemText primary="Log out" />
205
          <ListItemSecondaryAction>
206
            <IconButton>
207
              <ExitIcon className={classes.exitIcon} />
208
            </IconButton>
209
          </ListItemSecondaryAction>
210
        </MenuItem>
211
      </Menu>
212
    </>
213
  );
214
};
215

216
export const Header = ({ mode }) => {
2✔
217
  const { classes } = useStyles();
25✔
218
  const [gettingUser, setGettingUser] = useState(false);
25✔
219
  const [hasOfferCookie, setHasOfferCookie] = useState(false);
25✔
220

221
  const organization = useSelector(getOrganization);
25✔
222
  const { total: acceptedDevices = 0 } = useSelector(getAcceptedDevices);
25!
223
  const announcement = useSelector(state => state.app.hostedAnnouncement);
1,598✔
224
  const deviceLimit = useSelector(getDeviceLimit);
25✔
225
  const firstLoginAfterSignup = useSelector(state => state.app.firstLoginAfterSignup);
1,598✔
226
  const { trackingConsentGiven: hasTrackingEnabled } = useSelector(getUserSettings);
25✔
227
  const inProgress = useSelector(state => state.deployments.byStatus.inprogress.total);
1,598✔
228
  const isEnterprise = useSelector(getIsEnterprise);
25✔
229
  const { isDemoMode: demo, isHosted } = useSelector(getFeatures);
25✔
230
  const { isSearching, searchTerm, refreshTrigger } = useSelector(state => state.app.searchState);
1,598✔
231
  const { pending: pendingDevices } = useSelector(getDeviceCountsByStatus);
25✔
232
  const userSettingInitialized = useSelector(state => state.users.settingsInitialized);
1,598✔
233
  const user = useSelector(getCurrentUser);
25✔
234
  const { token } = useSelector(getCurrentSession);
25✔
235
  const userId = useDebounce(user.id, TIMEOUTS.debounceDefault);
25✔
236

237
  const dispatch = useDispatch();
25✔
238
  const deviceTimer = useRef();
25✔
239

240
  useEffect(() => {
25✔
241
    if ((!userId || !user.email?.length || !userSettingInitialized) && !gettingUser && token) {
10✔
242
      setGettingUser(true);
1✔
243
      dispatch(initializeSelf());
1✔
244
      return;
1✔
245
    }
246
    Tracking.setTrackingEnabled(hasTrackingEnabled);
9✔
247
    if (hasTrackingEnabled && user.id && organization.id) {
9!
UNCOV
248
      Tracking.setOrganizationUser(organization, user);
×
UNCOV
249
      if (firstLoginAfterSignup) {
×
UNCOV
250
        Tracking.pageview('/signup/complete');
×
UNCOV
251
        dispatch(setFirstLoginAfterSignup(false));
×
252
      }
253
    }
254
  }, [dispatch, firstLoginAfterSignup, gettingUser, hasTrackingEnabled, organization, token, user, user.email, userId, userSettingInitialized]);
255

256
  useEffect(() => {
25✔
257
    const showOfferCookie = cookies.get('offer') === currentOffer.name;
6✔
258
    setHasOfferCookie(showOfferCookie);
6✔
259
    clearInterval(deviceTimer.current);
6✔
260
    deviceTimer.current = setInterval(() => dispatch(getAllDeviceCounts()), TIMEOUTS.refreshDefault);
276✔
261
    return () => {
6✔
262
      clearInterval(deviceTimer.current);
6✔
263
    };
264
  }, [dispatch]);
265

266
  const onSearch = useCallback((searchTerm, refreshTrigger) => dispatch(setSearchState({ refreshTrigger, searchTerm, page: 1 })), [dispatch]);
25✔
267

268
  const setHideOffer = () => {
25✔
UNCOV
269
    cookies.set('offer', currentOffer.name, { path: '/', maxAge: 2629746 });
×
UNCOV
270
    setHasOfferCookie(true);
×
271
  };
272

273
  const showOffer =
274
    isHosted && moment().isBefore(currentOffer.expires) && (organization.trial ? currentOffer.trial : currentOffer[organization.plan]) && !hasOfferCookie;
25!
275

276
  const headerLogo = isDarkMode(mode) ? (isEnterprise ? whiteEnterpriseLogo : whiteLogo) : isEnterprise ? enterpriseLogo : logo;
25!
277

278
  return (
25✔
279
    <Toolbar id="fixedHeader" className={showOffer ? `${classes.header} ${classes.banner}` : classes.header}>
25!
280
      {!!announcement && (
31✔
281
        <Announcement
282
          announcement={announcement}
283
          errorIconClassName={classes.redAnnouncementIcon}
284
          iconClassName={classes.demoAnnouncementIcon}
285
          sectionClassName={classes.demoTrialAnnouncement}
UNCOV
286
          onHide={() => dispatch(setHideAnnouncement(true))}
×
287
        />
288
      )}
289
      {showOffer && <OfferHeader onHide={setHideOffer} />}
25!
290
      <div className="flexbox space-between">
291
        <div className="flexbox center-aligned">
292
          <Link to="/">
293
            <img id="logo" src={headerLogo} />
294
          </Link>
295
          {demo && <DemoNotification iconClassName={classes.demoAnnouncementIcon} sectionClassName={classes.demoTrialAnnouncement} />}
25!
296
          {organization.trial && (
25!
297
            <TrialNotification
298
              expiration={organization.trial_expiration}
299
              iconClassName={classes.demoAnnouncementIcon}
300
              sectionClassName={classes.demoTrialAnnouncement}
301
            />
302
          )}
303
        </div>
304
        <Search isSearching={isSearching} searchTerm={searchTerm} onSearch={onSearch} trigger={refreshTrigger} />
305
        <div className="flexbox center-aligned">
306
          <DeviceNotifications pending={pendingDevices} total={acceptedDevices} limit={deviceLimit} />
307
          <DeploymentNotifications inprogress={inProgress} />
308
          <AccountMenu />
309
        </div>
310
      </div>
311
    </Toolbar>
312
  );
313
};
314

315
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