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

[Feature] Descalificar participantes #98

Draft
wants to merge 17 commits into
base: main
Choose a base branch
from
Draft
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
Warnings:

- You are about to drop the column `disqualified` on the `ContestantParticipation` table. All the data in the column will be lost.

*/
-- AlterTable
ALTER TABLE "ContestantParticipation" DROP COLUMN "disqualified";

-- CreateTable
CREATE TABLE "Disqualification" (
"id" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"ofmiId" TEXT NOT NULL,
"reason" TEXT NOT NULL,
"appealed" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,

CONSTRAINT "Disqualification_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "Disqualification_userId_ofmiId_key" ON "Disqualification"("userId", "ofmiId");

-- AddForeignKey
ALTER TABLE "Disqualification" ADD CONSTRAINT "Disqualification_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Disqualification" ADD CONSTRAINT "Disqualification_ofmiId_fkey" FOREIGN KEY ("ofmiId") REFERENCES "Ofmi"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
Warnings:

- You are about to drop the column `ofmiId` on the `Disqualification` table. All the data in the column will be lost.
- You are about to drop the column `userId` on the `Disqualification` table. All the data in the column will be lost.
- A unique constraint covering the columns `[DisqualificationId]` on the table `ContestantParticipation` will be added. If there are existing duplicate values, this will fail.

*/
-- DropForeignKey
ALTER TABLE "Disqualification" DROP CONSTRAINT "Disqualification_ofmiId_fkey";

-- DropForeignKey
ALTER TABLE "Disqualification" DROP CONSTRAINT "Disqualification_userId_fkey";

-- DropIndex
DROP INDEX "Disqualification_userId_ofmiId_key";

-- AlterTable
ALTER TABLE "ContestantParticipation" ADD COLUMN "DisqualificationId" TEXT;

-- AlterTable
ALTER TABLE "Disqualification" DROP COLUMN "ofmiId",
DROP COLUMN "userId";

-- CreateIndex
CREATE UNIQUE INDEX "ContestantParticipation_DisqualificationId_key" ON "ContestantParticipation"("DisqualificationId");

-- AddForeignKey
ALTER TABLE "ContestantParticipation" ADD CONSTRAINT "ContestantParticipation_DisqualificationId_fkey" FOREIGN KEY ("DisqualificationId") REFERENCES "Disqualification"("id") ON DELETE SET NULL ON UPDATE CASCADE;
42 changes: 27 additions & 15 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -150,21 +150,24 @@ model Participation {
}

model ContestantParticipation {
id String @id @default(uuid())
schoolId String
School School @relation(fields: [schoolId], references: [id])
schoolGrade Int
medal String?
place Int?
disqualified Boolean
omegaupUserId String?
omegaupUser OmegaupUser? @relation(fields: [omegaupUserId], references: [id])
problemResults ProblemResult[]
Participation Participation[]
Mentorias Mentoria[]
File File[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
id String @id @default(uuid())
schoolId String
School School @relation(fields: [schoolId], references: [id])
schoolGrade Int
medal String?
place Int?
omegaupUserId String?
omegaupUser OmegaupUser? @relation(fields: [omegaupUserId], references: [id])
problemResults ProblemResult[]
Participation Participation[]
File File[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
Disqualification Disqualification? @relation(fields: [DisqualificationId], references: [id])
DisqualificationId String?
Mentoria Mentoria[]

@@unique([DisqualificationId])
}

model VolunteerParticipation {
Expand Down Expand Up @@ -241,3 +244,12 @@ model OmegaupUser {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

model Disqualification {
id String @id @default(uuid())
reason String
appealed Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
ContestantParticipation ContestantParticipation?
}
1 change: 0 additions & 1 deletion src/components/admin/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,6 @@ export default function Admin(): JSX.Element {
);
}}
>
<option value={""}></option>
{Object.keys(APIS).map((name) => (
<option value={name} key={name}>
{name}
Expand Down
34 changes: 34 additions & 0 deletions src/lib/emailer/baseEmailer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import {
contestantDisqualificationAppealTemplate,
contestantDisqualificationTemplate,
newUserEmailTemplate,
ofmiRegistrationCompleteTemplate,
passwordRecoveryAttemptTemplate,
Expand Down Expand Up @@ -35,4 +37,36 @@ export abstract class BaseEmailer {
public async notifySuccessfulPasswordRecovery(email: string): Promise<void> {
await this.sendEmail(successfulPasswordRecoveryTemplate(email));
}

public async notifyContestantDisqualification(
email: string,
ofmiName: string,
preferredName: string,
reason: string,
): Promise<void> {
await this.sendEmail(
contestantDisqualificationTemplate(
email,
ofmiName,
preferredName,
reason,
),
);
}

public async notifyContestantDisqualificationUpdate(
email: string,
ofmiName: string,
preferredName: string,
appealed: boolean,
): Promise<void> {
await this.sendEmail(
contestantDisqualificationAppealTemplate(
email,
ofmiName,
preferredName,
appealed,
),
);
}
}
51 changes: 51 additions & 0 deletions src/lib/emailer/template.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import config from "@/config/default";
import type { MailOptions } from "nodemailer/lib/json-transport";
import { disqualificationReasons } from "@/types/participation.schema";
import { getSecretOrError } from "../secret";

export const OFMI_EMAIL_SMTP_USER_KEY = "OFMI_EMAIL_SMTP_USER";
Expand Down Expand Up @@ -120,3 +121,53 @@ export const successfulPasswordRecoveryTemplate = (
`,
};
};

export const contestantDisqualificationTemplate = (
email: string,
ofmiName: string,
preferredName: string,
shortReason: string,
aaron-diaz marked this conversation as resolved.
Show resolved Hide resolved
): MailOptions => {
let longReason = shortReason;
if (Object.hasOwn(disqualificationReasons, shortReason)) {
longReason = disqualificationReasons[shortReason];
}
return {
from: getSecretOrError(OFMI_EMAIL_SMTP_USER_KEY),
to: email,
subject: `Descalificación de la ${ofmiName}`,
text: `Descalificación de la ${ofmiName}`,
html: `
<p>Hola, ${preferredName}!</p>
<p>Te informamos que, lamentablemente, has sido descalificada de la ${ofmiName} por el siguiente motivo: </p>
<p>${longReason}.</p>
<p>Si tienes alguna duda, quieres más informacion o te gustaría realizar una apelación, por favor envía un correo a
<a href="mailto:[email protected]">[email protected]</a></p>
<br />
<p>Equipo organizador de la OFMI</p>
`,
};
};

export const contestantDisqualificationAppealTemplate = (
email: string,
ofmiName: string,
preferredName: string,
appealed: boolean,
): MailOptions => {
return {
from: getSecretOrError(OFMI_EMAIL_SMTP_USER_KEY),
to: email,
subject: `(Actualización) Descalificación de la ${ofmiName}`,
text: `(Actualización) Descalificación de la ${ofmiName}`,
html: `
<p>Hola, ${preferredName}!</p>
<p>Te informamos que la apelación a tu descalificación de la ${ofmiName} ha sido ${appealed ? "aceptada" : "rechazada"}.</p>
<p>En otras palabras, hemos ${appealed ? "retractado" : "reafirmado"} nuestra decisión de descalificarte.</p>
<p>Si ${appealed ? "tienes alguna duda" : "te gustaría realizar otra apelación"}, por favor envía un correo a
<a href="mailto:[email protected]">[email protected]</a></p>
<br />
<p>Equipo organizador de la OFMI</p>
`,
};
};
44 changes: 39 additions & 5 deletions src/lib/ofmi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
ParticipationRequestInputSchema,
ParticipationOutputSchema,
UserParticipation,
UserParticipationSchema,
} from "@/types/participation.schema";
import { Pronoun, PronounsOfString } from "@/types/pronouns";
import { ShirtStyle, ShirtStyleOfString } from "@/types/shirt";
Expand All @@ -18,10 +19,19 @@ const caches = {
findMostRecentOfmi: new TTLCache<Ofmi>(),
};

export function friendlyOfmiName(ofmiEdition: number): string {
return `${ofmiEdition}a-ofmi`;
export function friendlyOfmiName(
ofmiEdition: number,
humanReadable = false,
): string {
return `${ofmiEdition}a${humanReadable ? " OFMI" : "-ofmi"}`;
}

export const findOfmiByEdition = async (
edition: number,
): Promise<Ofmi | null> => {
return prisma.ofmi.findFirst({ where: { edition } });
};

export function registrationSpreadsheetsPath(ofmiEdition: number): string {
return path.join(
friendlyOfmiName(ofmiEdition),
Expand Down Expand Up @@ -53,7 +63,7 @@ export async function findParticipants(
ofmi: Ofmi,
): Promise<Array<ParticipationRequestInput>> {
const participants = await prisma.participation.findMany({
where: { ofmiId: ofmi.id },
where: { ofmiId: ofmi.id, volunteerParticipationId: null },
include: {
user: {
include: {
Expand All @@ -66,12 +76,31 @@ export async function findParticipants(
ContestantParticipation: {
include: {
School: true,
Disqualification: {
select: {
appealed: true,
reason: true,
id: true,
},
},
},
},
VolunteerParticipation: true,
},
});

const mappedDisqualifications = new Map<string, string>();

for (const participant of participants) {
let reason = "N/A";
const participation = participant.ContestantParticipation!;
const disqualification = participation.Disqualification;
if (disqualification && !disqualification.appealed) {
reason = disqualification.reason;
}
mappedDisqualifications.set(participant.id, reason);
}

const res = participants.map((participation) => {
// TODO: Share code with findParticipation
const {
Expand All @@ -84,14 +113,16 @@ export async function findParticipants(

const userParticipation: UserParticipation | null =
(role === "CONTESTANT" &&
contestantParticipation && {
contestantParticipation &&
Value.Cast(UserParticipationSchema, {
role,
schoolName: contestantParticipation.School.name,
schoolStage: contestantParticipation.School.stage,
schoolGrade: contestantParticipation.schoolGrade,
schoolCountry: contestantParticipation.School.country,
schoolState: contestantParticipation.School.state,
}) ||
disqualificationReason: mappedDisqualifications.get(user.id),
})) ||
(role === "VOLUNTEER" &&
volunteerParticipation && {
role,
Expand Down Expand Up @@ -138,6 +169,9 @@ export async function findParticipation(
where: { ofmiId: ofmi.id, user: { UserAuth: { email: email } } },
include: {
user: {
select: {
id: true,
},
include: {
MailingAddress: true,
UserAuth: {
Expand Down
Loading