forked from fahrPool/fahrPool
1468 lines
60 KiB
Markdown
1468 lines
60 KiB
Markdown
# Übergabeprotokoll per E-Mail Implementation Plan
|
||
|
||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||
|
||
**Goal:** Wird ein Auftrag abgeschlossen, geht das Übergabeprotokoll (PDF, Fotos verkleinert) automatisch per SMTP an die E-Mail-Adresse des Erstellers — über die vorhandene `notification_outbox` mit Retry.
|
||
|
||
**Architecture:** Ein DB-Trigger legt beim Wechsel auf `abgeschlossen` eine Outbox-Zeile `protokoll_abgeschlossen` an. Die Dispatch-Verarbeitung wird von „nur WhatsApp" auf eine Handler-Tabelle je `event_type` umgebaut und claimt nur Ereignis-Arten, deren Kanal konfiguriert ist. Die PDF-Erzeugung wird aus der Download-Route in eine gemeinsame Funktion gezogen, die Fotos mit `sharp` verkleinert und von Route (Nutzer-Client) und Mail-Handler (Admin-Client) genutzt wird.
|
||
|
||
**Tech Stack:** Next.js 16 (App Router), Supabase (Postgres, pgTAP, pg_cron), Vitest, `@react-pdf/renderer`, `sharp@0.34.5` (bereits transitiv über Next im Lockfile), `nodemailer@10.0.12` (bringt eigene Typen mit).
|
||
|
||
**Spec:** `docs/superpowers/specs/2026-10-11-protokoll-email-design.md`
|
||
|
||
## Global Constraints
|
||
|
||
- Arbeit im Worktree `.claude/worktrees/protokoll-email/`, Branch `feature/protokoll-email`.
|
||
- Supabase-CLI-Befehle vom Worktree-Root; Frontend-Befehle aus `web/` (`npm test`, `npx tsc --noEmit`, `npm run lint`).
|
||
- Ereignis-Art exakt: `protokoll_abgeschlossen` (bestehend: `auftrag_erstellt`).
|
||
- Empfänger: nur `auth.users.email` des Erstellers (`auftraege.erstellt_von`), festgehalten im Payload-Feld `empfaenger`.
|
||
- SMTP-Variablen exakt: `SMTP_HOST`, `SMTP_PORT`, `SMTP_FROM` (Pflicht), `SMTP_USER`, `SMTP_PASSWORD`, `SMTP_SECURE` (optional).
|
||
- Fotos fürs PDF: längste Kante max. 1600 px, kein Hochskalieren, JPEG-Qualität 80, EXIF-Orientierung anwenden; Fehler → Original verwenden. Unterschrift unverändert.
|
||
- Betreff exakt: `Übergabeprotokoll <Auftragsnummer> – <fahrzeugBezeichnung>`; Anhang `protokoll-<Auftragsnummer>.pdf`.
|
||
- Datumsformat in der Mail: `Intl.DateTimeFormat("de-DE", { dateStyle: "medium", timeStyle: "short", timeZone: "Europe/Berlin" })`.
|
||
- Prozess-Regel: Niemals Prozesse beenden, die man nicht selbst gestartet hat (kein `taskkill /IM node.exe`); eigene Server per PID stoppen.
|
||
- Commit-Messages enden mit `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.
|
||
|
||
## Review Focus
|
||
|
||
- E-Mail-Kanal konfiguriert, WhatsApp nicht → Protokoll-Mails gehen trotzdem raus (heute bricht die Route ohne WhatsApp ab) (Task 4, Route-Test).
|
||
- Kein Kanal für eine vorhandene Zeile konfiguriert → Zeile bleibt `pending`, wird nicht auf `dead` gesetzt (Task 1 pgTAP `claim` filtert; Task 4 Test „claimt nur aktive Arten").
|
||
- Auftrag wird nach Abschluss erneut aktualisiert (z. B. Admin korrigiert ein Feld) → keine zweite Mail (Task 1 pgTAP).
|
||
- Großes Handyfoto (z. B. 4000×3000) → PDF enthält verkleinertes Bild; kaputte Bilddaten → kein Abbruch (Task 2 Tests).
|
||
- SMTP-Server nicht erreichbar → Zeile `failed` mit Backoff, Fahrer merkt nichts (Task 4 Test über Handler-Ergebnis; Live-Test Task 5 mit gestopptem Mailpit optional).
|
||
|
||
---
|
||
|
||
### Task 0: Worktree anlegen
|
||
|
||
- [ ] **Step 1:** Vom Haupt-Checkout:
|
||
|
||
```bash
|
||
git worktree add .claude/worktrees/protokoll-email -b feature/protokoll-email master
|
||
cd .claude/worktrees/protokoll-email/web && npm install
|
||
cp ../../../../web/.env.local .env.local
|
||
```
|
||
|
||
- [ ] **Step 2:** Baseline: `cd web && npm test && npx tsc --noEmit` → grün.
|
||
|
||
---
|
||
|
||
### Task 1: Datenbank — Enqueue-Trigger und Claim nach Ereignis-Art
|
||
|
||
**Files:**
|
||
- Create: `supabase/migrations/20261011090000_protokoll_email.sql`
|
||
- Create: `supabase/tests/protokoll_email_test.sql`
|
||
- Modify: `supabase/tests/notification_outbox_rls_test.sql` (Aufrufe von `claim_notification_batch`)
|
||
|
||
**Interfaces:**
|
||
- Produces: `public.claim_notification_batch(p_limit int, p_event_types text[]) returns setof public.notification_outbox` (nur `service_role`); Outbox-Zeilen `event_type = 'protokoll_abgeschlossen'`, `payload = {"auftragsnummer": text, "empfaenger": text}`.
|
||
|
||
- [ ] **Step 1: pgTAP-Test schreiben**
|
||
|
||
`supabase/tests/protokoll_email_test.sql`:
|
||
|
||
```sql
|
||
begin;
|
||
select plan(7);
|
||
|
||
insert into auth.users (id, email) values
|
||
('e5a00000-0000-0000-0000-000000000001', 'dispo-mail@test.local'),
|
||
('e5a00000-0000-0000-0000-000000000002', null);
|
||
|
||
update public.profiles set role = 'disponent' where id = 'e5a00000-0000-0000-0000-000000000001';
|
||
update public.profiles set role = 'disponent' where id = 'e5a00000-0000-0000-0000-000000000002';
|
||
|
||
insert into public.orte (id, adresse, ansprechpartner) values
|
||
('e5b00000-0000-0000-0000-000000000001', 'Hauptstr. 1, Musterstadt', 'Frau Muster'),
|
||
('e5b00000-0000-0000-0000-000000000002', 'Nebenweg 2, Musterstadt', 'Herr Beispiel');
|
||
|
||
insert into public.fahrzeuge (id, kennzeichen) values
|
||
('e5c00000-0000-0000-0000-000000000001', 'M-ML 001');
|
||
|
||
-- A: Ersteller mit E-Mail, unterwegs
|
||
-- B: Ersteller ohne E-Mail, unterwegs
|
||
-- C: Ersteller mit E-Mail, zugewiesen (wird nur storniert)
|
||
insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, start_km) values
|
||
('e5d00000-0000-0000-0000-00000000000a', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000001', 'unterwegs', 100),
|
||
('e5d00000-0000-0000-0000-00000000000b', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000002', 'unterwegs', 100),
|
||
('e5d00000-0000-0000-0000-00000000000c', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000001', 'zugewiesen', null);
|
||
|
||
-- 1) Abschluss legt genau eine Zeile an
|
||
update public.auftraege
|
||
set status = 'abgeschlossen', end_km = 150, uebergabe_bestaetigt_at = now()
|
||
where id = 'e5d00000-0000-0000-0000-00000000000a';
|
||
|
||
select is(
|
||
(select count(*)::int from public.notification_outbox
|
||
where auftrag_id = 'e5d00000-0000-0000-0000-00000000000a' and event_type = 'protokoll_abgeschlossen'),
|
||
1,
|
||
'Abschluss legt genau eine protokoll_abgeschlossen-Zeile an'
|
||
);
|
||
|
||
-- 2) Empfaenger und Auftragsnummer im Payload
|
||
select is(
|
||
(select payload->>'empfaenger' from public.notification_outbox
|
||
where auftrag_id = 'e5d00000-0000-0000-0000-00000000000a' and event_type = 'protokoll_abgeschlossen'),
|
||
'dispo-mail@test.local',
|
||
'payload.empfaenger ist die E-Mail des Erstellers'
|
||
);
|
||
|
||
select is(
|
||
(select payload->>'auftragsnummer' from public.notification_outbox
|
||
where auftrag_id = 'e5d00000-0000-0000-0000-00000000000a' and event_type = 'protokoll_abgeschlossen'),
|
||
(select auftragsnummer from public.auftraege where id = 'e5d00000-0000-0000-0000-00000000000a'),
|
||
'payload.auftragsnummer ist die Auftragsnummer'
|
||
);
|
||
|
||
-- 3) Erneutes Update eines abgeschlossenen Auftrags -> keine zweite Zeile
|
||
update public.auftraege set empfaenger_name = 'Herr Beispiel'
|
||
where id = 'e5d00000-0000-0000-0000-00000000000a';
|
||
|
||
select is(
|
||
(select count(*)::int from public.notification_outbox
|
||
where auftrag_id = 'e5d00000-0000-0000-0000-00000000000a' and event_type = 'protokoll_abgeschlossen'),
|
||
1,
|
||
'Update eines bereits abgeschlossenen Auftrags legt keine weitere Zeile an'
|
||
);
|
||
|
||
-- 4) Ersteller ohne E-Mail -> keine Zeile
|
||
update public.auftraege
|
||
set status = 'abgeschlossen', end_km = 150, uebergabe_bestaetigt_at = now()
|
||
where id = 'e5d00000-0000-0000-0000-00000000000b';
|
||
|
||
select is(
|
||
(select count(*)::int from public.notification_outbox
|
||
where auftrag_id = 'e5d00000-0000-0000-0000-00000000000b' and event_type = 'protokoll_abgeschlossen'),
|
||
0,
|
||
'Ersteller ohne E-Mail: keine Zeile'
|
||
);
|
||
|
||
-- 5) Anderer Statuswechsel (storniert) -> keine Zeile
|
||
update public.auftraege set status = 'storniert'
|
||
where id = 'e5d00000-0000-0000-0000-00000000000c';
|
||
|
||
select is(
|
||
(select count(*)::int from public.notification_outbox
|
||
where auftrag_id = 'e5d00000-0000-0000-0000-00000000000c' and event_type = 'protokoll_abgeschlossen'),
|
||
0,
|
||
'Stornierung legt keine protokoll_abgeschlossen-Zeile an'
|
||
);
|
||
|
||
-- 6) claim_notification_batch claimt nur die angefragten Ereignis-Arten
|
||
delete from public.notification_outbox;
|
||
insert into public.notification_outbox (id, event_type, status, payload, naechster_versuch_ab) values
|
||
('e5e00000-0000-0000-0000-000000000001', 'auftrag_erstellt', 'pending', '{}'::jsonb, now() - interval '1 minute'),
|
||
('e5e00000-0000-0000-0000-000000000002', 'protokoll_abgeschlossen', 'pending', '{}'::jsonb, now() - interval '1 minute');
|
||
|
||
select results_eq(
|
||
$$ select id::text from public.claim_notification_batch(10, array['protokoll_abgeschlossen']) $$,
|
||
$$ values ('e5e00000-0000-0000-0000-000000000002'::text) $$,
|
||
'claim_notification_batch claimt nur protokoll_abgeschlossen, auftrag_erstellt bleibt pending'
|
||
);
|
||
|
||
select * from finish();
|
||
rollback;
|
||
```
|
||
|
||
Hinweis zum Test: Die Aufträge werden als `postgres` (ohne JWT) aktualisiert; `check_auftrag_status_transition` lässt das zu, weil `user_role()` dann `null` ist und die Statusübergänge `unterwegs → abgeschlossen` (mit `end_km`, `uebergabe_bestaetigt_at`) bzw. `zugewiesen → storniert` gültig sind. Falls die Stornierung als `postgres` am Trigger scheitert (`Nur Disponent/Admin duerfen einen Auftrag stornieren`, weil `null not in (...)` nicht greift — prüfen!), Test 5 stattdessen mit `set local role authenticated` + JWT des Disponenten `e5a…0001` ausführen und danach `reset role`.
|
||
|
||
- [ ] **Step 2: Bestehenden Test anpassen**
|
||
|
||
In `supabase/tests/notification_outbox_rls_test.sql` beide Aufrufe ändern:
|
||
- `$$ select public.claim_notification_batch(5) $$` → `$$ select public.claim_notification_batch(5, array['auftrag_erstellt']) $$`
|
||
- `$$ select id::text from public.claim_notification_batch(10) order by id $$` → `$$ select id::text from public.claim_notification_batch(10, array['auftrag_erstellt']) order by id $$`
|
||
|
||
- [ ] **Step 3: RED**
|
||
|
||
Vom Worktree-Root: `npx supabase db reset && npx supabase test db` → `protokoll_email_test.sql` und `notification_outbox_rls_test.sql` FAIL (Funktion mit zwei Argumenten existiert nicht).
|
||
|
||
- [ ] **Step 4: Migration schreiben**
|
||
|
||
`supabase/migrations/20261011090000_protokoll_email.sql`:
|
||
|
||
```sql
|
||
-- Uebergabeprotokoll per E-Mail an den Ersteller des Auftrags.
|
||
-- Spec: docs/superpowers/specs/2026-10-11-protokoll-email-design.md
|
||
|
||
-- Enqueue beim Wechsel auf 'abgeschlossen'. Die E-Mail wird zum
|
||
-- Abschlusszeitpunkt im Payload festgehalten. Ohne E-Mail keine Zeile.
|
||
-- security definer: liest auth.users und schreibt in die Outbox, beides ohne
|
||
-- Rechte des ausloesenden Nutzers (Fahrer).
|
||
create function public.auftrag_protokoll_enqueue()
|
||
returns trigger
|
||
language plpgsql
|
||
security definer
|
||
set search_path = public
|
||
as $$
|
||
declare
|
||
v_email text;
|
||
begin
|
||
select u.email into v_email from auth.users u where u.id = new.erstellt_von;
|
||
if coalesce(btrim(v_email), '') = '' then
|
||
return new;
|
||
end if;
|
||
|
||
insert into public.notification_outbox (event_type, auftrag_id, payload)
|
||
values (
|
||
'protokoll_abgeschlossen',
|
||
new.id,
|
||
jsonb_build_object('auftragsnummer', new.auftragsnummer, 'empfaenger', v_email)
|
||
);
|
||
return new;
|
||
end;
|
||
$$;
|
||
|
||
create trigger auftrag_protokoll_enqueue_trg
|
||
after update on public.auftraege
|
||
for each row
|
||
when (old.status is distinct from 'abgeschlossen' and new.status = 'abgeschlossen')
|
||
execute function public.auftrag_protokoll_enqueue();
|
||
|
||
-- Claim nur fuer konfigurierte Kanaele: ist ein Kanal nicht konfiguriert,
|
||
-- bleiben seine Zeilen pending statt geclaimt und auf dead gesetzt zu werden.
|
||
-- Ersetzt claim_notification_batch(int) aus 20260903100000_notification_outbox.sql
|
||
-- (einziger Aufrufer: web/lib/notifications/dispatch.ts).
|
||
drop function public.claim_notification_batch(int);
|
||
|
||
create function public.claim_notification_batch(p_limit int, p_event_types text[])
|
||
returns setof public.notification_outbox
|
||
language sql
|
||
security definer
|
||
set search_path = public
|
||
as $$
|
||
update public.notification_outbox o
|
||
set status = 'sending', updated_at = now()
|
||
where o.id in (
|
||
select id from public.notification_outbox
|
||
where event_type = any(p_event_types)
|
||
and (
|
||
(status in ('pending', 'failed') and naechster_versuch_ab <= now())
|
||
or (status = 'sending' and updated_at < now() - interval '15 minutes')
|
||
)
|
||
order by created_at
|
||
limit p_limit
|
||
for update skip locked
|
||
)
|
||
returning o.*;
|
||
$$;
|
||
|
||
revoke all on function public.claim_notification_batch(int, text[]) from public;
|
||
revoke all on function public.claim_notification_batch(int, text[]) from anon;
|
||
revoke all on function public.claim_notification_batch(int, text[]) from authenticated;
|
||
grant execute on function public.claim_notification_batch(int, text[]) to service_role;
|
||
```
|
||
|
||
- [ ] **Step 5: GREEN**
|
||
|
||
`npx supabase db reset && npx supabase test db` → alle Dateien PASS.
|
||
|
||
- [ ] **Step 6: Commit**
|
||
|
||
```bash
|
||
git add supabase/migrations/20261011090000_protokoll_email.sql supabase/tests/protokoll_email_test.sql supabase/tests/notification_outbox_rls_test.sql
|
||
git commit -m "feat: Outbox-Zeile beim Auftragsabschluss, Claim nach Ereignis-Art"
|
||
```
|
||
|
||
Hinweis: Nach diesem Task ruft `dispatch.ts` noch die alte Signatur — das wird in Task 4 angepasst. Die Vitest-Suite bleibt grün, weil sie den Client fakt.
|
||
|
||
---
|
||
|
||
### Task 2: PDF-Erzeugung auslagern, Fotos verkleinern
|
||
|
||
**Files:**
|
||
- Modify: `web/package.json`, `web/package-lock.json` (`sharp`)
|
||
- Modify: `web/next.config.ts` (`serverExternalPackages` um `sharp`)
|
||
- Create: `web/lib/auftraege/foto-verkleinern.ts`, `web/lib/auftraege/foto-verkleinern.test.ts`
|
||
- Create: `web/lib/auftraege/protokoll-pdf.ts`
|
||
- Modify: `web/lib/auftraege/queries.ts` (`loadAuftrag`), `web/lib/auftraege/fotos.ts` (`loadAuftragFotoBuffers`, `loadUnterschriftBuffer`)
|
||
- Modify: `web/app/auftraege/[id]/protokoll.pdf/route.ts`
|
||
|
||
**Interfaces:**
|
||
- Produces:
|
||
- `verkleinereFoto(foto: ProtokollFoto): Promise<ProtokollFoto>`, Konstanten `MAX_KANTE_PX = 1600`, `JPEG_QUALITAET = 80`
|
||
- `loadAuftrag(id: string, client?: SupabaseClient)`, `loadAuftragFotoBuffers(auftragId: string, client?: SupabaseClient)`, `loadUnterschriftBuffer(storagePath: string | null, client?: SupabaseClient)` — ohne `client` wie bisher `createClient()`
|
||
- `erzeugeProtokollPdf(client: SupabaseClient, auftragId: string): Promise<{ auftrag: Auftrag; buffer: Buffer } | null>` — `null` wenn nicht vorhanden oder nicht `abgeschlossen`; Render-Fehler werden geworfen.
|
||
|
||
- [ ] **Step 1: Dependency**
|
||
|
||
```bash
|
||
cd web && npm install sharp@0.34.5 --save-exact
|
||
```
|
||
|
||
(`sharp@0.34.5` liegt bereits als optionale Next-Abhängigkeit im Lockfile; gleiche Version vermeidet eine zweite Kopie.)
|
||
|
||
`web/next.config.ts`: `serverExternalPackages: ["@react-pdf/renderer", "sharp"],`
|
||
|
||
- [ ] **Step 2: Tests schreiben (failing)**
|
||
|
||
`web/lib/auftraege/foto-verkleinern.test.ts`:
|
||
|
||
```ts
|
||
import { describe, expect, it } from "vitest";
|
||
import sharp from "sharp";
|
||
import { verkleinereFoto, MAX_KANTE_PX } from "./foto-verkleinern";
|
||
import type { ProtokollFoto } from "./protokoll";
|
||
|
||
async function testBild(width: number, height: number, format: "jpeg" | "png" = "jpeg"): Promise<Buffer> {
|
||
const bild = sharp({ create: { width, height, channels: 3, background: { r: 120, g: 120, b: 120 } } });
|
||
return format === "png" ? bild.png().toBuffer() : bild.jpeg().toBuffer();
|
||
}
|
||
|
||
function foto(buffer: Buffer, format: "png" | "jpg" = "jpg"): ProtokollFoto {
|
||
return { label: "Front", beschreibung: null, buffer, format };
|
||
}
|
||
|
||
describe("verkleinereFoto", () => {
|
||
it("verkleinert ein grosses Querformat auf max. 1600 px Breite", async () => {
|
||
const ergebnis = await verkleinereFoto(foto(await testBild(4000, 3000)));
|
||
const meta = await sharp(ergebnis.buffer).metadata();
|
||
expect(meta.width).toBe(MAX_KANTE_PX);
|
||
expect(meta.height).toBe(1200);
|
||
expect(ergebnis.format).toBe("jpg");
|
||
expect(ergebnis.label).toBe("Front");
|
||
});
|
||
|
||
it("verkleinert ein grosses Hochformat auf max. 1600 px Hoehe", async () => {
|
||
const ergebnis = await verkleinereFoto(foto(await testBild(3000, 4000)));
|
||
const meta = await sharp(ergebnis.buffer).metadata();
|
||
expect(meta.height).toBe(MAX_KANTE_PX);
|
||
expect(meta.width).toBe(1200);
|
||
});
|
||
|
||
it("vergroessert kleine Bilder nicht", async () => {
|
||
const ergebnis = await verkleinereFoto(foto(await testBild(800, 600)));
|
||
const meta = await sharp(ergebnis.buffer).metadata();
|
||
expect(meta.width).toBe(800);
|
||
expect(meta.height).toBe(600);
|
||
});
|
||
|
||
it("wandelt PNG in JPEG um", async () => {
|
||
const ergebnis = await verkleinereFoto(foto(await testBild(2000, 1000, "png"), "png"));
|
||
const meta = await sharp(ergebnis.buffer).metadata();
|
||
expect(meta.format).toBe("jpeg");
|
||
expect(ergebnis.format).toBe("jpg");
|
||
});
|
||
|
||
it("wendet die EXIF-Orientierung an (90 Grad gedreht gespeichertes Bild)", async () => {
|
||
// Pixel 2000x1000, EXIF Orientation 6 = Anzeige um 90 Grad gedreht -> 1000x2000
|
||
const roh = await sharp({ create: { width: 2000, height: 1000, channels: 3, background: { r: 10, g: 10, b: 10 } } })
|
||
.jpeg()
|
||
.withMetadata({ orientation: 6 })
|
||
.toBuffer();
|
||
const ergebnis = await verkleinereFoto(foto(roh));
|
||
const meta = await sharp(ergebnis.buffer).metadata();
|
||
expect(meta.width).toBe(800);
|
||
expect(meta.height).toBe(MAX_KANTE_PX);
|
||
});
|
||
|
||
it("gibt bei kaputten Bilddaten das Original zurueck", async () => {
|
||
const kaputt = foto(Buffer.from("das ist kein bild"));
|
||
const ergebnis = await verkleinereFoto(kaputt);
|
||
expect(ergebnis).toBe(kaputt);
|
||
});
|
||
});
|
||
```
|
||
|
||
Run: `cd web && npx vitest run lib/auftraege/foto-verkleinern.test.ts` → FAIL (Modul fehlt).
|
||
|
||
- [ ] **Step 3: `verkleinereFoto` implementieren**
|
||
|
||
`web/lib/auftraege/foto-verkleinern.ts`:
|
||
|
||
```ts
|
||
import sharp from "sharp";
|
||
import type { ProtokollFoto } from "./protokoll";
|
||
|
||
export const MAX_KANTE_PX = 1600;
|
||
export const JPEG_QUALITAET = 80;
|
||
|
||
// Handyfotos sind mehrere MB gross; unverkleinert wird das PDF fuer viele
|
||
// Mailserver zu gross. Originale im Storage bleiben unveraendert -- verkleinert
|
||
// wird nur die Kopie, die ins PDF eingebettet wird. Schlaegt das fehl, lieber
|
||
// das Original einbetten als das Protokoll scheitern lassen.
|
||
export async function verkleinereFoto(foto: ProtokollFoto): Promise<ProtokollFoto> {
|
||
try {
|
||
const buffer = await sharp(foto.buffer)
|
||
.rotate()
|
||
.resize({ width: MAX_KANTE_PX, height: MAX_KANTE_PX, fit: "inside", withoutEnlargement: true })
|
||
.jpeg({ quality: JPEG_QUALITAET })
|
||
.toBuffer();
|
||
return { ...foto, buffer, format: "jpg" };
|
||
} catch {
|
||
return foto;
|
||
}
|
||
}
|
||
```
|
||
|
||
Run: `npx vitest run lib/auftraege/foto-verkleinern.test.ts` → PASS.
|
||
|
||
- [ ] **Step 4: Ladefunktionen mit optionalem Client**
|
||
|
||
`web/lib/auftraege/queries.ts` — oben `import type { SupabaseClient } from "@supabase/supabase-js";` ergänzen, dann:
|
||
|
||
```ts
|
||
export async function loadAuftrag(id: string, client?: SupabaseClient): Promise<Auftrag | null> {
|
||
const supabase = client ?? (await createClient());
|
||
const { data } = await supabase.from("auftraege").select(AUFTRAG_SELECT).eq("id", id).single();
|
||
return (data as unknown as Auftrag) ?? null;
|
||
}
|
||
```
|
||
|
||
`web/lib/auftraege/fotos.ts` — gleiches Import ergänzen; in `loadAuftragFotoBuffers(auftragId: string, client?: SupabaseClient)` und `loadUnterschriftBuffer(storagePath: string | null, client?: SupabaseClient)` jeweils `const supabase = await createClient();` ersetzen durch `const supabase = client ?? (await createClient());`.
|
||
|
||
- [ ] **Step 5: `erzeugeProtokollPdf`**
|
||
|
||
`web/lib/auftraege/protokoll-pdf.ts`:
|
||
|
||
```ts
|
||
import { renderToBuffer, type DocumentProps } from "@react-pdf/renderer";
|
||
import { createElement, type ReactElement } from "react";
|
||
import type { SupabaseClient } from "@supabase/supabase-js";
|
||
import { loadAuftrag, type Auftrag } from "./queries";
|
||
import { loadAuftragFotoBuffers, loadUnterschriftBuffer } from "./fotos";
|
||
import { buildProtokollBasisdaten } from "./protokoll";
|
||
import { ProtokollDocument } from "./ProtokollDocument";
|
||
import { verkleinereFoto } from "./foto-verkleinern";
|
||
|
||
// Gemeinsam fuer PDF-Download (Nutzer-Client, RLS) und Mailversand
|
||
// (Admin-Client im Dispatcher). null = Auftrag fehlt oder ist nicht
|
||
// abgeschlossen; Render-Fehler werden geworfen, damit der Aufrufer sie
|
||
// unterscheiden kann (Route: 500, Dispatcher: Retry).
|
||
export async function erzeugeProtokollPdf(
|
||
client: SupabaseClient,
|
||
auftragId: string
|
||
): Promise<{ auftrag: Auftrag; buffer: Buffer } | null> {
|
||
const auftrag = await loadAuftrag(auftragId, client);
|
||
if (!auftrag || auftrag.status !== "abgeschlossen") {
|
||
return null;
|
||
}
|
||
|
||
const [fotos, unterschriftBuffer] = await Promise.all([
|
||
loadAuftragFotoBuffers(auftragId, client),
|
||
loadUnterschriftBuffer(auftrag.unterschrift_storage_path, client),
|
||
]);
|
||
const verkleinert = await Promise.all(fotos.map(verkleinereFoto));
|
||
|
||
const props = { ...buildProtokollBasisdaten(auftrag), fotos: verkleinert, unterschriftBuffer };
|
||
// @react-pdf/renderer v4 typt ProtokollDocument nicht als ReactElement<DocumentProps>,
|
||
// obwohl es einen <Document>-Baum liefert -- bekannte Typluecke der Lib.
|
||
const element = createElement(ProtokollDocument, { props }) as unknown as ReactElement<DocumentProps>;
|
||
const buffer = await renderToBuffer(element);
|
||
return { auftrag, buffer };
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 6: Route umstellen**
|
||
|
||
`web/app/auftraege/[id]/protokoll.pdf/route.ts` komplett:
|
||
|
||
```ts
|
||
import { NextResponse } from "next/server";
|
||
import { createClient } from "@/lib/supabase/server";
|
||
import { erzeugeProtokollPdf } from "@/lib/auftraege/protokoll-pdf";
|
||
|
||
export async function GET(_request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||
const { id } = await params;
|
||
|
||
let ergebnis: Awaited<ReturnType<typeof erzeugeProtokollPdf>>;
|
||
try {
|
||
ergebnis = await erzeugeProtokollPdf(await createClient(), id);
|
||
} catch (fehler) {
|
||
console.error("PDF-Erzeugung fehlgeschlagen", fehler);
|
||
return new NextResponse("PDF konnte nicht erzeugt werden", { status: 500 });
|
||
}
|
||
|
||
if (!ergebnis) {
|
||
return new NextResponse("Not found", { status: 404 });
|
||
}
|
||
|
||
return new NextResponse(new Uint8Array(ergebnis.buffer), {
|
||
headers: {
|
||
"Content-Type": "application/pdf",
|
||
"Content-Disposition": `attachment; filename="protokoll-${ergebnis.auftrag.auftragsnummer}.pdf"`,
|
||
},
|
||
});
|
||
}
|
||
```
|
||
|
||
Prüfen: `createClient` aus `@/lib/supabase/server` liefert einen zu `SupabaseClient` aus `@supabase/supabase-js` zuweisbaren Typ. Falls `tsc` das ablehnt, den Parametertyp in den drei Ladefunktionen und `erzeugeProtokollPdf` als `Awaited<ReturnType<typeof createClient>> | SupabaseClient` bzw. über einen gemeinsamen Alias `type DbClient = SupabaseClient` mit `as unknown as` an genau einer Stelle (Route) lösen und im Report begründen.
|
||
|
||
- [ ] **Step 7: Prüfen**
|
||
|
||
```bash
|
||
cd web && npm test && npx tsc --noEmit && npm run lint && npm run build
|
||
```
|
||
|
||
Live: lokalen CLI-Stack nutzen (Admin-Testzugang siehe `.claude/skills/supabase-local-dev/SKILL.md`; Login-Feld heißt `identifier`), einen abgeschlossenen Auftrag mit einem großen Testfoto (z. B. per `sharp` erzeugtes 4000×3000-JPEG in den Bucket `auftrag-fotos` hochgeladen und in `auftrag_fotos` eingetragen) anlegen, `GET /auftraege/<id>/protokoll.pdf` → 200, PDF deutlich kleiner als das Originalfoto. Eigenen Server nur per eigener PID stoppen. Testdaten danach entfernen.
|
||
|
||
- [ ] **Step 8: Commit**
|
||
|
||
```bash
|
||
git add web/package.json web/package-lock.json web/next.config.ts web/lib/auftraege/foto-verkleinern.ts web/lib/auftraege/foto-verkleinern.test.ts web/lib/auftraege/protokoll-pdf.ts web/lib/auftraege/queries.ts web/lib/auftraege/fotos.ts "web/app/auftraege/[id]/protokoll.pdf/route.ts"
|
||
git commit -m "feat: PDF-Erzeugung als gemeinsame Funktion, Fotos fuers Protokoll verkleinert"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 3: SMTP-Konfiguration, Mail-Aufbau, Versand
|
||
|
||
**Files:**
|
||
- Modify: `web/package.json`, `web/package-lock.json` (`nodemailer`)
|
||
- Create: `web/lib/notifications/email-config.ts`, `web/lib/notifications/email-config.test.ts`
|
||
- Create: `web/lib/notifications/email.ts`, `web/lib/notifications/email.test.ts`
|
||
- Modify: `.env.example`, `docker-compose.yaml` (web-Service `environment`)
|
||
|
||
**Interfaces:**
|
||
- Consumes: `fahrzeugBezeichnung` (`web/lib/orte-fahrzeuge/fahrzeug-bezeichnung.ts`), `finAbgleichText` (`web/lib/auftraege/fin-abgleich.ts`), Typ `Auftrag` (`web/lib/auftraege/queries.ts`), `SendErgebnis` (`web/lib/notifications/whatsapp.ts`).
|
||
- Produces:
|
||
- `type EmailConfig = { host: string; port: number; secure: boolean; from: string; auth: { user: string; pass: string } | null }`
|
||
- `getEmailConfig(): EmailConfig | null`
|
||
- `type ProtokollMail = { to: string; subject: string; text: string; attachments: { filename: string; content: Buffer; contentType: "application/pdf" }[] }`
|
||
- `baueProtokollMail(daten: { empfaenger: string; auftrag: Auftrag; pdf: Buffer }): ProtokollMail`
|
||
- `sendeProtokollMail(cfg: EmailConfig, mail: ProtokollMail): Promise<SendErgebnis>`
|
||
|
||
- [ ] **Step 1: Dependency**
|
||
|
||
```bash
|
||
cd web && npm install nodemailer@10.0.12 --save-exact
|
||
```
|
||
|
||
(10.0.12 ist vom 28.09.2026; bringt eigene Typen mit `./dist/cjs/nodemailer.d.ts` mit, kein `@types/nodemailer` nötig. Falls `tsc` dennoch keine Typen findet: im Report melden, nicht still `@types/nodemailer` hinzufügen.)
|
||
|
||
- [ ] **Step 2: Tests schreiben (failing)**
|
||
|
||
`web/lib/notifications/email-config.test.ts`:
|
||
|
||
```ts
|
||
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<string, string | undefined> = {};
|
||
|
||
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 <noreply@example.de>";
|
||
}
|
||
|
||
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 <noreply@example.de>",
|
||
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);
|
||
});
|
||
});
|
||
```
|
||
|
||
`web/lib/notifications/email.test.ts`:
|
||
|
||
```ts
|
||
import { describe, expect, it } from "vitest";
|
||
import { baueProtokollMail } from "./email";
|
||
import type { Auftrag } from "@/lib/auftraege/queries";
|
||
|
||
function makeAuftrag(overrides: Partial<Auftrag> = {}): 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");
|
||
});
|
||
});
|
||
```
|
||
|
||
Run: `npx vitest run lib/notifications/email-config.test.ts lib/notifications/email.test.ts` → FAIL.
|
||
|
||
- [ ] **Step 3: Implementieren**
|
||
|
||
`web/lib/notifications/email-config.ts`:
|
||
|
||
```ts
|
||
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,
|
||
};
|
||
}
|
||
```
|
||
|
||
`web/lib/notifications/email.ts`:
|
||
|
||
```ts
|
||
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<SendErgebnis> {
|
||
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();
|
||
}
|
||
}
|
||
```
|
||
|
||
Run: `npx vitest run lib/notifications/email-config.test.ts lib/notifications/email.test.ts` → PASS.
|
||
|
||
- [ ] **Step 4: Konfiguration dokumentieren**
|
||
|
||
`.env.example` — nach dem `NOTIFICATION_DISPATCH_SECRET`-Block anfügen:
|
||
|
||
```
|
||
# --- 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=
|
||
```
|
||
|
||
`docker-compose.yaml` — im `web`-Service unter `environment`, direkt nach `NOTIFICATION_DISPATCH_SECRET: ${NOTIFICATION_DISPATCH_SECRET}`:
|
||
|
||
```yaml
|
||
# 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}
|
||
```
|
||
|
||
- [ ] **Step 5: Prüfen und Commit**
|
||
|
||
```bash
|
||
cd web && npm test && npx tsc --noEmit && npm run lint
|
||
git add web/package.json web/package-lock.json web/lib/notifications/email-config.ts web/lib/notifications/email-config.test.ts web/lib/notifications/email.ts web/lib/notifications/email.test.ts .env.example docker-compose.yaml
|
||
git commit -m "feat: SMTP-Konfiguration und Protokoll-Mail (Aufbau und Versand)"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 4: Dispatcher auf Handler je Ereignis-Art umbauen
|
||
|
||
**Files:**
|
||
- Modify: `web/lib/notifications/dispatch.ts` (komplett ersetzen)
|
||
- Modify: `web/lib/notifications/dispatch.test.ts` (komplett ersetzen)
|
||
- Create: `web/lib/notifications/handler.ts`, `web/lib/notifications/handler.test.ts`
|
||
- Modify: `web/app/api/notifications/dispatch/route.ts`, `web/app/api/notifications/dispatch/route.test.ts`
|
||
|
||
**Interfaces:**
|
||
- Consumes: `claim_notification_batch(p_limit, p_event_types)` (Task 1); `erzeugeProtokollPdf` (Task 2); `getEmailConfig`, `baueProtokollMail`, `sendeProtokollMail` (Task 3); `getWhatsAppConfig`, `sendWhatsAppTemplate`, `AuftragErstelltPayload` (bestehend).
|
||
- Produces:
|
||
- `type OutboxRow = { id: string; event_type: string; auftrag_id: string | null; payload: Record<string, unknown>; versuche: number; max_versuche: number }`
|
||
- `type HandlerErgebnis = { ok: true; waMessageId?: string } | { ok: false; fehler: string; endgueltig?: boolean }`
|
||
- `type Handler = (row: OutboxRow) => Promise<HandlerErgebnis>`
|
||
- `verarbeiteOutbox(admin: SupabaseClient, handler: Record<string, Handler>, deps?: { jetzt?: () => Date }): Promise<VerarbeitungsErgebnis>`
|
||
- `whatsappHandler(cfg: WhatsAppConfig, sender?: typeof sendWhatsAppTemplate): Handler`
|
||
- `protokollMailHandler(admin: SupabaseClient, cfg: EmailConfig, deps?: { erzeugePdf?: typeof erzeugeProtokollPdf; sender?: typeof sendeProtokollMail }): Handler`
|
||
|
||
- [ ] **Step 1: Dispatch-Tests ersetzen (failing)**
|
||
|
||
`web/lib/notifications/dispatch.test.ts` komplett:
|
||
|
||
```ts
|
||
import { describe, expect, it, vi } from "vitest";
|
||
import { verarbeiteOutbox, type Handler, type HandlerErgebnis, type OutboxRow } from "./dispatch";
|
||
|
||
function row(over: Partial<OutboxRow> = {}): OutboxRow {
|
||
return {
|
||
id: "r1",
|
||
event_type: "auftrag_erstellt",
|
||
auftrag_id: "a1",
|
||
payload: {},
|
||
versuche: 0,
|
||
max_versuche: 5,
|
||
...over,
|
||
};
|
||
}
|
||
|
||
// Minimaler Fake des supabase-js-Clients: rpc() liefert die geclaimten Zeilen,
|
||
// from(...).update(...).eq(...) protokolliert die Updates. Ueber eqFehler laesst
|
||
// sich pro Update-Aufruf (Index) ein Fehlerobjekt einschleusen.
|
||
function fakeAdmin(claimed: OutboxRow[], eqFehler: Array<{ message: string } | null> = []) {
|
||
const updates: { id: string; felder: Record<string, unknown> }[] = [];
|
||
const client = {
|
||
rpc: vi.fn(async () => ({ data: claimed, error: null })),
|
||
from: vi.fn(() => ({
|
||
update: (felder: Record<string, unknown>) => ({
|
||
eq: async (_spalte: string, id: string) => {
|
||
const fehler = eqFehler[updates.length] ?? null;
|
||
updates.push({ id, felder });
|
||
return { data: null, error: fehler };
|
||
},
|
||
}),
|
||
})),
|
||
};
|
||
return { client, updates };
|
||
}
|
||
|
||
function handler(ergebnis: HandlerErgebnis) {
|
||
return vi.fn(async (_row: OutboxRow): Promise<HandlerErgebnis> => ergebnis);
|
||
}
|
||
|
||
describe("verarbeiteOutbox", () => {
|
||
it("claimt nur die Ereignis-Arten mit Handler, mit p_limit 20", async () => {
|
||
const { client } = fakeAdmin([]);
|
||
await verarbeiteOutbox(client as never, {
|
||
auftrag_erstellt: handler({ ok: true }),
|
||
protokoll_abgeschlossen: handler({ ok: true }),
|
||
});
|
||
expect(client.rpc).toHaveBeenCalledWith("claim_notification_batch", {
|
||
p_limit: 20,
|
||
p_event_types: ["auftrag_erstellt", "protokoll_abgeschlossen"],
|
||
});
|
||
});
|
||
|
||
it("ruft die Claim-Funktion nicht auf, wenn kein Handler aktiv ist", async () => {
|
||
const { client } = fakeAdmin([]);
|
||
const ergebnis = await verarbeiteOutbox(client as never, {});
|
||
expect(client.rpc).not.toHaveBeenCalled();
|
||
expect(ergebnis).toEqual({ verarbeitet: 0, gesendet: 0, fehlgeschlagen: 0, tot: 0 });
|
||
});
|
||
|
||
it("verteilt Zeilen nach event_type an den passenden Handler", async () => {
|
||
const wa = handler({ ok: true, waMessageId: "wamid.1" });
|
||
const mail = handler({ ok: true });
|
||
const { client, updates } = fakeAdmin([
|
||
row({ id: "r1", event_type: "auftrag_erstellt" }),
|
||
row({ id: "r2", event_type: "protokoll_abgeschlossen" }),
|
||
]);
|
||
|
||
const ergebnis = await verarbeiteOutbox(client as never, { auftrag_erstellt: wa, protokoll_abgeschlossen: mail });
|
||
|
||
expect(wa).toHaveBeenCalledOnce();
|
||
expect(mail).toHaveBeenCalledOnce();
|
||
expect(ergebnis).toEqual({ verarbeitet: 2, gesendet: 2, fehlgeschlagen: 0, tot: 0 });
|
||
expect(updates[0]).toMatchObject({ id: "r1", felder: { status: "sent", wa_message_id: "wamid.1", letzter_fehler: null } });
|
||
expect(updates[1]).toMatchObject({ id: "r2", felder: { status: "sent", wa_message_id: null, letzter_fehler: null } });
|
||
});
|
||
|
||
it("setzt bei Fehler status=failed, versuche+1 und einen Backoff in der Zukunft", async () => {
|
||
const jetzt = new Date("2026-09-03T12:00:00.000Z");
|
||
const { client, updates } = fakeAdmin([row({ versuche: 0, max_versuche: 5 })]);
|
||
|
||
const ergebnis = await verarbeiteOutbox(
|
||
client as never,
|
||
{ auftrag_erstellt: handler({ ok: false, fehler: "404 Template not found" }) },
|
||
{ jetzt: () => jetzt }
|
||
);
|
||
|
||
expect(ergebnis).toEqual({ verarbeitet: 1, gesendet: 0, fehlgeschlagen: 1, tot: 0 });
|
||
expect(updates[0].felder).toMatchObject({ status: "failed", versuche: 1 });
|
||
expect(updates[0].felder.naechster_versuch_ab).toBe("2026-09-03T12:02:00.000Z");
|
||
expect(updates[0].felder.letzter_fehler).toContain("404");
|
||
});
|
||
|
||
it("deckelt den Backoff bei 60 Minuten", async () => {
|
||
const jetzt = new Date("2026-09-03T12:00:00.000Z");
|
||
const { client, updates } = fakeAdmin([row({ versuche: 9, max_versuche: 20 })]);
|
||
await verarbeiteOutbox(client as never, { auftrag_erstellt: handler({ ok: false, fehler: "500" }) }, { jetzt: () => jetzt });
|
||
expect(updates[0].felder.naechster_versuch_ab).toBe("2026-09-03T13:00:00.000Z");
|
||
});
|
||
|
||
it("setzt status=dead, sobald versuche max_versuche erreicht", async () => {
|
||
const { client, updates } = fakeAdmin([row({ versuche: 4, max_versuche: 5 })]);
|
||
const ergebnis = await verarbeiteOutbox(client as never, { auftrag_erstellt: handler({ ok: false, fehler: "500" }) });
|
||
expect(ergebnis).toEqual({ verarbeitet: 1, gesendet: 0, fehlgeschlagen: 0, tot: 1 });
|
||
expect(updates[0].felder).toMatchObject({ status: "dead", versuche: 5 });
|
||
});
|
||
|
||
it("setzt bei endgueltigem Fehler sofort status=dead", async () => {
|
||
const { client, updates } = fakeAdmin([row({ event_type: "protokoll_abgeschlossen", versuche: 0 })]);
|
||
const ergebnis = await verarbeiteOutbox(client as never, {
|
||
protokoll_abgeschlossen: handler({ ok: false, fehler: "Auftrag nicht abgeschlossen", endgueltig: true }),
|
||
});
|
||
expect(ergebnis).toEqual({ verarbeitet: 1, gesendet: 0, fehlgeschlagen: 0, tot: 1 });
|
||
expect(updates[0].felder).toMatchObject({ status: "dead", letzter_fehler: "Auftrag nicht abgeschlossen" });
|
||
});
|
||
|
||
it("macht nach erfolgreicher Sendung einen Poison-Write auf dead, wenn das sent-Update fehlschlaegt", async () => {
|
||
const fehlerSpy = vi.spyOn(console, "error").mockImplementation(() => {});
|
||
const { client, updates } = fakeAdmin([row()], [{ message: "boom" }, null]);
|
||
|
||
const ergebnis = await verarbeiteOutbox(client as never, { auftrag_erstellt: handler({ ok: true, waMessageId: "wamid.1" }) });
|
||
|
||
expect(ergebnis.gesendet).toBe(1);
|
||
expect(updates).toHaveLength(2);
|
||
expect(updates[0].felder).toMatchObject({ status: "sent", wa_message_id: "wamid.1" });
|
||
expect(updates[1].felder.status).toBe("dead");
|
||
expect(String(updates[1].felder.letzter_fehler)).toContain("manuell pruefen");
|
||
fehlerSpy.mockRestore();
|
||
});
|
||
|
||
it("setzt eine geclaimte Zeile ohne Handler auf dead", async () => {
|
||
const fehlerSpy = vi.spyOn(console, "error").mockImplementation(() => {});
|
||
const wa = handler({ ok: true });
|
||
const { client, updates } = fakeAdmin([row({ event_type: "irgendwas_anderes" })]);
|
||
|
||
const ergebnis = await verarbeiteOutbox(client as never, { auftrag_erstellt: wa });
|
||
|
||
expect(wa).not.toHaveBeenCalled();
|
||
expect(ergebnis).toEqual({ verarbeitet: 1, gesendet: 0, fehlgeschlagen: 0, tot: 1 });
|
||
expect(updates[0].felder).toMatchObject({ status: "dead" });
|
||
expect(String(updates[0].felder.letzter_fehler)).toContain("irgendwas_anderes");
|
||
fehlerSpy.mockRestore();
|
||
});
|
||
|
||
it("behandelt einen werfenden Handler wie einen Sendefehler (Retry)", async () => {
|
||
const { client, updates } = fakeAdmin([row()]);
|
||
const werfend: Handler = vi.fn(async () => {
|
||
throw new Error("unerwartet");
|
||
});
|
||
const ergebnis = await verarbeiteOutbox(client as never, { auftrag_erstellt: werfend });
|
||
expect(ergebnis.fehlgeschlagen).toBe(1);
|
||
expect(updates[0].felder).toMatchObject({ status: "failed" });
|
||
expect(String(updates[0].felder.letzter_fehler)).toContain("unerwartet");
|
||
});
|
||
});
|
||
```
|
||
|
||
`web/lib/notifications/handler.test.ts`:
|
||
|
||
```ts
|
||
import { describe, expect, it, vi } from "vitest";
|
||
import { protokollMailHandler, whatsappHandler } from "./handler";
|
||
import type { OutboxRow } from "./dispatch";
|
||
import type { EmailConfig } from "./email-config";
|
||
import type { WhatsAppConfig } from "./config";
|
||
import type { Auftrag } from "@/lib/auftraege/queries";
|
||
|
||
const MAIL_CFG: EmailConfig = { host: "smtp", port: 587, secure: false, from: "noreply@example.de", auth: null };
|
||
const WA_CFG: WhatsAppConfig = {
|
||
accessToken: "tok",
|
||
phoneNumberId: "PN1",
|
||
recipient: "4915100000000",
|
||
templateName: "neuer_auftrag",
|
||
templateLang: "de",
|
||
graphVersion: "v21.0",
|
||
};
|
||
|
||
function row(over: Partial<OutboxRow> = {}): OutboxRow {
|
||
return {
|
||
id: "r1",
|
||
event_type: "protokoll_abgeschlossen",
|
||
auftrag_id: "a1",
|
||
payload: { auftragsnummer: "26-09-01-0001", empfaenger: "dispo@example.de" },
|
||
versuche: 0,
|
||
max_versuche: 5,
|
||
...over,
|
||
};
|
||
}
|
||
|
||
const AUFTRAG = {
|
||
auftragsnummer: "26-09-01-0001",
|
||
fahrzeug: { id: "f1", kennzeichen: "M-AB 123", fin: null, marke: null, modell: null },
|
||
abholort: { adresse: "A" },
|
||
zielort: { adresse: "B" },
|
||
zugewiesen_an_profil: null,
|
||
uebergabe_bestaetigt_at: null,
|
||
empfaenger_name: null,
|
||
start_fin: null,
|
||
start_fin_status: null,
|
||
} as unknown as Auftrag;
|
||
|
||
describe("protokollMailHandler", () => {
|
||
it("erzeugt das PDF mit dem Admin-Client und sendet an payload.empfaenger", async () => {
|
||
const admin = {} as never;
|
||
const erzeugePdf = vi.fn(async () => ({ auftrag: AUFTRAG, buffer: Buffer.from("%PDF") }));
|
||
const sender = vi.fn(async () => ({ ok: true as const, messageId: "<m1>" }));
|
||
|
||
const ergebnis = await protokollMailHandler(admin, MAIL_CFG, { erzeugePdf, sender })(row());
|
||
|
||
expect(ergebnis).toEqual({ ok: true });
|
||
expect(erzeugePdf).toHaveBeenCalledWith(admin, "a1");
|
||
expect(sender).toHaveBeenCalledWith(MAIL_CFG, expect.objectContaining({ to: "dispo@example.de" }));
|
||
});
|
||
|
||
it("ist endgueltig fehlgeschlagen, wenn der Auftrag nicht (mehr) abgeschlossen ist", async () => {
|
||
const ergebnis = await protokollMailHandler({} as never, MAIL_CFG, {
|
||
erzeugePdf: vi.fn(async () => null),
|
||
sender: vi.fn(),
|
||
})(row());
|
||
expect(ergebnis).toEqual({ ok: false, fehler: "Auftrag nicht gefunden oder nicht abgeschlossen", endgueltig: true });
|
||
});
|
||
|
||
it("ist endgueltig fehlgeschlagen ohne Empfaenger oder ohne auftrag_id", async () => {
|
||
const deps = { erzeugePdf: vi.fn(), sender: vi.fn() };
|
||
expect(await protokollMailHandler({} as never, MAIL_CFG, deps)(row({ payload: {} }))).toMatchObject({
|
||
ok: false,
|
||
endgueltig: true,
|
||
});
|
||
expect(await protokollMailHandler({} as never, MAIL_CFG, deps)(row({ auftrag_id: null }))).toMatchObject({
|
||
ok: false,
|
||
endgueltig: true,
|
||
});
|
||
expect(deps.erzeugePdf).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it("meldet einen PDF-Fehler als wiederholbaren Fehler", async () => {
|
||
const ergebnis = await protokollMailHandler({} as never, MAIL_CFG, {
|
||
erzeugePdf: vi.fn(async () => {
|
||
throw new Error("render kaputt");
|
||
}),
|
||
sender: vi.fn(),
|
||
})(row());
|
||
expect(ergebnis).toEqual({ ok: false, fehler: "PDF-Erzeugung fehlgeschlagen: render kaputt" });
|
||
});
|
||
|
||
it("reicht einen SMTP-Fehler als wiederholbaren Fehler durch", async () => {
|
||
const ergebnis = await protokollMailHandler({} as never, MAIL_CFG, {
|
||
erzeugePdf: vi.fn(async () => ({ auftrag: AUFTRAG, buffer: Buffer.from("%PDF") })),
|
||
sender: vi.fn(async () => ({ ok: false as const, fehler: "ECONNREFUSED" })),
|
||
})(row());
|
||
expect(ergebnis).toEqual({ ok: false, fehler: "ECONNREFUSED" });
|
||
});
|
||
});
|
||
|
||
describe("whatsappHandler", () => {
|
||
it("reicht die Meta-Message-ID als waMessageId durch", async () => {
|
||
const sender = vi.fn(async () => ({ ok: true as const, messageId: "wamid.1" }));
|
||
const payload = { auftragsnummer: "1", abholort_adresse: "A", zielort_adresse: "B", kennzeichen: "K" };
|
||
const ergebnis = await whatsappHandler(WA_CFG, sender)(row({ event_type: "auftrag_erstellt", payload }));
|
||
expect(ergebnis).toEqual({ ok: true, waMessageId: "wamid.1" });
|
||
expect(sender).toHaveBeenCalledWith(WA_CFG, payload);
|
||
});
|
||
|
||
it("reicht Sendefehler durch", async () => {
|
||
const sender = vi.fn(async () => ({ ok: false as const, fehler: "500" }));
|
||
expect(await whatsappHandler(WA_CFG, sender)(row({ event_type: "auftrag_erstellt" }))).toEqual({
|
||
ok: false,
|
||
fehler: "500",
|
||
});
|
||
});
|
||
});
|
||
```
|
||
|
||
Run: `npx vitest run lib/notifications/dispatch.test.ts lib/notifications/handler.test.ts` → FAIL.
|
||
|
||
- [ ] **Step 2: `dispatch.ts` ersetzen**
|
||
|
||
`web/lib/notifications/dispatch.ts` komplett:
|
||
|
||
```ts
|
||
import type { SupabaseClient } from "@supabase/supabase-js";
|
||
|
||
export type OutboxRow = {
|
||
id: string;
|
||
event_type: string;
|
||
auftrag_id: string | null;
|
||
payload: Record<string, unknown>;
|
||
versuche: number;
|
||
max_versuche: number;
|
||
};
|
||
|
||
// endgueltig: der Fehler wird durch Wiederholen nicht besser (z. B. Auftrag
|
||
// nicht mehr abgeschlossen) -> sofort dead statt Backoff.
|
||
export type HandlerErgebnis =
|
||
| { ok: true; waMessageId?: string }
|
||
| { ok: false; fehler: string; endgueltig?: boolean };
|
||
|
||
export type Handler = (row: OutboxRow) => Promise<HandlerErgebnis>;
|
||
|
||
export type VerarbeitungsErgebnis = {
|
||
verarbeitet: number;
|
||
gesendet: number;
|
||
fehlgeschlagen: number;
|
||
tot: number;
|
||
};
|
||
|
||
export type DispatchDeps = {
|
||
jetzt?: () => Date;
|
||
};
|
||
|
||
const BATCH_LIMIT = 20;
|
||
const BACKOFF_MAX_MIN = 60;
|
||
|
||
// Uebernimmt einen Batch faelliger Outbox-Zeilen der Ereignis-Arten, fuer die
|
||
// ein Handler (= konfigurierter Kanal) existiert, und gibt jede Zeile an ihren
|
||
// Handler. Erfolg -> sent; Fehler -> failed mit exponentiellem Backoff, bzw.
|
||
// dead sobald max_versuche erreicht oder der Fehler endgueltig ist.
|
||
export async function verarbeiteOutbox(
|
||
admin: SupabaseClient,
|
||
handler: Record<string, Handler>,
|
||
deps: DispatchDeps = {}
|
||
): Promise<VerarbeitungsErgebnis> {
|
||
const jetzt = deps.jetzt ?? (() => new Date());
|
||
const ergebnis: VerarbeitungsErgebnis = { verarbeitet: 0, gesendet: 0, fehlgeschlagen: 0, tot: 0 };
|
||
|
||
const eventTypes = Object.keys(handler);
|
||
if (eventTypes.length === 0) {
|
||
return ergebnis;
|
||
}
|
||
|
||
const { data, error } = await admin.rpc("claim_notification_batch", {
|
||
p_limit: BATCH_LIMIT,
|
||
p_event_types: eventTypes,
|
||
});
|
||
if (error) {
|
||
throw new Error(`claim_notification_batch fehlgeschlagen: ${error.message}`);
|
||
}
|
||
const rows = (data ?? []) as OutboxRow[];
|
||
|
||
for (const row of rows) {
|
||
const nun = jetzt();
|
||
|
||
// Jeder Status-Schreibvorgang wird geprueft: schlaegt er fehl, bleibt die
|
||
// Zeile sonst in 'sending' haengen und wird nach 15 min erneut geclaimt ->
|
||
// die Nachricht ginge wiederholt raus. Deshalb laut loggen und dem Aufrufer
|
||
// ueber den Rueckgabewert signalisieren.
|
||
async function schreibe(felder: Record<string, unknown>): Promise<boolean> {
|
||
const { error: updateFehler } = await admin.from("notification_outbox").update(felder).eq("id", row.id);
|
||
if (updateFehler) {
|
||
console.error("[notifications] Outbox-Status-Update fehlgeschlagen fuer", row.id, "-", updateFehler.message);
|
||
return false;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
ergebnis.verarbeitet += 1;
|
||
|
||
const verarbeite = handler[row.event_type];
|
||
if (!verarbeite) {
|
||
console.error("[notifications] kein Handler fuer event_type, Zeile wird auf dead gesetzt:", row.id, row.event_type);
|
||
await schreibe({
|
||
status: "dead",
|
||
letzter_fehler: `unbekannter event_type: ${row.event_type}`,
|
||
updated_at: nun.toISOString(),
|
||
});
|
||
ergebnis.tot += 1;
|
||
continue;
|
||
}
|
||
|
||
let res: HandlerErgebnis;
|
||
try {
|
||
res = await verarbeite(row);
|
||
} catch (fehler) {
|
||
res = { ok: false, fehler: fehler instanceof Error ? fehler.message : String(fehler) };
|
||
}
|
||
|
||
if (res.ok) {
|
||
const ok = await schreibe({
|
||
status: "sent",
|
||
wa_message_id: res.waMessageId ?? null,
|
||
letzter_fehler: null,
|
||
updated_at: nun.toISOString(),
|
||
});
|
||
if (!ok) {
|
||
// Nachricht ging raus, aber der Status-Schreibvorgang scheiterte. Ein
|
||
// einmaliger Poison-Write auf 'dead' verhindert, dass die 15-min-Reclaim
|
||
// die Nachricht im haeufigen transienten Fall erneut verschickt.
|
||
await schreibe({
|
||
status: "dead",
|
||
letzter_fehler: "Sendung ok, aber Status-Update fehlgeschlagen - manuell pruefen",
|
||
updated_at: nun.toISOString(),
|
||
});
|
||
}
|
||
ergebnis.gesendet += 1;
|
||
continue;
|
||
}
|
||
|
||
const neueVersuche = row.versuche + 1;
|
||
const tot = res.endgueltig === true || neueVersuche >= row.max_versuche;
|
||
const backoffMin = Math.min(2 ** neueVersuche, BACKOFF_MAX_MIN);
|
||
const naechster = new Date(nun.getTime() + backoffMin * 60_000);
|
||
|
||
const ok = await schreibe({
|
||
status: tot ? "dead" : "failed",
|
||
versuche: neueVersuche,
|
||
naechster_versuch_ab: naechster.toISOString(),
|
||
letzter_fehler: res.fehler.slice(0, 500),
|
||
updated_at: nun.toISOString(),
|
||
});
|
||
|
||
if (!ok) {
|
||
ergebnis.fehlgeschlagen += 1;
|
||
continue;
|
||
}
|
||
|
||
if (tot) ergebnis.tot += 1;
|
||
else ergebnis.fehlgeschlagen += 1;
|
||
}
|
||
|
||
return ergebnis;
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 3: `handler.ts`**
|
||
|
||
`web/lib/notifications/handler.ts`:
|
||
|
||
```ts
|
||
import type { SupabaseClient } from "@supabase/supabase-js";
|
||
import { erzeugeProtokollPdf } from "@/lib/auftraege/protokoll-pdf";
|
||
import type { WhatsAppConfig } from "./config";
|
||
import type { Handler } from "./dispatch";
|
||
import type { EmailConfig } from "./email-config";
|
||
import { baueProtokollMail, sendeProtokollMail } from "./email";
|
||
import { sendWhatsAppTemplate, type AuftragErstelltPayload } from "./whatsapp";
|
||
|
||
export function whatsappHandler(cfg: WhatsAppConfig, sender = sendWhatsAppTemplate): Handler {
|
||
return async (row) => {
|
||
const res = await sender(cfg, row.payload as AuftragErstelltPayload);
|
||
return res.ok ? { ok: true, waMessageId: res.messageId } : res;
|
||
};
|
||
}
|
||
|
||
export function protokollMailHandler(
|
||
admin: SupabaseClient,
|
||
cfg: EmailConfig,
|
||
deps: { erzeugePdf?: typeof erzeugeProtokollPdf; sender?: typeof sendeProtokollMail } = {}
|
||
): Handler {
|
||
const erzeugePdf = deps.erzeugePdf ?? erzeugeProtokollPdf;
|
||
const sender = deps.sender ?? sendeProtokollMail;
|
||
|
||
return async (row) => {
|
||
const empfaenger = typeof row.payload.empfaenger === "string" ? row.payload.empfaenger : "";
|
||
if (!empfaenger || !row.auftrag_id) {
|
||
return { ok: false, fehler: "Empfaenger oder Auftrag fehlt in der Outbox-Zeile", endgueltig: true };
|
||
}
|
||
|
||
let pdf: Awaited<ReturnType<typeof erzeugeProtokollPdf>>;
|
||
try {
|
||
pdf = await erzeugePdf(admin, row.auftrag_id);
|
||
} catch (fehler) {
|
||
return {
|
||
ok: false,
|
||
fehler: `PDF-Erzeugung fehlgeschlagen: ${fehler instanceof Error ? fehler.message : String(fehler)}`,
|
||
};
|
||
}
|
||
if (!pdf) {
|
||
return { ok: false, fehler: "Auftrag nicht gefunden oder nicht abgeschlossen", endgueltig: true };
|
||
}
|
||
|
||
const res = await sender(cfg, baueProtokollMail({ empfaenger, auftrag: pdf.auftrag, pdf: pdf.buffer }));
|
||
return res.ok ? { ok: true } : res;
|
||
};
|
||
}
|
||
```
|
||
|
||
Run: `npx vitest run lib/notifications/dispatch.test.ts lib/notifications/handler.test.ts` → PASS.
|
||
|
||
- [ ] **Step 4: Route umbauen (Tests zuerst)**
|
||
|
||
In `web/app/api/notifications/dispatch/route.test.ts`:
|
||
- Mocks oben ergänzen:
|
||
|
||
```ts
|
||
vi.mock("@/lib/notifications/email-config", () => ({ getEmailConfig: vi.fn() }));
|
||
vi.mock("@/lib/notifications/handler", () => ({
|
||
whatsappHandler: vi.fn(() => "wa-handler"),
|
||
protokollMailHandler: vi.fn(() => "mail-handler"),
|
||
}));
|
||
```
|
||
|
||
- Import ergänzen: `import { getEmailConfig } from "@/lib/notifications/email-config";`
|
||
- In `beforeEach`: `vi.mocked(getEmailConfig).mockReset();`
|
||
- Test „antwortet 200 uebersprungen, wenn keine WhatsApp-Config vorhanden ist" umbenennen in „antwortet 200 uebersprungen, wenn kein Kanal konfiguriert ist" und zusätzlich `vi.mocked(getEmailConfig).mockReturnValue(null);` setzen.
|
||
- Test „ruft verarbeiteOutbox …" ergänzen um `vi.mocked(getEmailConfig).mockReturnValue(null);` und die Erwartung `expect(verarbeiteOutbox).toHaveBeenCalledWith({}, { auftrag_erstellt: "wa-handler" });`
|
||
- Neuen Test anhängen:
|
||
|
||
```ts
|
||
it("verarbeitet Protokoll-Mails auch ohne WhatsApp-Config", async () => {
|
||
vi.mocked(getWhatsAppConfig).mockReturnValue(null);
|
||
vi.mocked(getEmailConfig).mockReturnValue({ host: "smtp", port: 587, secure: false, from: "x@y.de", auth: null });
|
||
vi.mocked(verarbeiteOutbox).mockResolvedValue({ verarbeitet: 1, gesendet: 1, fehlgeschlagen: 0, tot: 0 });
|
||
|
||
const res = await POST(req({ Authorization: "Bearer geheim" }));
|
||
|
||
expect(res.status).toBe(200);
|
||
expect(verarbeiteOutbox).toHaveBeenCalledWith({}, { protokoll_abgeschlossen: "mail-handler" });
|
||
});
|
||
```
|
||
|
||
Run: `npx vitest run app/api/notifications/dispatch/route.test.ts` → FAIL.
|
||
|
||
`web/app/api/notifications/dispatch/route.ts` — Imports anpassen und den Teil ab `const cfg = getWhatsAppConfig();` ersetzen:
|
||
|
||
```ts
|
||
import { getWhatsAppConfig } from "@/lib/notifications/config";
|
||
import { getEmailConfig } from "@/lib/notifications/email-config";
|
||
import { verarbeiteOutbox, type Handler } from "@/lib/notifications/dispatch";
|
||
import { protokollMailHandler, whatsappHandler } from "@/lib/notifications/handler";
|
||
```
|
||
|
||
```ts
|
||
const admin = createAdminClient();
|
||
const handler: Record<string, Handler> = {};
|
||
const waCfg = getWhatsAppConfig();
|
||
if (waCfg) {
|
||
handler.auftrag_erstellt = whatsappHandler(waCfg);
|
||
}
|
||
const mailCfg = getEmailConfig();
|
||
if (mailCfg) {
|
||
handler.protokoll_abgeschlossen = protokollMailHandler(admin, mailCfg);
|
||
}
|
||
|
||
if (Object.keys(handler).length === 0) {
|
||
console.warn("[notifications] kein Kanal konfiguriert – Outbox wird nicht verarbeitet");
|
||
return NextResponse.json({ verarbeitet: 0, uebersprungen: true });
|
||
}
|
||
|
||
try {
|
||
const ergebnis = await verarbeiteOutbox(admin, handler);
|
||
return NextResponse.json(ergebnis);
|
||
} catch (e) {
|
||
console.error("[notifications] Dispatch fehlgeschlagen:", e);
|
||
return NextResponse.json({ fehler: "Dispatch fehlgeschlagen" }, { status: 500 });
|
||
}
|
||
```
|
||
|
||
Run: `npx vitest run app/api/notifications/dispatch/route.test.ts` → PASS.
|
||
|
||
- [ ] **Step 5: Prüfen und Commit**
|
||
|
||
```bash
|
||
cd web && npm test && npx tsc --noEmit && npm run lint
|
||
git add web/lib/notifications/dispatch.ts web/lib/notifications/dispatch.test.ts web/lib/notifications/handler.ts web/lib/notifications/handler.test.ts web/app/api/notifications/dispatch/route.ts web/app/api/notifications/dispatch/route.test.ts
|
||
git commit -m "feat: Outbox-Dispatcher mit Handlern je Ereignis-Art, Protokoll-Mail-Handler"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 5: Abschluss-Verifikation inkl. Live-Versand
|
||
|
||
- [ ] **Step 1: Suiten**
|
||
|
||
```bash
|
||
npx supabase db reset && npx supabase test db
|
||
cd web && npm test && npx tsc --noEmit && npm run lint && npm run build
|
||
```
|
||
|
||
- [ ] **Step 2: Live-Versand gegen Mailpit**
|
||
|
||
Lokalen Test-Mailserver starten (gleiches Image wie im Supabase-CLI-Stack, bereits lokal vorhanden):
|
||
|
||
```bash
|
||
docker run -d --rm --name mailpit-protokoll-test -p 54335:1025 -p 54336:8025 public.ecr.aws/supabase/mailpit:v1.31.3
|
||
```
|
||
|
||
`web/.env.local` (nur im Worktree, nicht committen) ergänzen: `SMTP_HOST=127.0.0.1`, `SMTP_PORT=54335`, `SMTP_FROM=Aushilfsfahrer <noreply@test.local>`, `NOTIFICATION_DISPATCH_SECRET=lokal-test`, sowie `SUPABASE_SERVICE_ROLE_KEY` aus `npx supabase status`.
|
||
|
||
Testdaten im CLI-Stack: Disponent mit E-Mail (Auth-Admin-API), Fahrer, Auftrag im Status `unterwegs` mit Ersteller = Disponent, ein Foto. Auftrag per SQL (als `postgres`) auf `abgeschlossen` setzen (`end_km`, `uebergabe_bestaetigt_at`), dann `npm run build && node node_modules/next/dist/bin/next start -p 3108` (im Hintergrund, eigene PID merken) und
|
||
|
||
```bash
|
||
curl -s -X POST http://localhost:3108/api/notifications/dispatch -H "Authorization: Bearer lokal-test"
|
||
```
|
||
|
||
Erwartet: JSON mit `gesendet: 1`; `http://localhost:54336` (Mailpit-API `GET /api/v1/messages`) zeigt die Mail mit Betreff `Übergabeprotokoll <nr> – <fahrzeug>` und PDF-Anhang; Outbox-Zeile `status = 'sent'`.
|
||
|
||
Optional Fehlerfall: Mailpit stoppen, zweiten Auftrag abschließen, Dispatch aufrufen → Zeile `failed` mit `naechster_versuch_ab` in der Zukunft.
|
||
|
||
Aufräumen: eigenen Next-Server per PID stoppen, `docker stop mailpit-protokoll-test`, `npx supabase db reset`.
|
||
|
||
- [ ] **Step 3: Docker-Build**
|
||
|
||
`docker build -t aushilfsfahrer-web-mail-test web` → erfolgreich (prüft `sharp` unter Alpine/musl); danach `docker rmi aushilfsfahrer-web-mail-test`.
|