Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fine tune drinking water #510

Merged
merged 1 commit into from
Apr 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions api-node/data/about/drinking_water.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# L’alimentation en eau potable

Le réseau public d’eau potable dessert aujourd’hui la quasi-totalité de la population française, qu’elle habite en milieu urbain ou rural. L’eau du robinet est produite à partir d’eau prélevée par un captage dans une nappe souterraine ou dans une ressource superficielle d’eau douce (fleuves, rivières, canaux, lacs, barrages) ou d’eau de mer. Selon la qualité de l’eau prélevée, différentes étapes de traitement peuvent être nécessaires pour rendre l’eau potable et maintenir sa qualité dans les installations de stockage (réservoirs, châteaux d’eau) et dans les réseaux de distribution, jusqu’au robinet du consommateur.


Expand Down
2 changes: 1 addition & 1 deletion api-node/data/udi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Puis nous traduisons les fichiers .json en .sql : `ogr2ogr -f "PGDump" -t_srs EP
• `udis` est le nom de la table dans notre base de données (pas de uppercase possible)
• `-t_srs EPSG:4326` : pour spécifier le SRID (Spatial Reference Identifier) de la géographie à importer. Ici, 4326 correspond au système de coordonnées WGS 84 (GPS).

Enfin nous enregistrons les données dans notre base de données: `psql "postgresql://recosante:{password}@localhost:5442/recosante" -f bretagne.sql` par exemple
Enfin nous enregistrons les données dans notre base de données: `psql "postgresql://recosante:{password}@localhost:5442/recosante" -f output.sql` par exemple

ATTENTION: certains champs des colonnes `wkb_geometry` ou `code_udi` peuvent être nuls, pensez à les supprimer pour ne pas faire bugger Prisma

Expand Down
2 changes: 1 addition & 1 deletion api-node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"scripts": {
"pre:dev": "npm run prisma-setup && cross-env NODE_ENV=development npx prisma db push && npm run format && npm run ts:check",
"dev": "npm run pre:dev && tsx watch ./src/index.ts",
"dev-cronjobs": "npm run pre:dev && cross-env NODE_ENV=development tsx watch ./src/cronjobs/index.ts",
"dev-cronjobs": "npm run pre:dev && cross-env NODE_ENV=development tsx ./src/cronjobs/index.ts",
"start": "cross-env NODE_ENV=production npm run prisma-setup && npm run prisma-deploy && tsx ./src/index.ts",
"start-cronjobs": "cross-env NODE_ENV=production npm run prisma-setup && npm run prisma-deploy && tsx ./src/cronjobs/index.ts",
"prisma-setup": "prisma generate && prisma migrate deploy",
Expand Down
10 changes: 7 additions & 3 deletions api-node/src/aggregators/drinking_water.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,13 @@ async function getDrinkingWaterIndicator() {
logStep('Getting Drinking Waters');

// Step 1: grab the udis list from the database
const udisRows: Record<'udi', User['udi']>[] =
await prisma.$queryRaw`SELECT DISTINCT udi FROM "User";`;
const udis = udisRows.map((row) => row.udi).filter(Boolean);
const udis = await prisma.udis
.findMany({
select: {
code_udi: true,
},
})
.then((udis) => udis.map((udi) => udi.code_udi).filter(Boolean));

let insertedNewRows = 0;
let alreadyExistingRows = 0;
Expand Down
39 changes: 26 additions & 13 deletions api-node/src/controllers/indicators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,32 @@ import { getIndiceAtmoFromMunicipalityAndDate } from '~/getters/indice_atmo';
import { getPollensFromMunicipalityAndDate } from '~/getters/pollens';
import { getWeatherAlertFromMunicipalityAndDate } from '~/getters/weather_alert';
import { indicatorsList } from '~/getters/indicators_list';
// import { indicatorsMock } from './mocks/indicators';
import { withUser } from '~/middlewares/auth';
import utc from 'dayjs/plugin/utc';
import { getBathingWaterFromMunicipalityAndDate } from '~/getters/bathing_water';
// import { getDrinkingWaterFromUdi } from '~/getters/drinking_water';
import { getDrinkingWaterFromUdi } from '~/getters/drinking_water';
import { IndicatorsSlugEnum } from '@prisma/client';
dayjs.extend(utc);

const router = express.Router();

router.get(
'/list',
catchErrors(async (_req: express.Request, res: express.Response) => {
withUser,
catchErrors(async (req: RequestWithUser, res: express.Response) => {
if (Number(req.user.appbuild) < 62) {
res
.status(200)
.send({
ok: true,
data: indicatorsList.filter(
(list) => list.slug !== IndicatorsSlugEnum.drinking_water,
),
});
return;
}
res.status(200).send({ ok: true, data: indicatorsList });
return;
}),
);

Expand Down Expand Up @@ -99,16 +112,16 @@ router.get(

if (bathingWater) indicators.push(bathingWater);

// const drinkingWater = await getDrinkingWaterFromUdi({
// udi: req.user.udi,
// municipality_insee_code,
// date_UTC_ISO: dayjs().utc().toISOString(),
// });
// if (drinkingWater instanceof Error) {
// next(drinkingWater);
// return;
// }
// if (drinkingWater) indicators.push(drinkingWater);
const drinkingWater = await getDrinkingWaterFromUdi({
udi: req.user.udi,
municipality_insee_code,
date_UTC_ISO: dayjs().utc().toISOString(),
});
if (drinkingWater instanceof Error) {
next(drinkingWater);
return;
}
if (drinkingWater) indicators.push(drinkingWater);

res.status(200).send({ ok: true, data: indicators });
},
Expand Down
6 changes: 3 additions & 3 deletions api-node/src/controllers/udi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { z } from 'zod';
import prisma from '~/prisma';
import { catchErrors } from '../middlewares/errors';
import { type CustomError } from '~/types/error';
import { type udis } from '@prisma/client';
import { type udis as UdiType } from '@prisma/client';

const router = express.Router();

Expand Down Expand Up @@ -43,7 +43,7 @@ router.get(
const longitude = parseFloat(lon as string);
const latitude = parseFloat(lat as string);

const udi: udis = await prisma.$queryRaw`
const udis: Array<UdiType> = await prisma.$queryRaw`
SELECT code_udi
FROM public.udis
WHERE ST_Within(
Expand All @@ -52,7 +52,7 @@ router.get(
);
`;

res.status(200).send({ ok: true, data: udi });
res.status(200).send({ ok: true, data: udis[0] });
},
),
);
Expand Down
26 changes: 26 additions & 0 deletions api-node/src/controllers/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { type CustomError } from '~/types/error';
import { type User } from '@prisma/client';
import { withUser } from '~/middlewares/auth.js';
import type { RequestWithUser } from '~/types/request';
import { type udis as UdiType } from '@prisma/client';
const router = express.Router();

router.post(
Expand Down Expand Up @@ -59,6 +60,12 @@ router.put(
udi: z.string().optional(),
push_notif_token: z.string().optional(),
favorite_indicator: z.string().optional(),
coordinates: z
.object({
lat: z.number(),
lon: z.number(),
})
.optional(),
notification_preference: z.array(z.string()).optional(),
}).parse(req.body);
} catch (zodError) {
Expand Down Expand Up @@ -93,6 +100,25 @@ router.put(
if (bodyHasProperty('udi')) {
updatedUser.udi = req.body.udi;
}
if (bodyHasProperty('coordinates')) {
if (req.body.coordinates.lat && req.body.coordinates.lon) {
const longitude = parseFloat(req.body.coordinates.lon);
const latitude = parseFloat(req.body.coordinates.lat);

const udis: Array<UdiType> = await prisma.$queryRaw`
SELECT code_udi
FROM public.udis
WHERE ST_Within(
ST_SetSRID(ST_MakePoint(${longitude}, ${latitude}), 4326),
wkb_geometry
);
`;

if (udis?.length) {
updatedUser.udi = udis[0].code_udi;
}
}
}
if (bodyHasProperty('push_notif_token')) {
updatedUser.push_notif_token = req.body.push_notif_token;
}
Expand Down
10 changes: 5 additions & 5 deletions api-node/src/getters/drinking_water.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,9 @@ async function getDrinkingWaterFromUdi({
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
recommendations: [drinkingWater.conclusion_conformite_prelevement!],
},
values: ((drinkingWater.all_tests_results ?? []) as Prisma.JsonArray)?.map(
(jsonValue) => {
values: ((drinkingWater.all_tests_results ?? []) as Prisma.JsonArray)
?.filter((_, index) => index < 10)
.map((jsonValue) => {
const test_result =
jsonValue as unknown as ExtendedShortPrelevementResult;
return {
Expand All @@ -99,14 +100,13 @@ async function getDrinkingWaterFromUdi({
bacteriological:
checkPrelevementConformityBacteriological(test_result),
},
drinkingWaterMetadata: {
drinkingWater: {
parameters_count: test_result.parameters_count,
prelevement_code: test_result.code_prelevement,
prelevement_date: test_result.date_prelevement,
},
};
},
),
}),
diffusion_date: dayjs(drinkingWater.diffusion_date).format('YYYY-MM-DD'),
validity_start: dayjs(drinkingWater.diffusion_date).format('YYYY-MM-DD'),
validity_end: 'N/A',
Expand Down
1 change: 0 additions & 1 deletion api-node/src/getters/indicators_list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ const indicatorsObject: Record<IndicatorsSlugEnum, IndicatorItem> = {
slug: IndicatorsSlugEnum.bathing_water,
},
[IndicatorsSlugEnum.drinking_water]: {
active: false,
name: 'Eau du robinet',
long_name: "La qualité de l'eau du robinet",
short_name: 'Eau du robinet',
Expand Down
Loading