96 lines
2.6 KiB
TypeScript
96 lines
2.6 KiB
TypeScript
import "dotenv/config";
|
||
|
||
import { db } from "../src/db";
|
||
import * as schema from "../src/schema";
|
||
import { getEntry, getCollection } from "astro:content";
|
||
import { mailClient } from "../src/mail";
|
||
import { setTimeout } from "node:timers/promises";
|
||
import { and, eq } from "drizzle-orm";
|
||
|
||
export const prerender = false;
|
||
|
||
const MAIL_FROM = process.env.MAIL_FROM || "vig@re-set.cz";
|
||
|
||
const variantIds: Record<string, string> = {
|
||
"1": "oil-gas-policy",
|
||
"2": "coal-policy",
|
||
"3": "neptun-deep",
|
||
};
|
||
|
||
const variants = await getCollection("variants");
|
||
|
||
export function getSubject(lang: string, variantNr: string) {
|
||
const variant = variants.find((v) => v.slug === `${lang}/${variantIds[variantNr]}`);
|
||
if (!variant) {
|
||
throw new Error("No variant");
|
||
}
|
||
return `VIG – ${variant.data.title}`;
|
||
}
|
||
|
||
async function processLetters() {
|
||
const letters = await db.select().from(schema.letters).where(eq(schema.letters.confirmed, true));
|
||
|
||
for (const letter of letters) {
|
||
const branch = await getEntry("branches", letter.branch as string);
|
||
const subject = getSubject(
|
||
letter.branch === "vig-holding" ? "en" : letter.lang,
|
||
letter.variant
|
||
);
|
||
console.log("Subject", subject);
|
||
|
||
if (!branch) {
|
||
console.error("No branch", letter.branch);
|
||
continue;
|
||
}
|
||
|
||
for (const recipientEmail of branch.data.emails) {
|
||
const [message] = await db
|
||
.insert(schema.messages)
|
||
.values({
|
||
letterId: letter.id,
|
||
from: letter.email,
|
||
to: recipientEmail,
|
||
status: "pending",
|
||
})
|
||
.returning({ id: schema.messages.id });
|
||
|
||
if (!message) {
|
||
console.error("Error creating message");
|
||
continue;
|
||
}
|
||
|
||
const name = `${letter.firstName} ${letter.lastName}`;
|
||
const messageText =
|
||
letter.lang === "hu"
|
||
? letter.message.replace("Tisztelt Hölgyem,", "Tisztelt Hölgyem/Uram,")
|
||
: letter.message;
|
||
|
||
try {
|
||
const values = {
|
||
subject,
|
||
from: `${name} <${MAIL_FROM}>`,
|
||
to: [recipientEmail],
|
||
replyTo: `${name} <${letter.email}>`,
|
||
plainBody: messageText,
|
||
};
|
||
const result = await mailClient.send(values);
|
||
console.log(result);
|
||
|
||
await db
|
||
.update(schema.messages)
|
||
.set({ status: "success" })
|
||
.where(eq(schema.messages.id, message.id));
|
||
} catch (error) {
|
||
console.log(error);
|
||
await db
|
||
.update(schema.messages)
|
||
.set({ status: "error" })
|
||
.where(eq(schema.messages.id, message.id));
|
||
}
|
||
|
||
await setTimeout(2000);
|
||
}
|
||
}
|
||
}
|
||
|
||
await processLetters();
|