diff --git a/web/lib/notifications/whatsapp.test.ts b/web/lib/notifications/whatsapp.test.ts new file mode 100644 index 0000000..00dff5e --- /dev/null +++ b/web/lib/notifications/whatsapp.test.ts @@ -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).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" }); + }); +}); diff --git a/web/lib/notifications/whatsapp.ts b/web/lib/notifications/whatsapp.ts new file mode 100644 index 0000000..e3e3d33 --- /dev/null +++ b/web/lib/notifications/whatsapp.ts @@ -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 { + 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); + } +}