48 KiB
WhatsApp-Benachrichtigung bei neuem Auftrag — 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: Beim Anlegen eines Auftrags geht automatisch eine WhatsApp-Nachricht an eine feste Sammel-Nummer, zuverlässig zugestellt über eine transaktionale Outbox mit Retry.
Architecture: Ein AFTER INSERT-Trigger auf auftraege schreibt eine Zeile in
notification_outbox. Ein pg_cron-Job stößt minütlich per pg_net die interne Route
POST /api/notifications/dispatch an (Shared Secret). Die Route übernimmt fällige Zeilen
über eine SECURITY DEFINER-Batch-Funktion, ruft die Meta WhatsApp Cloud API auf und
schreibt sent / failed+Backoff / dead zurück. Die WhatsApp-/Meta-Logik liegt komplett
in web/lib/notifications/* (TypeScript, env), die DB macht nur „einmal pro Minute
anklopfen".
Tech Stack: Next.js Route Handler (Node runtime), Supabase (Postgres RLS, pg_cron,
pg_net), @supabase/supabase-js Service-Role-Client, Meta Graph API (fetch), Vitest,
pgTAP.
Spec: docs/superpowers/specs/2026-09-03-whatsapp-benachrichtigung-design.md
Global Constraints
- RLS ist die Sicherheitsgrenze.
notification_outboxbekommt nur eineSELECT-Policy für Rolleadmin; keinINSERT/UPDATE/DELETEfürauthenticated/anon. Geschrieben wird ausschließlich vomSECURITY DEFINER-Trigger und vom Service-Role-Client der Route. - Feature ist ohne Meta-Konto „aus". Fehlt eine der Pflichtvariablen
(
WHATSAPP_ACCESS_TOKEN,WHATSAPP_PHONE_NUMBER_ID,WHATSAPP_RECIPIENT,WHATSAPP_TEMPLATE_NAME,WHATSAPP_TEMPLATE_LANG), verarbeitet der Dispatcher keine Zeilen, loggt einmalconsole.warn, und die Route antwortet200{ verarbeitet: 0, uebersprungen: true }. Der Code muss vor dem fertigen Meta-Konto mergebar und grün sein. - Kein Secret/keine Umgebungs-URL in einer committeten Migration. Der Cron-Job liest
current_setting('app.notification_dispatch_url', true)undcurrent_setting('app.notification_dispatch_secret', true); diese Settings werden pro Stack out-of-band gesetzt. - Feste Parameter-Reihenfolge im Template-Body:
auftragsnummer,abholort_adresse,zielort_adresse,kennzeichen. - Backoff:
naechster_versuch_ab = now() + min(2^versuche, 60) Minuten; Übergang nachdeadbeiversuche >= max_versuche(Defaultmax_versuche = 5). - Supabase-CLI-Befehle vom Repo-Root (
npx supabase db reset,npx supabase test db), nicht ausweb/.web/-Unit-Tests:cd web && npx vitest run. - Live-Verifikation (curl gegen die laufende Route) macht der Controller konsolidiert
nach Task 7 — dispatchte Implementer-Subagents haben keinen zuverlässigen Zugriff auf
einen laufenden Dev-Server. Implementer machen
tsc+ Vitest + (bei Migrationen)db reset/test db. - Neueste vorhandene Migration:
20260903091000. Neue Dateien:20260903100000_…und20260903101000_….
Task 1: Migration — notification_outbox, Batch-Claim-Funktion, Enqueue-Trigger + pgTAP
Files:
- Create:
supabase/migrations/20260903100000_notification_outbox.sql - Create:
supabase/tests/notification_outbox_rls_test.sql
Interfaces:
-
Consumes:
public.auftraege(id, abholort_id, zielort_id, fahrzeug_id, auftragsnummer),public.orte(id, adresse),public.fahrzeuge(id, kennzeichen),public.user_role()(alle bestehend). -
Produces:
- Tabelle
public.notification_outboxmit Spaltenid uuid,event_type text,auftrag_id uuid,payload jsonb,status text,versuche int,max_versuche int,naechster_versuch_ab timestamptz,letzter_fehler text,wa_message_id text,created_at timestamptz,updated_at timestamptz. - Funktion
public.claim_notification_batch(p_limit int) returns setof public.notification_outbox— von Task 4 (verarbeiteOutbox) überadmin.rpc("claim_notification_batch", { p_limit })aufgerufen.
- Tabelle
-
Step 1: Migration schreiben
Datei supabase/migrations/20260903100000_notification_outbox.sql:
-- Transaktionale Outbox fuer ausgehende Benachrichtigungen. Vorerst nur das
-- Ereignis 'auftrag_erstellt' (WhatsApp an eine feste Sammel-Nummer), aber
-- event_type/payload sind generisch fuer spaetere Ereignisse. Geschrieben wird
-- ausschliesslich vom SECURITY DEFINER-Enqueue-Trigger und vom
-- Service-Role-Client der Dispatch-Route; RLS gibt nur admin Leserechte.
create table public.notification_outbox (
id uuid primary key default gen_random_uuid(),
event_type text not null,
auftrag_id uuid references public.auftraege(id) on delete set null,
payload jsonb not null,
status text not null default 'pending'
check (status in ('pending', 'sending', 'sent', 'failed', 'dead')),
versuche int not null default 0,
max_versuche int not null default 5,
naechster_versuch_ab timestamptz not null default now(),
letzter_fehler text,
wa_message_id text,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
create index notification_outbox_faellig_idx
on public.notification_outbox (status, naechster_versuch_ab);
alter table public.notification_outbox enable row level security;
-- Nur Einsicht fuer admin (Studio / spaeteres Admin-View). Kein
-- INSERT/UPDATE/DELETE fuer authenticated: der Enqueue-Trigger laeuft als
-- SECURITY DEFINER, die Dispatch-Route ueber den Service-Role-Key -- beide
-- umgehen RLS.
create policy "Admin liest notification_outbox"
on public.notification_outbox for select
using (public.user_role() = 'admin');
-- Enqueue: bei jedem INSERT in auftraege genau eine pending-Zeile. Laeuft als
-- AFTER INSERT, auftragsnummer ist zu diesem Zeitpunkt vom BEFORE-Trigger
-- auftragsnummer_generieren bereits gefuellt.
create function public.auftrag_notification_enqueue()
returns trigger
language plpgsql
security definer
set search_path = public
as $$
begin
insert into public.notification_outbox (event_type, auftrag_id, payload)
select
'auftrag_erstellt',
new.id,
jsonb_build_object(
'auftragsnummer', new.auftragsnummer,
'abholort_adresse', abhol.adresse,
'zielort_adresse', ziel.adresse,
'kennzeichen', fz.kennzeichen)
from public.orte abhol
join public.orte ziel on ziel.id = new.zielort_id
join public.fahrzeuge fz on fz.id = new.fahrzeug_id
where abhol.id = new.abholort_id;
return new;
end;
$$;
create trigger auftrag_notification_enqueue_trg
after insert on public.auftraege
for each row execute function public.auftrag_notification_enqueue();
-- Atomare Batch-Uebernahme fuer den Dispatcher: selektiert faellige Zeilen
-- (pending/failed und Zeitpunkt erreicht, oder in 'sending' haengengeblieben
-- seit >15 min) und setzt sie in einem Rutsch auf 'sending'. FOR UPDATE SKIP
-- LOCKED verhindert Doppel-Uebernahme bei ueberlappenden Laeufen.
create function public.claim_notification_batch(p_limit int)
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 (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) from public;
revoke all on function public.claim_notification_batch(int) from anon;
revoke all on function public.claim_notification_batch(int) from authenticated;
-- Nur die Dispatch-Route (Service-Role-Client) darf den Batch uebernehmen.
grant execute on function public.claim_notification_batch(int) to service_role;
- Step 2: Migration anwenden
Run (Repo-Root): npx supabase db reset
Expected: Läuft durch bis „Finished supabase db reset.", keine Fehler.
- Step 3: pgTAP-Test schreiben
Datei supabase/tests/notification_outbox_rls_test.sql:
begin;
select plan(8);
insert into auth.users (id, email) values
('c1111111-1111-1111-1111-111111111111', 'admin-outbox@auftraege.test.local'),
('c2222222-2222-2222-2222-222222222222', 'disponent-outbox@auftraege.test.local');
update public.profiles set role = 'admin' where id = 'c1111111-1111-1111-1111-111111111111';
update public.profiles set role = 'disponent' where id = 'c2222222-2222-2222-2222-222222222222';
insert into public.orte (id, adresse, ansprechpartner) values
('c3111111-1111-1111-1111-111111111111', 'Startstr. 1, Teststadt', 'Frau A'),
('c3222222-2222-2222-2222-222222222222', 'Zielstr. 2, Teststadt', 'Herr B');
insert into public.fahrzeuge (id, kennzeichen) values
('c3333333-0000-0000-0000-000000000001', 'S-WA 42');
set local role authenticated;
set local request.jwt.claims to '{"sub": "c2222222-2222-2222-2222-222222222222", "role": "authenticated"}';
-- 1) Disponent legt einen Auftrag an -> Enqueue-Trigger erzeugt genau eine Zeile.
insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status)
values (
'c4000000-0000-0000-0000-00000000000a',
'c3111111-1111-1111-1111-111111111111',
'c3222222-2222-2222-2222-222222222222',
'c3333333-0000-0000-0000-000000000001',
'c2222222-2222-2222-2222-222222222222',
'offen'
);
reset role;
reset request.jwt.claims;
select is(
(select count(*)::int from public.notification_outbox
where auftrag_id = 'c4000000-0000-0000-0000-00000000000a'),
1,
'Enqueue-Trigger legt genau eine notification_outbox-Zeile pro neuem Auftrag an'
);
select is(
(select status from public.notification_outbox
where auftrag_id = 'c4000000-0000-0000-0000-00000000000a'),
'pending',
'Neue Outbox-Zeile hat status = pending'
);
select is(
(select event_type from public.notification_outbox
where auftrag_id = 'c4000000-0000-0000-0000-00000000000a'),
'auftrag_erstellt',
'Neue Outbox-Zeile hat event_type = auftrag_erstellt'
);
select is(
(select payload->>'kennzeichen' from public.notification_outbox
where auftrag_id = 'c4000000-0000-0000-0000-00000000000a'),
'S-WA 42',
'payload.kennzeichen kommt aus dem verknuepften Fahrzeug'
);
select is(
(select payload->>'abholort_adresse' from public.notification_outbox
where auftrag_id = 'c4000000-0000-0000-0000-00000000000a'),
'Startstr. 1, Teststadt',
'payload.abholort_adresse kommt aus dem Abholort (nicht dem Zielort)'
);
-- 2) SELECT-RLS: Disponent sieht die Outbox nicht.
set local role authenticated;
set local request.jwt.claims to '{"sub": "c2222222-2222-2222-2222-222222222222", "role": "authenticated"}';
select is_empty(
$$ select id from public.notification_outbox $$,
'Disponent sieht keine notification_outbox-Zeilen (keine SELECT-Policy fuer disponent)'
);
-- 3) SELECT-RLS: Admin sieht die Outbox.
reset request.jwt.claims;
set local request.jwt.claims to '{"sub": "c1111111-1111-1111-1111-111111111111", "role": "authenticated"}';
select isnt_empty(
$$ select id from public.notification_outbox $$,
'Admin sieht notification_outbox-Zeilen'
);
-- 4) EXECUTE-Recht: authenticated darf die Batch-Claim-Funktion nicht aufrufen
-- (revoke von authenticated, grant nur an service_role).
set local request.jwt.claims to '{"sub": "c2222222-2222-2222-2222-222222222222", "role": "authenticated"}';
select throws_ok(
$$ select public.claim_notification_batch(5) $$,
'42501',
'authenticated darf claim_notification_batch nicht ausfuehren'
);
reset role;
reset request.jwt.claims;
select * from finish();
rollback;
- Step 4: Tests ausführen
Run (Repo-Root): npx supabase test db
Expected: notification_outbox_rls_test.sql PASS (8/8), alle übrigen Tests weiterhin PASS.
- Step 5: Commit
git add supabase/migrations/20260903100000_notification_outbox.sql supabase/tests/notification_outbox_rls_test.sql
git commit -m "feat: notification_outbox Tabelle, Enqueue-Trigger und Batch-Claim-Funktion"
Task 2: config.ts — WhatsApp-Konfiguration aus env
Files:
- Create:
web/lib/notifications/config.ts - Create:
web/lib/notifications/config.test.ts
Interfaces:
-
Produces:
type WhatsAppConfig = { accessToken: string; phoneNumberId: string; recipient: string; templateName: string; templateLang: string; graphVersion: string }function getWhatsAppConfig(): WhatsAppConfig | null—null, wenn eine Pflichtvariable fehlt/leer ist.graphVersionfällt auf"v21.0"zurück.
-
Step 1: Fehlschlagenden Test schreiben
Datei web/lib/notifications/config.test.ts:
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { getWhatsAppConfig } from "./config";
const PFLICHT = {
WHATSAPP_ACCESS_TOKEN: "tok",
WHATSAPP_PHONE_NUMBER_ID: "123",
WHATSAPP_RECIPIENT: "4915100000000",
WHATSAPP_TEMPLATE_NAME: "neuer_auftrag",
WHATSAPP_TEMPLATE_LANG: "de",
};
let alt: Record<string, string | undefined>;
beforeEach(() => {
alt = {};
for (const k of [...Object.keys(PFLICHT), "WHATSAPP_GRAPH_VERSION"]) {
alt[k] = process.env[k];
delete process.env[k];
}
});
afterEach(() => {
for (const [k, v] of Object.entries(alt)) {
if (v === undefined) delete process.env[k];
else process.env[k] = v;
}
});
describe("getWhatsAppConfig", () => {
it("liefert die Config, wenn alle Pflichtvariablen gesetzt sind", () => {
Object.assign(process.env, PFLICHT);
expect(getWhatsAppConfig()).toEqual({
accessToken: "tok",
phoneNumberId: "123",
recipient: "4915100000000",
templateName: "neuer_auftrag",
templateLang: "de",
graphVersion: "v21.0",
});
});
it("uebernimmt WHATSAPP_GRAPH_VERSION, wenn gesetzt", () => {
Object.assign(process.env, PFLICHT, { WHATSAPP_GRAPH_VERSION: "v22.0" });
expect(getWhatsAppConfig()?.graphVersion).toBe("v22.0");
});
it.each(Object.keys(PFLICHT))("liefert null, wenn %s fehlt", (fehlt) => {
const teil = { ...PFLICHT } as Record<string, string>;
delete teil[fehlt];
Object.assign(process.env, teil);
expect(getWhatsAppConfig()).toBeNull();
});
it("liefert null, wenn eine Pflichtvariable leer ist", () => {
Object.assign(process.env, PFLICHT, { WHATSAPP_ACCESS_TOKEN: "" });
expect(getWhatsAppConfig()).toBeNull();
});
});
- Step 2: Test ausführen, Fehlschlag verifizieren
Run: cd web && npx vitest run lib/notifications/config.test.ts
Expected: FAIL — Modul ./config existiert nicht.
- Step 3:
config.tsimplementieren
Datei web/lib/notifications/config.ts:
export type WhatsAppConfig = {
accessToken: string;
phoneNumberId: string;
recipient: string;
templateName: string;
templateLang: string;
graphVersion: string;
};
// Liest die WhatsApp-Cloud-API-Konfiguration aus den Umgebungsvariablen.
// Gibt null zurueck, sobald eine Pflichtvariable fehlt oder leer ist -- der
// Dispatcher behandelt null als "Feature aus" und verarbeitet keine Zeilen.
export function getWhatsAppConfig(): WhatsAppConfig | null {
const accessToken = process.env.WHATSAPP_ACCESS_TOKEN;
const phoneNumberId = process.env.WHATSAPP_PHONE_NUMBER_ID;
const recipient = process.env.WHATSAPP_RECIPIENT;
const templateName = process.env.WHATSAPP_TEMPLATE_NAME;
const templateLang = process.env.WHATSAPP_TEMPLATE_LANG;
if (!accessToken || !phoneNumberId || !recipient || !templateName || !templateLang) {
return null;
}
return {
accessToken,
phoneNumberId,
recipient,
templateName,
templateLang,
graphVersion: process.env.WHATSAPP_GRAPH_VERSION || "v21.0",
};
}
- Step 4: Test ausführen, Erfolg verifizieren
Run: cd web && npx vitest run lib/notifications/config.test.ts
Expected: PASS, alle Fälle grün.
- Step 5: Commit
git add web/lib/notifications/config.ts web/lib/notifications/config.test.ts
git commit -m "feat: getWhatsAppConfig -- WhatsApp-Konfiguration aus env"
Task 3: whatsapp.ts — Template-Bau und Meta-API-Aufruf
Files:
- Create:
web/lib/notifications/whatsapp.ts - Create:
web/lib/notifications/whatsapp.test.ts
Interfaces:
-
Consumes:
WhatsAppConfigaus Task 2. -
Produces:
type AuftragErstelltPayload = { auftragsnummer: string; abholort_adresse: string; zielort_adresse: string; kennzeichen: string }type TemplateParameter = { type: "text"; text: string }type TemplateComponent = { type: "body"; parameters: TemplateParameter[] }function buildTemplateComponents(payload: AuftragErstelltPayload): TemplateComponent[]type SendErgebnis = { ok: true; messageId: string } | { ok: false; fehler: string }async function sendWhatsAppTemplate(cfg: WhatsAppConfig, payload: AuftragErstelltPayload): Promise<SendErgebnis>
-
Step 1: Fehlschlagenden Test schreiben
Datei web/lib/notifications/whatsapp.test.ts:
import { afterEach, describe, expect, it, vi } from "vitest";
import type { WhatsAppConfig } from "./config";
import { buildTemplateComponents, sendWhatsAppTemplate } from "./whatsapp";
const CFG: WhatsAppConfig = {
accessToken: "tok",
phoneNumberId: "PN1",
recipient: "4915100000000",
templateName: "neuer_auftrag",
templateLang: "de",
graphVersion: "v21.0",
};
const PAYLOAD = {
auftragsnummer: "26-09-03-0001",
abholort_adresse: "Startstr. 1, Teststadt",
zielort_adresse: "Zielstr. 2, Teststadt",
kennzeichen: "S-WA 42",
};
afterEach(() => {
vi.restoreAllMocks();
});
describe("buildTemplateComponents", () => {
it("baut genau einen body-Component mit vier text-Parametern in fester Reihenfolge", () => {
expect(buildTemplateComponents(PAYLOAD)).toEqual([
{
type: "body",
parameters: [
{ type: "text", text: "26-09-03-0001" },
{ type: "text", text: "Startstr. 1, Teststadt" },
{ type: "text", text: "Zielstr. 2, Teststadt" },
{ type: "text", text: "S-WA 42" },
],
},
]);
});
});
describe("sendWhatsAppTemplate", () => {
it("POSTet an die Meta-Graph-URL und gibt bei 2xx die message id zurueck", async () => {
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response(JSON.stringify({ messages: [{ id: "wamid.ABC" }] }), { status: 200 })
);
const res = await sendWhatsAppTemplate(CFG, PAYLOAD);
expect(res).toEqual({ ok: true, messageId: "wamid.ABC" });
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe("https://graph.facebook.com/v21.0/PN1/messages");
expect(init?.method).toBe("POST");
expect((init?.headers as Record<string, string>).Authorization).toBe("Bearer tok");
const body = JSON.parse(init?.body as string);
expect(body).toMatchObject({
messaging_product: "whatsapp",
to: "4915100000000",
type: "template",
template: { name: "neuer_auftrag", language: { code: "de" } },
});
expect(body.template.components[0].parameters).toHaveLength(4);
});
it("gibt bei nicht-2xx ok:false mit Status und Body zurueck", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response(JSON.stringify({ error: { message: "Template not found" } }), { status: 404 })
);
const res = await sendWhatsAppTemplate(CFG, PAYLOAD);
expect(res.ok).toBe(false);
expect(res).toMatchObject({ ok: false });
if (!res.ok) expect(res.fehler).toContain("404");
if (!res.ok) expect(res.fehler).toContain("Template not found");
});
it("gibt bei einer fetch-Exception ok:false zurueck", async () => {
vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("ECONNRESET"));
const res = await sendWhatsAppTemplate(CFG, PAYLOAD);
expect(res).toEqual({ ok: false, fehler: "ECONNRESET" });
});
});
- Step 2: Test ausführen, Fehlschlag verifizieren
Run: cd web && npx vitest run lib/notifications/whatsapp.test.ts
Expected: FAIL — Modul ./whatsapp existiert nicht.
- Step 3:
whatsapp.tsimplementieren
Datei web/lib/notifications/whatsapp.ts:
import type { WhatsAppConfig } from "./config";
export type AuftragErstelltPayload = {
auftragsnummer: string;
abholort_adresse: string;
zielort_adresse: string;
kennzeichen: string;
};
export type TemplateParameter = { type: "text"; text: string };
export type TemplateComponent = { type: "body"; parameters: TemplateParameter[] };
export type SendErgebnis = { ok: true; messageId: string } | { ok: false; fehler: string };
// Body-Parameter in fester Reihenfolge -- muss zu {{1}}..{{4}} im genehmigten
// Meta-Template "neuer_auftrag" passen: Auftragsnummer, Abholort, Zielort,
// Kennzeichen.
export function buildTemplateComponents(payload: AuftragErstelltPayload): TemplateComponent[] {
return [
{
type: "body",
parameters: [
{ type: "text", text: payload.auftragsnummer },
{ type: "text", text: payload.abholort_adresse },
{ type: "text", text: payload.zielort_adresse },
{ type: "text", text: payload.kennzeichen },
],
},
];
}
const TIMEOUT_MS = 10_000;
export async function sendWhatsAppTemplate(
cfg: WhatsAppConfig,
payload: AuftragErstelltPayload
): Promise<SendErgebnis> {
const url = `https://graph.facebook.com/${cfg.graphVersion}/${cfg.phoneNumberId}/messages`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
try {
const response = await fetch(url, {
method: "POST",
headers: {
Authorization: `Bearer ${cfg.accessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
messaging_product: "whatsapp",
to: cfg.recipient,
type: "template",
template: {
name: cfg.templateName,
language: { code: cfg.templateLang },
components: buildTemplateComponents(payload),
},
}),
signal: controller.signal,
});
const text = await response.text();
if (!response.ok) {
return { ok: false, fehler: `${response.status} ${text}`.slice(0, 500) };
}
const daten = JSON.parse(text) as { messages?: { id?: string }[] };
const messageId = daten.messages?.[0]?.id;
if (!messageId) {
return { ok: false, fehler: `2xx ohne message id: ${text}`.slice(0, 500) };
}
return { ok: true, messageId };
} catch (fehler) {
return { ok: false, fehler: fehler instanceof Error ? fehler.message : String(fehler) };
} finally {
clearTimeout(timer);
}
}
- Step 4: Test ausführen, Erfolg verifizieren
Run: cd web && npx vitest run lib/notifications/whatsapp.test.ts
Expected: PASS.
- Step 5: Commit
git add web/lib/notifications/whatsapp.ts web/lib/notifications/whatsapp.test.ts
git commit -m "feat: buildTemplateComponents und sendWhatsAppTemplate (Meta Cloud API)"
Task 4: dispatch.ts — Outbox-Batch verarbeiten
Files:
- Create:
web/lib/notifications/dispatch.ts - Create:
web/lib/notifications/dispatch.test.ts
Interfaces:
-
Consumes:
WhatsAppConfig(Task 2);sendWhatsAppTemplate,SendErgebnis,AuftragErstelltPayload(Task 3);public.claim_notification_batch(p_limit int)(Task 1) überadmin.rpc. -
Produces:
type OutboxRow = { id: string; event_type: string; payload: AuftragErstelltPayload; versuche: number; max_versuche: number }type VerarbeitungsErgebnis = { verarbeitet: number; gesendet: number; fehlgeschlagen: number; tot: number }type DispatchDeps = { sender?: typeof sendWhatsAppTemplate; jetzt?: () => Date }async function verarbeiteOutbox(admin: SupabaseClient, cfg: WhatsAppConfig, deps?: DispatchDeps): Promise<VerarbeitungsErgebnis>— genutzt von der Route (Task 5).
-
Step 1: Fehlschlagenden Test schreiben
Datei web/lib/notifications/dispatch.test.ts:
import { describe, expect, it, vi } from "vitest";
import type { WhatsAppConfig } from "./config";
import type { SendErgebnis } from "./whatsapp";
import { verarbeiteOutbox, type OutboxRow } from "./dispatch";
const CFG: WhatsAppConfig = {
accessToken: "tok",
phoneNumberId: "PN1",
recipient: "4915100000000",
templateName: "neuer_auftrag",
templateLang: "de",
graphVersion: "v21.0",
};
function row(over: Partial<OutboxRow> = {}): OutboxRow {
return {
id: over.id ?? "r1",
event_type: "auftrag_erstellt",
payload: {
auftragsnummer: "26-09-03-0001",
abholort_adresse: "A",
zielort_adresse: "B",
kennzeichen: "S-WA 42",
},
versuche: over.versuche ?? 0,
max_versuche: over.max_versuche ?? 5,
...over,
};
}
// Minimaler Fake des supabase-js-Clients: rpc() liefert die geclaimten Zeilen,
// from(...).update(...).eq(...) protokolliert die Updates.
function fakeAdmin(claimed: OutboxRow[]) {
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) => {
updates.push({ id, felder });
return { data: null, error: null };
},
}),
})),
};
return { client, updates };
}
describe("verarbeiteOutbox", () => {
it("markiert eine erfolgreich gesendete Zeile als sent mit wa_message_id", async () => {
const { client, updates } = fakeAdmin([row({ id: "r1" })]);
const sender = vi.fn<[], Promise<SendErgebnis>>(async () => ({ ok: true, messageId: "wamid.1" }));
const ergebnis = await verarbeiteOutbox(client as never, CFG, { sender });
expect(ergebnis).toEqual({ verarbeitet: 1, gesendet: 1, fehlgeschlagen: 0, tot: 0 });
expect(updates).toHaveLength(1);
expect(updates[0]).toMatchObject({
id: "r1",
felder: { status: "sent", wa_message_id: "wamid.1", 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({ id: "r1", versuche: 0, max_versuche: 5 })]);
const sender = vi.fn(async () => ({ ok: false, fehler: "404 Template not found" }));
const ergebnis = await verarbeiteOutbox(client as never, CFG, { sender, jetzt: () => jetzt });
expect(ergebnis).toEqual({ verarbeitet: 1, gesendet: 0, fehlgeschlagen: 1, tot: 0 });
expect(updates[0].felder).toMatchObject({ status: "failed", versuche: 1 });
// 2^1 = 2 Minuten
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({ id: "r1", versuche: 9, max_versuche: 20 })]);
const sender = vi.fn(async () => ({ ok: false, fehler: "500" }));
await verarbeiteOutbox(client as never, CFG, { sender, 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({ id: "r1", versuche: 4, max_versuche: 5 })]);
const sender = vi.fn(async () => ({ ok: false, fehler: "500" }));
const ergebnis = await verarbeiteOutbox(client as never, CFG, { sender });
expect(ergebnis).toEqual({ verarbeitet: 1, gesendet: 0, fehlgeschlagen: 0, tot: 1 });
expect(updates[0].felder).toMatchObject({ status: "dead", versuche: 5 });
});
it("macht nichts und ruft den sender nicht, wenn keine Zeilen faellig sind", async () => {
const { client, updates } = fakeAdmin([]);
const sender = vi.fn(async () => ({ ok: true, messageId: "x" }));
const ergebnis = await verarbeiteOutbox(client as never, CFG, { sender });
expect(ergebnis).toEqual({ verarbeitet: 0, gesendet: 0, fehlgeschlagen: 0, tot: 0 });
expect(sender).not.toHaveBeenCalled();
expect(updates).toHaveLength(0);
});
it("uebergibt p_limit 20 an die claim-Funktion", async () => {
const { client } = fakeAdmin([]);
await verarbeiteOutbox(client as never, CFG, { sender: vi.fn(async () => ({ ok: true, messageId: "x" })) });
expect(client.rpc).toHaveBeenCalledWith("claim_notification_batch", { p_limit: 20 });
});
});
- Step 2: Test ausführen, Fehlschlag verifizieren
Run: cd web && npx vitest run lib/notifications/dispatch.test.ts
Expected: FAIL — Modul ./dispatch existiert nicht.
- Step 3:
dispatch.tsimplementieren
Datei web/lib/notifications/dispatch.ts:
import type { SupabaseClient } from "@supabase/supabase-js";
import type { WhatsAppConfig } from "./config";
import { sendWhatsAppTemplate, type AuftragErstelltPayload } from "./whatsapp";
export type OutboxRow = {
id: string;
event_type: string;
payload: AuftragErstelltPayload;
versuche: number;
max_versuche: number;
};
export type VerarbeitungsErgebnis = {
verarbeitet: number;
gesendet: number;
fehlgeschlagen: number;
tot: number;
};
export type DispatchDeps = {
sender?: typeof sendWhatsAppTemplate;
jetzt?: () => Date;
};
const BATCH_LIMIT = 20;
const BACKOFF_MAX_MIN = 60;
// Uebernimmt einen Batch faelliger Outbox-Zeilen (atomar via
// claim_notification_batch) und sendet sie einzeln. Erfolg -> sent; Fehler ->
// failed mit exponentiellem Backoff, bzw. dead sobald max_versuche erreicht.
export async function verarbeiteOutbox(
admin: SupabaseClient,
cfg: WhatsAppConfig,
deps: DispatchDeps = {}
): Promise<VerarbeitungsErgebnis> {
const sender = deps.sender ?? sendWhatsAppTemplate;
const jetzt = deps.jetzt ?? (() => new Date());
const { data, error } = await admin.rpc("claim_notification_batch", { p_limit: BATCH_LIMIT });
if (error) {
throw new Error(`claim_notification_batch fehlgeschlagen: ${error.message}`);
}
const rows = (data ?? []) as OutboxRow[];
const ergebnis: VerarbeitungsErgebnis = {
verarbeitet: 0,
gesendet: 0,
fehlgeschlagen: 0,
tot: 0,
};
for (const row of rows) {
ergebnis.verarbeitet += 1;
const res = await sender(cfg, row.payload);
if (res.ok) {
await admin
.from("notification_outbox")
.update({
status: "sent",
wa_message_id: res.messageId,
letzter_fehler: null,
updated_at: jetzt().toISOString(),
})
.eq("id", row.id);
ergebnis.gesendet += 1;
continue;
}
const neueVersuche = row.versuche + 1;
const tot = neueVersuche >= row.max_versuche;
const backoffMin = Math.min(2 ** neueVersuche, BACKOFF_MAX_MIN);
const naechster = new Date(jetzt().getTime() + backoffMin * 60_000);
await admin
.from("notification_outbox")
.update({
status: tot ? "dead" : "failed",
versuche: neueVersuche,
naechster_versuch_ab: naechster.toISOString(),
letzter_fehler: res.fehler.slice(0, 500),
updated_at: jetzt().toISOString(),
})
.eq("id", row.id);
if (tot) ergebnis.tot += 1;
else ergebnis.fehlgeschlagen += 1;
}
return ergebnis;
}
- Step 4: Test ausführen, Erfolg verifizieren
Run: cd web && npx vitest run lib/notifications/dispatch.test.ts
Expected: PASS.
- Step 5: Commit
git add web/lib/notifications/dispatch.ts web/lib/notifications/dispatch.test.ts
git commit -m "feat: verarbeiteOutbox -- Outbox-Batch mit Retry/Backoff verarbeiten"
Task 5: Route POST /api/notifications/dispatch
Files:
- Create:
web/app/api/notifications/dispatch/route.ts - Create:
web/app/api/notifications/dispatch/route.test.ts
Interfaces:
-
Consumes:
getWhatsAppConfig(Task 2),verarbeiteOutbox(Task 4),createAdminClientausweb/lib/supabase/admin.ts(bestehend). -
Produces: HTTP-Endpunkt.
401ohne/mit falschem Bearer-Token;500, wennNOTIFICATION_DISPATCH_SECRETnicht gesetzt ist;200 { verarbeitet: 0, uebersprungen: true }, wenngetWhatsAppConfig()nullliefert; sonst200mit demVerarbeitungsErgebnis. -
Step 1: Fehlschlagenden Test schreiben
Datei web/app/api/notifications/dispatch/route.test.ts:
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/supabase/admin", () => ({ createAdminClient: vi.fn(() => ({})) }));
vi.mock("@/lib/notifications/config", () => ({ getWhatsAppConfig: vi.fn() }));
vi.mock("@/lib/notifications/dispatch", () => ({ verarbeiteOutbox: vi.fn() }));
import { getWhatsAppConfig } from "@/lib/notifications/config";
import { verarbeiteOutbox } from "@/lib/notifications/dispatch";
import { POST } from "./route";
const CFG = {
accessToken: "tok",
phoneNumberId: "PN1",
recipient: "4915100000000",
templateName: "neuer_auftrag",
templateLang: "de",
graphVersion: "v21.0",
};
function req(headers: Record<string, string> = {}) {
return new Request("http://localhost/api/notifications/dispatch", { method: "POST", headers });
}
let altSecret: string | undefined;
beforeEach(() => {
altSecret = process.env.NOTIFICATION_DISPATCH_SECRET;
process.env.NOTIFICATION_DISPATCH_SECRET = "geheim";
vi.mocked(getWhatsAppConfig).mockReset();
vi.mocked(verarbeiteOutbox).mockReset();
});
afterEach(() => {
if (altSecret === undefined) delete process.env.NOTIFICATION_DISPATCH_SECRET;
else process.env.NOTIFICATION_DISPATCH_SECRET = altSecret;
});
describe("POST /api/notifications/dispatch", () => {
it("antwortet 401 ohne Bearer-Token", async () => {
const res = await POST(req());
expect(res.status).toBe(401);
expect(verarbeiteOutbox).not.toHaveBeenCalled();
});
it("antwortet 401 bei falschem Token", async () => {
const res = await POST(req({ Authorization: "Bearer falsch" }));
expect(res.status).toBe(401);
});
it("antwortet 500, wenn NOTIFICATION_DISPATCH_SECRET nicht gesetzt ist", async () => {
delete process.env.NOTIFICATION_DISPATCH_SECRET;
const res = await POST(req({ Authorization: "Bearer geheim" }));
expect(res.status).toBe(500);
});
it("antwortet 200 uebersprungen, wenn keine WhatsApp-Config vorhanden ist", async () => {
vi.mocked(getWhatsAppConfig).mockReturnValue(null);
const res = await POST(req({ Authorization: "Bearer geheim" }));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ verarbeitet: 0, uebersprungen: true });
expect(verarbeiteOutbox).not.toHaveBeenCalled();
});
it("ruft verarbeiteOutbox und gibt dessen Ergebnis als 200 zurueck", async () => {
vi.mocked(getWhatsAppConfig).mockReturnValue(CFG);
vi.mocked(verarbeiteOutbox).mockResolvedValue({
verarbeitet: 2,
gesendet: 1,
fehlgeschlagen: 1,
tot: 0,
});
const res = await POST(req({ Authorization: "Bearer geheim" }));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ verarbeitet: 2, gesendet: 1, fehlgeschlagen: 1, tot: 0 });
expect(verarbeiteOutbox).toHaveBeenCalledOnce();
});
});
- Step 2: Test ausführen, Fehlschlag verifizieren
Run: cd web && npx vitest run app/api/notifications/dispatch/route.test.ts
Expected: FAIL — Modul ./route existiert nicht.
- Step 3:
route.tsimplementieren
Datei web/app/api/notifications/dispatch/route.ts:
import { NextResponse } from "next/server";
import { timingSafeEqual } from "crypto";
import { createAdminClient } from "@/lib/supabase/admin";
import { getWhatsAppConfig } from "@/lib/notifications/config";
import { verarbeiteOutbox } from "@/lib/notifications/dispatch";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
function sichererVergleich(a: string, b: string): boolean {
const bufA = Buffer.from(a);
const bufB = Buffer.from(b);
if (bufA.length !== bufB.length) return false;
return timingSafeEqual(bufA, bufB);
}
export async function POST(request: Request): Promise<Response> {
const secret = process.env.NOTIFICATION_DISPATCH_SECRET;
if (!secret) {
console.error("[notifications] NOTIFICATION_DISPATCH_SECRET nicht gesetzt");
return new NextResponse("Fehlkonfiguration", { status: 500 });
}
const auth = request.headers.get("authorization") ?? "";
const token = auth.startsWith("Bearer ") ? auth.slice(7) : "";
if (!token || !sichererVergleich(token, secret)) {
return new NextResponse("Unauthorized", { status: 401 });
}
const cfg = getWhatsAppConfig();
if (!cfg) {
console.warn("[notifications] WhatsApp nicht konfiguriert – Outbox wird nicht verarbeitet");
return NextResponse.json({ verarbeitet: 0, uebersprungen: true });
}
const ergebnis = await verarbeiteOutbox(createAdminClient(), cfg);
return NextResponse.json(ergebnis);
}
- Step 4: Test ausführen, Erfolg verifizieren
Run: cd web && npx vitest run app/api/notifications/dispatch/route.test.ts
Expected: PASS.
- Step 5: Volle Suite + Typecheck
Run: cd web && npx vitest run && npx tsc --noEmit
Expected: Alle Tests grün, keine Typfehler.
- Step 6: Commit
git add web/app/api/notifications/dispatch/route.ts web/app/api/notifications/dispatch/route.test.ts
git commit -m "feat: POST /api/notifications/dispatch -- Outbox-Dispatch-Route mit Shared-Secret"
Task 6: Migration — pg_cron / pg_net + geplanter Dispatch-Aufruf
Files:
- Create:
supabase/migrations/20260903101000_notification_dispatch_cron.sql
Interfaces:
-
Consumes: nichts aus früheren Tasks direkt; verweist inhaltlich auf die Route aus Task 5.
-
Produces: Cron-Job
notification-dispatchincron.job, der minütlich pernet.http_postcurrent_setting('app.notification_dispatch_url', true)aufruft (inert, solange das Setting leer/ungesetzt ist). -
Step 1: Migration schreiben
Datei supabase/migrations/20260903101000_notification_dispatch_cron.sql:
-- Minuetlicher Anstoss der Dispatch-Route. URL und Secret stehen bewusst
-- NICHT hier (umgebungsabhaengig, kein Secret in Git), sondern in den
-- DB-Settings app.notification_dispatch_url / app.notification_dispatch_secret,
-- die pro Stack out-of-band gesetzt werden. Ist die URL leer/ungesetzt (z.B.
-- lokaler CLI-Dev-Stack), verhindert die where-Bedingung jeden http_post --
-- der Job existiert dann, tut aber nichts.
create extension if not exists pg_cron;
create extension if not exists pg_net;
select cron.schedule(
'notification-dispatch',
'* * * * *',
$$
select net.http_post(
url := current_setting('app.notification_dispatch_url', true),
headers := jsonb_build_object(
'Content-Type', 'application/json',
'Authorization', 'Bearer ' || current_setting('app.notification_dispatch_secret', true)),
body := '{}'::jsonb)
where coalesce(current_setting('app.notification_dispatch_url', true), '') <> ''
$$
);
- Step 2: Migration anwenden
Run (Repo-Root): npx supabase db reset
Expected: Läuft durch ohne Fehler (create extension für pg_cron/pg_net gelingt im
Supabase-Image; cron.schedule legt den Job an).
- Step 3: Job-Anlage verifizieren
Run (Repo-Root):
docker exec -i supabase_db_fundament-auth-rollen psql -U postgres -d postgres \
-c "select jobname, schedule, active from cron.job where jobname = 'notification-dispatch';"
Expected: genau eine Zeile, schedule = '* * * * *', active = t.
- Step 4: Bestehende Suite bleibt grün (Regressionscheck)
Run (Repo-Root): npx supabase test db
Expected: alle Tests PASS (die neue Migration ändert keine Policy).
- Step 5: Commit
git add supabase/migrations/20260903101000_notification_dispatch_cron.sql
git commit -m "feat: pg_cron-Job stoesst minuetlich die Dispatch-Route an"
Task 7: Konfiguration verdrahten, dokumentieren + konsolidierte Live-Verifikation
Files:
- Modify:
web/.env.local.example - Modify:
docker-compose.yaml(web-Service:environment:) - Modify:
.claude/skills/rebuild-master-stack/SKILL.md
Interfaces:
-
Consumes: die
env-Namen aus Task 2 (WHATSAPP_*) und Task 5 (NOTIFICATION_DISPATCH_SECRET), die Settings aus Task 6 (app.notification_dispatch_url/_secret). -
Produces: keine Code-Schnittstelle — dokumentierte/verdrahtete Konfiguration.
-
Step 1:
web/.env.local.exampleerweitern
Ans Ende von web/.env.local.example anhängen:
# --- WhatsApp-Benachrichtigung (Meta WhatsApp Cloud API) ---
# Fehlt eine der folgenden fuenf Pflichtvariablen, ist das Feature "aus":
# die Dispatch-Route antwortet dann 200 { uebersprungen: true } und verschickt
# nichts. Werte stammen aus dem Meta Business Manager (WhatsApp > API-Setup).
WHATSAPP_ACCESS_TOKEN=
WHATSAPP_PHONE_NUMBER_ID=
# Feste Empfaenger-Sammelnummer, E.164 ohne fuehrendes "+" (z.B. 4915112345678).
WHATSAPP_RECIPIENT=
# Name + Sprache des genehmigten Message-Templates.
WHATSAPP_TEMPLATE_NAME=neuer_auftrag
WHATSAPP_TEMPLATE_LANG=de
# Optional, Default v21.0.
WHATSAPP_GRAPH_VERSION=
# Shared Secret fuer den Aufruf des pg_cron-Jobs an POST
# /api/notifications/dispatch. MUSS mit dem DB-Setting
# app.notification_dispatch_secret uebereinstimmen (siehe unten).
NOTIFICATION_DISPATCH_SECRET=
- Step 2:
docker-compose.yamlerweitern
Im web-Service, im environment:-Block (nach SUPABASE_SERVICE_ROLE_KEY:), anfügen:
# WhatsApp-Benachrichtigung -- Werte aus der Root-.env. Fehlt eine der
# fuenf WHATSAPP_*-Pflichtvariablen, ueberspringt der Dispatcher sauber.
WHATSAPP_ACCESS_TOKEN: ${WHATSAPP_ACCESS_TOKEN}
WHATSAPP_PHONE_NUMBER_ID: ${WHATSAPP_PHONE_NUMBER_ID}
WHATSAPP_RECIPIENT: ${WHATSAPP_RECIPIENT}
WHATSAPP_TEMPLATE_NAME: ${WHATSAPP_TEMPLATE_NAME}
WHATSAPP_TEMPLATE_LANG: ${WHATSAPP_TEMPLATE_LANG}
WHATSAPP_GRAPH_VERSION: ${WHATSAPP_GRAPH_VERSION}
# Muss mit dem DB-Setting app.notification_dispatch_secret uebereinstimmen.
NOTIFICATION_DISPATCH_SECRET: ${NOTIFICATION_DISPATCH_SECRET}
- Step 3:
rebuild-master-stack-Skill um den Settings-Schritt ergänzen
In .claude/skills/rebuild-master-stack/SKILL.md, in Schritt 5 (nach dem Anwenden fehlender
Migrationen), diesen Absatz anfügen:
Enthielten die neuen Migrationen einen `pg_cron`-Job, der die App aufruft
(z.B. `notification-dispatch`), zusätzlich die beiden DB-Settings setzen, die
die Migration bewusst nicht enthält:
```bash
docker exec -i aushilfsfahrer-db-1 psql -U postgres -d postgres -c \
"alter database postgres set app.notification_dispatch_url = 'http://web:3000/api/notifications/dispatch';"
docker exec -i aushilfsfahrer-db-1 psql -U postgres -d postgres -c \
"alter database postgres set app.notification_dispatch_secret = '<Wert von NOTIFICATION_DISPATCH_SECRET aus der Root-.env>';"
Danach greifen neue Verbindungen die Settings auf; der Cron-Job ruft ab der
nächsten Minute POST /api/notifications/dispatch auf.
- [ ] **Step 4: Typecheck + volle Suiten (nichts darf gebrochen sein)**
Run: `cd web && npx tsc --noEmit && npx vitest run`
Run (Repo-Root): `npx supabase db reset && npx supabase test db`
Expected: alles grün.
- [ ] **Step 5: Commit**
```bash
git add web/.env.local.example docker-compose.yaml .claude/skills/rebuild-master-stack/SKILL.md
git commit -m "chore: env-Doku und docker-compose fuer WhatsApp-Benachrichtigung, rebuild-master-stack-Hinweis"
- Step 6: Konsolidierte Live-Verifikation (Controller, nicht Implementer)
Voraussetzung: lokaler CLI-Dev-Stack läuft, ein Dev-Server der web-App zeigt auf diesen
Stack (web/.env.local mit NEXT_PUBLIC_SUPABASE_URL=http://127.0.0.1:54321), und
NOTIFICATION_DISPATCH_SECRET ist im Dev-Server-env gesetzt.
-
Enqueue: Auftrag über die UI anlegen (oder als Service-Role direkt in
auftraegeinserten). Prüfen:docker exec -i supabase_db_fundament-auth-rollen psql -U postgres -d postgres \ -c "select status, event_type, payload from notification_outbox order by created_at desc limit 1;"Erwartet: eine
pending-Zeile,event_type = auftrag_erstellt,payloadmit den vier Schlüsseln. -
Auth der Route:
curl -s -o /dev/null -w "%{http_code}\n" -X POST http://localhost:<port>/api/notifications/dispatch curl -s -o /dev/null -w "%{http_code}\n" -X POST -H "Authorization: Bearer falsch" \ http://localhost:<port>/api/notifications/dispatchErwartet: beide
401. -
Config aus: ohne gesetzte
WHATSAPP_*-Variablen:curl -s -X POST -H "Authorization: Bearer <secret>" \ http://localhost:<port>/api/notifications/dispatchErwartet:
200 {"verarbeitet":0,"uebersprungen":true}, Outbox-Zeile bleibtpending. -
Fehlerpfad mit Backoff:
WHATSAPP_*mit gültiger Form aber falschemWHATSAPP_ACCESS_TOKENsetzen, Dev-Server neu starten, Route erneut per curl aufrufen. Erwartet: Antwort{"verarbeitet":1,"gesendet":0,"fehlgeschlagen":1,"tot":0}; die Outbox-Zeile istfailed,versuche = 1,naechster_versuch_abin der Zukunft,letzter_fehlerenthält den Meta-Fehlertext. Route 5× auslösen (jeweilsnaechster_versuch_abper SQL aufnow()zurücksetzen) → Zeile wirddeadbeiversuche = 5. -
Cron-Guard: ohne gesetztes
app.notification_dispatch_urlim CLI-Dev-Stack prüfen, dass der Job nichts tut:docker exec -i supabase_db_fundament-auth-rollen psql -U postgres -d postgres \ -c "select count(*) from cron.job_run_details d join cron.job j using (jobid) where j.jobname = 'notification-dispatch' and d.status = 'failed';"Erwartet:
0(derwhere-Guard verhindert denhttp_post, keine Fehlläufe). -
Echte WhatsApp-Zustellung: nur manuell, sobald das Meta-Template
neuer_auftraggenehmigt und die Produktions-envgesetzt ist — nicht Teil dieser Verifikation.
Self-Review-Notizen
- Spec-Abdeckung:
- Spec §1 (Datenmodell: Tabelle, Status-Semantik, RLS, Trigger) → Task 1. Die
Batch-Claim-Funktion
claim_notification_batchist eine Implementierungs-Konkretisierung von Spec §3 Schritt 4 („select … dann status='sending'") — alsSECURITY DEFINER-SQL mitfor update skip lockedfür Atomarität statt zweiersupabase-js-Aufrufe. - Spec §2 (Konfiguration,
getWhatsAppConfig,null= aus) → Task 2 (Logik) + Task 7 (.env.local.example,docker-compose.yaml). - Spec §3 (Dispatch-Route: Auth 401/500, Config-null → 200 skip, Batch, Meta-Aufruf,
sent/failed+Backoff/dead, Moduleconfig/whatsapp/dispatch) → Tasks 3 (whatsapp.ts), 4 (dispatch.ts), 5 (route.ts).runtime="nodejs"+dynamic="force-dynamic"in Task 5 Step 3. - Spec §4 (
pg_cron/pg_net,current_setting, kein Secret in der Migration,where-Guard, Master-Stack-Schritt inrebuild-master-stack) → Task 6 + Task 7 Step 3. - Spec §5 (Vitest whatsapp/config/dispatch/route; pgTAP RLS + Trigger legt genau eine Zeile an; Live-Verifikation) → Tests in Tasks 2–5, pgTAP in Task 1, Live-Verifikation in Task 7 Step 6.
- Spec §6 (Voraussetzungen außerhalb des Codes) → keine Tasks (Betreiber-Aufgabe), in Task 7
Step 1 als Kommentar in
.env.local.examplereferenziert. - Spec §7 (Out of Scope) → keine Tasks, wie vorgesehen.
- Spec §1 (Datenmodell: Tabelle, Status-Semantik, RLS, Trigger) → Task 1. Die
Batch-Claim-Funktion
- Platzhalter-Scan: keine TBD/TODO; alle Code- und SQL-Blöcke vollständig.
<port>und<secret>in Task 7 Step 6 sind bewusste Laufzeit-Werte der manuellen Verifikation, kein Implementierungs-Platzhalter. - Typ-Konsistenz geprüft:
WhatsAppConfig(Task 2) → identisch konsumiert in Tasks 3/4/5.AuftragErstelltPayload(Task 3) →OutboxRow.payload(Task 4) →payload-Spalte der Tabelle (Task 1, vier Schlüsselauftragsnummer/abholort_adresse/zielort_adresse/kennzeichen).SendErgebnis(Task 3) → Rückgabe vondeps.senderin Task 4.VerarbeitungsErgebnis(Task 4) → Response-Body der Route (Task 5) und der Vitest-Assertions.claim_notification_batch(p_limit int)(Task 1) →admin.rpc("claim_notification_batch", { p_limit: 20 })(Task 4).getWhatsAppConfig/verarbeiteOutbox/createAdminClient(Tasks 2/4/bestehend) → Importe in Task 5. - Migrations-Reihenfolge:
20260903100000(Tabelle + Funktion + Trigger) vor20260903101000(Cron). Der Cron-Job hat keine harte DB-Abhängigkeit zur Tabelle, aber die fachliche Reihenfolge ist so korrekt.