Skip to content

Commit

Permalink
fix(mails): add sending mail after contribution received
Browse files Browse the repository at this point in the history
  • Loading branch information
Mihoub2 committed Oct 8, 2024
1 parent dc5a63d commit 36c204e
Show file tree
Hide file tree
Showing 9 changed files with 340 additions and 24 deletions.
20 changes: 20 additions & 0 deletions server/routes/contacts/post/emailRecipents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export const emailRecipients: { [key: string]: { to: string[] } } = {
scanr: {
to: process.env.SCANR_EMAIL_RECIPIENTS?.split(",") || [],
},
paysage: {
to: process.env.PAYSAGE_EMAIL_RECIPIENTS?.split(",") || [],
},
bso: {
to: process.env.BSO_EMAIL_RECIPIENTS?.split(",") || [],
},
"works-magnet": {
to: process.env.WORKS_MAGNET_EMAIL_RECIPIENTS?.split(",") || [],
},
datasupr: {
to: process.env.DATASUPR_EMAIL_RECIPIENTS?.split(",") || [],
},
curiexplore: {
to: process.env.CURIEXPLORE_EMAIL_RECIPIENTS?.split(",") || [],
},
};
66 changes: 60 additions & 6 deletions server/routes/contacts/post/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import db from "../../../libs/mongo";
import { contactSchema } from "../../../schemas/get/contactSchema";
import { errorSchema } from "../../../schemas/errors/errorSchema";
import { ObjectId } from "mongodb";
import { emailRecipients } from "./emailRecipents";

type postContactSchemaType = Static<typeof postContactSchema>;
const postContactsRoutes = new Elysia();

const postContactsRoutes = new Elysia();
postContactsRoutes.post(
"/contacts",
async ({ error, body }: { error: any; body: postContactSchemaType }) => {
Expand All @@ -21,10 +22,10 @@ postContactsRoutes.post(
];

if (!allowedFromApps.includes(body.fromApplication)) {
return error(
400,
"Invalid fromApplication value, check child attributes"
);
return error(400, {
message: "Invalid fromApplication value, check child attributes",
code: "INVALID_FROM_APP",
});
}

const extraLowercase = Object.keys(body.extra || {}).reduce(
Expand All @@ -46,14 +47,66 @@ postContactsRoutes.post(

const result = await db.collection("contacts").insertOne(newContribution);
if (!result.insertedId) {
return error(500, "Failed to create the contribution");
return error(500, {
message: "Failed to create the contribution",
code: "INSERTION_FAILED",
});
}

const finalContribution = {
...newContribution,
id: result.insertedId.toHexString(),
};

const contributionLink = `https://ticket-office.staging.dataesr.ovh/${body.fromApplication}-contact?page=1&query=${finalContribution.id}&searchInMessage=false&sort=DESC&status=choose`;

const BREVO_API_KEY = process.env.BREVO_API_KEY;
if (!BREVO_API_KEY) {
return error(500, {
message: "BREVO_API_KEY is not defined",
code: "MISSING_API_KEY",
});
}

const recipients = emailRecipients[body.fromApplication];
if (!recipients) {
return error(400, {
message: "No email recipients found for this application",
code: "NO_RECIPIENTS_FOUND",
});
}

const dataForBrevo = {
sender: {
email: process.env.MAIL_SENDER,
name: "L'équipe scanR",
},
to: recipients.to.map((email) => ({ email, name: email.split("@")[0] })),
replyTo: { email: "support@scanr.fr", name: "L'équipe scanR" },
subject: "Nouvelle contribution créée",
templateId: 268,
params: {
date: new Date().toLocaleDateString("fr-FR"),
message: `La contribution avec l'ID ${finalContribution.id} a été ajoutée. Vous pouvez consulter la contribution en cliquant sur le lien suivant : ${contributionLink}`,
},
};

const response = await fetch("https://api.brevo.com/v3/smtp/email", {
method: "POST",
headers: {
"Content-Type": "application/json",
"api-key": BREVO_API_KEY,
},
body: JSON.stringify(dataForBrevo),
});

if (!response.ok) {
return error(500, {
message: `Erreur d'envoi d'email: ${response.statusText}`,
code: "EMAIL_SEND_FAILED",
});
}

return finalContribution;
},
{
Expand All @@ -71,4 +124,5 @@ postContactsRoutes.post(
},
}
);

export default postContactsRoutes;
52 changes: 50 additions & 2 deletions server/routes/contributionObjectRoutes/post/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { postContributionObjectSchema } from "../../../schemas/post/contribution
import { errorSchema } from "../../../schemas/errors/errorSchema";
import { contributionObjectSchema } from "../../../schemas/get/contributionsObjectSchema";
import { ObjectId } from "mongodb";
import { emailRecipients } from "../../contacts/post/emailRecipents";

type postContributionObjectSchemaType = Static<
typeof postContributionObjectSchema
Expand Down Expand Up @@ -38,12 +39,12 @@ postContributionObjectRoutes.post(
status: "new",
};

const result = await db.collection("contribute").insertOne(newContribution);

if (!body.objectId && !body.objectType) {
return error(400, "objectId is required when objectType is provided");
}

const result = await db.collection("contribute").insertOne(newContribution);

if (!result.insertedId) {
return error(500, "Failed to create the contribution");
}
Expand All @@ -53,6 +54,53 @@ postContributionObjectRoutes.post(
id: result.insertedId.toHexString(),
};

const contributionLink = `https://ticket-office.staging.dataesr.ovh/scanr-contributionPage?page=1&query=${finalContribution.id}&searchInMessage=false&sort=DESC&status=choose`;

const BREVO_API_KEY = process.env.BREVO_API_KEY;
if (!BREVO_API_KEY) {
return error(500, {
message: "BREVO_API_KEY is not defined",
code: "MISSING_API_KEY",
});
}

const recipients = emailRecipients["contribute"] || {
to: process.env.SCANR_EMAIL_RECIPIENTS?.split(",") || [],
};

const dataForBrevo = {
sender: {
email: process.env.MAIL_SENDER,
name: "L'équipe scanR",
},
to: recipients.to.map((email: string) => ({
email,
name: email.split("@")[0],
})),
replyTo: { email: "support@scanr.fr", name: "L'équipe scanR" },
subject: "Nouvelle contribution par objet créée",
templateId: 268,
params: {
date: new Date().toLocaleDateString("fr-FR"),
message: `La contribution avec l'ID ${finalContribution.id} a été ajoutée. Vous pouvez consulter la contribution en cliquant sur le lien suivant : <a href="${contributionLink}">Consulter la contribution</a>`,
},
};

const response = await fetch("https://api.brevo.com/v3/smtp/email", {
method: "POST",
headers: {
"Content-Type": "application/json",
"api-key": BREVO_API_KEY,
},
body: JSON.stringify(dataForBrevo),
});
if (!response.ok) {
return error(500, {
message: `Erreur d'envoi d'email: ${response.statusText}`,
code: "EMAIL_SEND_FAILED",
});
}

return finalContribution;
},
{
Expand Down
48 changes: 48 additions & 0 deletions server/routes/productions/post/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { postProductionsSchema } from "../../../schemas/post/productionsSchema";
import { productionSchema } from "../../../schemas/get/productionSchema";
import { errorSchema } from "../../../schemas/errors/errorSchema";
import { ObjectId } from "mongodb";
import { emailRecipients } from "../../contacts/post/emailRecipents";

type postProductionSchemaType = Static<typeof postProductionsSchema>;

Expand Down Expand Up @@ -43,6 +44,53 @@ postProductionRoutes.post(
id: result.insertedId.toHexString(),
};

const contributionLink = `https://ticket-office.staging.dataesr.ovh/scanr-apioperations?page=1&query=${finalContribution.id}&searchInMessage=false&sort=DESC&status=choose`;

const BREVO_API_KEY = process.env.BREVO_API_KEY;
if (!BREVO_API_KEY) {
return error(500, {
message: "BREVO_API_KEY is not defined",
code: "MISSING_API_KEY",
});
}

const recipients = emailRecipients["contribute_productions"] || {
to: process.env.SCANR_EMAIL_RECIPIENTS?.split(",") || [],
};

const dataForBrevo = {
sender: {
email: process.env.MAIL_SENDER,
name: "L'équipe scanR",
},
to: recipients.to.map((email: string) => ({
email,
name: email.split("@")[0],
})),
replyTo: { email: "support@scanr.fr", name: "L'équipe scanR" },
subject: "Nouvelle contribution d'affiliation de publication",
templateId: 268,
params: {
date: new Date().toLocaleDateString("fr-FR"),
message: `La contribution avec l'ID ${finalContribution.id} a été ajoutée. Vous pouvez consulter la contribution en cliquant sur le lien suivant : <a href="${contributionLink}">Consulter la contribution</a>`,
},
};

const response = await fetch("https://api.brevo.com/v3/smtp/email", {
method: "POST",
headers: {
"Content-Type": "application/json",
"api-key": BREVO_API_KEY,
},
body: JSON.stringify(dataForBrevo),
});
if (!response.ok) {
return error(500, {
message: `Erreur d'envoi d'email: ${response.statusText}`,
code: "EMAIL_SEND_FAILED",
});
}

return finalContribution;
},
{
Expand Down
75 changes: 62 additions & 13 deletions server/routes/receive-email/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,12 @@ async function updateContribution(
await client.connect();
const database = client.db(dbName);
const collection = database.collection(collectionName);
console.log("Collection:", collectionName);
if (!collection) {
console.log("La collection n'existe pas :", collectionName);
return;
}

const contribution = await collection.findOne({
id: referenceId,
});

const contribution = await collection.findOne({ id: referenceId });
if (contribution) {
const existingThreads = Array.isArray(contribution.threads)
? contribution.threads
Expand Down Expand Up @@ -67,14 +63,21 @@ async function updateContribution(
timestamp: formatDate(timestamp),
};

await collection.updateOne(
const updateResult = await collection.updateOne(
{ _id: contribution._id },
{ $set: { threads: [...existingThreads, response] } }
);
console.log(
"Réponse ajoutée dans les threads pour la contribution:",
referenceId
);

if (updateResult.modifiedCount > 0) {
console.log(
`Contribution mise à jour avec succès pour l'ID de référence: ${referenceId}`
);
await sendNotificationEmail(referenceId, contribution, responseMessage);
} else {
console.log(
`Aucune contribution mise à jour pour l'ID de référence: ${referenceId}`
);
}
} else {
console.log(
"Aucune contribution trouvée pour l'ID de référence",
Expand All @@ -86,6 +89,54 @@ async function updateContribution(
}
}

async function sendNotificationEmail(
referenceId: string,
contribution: any,
responseMessage: string
) {
const recipients = {
to: process.env.SCANR_EMAIL_RECIPIENTS?.split(",") || [],
};
const BREVO_API_KEY = process.env.BREVO_API_KEY;
if (!BREVO_API_KEY) {
throw new Error("BREVO_API_KEY is not defined");
}
const dataForBrevo = {
sender: {
email: process.env.MAIL_SENDER,
name: "L'équipe scanR",
},
to: recipients.to.map((email: string) => ({
email,
name: email.split("@")[0],
})),
replyTo: { email: process.env.MAIL_SENDER, name: "L'équipe scanR" },
subject: "Nouvelle réponse à une contribution",
templateId: 268,
params: {
date: new Date().toLocaleDateString("fr-FR"),
message: `La contribution avec l'ID ${referenceId} a été mise à jour. Vous pouvez consulter la contribution en cliquant sur le lien suivant : URL A VENIR`,
},
};

const response = await fetch("https://api.brevo.com/v3/smtp/email", {
method: "POST",
headers: {
"Content-Type": "application/json",
"api-key": BREVO_API_KEY,
},
body: JSON.stringify(dataForBrevo),
});

if (!response.ok) {
console.error(`Erreur d'envoi d'email: ${response.statusText}`);
} else {
console.log(
`Email envoyé avec succès pour la contribution ID: ${referenceId}`
);
}
}

export async function fetchEmails() {
const client = new ImapFlow({
host: mailHost!,
Expand All @@ -95,6 +146,7 @@ export async function fetchEmails() {
user: email!,
pass: password,
},
logger: false,
});

await client.connect();
Expand Down Expand Up @@ -126,9 +178,6 @@ export async function fetchEmails() {
referenceId = referenceMatch[2];
}

console.log("Collection Prefix:", collectionPrefix);
console.log("Reference ID:", referenceId);

const startMarker = "Content-Transfer-Encoding: quoted-printable";
const endMarker = "Le ";

Expand Down
Loading

0 comments on commit 36c204e

Please sign in to comment.