Skip to content

Commit

Permalink
no more refresh
Browse files Browse the repository at this point in the history
  • Loading branch information
guillaume-pages committed Jun 5, 2024
1 parent 583257e commit fde1efb
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 93 deletions.
52 changes: 30 additions & 22 deletions server/controllers/mediatheque.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { Request, Response } from 'express';
import { Brackets } from 'typeorm';

import type { Filter } from '../../types/mediatheque.type';
Expand All @@ -7,30 +8,37 @@ import { Controller } from './controller';

const mediathequeController = new Controller('/mediatheque');

mediathequeController.post({ path: '' }, async (req, res) => {
const filters: Array<Filter[]> = req?.body?.filters || [];
const offset = req?.query?.offset || 0;
mediathequeController.post({ path: '' }, async (req: Request, res: Response) => {
try {
const filters: Array<Filter[]> = req.body.filters || [];

let subQueryBuilder = AppDataSource.getRepository(Activity).createQueryBuilder('activity').innerJoin('activity.user', 'user');
if (!Array.isArray(filters)) {
return res.status(400).send({ error: 'Invalid filters format' });
}

filters.map((filter, index) => {
subQueryBuilder = subQueryBuilder[index === 0 ? 'where' : 'orWhere'](
new Brackets((qb) => {
filter.map(({ table, column, values }, subQueryIndex) => {
let condition = '';
values.map((value, valueIndex) => {
condition += valueIndex > 0 ? ' or ' : '(';
condition += `${table}.${column} = ${values[valueIndex]}`;
let subQueryBuilder = AppDataSource.getRepository(Activity).createQueryBuilder('activity').innerJoin('activity.user', 'user');

filters.map((filter, index) => {
subQueryBuilder = subQueryBuilder[index === 0 ? 'where' : 'orWhere'](
new Brackets((qb) => {
filter.map(({ table, column, values }, subQueryIndex) => {
let condition = '';
values.map((value, valueIndex) => {
condition += valueIndex > 0 ? ' or ' : '(';
condition += `${table}.${column} = ${values[valueIndex]}`;
});
condition += ')';
qb[subQueryIndex === 0 ? 'where' : 'andWhere'](condition);
});
condition += ')';
qb[subQueryIndex === 0 ? 'where' : 'andWhere'](condition);
});
}),
);
});
const activities = await subQueryBuilder
.getMany();
res.send(activities);
}),
);
});
const activities = await subQueryBuilder.getMany();
res.send(activities);
} catch (error) {
console.error('Error fetching media data:', error);
res.status(500).send({ error: 'Internal Server Error' });
}
});

export { mediathequeController };
export { mediathequeController };
4 changes: 0 additions & 4 deletions src/api/mediatheque/mediatheque.get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,6 @@ async function getMediatheque(params: { filters: Array<Filter[]> }) {
method: 'POST',
baseURL: '/api',
url: '/mediatheque',
// params: {
// offset: offset,
// limit: limit,
// },
data: {
filters: filters,
},
Expand Down
3 changes: 1 addition & 2 deletions src/components/admin/mediatheque/CardMediatheque.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,9 @@ import Typography from '@mui/material/Typography';

import MediathequeContext from 'src/contexts/mediathequeContext';

export default function MediaCard({ page }) {
export default function MediaCard({ page }: { page: number }) {
const { allFiltered } = useContext(MediathequeContext);


const activitiesMediaFinder = allFiltered?.map(({ id, content, subType, type, villageId, userId, user }) => {
const result = { id, subType, type, villageId, userId, content: [], user };
if (content.game) {

Check failure on line 15 in src/components/admin/mediatheque/CardMediatheque.tsx

View workflow job for this annotation

GitHub Actions / typescript

Property 'game' does not exist on type 'never'.
Expand Down
59 changes: 18 additions & 41 deletions src/components/admin/mediatheque/FiltersActivities.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useState, useContext } from 'react';
import React, { useEffect, useState, useContext, useCallback } from 'react';

import FormControl from '@mui/material/FormControl';
import MenuItem from '@mui/material/MenuItem';
Expand Down Expand Up @@ -32,50 +32,29 @@ export default function FiltersActivities() {
const theme = useTheme();
const [labelNameActivity, setLabelNameActivity] = useState<string[]>([]);
const [labelNameSubTheme, setLabelNameSubTheme] = useState<string[]>([]);
const [, setActivityNumber] = useState<number[]>([]);
const [, setSubThemeNumber] = useState<number[]>([]);
const { setFilters } = useContext(MediathequeContext);

useEffect(() => {
const updatedActivityNumbers: number[] = [];
const updatedSubThemeNumbers: number[] = [];

labelNameActivity.forEach((activity) => {
const number = activityNumberMapper[activity];
if (number !== undefined && !updatedActivityNumbers.includes(number)) {
updatedActivityNumbers.push(number);
}
});

labelNameSubTheme.forEach((subTheme) => {
const number = subThemeNumberMapper[subTheme];
if (number !== undefined && !updatedSubThemeNumbers.includes(number)) {
updatedSubThemeNumbers.push(number);
}
});

setActivityNumber(updatedActivityNumbers);
setSubThemeNumber(updatedSubThemeNumbers);
const updateFilters = useCallback(() => {
const updatedActivityNumbers = labelNameActivity.map((activity) => activityNumberMapper[activity]).filter(Boolean);
const updatedSubThemeNumbers = labelNameSubTheme.map((subTheme) => subThemeNumberMapper[subTheme]).filter(Boolean);

const newFilters = [];
if (updatedActivityNumbers.length > 0) {
const result: { table: string; column: string; values: number[] }[][] = [[{ table: 'activity', column: 'type', values: [] }]];
result[0][0].values = updatedActivityNumbers;
setFilters(result);
const activityFilter = { table: 'activity', column: 'type', values: updatedActivityNumbers };
newFilters.push([activityFilter]);

if (updatedSubThemeNumbers.length > 0) {
const result = [
[
{ table: 'activity', column: 'type', values: updatedActivityNumbers },
{ table: 'activity', column: 'subType', values: [] },
],
];
updatedSubThemeNumbers.forEach((number) => {
result[0][1].values.push(number);
});
setFilters(result);
const subThemeFilter = { table: 'activity', column: 'subType', values: updatedSubThemeNumbers };
newFilters[0].push(subThemeFilter);
}
}
setFilters(newFilters);
}, [labelNameActivity, labelNameSubTheme, setFilters]);

useEffect(() => {
updateFilters();
}, [labelNameActivity, labelNameSubTheme, updateFilters]);

const handleChangeLabelActivity = (event: SelectChangeEvent<typeof labelNameActivity>) => {
const {
target: { value },
Expand All @@ -84,12 +63,11 @@ export default function FiltersActivities() {
setLabelNameSubTheme([]);
};

const subThemes = labelNameActivity.map((activity) => subThemesMap[activity] || []).flat();
const subThemes = labelNameActivity.flatMap((activity) => subThemesMap[activity] || []);

return (
<>
<div>
{/* Filtre pour activités */}
<FormControl sx={{ m: 1, minWidth: 140 }} size="small">
<Select
displayEmpty
Expand All @@ -105,15 +83,14 @@ export default function FiltersActivities() {
MenuProps={MenuProps}
inputProps={{ 'aria-label': 'Label' }}
>
{activitiesLabel.map((label: string, index: number) => (
{activitiesLabel.map((label, index) => (
<MenuItem key={index} value={label} style={getStyles(label, labelNameActivity, theme)}>
{label}
</MenuItem>
))}
</Select>
</FormControl>
</div>
{/* Filtres pour sous thème d'une activité */}
<div>
<FormControl sx={{ m: 1, width: 140 }} size="small">
<Select
Expand All @@ -134,7 +111,7 @@ export default function FiltersActivities() {
<MenuItem disabled value="">
<em>{subThemes.length ? 'Thèmes' : 'Pas de thématiques'}</em>
</MenuItem>
{subThemes.map((label: string, index: number) => (
{subThemes.map((label, index) => (
<MenuItem key={index} value={label} style={getStyles(label, labelNameSubTheme, theme)}>
{label}
</MenuItem>
Expand Down
38 changes: 14 additions & 24 deletions src/contexts/mediathequeContext.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { FC, Dispatch, SetStateAction } from 'react';
import React, { createContext, useState } from 'react';
import React, { createContext, useState, useMemo } from 'react';

import { useGetMediatheque } from 'src/api/mediatheque/mediatheque.get';
import type { Filter } from 'types/mediatheque.type';
Expand All @@ -10,40 +9,31 @@ type MediathequeProviderProps = {

type MediathequeContextType = {
filters: Array<Filter[]>;
setFilters: Dispatch<SetStateAction<Array<Filter[]>>>;
setOffset: Dispatch<SetStateAction<number>>;
setFilters: React.Dispatch<React.SetStateAction<Array<Filter[]>>>;
allFiltered: [];
};

const MediathequeContext: React.Context<MediathequeContextType> = createContext<MediathequeContextType>({
const MediathequeContext = createContext<MediathequeContextType>({
filters: [],
setFilters: () => {},
setOffset: () => {},
allFiltered: [],
});

export const MediathequeProvider: FC<MediathequeProviderProps> = ({ children }) => {
export const MediathequeProvider: React.FC<MediathequeProviderProps> = ({ children }) => {
const [filters, setFilters] = useState<Array<Filter[]>>([[]]);
const [, setOffset] = useState<number>(0);

const { data: allData } = useGetMediatheque(filters);
console.log('allData : ', allData);

if (!allData) {
return null;
}
return (
<MediathequeContext.Provider
value={{
filters,
setFilters,
setOffset,
allFiltered: allData,
}}
>
{children}
</MediathequeContext.Provider>

const value = useMemo(
() => ({
filters,
setFilters,
allFiltered: allData || [],
}),
[filters, allData],
);

return <MediathequeContext.Provider value={value}>{children}</MediathequeContext.Provider>;
};

export default MediathequeContext;

0 comments on commit fde1efb

Please sign in to comment.