Skip to content

Commit

Permalink
feat: use mfsOrganizations instead of csv,
Browse files Browse the repository at this point in the history
remove unused npm packages
  • Loading branch information
JoeSlain committed Nov 26, 2024
1 parent cfe4125 commit 85121c0
Show file tree
Hide file tree
Showing 6 changed files with 42 additions and 63 deletions.
29 changes: 0 additions & 29 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 0 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
"event-source-polyfill": "^1.0.31",
"events": "^3.3.0",
"fuse.js": "^7.0.0",
"papaparse": "^5.4.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-intersection-observer": "^9.10.3",
Expand All @@ -39,7 +38,6 @@
"react-redux": "^9.1.2",
"react-router-dom": "^6.24.1",
"react-string-replace": "^1.1.1",
"react-to-print": "^2.15.1",
"react-tooltip": "^5.27.1",
"redux": "^5.0.1",
"upgrade": "^1.1.0",
Expand All @@ -48,7 +46,6 @@
"devDependencies": {
"@biomejs/biome": "^1.9.1",
"@types/node": "^20.14.9",
"@types/papaparse": "^5.3.14",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@types/react-modal": "^3.16.3",
Expand Down
1 change: 1 addition & 0 deletions src/api/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ export const feedbackUrl = `${apiBase}/feedback/add`
export const getSheetsUrl = `${apiBase}/get_sheets`
export const getChunksUrl = `${apiBase}/get_chunks`
export const getChunkUrl = `${apiBase}/get_chunk`
export const mfsOrganizationsUrl = `${apiBase}/organizations/mfs`
6 changes: 2 additions & 4 deletions src/api/useGetMfsOrganizations.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useQuery } from '@tanstack/react-query'
import { setHeaders } from '../utils/setData'

export function useGetOrganizations() {
return useQuery({
Expand All @@ -11,10 +12,7 @@ export function useGetOrganizations() {
const fetchOrganizations = async (): Promise<string[]> => {
const res = await fetch(`${'/organizations/mfs'}`, {
method: 'GET',

headers: {
'Content-Type': 'application/json',
},
headers: setHeaders(false),
})

if (!res.ok) {
Expand Down
53 changes: 32 additions & 21 deletions src/components/Auth/LoginFields.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { mfsOrganizationsUrl } from '@api'
import Input from '@codegouvfr/react-dsfr/Input'
import { PasswordInput } from '@codegouvfr/react-dsfr/blocks/PasswordInput'
import Fuse from 'fuse.js'
import Papa from 'papaparse'
import { useContext, useEffect, useMemo, useState } from 'react'
import { useEffect, useMemo, useState } from 'react'

export const LoginFields = ({
fields,
Expand Down Expand Up @@ -90,12 +90,10 @@ export const LoginFields = ({
</>
)
}

function MFSInput({ selectedValue, setSelectedValue, matricule, setMatricule }) {
const [searchResults, setSearchResults] = useState([])
const [data, setData] = useState([])
const [data, setData] = useState<[{ id: string; name: string }] | []>([])
const [selectedIndex, setSelectedIndex] = useState(-1)
const mfsOrganizationsUrl = '/organizations/mfs'

const handleKeyDown = (e) => {
if (['ArrowDown', 'ArrowUp'].includes(e.key)) {
Expand All @@ -106,36 +104,49 @@ function MFSInput({ selectedValue, setSelectedValue, matricule, setMatricule })
: Math.max(selectedIndex - 1, 0)
if (newIndex >= 0 && newIndex <= 4) {
setSelectedIndex(newIndex)
setSelectedValue(searchResults[newIndex]?.lib_fs || '')
setSelectedValue(searchResults[newIndex]?.nane || '')
}
} else if (e.key === 'Enter') {
e.preventDefault()
const selectedResult = searchResults[selectedIndex]
if (selectedResult) {
handleSelect(selectedResult)
} else {
// resetSelection()
}
}
}

useEffect(() => {
const fetchData = async () => {
const response = await fetch('/mfs.csv')
const reader = response.body.getReader()
const result = await reader.read()
const decoder = new TextDecoder('utf-8')
const csv = decoder.decode(result.value)
const parsedData = Papa.parse(csv, { header: true }).data
setData(parsedData)
try {
const response = await fetch(mfsOrganizationsUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
})

if (!response.ok) {
// Handle HTTP errors
const errorText = await response.text()
throw new Error(`Error ${response.status}: ${errorText}`)
}

const institutions: [{ id: string; name: string }] = await response.json()
setData(institutions)
} catch (error) {
console.error('Failed to fetch MFS organizations:', error)
// Optionally, set an error state here to display to the user
}
}

fetchData()
}, [])

console.log('data', data)
const fuse = useMemo(
() =>
new Fuse(data, {
keys: ['lib_fs'],
keys: ['name', 'id'],
includeScore: true,
threshold: 0.2,
}),
Expand All @@ -152,8 +163,8 @@ function MFSInput({ selectedValue, setSelectedValue, matricule, setMatricule })
}

const handleSelect = (item) => {
setSelectedValue(item.lib_fs)
setMatricule(item.id_fs)
setSelectedValue(item.name)
setMatricule(item.id)
setSearchResults([])
setSelectedIndex(-1)
}
Expand All @@ -178,10 +189,10 @@ function MFSInput({ selectedValue, setSelectedValue, matricule, setMatricule })
className={`fr-card cursor-pointer p-0 ${
selectedIndex === index ? 'bg-light-grey' : ''
}`}
key={item}
key={item.id} // Use a unique identifier here
onClick={() => handleSelect(item)}
>
<p className="fr-ml-3w fr-mt-1w fr-mb-1w">{item.lib_fs}</p>
<p className="fr-ml-3w fr-mt-1w fr-mb-1w">{item.name}</p>
</div>
))}
</div>
Expand Down
13 changes: 7 additions & 6 deletions src/pages/Signup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { userUrl } from '@api'
import { ButtonsGroup } from '@codegouvfr/react-dsfr/ButtonsGroup'
import { initButtonsSignup } from '@constants/connexion'
import { signupFields } from '@constants/inputFields'
import { useState } from 'react'
import { useGetOrganizations } from 'api/useGetMfsOrganizations'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import {
email,
Expand All @@ -17,7 +18,6 @@ import {
} from 'valibot'
import { LoginFields } from '../components/Auth/LoginFields'
import { ButtonInformation } from '../components/Global/ButtonInformation'
import { useGetOrganizations } from 'api/useGetMfsOrganizations'

const SignupSchemaMFS = object({
username: pipe(
Expand Down Expand Up @@ -45,8 +45,10 @@ export function Signup({ authFailed, setAuthFailed, userAuth, setUserAuth }) {
const [selectedMatricule, setSelectedMatricule] = useState('')
const [sent, setSent] = useState(false)

const { data, error } = useGetOrganizations()
if (data) console.log(data)
const { data: organizations, error } = useGetOrganizations()
useEffect(() => {
if (organizations) console.log(organizations)
}, [organizations])
const navigate = useNavigate()
const handleChange = (e) => {
e.preventDefault()
Expand All @@ -67,8 +69,7 @@ export function Signup({ authFailed, setAuthFailed, userAuth, setUserAuth }) {

const handleValidatePassword = (auth) => {
return (
userAuth.username &&
userAuth.username.length &&
userAuth.username?.length &&
userAuth.email.length &&
userAuth.email.includes('@') &&
password.length &&
Expand Down

0 comments on commit 85121c0

Please sign in to comment.