forked from fahrPool/fahrPool
Merge feature/whatsapp-benachrichtigung: WhatsApp-Benachrichtigung bei neuem Auftrag
- notification_outbox (transaktionale Outbox) + AFTER-INSERT-Trigger auf auftraege
- SECURITY DEFINER claim_notification_batch (FOR UPDATE SKIP LOCKED, 15-min stale-reclaim)
- web/lib/notifications/{config,whatsapp,dispatch}.ts + POST /api/notifications/dispatch (Shared Secret)
- pg_cron/pg_net-Job stoesst die Route minuetlich an; URL/Secret aus DB-Settings, nicht in der Migration
- Middleware nimmt /api/notifications/dispatch vom Session-Gate aus
- Feature ist 'aus' ohne WHATSAPP_*-env: Route antwortet 200 { uebersprungen: true }
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Dimk8Jo64b4wULp2yAzSNh
This commit is contained in:
commit
ff33b681e3
|
|
@ -48,4 +48,18 @@ The user granted standing permission (2026-08-19) to run this proactively after
|
|||
docker exec -i aushilfsfahrer-db-1 psql -U postgres -d postgres -c "insert into supabase_migrations.schema_migrations (version) values ('<version>') on conflict (version) do nothing;"
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
Report the admin login URL/credentials back to the user once verified (`admin@aushilfsfahrer.local` / `Admin123!`, or the current password — see the `supabase-local-dev` skill if it's been reset).
|
||||
|
|
|
|||
13
.env.example
13
.env.example
|
|
@ -26,3 +26,16 @@ STUDIO_PORT=8082
|
|||
# Muss von aussen erreichbar sein (Browser!), nicht der interne Docker-Hostname:
|
||||
NEXT_PUBLIC_SUPABASE_URL=http://localhost:8000
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=
|
||||
|
||||
# --- WhatsApp-Benachrichtigung (Meta WhatsApp Cloud API) ---
|
||||
# Fehlt eine der fuenf Pflichtvariablen, ist das Feature "aus": die
|
||||
# Dispatch-Route antwortet dann 200 { uebersprungen: true } und sendet nichts.
|
||||
WHATSAPP_ACCESS_TOKEN=
|
||||
WHATSAPP_PHONE_NUMBER_ID=
|
||||
WHATSAPP_RECIPIENT=
|
||||
WHATSAPP_TEMPLATE_NAME=neuer_auftrag
|
||||
WHATSAPP_TEMPLATE_LANG=de
|
||||
WHATSAPP_GRAPH_VERSION=
|
||||
# MUSS mit dem DB-Setting app.notification_dispatch_secret uebereinstimmen
|
||||
# (siehe .claude/skills/rebuild-master-stack/SKILL.md).
|
||||
NOTIFICATION_DISPATCH_SECRET=
|
||||
|
|
|
|||
|
|
@ -181,3 +181,13 @@ services:
|
|||
# denselben Wert, den kong/auth/rest bereits als SERVICE_KEY bekommen
|
||||
# (siehe SERVICE_ROLE_KEY in der Root-.env).
|
||||
SUPABASE_SERVICE_ROLE_KEY: ${SERVICE_ROLE_KEY}
|
||||
# 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}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,94 @@
|
|||
-- 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;
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
-- 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. Gleiches gilt, solange
|
||||
-- app.notification_dispatch_url ODER app.notification_dispatch_secret leer ist.
|
||||
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), '') <> ''
|
||||
and coalesce(current_setting('app.notification_dispatch_secret', true), '') <> ''
|
||||
$$
|
||||
);
|
||||
|
|
@ -0,0 +1,159 @@
|
|||
begin;
|
||||
select plan(11);
|
||||
|
||||
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"}';
|
||||
-- 2-arg throws_ok(sql, sqlstate): die 3-arg-Form (sql, sqlstate, description)
|
||||
-- kollidiert mit pgTAPs throws_ok(sql, errcode, errmsg)-Signatur und wuerde die
|
||||
-- Beschreibung als erwartete Fehlermeldung interpretieren. Getestet wird
|
||||
-- unveraendert: authenticated laeuft in SQLSTATE 42501 (insufficient_privilege).
|
||||
select throws_ok(
|
||||
$$ select public.claim_notification_batch(5) $$,
|
||||
'42501'
|
||||
);
|
||||
|
||||
reset role;
|
||||
reset request.jwt.claims;
|
||||
|
||||
-- 5) claim_notification_batch waehlt genau die faelligen Zeilen aus.
|
||||
-- Zuerst die vom Enqueue-Trigger oben angelegte Zeile entfernen, damit die
|
||||
-- erwartete Ergebnismenge exakt ist (als postgres, RLS-umgehend).
|
||||
delete from public.notification_outbox
|
||||
where auftrag_id = 'c4000000-0000-0000-0000-00000000000a';
|
||||
|
||||
insert into public.notification_outbox
|
||||
(id, event_type, status, payload, naechster_versuch_ab, updated_at)
|
||||
values
|
||||
-- faellig: pending, Zeitpunkt erreicht
|
||||
('c5000000-0000-0000-0000-000000000001', 'auftrag_erstellt', 'pending', '{}'::jsonb,
|
||||
now() - interval '1 minute', now()),
|
||||
-- nicht faellig: failed, Backoff noch in der Zukunft
|
||||
('c5000000-0000-0000-0000-000000000002', 'auftrag_erstellt', 'failed', '{}'::jsonb,
|
||||
now() + interval '1 hour', now()),
|
||||
-- nicht reclaimt: sending, erst vor 2 Minuten uebernommen
|
||||
('c5000000-0000-0000-0000-000000000003', 'auftrag_erstellt', 'sending', '{}'::jsonb,
|
||||
now(), now() - interval '2 minutes'),
|
||||
-- reclaimt: sending, seit 20 Minuten haengengeblieben
|
||||
('c5000000-0000-0000-0000-000000000004', 'auftrag_erstellt', 'sending', '{}'::jsonb,
|
||||
now(), now() - interval '20 minutes');
|
||||
|
||||
select results_eq(
|
||||
$$ select id::text from public.claim_notification_batch(10) order by id $$,
|
||||
$$ values ('c5000000-0000-0000-0000-000000000001'::text),
|
||||
('c5000000-0000-0000-0000-000000000004') $$,
|
||||
'claim_notification_batch liefert genau die faellige pending- und die abgestandene sending-Zeile'
|
||||
);
|
||||
|
||||
-- 6) Write-RLS: authenticated (disponent) darf nicht in die Outbox schreiben.
|
||||
set local role authenticated;
|
||||
set local request.jwt.claims to '{"sub": "c2222222-2222-2222-2222-222222222222", "role": "authenticated"}';
|
||||
|
||||
-- 2-arg throws_ok(sql, sqlstate): siehe Kommentar bei Assertion 4 -- die 3-arg-Form
|
||||
-- wuerde die Beschreibung als erwartete Fehlermeldung interpretieren. Geprueft wird
|
||||
-- nur, dass der INSERT in SQLSTATE 42501 (RLS: keine INSERT-Policy) laeuft.
|
||||
select throws_ok(
|
||||
$$ insert into public.notification_outbox (event_type, payload) values ('x', '{}'::jsonb) $$,
|
||||
'42501'
|
||||
);
|
||||
|
||||
-- RLS ohne UPDATE-Policy wirft nicht, sondern trifft schlicht 0 Zeilen: das
|
||||
-- UPDATE laeuft durch, aendert aber keine Zeile. Danach (als postgres) pruefen,
|
||||
-- dass wirklich keine der vier Zeilen auf 'sent' gekippt ist. (Ein
|
||||
-- data-modifying UPDATE laesst sich nicht in einen Sub-SELECT/CTE-Ausdruck
|
||||
-- packen, daher als eigenes Statement + separate Assertion.)
|
||||
update public.notification_outbox set status = 'sent' where true;
|
||||
|
||||
reset role;
|
||||
reset request.jwt.claims;
|
||||
|
||||
select is(
|
||||
(select count(*)::int from public.notification_outbox where status = 'sent'),
|
||||
0,
|
||||
'authenticated-UPDATE auf notification_outbox aendert keine Zeile (keine Write-Policy)'
|
||||
);
|
||||
|
||||
select * from finish();
|
||||
rollback;
|
||||
|
|
@ -10,3 +10,21 @@ SUPABASE_INTERNAL_URL=http://localhost:8000
|
|||
# `npx supabase status` (Repo-Root) auslesen ("service_role key"). Fuer den
|
||||
# Docker-Compose-Master-Stack ist es SERVICE_ROLE_KEY aus der Root-.env.
|
||||
SUPABASE_SERVICE_ROLE_KEY=
|
||||
|
||||
# --- 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=
|
||||
|
|
|
|||
|
|
@ -0,0 +1,95 @@
|
|||
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;
|
||||
let fehlerSpy: ReturnType<typeof vi.spyOn>;
|
||||
let warnSpy: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
beforeEach(() => {
|
||||
altSecret = process.env.NOTIFICATION_DISPATCH_SECRET;
|
||||
process.env.NOTIFICATION_DISPATCH_SECRET = "geheim";
|
||||
vi.mocked(getWhatsAppConfig).mockReset();
|
||||
vi.mocked(verarbeiteOutbox).mockReset();
|
||||
fehlerSpy = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (altSecret === undefined) delete process.env.NOTIFICATION_DISPATCH_SECRET;
|
||||
else process.env.NOTIFICATION_DISPATCH_SECRET = altSecret;
|
||||
fehlerSpy.mockRestore();
|
||||
warnSpy.mockRestore();
|
||||
});
|
||||
|
||||
describe("POST /api/notifications/dispatch", () => {
|
||||
// Muss zuerst laufen: route.ts drosselt den Missing-Secret-Log ueber ein
|
||||
// modul-lokales Flag, das nach dem ersten Treffer gesetzt bleibt.
|
||||
it("antwortet 500 (JSON), wenn NOTIFICATION_DISPATCH_SECRET nicht gesetzt ist, und loggt nur einmal", async () => {
|
||||
delete process.env.NOTIFICATION_DISPATCH_SECRET;
|
||||
|
||||
const res1 = await POST(req({ Authorization: "Bearer geheim" }));
|
||||
expect(res1.status).toBe(500);
|
||||
expect(await res1.json()).toEqual({ fehler: "Fehlkonfiguration" });
|
||||
|
||||
const res2 = await POST(req({ Authorization: "Bearer geheim" }));
|
||||
expect(res2.status).toBe(500);
|
||||
|
||||
// Log-Drossel: trotz zweier Aufrufe nur ein console.error.
|
||||
expect(fehlerSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("antwortet 401 (JSON) ohne Bearer-Token", async () => {
|
||||
const res = await POST(req());
|
||||
expect(res.status).toBe(401);
|
||||
expect(await res.json()).toEqual({ fehler: "Unauthorized" });
|
||||
expect(verarbeiteOutbox).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("antwortet 401 (JSON) bei falschem Token", async () => {
|
||||
const res = await POST(req({ Authorization: "Bearer falsch" }));
|
||||
expect(res.status).toBe(401);
|
||||
expect(await res.json()).toEqual({ fehler: "Unauthorized" });
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
import { NextResponse } from "next/server";
|
||||
import { timingSafeEqual } from "node: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";
|
||||
|
||||
// Verhindert Log-Flut, wenn ein fehlkonfigurierter Cron diese Route minuetlich
|
||||
// trifft: der 500-Fall wird nur einmal pro Prozess geloggt.
|
||||
let secretFehltGemeldet = false;
|
||||
|
||||
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) {
|
||||
if (!secretFehltGemeldet) {
|
||||
console.error("[notifications] NOTIFICATION_DISPATCH_SECRET nicht gesetzt");
|
||||
secretFehltGemeldet = true;
|
||||
}
|
||||
return NextResponse.json({ fehler: "Fehlkonfiguration" }, { status: 500 });
|
||||
}
|
||||
|
||||
const auth = request.headers.get("authorization") ?? "";
|
||||
const token = auth.startsWith("Bearer ") ? auth.slice(7) : "";
|
||||
if (!token || !sichererVergleich(token, secret)) {
|
||||
return NextResponse.json({ fehler: "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 });
|
||||
}
|
||||
|
||||
try {
|
||||
const ergebnis = await verarbeiteOutbox(createAdminClient(), cfg);
|
||||
return NextResponse.json(ergebnis);
|
||||
} catch (e) {
|
||||
console.error("[notifications] Dispatch fehlgeschlagen:", e);
|
||||
return NextResponse.json({ fehler: "Dispatch fehlgeschlagen" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
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();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
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",
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,149 @@
|
|||
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. 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 };
|
||||
}
|
||||
|
||||
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(async (): Promise<SendErgebnis> => ({ 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 (): Promise<SendErgebnis> => ({ 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 (): Promise<SendErgebnis> => ({ 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 (): Promise<SendErgebnis> => ({ 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 (): Promise<SendErgebnis> => ({ 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 (): Promise<SendErgebnis> => ({ ok: true, messageId: "x" })),
|
||||
});
|
||||
expect(client.rpc).toHaveBeenCalledWith("claim_notification_batch", { p_limit: 20 });
|
||||
});
|
||||
|
||||
it("macht nach erfolgreicher Sendung einen Poison-Write auf dead, wenn das sent-Update fehlschlaegt", async () => {
|
||||
const fehlerSpy = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
// Erster Update-Aufruf (sent) schlaegt fehl, zweiter (dead) geht durch.
|
||||
const { client, updates } = fakeAdmin([row({ id: "r1" })], [{ message: "boom" }, null]);
|
||||
const sender = vi.fn(async (): Promise<SendErgebnis> => ({ ok: true, messageId: "wamid.1" }));
|
||||
|
||||
const ergebnis = await verarbeiteOutbox(client as never, CFG, { sender });
|
||||
|
||||
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 Zeile mit unbekanntem event_type auf dead, ohne den sender zu rufen", async () => {
|
||||
const fehlerSpy = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const { client, updates } = fakeAdmin([row({ id: "r1", event_type: "irgendwas_anderes" })]);
|
||||
const sender = vi.fn(async (): Promise<SendErgebnis> => ({ ok: true, messageId: "x" }));
|
||||
|
||||
const ergebnis = await verarbeiteOutbox(client as never, CFG, { sender });
|
||||
|
||||
expect(sender).not.toHaveBeenCalled();
|
||||
expect(ergebnis).toEqual({ verarbeitet: 1, gesendet: 0, fehlgeschlagen: 0, tot: 1 });
|
||||
expect(updates).toHaveLength(1);
|
||||
expect(updates[0].felder).toMatchObject({ status: "dead" });
|
||||
expect(String(updates[0].felder.letzter_fehler)).toContain("irgendwas_anderes");
|
||||
fehlerSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,142 @@
|
|||
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) {
|
||||
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;
|
||||
|
||||
if (row.event_type !== "auftrag_erstellt") {
|
||||
console.error(
|
||||
"[notifications] unbekannter 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;
|
||||
}
|
||||
|
||||
const res = await sender(cfg, row.payload);
|
||||
|
||||
if (res.ok) {
|
||||
const ok = await schreibe({
|
||||
status: "sent",
|
||||
wa_message_id: res.messageId,
|
||||
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 an Meta ok, aber Status-Update fehlgeschlagen - manuell pruefen",
|
||||
updated_at: nun.toISOString(),
|
||||
});
|
||||
}
|
||||
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(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) {
|
||||
// Status-Schreibvorgang gescheitert -> der laute Log oben ist das
|
||||
// Operator-Signal; die Zeile zaehlt als fehlgeschlagen (nicht tot).
|
||||
ergebnis.fehlgeschlagen += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (tot) ergebnis.tot += 1;
|
||||
else ergebnis.fehlgeschlagen += 1;
|
||||
}
|
||||
|
||||
return ergebnis;
|
||||
}
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
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" });
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { NextResponse, NextRequest } from "next/server";
|
||||
|
||||
// updateSession telefoniert normalerweise ueber das Netz zu Supabase
|
||||
// (supabase.auth.getUser()). Fuer einen schnellen, deterministischen Test
|
||||
// stubben wir es und pruefen nur, ob die Middleware es aufruft oder umgeht.
|
||||
vi.mock("@/lib/supabase/middleware", () => ({
|
||||
updateSession: vi.fn(),
|
||||
}));
|
||||
|
||||
import { updateSession } from "@/lib/supabase/middleware";
|
||||
import { middleware } from "@/middleware";
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(updateSession).mockReset();
|
||||
vi.mocked(updateSession).mockImplementation(async (request) => {
|
||||
const url = request.nextUrl.clone();
|
||||
url.pathname = "/login";
|
||||
return NextResponse.redirect(url);
|
||||
});
|
||||
});
|
||||
|
||||
describe("middleware", () => {
|
||||
it("laesst POST /api/notifications/dispatch ohne Session-Cookie ohne Redirect passieren", async () => {
|
||||
const request = new NextRequest("http://localhost/api/notifications/dispatch", {
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
const res = await middleware(request);
|
||||
|
||||
// Session-Gate (updateSession) darf fuer diese Route gar nicht laufen
|
||||
expect(updateSession).not.toHaveBeenCalled();
|
||||
// Kein 3xx-Redirect nach /login
|
||||
expect(res.status).toBe(200);
|
||||
const location = res.headers.get("location");
|
||||
expect(location === null || !location.endsWith("/login")).toBe(true);
|
||||
});
|
||||
|
||||
it("leitet GET /dashboard ohne Session-Cookie weiterhin auf /login um", async () => {
|
||||
const request = new NextRequest("http://localhost/dashboard", { method: "GET" });
|
||||
|
||||
const res = await middleware(request);
|
||||
|
||||
expect(updateSession).toHaveBeenCalledTimes(1);
|
||||
expect(res.status).toBeGreaterThanOrEqual(300);
|
||||
expect(res.status).toBeLessThan(400);
|
||||
expect(res.headers.get("location")).toMatch(/\/login$/);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,7 +1,13 @@
|
|||
import { type NextRequest } from "next/server";
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { updateSession } from "@/lib/supabase/middleware";
|
||||
|
||||
export async function middleware(request: NextRequest) {
|
||||
// Interne Endpunkte mit eigener Authentifizierung (Shared Secret) umgehen
|
||||
// das Supabase-Session-Gating -- der pg_cron-Aufruf an diese Route traegt
|
||||
// kein Session-Cookie.
|
||||
if (request.nextUrl.pathname === "/api/notifications/dispatch") {
|
||||
return NextResponse.next();
|
||||
}
|
||||
return await updateSession(request);
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue