Skip to content

Commit

Permalink
refactor: fix requests after login #2473 (#953)
Browse files Browse the repository at this point in the history
  • Loading branch information
thicham43 authored and Mehdi-BOUYAHIA committed Feb 29, 2024
1 parent cb98396 commit 510ef7f
Show file tree
Hide file tree
Showing 13 changed files with 101 additions and 207 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const ProjectRow: React.FC<ProjectRowProps> = ({ project, requestsList, selected
return (
<ListItem key={request.uuid} className={classes.requestItem}>
<ListItemText onClick={() => onSelectedItem(request.uuid as string)}>
{request.shared_by?.displayed_name ? (
{request.shared_by?.display_name ? (
<Typography noWrap style={{ marginLeft: 8 }}>
{request.name} - Envoyée par : {request.shared_by.firstname}{' '}
{request.shared_by.lastname?.toUpperCase()}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
FormControlLabel
} from '@mui/material'

import { RequestType, Provider, SimpleStatus } from 'types'
import { RequestType, User, SimpleStatus } from 'types'

import { useAppSelector } from 'state'

Expand All @@ -36,15 +36,15 @@ const ModalShareRequest: React.FC<{
const selectedCurrentRequest = selectedRequestShare || requestShare
const [loading, setLoading] = useState(false)
const [currentRequest, setCurrentRequest] = useState<RequestType | null | undefined>(selectedCurrentRequest)
const [currentUserToShare, setCurrentUserToShare] = useState<Provider[] | null>(null)
const [currentUserToShare, setCurrentUserToShare] = useState<User[] | null>(null)
const [error, setError] = useState<'error_title' | 'error_user_share_list' | null>(null)
const [notifyByEmail, setNotifyByEmail] = useState(false)

const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setNotifyByEmail(event.target.checked)
}

const _onChangeValue = (key: 'name' | 'requestName' | 'usersToShare', value: string | string | Provider[]) => {
const _onChangeValue = (key: 'name' | 'requestName' | 'usersToShare', value: string | string | User[]) => {
if (value && typeof value !== 'string') {
setCurrentUserToShare(value)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import React, { useState, useEffect, Fragment, PropsWithChildren } from 'react'

import { Autocomplete, CircularProgress, Grid, TextField, Typography } from '@mui/material'

import { RequestType, Provider } from 'types'
import { RequestType, User } from 'types'

import { getProviders } from 'services/aphp/serviceProviders'
import { getUsers } from 'services/aphp/serviceUsers'

import ProvidersTable from './providersTable'
import UsersTable from './usersTable'
import { useDebounce } from 'utils/debounce'
import { Direction, Order, OrderBy } from 'types/searchCriterias'

Expand All @@ -17,61 +17,61 @@ const orderDefault: OrderBy = { orderBy: Order.LASTNAME, orderDirection: Directi

type RequestShareFormProps = {
currentRequest: RequestType | undefined
onChangeValue: (key: 'name' | 'requestName' | 'usersToShare', value: string | string | Provider[]) => void
onChangeValue: (key: 'name' | 'requestName' | 'usersToShare', value: string | string | User[]) => void
error: 'error_title' | 'error_user_share_list' | null
}

const RequestShareForm: React.FC<PropsWithChildren<RequestShareFormProps>> = (
props: PropsWithChildren<RequestShareFormProps>
) => {
const { currentRequest, onChangeValue, error, children } = props
const [providersSearchResults, setProvidersSearchResults] = useState<Provider[]>([])
const [usersSearchResults, setUsersSearchResults] = useState<User[]>([])
const [loadingOnSearch, setLoadingOnSearch] = useState(false)
const [usersToShare] = useState<Provider[]>([])
const [usersToShare] = useState<User[]>([])
const [searchInput, setSearchInput] = useState('')

const debouncedSearchTerm = useDebounce(700, searchInput)

const addProvider = (provider?: Provider | null) => {
if (!provider) return
const addUser = (user?: User | null) => {
if (!user) return

const _usersToShare = usersToShare ?? []
let alreadyExists = false

for (const user of _usersToShare) {
if (user.displayed_name === provider.displayed_name) {
for (const _user of _usersToShare) {
if (_user.display_name === user.display_name) {
alreadyExists = true
}
}

if (!alreadyExists) {
_usersToShare.push(provider)
_usersToShare.push(user)
}

onChangeValue('usersToShare', _usersToShare)
}

useEffect(() => {
const _searchProviders = async () => {
const _searchUsers = async () => {
try {
setLoadingOnSearch(true)

const providersResp = await getProviders(orderDefault, 1, debouncedSearchTerm)
const usersResp = await getUsers(orderDefault, 1, debouncedSearchTerm)

setProvidersSearchResults(providersResp.providers)
setUsersSearchResults(usersResp.users)

setLoadingOnSearch(false)
} catch (error) {
console.error('Erreur lors de la recherche des utilisateurs')
setProvidersSearchResults([])
setUsersSearchResults([])
setLoadingOnSearch(false)
}
}

if (debouncedSearchTerm && debouncedSearchTerm?.length > 0) {
_searchProviders()
_searchUsers()
} else {
setProvidersSearchResults([])
setUsersSearchResults([])
}
}, [debouncedSearchTerm])

Expand Down Expand Up @@ -105,16 +105,16 @@ const RequestShareForm: React.FC<PropsWithChildren<RequestShareFormProps>> = (
<Autocomplete
noOptionsText="Rechercher un utilisateur"
clearOnEscape
options={providersSearchResults ?? []}
options={usersSearchResults ?? []}
loading={loadingOnSearch}
onChange={(e, value) => {
addProvider(value)
addUser(value)
setSearchInput('')
}}
inputValue={searchInput}
onInputChange={() => setSearchInput('')}
getOptionLabel={(option) =>
`${option.provider_source_value} - ${option.lastname?.toLocaleUpperCase()} ${option.firstname} ${
`${option.username} - ${option.lastname?.toLocaleUpperCase()} ${option.firstname} ${
option.email ? `- ${option.email}` : ''
}` ?? ''
}
Expand All @@ -140,11 +140,7 @@ const RequestShareForm: React.FC<PropsWithChildren<RequestShareFormProps>> = (
)}
/>

<ProvidersTable
providersList={usersToShare}
onChangeUsersAssociated={onChangeValue}
usersAssociated={usersToShare}
/>
<UsersTable usersList={usersToShare} onChangeUsersAssociated={onChangeValue} usersAssociated={usersToShare} />
</div>
</Grid>
<Grid container direction="column">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,27 +17,22 @@ import { TableCellWrapper } from 'components/ui/TableCell/styles'
import DeleteIcon from '@mui/icons-material/Delete'

import useStyles from './styles'
import { Provider } from 'types'
import { User } from 'types'

type ProvidersTableProps = {
providersList: Provider[]
type UsersTableProps = {
usersList: User[]
loading?: boolean
usersAssociated?: Provider[]
usersAssociated?: User[]
onChangeUsersAssociated: (key: any, value: any) => void
}

const ProvidersTable: React.FC<ProvidersTableProps> = ({
providersList,
loading,
usersAssociated,
onChangeUsersAssociated
}) => {
const UsersTable: React.FC<UsersTableProps> = ({ usersList, loading, usersAssociated, onChangeUsersAssociated }) => {
const { classes } = useStyles()

const columns = [
{
label: 'Identifiant APH',
code: 'provider_source_value'
code: 'username'
},
{
label: 'Nom',
Expand All @@ -56,10 +51,10 @@ const ProvidersTable: React.FC<ProvidersTableProps> = ({
}
]

const deleteItem = (provider: Provider) => {
const deleteItem = (user: User) => {
const _usersAssociatedCopy = usersAssociated ?? []

const index = _usersAssociatedCopy.indexOf(provider) ?? -1
const index = _usersAssociatedCopy.indexOf(user) ?? -1
if (index > -1) {
_usersAssociatedCopy.splice(index, 1)
}
Expand Down Expand Up @@ -88,27 +83,27 @@ const ProvidersTable: React.FC<ProvidersTableProps> = ({
</div>
</TableCellWrapper>
</TableRow>
) : !providersList || providersList?.length === 0 ? (
) : !usersList || usersList?.length === 0 ? (
<TableRow>
<TableCellWrapper colSpan={7}>
<Typography className={classes.loadingSpinnerContainer}>Aucun résultat à afficher</Typography>
</TableCellWrapper>
</TableRow>
) : (
providersList.map((provider: Provider) => {
usersList.map((user: User) => {
return (
provider && (
<TableRow key={provider.provider_id} className={classes.tableBodyRows} hover>
<TableCellWrapper>{provider.provider_source_value}</TableCellWrapper>
<TableCellWrapper>{provider.lastname?.toLocaleUpperCase()}</TableCellWrapper>
<TableCellWrapper>{provider.firstname}</TableCellWrapper>
<TableCellWrapper>{provider.email ?? '-'}</TableCellWrapper>
user && (
<TableRow key={user.username} className={classes.tableBodyRows} hover>
<TableCellWrapper>{user.username}</TableCellWrapper>
<TableCellWrapper>{user.lastname?.toLocaleUpperCase()}</TableCellWrapper>
<TableCellWrapper>{user.firstname}</TableCellWrapper>
<TableCellWrapper>{user.email ?? '-'}</TableCellWrapper>
<TableCellWrapper>
<Tooltip title="Supprimer l'utilisateur" style={{ padding: '0 12px' }}>
<IconButton
onClick={(event) => {
event.stopPropagation()
deleteItem(provider)
deleteItem(user)
}}
>
<DeleteIcon />
Expand All @@ -126,4 +121,4 @@ const ProvidersTable: React.FC<ProvidersTableProps> = ({
)
}

export default ProvidersTable
export default UsersTable
2 changes: 1 addition & 1 deletion src/components/Requests/PreviewTable/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ const RequestsTable = ({ data, loading }: RequestsTableProps) => {
{data?.map((row: RequestType) => (
<TableRow className={classes.pointerHover} hover key={row.uuid}>
<TableCell onClick={() => _onClickRow(row)}>
{row.shared_by?.displayed_name ? (
{row.shared_by?.display_name ? (
<>
{row.name} - Envoyée par : {row.shared_by.firstname} {row.shared_by.lastname?.toUpperCase()}
</>
Expand Down
2 changes: 1 addition & 1 deletion src/components/Requests/ProjectsTable/RequestRow/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ const RequestRow: React.FC<RequestRowProps> = ({ row, cohortsList, selectedReque
</IconButton>
</TableCellWrapper>
<TableCellWrapper align="left" className={classes.tdName}>
{row?.shared_by?.displayed_name ? (
{row?.shared_by?.display_name ? (
<Link onClick={() => navigate(`/cohort/new/${row.uuid}`)} underline="hover" style={{ cursor: 'pointer' }}>
{`${row.name} - Envoyée par : ${row?.shared_by?.firstname} ${row?.shared_by?.lastname?.toUpperCase()}`}
</Link>
Expand Down
6 changes: 3 additions & 3 deletions src/components/Routes/AutoLogoutContainer.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,11 @@ const AutoLogoutContainer = () => {

const refreshToken = async () => {
try {
const res = await apiBackend.post(`/accounts/refresh/`)
const res = await apiBackend.post(`/auth/refresh/`, { refresh_token: localStorage.getItem(REFRESH_TOKEN) })

if (res.status === 200) {
localStorage.setItem(ACCESS_TOKEN, res.data.access)
localStorage.setItem(REFRESH_TOKEN, res.data.refresh)
localStorage.setItem(ACCESS_TOKEN, res.data.access_token)
localStorage.setItem(REFRESH_TOKEN, res.data.refresh_token)
} else {
logout()
}
Expand Down
4 changes: 2 additions & 2 deletions src/constants.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export let BOOLEANTRUE = 'true'

export const ACCESS_TOKEN = 'access'
export const REFRESH_TOKEN = 'refresh'
export const ACCESS_TOKEN = 'access_token'
export const REFRESH_TOKEN = 'refresh_token'

export const OIDC_PROVIDER_URL = import.meta.env.DEV
? import.meta.env.VITE_OIDC_PROVIDER_URL
Expand Down
63 changes: 4 additions & 59 deletions src/services/aphp/servicePractitioner.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { AxiosResponse } from 'axios'
import apiBackend from 'services/apiBackend'
import { ACCESS_TOKEN, REFRESH_TOKEN } from '../../constants'
import { REFRESH_TOKEN } from '../../constants'

export interface IServicePractitioner {
/**
Expand All @@ -25,26 +24,6 @@ export interface IServicePractitioner {
* Maintenance
*/
maintenance: () => Promise<any>

/**
* Cette fonction nous retourne les informations relative à un pratitioner
*
* Argument:
* - username: Identifiant du practitioner
*
* Retourne:
* - id: Identifiant technique du practitioner
* - userName: Identifiant AP-HP
* - displayName: Nom + prénom du practitioner
* - firstName: Prénom du practitioner
* - lastName: Nom du practitioner
*/
fetchPractitioner: (username: string) => Promise<{
id: number
displayName: string
firstName: string
lastName: string
} | null>
}

const servicePractitioner: IServicePractitioner = {
Expand All @@ -54,7 +33,7 @@ const servicePractitioner: IServicePractitioner = {
formData.append('username', username.toString())
formData.append('password', password)

return await apiBackend.post(`/accounts/login/`, formData)
return await apiBackend.post(`/auth/login/`, formData)
} catch (error) {
console.error('Error authenticating with credentials', error)
return error
Expand All @@ -63,20 +42,15 @@ const servicePractitioner: IServicePractitioner = {

authenticateWithCode: async (authCode: string) => {
try {
const response = await apiBackend.post(`/auth/oidc/login`, { auth_code: authCode })
if (response.status === 200) {
localStorage.setItem(ACCESS_TOKEN, response.data.jwt.access)
localStorage.setItem(REFRESH_TOKEN, response.data.jwt.refresh)
}
return response
return await apiBackend.post(`/auth/oidc/login`, { auth_code: authCode })
} catch (error) {
console.error('Error authenticating with an authorization code', error)
return error
}
},

logout: async () => {
await apiBackend.post(`/accounts/logout/`)
await apiBackend.post(`/auth/logout/`, { refresh_token: localStorage.getItem(REFRESH_TOKEN) })
localStorage.clear()
},

Expand All @@ -87,35 +61,6 @@ const servicePractitioner: IServicePractitioner = {
console.error("erreur lors de l'éxécution de la fonction maintenance", error)
return error
}
},

fetchPractitioner: async (username) => {
try {
const practitioner: any = await apiBackend.get<AxiosResponse>(`/users/${username}/`)

if (!practitioner || (practitioner && !practitioner.data)) {
return null
}

const id = practitioner.data.provider_id
const userName = practitioner.data.provider_username
const firstName = practitioner.data.firstname
const lastName = practitioner.data.lastname
const displayName = `${firstName} ${lastName}`
const response = practitioner

return {
id,
userName,
displayName,
firstName,
lastName,
response
}
} catch (error: any) {
console.error("Erreur lors de l'éxécution de la fonction fetchPractitioner", error)
return error
}
}
}

Expand Down
Loading

0 comments on commit 510ef7f

Please sign in to comment.