Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Teammedlemmer #67

Merged
merged 17 commits into from
Feb 27, 2024
21 changes: 7 additions & 14 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import ViteExpress from 'vite-express'
import { createLightship } from 'lightship'
import cache from 'memory-cache'
import express from 'express'
import jwt from 'jsonwebtoken'
import jwksClient from 'jwks-rsa'
import { getReasonPhrase } from 'http-status-codes'
import dotenv from 'dotenv'

// TODO: Do a massive cleanup. There are much of the code that can be re-written for reuseability, and some functions
// may not even be required anymore after dapla-team-api-redux changes.

if (!process.env.VITE_JWKS_URI) {
dotenv.config({ path: './.env.local' })
}
Expand Down Expand Up @@ -141,22 +143,13 @@ app.get('/api/userProfile/:principalName', tokenVerificationMiddleware, async (r
const userManagerUrl = `${DAPLA_TEAM_API_URL}/users/${principalName}/manager`
const userPhotoUrl = `${DAPLA_TEAM_API_URL}/users/${principalName}/photo`

const cacheKey = `userProfile-${principalName}`
const cachedUserProfile = cache.get(cacheKey)
if (cachedUserProfile) {
return res.json(cachedUserProfile)
}

const [userProfile, userManager, userPhoto] = await Promise.all([
fetchAPIData(token, userProfileUrl, 'Failed to fetch userProfile'),
fetchAPIData(token, userManagerUrl, 'Failed to fetch user manager').catch(() => managerFallback()),
fetchPhoto(token, userPhotoUrl, 'Failed to fetch user photo'),
])

const data = { ...userProfile, manager: { ...userManager }, photo: userPhoto }
cache.put(cacheKey, data, 3600000)

return res.json(data)
return res.json({ ...userProfile, manager: { ...userManager }, photo: userPhoto })
} catch (error) {
next(error)
}
Expand Down Expand Up @@ -254,7 +247,7 @@ app.get('/api/teamDetail/:teamUniformName', tokenVerificationMiddleware, async (

const [teamInfo, teamUsers] = await Promise.all([
fetchAPIData(token, teamInfoUrl, 'Failed to fetch team info').then(async (teamInfo) => {
const manager = await fetchTeamManager(token, teamInfo)
const manager = await fetchTeamManager(token, teamInfo.uniform_name)
return { ...teamInfo, manager }
}),
fetchAPIData(token, teamUsersUrl, 'Failed to fetch team users').then(async (teamUsers) => {
Expand All @@ -270,8 +263,8 @@ app.get('/api/teamDetail/:teamUniformName', tokenVerificationMiddleware, async (
}
})

async function fetchTeamManager(token, teamInfo) {
const teamManagerUrl = `${DAPLA_TEAM_API_URL}/groups/${teamInfo.uniform_name}-managers/users`
async function fetchTeamManager(token, teamUniformName) {
const teamManagerUrl = `${DAPLA_TEAM_API_URL}/groups/${teamUniformName}-managers/users`
return await fetchAPIData(token, teamManagerUrl, 'Failed to fetch team manager')
.then((teamManager) => {
return teamManager.count > 0 ? teamManager._embedded.users[0] : managerFallback()
Expand Down
3 changes: 2 additions & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import Login from './pages/Login/Login'
import TeamOverview from './pages/TeamOverview/TeamOverview'
import UserProfile from './pages/UserProfile/UserProfile'
import TeamDetail from './pages/TeamDetail/TeamDetail'
import TeamMembers from './pages/TeamMembers/TeamMembers'

import { Routes, Route } from 'react-router-dom'

Expand All @@ -17,7 +18,7 @@ export default function App() {
example: <ProtectedRoute roles={['managers', 'data-admins']} />
*/}
<Route path='/' element={<TeamOverview />} />
<Route path='/teammedlemmer' element={<h1>Teammedlemmer</h1>} />
<Route path='/teammedlemmer' element={<TeamMembers />} />
<Route path='/teammedlemmer/:principalName' element={<UserProfile />} />
<Route path='/:teamId' element={<TeamDetail />} />
<Route path='*' element={<NotFound />} />
Expand Down
153 changes: 153 additions & 0 deletions src/pages/TeamMembers/TeamMembers.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import pageLayoutStyles from '../../components/PageLayout/pagelayout.module.scss'

import { useCallback, useEffect, useState } from 'react'
import { Dialog, Title, Text, Link, Tabs, Divider } from '@statisticsnorway/ssb-component-library'

import { TabProps } from '../../@types/pageTypes'
import PageLayout from '../../components/PageLayout/PageLayout'
import Table, { TableData } from '../../components/Table/Table'
import PageSkeleton from '../../components/PageSkeleton/PageSkeleton'

import { fetchAllTeamMembersData, TeamMembersData, User } from '../../services/teamMembers'
import { formatDisplayName } from '../../utils/utils'
import { ApiError } from '../../utils/services'

export default function TeamMembers() {
const accessToken = localStorage.getItem('access_token') || ''
const jwt = JSON.parse(atob(accessToken.split('.')[1]))

const defaultActiveTab = {
title: 'Mine teammedlemmer',
path: 'myUsers',
}

const [activeTab, setActiveTab] = useState<TabProps | string>(defaultActiveTab)
const [teamMembersData, setTeamMembersData] = useState<TeamMembersData>()
const [teamMembersTableData, setTeamMembersTableData] = useState<TableData['data']>()
const [teamMembersTableTitle, setTeamMembersTableTitle] = useState<string>(defaultActiveTab.title)
const [error, setError] = useState<ApiError | undefined>()
const [loading, setLoading] = useState<boolean>(true)

const prepUserData = useCallback(
(response: TeamMembersData): TableData['data'] => {
const teamMember = (activeTab as TabProps)?.path ?? activeTab

return response[teamMember].users.map((teamMember) => ({
id: teamMember.principal_name,
navn: renderUserNameColumn(teamMember),
team: teamMember.teams.length,
data_admin_roller: teamMember.groups.filter((group) => group.uniform_name.endsWith('data-admins')).length,
seksjon: teamMember.section_name,
seksjonsleder: formatDisplayName(
teamMember.section_manager && teamMember.section_manager.length > 0
? teamMember.section_manager[0].display_name
: 'Seksjonsleder ikke funnet'
),
}))
},
[activeTab]
)

useEffect(() => {
if (!jwt) return
fetchAllTeamMembersData(jwt.email)
.then((response) => {
setTeamMembersData(response as TeamMembersData)
setTeamMembersTableData(prepUserData(response as TeamMembersData))
})
.finally(() => setLoading(false))
.catch((error) => {
setError(error as ApiError)
})
}, [prepUserData, jwt])

useEffect(() => {
if (teamMembersData) {
setTeamMembersTableData(prepUserData(teamMembersData))
}
}, [teamMembersData, prepUserData])

const handleTabClick = (tab: string) => {
setActiveTab(tab)
if (tab === 'myUsers') {
setTeamMembersTableTitle('Mine teammedlemmer')
} else {
setTeamMembersTableTitle('Alle teammedlemmer')
}
}

function renderUserNameColumn(user: User) {
return (
<>
<span>
<Link href={`/teammedlemmer/${user.principal_name}`}>
<b>{user.display_name}</b>
</Link>
</span>
{user.section_name && <Text>{user.section_name}</Text>}
</>
)
}

function renderErrorAlert() {
return (
<Dialog type='warning' title='Could not fetch users'>
{`${error?.code} - ${error?.message}`}
</Dialog>
)
}

function renderContent() {
if (error) return renderErrorAlert()
if (loading) return <PageSkeleton />

if (teamMembersTableData) {
const teamMembersTableHeaderColumns = [
{
id: 'navn',
label: 'Navn',
},
{
id: 'team',
label: 'Team',
},
{
id: 'data_admin_roller',
label: 'Data-admin-roller',
},
{
id: 'seksjonsleder',
label: 'Seksjonsleder',
},
]

return (
<>
<Tabs
onClick={handleTabClick}
activeOnInit={defaultActiveTab.path}
items={[
{ title: `Mine teammedlemmer (${teamMembersData?.myUsers.users.length ?? 0})`, path: 'myUsers' },
{ title: `Alle teammedlemmer (${teamMembersData?.allUsers.users.length ?? 0})`, path: 'allUsers' },
]}
/>
<Divider dark />
{/* TODO: Remove Title */}
<Title size={2} className={pageLayoutStyles.tableTitle}>
{teamMembersTableTitle}
</Title>
{teamMembersTableData.length > 0 ? (
//TODO: <Table title={teamMembersTableTitle} columns={teamMembersTableHeaderColumns} data={teamMembersTableData as TableData['data']} />
<Table columns={teamMembersTableHeaderColumns} data={teamMembersTableData as TableData['data']} />
) : (
<Dialog type='warning' title='No team members found'>
You are not a manager in any dapla-team
</Dialog>
)}
</>
)
}
}

return <PageLayout title={'Teammedlemmer'} content={renderContent()} />
}
1 change: 1 addition & 0 deletions src/pages/TeamMembers/teamMembers.module.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@use '@statisticsnorway/ssb-component-library/src/style/variables' as variables;
Loading