Skip to content

Commit

Permalink
fix(send-mail): add send mail route to ui
Browse files Browse the repository at this point in the history
  • Loading branch information
Mihoub2 committed Sep 30, 2024
1 parent 94b3fd7 commit abc94ae
Show file tree
Hide file tree
Showing 13 changed files with 208 additions and 153 deletions.
75 changes: 19 additions & 56 deletions client/src/api/send-mail/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import {
Col,
} from "@dataesr/dsfr-plus";
import { EmailSenderProps } from "../../types";
import { postHeaders } from "../../config/api";
import { toast } from "react-toastify";
import ProfileModal from "../../components/profil-modal";
import EmailForm from "../../components/mail-form";
import { getCollectionNameFromUrl } from "../utils/collectionName";

function EmailSender({ contribution, refetch }: EmailSenderProps) {
const [, setEmailSent] = useState(false);
Expand All @@ -24,18 +24,9 @@ function EmailSender({ contribution, refetch }: EmailSenderProps) {
);

const isDevelopment = import.meta.env.VITE_HEADER_TAG === "Development";
let basePath = "contacts";
if (window.location.pathname.includes("contributionpage")) {
basePath = "contribute";
} else if (window.location.pathname.includes("apioperations")) {
basePath = "production";
}
const brevoUrl = isDevelopment
? "http://localhost:3000/api/"
: "https://ticket-office.staging.dataesr.ovh/";
const scanRUrl = isDevelopment
? `http://localhost:3000/api${basePath}/${contribution?.id}`
: `https://ticket-office.staging.dataesr.ovh/api/${basePath}/${contribution?.id}`;
const apiBaseUrl = isDevelopment
? "http://localhost:3000/api/send-email"
: "https://ticket-office.staging.dataesr.ovh/api/send-email";

useEffect(() => {
const profileFromLocalStorage = localStorage.getItem("selectedProfile");
Expand All @@ -56,59 +47,31 @@ function EmailSender({ contribution, refetch }: EmailSenderProps) {

const formattedResponse = userResponse.replace(/\n/g, "<br/>");

const dataForBrevo = {
sender: {
email: "scanr@recherche.gouv.fr",
name: `${selectedProfile} de l'équipe scanR`,
},
to: [
{
email: `${contribution.email}`,
name: `${contribution.name}`,
},
],
replyTo: {
email: "scanr@recherche.gouv.fr",
name: "L'équipe scanR",
},
const currentUrl = window.location.href;
const collectionName = getCollectionNameFromUrl(currentUrl);

const emailPayload = {
contributionId: contribution.id,
collectionName: collectionName,
to: contribution.email,
name: contribution.name,
subject: `Réponse à votre contribution, référence ${contribution.id}`,
templateId: 262,
params: {
date: new Date().toLocaleDateString(),
userResponse: formattedResponse,
message: contribution.message,
selectedProfile: selectedProfile,
},
userResponse: formattedResponse,
selectedProfile,
message: contribution.message,
};

try {
const responseBrevo = await fetch(brevoUrl, {
const response = await fetch(apiBaseUrl, {
method: "POST",
headers: {
"api-key": import.meta.env.VITE_BREVO_API_AUTHORIZATION,
"Content-Type": "application/json",
},
body: JSON.stringify(dataForBrevo),
});

if (!responseBrevo.ok) {
throw new Error(`HTTP error! status: ${responseBrevo.status}`);
}

const dataForScanR = {
mailSent: userResponse,
mailSentDate: new Date(),
responseFrom: selectedProfile,
};

const responseScanR = await fetch(scanRUrl, {
method: "PATCH",
headers: postHeaders,
body: JSON.stringify(dataForScanR),
body: JSON.stringify(emailPayload),
});

if (!responseScanR.ok) {
throw new Error(`HTTP error! status: ${responseScanR.status}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

setEmailSent(true);
Expand Down
29 changes: 29 additions & 0 deletions client/src/api/utils/collectionName.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const collectionMapping = [
{
regex: /contact/i,
collectionName: "contacts",
},
{
regex: /contribution/i,
collectionName: "contribute",
},
{
regex: /apioperations/i,
collectionName: "contribute_productions",
},
{
regex: /removeuser/i,
collectionName: "remove-user",
},
{
regex: /namechange/i,
collectionName: "update-user-data",
},
];

export const getCollectionNameFromUrl = (url: string) => {
const mapping = collectionMapping.find(({ regex }) => regex.test(url));
return mapping ? mapping.collectionName : null;
};

export default collectionMapping;
8 changes: 4 additions & 4 deletions client/src/components/contact/contributor-summary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ const ContributorSummary: React.FC<ContributorSummaryProps> = ({

return (
<SideMenu title="Contributeurs" sticky fullHeight>
{contributions.map((contribution) => (
{contributions.map((contribution, index) => (
<SideMenuItem
key={contribution.id}
key={`${contribution.id}-${index}`}
className="contribution-message"
title={
<>
Expand Down Expand Up @@ -56,9 +56,9 @@ const ContributorSummary: React.FC<ContributorSummaryProps> = ({
{contribution?.tags?.length > 0 &&
contribution.tags
.filter((tag) => tag !== "")
.map((tag) => (
.map((tag, key) => (
<Badge
key={tag}
key={key}
size="sm"
color="green-menthe"
className="fr-mr-1w fr-mb-1w"
Expand Down
4 changes: 3 additions & 1 deletion client/src/components/last-mail/lasts-mails-sent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,9 @@ const LatestMails: React.FC<LatestMailsProps> = ({ data }) => {
}}
>
<Text size="xs">
<strong>{mail.threads?.[0]?.team?.join(", ") || "Équipe"}</strong>{" "}
<strong>
{mail.threads?.[0].responses?.[0]?.team?.join(", ") || "Équipe"}
</strong>{" "}
le{" "}
<i>
{new Date(
Expand Down
1 change: 0 additions & 1 deletion client/src/components/mail-form/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Button, Col, Row, TextArea, ButtonGroup } from "@dataesr/dsfr-plus";
import React from "react";

function EmailForm({
userResponse,
Expand Down
3 changes: 3 additions & 0 deletions client/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export interface Contribution {
fonction?: string;
modified_at?: string;
threads?: Thread[];
fromApplication: string;
}
export interface ContributorSummaryProps {
contributions: Contribution[];
Expand Down Expand Up @@ -144,6 +145,7 @@ export type Contribute_Production = {
status: string;
productions: any[];
threads?: Thread[];
fromApplication: string;
};

export type EditModalProps = {
Expand Down Expand Up @@ -197,6 +199,7 @@ interface MailData {
threads: Array<{
team: string[];
responses: Array<{
team: any;
responseMessage: string;
timestamp: string;
}>;
Expand Down
5 changes: 3 additions & 2 deletions server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import contributionObjectRoutes from "./routes/contributionObjectRoutes";
import productionsRoutes from "./routes/productions";
import removeUserRoutes from "./routes/remove-user";
import updateUserDataRoutes from "./routes/update-user-data";
// import replyRoutes from "./routes/reply/replyRoutes";
import contactsRoutes from "./routes/contacts";
import sendMail from "./routes/reply/replyRoutes";
// import connectToImapServer from "./routes/receive-email";

dotenv.config();
Expand Down Expand Up @@ -37,6 +37,7 @@ app
{ name: "Contacts", description: "Gestion des contacts" },
{ name: "Contributions", description: "Gestion des contributions" },
{ name: "Productions", description: "Gestion des productions" },
{ name: "Envoi de mails", description: "Gestion de emails" },
{
name: "Supressions de profil",
description: "Gestion des demandes supression de profil",
Expand All @@ -59,7 +60,7 @@ app
app.use(productionsRoutes);
app.use(removeUserRoutes);
app.use(updateUserDataRoutes);
// app.use(replyRoutes);
app.use(sendMail);
return app;
})
.use(
Expand Down
5 changes: 3 additions & 2 deletions server/routes/contacts/post/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,12 @@ postContactsRoutes.post(
}),
{}
);

const _id = new ObjectId();
const newContribution = {
...body,
_id,
extra: extraLowercase,
id: new ObjectId().toHexString(),
id: _id.toHexString(),
created_at: new Date(),
status: "new",
};
Expand Down
4 changes: 3 additions & 1 deletion server/routes/contributionObjectRoutes/post/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,12 @@ postContributionObjectRoutes.post(
{}
);

const _id = new ObjectId();
const newContribution = {
...body,
_id,
extra: extraLowercase,
id: new ObjectId().toHexString(),
id: _id.toHexString(),
created_at: new Date(),
status: "new",
};
Expand Down
6 changes: 4 additions & 2 deletions server/routes/productions/post/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@ postProductionRoutes.post(
{}
);

const _id = new ObjectId();
const newContribution = {
...body,
id: new ObjectId().toHexString(),
_id,
extra: extraLowercase,
id: _id.toHexString(),
created_at: new Date(),
status: "new",
extra: extraLowercase,
};

const result = await db
Expand Down
6 changes: 4 additions & 2 deletions server/routes/remove-user/post/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@ postRemoveUserRoutes.post(
{}
);

const _id = new ObjectId();
const newContribution = {
...body,
id: new ObjectId().toHexString(),
_id,
extra: extraLowercase,
id: _id.toHexString(),
created_at: new Date(),
status: "new",
extra: extraLowercase,
};

const result = await db
Expand Down
Loading

0 comments on commit abc94ae

Please sign in to comment.