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

feat: add participant to event #103

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
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
64 changes: 64 additions & 0 deletions components/events/event-participants-table.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { useCallback, useState } from "react";

import Pagination from "react-js-pagination";

import { Participant } from "server/lib/participant/entity";
import ParticipantItem from "./participant-item";
import Button from "@codegouvfr/react-dsfr/Button";
import { getEventParticipantsCSV } from "@/lib/events";

interface EventParticipantTableProps {
eventId: string;
participants: Participant[];
}

const EventParticipantTable = ({
eventId,
participants,
}: EventParticipantTableProps) => {
const downloadFile = (file: string, filename: string) => {
const url = window.URL.createObjectURL(new Blob([file]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", filename);
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
};

const downloadParticipantCsv = async () => {
const file = await getEventParticipantsCSV(eventId);
downloadFile(file, "participant.csv");
};

return (
<div className="fr-table">
<table>
<caption>Liste des participants</caption>
<Button
priority="primary"
onClick={downloadParticipantCsv}
style={{ marginBottom: "12px" }}
>
Liste participants CSV
</Button>
<thead>
<tr>
<th scope="col">Nom/Prénom</th>
<th scope="col">Email</th>
<th scope="col">Commune/Collectivité</th>
<th scope="col">Poste/Fonction</th>
</tr>
</thead>

<tbody>
{participants.map((participant) => (
<ParticipantItem key={participant.id} participant={participant} />
))}
</tbody>
</table>
</div>
);
};

export default EventParticipantTable;
16 changes: 16 additions & 0 deletions components/events/participant-item.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Participant } from "server/lib/participant/entity";

interface ParticipantItemProps {
participant: Participant;
}

const ParticipantItem = ({ participant }: ParticipantItemProps) => (
<tr>
<td className="fr-col fr-my-1v">{participant.fullname}</td>
<td className="fr-col fr-my-1v">{participant.email}</td>
<td className="fr-col fr-my-1v">{participant.community}</td>
<td className="fr-col fr-my-1v">{participant.function}</td>
</tr>
);

export default ParticipantItem;
19 changes: 19 additions & 0 deletions lib/events.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { EventDTO } from "server/lib/events/dto";
import type { Event } from "../server/lib/events/entity";
import { Participant } from "server/lib/participant/entity";

const NEXT_PUBLIC_BAL_ADMIN_URL =
process.env.NEXT_PUBLIC_BAL_ADMIN_URL || "http://localhost:3000";
Expand All @@ -20,6 +21,24 @@ export async function getEvent(id: string): Promise<Event> {
return event as Event;
}

export async function getEventParticipantsCSV(id: string): Promise<any> {
const response = await fetch(
`${NEXT_PUBLIC_BAL_ADMIN_URL}/api/events/${id}/participants.csv`
);
const csvText = await response.text();

return csvText;
}

export async function getEventParticipants(id: string): Promise<Participant[]> {
const response = await fetch(
`${NEXT_PUBLIC_BAL_ADMIN_URL}/api/events/${id}/participants`
);
const participants = await processResponse(response);

return participants as Participant[];
}

export async function getEvents(): Promise<Event[]> {
const url = new URL(`${NEXT_PUBLIC_BAL_ADMIN_URL}/api/events`);

Expand Down
18 changes: 18 additions & 0 deletions migrations/1736951455423-entity_participant_to_event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { MigrationInterface, QueryRunner } from "typeorm";

export class EntityParticipantToEvent1736951455423 implements MigrationInterface {
name = 'EntityParticipantToEvent1736951455423'

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE TABLE "participants" ("id" character varying(24) NOT NULL, "event_id" character varying(24) NOT NULL, "fullname" text NOT NULL, "community" text, "function" text, "email" text NOT NULL, "created_at" TIMESTAMP NOT NULL DEFAULT now(), "updated_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_1cda06c31eec1c95b3365a0283f" PRIMARY KEY ("id"))`);
await queryRunner.query(`CREATE INDEX "IDX_numeros_voie_id" ON "participants" ("event_id") `);
await queryRunner.query(`ALTER TABLE "participants" ADD CONSTRAINT "FK_1f663d2c0e63c2b9794b6b12802" FOREIGN KEY ("event_id") REFERENCES "events"("id") ON DELETE CASCADE ON UPDATE NO ACTION`);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "participants" DROP CONSTRAINT "FK_1f663d2c0e63c2b9794b6b12802"`);
await queryRunner.query(`DROP INDEX "public"."IDX_numeros_voie_id"`);
await queryRunner.query(`DROP TABLE "participants"`);
}

}
14 changes: 14 additions & 0 deletions migrations/1737985572770-event_reminder_send.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { MigrationInterface, QueryRunner } from "typeorm";

export class EventReminderSend1737985572770 implements MigrationInterface {
name = 'EventReminderSend1737985572770'

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "events" ADD "reminder_send" boolean NOT NULL DEFAULT false`);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "events" DROP COLUMN "reminder_send"`);
}

}
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,12 @@
"express": "^4.18.2",
"fuse.js": "6.6.2",
"got": "11.8",
"json-2-csv": "^5.5.8",
"lodash": "^4.17.21",
"next": "^13.5.6",
"next-auth": "^4.24.5",
"next-transpile-modules": "^10.0.1",
"node-cron": "^3.0.3",
"nodemailer": "^6.9.9",
"pg": "^8.13.1",
"prop-types": "^15.8.1",
Expand Down
22 changes: 20 additions & 2 deletions pages/events/[id].tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
import React from "react";
import React, { useEffect, useState } from "react";
import { toast } from "react-toastify";

import { useRouter } from "next/router";
import { Button } from "@codegouvfr/react-dsfr/Button";
import { createModal } from "@codegouvfr/react-dsfr/Modal";

import { EventForm } from "@/components/events/event-form";
import { deleteEvent, getEvent, updateEvent } from "@/lib/events";
import {
deleteEvent,
getEvent,
getEventParticipants,
updateEvent,
} from "@/lib/events";
import { Event } from "../../server/lib/events/entity";
import { EventDTO } from "server/lib/events/dto";
import { Participant } from "server/lib/participant/entity";
import EventParticipantTable from "@/components/events/event-participants-table";

type EventPageProps = {
event: Event;
Expand All @@ -21,6 +28,16 @@ const deleteEventModale = createModal({

const EventPage = ({ event }: EventPageProps) => {
const router = useRouter();
const [participants, setParticipants] = useState<Participant[]>([]);

useEffect(() => {
const loadParticpants = async () => {
const res = await getEventParticipants(event.id);
setParticipants(res);
};

loadParticpants();
}, [event.id]);

const onUpdate = async (formData: EventDTO) => {
try {
Expand Down Expand Up @@ -79,6 +96,7 @@ const EventPage = ({ event }: EventPageProps) => {
</Button>
</div>
</deleteEventModale.Component>
<EventParticipantTable eventId={event.id} participants={participants} />
</div>
);
};
Expand Down
4 changes: 4 additions & 0 deletions server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ dotenv.config();

import { AppDataSource } from "./utils/typeorm-client";
import routeGuard from "./route-guard";
import { cronEvents } from "./lib/events/cron";
// PROXY
import ProxyApiDepot from "./proxy/api-depot.proxy";
import ProxyMoissonneurBal from "./proxy/moissonneur-bal.proxy";
Expand Down Expand Up @@ -64,6 +65,9 @@ async function main() {
await nextAppRequestHandler(req, res);
});

// Start cron events
cronEvents();

server.listen(port, () => {
Logger.info(`Start listening on port ${port}`);
});
Expand Down
48 changes: 48 additions & 0 deletions server/lib/events/controller.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import express from "express";
import cors from "cors";

import { pick } from "lodash";
import { json2csv } from "json-2-csv";
import routeGuard from "../../route-guard";
import * as EventsService from "./service";
import * as ParticipantsService from "./../participant/service";
import { Logger } from "../../utils/logger.utils";
import { Participant } from "../participant/entity";

const eventsRoutes = express.Router();

Expand Down Expand Up @@ -71,4 +75,48 @@ eventsRoutes.delete("/:id", routeGuard, async (req, res) => {
}
});

eventsRoutes.get("/:id/participants.csv", routeGuard, async (req, res) => {
try {
const participants: Participant[] =
await ParticipantsService.findManyByEvent(req.params.id);
const csv = json2csv(
participants.map((p) =>
pick(p, ["fullname", "community", "function", "email"])
)
);
res.header("Content-Type", "text/csv");
res.attachment("participant.csv");
res.send(csv);
} catch (err) {
Logger.error(`Impossible de récupérer les participants`, err);
res.status(500).json({ error: err.message });
}
});

eventsRoutes.get("/:id/participants", routeGuard, async (req, res) => {
try {
const participants = await ParticipantsService.findManyByEvent(
req.params.id
);
res.json(participants);
} catch (err) {
Logger.error(`Impossible de récupérer les participants`, err);
res.status(500).json({ error: err.message });
}
});

eventsRoutes.post("/:id/participants", async (req, res) => {
try {
const event = await EventsService.findOneOrFail(req.params.id);
const participant = await ParticipantsService.createOneByEvent(
event,
req.body
);
res.json(participant);
} catch (err) {
Logger.error(`Impossible de créer un participant`, err);
res.status(500).json({ error: err.message });
}
});

export default eventsRoutes;
29 changes: 29 additions & 0 deletions server/lib/events/cron.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { schedule } from "node-cron";
import * as EventService from "./service";
import { Event } from "./entity";
import { Participant } from "../participant/entity";
import { findManyByEvent } from "../participant/service";
import { sendParticipationEvenement } from "../mailer/service";

async function sendReminderEvents() {
const today = new Date().toISOString().split("T")[0];
const events: Event[] = await EventService.findMany({
date: today,
reminderSend: false,
});
for (const event of events) {
const participants: Participant[] = await findManyByEvent(event.id);
for (const participant of participants) {
await sendParticipationEvenement(event, participant);
}
await EventService.reminderSent(event.id);
}
}

export const cronEvents = () => {
sendReminderEvents();
schedule("0 8 * * *", () => {
// Cette tâche s'exécute tous les jours à 8h00
sendReminderEvents();
});
};
8 changes: 8 additions & 0 deletions server/lib/events/entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ import {
CreateDateColumn,
DeleteDateColumn,
Entity,
OneToMany,
PrimaryColumn,
UpdateDateColumn,
} from "typeorm";
import { Participant } from "../participant/entity";

export enum EventTypeEnum {
FORMATION = "formation",
Expand Down Expand Up @@ -72,6 +74,9 @@ export class Event {
commune?: string;
};

@Column("boolean", { nullable: false, name: "reminder_send", default: false })
reminderSend: boolean;

@Column("text", { nullable: true })
href: string;

Expand All @@ -87,6 +92,9 @@ export class Event {
@Column("text", { nullable: false, name: "end_hour" })
endHour: string;

@OneToMany("Participant", "event")
participants?: Participant[];

@CreateDateColumn({ name: "created_at" })
createdAt?: Date;

Expand Down
16 changes: 14 additions & 2 deletions server/lib/events/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ import { ObjectId } from "bson";
const eventRepository = AppDataSource.getRepository(Event);

export async function findMany(query: any = {}): Promise<Event[]> {
const { type, isSubscriptionClosed } = query;

const { type, isSubscriptionClosed, date, reminderSend } = query;
const where: FindOptionsWhere<Event> = {};

if (type) {
Expand All @@ -20,6 +19,14 @@ export async function findMany(query: any = {}): Promise<Event[]> {
where.isSubscriptionClosed = isSubscriptionClosed;
}

if (date) {
where.date = date;
}

if (reminderSend !== undefined) {
where.reminderSend = reminderSend;
}

return eventRepository.findBy(where);
}

Expand Down Expand Up @@ -55,6 +62,11 @@ export async function updateOne(id: string, payload: EventDTO) {
return findOneOrFail(id);
}

export async function reminderSent(id: string) {
await eventRepository.update({ id }, { reminderSend: true });
return findOneOrFail(id);
}

export async function deleteOne(id: string) {
await eventRepository.delete({ id });
return true;
Expand Down
Loading
Loading