From 0e25a36568dd4287b370c821ed501f4238b2f46d Mon Sep 17 00:00:00 2001 From: Jonny Date: Sun, 11 Oct 2026 20:29:14 +0200 Subject: [PATCH] feat: SMTP-Konfiguration und Protokoll-Mail (Aufbau und Versand) Co-Authored-By: Claude Opus 5.5 --- .env.example | 12 ++++ docker-compose.yaml | 8 +++ web/lib/notifications/email-config.test.ts | 63 +++++++++++++++++ web/lib/notifications/email-config.ts | 32 +++++++++ web/lib/notifications/email.test.ts | 82 ++++++++++++++++++++++ web/lib/notifications/email.ts | 75 ++++++++++++++++++++ web/package-lock.json | 10 +++ web/package.json | 1 + 8 files changed, 283 insertions(+) create mode 100644 web/lib/notifications/email-config.test.ts create mode 100644 web/lib/notifications/email-config.ts create mode 100644 web/lib/notifications/email.test.ts create mode 100644 web/lib/notifications/email.ts diff --git a/.env.example b/.env.example index 7a5fff8..8757145 100644 --- a/.env.example +++ b/.env.example @@ -39,3 +39,15 @@ WHATSAPP_GRAPH_VERSION= # MUSS mit dem DB-Setting app.notification_dispatch_secret uebereinstimmen # (siehe .claude/skills/rebuild-master-stack/SKILL.md). NOTIFICATION_DISPATCH_SECRET= + +# --- Uebergabeprotokoll per E-Mail (SMTP) --- +# Fehlt SMTP_HOST, SMTP_PORT oder SMTP_FROM, ist der E-Mail-Versand "aus": +# die Protokoll-Zeilen bleiben in der Outbox pending, bis SMTP konfiguriert ist. +# SMTP_SECURE=true fuer TLS ab Verbindungsbeginn (meist Port 465), sonst +# STARTTLS (meist Port 587). SMTP_USER/SMTP_PASSWORD nur zusammen. +SMTP_HOST= +SMTP_PORT=587 +SMTP_SECURE=false +SMTP_USER= +SMTP_PASSWORD= +SMTP_FROM= diff --git a/docker-compose.yaml b/docker-compose.yaml index 81c9e85..330fc51 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -191,3 +191,11 @@ services: WHATSAPP_GRAPH_VERSION: ${WHATSAPP_GRAPH_VERSION} # Muss mit dem DB-Setting app.notification_dispatch_secret uebereinstimmen. NOTIFICATION_DISPATCH_SECRET: ${NOTIFICATION_DISPATCH_SECRET} + # Uebergabeprotokoll per E-Mail -- Werte aus der Root-.env. Fehlt + # SMTP_HOST/SMTP_PORT/SMTP_FROM, bleibt der E-Mail-Versand aus. + SMTP_HOST: ${SMTP_HOST} + SMTP_PORT: ${SMTP_PORT} + SMTP_SECURE: ${SMTP_SECURE} + SMTP_USER: ${SMTP_USER} + SMTP_PASSWORD: ${SMTP_PASSWORD} + SMTP_FROM: ${SMTP_FROM} diff --git a/web/lib/notifications/email-config.test.ts b/web/lib/notifications/email-config.test.ts new file mode 100644 index 0000000..263d81e --- /dev/null +++ b/web/lib/notifications/email-config.test.ts @@ -0,0 +1,63 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { getEmailConfig } from "./email-config"; + +const VARS = ["SMTP_HOST", "SMTP_PORT", "SMTP_FROM", "SMTP_USER", "SMTP_PASSWORD", "SMTP_SECURE"] as const; +let alt: Record = {}; + +beforeEach(() => { + alt = Object.fromEntries(VARS.map((v) => [v, process.env[v]])); + for (const v of VARS) delete process.env[v]; +}); + +afterEach(() => { + for (const v of VARS) { + if (alt[v] === undefined) delete process.env[v]; + else process.env[v] = alt[v]; + } +}); + +function setzePflicht() { + process.env.SMTP_HOST = "smtp.example.de"; + process.env.SMTP_PORT = "587"; + process.env.SMTP_FROM = "Aushilfsfahrer "; +} + +describe("getEmailConfig", () => { + it("liefert die vollstaendige Konfiguration", () => { + setzePflicht(); + process.env.SMTP_USER = "user"; + process.env.SMTP_PASSWORD = "pw"; + process.env.SMTP_SECURE = "true"; + expect(getEmailConfig()).toEqual({ + host: "smtp.example.de", + port: 587, + secure: true, + from: "Aushilfsfahrer ", + auth: { user: "user", pass: "pw" }, + }); + }); + + it("ist null, wenn eine Pflichtvariable fehlt", () => { + setzePflicht(); + delete process.env.SMTP_FROM; + expect(getEmailConfig()).toBeNull(); + }); + + it("ist null bei ungueltigem Port", () => { + setzePflicht(); + process.env.SMTP_PORT = "abc"; + expect(getEmailConfig()).toBeNull(); + }); + + it("ohne Passwort keine Authentifizierung", () => { + setzePflicht(); + process.env.SMTP_USER = "user"; + expect(getEmailConfig()?.auth).toBeNull(); + }); + + it("secure ist false, wenn SMTP_SECURE nicht 'true' ist", () => { + setzePflicht(); + process.env.SMTP_SECURE = "yes"; + expect(getEmailConfig()?.secure).toBe(false); + }); +}); diff --git a/web/lib/notifications/email-config.ts b/web/lib/notifications/email-config.ts new file mode 100644 index 0000000..d783777 --- /dev/null +++ b/web/lib/notifications/email-config.ts @@ -0,0 +1,32 @@ +export type EmailConfig = { + host: string; + port: number; + secure: boolean; + from: string; + auth: { user: string; pass: string } | null; +}; + +// Liest die SMTP-Konfiguration aus den Umgebungsvariablen. null = E-Mail-Kanal +// aus (gleiches Muster wie getWhatsAppConfig): die Outbox-Zeilen bleiben dann +// pending, bis SMTP konfiguriert ist. +export function getEmailConfig(): EmailConfig | null { + const host = process.env.SMTP_HOST; + const portRoh = process.env.SMTP_PORT; + const from = process.env.SMTP_FROM; + if (!host || !portRoh || !from) { + return null; + } + const port = Number(portRoh); + if (!Number.isInteger(port) || port <= 0) { + return null; + } + const user = process.env.SMTP_USER; + const pass = process.env.SMTP_PASSWORD; + return { + host, + port, + secure: process.env.SMTP_SECURE === "true", + from, + auth: user && pass ? { user, pass } : null, + }; +} diff --git a/web/lib/notifications/email.test.ts b/web/lib/notifications/email.test.ts new file mode 100644 index 0000000..217e074 --- /dev/null +++ b/web/lib/notifications/email.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from "vitest"; +import { baueProtokollMail } from "./email"; +import type { Auftrag } from "@/lib/auftraege/queries"; + +function makeAuftrag(overrides: Partial = {}): Auftrag { + return { + id: "a1", + auftragsnummer: "26-09-01-0001", + zeitplanung_typ: "ab_sofort", + zeitplanung_zeitpunkt: null, + status: "abgeschlossen", + abholort: { id: "o1", adresse: "Hauptstr. 1, Musterstadt", ansprechpartner: "Frau Muster", telefon: null, email: null }, + zielort: { id: "o2", adresse: "Nebenweg 2, Musterstadt", ansprechpartner: "Herr Beispiel", telefon: null, email: null }, + fahrzeug: { id: "f1", kennzeichen: "M-AB 123", fin: null, marke: null, modell: null }, + zugewiesen_an: "u1", + start_zeit: "2026-09-01T08:00:00Z", + start_km: 1000, + end_km: 1050, + start_fin: null, + start_fin_status: null, + uebergabe_bestaetigt_at: "2026-09-01T09:00:00Z", + empfaenger_name: "Herr Beispiel", + unterschrift_storage_path: null, + vorgaenger_auftrag_id: null, + created_at: "2026-09-01T07:00:00Z", + erstellt_von: { id: "d1", name: "Dora Dispo" }, + zugewiesen_an_profil: { id: "u1", name: "Max Fahrer" }, + ...overrides, + }; +} + +const PDF = Buffer.from("%PDF-test"); + +describe("baueProtokollMail", () => { + it("setzt Empfaenger, Betreff und Anhang", () => { + const mail = baueProtokollMail({ empfaenger: "dispo@example.de", auftrag: makeAuftrag(), pdf: PDF }); + expect(mail.to).toBe("dispo@example.de"); + expect(mail.subject).toBe("Übergabeprotokoll 26-09-01-0001 – M-AB 123"); + expect(mail.attachments).toEqual([ + { filename: "protokoll-26-09-01-0001.pdf", content: PDF, contentType: "application/pdf" }, + ]); + }); + + it("nutzt die FIN im Betreff, wenn kein Kennzeichen da ist", () => { + const mail = baueProtokollMail({ + empfaenger: "d@example.de", + auftrag: makeAuftrag({ fahrzeug: { id: "f1", kennzeichen: null, fin: "WDB9066331S123456", marke: null, modell: null } }), + pdf: PDF, + }); + expect(mail.subject).toBe("Übergabeprotokoll 26-09-01-0001 – FIN WDB9066331S123456"); + }); + + it("enthaelt die Eckdaten im Text (Uhrzeit Europe/Berlin)", () => { + const { text } = baueProtokollMail({ empfaenger: "d@example.de", auftrag: makeAuftrag(), pdf: PDF }); + expect(text).toContain("Abholort: Hauptstr. 1, Musterstadt"); + expect(text).toContain("Zielort: Nebenweg 2, Musterstadt"); + expect(text).toContain("Fahrzeug: M-AB 123"); + expect(text).toContain("Fahrer: Max Fahrer"); + expect(text).toContain("Übergabe bestätigt: 01.09.2026, 11:00"); + expect(text).toContain("Empfänger: Herr Beispiel"); + expect(text).not.toContain("FIN-Abgleich"); + }); + + it("laesst Empfaenger weg, wenn keiner erfasst ist, und zeigt '-' ohne Fahrer", () => { + const { text } = baueProtokollMail({ + empfaenger: "d@example.de", + auftrag: makeAuftrag({ empfaenger_name: null, zugewiesen_an_profil: null }), + pdf: PDF, + }); + expect(text).not.toContain("Empfänger:"); + expect(text).toContain("Fahrer: -"); + }); + + it("nennt eine FIN-Abweichung", () => { + const { text } = baueProtokollMail({ + empfaenger: "d@example.de", + auftrag: makeAuftrag({ start_fin: "WVWZZZ1KZAW999999", start_fin_status: "abweichend" }), + pdf: PDF, + }); + expect(text).toContain("FIN-Abgleich bei Fahrtbeginn: abweichend – vor Ort: WVWZZZ1KZAW999999"); + }); +}); diff --git a/web/lib/notifications/email.ts b/web/lib/notifications/email.ts new file mode 100644 index 0000000..35319a6 --- /dev/null +++ b/web/lib/notifications/email.ts @@ -0,0 +1,75 @@ +import nodemailer from "nodemailer"; +import type { Auftrag } from "@/lib/auftraege/queries"; +import { finAbgleichText } from "@/lib/auftraege/fin-abgleich"; +import { fahrzeugBezeichnung } from "@/lib/orte-fahrzeuge/fahrzeug-bezeichnung"; +import type { EmailConfig } from "./email-config"; +import type { SendErgebnis } from "./whatsapp"; + +export type ProtokollMail = { + to: string; + subject: string; + text: string; + attachments: { filename: string; content: Buffer; contentType: "application/pdf" }[]; +}; + +const DATUM = new Intl.DateTimeFormat("de-DE", { + dateStyle: "medium", + timeStyle: "short", + timeZone: "Europe/Berlin", +}); + +const TIMEOUT_MS = 10_000; + +export function baueProtokollMail(daten: { empfaenger: string; auftrag: Auftrag; pdf: Buffer }): ProtokollMail { + const { auftrag } = daten; + const fahrzeug = fahrzeugBezeichnung(auftrag.fahrzeug); + const zeilen = [ + "Guten Tag,", + "", + `der Auftrag ${auftrag.auftragsnummer} wurde übergeben. Das Übergabeprotokoll ist als PDF angehängt.`, + "", + `Abholort: ${auftrag.abholort.adresse}`, + `Zielort: ${auftrag.zielort.adresse}`, + `Fahrzeug: ${fahrzeug}`, + `Fahrer: ${auftrag.zugewiesen_an_profil?.name ?? "-"}`, + `Übergabe bestätigt: ${ + auftrag.uebergabe_bestaetigt_at ? DATUM.format(new Date(auftrag.uebergabe_bestaetigt_at)) : "-" + }`, + ]; + if (auftrag.empfaenger_name) { + zeilen.push(`Empfänger: ${auftrag.empfaenger_name}`); + } + if (auftrag.start_fin_status && auftrag.start_fin) { + zeilen.push(`FIN-Abgleich bei Fahrtbeginn: ${finAbgleichText(auftrag.start_fin_status, auftrag.start_fin)}`); + } + zeilen.push("", "Diese E-Mail wurde automatisch versendet."); + + return { + to: daten.empfaenger, + subject: `Übergabeprotokoll ${auftrag.auftragsnummer} – ${fahrzeug}`, + text: zeilen.join("\n"), + attachments: [ + { filename: `protokoll-${auftrag.auftragsnummer}.pdf`, content: daten.pdf, contentType: "application/pdf" }, + ], + }; +} + +export async function sendeProtokollMail(cfg: EmailConfig, mail: ProtokollMail): Promise { + const transport = nodemailer.createTransport({ + host: cfg.host, + port: cfg.port, + secure: cfg.secure, + auth: cfg.auth ?? undefined, + connectionTimeout: TIMEOUT_MS, + greetingTimeout: TIMEOUT_MS, + socketTimeout: 3 * TIMEOUT_MS, + }); + try { + const info = await transport.sendMail({ from: cfg.from, ...mail }); + return { ok: true, messageId: info.messageId }; + } catch (fehler) { + return { ok: false, fehler: fehler instanceof Error ? fehler.message : String(fehler) }; + } finally { + transport.close(); + } +} diff --git a/web/package-lock.json b/web/package-lock.json index 67fc937..0d1047d 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -15,6 +15,7 @@ "@supabase/supabase-js": "^2.110.0", "barcode-detector": "^3.2.2", "next": "16.2.10", + "nodemailer": "10.0.12", "react": "19.2.4", "react-dom": "19.2.4", "sharp": "0.34.5" @@ -6272,6 +6273,15 @@ "node": ">=18" } }, + "node_modules/nodemailer": { + "version": "10.0.12", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.0.12.tgz", + "integrity": "sha512-PQ46oNbNMuH/Sno7B5IWIU9etytwrO0xdTFvWXpIQFRXhBAXtzD48243AS+BCbQQTPD8y3fqUrgLn0tSo77gvg==", + "license": "MIT-0", + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/normalize-svg-path": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/normalize-svg-path/-/normalize-svg-path-1.1.0.tgz", diff --git a/web/package.json b/web/package.json index 0f52175..7c0cf7b 100644 --- a/web/package.json +++ b/web/package.json @@ -19,6 +19,7 @@ "@supabase/supabase-js": "^2.110.0", "barcode-detector": "^3.2.2", "next": "16.2.10", + "nodemailer": "10.0.12", "react": "19.2.4", "react-dom": "19.2.4", "sharp": "0.34.5"