Files
lunch/tests/round-mails.test.ts
kai 8d88e90a07
release / which version (push) Successful in 3s
release / olares chart · sanity (push) Successful in 4s
release / app (push) Successful in 1m2s
release / tag and release (push) Successful in 2s
26.11.53: Mails zur Runde (#55)
2026-11-09 07:38:56 +00:00

135 lines
7.2 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { mkdtempSync, readdirSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import pg from "pg";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { seedHousehold } from "./fixture";
vi.mock("server-only", () => ({}));
vi.mock("next-intl/server", async () => {
const { createTranslator } = await import("next-intl");
const { readFileSync: read } = await import("node:fs");
return {
getTranslations: async ({ locale, namespace }: { locale: string; namespace: string }) =>
createTranslator({ locale, messages: JSON.parse(read(`messages/${locale}.json`, "utf8")), namespace: namespace as never }),
};
});
// Mails zur Runde (26.11.53): wer sie bekommt, wann, höchstens einmal; Frist schließt
// das Wünschen; Abmelde-Link; Bestätigung einer Adresse ohne Sitzung.
const url = process.env.TEST_DATABASE_URL;
describe.skipIf(!url)("round mails", () => {
const client = new pg.Client({ connectionString: url });
const h = randomUUID();
// Eigener Ordner im System-Temp; die Mails landen dort statt beim Mailweg.
const dir = mkdtempSync(path.join(tmpdir(), "rundenmail-"));
const ids: Record<string, string> = {};
let roundId = "";
let db: typeof import("@/lib/db");
let mails: typeof import("@/lib/round-mails");
let wishes: typeof import("@/lib/wishes");
let tokens: typeof import("@/lib/auth/mail-login");
let vault: typeof import("@/lib/vault");
const H = 3600 * 1000;
const deadline = new Date(Date.now() + 72 * H);
const sent = () =>
readdirSync(dir)
.filter((f) => f.endsWith(".json"))
.sort()
.map((f) => JSON.parse(readFileSync(path.join(dir, f), "utf8")) as { to: string; subject: string; html: string; text: string });
const as = <T>(fn: (c: pg.PoolClient) => Promise<T>) => db.withHousehold(h, fn);
beforeAll(async () => {
process.env.DATABASE_URL = url;
process.env.MAIL_TEST_DIR = dir;
process.env.APP_DATA_DIR = path.join(dir, "data");
await client.connect();
const ingredient = (await client.query("select id from ingredients limit 1")).rows[0].id;
ids.kai = (await seedHousehold(client, h, ingredient)).member;
db = await import("@/lib/db");
mails = await import("@/lib/round-mails");
wishes = await import("@/lib/wishes");
tokens = await import("@/lib/auth/mail-login");
vault = await import("@/lib/vault");
await db.withAuth(async (c) => {
if (!(await c.query("select 1 from instance")).rowCount) await c.query("insert into instance (origin, rp_id) values ('https://lunch.example', 'lunch.example')");
});
const key = await vault.seal("re_test");
await as(async (c) => {
await c.query("update household_mail set password_enc = $1", [key]);
await c.query("update members set notify_email = $2, notify_verified_at = now() where id = $1", [ids.kai, `kai-${h}@test.example`]);
const add = async (name: string, role: string, extra: string, params: unknown[]) =>
(
await c.query(
`insert into members (household_id, display_name, role${extra}) values ($1, $2, $3${params.map((_, i) => `, $${i + 4}`).join("")}) returning id`,
[h, name, role, ...params],
)
).rows[0].id as string;
ids.ben = await add("Ben", "child", ", notify_email, notify_verified_at", [`ben-${h}@test.example`, new Date()]);
ids.lea = await add("Lea", "teen", ", notify_email", [`lea-${h}@test.example`]); // nicht bestätigt
ids.max = await add("Max", "member", ", notify_email, notify_verified_at, notify_off", [`max-${h}@test.example`, new Date(), true]);
ids.gast = await add("Gast", "guest", ", notify_email, notify_verified_at", [`gast-${h}@test.example`, new Date()]);
await c.query("update rounds set status = 'done'");
roundId = (await c.query("insert into rounds (household_id, slots_count, default_portions, wish_deadline) values ($1, 3, 4, $2) returning id", [h, deadline])).rows[0].id;
});
});
afterAll(async () => {
await db.pool.end();
await client.end();
});
it("invites confirmed, subscribed people once — not unconfirmed, unsubscribed or guests", async () => {
const got = await mails.sendRoundMails(h, new Date());
expect(got).toEqual([{ kind: "invite", to: [`ben-${h}@test.example`, `kai-${h}@test.example`] }]);
const invite = sent().find((m) => m.to.startsWith("kai-"))!;
expect(invite.subject).toContain("Du entscheidest mit");
expect(invite.html).toMatch(/href="https?:\/\/[^"]+\/wuenschen"/);
expect(invite.html).toMatch(/\/mail\/abmelden#[0-9a-f-]{36}\./);
expect(invite.text).toMatch(/noch 2 Tage 23 Std\./);
expect(await mails.sendRoundMails(h, new Date())).toEqual([]);
});
it("reminds only those who have not wished yet", async () => {
const dish = await as(async (c) => (await c.query("select id from dishes limit 1")).rows[0].id as string);
await as((c) => wishes.addWish(c, h, ids.ben!, dish));
const got = await mails.sendRoundMails(h, new Date(deadline.getTime() - 23 * H));
expect(got).toEqual([{ kind: "remind24", to: [`kai-${h}@test.example`] }]);
expect(await mails.sendRoundMails(h, new Date(deadline.getTime() - 1.5 * H))).toEqual([{ kind: "remind2", to: [`kai-${h}@test.example`] }]);
});
it("closes wishing after the deadline", async () => {
await as((c) => c.query("update rounds set wish_deadline = now() - interval '1 minute' where id = $1", [roundId]));
const dish = await as(async (c) => (await c.query("select id from dishes limit 1")).rows[0].id as string);
await expect(as((c) => wishes.addWish(c, h, ids.kai!, dish))).rejects.toMatchObject({ reason: "closed" });
await expect(as((c) => wishes.removeWish(c, ids.ben!, dish))).rejects.toMatchObject({ reason: "closed" });
});
it("says the plan is ready after approval", async () => {
await as((c) => c.query("update rounds set status = 'planned' where id = $1", [roundId]));
const got = await mails.sendRoundMails(h, new Date());
expect(got[0]).toMatchObject({ kind: "plan" });
expect(sent().some((m) => m.subject.includes("Der Plan steht"))).toBe(true);
});
it("the unsubscribe link carries a check sum that cannot be forged", async () => {
const link = await mails.unsubscribeUrl("https://lunch.example", ids.kai!);
const [member, mac] = link.split("#")[1]!.split(".");
expect(member).toBe(ids.kai);
expect(await vault.macOk(`unsubscribe:${ids.kai}`, mac!)).toBe(true);
expect(await vault.macOk(`unsubscribe:${ids.ben}`, mac!)).toBe(false);
});
it("confirming an address for round mails starts no session", async () => {
const token = await db.withAuth((c) => tokens.createMailToken(c, { householdId: h, memberId: ids.lea!, purpose: "notify", email: `lea-${h}@test.example` }));
const hit = await db.withAuth((c) => tokens.consumeMailToken(c, token));
expect(hit).toMatchObject({ purpose: "notify", memberId: ids.lea });
const lea = await as(async (c) => (await c.query("select notify_verified_at is not null as ok from members where id = $1", [ids.lea])).rows[0].ok);
expect(lea).toBe(true);
const sessions = await as(async (c) => (await c.query("select count(*)::int as n from sessions where member_id = $1", [ids.lea])).rows[0].n);
expect(sessions).toBe(0);
});
});