Skip to content

Commit

Permalink
fixing countries WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
Neo-Ryo committed Apr 22, 2024
1 parent 06ac26e commit b67e4d3
Show file tree
Hide file tree
Showing 25 changed files with 161 additions and 85 deletions.
8 changes: 2 additions & 6 deletions server/controllers/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,13 @@ const activityController = new Controller('/activities');
// --- Get all activities. ---
activityController.get({ path: '', userType: UserType.OBSERVATOR }, async (req: Request, res: Response) => {
if (!req.user) throw new AppError('Forbidden', ErrorCode.UNKNOWN);
console.log(req.query);

const activities = await getActivities({
limit: req.query.limit ? Number(getQueryString(req.query.limit)) || 200 : undefined,
page: req.query.page ? Number(getQueryString(req.query.page)) || 0 : undefined,
villageId: req.query.villageId ? Number(getQueryString(req.query.villageId)) || 0 : undefined,
countries:
req.query.countries !== undefined
? req.query.countries.length === 0
? []
: (getQueryString(req.query.countries) || '').split(',')
: undefined,
countries: req.query.countries && req.query.countries.length ? (req.query.countries as string[]).map((e) => Number(e)) : [],
pelico: req.query.pelico ? req.query.pelico !== 'false' : undefined,
type: req.query.type ? (getQueryString(req.query.type) || '').split(',') : undefined,
subType: req.query.subType ? Number(getQueryString(req.query.subType)) || 0 : undefined,
Expand Down
2 changes: 1 addition & 1 deletion server/controllers/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ userController.get({ path: '', userType: UserType.OBSERVATOR }, async (req: Requ
userController.get({ path: '/:id', userType: UserType.TEACHER }, async (req: Request, res: Response, next: NextFunction) => {
const id = parseInt(req.params.id, 10) || 0;

const user = await AppDataSource.getRepository(User).findOne({ where: { id } });
const user = await AppDataSource.getRepository(User).findOne({ where: { id }, relations: { country: true } });
const isSelfProfile = req.user && req.user.id === id;
const isAdmin = req.user && req.user.type <= UserType.ADMIN;
if (user === null || (!isSelfProfile && !isAdmin)) {
Expand Down
4 changes: 2 additions & 2 deletions server/manager/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ type ActivityGetter = {
villageId?: number;
type?: string[];
subType?: number | null;
countries?: string[];
countries?: number[];
pelico?: boolean;
userId?: number;
status?: number;
Expand Down Expand Up @@ -80,7 +80,7 @@ export const getActivities = async ({
} else if (pelico && countries !== undefined && countries.length > 0) {
subQueryBuilder = subQueryBuilder
.innerJoin('activity.user', 'user')
.andWhere('((user.countryCode IN (:countries) AND user.type >= :userType) OR user.type <= :userType2)', {
.andWhere('((user.countryId IN (:countries) AND user.type >= :userType) OR user.type <= :userType2)', {
countries,
userType: UserType.TEACHER,
userType2: UserType.MEDIATOR,
Expand Down
4 changes: 3 additions & 1 deletion server/middlewares/setVillage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ export async function setVillage(req: Request, res: Response, next: NextFunction
villageId = req.cookies?.['village-id'] || -1;
}
if (villageId !== -1 || (user && user.type !== UserType.TEACHER)) {
const villages = await AppDataSource.getRepository(Village).find(villageId !== -1 ? { where: { id: villageId } } : { order: { id: 'ASC' } });
const villages = await AppDataSource.getRepository(Village).find(
villageId !== -1 ? { where: { id: villageId }, relations: { countries: true } } : { order: { id: 'ASC' } },
);
req.village = villages[0];
}
if (villageId === -1 && req.village !== undefined) {
Expand Down
18 changes: 18 additions & 0 deletions src/api/countries/countries.get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useQuery } from 'react-query';
import type { Country } from 'server/entities/country';

import { axiosRequest } from 'src/utils/axiosRequest';

async function getCountries(): Promise<Country[]> {
return (
await axiosRequest({
method: 'GET',
baseURL: '/api',
url: '/countries',
})
).data;
}

export const useGetCountries = () => {
return useQuery(['countries'], () => getCountries());
};
8 changes: 6 additions & 2 deletions src/components/Flag.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React from 'react';
import type { Country } from 'server/entities/country';

import MysteryFlag from 'src/svg/mystery-flag.svg';

Expand All @@ -9,7 +10,7 @@ const sizes = {

interface FlagProps {
isMistery?: boolean;
country?: string;
country?: Country;
size?: 'small' | 'medium';
style?: React.CSSProperties;
}
Expand All @@ -20,6 +21,9 @@ export const Flag = ({ country, isMistery = false, size = 'medium', style = {} }
return (
// Small SVG, no need of improvments
// eslint-disable-next-line @next/next/no-img-element
<img style={{ ...style, width: 'auto', height: sizes[size], borderRadius: '2px' }} src={`/country-flags/${country.toLowerCase()}.svg`}></img>
<img
style={{ ...style, width: 'auto', height: sizes[size], borderRadius: '2px' }}
src={`/country-flags/${country.isoCode.toLowerCase()}.svg`}
></img>
);
};
4 changes: 2 additions & 2 deletions src/components/Navigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ export const Navigation = (): JSX.Element => {
<Flag
style={{ margin: '0.25rem' }}
key={country.isoCode}
country={country.isoCode}
country={country}
isMistery={
!village ||
!user ||
Expand All @@ -272,7 +272,7 @@ export const Navigation = (): JSX.Element => {
<Flag
style={{ margin: '0.25rem' }}
key={country.isoCode}
country={country.isoCode}
country={country}
isMistery={
!village ||
!user ||
Expand Down
2 changes: 1 addition & 1 deletion src/components/WelcomeModal/FirstPhase.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ export const FirstPhase = () => {
<br />
<h2 style={{ fontSize: '1.2rem', margin: '1rem 0' }} className="text--primary">
<span style={{ marginRight: '0.5rem' }}>{user ? user.country?.name : ''}</span>
{user && <Flag country={user.country?.isoCode}></Flag>}
{user && <Flag country={user.country ?? undefined}></Flag>}
</h2>
<Button
color="inherit"
Expand Down
2 changes: 1 addition & 1 deletion src/components/WorldMap/UserPopover.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export const UserPopover = ({ user }: { user: User }) => {
<p style={{ margin: '0 0 0.25rem 0', padding: 0 }} className="text text--small">
{[user.address, user.city, user.country?.name].filter((d) => d && d.length > 0).join(', ')}
</p>
<Flag country={user.country?.isoCode} size="small" style={{ marginLeft: '0.6rem' }} />
<Flag country={user.country ?? undefined} size="small" style={{ marginLeft: '0.6rem' }} />
</div>
)}
</div>
Expand Down
1 change: 1 addition & 0 deletions src/components/WorldMap/world/world.constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export const PELICO_USER: User = {
avatar: '/static-images/pelico-avatar.jpg',
city: '',
country: {
id: -1,
isoCode: 'FR',
name: 'France',
},
Expand Down
18 changes: 14 additions & 4 deletions src/components/accueil/Accueil.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { UserContext } from 'src/contexts/userContext';
import { VillageContext } from 'src/contexts/villageContext';
import { useActivities } from 'src/services/useActivities';
import PelicoReflechit from 'src/svg/pelico/pelico_reflechit.svg';
import type { Country } from 'types/country.type';
import { UserType } from 'types/user.type';

export const Accueil = () => {
Expand All @@ -23,13 +24,22 @@ export const Accueil = () => {
const isMediator = user && user.type <= UserType.MEDIATOR;

//TODO: redo conditions and switchs
const filterCountries: string[] = React.useMemo(() => {
const filterCountries: Country[] = React.useMemo(() => {
// console.log(selectedPhase);
// console.log(village);
// console.log(user);
// console.log(isMediator);
if (!village || (selectedPhase === 1 && !isMediator)) {
return user?.country ? [user?.country] : [];
} else {
return village.countries;
}
// return !village || (selectedPhase === 1 && !isMediator)
// ? user && user.country !== null
// ? [user?.country?.isoCode.toUpperCase()]
// : []
// : village.countries.map((c) => c.isoCode);
return [];
// return [];
}, [selectedPhase, village, user, isMediator]);

//TODO: create a function() that test if you get filteredCountries. create a file with the function .test.ts
Expand All @@ -41,7 +51,7 @@ export const Accueil = () => {
types: 'all',
status: 0,
countries: filterCountries.reduce<{ [key: string]: boolean }>((acc, c) => {
acc[c] = true;
acc[c.isoCode] = true;
return acc;
}, {}),
pelico: true,
Expand All @@ -50,7 +60,7 @@ export const Accueil = () => {
const { activities } = useActivities({
limit: 200,
page: 0,
countries: Object.keys(filters.countries).filter((key) => filters.countries[key]),
countries: filterCountries.map((c) => c.id),
pelico: filters.pelico,
type: filters.types === 'all' ? undefined : filters.types,
phase: selectedPhase,
Expand Down
11 changes: 6 additions & 5 deletions src/components/accueil/Filters/Filters.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React from 'react';
import type { Country } from 'server/entities/country';

import Checkbox from '@mui/material/Checkbox';

Expand Down Expand Up @@ -59,7 +60,7 @@ export type FilterArgs = {
};

interface FiltersProps {
countries?: string[];
countries?: Country[];
filters: FilterArgs;
onChange: React.Dispatch<React.SetStateAction<FilterArgs>>;
phase: number;
Expand All @@ -71,7 +72,7 @@ export const Filters = ({ filters, onChange, countries = [], phase, isMesFamille
onChange((f) => ({
...f,
countries: countries.reduce<{ [key: string]: boolean }>((acc, c) => {
acc[c] = true;
acc[c.isoCode] = true;
return acc;
}, {}),
}));
Expand Down Expand Up @@ -118,17 +119,17 @@ export const Filters = ({ filters, onChange, countries = [], phase, isMesFamille
/> */}
<div style={{ display: 'flex', alignItems: 'center', userSelect: 'none' }}>
{countries.map((c) => (
<label key={c} style={{ display: 'inline-flex', alignItems: 'center', cursor: 'pointer', margin: '0 0.5rem 0 0.2rem' }}>
<label key={c.isoCode} style={{ display: 'inline-flex', alignItems: 'center', cursor: 'pointer', margin: '0 0.5rem 0 0.2rem' }}>
<Checkbox
color="success"
style={{ padding: '0' }}
checked={filters.countries[c] || false}
checked={filters.countries[c.isoCode] || false}
onChange={(event) => {
onChange({
...filters,
countries: {
...filters.countries,
[c]: event.target.checked,
[c.isoCode]: event.target.checked,
},
});
}}
Expand Down
4 changes: 2 additions & 2 deletions src/components/accueil/RightNavigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ export const RightNavigation = ({ activityUser, displayAsUser = false }: { activ
)}
</div>
<span style={{ marginLeft: '0.25rem', display: 'flex' }}>
<Flag country={activityUser.country?.isoCode}></Flag>
<Flag country={activityUser.country ?? undefined}></Flag>
</span>
</div>
{/* MASCOTTE + drapeau à garder */}
Expand Down Expand Up @@ -220,7 +220,7 @@ export const RightNavigation = ({ activityUser, displayAsUser = false }: { activ
}}
>
<div style={{ marginBottom: '1rem' }}>
<Flag country={activityUser.country?.isoCode}></Flag> {activityUser.city}
<Flag country={activityUser.country ?? undefined}></Flag> {activityUser.city}
</div>
{localTime}
{weather && (
Expand Down
2 changes: 1 addition & 1 deletion src/components/activities/ActivityCard/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ export const ActivityCard = ({
<PelicoNeutre style={{ marginLeft: '0.6rem', height: '16px', width: 'auto', cursor: 'pointer' }} />
</Link>
) : (
<Flag country={user?.country?.isoCode} size="small" style={{ marginLeft: '0.6rem' }} />
<Flag country={user.country ?? undefined} size="small" style={{ marginLeft: '0.6rem' }} />
)}
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/components/activities/ActivityComments/CommentCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export const CommentCard = ({ activity, comment, user }: CommentCardProps) => {
{isPelico ? (
<PelicoNeutre style={{ marginLeft: '0.6rem', height: '16px', width: 'auto' }} />
) : (
<Flag country={user?.country?.isoCode} size="small" style={{ marginLeft: '0.6rem' }} />
<Flag country={user?.country ?? undefined} size="small" style={{ marginLeft: '0.6rem' }} />
)}
</p>
)}
Expand Down
2 changes: 1 addition & 1 deletion src/components/activities/ActivityView/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export const ActivityView = ({ activity, user }: ActivityViewProps) => {
{isPelico ? (
<PelicoNeutre style={{ marginLeft: '0.6rem', height: '16px', width: 'auto' }} />
) : (
<Flag country={user?.country?.isoCode} size="small" style={{ marginLeft: '0.6rem' }} />
<Flag country={user.country ?? undefined} size="small" style={{ marginLeft: '0.6rem' }} />
)}
</div>
</div>
Expand Down
5 changes: 3 additions & 2 deletions src/components/activities/GameStats.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ import React, { useMemo } from 'react';

import { AvatarImg } from '../Avatar';
import { Flag } from '../Flag';
import type { Country } from 'types/country.type';
import type { GameResponse } from 'types/gameResponse.type';
import { UserType } from 'types/user.type';
import type { User } from 'types/user.type';

type GameStatsProps = {
gameResponses: GameResponse[];
choices: number[];
country: string;
country?: Country;
userMap: { [key: number]: number };
users: User[];
position: number;
Expand All @@ -22,7 +23,7 @@ const POSITION = [
];
const GameStats = ({ gameResponses, choices, country, userMap, users, position }: GameStatsProps) => {
const countryResponses = useMemo(() => {
return gameResponses.filter((responseGame) => users[userMap[responseGame.userId]]?.country?.isoCode === country);
return gameResponses.filter((responseGame) => users[userMap[responseGame.userId]]?.country?.isoCode === country?.isoCode);
}, [country, gameResponses, userMap, users]);
const responseCount = countryResponses.length;

Expand Down
29 changes: 29 additions & 0 deletions src/contexts/countryContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import type { ReactNode } from 'react';
import React, { useCallback, createContext, useState } from 'react';
import type { Country } from 'server/entities/country';

import { CircularProgress } from '@mui/material';

import { useGetCountries } from 'src/api/countries/countries.get';

interface CountryContextValue {
countries: Country[];
}
export const CountryContext = createContext<CountryContextValue>({
countries: [],
});

interface Props {
children?: ReactNode;
}
export function CountryContextProvider({ children }: Props) {
const [countries, setCountries] = useState<Country[]>([]);
const countriesFetch = useGetCountries();
useCallback(() => {
if (countriesFetch.data) setCountries(countriesFetch.data);
}, [countriesFetch.data]);
if (countriesFetch.isLoading || countriesFetch.isIdle) {
return <CircularProgress />;
}
return <CountryContext.Provider value={{ countries }}>{children}</CountryContext.Provider>;
}
Loading

0 comments on commit b67e4d3

Please sign in to comment.