Skip to content

Commit

Permalink
fix(imap): fix imap server
Browse files Browse the repository at this point in the history
  • Loading branch information
Mihoub2 committed Oct 23, 2024
1 parent 216df8f commit fe30737
Show file tree
Hide file tree
Showing 7 changed files with 87 additions and 70 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ created a .env.local (ask me mine)
--you might have issues with imap server if you start localy (especialy on work wifi), if needed, disable the function called : "fetchEmails"

--you also might have issues if you install a new dependencie, check if all dependencies are in package.json (especially in server)
if you have and 503 issue, check error on pod
--`kubectl get pods -n ticket-office`
--`kubectl logs ticket-office-xxxxxxx-yyyyyy -n ticket-office`

# Links

Expand Down
Binary file modified bun.lockb
Binary file not shown.
4 changes: 3 additions & 1 deletion client/src/components/items/staff-action.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,9 @@ const StaffActions = ({
<br />
<small>
Répondu le {responseDate} à {responseTime} par{" "}
{response.team}
{response.team.includes("user")
? data.name || response.team
: response.team}
</small>
</Text>
</div>
Expand Down
7 changes: 7 additions & 0 deletions client/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,11 @@ export default defineConfig({
},
},
},
css: {
preprocessorOptions: {
scss: {
api: "modern",
},
},
},
});
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,8 @@
"start:server": "cd server && bun run --watch server.ts",
"start": "concurrently \"npm run start:client\" \"bun run start:server\"",
"deploy": "git switch main && git pull origin main --rebase --tags && git merge origin/staging && npm version $npm_config_level && git push origin main --tags && git switch staging"
},
"dependencies": {
"concurrently": "^9.0.1"
}
}
1 change: 1 addition & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"@types/imap": "^0.8.40",
"@types/imap-simple": "^4.2.9",
"@types/imapflow": "^1.0.19",
"@types/mailparser": "^3.4.5",
"@types/mongodb": "^4.0.7",
"cheerio": "^1.0.0",
"dotenv": "^16.4.5",
Expand Down
139 changes: 70 additions & 69 deletions server/routes/receive-email/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ function formatDate(dateString: string | number | Date | null) {
const date = new Date(dateString || "");
return date.toISOString();
}

async function updateContribution(
referenceId: string,
responseMessage: string,
Expand All @@ -34,54 +33,52 @@ async function updateContribution(
const collection = database.collection(collectionName);

const contribution = await collection.findOne({ id: referenceId });
if (!contribution) {
console.log(
`Aucune contribution trouvée pour l'ID de référence: ${referenceId}`
if (contribution) {
const existingThreads = Array.isArray(contribution.threads)
? contribution.threads
: [];

const isDuplicate = existingThreads.some(
(thread) =>
thread.timestamp === formatDate(timestamp) &&
thread.responses.some(
(response: { responseMessage: string }) =>
response.responseMessage === responseMessage
)
);
return;
}

const existingThreads = Array.isArray(contribution.threads)
? contribution.threads
: [];

const isDuplicate = existingThreads.some(
(thread) => thread.timestamp === formatDate(timestamp)
);

if (isDuplicate) {
console.log(
`Thread déjà existant pour la date: ${timestamp}, annulation.`
if (isDuplicate) {
console.log(
"Un thread avec la même date et réponse existe déjà, mise à jour annulée pour la contribution:",
referenceId
);
return;
}

const response = {
threadId: contribution._id.toString(),
responses: [
{
responseMessage,
read: false,
timestamp: formatDate(timestamp),
team: ["user"],
},
],
timestamp: formatDate(timestamp),
};

const updateResult = await collection.updateOne(
{ _id: contribution._id },
{ $set: { threads: [...existingThreads, response] } }
);
return;
}

const response = {
threadId: contribution._id.toString(),
responses: [
{
responseMessage,
read: false,
timestamp: formatDate(timestamp),
team: ["user"],
},
],
timestamp: formatDate(timestamp),
};

const updateResult = await collection.updateOne(
{ _id: contribution._id },
{ $set: { threads: [...existingThreads, response] } }
);

if (updateResult.modifiedCount > 0) {
console.log(`Mise à jour réussie pour l'ID de référence: ${referenceId}`);
await sendNotificationEmail(
referenceId,
contribution,
responseMessage,
collectionName
);
if (updateResult.modifiedCount > 0) {
console.log(
`Mise à jour réussie pour l'ID de référence: ${referenceId}`
);
await sendNotificationEmail(referenceId, contribution, collectionName);
}
} else {
console.log(`Aucune mise à jour pour l'ID: ${referenceId}`);
}
Expand All @@ -93,7 +90,6 @@ async function updateContribution(
async function sendNotificationEmail(
referenceId: string,
contribution: any,
responseMessage: string,
collectionName: string
) {
const recipients = process.env.SCANR_EMAIL_RECIPIENTS?.split(",") || [];
Expand Down Expand Up @@ -124,7 +120,6 @@ async function sendNotificationEmail(
url: contributionLink,
},
};

const response = await fetch("https://api.brevo.com/v3/smtp/email", {
method: "POST",
headers: {
Expand Down Expand Up @@ -227,28 +222,34 @@ export async function fetchEmails() {
});

for await (let message of messages) {
if (!message.envelope || !message.source) continue;

const messageSource = message.source.toString();
const date = formatDate(message.envelope.date?.toISOString() || null);
const subject = message.envelope.subject || "";

const referenceMatch = subject.match(
/référence\s+([a-zA-Z0-9_-]+)-([a-zA-Z0-9]+)/
);
let referenceId = referenceMatch ? referenceMatch[2] : null;
let collectionPrefix = referenceMatch ? referenceMatch[1] : "contacts";

const extractedContent = await processEmailContent(messageSource);
if (!extractedContent) continue;

const collectionName = determineCollectionName(collectionPrefix);
await updateContribution(
referenceId!,
extractedContent,
date,
collectionName
);
try {
if (!message.envelope || !message.source) continue;

const messageSource = message.source.toString();
const date = formatDate(message.envelope.date?.toISOString() || null);
const subject = message.envelope.subject || "";

const referenceMatch = subject.match(
/référence\s+([a-zA-Z0-9_-]+)-([a-zA-Z0-9]+)/
);
let referenceId = referenceMatch ? referenceMatch[2] : null;
let collectionPrefix = referenceMatch ? referenceMatch[1] : "contacts";

const extractedContent = await processEmailContent(messageSource);
if (!extractedContent) continue;

const collectionName = determineCollectionName(collectionPrefix);

await updateContribution(
referenceId!,
extractedContent,
date,
collectionName
);
} catch (err) {
console.error(`Erreur lors du traitement de l'email : ${err}`);
continue;
}
}
} finally {
lock.release();
Expand Down

0 comments on commit fe30737

Please sign in to comment.