diff --git a/.eslintrc b/.eslintrc index 1d64dea9b..a599696fb 100644 --- a/.eslintrc +++ b/.eslintrc @@ -24,6 +24,7 @@ ], "react/no-unknown-property": 0, "react/prop-types": 0, + // TODO set this rule to 2 and fix all the errors "@typescript-eslint/no-explicit-any": 0, "@typescript-eslint/camelcase": 0, "@typescript-eslint/explicit-function-return-type": 0, diff --git a/src/components/CreationCohort/ControlPanel/ControlPanel.tsx b/src/components/CreationCohort/ControlPanel/ControlPanel.tsx index 3e3e841a6..5d1b81a34 100644 --- a/src/components/CreationCohort/ControlPanel/ControlPanel.tsx +++ b/src/components/CreationCohort/ControlPanel/ControlPanel.tsx @@ -34,7 +34,7 @@ import { } from 'state/cohortCreation' import { MeState } from 'state/me' -import { RequestType } from 'types' +import { CohortCreationCounterType, RequestType, SimpleStatus } from 'types' import useStyle from './styles' @@ -50,11 +50,11 @@ const ControlPanel: React.FC<{ const classes = useStyle() const dispatch = useAppDispatch() const [openModal, onSetOpenModal] = useState<'executeCohortConfirmation' | null>(null) - const [oldCount, setOldCount] = useState(null) + const [oldCount, setOldCount] = useState(null) const [openShareRequestModal, setOpenShareRequestModal] = useState(false) - const [shareSuccessOrFailMessage, setShareSuccessOrFailMessage] = useState<'success' | 'error' | null>(null) + const [shareSuccessOrFailMessage, setShareSuccessOrFailMessage] = useState(null) const wrapperSetShareSuccessOrFailMessage = useCallback( - (val: any) => { + (val: SimpleStatus) => { setShareSuccessOrFailMessage(val) }, [setShareSuccessOrFailMessage] @@ -94,7 +94,7 @@ const ControlPanel: React.FC<{ selectedPopulation === null ? null : selectedPopulation - .map((population: any) => population && population.access) + .map((population) => population && population.access) .filter((elem) => elem && elem === 'Pseudonymisé').length > 0 const checkIfLogicalOperatorIsEmpty = () => { @@ -258,18 +258,18 @@ const ControlPanel: React.FC<{ {includePatient !== undefined && includePatient !== null ? displayDigit(includePatient) : '-'} - {oldCount !== null - ? (includePatient ?? 0) - oldCount?.includePatient > 0 - ? ` (+${(includePatient ?? 0) - oldCount?.includePatient})` - : ` (${(includePatient ?? 0) - oldCount?.includePatient})` + {oldCount !== null && !!oldCount.includePatient + ? (includePatient ?? 0) - oldCount.includePatient > 0 + ? ` (+${(includePatient ?? 0) - oldCount.includePatient})` + : ` (${(includePatient ?? 0) - oldCount.includePatient})` : ''} - {oldCount !== null && ( + {oldCount !== null && !!oldCount.includePatient && ( 0 - ? ` (+${(includePatient ?? 0) - oldCount?.includePatient})` - : ` (${(includePatient ?? 0) - oldCount?.includePatient})` + (includePatient ?? 0) - oldCount.includePatient > 0 + ? ` (+${(includePatient ?? 0) - oldCount.includePatient})` + : ` (${(includePatient ?? 0) - oldCount.includePatient})` } est la différence de patient entre le ${lastUpdatedOldCount?.format( 'DD/MM/YYYY' )} et la date du jour.`} diff --git a/src/components/CreationCohort/DiagramView/components/CriteriaCard/components/CriteriaCardContent/CriteriaCardContent.tsx b/src/components/CreationCohort/DiagramView/components/CriteriaCard/components/CriteriaCardContent/CriteriaCardContent.tsx index 907bc41ff..56a2d93d9 100644 --- a/src/components/CreationCohort/DiagramView/components/CriteriaCard/components/CriteriaCardContent/CriteriaCardContent.tsx +++ b/src/components/CreationCohort/DiagramView/components/CriteriaCard/components/CriteriaCardContent/CriteriaCardContent.tsx @@ -15,6 +15,7 @@ import { DocType, SearchByTypes, SelectedCriteriaType } from 'types' import docTypes from 'assets/docTypes.json' import useStyles from './styles' +import { ReactJSXElement } from '@emotion/react/types/jsx-namespace' type CriteriaCardContentProps = { currentCriteria: SelectedCriteriaType @@ -23,7 +24,7 @@ type CriteriaCardContentProps = { const CriteriaCardContent: React.FC = ({ currentCriteria }) => { const _displayCardContent = (_currentCriteria: SelectedCriteriaType) => { if (!_currentCriteria) return [] - let content: any[] = [] + let content: Array = [] const reducer = (accumulator: any, currentValue: any) => accumulator ? `${accumulator} - ${currentValue}` : currentValue ? currentValue : accumulator @@ -42,7 +43,7 @@ const CriteriaCardContent: React.FC = ({ currentCriter ) let _data: any = null - const _searchDataFromCriteria = (_criteria: any[], type: string) => { + const _searchDataFromCriteria = (_criteria: CriteriaItemType[], type: string) => { for (const _criterion of _criteria) { if (_criterion.id === 'Medication' && ('MedicationRequest' === type || 'MedicationAdministration' === type)) { _data = _criterion.data diff --git a/src/components/CreationCohort/DiagramView/components/LogicalOperator/LogicalOperator.tsx b/src/components/CreationCohort/DiagramView/components/LogicalOperator/LogicalOperator.tsx index 8b14871d3..4fe4e14f5 100644 --- a/src/components/CreationCohort/DiagramView/components/LogicalOperator/LogicalOperator.tsx +++ b/src/components/CreationCohort/DiagramView/components/LogicalOperator/LogicalOperator.tsx @@ -53,7 +53,7 @@ const OperatorItem: React.FC = ({ const displayingItem = criteriaGroup.filter((_criteriaGroup: CriteriaGroupType) => _criteriaGroup.id === itemId) - let timeout: any = null + let timeout: NodeJS.Timeout | null = null const [isExpanded, onExpand] = useState(false) diff --git a/src/components/CreationCohort/DiagramView/components/LogicalOperator/components/LogicalOperatorItem/LogicalOperatorItem.tsx b/src/components/CreationCohort/DiagramView/components/LogicalOperator/components/LogicalOperatorItem/LogicalOperatorItem.tsx index bc723695e..849bae200 100644 --- a/src/components/CreationCohort/DiagramView/components/LogicalOperator/components/LogicalOperatorItem/LogicalOperatorItem.tsx +++ b/src/components/CreationCohort/DiagramView/components/LogicalOperator/components/LogicalOperatorItem/LogicalOperatorItem.tsx @@ -35,7 +35,7 @@ const LogicalOperatorItem: React.FC = ({ itemId }) => const classes = useStyles() const dispatch = useAppDispatch() - let timeout: any = null + let timeout: NodeJS.Timeout | null = null const isMainOperator = itemId === 0 diff --git a/src/components/CreationCohort/DiagramView/components/PopulationCard/PopulationCard.tsx b/src/components/CreationCohort/DiagramView/components/PopulationCard/PopulationCard.tsx index efacad83c..a6a2809e7 100644 --- a/src/components/CreationCohort/DiagramView/components/PopulationCard/PopulationCard.tsx +++ b/src/components/CreationCohort/DiagramView/components/PopulationCard/PopulationCard.tsx @@ -51,6 +51,7 @@ const PopulationCard: React.FC = () => { if (_selectedPopulations === null) return _selectedPopulations = filterScopeTree(_selectedPopulations) + if (_selectedPopulations === null) return _selectedPopulations = _selectedPopulations.map((_selectedPopulation: ScopeTreeRow) => ({ ..._selectedPopulation, subItems: [] @@ -118,8 +119,8 @@ const PopulationCard: React.FC = () => { {isExtended ? ( <> {selectedPopulation && - selectedPopulation.map((pop: any, index: number) => ( - + selectedPopulation.map((pop, index: number) => ( + ))} { {selectedPopulation && selectedPopulation .slice(0, 4) - .map((pop: any, index: number) => + .map((pop, index: number) => pop ? ( ) : ( diff --git a/src/components/CreationCohort/DiagramView/components/TemporalConstraintCard/components/EventSequenceTable/EventSequenceTable.tsx b/src/components/CreationCohort/DiagramView/components/TemporalConstraintCard/components/EventSequenceTable/EventSequenceTable.tsx index 72a769227..8a4be2626 100644 --- a/src/components/CreationCohort/DiagramView/components/TemporalConstraintCard/components/EventSequenceTable/EventSequenceTable.tsx +++ b/src/components/CreationCohort/DiagramView/components/TemporalConstraintCard/components/EventSequenceTable/EventSequenceTable.tsx @@ -47,10 +47,10 @@ const columns = [ } ] -const EventSequenceTable: React.FC<{ temporalConstraints: TemporalConstraintsType[]; onChangeConstraints: any }> = ({ - temporalConstraints, - onChangeConstraints -}) => { +const EventSequenceTable: React.FC<{ + temporalConstraints: TemporalConstraintsType[] + onChangeConstraints: (c: TemporalConstraintsType[]) => void +}> = ({ temporalConstraints, onChangeConstraints }) => { const { selectedCriteria } = useAppSelector((state) => state.cohortCreation.request) const classes = useStyles() @@ -60,12 +60,12 @@ const EventSequenceTable: React.FC<{ temporalConstraints: TemporalConstraintsTyp onChangeConstraints(remainingConstraints) } - const findCriteriaTitle = (id: any) => { + const findCriteriaTitle = (id: number | 'All') => { const criteria = selectedCriteria.find((criteria) => criteria.id === id) return criteria?.title } - const durationMeasurementInFrench = (key: any) => { + const durationMeasurementInFrench = (key: string) => { let keyInFrench if (key === 'days') { keyInFrench = 'jour(s)' @@ -81,9 +81,9 @@ const EventSequenceTable: React.FC<{ temporalConstraints: TemporalConstraintsTyp return keyInFrench } - const storeNonZeroMinDuration = (temporalConstraint: any) => { + const storeNonZeroMinDuration = (temporalConstraint: TemporalConstraintsType) => { const minDuration = temporalConstraint.timeRelationMinDuration - let nonZeroMinDuration: any = {} + let nonZeroMinDuration: { keys?: string; values?: number } = {} if (temporalConstraint.constraintType === 'directChronologicalOrdering' && minDuration) { for (const [key, value] of Object.entries(minDuration)) { @@ -100,9 +100,9 @@ const EventSequenceTable: React.FC<{ temporalConstraints: TemporalConstraintsTyp return nonZeroMinDuration } - const storeNonZeroMaxDuration = (temporalConstraint: any) => { + const storeNonZeroMaxDuration = (temporalConstraint: TemporalConstraintsType) => { const maxDuration = temporalConstraint.timeRelationMaxDuration - let nonZeroMaxDuration: any = {} + let nonZeroMaxDuration: { keys?: string; values?: number } = {} if (temporalConstraint.constraintType === 'directChronologicalOrdering' && maxDuration) { for (const [key, value] of Object.entries(maxDuration)) { diff --git a/src/components/CreationCohort/DiagramView/components/TemporalConstraintCard/components/TemporalConstraintConfig/TemporalConstraintConfig.tsx b/src/components/CreationCohort/DiagramView/components/TemporalConstraintCard/components/TemporalConstraintConfig/TemporalConstraintConfig.tsx index 16a5b448f..0df550076 100644 --- a/src/components/CreationCohort/DiagramView/components/TemporalConstraintCard/components/TemporalConstraintConfig/TemporalConstraintConfig.tsx +++ b/src/components/CreationCohort/DiagramView/components/TemporalConstraintCard/components/TemporalConstraintConfig/TemporalConstraintConfig.tsx @@ -12,6 +12,7 @@ import { InputLabel, MenuItem, Select, + SelectChangeEvent, Typography } from '@mui/material' @@ -41,7 +42,7 @@ const timeMeasurements = [ const TemporalConstraintConfig: React.FC<{ newConstraintsList: TemporalConstraintsType[] - onChangeNewConstraintsList: any + onChangeNewConstraintsList: (c: TemporalConstraintsType[]) => void }> = ({ newConstraintsList, onChangeNewConstraintsList }) => { const classes = useStyles() @@ -92,13 +93,13 @@ const TemporalConstraintConfig: React.FC<{ const selectableCriteria1 = getSelectableCriteria(secondCriteriaValue) const selectableCriteria2 = getSelectableCriteria(firstCriteriaValue) - const onChangeMinTimeMeasurement = (event: React.ChangeEvent<{ value: any }>) => { - setMinTimeMeasurement(event.target.value as string) + const onChangeMinTimeMeasurement = (event: SelectChangeEvent) => { + setMinTimeMeasurement(event.target.value) setMinTime(1) } - const onChangeMaxTimeMeasurement = (event: React.ChangeEvent<{ value: any }>) => { - setMaxTimeMeasurement(event.target.value as string) + const onChangeMaxTimeMeasurement = (event: SelectChangeEvent) => { + setMaxTimeMeasurement(event.target.value) setMaxTime(1) } @@ -239,7 +240,7 @@ const TemporalConstraintConfig: React.FC<{ diff --git a/src/components/CreationCohort/DiagramView/components/TemporalConstraintCard/components/TemporalConstraintModal/TemporalConstraintModal.tsx b/src/components/CreationCohort/DiagramView/components/TemporalConstraintCard/components/TemporalConstraintModal/TemporalConstraintModal.tsx index 5ee902ff1..0f430867c 100644 --- a/src/components/CreationCohort/DiagramView/components/TemporalConstraintCard/components/TemporalConstraintModal/TemporalConstraintModal.tsx +++ b/src/components/CreationCohort/DiagramView/components/TemporalConstraintCard/components/TemporalConstraintModal/TemporalConstraintModal.tsx @@ -68,7 +68,7 @@ const TemporalConstraint: React.FC<{ onChangeValue(e.target.value)} + onChange={(e) => onChangeValue(e.target.value as unknown as TemporalConstraintsType['constraintType'])} style={{ margin: '1em', justifyContent: 'space-around' }} > } label="Aucune contrainte sur les séjours" /> diff --git a/src/components/CreationCohort/Modals/ModalCohortTitle/ModalCohortTitle.tsx b/src/components/CreationCohort/Modals/ModalCohortTitle/ModalCohortTitle.tsx index 75f43624b..24f9bd063 100644 --- a/src/components/CreationCohort/Modals/ModalCohortTitle/ModalCohortTitle.tsx +++ b/src/components/CreationCohort/Modals/ModalCohortTitle/ModalCohortTitle.tsx @@ -56,7 +56,7 @@ const ModalCohortTitle: React.FC<{ onChangeTitle(e.target.value)} + onChange={(e) => onChangeTitle(e.target.value)} autoFocus id="title" margin="normal" @@ -77,7 +77,7 @@ const ModalCohortTitle: React.FC<{ onChangeDescription(e.target.value)} + onChange={(e) => onChangeDescription(e.target.value)} id="description" margin="normal" fullWidth diff --git a/src/components/CreationCohort/Modals/ModalCreateNewRequest/components/RequestForm.tsx b/src/components/CreationCohort/Modals/ModalCreateNewRequest/components/RequestForm.tsx index 3bba44252..155f53f03 100644 --- a/src/components/CreationCohort/Modals/ModalCreateNewRequest/components/RequestForm.tsx +++ b/src/components/CreationCohort/Modals/ModalCreateNewRequest/components/RequestForm.tsx @@ -38,7 +38,7 @@ const RequestForm: React.FC = ({ onChangeValue('name', e.target.value)} + onChange={(e) => onChangeValue('name', e.target.value)} autoFocus id="title" margin="normal" @@ -76,7 +76,7 @@ const RequestForm: React.FC = ({ onChangeProjectName(e.target.value)} + onChange={(e) => onChangeProjectName(e.target.value)} id="project_name" margin="normal" fullWidth @@ -90,7 +90,7 @@ const RequestForm: React.FC = ({ onChangeValue('description', e.target.value)} + onChange={(e) => onChangeValue('description', e.target.value)} id="description" margin="normal" fullWidth diff --git a/src/components/DataTable/DataTable.tsx b/src/components/DataTable/DataTable.tsx index 059b2631e..0485b6b8a 100644 --- a/src/components/DataTable/DataTable.tsx +++ b/src/components/DataTable/DataTable.tsx @@ -42,7 +42,7 @@ const DataTable: React.FC = ({ }) => { const classes = useStyles() - const createSortHandler = (property: any) => () => { + const createSortHandler = (property: string) => () => { if (setOrder) { const isAsc: boolean = order?.orderBy === property && order?.orderDirection === 'asc' const _orderDirection = isAsc ? 'desc' : 'asc' @@ -72,7 +72,7 @@ const DataTable: React.FC = ({ {column.label} @@ -91,7 +91,7 @@ const DataTable: React.FC = ({ className={classes.multiple} active={order?.orderBy === subColumn.code} direction={order?.orderBy === subColumn.code ? order?.orderDirection : 'asc'} - onClick={createSortHandler(subColumn.code)} + onClick={createSortHandler(subColumn.code || '')} > {subColumn.label} diff --git a/src/components/DataTable/DataTableMedication.tsx b/src/components/DataTable/DataTableMedication.tsx index 436c4a906..2e225b734 100644 --- a/src/components/DataTable/DataTableMedication.tsx +++ b/src/components/DataTable/DataTableMedication.tsx @@ -122,7 +122,7 @@ const DataTableMedicationLine: React.FC<{ const prescriptionType = medication.resourceType === 'MedicationRequest' && - (medication.extension?.find((extension: any) => extension.url === 'type') || {}).valueString + (medication.extension?.find((extension) => extension.url === 'type') || {}).valueString const administrationRoute = medication.resourceType === 'MedicationRequest' ? medication.dosageInstruction?.[0]?.route?.text diff --git a/src/components/DataTable/DataTableObservation.tsx b/src/components/DataTable/DataTableObservation.tsx index 2bd3ba3c8..5d629d967 100644 --- a/src/components/DataTable/DataTableObservation.tsx +++ b/src/components/DataTable/DataTableObservation.tsx @@ -80,9 +80,9 @@ const DataTableObservationLine: React.FC<{ const nda = observation.NDA const date = observation.effectiveDateTime - const libelleANABIO = observation.code?.coding?.find((code: any) => code.id === 'CODE ANABIO')?.display - const codeLOINC = observation.code?.coding?.find((code: any) => code.id === 'CODE LOINC')?.code - const libelleLOINC = observation.code?.coding?.find((code: any) => code.id === 'CODE LOINC')?.display + const libelleANABIO = observation.code?.coding?.find((code) => code.id === 'CODE ANABIO')?.display + const codeLOINC = observation.code?.coding?.find((code) => code.id === 'CODE LOINC')?.code + const libelleLOINC = observation.code?.coding?.find((code) => code.id === 'CODE LOINC')?.display const result = observation.valueQuantity ? observation.valueQuantity.code ? observation.valueQuantity.code diff --git a/src/components/ErrorView/styles.ts b/src/components/ErrorView/styles.ts index 3a4ee1677..99c9d47fe 100644 --- a/src/components/ErrorView/styles.ts +++ b/src/components/ErrorView/styles.ts @@ -1,7 +1,8 @@ +import { Theme } from '@mui/material' import { makeStyles } from '@mui/styles' import { smallDrawerWidth, largeDrawerWidth } from 'components/Routes/LeftSideBar/LeftSideBar' -export default makeStyles((theme: any) => ({ +export default makeStyles((theme: Theme) => ({ appBar: { height: '100vh', marginLeft: smallDrawerWidth, diff --git a/src/components/MasterChips/MasterChips.tsx b/src/components/MasterChips/MasterChips.tsx index 393076161..90bb11faf 100644 --- a/src/components/MasterChips/MasterChips.tsx +++ b/src/components/MasterChips/MasterChips.tsx @@ -8,7 +8,7 @@ import useStyles from './styles' export type MasterChipsProps = { chips: { label: string - onDelete?: (id?: any) => void + onDelete?: () => void }[] } const MasterChips: React.FC = ({ chips }) => { diff --git a/src/components/MyProjects/Modals/ModalShareRequest/ModalShareRequest.tsx b/src/components/MyProjects/Modals/ModalShareRequest/ModalShareRequest.tsx index 85639738e..f3cc37fbd 100644 --- a/src/components/MyProjects/Modals/ModalShareRequest/ModalShareRequest.tsx +++ b/src/components/MyProjects/Modals/ModalShareRequest/ModalShareRequest.tsx @@ -3,7 +3,7 @@ import { useNavigate } from 'react-router-dom' import { Dialog, DialogTitle, DialogContent, DialogActions, Button, Grid, CircularProgress } from '@mui/material' -import { RequestType, Provider } from 'types' +import { RequestType, Provider, SimpleStatus } from 'types' import { useAppSelector } from 'state' import { RequestState } from 'state/request' @@ -17,8 +17,8 @@ const ERROR_USER_SHARE_LIST = 'error_user_share_list' const ModalShareRequest: React.FC<{ requestShare?: RequestType | null - shareSuccessOrFailMessage?: 'success' | 'error' | null - parentStateSetter: (val: any) => void + shareSuccessOrFailMessage?: SimpleStatus + parentStateSetter: (val: SimpleStatus) => void onClose: () => void }> = ({ requestShare, onClose, parentStateSetter }) => { const { requestState } = useAppSelector<{ requestState: RequestState }>((state) => ({ requestState: state.request })) @@ -31,7 +31,7 @@ const ModalShareRequest: React.FC<{ const [currentRequest, setCurrentRequest] = useState(selectedCurrentRequest) const [currentUserToShare, setCurrentUserToShare] = useState(null) const [error, setError] = useState<'error_title' | 'error_user_share_list' | null>(null) - const [shareMessage, setShareMessage] = useState<'success' | 'error' | null>(null) + const [shareMessage, setShareMessage] = useState(null) useEffect(() => { parentStateSetter(shareMessage) diff --git a/src/components/Patient/PatientHeader/PatientHeader.tsx b/src/components/Patient/PatientHeader/PatientHeader.tsx index cfd6a1e0e..320da585b 100644 --- a/src/components/Patient/PatientHeader/PatientHeader.tsx +++ b/src/components/Patient/PatientHeader/PatientHeader.tsx @@ -29,7 +29,7 @@ const PatientHeader: React.FC = ({ const ipp = deidentifiedBoolean ? `IPP chiffré: ${patient.id ?? '-'}` : `IPP: ${ - patient.identifier?.find((item: any) => item.type?.coding?.[0].code === 'IPP')?.value ?? + patient.identifier?.find((item) => item.type?.coding?.[0].code === 'IPP')?.value ?? patient.identifier?.[0].value }` diff --git a/src/components/Patient/PatientHeader/PatientTitle/PatientTitle.tsx b/src/components/Patient/PatientHeader/PatientTitle/PatientTitle.tsx index 860ee1171..e387e5ae7 100644 --- a/src/components/Patient/PatientHeader/PatientTitle/PatientTitle.tsx +++ b/src/components/Patient/PatientHeader/PatientTitle/PatientTitle.tsx @@ -32,7 +32,7 @@ const PatientTitle: React.FC = ({ firstName, lastName }) => { const goBacktoCohort = () => { const path = cohort.cohort && Array.isArray(cohort.cohort) && cohort.cohort.length > 0 - ? `/perimeters/patients?${cohort.cohort.map((e: any) => e.id).join()}` + ? `/perimeters/patients?${cohort.cohort.map((e) => e.id).join()}` : !Array.isArray(cohort.cohort) && cohort.cohort?.id ? `/cohort/${cohort.cohort?.id}/patients` : groupId diff --git a/src/components/SavedResearch/ResearchTable/RequestsTable.tsx b/src/components/SavedResearch/ResearchTable/RequestsTable.tsx index 493656902..8b1b30f9d 100644 --- a/src/components/SavedResearch/ResearchTable/RequestsTable.tsx +++ b/src/components/SavedResearch/ResearchTable/RequestsTable.tsx @@ -45,7 +45,7 @@ import { import { MeState } from 'state/me' -import { RequestType } from 'types' +import { RequestType, SimpleStatus } from 'types' import useStyles from './styles' @@ -86,9 +86,9 @@ const RequestsTable: React.FC = ({ const [dialogOpen, setOpenDialog] = useState(false) const [selectedRequest, setSelectedRequest] = useState() const [anchorEl, setAnchorEl] = React.useState(null) - const [shareSuccessOrFailMessage, setShareSuccessOrFailMessage] = useState<'success' | 'error' | null>(null) + const [shareSuccessOrFailMessage, setShareSuccessOrFailMessage] = useState(null) const wrapperSetShareSuccessOrFailMessage = useCallback( - (val: any) => { + (val: SimpleStatus) => { setShareSuccessOrFailMessage(val) }, [setShareSuccessOrFailMessage] diff --git a/src/components/TopBar/TopBar.tsx b/src/components/TopBar/TopBar.tsx index c065150af..b4e85c412 100644 --- a/src/components/TopBar/TopBar.tsx +++ b/src/components/TopBar/TopBar.tsx @@ -70,9 +70,9 @@ const TopBar: React.FC = ({ context, patientsNb, access, afterEdit const [isExtended, onExtend] = useState(false) const [openModal, setOpenModal] = useState<'' | 'edit' | 'export' | 'delete'>('') const [patientsNumber, setPatientsNumber] = useState(patientsNb ?? 0) - const [anchorEl, setAnchorEl] = useState(null) + const [anchorEl, setAnchorEl] = useState(null) - const handleClick = (event: any) => { + const handleClick = (event: React.MouseEvent) => { setAnchorEl(event.currentTarget) } @@ -84,8 +84,9 @@ const TopBar: React.FC = ({ context, patientsNb, access, afterEdit React.useEffect(() => { const _fetchPatientNumber = async () => { const _patientNumber = await services.patients.fetchPatientsCount() - - setPatientsNumber(_patientNumber) + if (_patientNumber !== null) { + setPatientsNumber(_patientNumber) + } } if (dashboard.totalPatients === undefined) { @@ -140,7 +141,7 @@ const TopBar: React.FC = ({ context, patientsNb, access, afterEdit description: '', perimeters: dashboard.cohort && Array.isArray(dashboard.cohort) - ? dashboard.cohort.map((p: any) => (p.name ? p.name.replace('Patients passés par: ', '') : '-')) + ? dashboard.cohort.map((p) => (p.name ? p.name.replace('Patients passés par: ', '') : '-')) : [], icon: , showActionButton: false @@ -212,7 +213,7 @@ const TopBar: React.FC = ({ context, patientsNb, access, afterEdit {isExtended ? ( <> {cohort.perimeters && - cohort.perimeters.map((perimeter: any) => ( + cohort.perimeters.map((perimeter) => ( diff --git a/src/components/Welcome/PatientsCard/PatientsCard.jsx b/src/components/Welcome/PatientsCard/PatientsCard.jsx index 48ea1614c..5d543c8ac 100644 --- a/src/components/Welcome/PatientsCard/PatientsCard.jsx +++ b/src/components/Welcome/PatientsCard/PatientsCard.jsx @@ -24,7 +24,9 @@ const PatientSearchCard = () => { setLoading(true) const patientNumber = await services.patients.fetchPatientsCount() - setPatientNb(patientNumber) + if (patientNumber !== null) { + setPatientNb(patientNumber) + } setLoading(false) } diff --git a/src/services/aphp/callApi.ts b/src/services/aphp/callApi.ts index f02ba06e4..8f98d3273 100644 --- a/src/services/aphp/callApi.ts +++ b/src/services/aphp/callApi.ts @@ -19,10 +19,14 @@ import { Group, MedicationAdministration, MedicationRequest, + OperationOutcome, + Parameters, + ParametersParameter, Patient, Procedure } from 'fhir/r4' import { Observation } from 'fhir/r4' +import { getApiResponseResources, getApiResponseResourcesOrThrow } from 'utils/apiHelpers' const reducer = (accumulator: any, currentValue: any) => accumulator ? `${accumulator},${currentValue}` : currentValue ? currentValue : accumulator @@ -43,7 +47,8 @@ type fetchGroupProps = { 'managing-entity'?: string[] // ID List of organization _elements?: ('name' | 'managingEntity')[] } -export const fetchGroup = async (args: fetchGroupProps) => { +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export const fetchGroup = async (args: fetchGroupProps): Promise, any>> => { const { _id, provider } = args let { _list, _elements } = args let managingEntity = args['managing-entity'] @@ -308,12 +313,17 @@ export const fetchComposition = async (args: fetchCompositionProps) => { return response } -export const fetchCheckDocumentSearchInput = async (searchInput: string, signal?: AbortSignal) => { - const checkDocumentSearchInput = await apiFhir.get( +export const fetchCheckDocumentSearchInput = async ( + searchInput: string, + signal?: AbortSignal +): Promise => { + const checkDocumentSearchInput = await apiFhir.get( `/Composition/$text?_text=${encodeURIComponent(searchInput)}`, { signal: signal } ) - return checkDocumentSearchInput.data.parameter ?? null + return checkDocumentSearchInput.data.resourceType === 'OperationOutcome' + ? undefined + : (checkDocumentSearchInput.data as Parameters).parameter } export const fetchCompositionContent = async (compositionId: string) => { diff --git a/src/services/aphp/cohortCreation/fetchMedication.ts b/src/services/aphp/cohortCreation/fetchMedication.ts index b82caee55..200ce4f68 100644 --- a/src/services/aphp/cohortCreation/fetchMedication.ts +++ b/src/services/aphp/cohortCreation/fetchMedication.ts @@ -9,6 +9,8 @@ import { codeSort } from 'utils/alphabeticalSort' import { capitalizeFirstLetter } from 'utils/capitalize' import apiFhir from '../../apiFhir' import { getApiResponseResources } from 'utils/apiHelpers' +import { FHIR_API_Response } from 'types' +import { ValueSet, ValueSetComposeIncludeConcept } from 'fhir/r4' export const fetchAtcData = async (searchValue?: string, noStar?: boolean) => { noStar = noStar === undefined ? true : noStar @@ -29,15 +31,15 @@ export const fetchAtcData = async (searchValue?: string, noStar?: boolean) => { ? `&_text=${encodeURIComponent(searchValue.trim().replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'))}*` //eslint-disable-line : '' - const res = await apiFhir.get(`/ValueSet?url=${MEDICATION_ATC}${_searchValue}&size=${VALUE_SET_SIZE ?? 9999}`) + const res = await apiFhir.get>( + `/ValueSet?url=${MEDICATION_ATC}${_searchValue}&size=${VALUE_SET_SIZE ?? 9999}` + ) - const data = - res && res.data && res.data.entry && res.data.entry[0] && res.data.resourceType === 'Bundle' - ? res.data.entry[0].resource?.compose?.include[0].concept - : [] + const resources = getApiResponseResources(res) + const data = resources?.length ? resources[0].compose?.include[0].concept || [] : [] return data && data.length > 0 - ? data.sort(codeSort).map((_data: { code: string; display: string }) => ({ + ? data.sort(codeSort).map((_data: ValueSetComposeIncludeConcept) => ({ id: _data.code, label: `${_data.code} - ${capitalizeFirstLetter(_data.display)}`, subItems: [{ id: 'loading', label: 'loading', subItems: [] }] @@ -47,18 +49,16 @@ export const fetchAtcData = async (searchValue?: string, noStar?: boolean) => { export const fetchAtcHierarchy = async (atcParent: string) => { if (!atcParent) { - const res = await apiFhir.get(`/ValueSet?url=${MEDICATION_ATC}`) + const res = await apiFhir.get>(`/ValueSet?url=${MEDICATION_ATC}`) - let atcList = - res && res.data && res.data.entry && res.data.entry[0] && res.data.resourceType === 'Bundle' - ? res.data.entry[0].resource?.compose?.include[0].concept - : [] + const resources = getApiResponseResources(res) + const atcList = resources?.length ? resources[0].compose?.include[0].concept || [] : [] - atcList = + const atcDataList = atcList && atcList.length > 0 ? atcList .sort(codeSort) - .map((atcData: any) => ({ + .map((atcData: ValueSetComposeIncludeConcept) => ({ id: atcData.code, label: `${atcData.code} - ${atcData.display}`, subItems: [{ id: 'loading', label: 'loading', subItems: [] }] @@ -68,7 +68,7 @@ export const fetchAtcHierarchy = async (atcParent: string) => { .filter((atcData: any) => atcData.label.search(new RegExp(/^[X-Y] - /, 'gi')) !== 0) : [] - return [{ id: '*', label: 'Toute la hiérarchie Médicament', subItems: [...atcList] }] + return [{ id: '*', label: 'Toute la hiérarchie Médicament', subItems: [...atcDataList] }] } else { const json = { resourceType: 'ValueSet', diff --git a/src/services/aphp/serviceCohorts.ts b/src/services/aphp/serviceCohorts.ts index 2ff7e872e..04f55f962 100644 --- a/src/services/aphp/serviceCohorts.ts +++ b/src/services/aphp/serviceCohorts.ts @@ -11,7 +11,8 @@ import { GenderRepartitionType, searchInputError, errorDetails, - PatientGenderKind + PatientGenderKind, + GroupRights } from 'types' import { getGenderRepartitionMapAphp, @@ -19,7 +20,7 @@ import { getAgeRepartitionMapAphp, getVisitRepartitionMapAphp } from 'utils/graphUtils' -import { getApiResponseResources } from 'utils/apiHelpers' +import { getApiResponseResources, getApiResponseResourcesOrThrow } from 'utils/apiHelpers' import { fetchGroup, @@ -34,7 +35,17 @@ import { import { ODD_EXPORT } from '../../constants' import apiBackend from '../apiBackend' -import { DocumentReference, Identifier, Patient } from 'fhir/r4' +import { + BundleEntry, + DocumentReference, + Encounter, + Extension, + Group, + GroupMember, + Identifier, + ParametersParameter, + Patient +} from 'fhir/r4' export interface IServiceCohorts { /** @@ -279,7 +290,8 @@ const servicesCohorts: IServiceCohorts = { const visitTypeRepartitionData = encountersResp.data.resourceType === 'Bundle' ? getEncounterRepartitionMapAphp( - encountersResp.data.meta?.extension?.find((facet: any) => facet.url === 'facet-class-simple')?.extension + encountersResp.data.meta?.extension?.find((facet: Extension) => facet.url === 'facet-class-simple') + ?.extension ) : undefined @@ -367,14 +379,14 @@ const servicesCohorts: IServiceCohorts = { const agePyramidData = patientsResp.data.resourceType === 'Bundle' ? getAgeRepartitionMapAphp( - patientsResp.data.meta?.extension?.find((facet: any) => facet.url === 'facet-age-month')?.extension + patientsResp.data.meta?.extension?.find((facet: Extension) => facet.url === 'facet-age-month')?.extension ) : undefined const genderRepartitionMap = patientsResp.data.resourceType === 'Bundle' ? getGenderRepartitionMapAphp( - patientsResp.data.meta?.extension?.find((facet: any) => facet.url === 'facet-deceased')?.extension + patientsResp.data.meta?.extension?.find((facet: Extension) => facet.url === 'facet-deceased')?.extension ) : undefined @@ -496,33 +508,44 @@ const servicesCohorts: IServiceCohorts = { const checkDocumentSearchInput = await fetchCheckDocumentSearchInput(searchInput, signal) if (checkDocumentSearchInput) { - const errors = checkDocumentSearchInput.find((parameter: any) => parameter.name === 'WARNING')?.part ?? [] + const errors = checkDocumentSearchInput.find((parameter) => parameter.name === 'WARNING')?.part ?? [] const parsedErrors: errorDetails[] = [] - errors.forEach((error: any) => { - const splitError = error.valueString.split(';') - - const errorPositions = splitError.find((errorPart: any) => errorPart.includes('Positions')) - - const cleanedErrorPositions = errorPositions - ? errorPositions.replaceAll(' ', '').replace('Positions:', '').split('char:').slice(1) - : [] - - const errorSolution = splitError.find((errorPart: any) => errorPart.includes('Solution')) - const cleanedErrorSolution = errorSolution ? errorSolution.replace(' Solution: ', '') : '' + errors.forEach((error: ParametersParameter) => { + try { + if (error.valueString) { + const splitError = error.valueString.split(';') + + const errorPositions = splitError.find((errorPart) => errorPart.includes('Positions')) + + const cleanedErrorPositions = errorPositions + ? errorPositions + .replaceAll(' ', '') + .replace('Positions:', '') + .split('char:') + .slice(1) + .map((el) => parseInt(el)) + : [] + + const errorSolution = splitError.find((errorPart) => errorPart.includes('Solution')) + const cleanedErrorSolution = errorSolution ? errorSolution.replace(' Solution: ', '') : '' + + const errorObject = { + errorName: error.name, + errorPositions: cleanedErrorPositions, + errorSolution: cleanedErrorSolution + } - const errorObject = { - errorName: error.name, - errorPositions: cleanedErrorPositions, - errorSolution: cleanedErrorSolution + parsedErrors.push(errorObject) + } + } catch (e) { + console.log('failed to parse int', e) } - - parsedErrors.push(errorObject) }) return { - isError: checkDocumentSearchInput.find((parameter: any) => parameter.name === 'VALIDÉ') ? false : true, + isError: checkDocumentSearchInput.find((parameter) => parameter.name === 'VALIDÉ') ? false : true, errorsDetails: parsedErrors } } else { @@ -559,39 +582,22 @@ const servicesCohorts: IServiceCohorts = { }) .filter((id) => id !== '') - const cohortsResponse: any = await new Promise((resolve) => { - resolve(fetchGroup({ _id: ids })) - }) - .then((values) => { - return values - }) - .catch((error) => { - return { error: true, ...error } - }) - let caresiteIds = '' - let organizationLinkList: any[] = [] + const cohortLinkList: Group[] = getApiResponseResourcesOrThrow(await fetchGroup({ _id: ids })) - const cohortLinkList = cohortsResponse?.data?.entry?.[0]?.resource - ? cohortsResponse.data.entry.map((cohortsResponse: any) => cohortsResponse.resource) - : [] + let caresiteIds = '' + let organizationLinkList: Group[] = [] // On cherche la liste des Organisations présente dans l'objet `member` - caresiteIds = - cohortLinkList?.length > 0 - ? cohortLinkList - .map((cohortLinkItem: any) => - cohortLinkItem?.member?.length > 0 - ? cohortLinkItem.member.map((member: any) => - member.entity.display?.search('Organization/') !== -1 - ? member.entity.display?.replace('Organization/', '') - : '' - ) - : '' - ) - .flat() - .filter((item: any, index: number, array: any[]) => item && array.indexOf(item) === index) - .join(',') - : '' + caresiteIds = cohortLinkList + .flatMap((cohortLinkItem) => + cohortLinkItem.member?.map((member) => + member.entity.display?.search('Organization/') !== -1 + ? member.entity.display?.replace('Organization/', '') + : '' + ) + ) + .filter((el) => !!el) + .join(',') if (caresiteIds) { // Si une liste d'Organisation est présente dans l'objet `member` @@ -599,9 +605,9 @@ const servicesCohorts: IServiceCohorts = { organizationLinkList = cohortLinkList?.length > 0 ? cohortLinkList - .map((cohortLinkItem: any) => { + .map((cohortLinkItem: Group) => { const members = cohortLinkItem?.member ?? [] - let organizationLinks: any[] = [] + let organizationLinks: Group[] = [] for (let index = 0; index < members.length; index += 2) { const group = members[index] || null @@ -609,8 +615,11 @@ const servicesCohorts: IServiceCohorts = { organizationLinks = [ ...organizationLinks, { - id: group.entity.display.replace('Group/', ''), - managingEntity: organization.entity + id: group?.entity?.display?.replace('Group/', ''), + managingEntity: organization.entity, + resourceType: 'Group', + type: 'person', + actual: true } ] } @@ -618,81 +627,58 @@ const servicesCohorts: IServiceCohorts = { return organizationLinks }) .flat() - .filter((item: any, index: number, array: any[]) => item && array.indexOf(item) === index) + .filter((el) => !!el) : [] } else { // Sinon // On cherche les Group ID - const parentGroupsId = - cohortLinkList?.length > 0 - ? cohortLinkList - .map((cohortLinkItem: any) => - cohortLinkItem?.member?.length > 0 - ? cohortLinkItem.member.map((member: any) => - member.entity.display?.search('Group/') !== -1 - ? member.entity.display?.replace('Group/', '') - : '' - ) - : '' - ) - .flat() - .filter((item: any, index: number, array: any[]) => item && array.indexOf(item) === index) - : [] + const parentGroupsId: string[] = cohortLinkList + .flatMap((cohortLinkItem) => + cohortLinkItem.member?.map((member) => + member.entity.display?.search('Group/') !== -1 ? member.entity.display?.replace('Group/', '') : '' + ) + ) + .filter((el): el is string => !!el) // Pour récupérer les informations du périmètre de la cohorte - const parentGroupsResponse = await Promise.all( - parentGroupsId.map((parentGroupId: string) => - new Promise((resolve) => { - resolve(fetchGroup({ _id: parentGroupId })) - }) - .then((values) => { - return values - }) - .catch((error) => { - return { error: true, ...error } - }) - ) - ) + organizationLinkList = ( + await Promise.all(parentGroupsId.map((parentGroupId: string) => fetchGroup({ _id: parentGroupId }))) + ).flatMap((res) => getApiResponseResourcesOrThrow(res)) // Et faire le lien avec les organisations, donc ... // On crée un dictionnaire pour faire le lien entre les Groups et les Organisations (Dictionnaire 2) - organizationLinkList = parentGroupsResponse - .filter((parentGroupResponse: any) => parentGroupResponse.error !== true) - .map( - (parentGroupResponse: any) => - parentGroupResponse?.data?.resourceType === 'Bundle' && parentGroupResponse?.data?.entry?.[0]?.resource - ) if (!organizationLinkList || organizationLinkList?.length === 0) return cohorts // On crée une liste des Organisations liées au périmètre (caresiteIds = string) caresiteIds = organizationLinkList - .map((currentParentItem: any) => currentParentItem?.managingEntity?.display?.replace('Organization/', '')) - .filter((item: any, index: number, array: any[]) => item && array.indexOf(item) === index) + .map((currentParentItem: Group) => currentParentItem?.managingEntity?.display?.replace('Organization/', '')) + .filter((el) => !!el) .join(',') } // On appelle le back-end pour avoir la liste des droits const rightsResponse = await apiBackend.get(`accesses/accesses/my-rights/?care-site-ids=${caresiteIds}`) - const rightsData: any = rightsResponse.data ?? [] + const rightsData: GroupRights[] = rightsResponse.data ?? [] return cohorts.map((cohort) => { - const cohortLinkItem = cohortLinkList.find((cohortLink: any) => cohortLink?.id === cohort.fhir_group_id) + const cohortLinkItem = cohortLinkList.find((cohortLink: Group) => cohortLink?.id === cohort.fhir_group_id) const organizationLinkItems = !cohortLinkItem ? undefined - : organizationLinkList.filter((organizationLink: any) => - cohortLinkItem?.member?.length > 0 + : organizationLinkList.filter((organizationLink: Group) => + (cohortLinkItem?.member?.length || 0) > 0 ? cohortLinkItem.member?.find( - (member: any) => member.entity.display?.replace('Group/', '') === organizationLink.id + (member: GroupMember) => member.entity.display?.replace('Group/', '') === organizationLink.id ) : false ) const allRightOfCohort = !organizationLinkItems ? [] - : rightsData.filter((rightData: any) => + : rightsData.filter((rightData: GroupRights) => organizationLinkItems.find( (organizationLinkItem) => - +organizationLinkItem.managingEntity.display.replace('Organization/', '') === rightData.care_site_id + (organizationLinkItem?.managingEntity?.display || '').replace('Organization/', '') === + String(rightData.care_site_id) ) ) @@ -702,7 +688,7 @@ const servicesCohorts: IServiceCohorts = { valueString: !!ODD_EXPORT && allRightOfCohort.filter( - (rightOfCohort: any) => + (rightOfCohort: GroupRights) => rightOfCohort.right_export_csv_nominative === true && rightOfCohort.right_read_patient_nominative === true ).length === allRightOfCohort.length @@ -713,7 +699,7 @@ const servicesCohorts: IServiceCohorts = { url: 'READ_ACCESS', valueString: allRightOfCohort.filter( - (rightOfCohort: any) => rightOfCohort.right_read_patient_nominative === true // eslint-disabled-line + (rightOfCohort: GroupRights) => rightOfCohort.right_read_patient_nominative === true // eslint-disabled-line ).length === allRightOfCohort.length ? 'DATA_NOMINATIVE' : 'DATA_PSEUDOANONYMISED' @@ -809,11 +795,11 @@ const getDocumentInfos: ( return [] } - const listeEncounters = encounters.data.entry.map((e: any) => e.resource) + const listeEncounters = encounters.data.entry.map((e: BundleEntry) => e.resource) as Encounter[] - let listePatients = [] + let listePatients: Array = [] if (patients.data.resourceType === 'Bundle' && patients.data.entry) { - listePatients = patients?.data?.entry.map((e: any) => e.resource) + listePatients = patients?.data?.entry.map((e: BundleEntry) => e.resource).filter((e): e is Patient => !!e) } for (const document of cohortDocuments) { diff --git a/src/services/aphp/servicePatients.ts b/src/services/aphp/servicePatients.ts index 4c5dd7399..29a12bfd9 100644 --- a/src/services/aphp/servicePatients.ts +++ b/src/services/aphp/servicePatients.ts @@ -48,7 +48,7 @@ export interface IServicePatients { ** ** Elle ne prend aucun argument, et un nombre de patient */ - fetchPatientsCount: () => Promise + fetchPatientsCount: () => Promise /* ** Cette fonction permet de récupérer l'ensemble des patients lié à un utilisateur @@ -299,11 +299,11 @@ const servicesPatients: IServicePatients = { fetchPatientsCount: async () => { try { const response = await fetchPatient({ size: 0 }) - if (response?.data?.resourceType === 'OperationOutcome') return null as any + if (response?.data?.resourceType === 'OperationOutcome') return null return response.data.total ?? 0 - } catch (error: any) { + } catch (error) { console.error(error) - return null as any + return null } }, diff --git a/src/state/cohortCreation.ts b/src/state/cohortCreation.ts index 356fd938d..457c6111c 100644 --- a/src/state/cohortCreation.ts +++ b/src/state/cohortCreation.ts @@ -260,7 +260,7 @@ const buildCohortCreation = createAsyncThunk { try { - const state: any = getState() + const state = getState() const _selectedPopulation = selectedPopulation ? selectedPopulation @@ -349,7 +349,7 @@ const unbuildCohortCreation = createAsyncThunk 0) { - _temporalConstraints = temporalConstraints.map((temporalConstraint: TemporalConstraintsType, index) => { + _temporalConstraints = temporalConstraints.map((temporalConstraint: TemporalConstraintsType, index: number) => { return { ...temporalConstraint, id: index + 1 diff --git a/src/state/medication.ts b/src/state/medication.ts index 987df66ca..2e61023e7 100644 --- a/src/state/medication.ts +++ b/src/state/medication.ts @@ -91,7 +91,7 @@ const expandMedicationElement = createAsyncThunk i.id === 'loading') : true + const foundItem = item.subItems ? item.subItems.find((i) => i.id === 'loading') : true if (foundItem) { let subItems: MedicationListType[] = [] subItems = await services.cohortCreation.fetchAtcHierarchy(item.id) @@ -122,7 +122,7 @@ const expandMedicationElement = createAsyncThunk savedSelectedItem.id !== 'loading') + savedSelectedItems: savedSelectedItems.filter((savedSelectedItem) => savedSelectedItem.id !== 'loading') } } ) diff --git a/src/state/pmsi.ts b/src/state/pmsi.ts index 6391b79dd..385cfd383 100644 --- a/src/state/pmsi.ts +++ b/src/state/pmsi.ts @@ -162,7 +162,7 @@ const expandPmsiElement = createAsyncThunk i.id === 'loading') : true + const foundItem = item.subItems ? item.subItems.find((i) => i.id === 'loading') : true if (foundItem) { let subItems: PmsiListType[] = [] if (keyElement === 'claim') { @@ -204,7 +204,7 @@ const expandPmsiElement = createAsyncThunk savedSelectedItem.id !== 'loading') + savedSelectedItems: savedSelectedItems.filter((savedSelectedItem) => savedSelectedItem.id !== 'loading') } } ) diff --git a/src/state/scope.ts b/src/state/scope.ts index 4c630fe2f..90fced3a6 100644 --- a/src/state/scope.ts +++ b/src/state/scope.ts @@ -131,7 +131,7 @@ const expandScopeElement = createAsyncThunk i.id === 'loading') : true + const foundItem = item.subItems ? item.subItems.find((i) => i.id === 'loading') : true if (foundItem) { const subItems: ScopeTreeRow[] = await services.perimeters.getScopeSubItems( item.inferior_levels_ids, diff --git a/src/types.ts b/src/types.ts index 52093e4bb..991235c42 100644 --- a/src/types.ts +++ b/src/types.ts @@ -159,10 +159,12 @@ export type CohortFilters = { endDate: null | string } +export type SimpleCodeType = { code: string; label: string; type: string } + export type DocumentFilters = { ipp?: string nda: string - selectedDocTypes: { code: string; label: string; type: string }[] + selectedDocTypes: SimpleCodeType[] startDate: string | null endDate: string | null onlyPdfAvailable: boolean @@ -801,6 +803,22 @@ export type IScope = { previous: string | null results: ScopePage[] } + +export type GroupRights = { + perimeter_id: string + care_site_id: number + provider_id: string + care_site_history_ids: number[] + access_ids: number[] + right_read_patient_nominative: boolean + right_read_patient_pseudo_anonymised: boolean + right_search_patient_with_ipp: boolean + right_export_csv_nominative: boolean + right_export_csv_pseudo_anonymised: boolean + right_transfer_jupyter_nominative: boolean + right_transfer_jupyter_pseudo_anonymised: boolean +} + export type ErrorType = { isError: boolean; errorMessage?: string } export type AgeRangeType = { year?: number @@ -812,6 +830,8 @@ export type AccessExpirationsProps = { expiring?: boolean } +export type SimpleStatus = 'success' | 'error' | null + export type AccessExpiration = { leftDays?: number start_datetime: Date diff --git a/src/utils/age.ts b/src/utils/age.ts index aaca1854f..8724312df 100644 --- a/src/utils/age.ts +++ b/src/utils/age.ts @@ -1,11 +1,11 @@ import { AgeRangeType, CohortPatient } from 'types' import moment from 'moment' -export const getAgeAphp = (ageObj: any, momentUnit: 'days' | 'months') => { - if (!ageObj) return 'Âge inconnu' +export const getAgeAphp = (ageValue: number | undefined, momentUnit: 'days' | 'months'): string => { + if (!ageValue) return 'Âge inconnu' let ageUnit: 'year' | 'month' | 'day' = 'year' let ageUnitDisplay = '' - const momentAge = moment().subtract(ageObj.valueInteger, momentUnit) + const momentAge = moment().subtract(ageValue, momentUnit) const today = moment() if (today.diff(momentAge, 'year') > 0) { @@ -27,17 +27,17 @@ export const getAgeAphp = (ageObj: any, momentUnit: 'days' | 'months') => { export const getAge = (patient: CohortPatient): string => { if (patient.extension) { const totalDays = patient.extension.find((item) => item.url?.includes('Age(TotalDays)')) + const totalMonths = patient.extension.find((item) => item.url?.includes('Age(TotalMonths)')) if (totalDays) { - return getAgeAphp(totalDays, 'days') - } else { - const totalMonths = patient.extension.find((item) => item.url?.includes('Age(TotalMonths)')) - return getAgeAphp(totalMonths, 'months') + return getAgeAphp(totalDays.valueInteger, 'days') + } else if (totalMonths) { + return getAgeAphp(totalMonths.valueInteger, 'months') } } return 'Âge inconnu' } -export const ageName = (dates: [string, string]) => { +export const ageName = (dates: [string, string]): string => { const minDate: AgeRangeType = convertStringToAgeRangeType(dates[1]) ?? { year: 0, month: 0, days: 0 } const maxDate: AgeRangeType = convertStringToAgeRangeType(dates[0]) ?? { year: 0, month: 0, days: 0 } @@ -66,7 +66,7 @@ export const ageName = (dates: [string, string]) => { ${(maxDate.days ?? 0) > 0 ? `${maxDate.days} jour(s) ` : ``}` } -export const substructAgeRangeType = (ageDate: AgeRangeType) => { +export const substructAgeRangeType = (ageDate: AgeRangeType): Date => { if (!ageDate) return new Date() const today: Date = new Date() const newDate: Date = new Date( @@ -80,12 +80,12 @@ export const substructAgeRangeType = (ageDate: AgeRangeType) => { return newDate } -export const substructAgeString = (range: string) => { +export const substructAgeString = (range: string): Date => { const ageRangeType: AgeRangeType = convertStringToAgeRangeType(range) ?? { year: 0, month: 0, days: 0 } return substructAgeRangeType(ageRangeType) } -export const convertStringToAgeRangeType = (age: string) => { +export const convertStringToAgeRangeType = (age: string): AgeRangeType | undefined => { if (!age) return undefined const newAge: AgeRangeType = { year: Number(age.split('/')[2]), @@ -95,6 +95,6 @@ export const convertStringToAgeRangeType = (age: string) => { return newAge } -export const convertAgeRangeTypeToString = (ageDate: AgeRangeType) => { +export const convertAgeRangeTypeToString = (ageDate: AgeRangeType): string => { return ageDate.days + '/' + ageDate.month + '/' + ageDate.year } diff --git a/src/utils/alphabeticalSort.ts b/src/utils/alphabeticalSort.ts index a86f047e8..dd82ffeb9 100644 --- a/src/utils/alphabeticalSort.ts +++ b/src/utils/alphabeticalSort.ts @@ -1,6 +1,6 @@ import moment from 'moment' -export const codeSort = (a: any, b: any) => { +export const codeSort = (a: any, b: any): number => { if (a.code < b.code) { return -1 } @@ -10,7 +10,7 @@ export const codeSort = (a: any, b: any) => { return 0 } -export const displaySort = (a: any, b: any) => { +export const displaySort = (a: any, b: any): number => { if (a.display < b.display) { return -1 } @@ -20,7 +20,7 @@ export const displaySort = (a: any, b: any) => { return 0 } -export const targetDisplaySort = (a: any, b: any) => { +export const targetDisplaySort = (a: any, b: any): number => { if (a.target?.[0].display < b.target?.[0].display) { return -1 } @@ -30,7 +30,7 @@ export const targetDisplaySort = (a: any, b: any) => { return 0 } -export const descendingComparator = (a: any, b: any, orderBy: any) => { +export const descendingComparator = (a: any, b: any, orderBy: any): number => { const dateA = moment(new Date(a[orderBy])) const dateB = moment(new Date(b[orderBy])) @@ -46,13 +46,13 @@ export const descendingComparator = (a: any, b: any, orderBy: any) => { return 0 } -export const getComparator = (order: any, orderBy: any) => { +export const getComparator = (order: any, orderBy: any): ((a: any, b: any) => number) => { return order === 'desc' - ? (a: any, b: any) => descendingComparator(a, b, orderBy) - : (a: any, b: any) => -descendingComparator(a, b, orderBy) + ? (a: any, b: any): number => descendingComparator(a, b, orderBy) + : (a: any, b: any): number => -descendingComparator(a, b, orderBy) } -export const stableSort = (array: any[], comparator: any) => { +export const stableSort = (array: any[], comparator: any): any[] => { const stabilizedThis = array.map((el, index) => [el, index]) stabilizedThis.sort((a, b) => { const order = comparator(a[0], b[0]) diff --git a/src/utils/apiHelpers.ts b/src/utils/apiHelpers.ts index a0284483c..6fc71000d 100644 --- a/src/utils/apiHelpers.ts +++ b/src/utils/apiHelpers.ts @@ -1,11 +1,25 @@ import { AxiosResponse } from 'axios' -import { FhirResource } from 'fhir/r4' +import { FhirResource, OperationOutcome } from 'fhir/r4' import { FHIR_API_Response } from 'types' export function getApiResponseResources( response: AxiosResponse> ): T[] | undefined { - if (!response || !(response && response.data) || response.data.resourceType === 'OperationOutcome') return undefined + try { + return getApiResponseResourcesOrThrow(response) + } catch (e) { + return undefined + } +} + +export function getApiResponseResourcesOrThrow( + response: AxiosResponse> +): T[] { + if (!response || !(response && response.data) || response.data.resourceType === 'OperationOutcome') { + throw new Error( + (response.data as OperationOutcome).issue.map((issue) => issue.details?.text || issue.code).join('\n') + ) + } const a = response.data.entry ? response.data.entry.map((r) => r.resource).filter((r): r is T => undefined !== r) : [] return a diff --git a/src/utils/capitalize.ts b/src/utils/capitalize.ts index 6973432a1..d32e3c71a 100644 --- a/src/utils/capitalize.ts +++ b/src/utils/capitalize.ts @@ -1,4 +1,4 @@ -export const capitalizeFirstLetter = (string?: string) => { +export const capitalizeFirstLetter = (string?: string): string => { if (!string) return '' return string diff --git a/src/utils/chips.ts b/src/utils/chips.ts index 2684ed8c9..d1be29ac0 100644 --- a/src/utils/chips.ts +++ b/src/utils/chips.ts @@ -13,11 +13,12 @@ import { PMSIFilters as PMSIFiltersType, CohortFilters as CohortFiltersType } from 'types' +import { MasterChipsProps } from 'components/MasterChips/MasterChips' export const buildDocumentFiltersChips = ( filters: DocumentFiltersType, handleDeleteChip: (filterName: 'nda' | 'ipp' | 'selectedDocTypes' | 'startDate' | 'endDate', value?: string) => void -) => { +): MasterChipsProps['chips'] => { const displayingSelectedDocType: any[] = getDisplayingSelectedDocTypes(filters.selectedDocTypes) return ( @@ -54,17 +55,14 @@ export const buildDocumentFiltersChips = ( ] .flat() // @ts-ignore - .filter((chip) => chip?.label) as { - label: string - onDelete?: (args: any) => void - }[] + .filter((chip) => chip?.label) as MasterChipsProps['chips'] ) } export const buildPatientFiltersChips = ( filters: PatientFiltersType, handleDeleteChip: (filterName: 'gender' | 'birthdates' | 'vitalStatus') => void -) => { +): MasterChipsProps['chips'] => { const gender = genderName(filters.gender) const birthdates = ageName(filters.birthdatesRanges) const vitalStatus = vitalStatusName(filters.vitalStatus) @@ -73,16 +71,13 @@ export const buildPatientFiltersChips = ( { label: gender ? gender : '', onDelete: () => handleDeleteChip('gender') }, { label: birthdates ? birthdates : '', onDelete: () => handleDeleteChip('birthdates') }, { label: vitalStatus ? vitalStatus : '', onDelete: () => handleDeleteChip('vitalStatus') } - ].filter((chip) => chip?.label) as { - label: string - onDelete?: (args: any) => void - }[] + ].filter((chip) => chip?.label) as MasterChipsProps['chips'] } export const buildObservationFiltersChips = ( filters: ObservationFiltersType, handleDeleteChip: (filterName: 'nda' | 'loinc' | 'anabio' | 'startDate' | 'endDate', value?: any) => void -) => { +): MasterChipsProps['chips'] => { return ( [ filters.nda && @@ -132,10 +127,7 @@ export const buildObservationFiltersChips = ( ] .flat() // @ts-ignore - .filter((chip) => chip?.label) as { - label: string - onDelete?: (args: any) => void - }[] + .filter((chip) => chip?.label) as MasterChipsProps['chips'] ) } @@ -145,7 +137,7 @@ export const buildMedicationFiltersChips = ( filterName: 'nda' | 'selectedPrescriptionTypes' | 'selectedAdministrationRoutes' | 'startDate' | 'endDate', value?: any ) => void -) => { +): MasterChipsProps['chips'] => { return ( [ filters.nda && @@ -189,10 +181,7 @@ export const buildMedicationFiltersChips = ( ] .flat() // @ts-ignore - .filter((chip) => chip?.label) as { - label: string - onDelete?: (args: any) => void - }[] + .filter((chip) => chip?.label) as MasterChipsProps['chips'] ) } @@ -202,7 +191,7 @@ export const buildPmsiFiltersChips = ( filterName: 'nda' | 'code' | 'selectedDiagnosticTypes' | 'startDate' | 'endDate', value?: any ) => void -) => { +): MasterChipsProps['chips'] => { return ( [ filters.nda && @@ -245,10 +234,7 @@ export const buildPmsiFiltersChips = ( ] .flat() // @ts-ignore - .filter((chip) => chip?.label) as { - label: string - onDelete?: (args: any) => void - }[] + .filter((chip) => chip?.label) as MasterChipsProps['chips'] ) } @@ -258,7 +244,7 @@ export const buildCohortFiltersChips = ( filterName: 'status' | 'favorite' | 'minPatients' | 'maxPatients' | 'startDate' | 'endDate', value?: any ) => void -) => { +): MasterChipsProps['chips'] => { return ( [ filters.status?.length > 0 && @@ -294,9 +280,6 @@ export const buildCohortFiltersChips = ( ] .flat() // @ts-ignore - .filter((chip) => chip?.label) as { - label: string - onDelete?: (args: any) => void - }[] + .filter((chip) => chip?.label) as MasterChipsProps['chips'] ) } diff --git a/src/utils/cleanValueSet.ts b/src/utils/cleanValueSet.ts index 57f619cf4..88d075aea 100644 --- a/src/utils/cleanValueSet.ts +++ b/src/utils/cleanValueSet.ts @@ -2,7 +2,7 @@ import { ValueSet } from 'types' import { displaySort } from './alphabeticalSort' import { capitalizeFirstLetter } from './capitalize' -export const cleanValueSet = (valueSet: ValueSet[]) => { +export const cleanValueSet = (valueSet: ValueSet[]): { id: string; label: string }[] => { if (valueSet && valueSet.length > 0) { const cleanData = valueSet.filter((value: ValueSet) => value.code !== 'APHP generated') diff --git a/src/utils/cohortCreation.ts b/src/utils/cohortCreation.ts index dcb0019cb..b0ad8f19c 100644 --- a/src/utils/cohortCreation.ts +++ b/src/utils/cohortCreation.ts @@ -158,12 +158,12 @@ type RequeteurSearchType = { request: RequeteurGroupType | undefined } -const constructFilterFhir = (criterion: SelectedCriteriaType) => { +const constructFilterFhir = (criterion: SelectedCriteriaType): string => { let filterFhir = '' - const filterReducer = (accumulator: any, currentValue: any) => + const filterReducer = (accumulator: any, currentValue: any): string => accumulator ? `${accumulator}&${currentValue}` : currentValue ? currentValue : accumulator - const searchReducer = (accumulator: any, currentValue: any) => + const searchReducer = (accumulator: any, currentValue: any): string => accumulator || accumulator === false ? `${accumulator},${currentValue}` : currentValue ? currentValue : accumulator switch (criterion.type) { @@ -520,11 +520,11 @@ export function buildRequest( selectedCriteria: SelectedCriteriaType[], criteriaGroup: CriteriaGroupType[], temporalConstraints: TemporalConstraintsType[] -) { +): string { if (!selectedPopulation) return '' selectedPopulation = selectedPopulation.filter((elem) => elem !== undefined) - const exploreCriteriaGroup = (itemIds: number[]) => { + const exploreCriteriaGroup = (itemIds: number[]): (RequeteurCriteriaType | RequeteurGroupType)[] => { let children: (RequeteurCriteriaType | RequeteurGroupType)[] = [] for (const itemId of itemIds) { @@ -636,7 +636,7 @@ export function buildRequest( return JSON.stringify(json) } -export async function unbuildRequest(_json: string) { +export async function unbuildRequest(_json: string): Promise { let population: (ScopeTreeRow | undefined)[] | null = null let criteriaItems: RequeteurCriteriaType[] = [] let criteriaGroup: RequeteurGroupType[] = [] @@ -684,7 +684,7 @@ export async function unbuildRequest(_json: string) { * Retrieve criteria + groups * */ - const exploreRequest = (currentItem: any) => { + const exploreRequest = (currentItem: any): void => { const { criteria } = currentItem for (const criterion of criteria) { @@ -706,7 +706,7 @@ export async function unbuildRequest(_json: string) { return { population, criteria: [], criteriaGroup: [] } } - const _retrieveInformationFromJson = async (element: RequeteurCriteriaType) => { + const _retrieveInformationFromJson = async (element: RequeteurCriteriaType): Promise => { const currentCriterion: any = { id: element._id, type: element.resourceType, @@ -1574,7 +1574,7 @@ export const getDataFromFetch = async ( _criteria: any, selectedCriteria: SelectedCriteriaType[], oldCriteriaList?: any -) => { +): Promise => { for (const _criterion of _criteria) { const oldCriterion = oldCriteriaList ? oldCriteriaList?.find((oldCriterionItem: any) => oldCriterionItem.id === _criterion.id) @@ -1662,11 +1662,11 @@ export const getDataFromFetch = async ( return _criteria } -export const joinRequest = async (oldJson: string, newJson: string, parentId: number | null) => { +export const joinRequest = async (oldJson: string, newJson: string, parentId: number | null): Promise => { const oldRequest = JSON.parse(oldJson) as RequeteurSearchType const newRequest = JSON.parse(newJson) as RequeteurSearchType - const changeIdOfRequest = (request: any) => { + const changeIdOfRequest = (request: any): any => { const { criteria } = request for (const criterion of criteria) { @@ -1689,7 +1689,7 @@ export const joinRequest = async (oldJson: string, newJson: string, parentId: nu criteria: changeIdOfRequest(newRequest.request) } - const fillRequestWithNewRequest = (criterionGroup?: RequeteurGroupType) => { + const fillRequestWithNewRequest = (criterionGroup?: RequeteurGroupType): RequeteurGroupType | undefined => { if (!criterionGroup) return criterionGroup if (criterionGroup._id === parentId) { diff --git a/src/utils/d3_helper.js b/src/utils/d3_helper.js index 3639824c6..41fb617e7 100644 --- a/src/utils/d3_helper.js +++ b/src/utils/d3_helper.js @@ -1,3 +1,4 @@ +// eslint-disable-next-line @typescript-eslint/explicit-function-return-type export const getOptimalTicksCount = (maxTick) => { /* Function adapted from http://bl.ocks.org/tanykim/62462c396b37874ebd87 diff --git a/src/utils/debounce.ts b/src/utils/debounce.ts index 21bcbda85..3c726203e 100644 --- a/src/utils/debounce.ts +++ b/src/utils/debounce.ts @@ -1,6 +1,6 @@ import { useState, useEffect } from 'react' -export const useDebounce = (delay: number, value?: string) => { +export const useDebounce = (delay: number, value?: string): string | undefined => { const [debouncedValue, setDebouncedValue] = useState(value) useEffect(() => { @@ -16,7 +16,7 @@ export const useDebounce = (delay: number, value?: string) => { return debouncedValue } -export const debounce = (fn: any, delay: any) => { +export const debounce = (fn: any, delay: any): ((...args: any) => void) => { let timeout: any = -1 return (...args: any) => { diff --git a/src/utils/displayDigit.ts b/src/utils/displayDigit.ts index 932a19788..7a8f6228b 100644 --- a/src/utils/displayDigit.ts +++ b/src/utils/displayDigit.ts @@ -1,4 +1,4 @@ -export default function (number: number) { +export default function (number: number): string { const _number: string = number?.toString().split('').reverse().join('') let result = '' for (let i = _number?.length - 1; i >= 0; i--) { diff --git a/src/utils/documentsFormatter.ts b/src/utils/documentsFormatter.ts index 49e391577..ae481fac6 100644 --- a/src/utils/documentsFormatter.ts +++ b/src/utils/documentsFormatter.ts @@ -1,5 +1,5 @@ import docTypes from 'assets/docTypes.json' -import { CompositionStatusKind, DocumentReferenceStatusKind, EncounterStatusKind } from 'types' +import { CompositionStatusKind, DocumentReferenceStatusKind, EncounterStatusKind, SimpleCodeType } from 'types' export const getDocumentStatus = (status?: CompositionStatusKind | DocumentReferenceStatusKind): string => { switch (status) { @@ -54,9 +54,9 @@ export const getProcedureStatus = (status?: string): string => { } } -export const getDisplayingSelectedDocTypes = (selectedDocTypes: any[]) => { - let displayingSelectedDocTypes: any[] = [] - const allTypes = docTypes.docTypes.map((docType: any) => docType.type) +export const getDisplayingSelectedDocTypes = (selectedDocTypes: SimpleCodeType[]): SimpleCodeType[] => { + let displayingSelectedDocTypes: SimpleCodeType[] = [] + const allTypes = docTypes.docTypes.map((docType: SimpleCodeType) => docType.type) for (const selectedDocType of selectedDocTypes) { const numberOfElementFromGroup = (allTypes.filter((type) => type === selectedDocType.type) || []).length diff --git a/src/utils/formatDate.ts b/src/utils/formatDate.ts index be6358c00..a831fde72 100644 --- a/src/utils/formatDate.ts +++ b/src/utils/formatDate.ts @@ -1,7 +1,7 @@ import { Month } from 'types' import moment from 'moment/moment' -const getFormatedDate = (date: Date) => { +const getFormatedDate = (date: Date): string => { const mm = date.getMonth() + 1 // getMonth() is zero-based const dd = date.getDate() diff --git a/src/utils/graphUtils.ts b/src/utils/graphUtils.ts index 6a563b6d8..5141b50c1 100644 --- a/src/utils/graphUtils.ts +++ b/src/utils/graphUtils.ts @@ -8,7 +8,7 @@ import { import { getStringMonth, getStringMonthAphp } from './formatDate' import { Encounter, Extension, Patient } from 'fhir/r4' -function getRandomColor() { +function getRandomColor(): string { const letters = '0123456789ABCDEF' let color = '#' for (let i = 0; i < 6; i++) { @@ -17,7 +17,7 @@ function getRandomColor() { return color } -const getVisitTypeName = (visitType?: string) => { +const getVisitTypeName = (visitType?: string): string => { let name = '' switch (visitType) { @@ -40,7 +40,7 @@ const getVisitTypeName = (visitType?: string) => { return name } -const getVisitTypeColor = (visitType?: string) => { +const getVisitTypeColor = (visitType?: string): string => { let color = '' switch (visitType) { diff --git a/src/utils/patient.ts b/src/utils/patient.ts index 7b1b2a8a8..d0a76fa8a 100644 --- a/src/utils/patient.ts +++ b/src/utils/patient.ts @@ -1,6 +1,6 @@ import { PatientGenderKind, VitalStatus } from 'types' -export const genderName = (gender: PatientGenderKind) => { +export const genderName = (gender: PatientGenderKind): string => { switch (gender) { case PatientGenderKind._female: return 'Genre: Femmes' @@ -8,14 +8,19 @@ export const genderName = (gender: PatientGenderKind) => { return 'Genre: Hommes' case PatientGenderKind._other: return 'Genre: Autre' + case PatientGenderKind._unknown: + default: + return 'Genre: Inconnu' } } -export const vitalStatusName = (vitalStatus: VitalStatus) => { +export const vitalStatusName = (vitalStatus: VitalStatus): string => { switch (vitalStatus) { case VitalStatus.alive: return 'Patients vivants' case VitalStatus.deceased: return 'Patients décédés' + default: + return 'Statut vital: Inconnu' } } diff --git a/src/utils/pmsi.ts b/src/utils/pmsi.ts index 1177362de..95a39bb6b 100644 --- a/src/utils/pmsi.ts +++ b/src/utils/pmsi.ts @@ -16,7 +16,7 @@ import { expandBiologyElement } from '../state/biology' * This function is called when a user select an element of pmsi hierarchy * return selected items that should be saved */ -export const getSelectedPmsi = (row: any, selectedItems: any[] | undefined, rootRows: any[]) => { +export const getSelectedPmsi = (row: any, selectedItems: any[] | undefined, rootRows: any[]): any[] => { selectedItems = (selectedItems ?? []).map( (selectedItem) => findEquivalentRowInItemAndSubItems(selectedItem, rootRows).equivalentRow ?? selectedItem ) @@ -24,7 +24,7 @@ export const getSelectedPmsi = (row: any, selectedItems: any[] | undefined, root let savedSelectedItems = flattedSelectedItems const isFound = savedSelectedItems?.find((item) => item.id === row.id) - const getRowAndChildren = (parent: any) => { + const getRowAndChildren = (parent: any): any[] => { const getChild: (subItem: any) => any[] = (subItem: any) => { if (subItem?.id === 'loading') return [] @@ -41,7 +41,7 @@ export const getSelectedPmsi = (row: any, selectedItems: any[] | undefined, root ].flat() } - const deleteRowAndChildren = (parent: any) => { + const deleteRowAndChildren = (parent: any): any[] => { const elemToDelete = getRowAndChildren(parent) savedSelectedItems = savedSelectedItems.filter((row) => !elemToDelete.some(({ id }) => id === row.id)) @@ -56,7 +56,7 @@ export const getSelectedPmsi = (row: any, selectedItems: any[] | undefined, root } let _savedSelectedItems: any[] = [] - const checkIfParentIsChecked = (rows: any[]) => { + const checkIfParentIsChecked = (rows: any[]): void => { for (let index = 0; index < rows.length; index++) { const row = rows[index] if ( @@ -109,7 +109,7 @@ export const getSelectedPmsi = (row: any, selectedItems: any[] | undefined, root return savedSelectedItems } -export const optimizeHierarchySelection = (selectedItems: PmsiListType[], rootRows: PmsiListType[]) => { +export const optimizeHierarchySelection = (selectedItems: PmsiListType[], rootRows: PmsiListType[]): PmsiListType[] => { // If you chenge this code, change it too inside: PopulationCard.tsx:31 and Scope.jsx:25 selectedItems = selectedItems.map( (selectedItem) => findEquivalentRowInItemAndSubItems(selectedItem, rootRows).equivalentRow ?? selectedItem @@ -257,10 +257,10 @@ export const findEquivalentRowInItemAndSubItems: ( } return { equivalentRow: equivalentRow, parentsList: parentsList } } -export const flatItems = (items: any[] | undefined) => { - const selectedIds: string[] | undefined = [] - const flattedSelectedItems: any[] | undefined = [] - const flat = (items: any[] | undefined) => { +export const flatItems = (items: any[] | undefined): { flattedSelectedItems: any[]; selectedIds: string[] } => { + const selectedIds: string[] = [] + const flattedSelectedItems: any[] = [] + const flat = (items: any[] | undefined): void => { if (!items) return items.forEach((item) => { if (item.id === 'loading') { @@ -285,7 +285,7 @@ export const initSyncHierarchyTableEffect = async ( resourceType: string, dispatch: AppDispatch, isFetchedResource?: boolean -) => { +): Promise => { if (!isFetchedResource) { await dispatch(fetchResource()) } @@ -311,12 +311,12 @@ export const onChangeSelectedCriteriaEffect = async ( resourceHierarchy: PmsiListType[], resourceType: string, dispatch: AppDispatch -) => { +): Promise => { await expandHierarchyCodes(codesToExpand, selectedCodes, resourceHierarchy, resourceType, dispatch) dispatch(pushSyncHierarchyTable({ code: selectedCodes })) } -const isExpanded = (itemToExpand: PmsiListType | undefined) => { +const isExpanded = (itemToExpand: PmsiListType | undefined): boolean => { if ( itemToExpand && itemToExpand.subItems && @@ -339,7 +339,7 @@ const expandRequest = async ( selectedCodes: PmsiListType[], resourceType: string, dispatch: AppDispatch -) => { +): Promise => { let type: 'claim' | 'condition' | 'procedure' = 'claim' if (resourceType.toLowerCase() === MEDICATION_REQUEST.toLowerCase()) { const expandedMedication = await dispatch( @@ -382,7 +382,7 @@ export const expandItem = async ( resourceHierarchy: PmsiListType[], resourceType: string, dispatch: AppDispatch -) => { +): Promise => { const equivalentRow = findEquivalentRowInItemAndSubItems( { id: codeToExpand, label: 'loading' }, resourceHierarchy @@ -402,7 +402,7 @@ const expandSingleResourceItem = async ( resourceHierarchy: PmsiListType[], resourceType: string, dispatch: AppDispatch -) => { +): Promise => { if ( !codeToExpand || (selectedCodes.find((item) => item.id === codeToExpand.id) && @@ -410,7 +410,7 @@ const expandSingleResourceItem = async ( ) return resourceHierarchy let newResourceHierarchy: PmsiListType[] = resourceHierarchy - const expandItemAndSubItems = async (itemToExpand: PmsiListType, resourceType: string) => { + const expandItemAndSubItems = async (itemToExpand: PmsiListType, resourceType: string): Promise => { newResourceHierarchy = await expandItem( itemToExpand?.id, selectedCodes, @@ -432,7 +432,7 @@ const expandSingleResourceItem = async ( } return newResourceHierarchy } - const getHigherParentFromList = (parentsList: PmsiListType[]) => { + const getHigherParentFromList = (parentsList: PmsiListType[]): PmsiListType | undefined => { const higherParentCode: PmsiListType | undefined = newResourceHierarchy && newResourceHierarchy[0] && newResourceHierarchy[0].subItems ? newResourceHierarchy[0].subItems.find(({ id }) => parentsList.find((code) => code.id === id)) @@ -440,7 +440,9 @@ const expandSingleResourceItem = async ( return higherParentCode } - const getHigherParent = async (code: PmsiListType) => { + const getHigherParent = async ( + code: PmsiListType + ): Promise<{ higherParentCode: PmsiListType | undefined; parentsList: any[] }> => { const { parentsList: parentsListByAlreadyFetched } = findEquivalentRowInItemAndSubItems( codeToExpand, newResourceHierarchy @@ -473,7 +475,7 @@ const expandHierarchyCodes = async ( resourceHierarchy: PmsiListType[], resourceType: string, dispatch: AppDispatch -) => { +): Promise => { let newResourceHierarchy: PmsiListType[] = resourceHierarchy for await (const itemToExpand of codesToExpand) { newResourceHierarchy = await expandSingleResourceItem( @@ -496,7 +498,7 @@ export const syncOnChangeFormValue = async ( selectedTab: string, resourceType: string, dispatch: AppDispatch -) => { +): Promise => { const newSelectedCriteria: any = selectedCriteria ? { ...selectedCriteria } : {} newSelectedCriteria[key] = value if (key === 'code') { diff --git a/src/utils/scopeTree.ts b/src/utils/scopeTree.ts index a070754bf..46fa9df2f 100644 --- a/src/utils/scopeTree.ts +++ b/src/utils/scopeTree.ts @@ -8,13 +8,13 @@ export const getSelectedScopes = ( row: ScopeTreeRow, selectedItems: ScopeTreeRow[] | undefined, rootRows: ScopeTreeRow[] -) => { +): ScopeTreeRow[] => { let savedSelectedItems = selectedItems ? [...selectedItems] : [] const foundItem = savedSelectedItems.find(({ id }) => id === row.id) const index = foundItem ? savedSelectedItems.indexOf(foundItem) : -1 - const getRowAndChildren = (parent: ScopeTreeRow) => { + const getRowAndChildren = (parent: ScopeTreeRow): ScopeTreeRow[] => { const getChild: (subItem: ScopeTreeRow) => ScopeTreeRow[] = (subItem: ScopeTreeRow) => { if (subItem?.id === 'loading') return [] @@ -34,7 +34,7 @@ export const getSelectedScopes = ( ].flat() } - const deleteRowAndChildren = (parent: ScopeTreeRow) => { + const deleteRowAndChildren = (parent: ScopeTreeRow): ScopeTreeRow[] => { const elemToDelete = getRowAndChildren(parent) savedSelectedItems = savedSelectedItems.filter((row) => !elemToDelete.some(({ id }) => id === row.id)) @@ -43,7 +43,7 @@ export const getSelectedScopes = ( if (row.subItems && row.subItems.length > 0 && row.subItems[0].id === 'loading') { return true } - const numberOfSubItemsSelected = row?.subItems?.filter((subItem: any) => + const numberOfSubItemsSelected = row?.subItems?.filter((subItem) => savedSelectedItems.find(({ id }) => id === subItem.id) )?.length if (numberOfSubItemsSelected && numberOfSubItemsSelected !== row?.subItems?.length) { @@ -62,7 +62,7 @@ export const getSelectedScopes = ( } let _savedSelectedItems: any[] = [] - const checkIfParentIsChecked = (rows: ScopeTreeRow[]) => { + const checkIfParentIsChecked = (rows: ScopeTreeRow[]): void => { for (let index = 0; index < rows.length; index++) { const row = rows[index] if ( @@ -113,7 +113,7 @@ export const getSelectedScopes = ( return savedSelectedItems } -export const filterScopeTree = (_selectedItems: any[]) => { +export const filterScopeTree = (_selectedItems: any[]): any => { // If you chenge this code, change it too inside: PopulationCard.tsx:31 return _selectedItems.filter((item, index, array) => { // reemove double item @@ -161,7 +161,7 @@ export const filterScopeTree = (_selectedItems: any[]) => { }) } -export const sortByQuantityAndName = (scopeRows: ScopeTreeRow[]) => { +export const sortByQuantityAndName = (scopeRows: ScopeTreeRow[]): ScopeTreeRow[] => { // Sort by quantity scopeRows = scopeRows.sort((a: ScopeTreeRow, b: ScopeTreeRow) => { if (a.quantity > b.quantity) { diff --git a/src/views/Contact/Contact.tsx b/src/views/Contact/Contact.tsx index 654a1c607..39aa3a42a 100644 --- a/src/views/Contact/Contact.tsx +++ b/src/views/Contact/Contact.tsx @@ -61,7 +61,10 @@ const Contact: React.FC = () => { const [createIssueSuccess, setCreateIssueSuccess] = useState(false) const [createIssueFail, setCreateIssueFail] = useState(false) - const _onChangeValue = (key: 'requestType' | 'object' | 'url' | 'files' | 'message', value: any) => { + const _onChangeValue = ( + key: 'requestType' | 'object' | 'url' | 'files' | 'message', + value: string | FileList | null + ) => { const _contactRequest = { ...contactRequest } _contactRequest[key] = value setContactRequest(_contactRequest) diff --git a/src/views/Dashboard/Dashboard.tsx b/src/views/Dashboard/Dashboard.tsx index 6773fe2af..28617907c 100644 --- a/src/views/Dashboard/Dashboard.tsx +++ b/src/views/Dashboard/Dashboard.tsx @@ -113,7 +113,7 @@ const Dashboard: React.FC<{ dispatch(fetchExploredCohort({ context, id, forceReload: true })) } - const handleChangeTabs = (event: any, newTab: string) => { + const handleChangeTabs = (event: React.SyntheticEvent, newTab: string) => { selectTab(newTab) } diff --git a/src/views/MyProjects/MyProjects.tsx b/src/views/MyProjects/MyProjects.tsx index aab1ef55a..ac5a9a4af 100644 --- a/src/views/MyProjects/MyProjects.tsx +++ b/src/views/MyProjects/MyProjects.tsx @@ -17,7 +17,7 @@ import ModalMoveRequests from 'components/MyProjects/Modals/ModalMoveRequest/Mod import ModalDeleteRequests from 'components/MyProjects/Modals/ModalDeleteRequests/ModalDeleteRequests' import ModalShareRequest from 'components/MyProjects/Modals/ModalShareRequest/ModalShareRequest' -import { RequestType } from 'types' +import { RequestType, SimpleStatus } from 'types' import { useAppSelector, useAppDispatch } from 'state' import { ProjectState, fetchProjects as fetchProjectsList, setSelectedProject } from 'state/project' @@ -39,9 +39,9 @@ const MyProjects: React.FC<{}> = () => { const [searchInput, setSearchInput] = useState('') const [selectedRequests, setSelectedRequests] = useState([]) const [openModal, setOpenModal] = useState<'move_to_folder' | 'delete_items' | null>(null) - const [shareSuccessOrFailMessage, setShareSuccessOrFailMessage] = useState<'success' | 'error' | null>(null) + const [shareSuccessOrFailMessage, setShareSuccessOrFailMessage] = useState(null) const wrapperSetShareSuccessOrFailMessage = useCallback( - (val: any) => { + (val: SimpleStatus) => { setShareSuccessOrFailMessage(val) }, [setShareSuccessOrFailMessage] diff --git a/src/views/Patient/Patient.tsx b/src/views/Patient/Patient.tsx index dc3bd75fe..7dcfa1399 100644 --- a/src/views/Patient/Patient.tsx +++ b/src/views/Patient/Patient.tsx @@ -71,7 +71,7 @@ const Patient = () => { return } - const handleChangeTabs = (event: any, newTab: string) => { + const handleChangeTabs = (event: React.SyntheticEvent, newTab: string) => { selectTab(newTab) }