diff --git a/src/app/admin/(panel)/anmeldung/actions.ts b/src/app/admin/(panel)/anmeldung/actions.ts deleted file mode 100644 index 15d278e..0000000 --- a/src/app/admin/(panel)/anmeldung/actions.ts +++ /dev/null @@ -1,39 +0,0 @@ -"use server"; -import { revalidatePath } from "next/cache"; -import { assertPermission, audit } from "@/lib/auth"; -import { fail, ok, type ActionResult } from "@/lib/action-result"; -import { getLoginProviders, isConfigured, saveLoginProviders, type LoginProviders } from "@/lib/social/config"; -import { isValidApplePrivateKey } from "@/lib/social/oauth"; - -const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim(); - -export async function saveLoginSettings(_prev: ActionResult, fd: FormData): Promise { - const user = await assertPermission("settings.edit"); - const current = await getLoginProviders(); - // Leere Geheimfelder behalten den gespeicherten Wert - const keep = (v: string, old: string) => (v ? v : old); - const privateKey = keep(str(fd, "applePrivateKey").replace(/\r\n/g, "\n"), current.apple.privateKey); - if (privateKey && !isValidApplePrivateKey(privateKey)) - return fail("Der Apple-Schlüssel lässt sich nicht lesen. Füge den ganzen Inhalt der .p8-Datei ein, mit den Zeilen BEGIN und END.", { applePrivateKey: "Ungültiger Schlüssel" }); - - const next: LoginProviders = { - google: { - enabled: fd.get("googleEnabled") === "on", - clientId: str(fd, "googleClientId"), - clientSecret: fd.get("googleClear") === "on" ? "" : keep(str(fd, "googleClientSecret"), current.google.clientSecret), - }, - apple: { - enabled: fd.get("appleEnabled") === "on", - servicesId: str(fd, "appleServicesId"), - teamId: str(fd, "appleTeamId").toUpperCase(), - keyId: str(fd, "appleKeyId").toUpperCase(), - privateKey: fd.get("appleClear") === "on" ? "" : privateKey, - }, - }; - if (next.google.enabled && !isConfigured("google", next)) return fail("Für Google brauchst du Client-ID und Client-Secret."); - if (next.apple.enabled && !isConfigured("apple", next)) return fail("Für Apple brauchst du Services-ID, Team-ID, Key-ID und den Schlüssel."); - await saveLoginProviders(next); - await audit(user, "Anmeldung mit Google/Apple geändert", `Google: ${next.google.enabled ? "an" : "aus"}, Apple: ${next.apple.enabled ? "an" : "aus"}`); - revalidatePath("/admin/anmeldung"); - return ok(); -} diff --git a/src/app/admin/(panel)/anmeldung/page.tsx b/src/app/admin/(panel)/anmeldung/page.tsx index bedf0aa..7c144ee 100644 --- a/src/app/admin/(panel)/anmeldung/page.tsx +++ b/src/app/admin/(panel)/anmeldung/page.tsx @@ -1,44 +1,6 @@ -import { requireAdmin } from "@/lib/auth"; -import { mask } from "@/lib/payments/credentials"; -import { callbackUrl, getLoginProviders, isConfigured } from "@/lib/social/config"; -import { Field, TextareaField } from "@/components/Field"; -import { AdminForm } from "@/components/admin/AdminForm"; -import { Card, PageHead, Pill, Switch } from "@/components/admin/ui"; -import { saveLoginSettings } from "./actions"; +import { redirect } from "next/navigation"; -export default async function LoginSettingsPage() { - await requireAdmin("settings.edit"); - const c = await getLoginProviders(); - const status = (p: "google" | "apple") => - !isConfigured(p, c) ? Nicht eingerichtet : c[p].enabled ? Aktiv : Aus; - const domain = new URL(callbackUrl("apple")).host; - return ( -
- - - - - - -
- In der Google Cloud Console unter APIs & Dienste → Anmeldedaten eine OAuth-Client-ID vom Typ „Webanwendung“ anlegen. Als autorisierte Weiterleitungs-URI eintragen: {callbackUrl("google")} -
- {c.google.clientSecret && } -
- - - -
- - -
- -
- Im Apple-Developer-Bereich unter Certificates, Identifiers & Profiles: eine Services-ID mit „Sign in with Apple“ anlegen, als Domain {domain} und als Return-URL {callbackUrl("apple")} eintragen. Danach unter Keys einen Schlüssel mit „Sign in with Apple“ erstellen und die .p8-Datei herunterladen. -
- {c.apple.privateKey && } -
-
-
- ); +// Die Einrichtung von Google und Apple ist nach „Verbindungen“ umgezogen +export default function LoginSettingsPage() { + redirect("/admin/verbindungen"); } diff --git a/src/app/admin/(panel)/dhl/actions.ts b/src/app/admin/(panel)/dhl/actions.ts index c2f76a2..a6c29c4 100644 --- a/src/app/admin/(panel)/dhl/actions.ts +++ b/src/app/admin/(panel)/dhl/actions.ts @@ -2,7 +2,7 @@ import { revalidatePath } from "next/cache"; import { assertPermission, audit } from "@/lib/auth"; import { fail, ok, type ActionResult } from "@/lib/action-result"; -import { getDhlConfig, saveDhlConfig, testConnection, type DhlConfig } from "@/lib/dhl"; +import { getDhlConfig, saveDhlConfig, type DhlConfig } from "@/lib/dhl"; const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim(); const grams = (fd: FormData, k: string, fallback: number) => { @@ -13,16 +13,15 @@ const grams = (fd: FormData, k: string, fallback: number) => { export async function saveDhl(_prev: ActionResult, fd: FormData): Promise { const user = await assertPermission("shipping.edit"); const current = await getDhlConfig(); - // Leere Geheimfelder behalten den gespeicherten Wert - const keep = (v: string, old: string) => (v ? v : old); const next: DhlConfig = { - enabled: fd.get("enabled") === "on", - sandbox: fd.get("sandbox") === "on", - apiKey: keep(str(fd, "apiKey"), current.apiKey), - username: str(fd, "username"), - password: keep(str(fd, "password"), current.password), - billingNational: str(fd, "billingNational").replace(/\s/g, ""), - billingInternational: str(fd, "billingInternational").replace(/\s/g, ""), + // Die Verbindung selbst wird unter Verbindungen gepflegt + enabled: current.enabled, + sandbox: current.sandbox, + apiKey: current.apiKey, + username: current.username, + password: current.password, + billingNational: current.billingNational, + billingInternational: current.billingInternational, shipperName: str(fd, "shipperName"), shipperStreet: str(fd, "shipperStreet"), shipperHouse: str(fd, "shipperHouse"), @@ -35,28 +34,9 @@ export async function saveDhl(_prev: ActionResult, fd: FormData): Promise = {}; - for (const k of ["billingNational", "billingInternational"] as const) { - if (next[k] && !/^\d{14}$/.test(next[k])) errors[k] = "14 Ziffern, z. B. 22222222220101"; - } - if (next.shipperZip && !/^\d{5}$/.test(next.shipperZip)) errors.shipperZip = "5 Ziffern"; - if (Object.keys(errors).length) return fail("Bitte prüfe die markierten Felder.", errors); - if (next.enabled && !next.apiKey) return fail("Zum Einschalten braucht DHL einen API-Schlüssel.", { apiKey: "Bitte eintragen" }); - if (next.enabled && !next.sandbox && (!next.username || !next.password || !next.billingNational)) { - return fail("Für den Live-Betrieb fehlen Benutzername, Passwort oder Abrechnungsnummer."); - } + if (next.shipperZip && !/^\d{5}$/.test(next.shipperZip)) return fail("Bitte prüfe die Postleitzahl.", { shipperZip: "5 Ziffern" }); await saveDhlConfig(next); - await audit(user, "DHL-Einstellungen geändert", `${next.enabled ? "an" : "aus"}, ${next.sandbox ? "Sandbox" : "Live"}`); + await audit(user, "DHL-Einstellungen geändert", "Absender und Pakete"); revalidatePath("/admin/dhl"); return ok("Gespeichert."); } - -export async function testDhl(_prev: ActionResult): Promise { - await assertPermission("shipping.edit"); - const r = await testConnection(await getDhlConfig()); - return r.ok ? ok(r.message) : fail(r.message); -} diff --git a/src/app/admin/(panel)/dhl/page.tsx b/src/app/admin/(panel)/dhl/page.tsx index 9302229..72c8db4 100644 --- a/src/app/admin/(panel)/dhl/page.tsx +++ b/src/app/admin/(panel)/dhl/page.tsx @@ -1,12 +1,11 @@ +import Link from "next/link"; import { requireAdmin } from "@/lib/auth"; import { getSettings } from "@/lib/settings"; import { canCreateLabels, getDhlConfig, splitStreet } from "@/lib/dhl"; -import { mask } from "@/lib/payments/credentials"; import { Field } from "@/components/Field"; import { AdminForm } from "@/components/admin/AdminForm"; -import { TestButton } from "@/components/admin/TestButton"; import { Card, PageHead, Pill, Switch } from "@/components/admin/ui"; -import { saveDhl, testDhl } from "./actions"; +import { saveDhl } from "./actions"; const kg = (g: number) => (g ? String(g / 1000).replace(".", ",") : ""); @@ -19,26 +18,14 @@ export default async function DhlPage() { const ready = canCreateLabels(c); return (
- + + Nicht eingerichtet : {c.sandbox ? "Sandbox" : "Live"}}> +

+ {ready ? "DHL ist verbunden. Labels erstellst du direkt in der Bestellung." : "Noch nicht verbunden."}{" "} + {ready ? "Verbindung ansehen" : "Jetzt einrichten"} +

+
- Nicht eingerichtet : {c.sandbox ? "Sandbox" : "Live"}} - > - - - -
- - -
-
- - -
- {(c.apiKey || c.password) && } -
@@ -63,9 +50,6 @@ export default async function DhlPage() { -
- -
); } diff --git a/src/app/admin/(panel)/verbindungen/[provider]/page.tsx b/src/app/admin/(panel)/verbindungen/[provider]/page.tsx new file mode 100644 index 0000000..db09634 --- /dev/null +++ b/src/app/admin/(panel)/verbindungen/[provider]/page.tsx @@ -0,0 +1,271 @@ +import { notFound } from "next/navigation"; +import { requireAdmin } from "@/lib/auth"; +import { getCredentials, mask } from "@/lib/payments/credentials"; +import { getDhlConfig } from "@/lib/dhl"; +import { appUrl, callbackUrl, getLoginProviders } from "@/lib/social/config"; +import { INTEGRATIONS, STRIPE_WEBHOOK_EVENTS, getStatuses, stripeWebhookUrl, type IntegrationKey, type TestResult } from "@/lib/integrations"; +import { dateFmt } from "@/lib/status"; +import { Field } from "@/components/Field"; +import { AdminForm, ConfirmButton } from "@/components/admin/AdminForm"; +import { Card, PageHead, Switch } from "@/components/admin/ui"; +import { TestButton } from "@/components/admin/TestButton"; +import { CopyValue } from "@/components/admin/CopyValue"; +import { KeyFileInput } from "@/components/admin/KeyFileInput"; +import { OpenLink, Step, Steps } from "@/components/admin/Setup"; +import { StatusPill } from "@/components/admin/IntegrationStatus"; +import { disconnect, retest, saveApple, saveDhlConnection, saveGoogle, savePaypal, saveStripe } from "../actions"; + +function LastTest({ t }: { t: TestResult | null }) { + if (!t) return null; + return ( +
+
+ {t.message} + Zuletzt geprüft: {dateFmt.format(new Date(t.at))} +
+
+ ); +} + +export default async function IntegrationSetup({ params }: { params: Promise<{ provider: string }> }) { + const { provider } = await params; + const meta = INTEGRATIONS.find((i) => i.key === provider); + if (!meta) notFound(); + await requireAdmin(meta.permission); + const status = (await getStatuses())[meta.key]; + const Wizard = WIZARDS[meta.key]; + return ( +
+ + + + + + {status.configured && ( +
+ + +
+ )} +
+ ); +} + +// ---------- Stripe ---------- + +async function StripeWizard({ ok }: { ok: boolean }) { + const c = (await getCredentials()).stripe; + return ( + + + + +

Falls du noch keins hast: kostenlos registrieren und im Dashboard „Konto aktivieren“ durchgehen (Firmendaten und Bankkonto für Auszahlungen). Zum Ausprobieren reicht der Testmodus, dann geht es auch ohne Aktivierung.

+ Bei Stripe registrieren +

Unter Zahlungsmethoden schaltest du ein, was Kunden nutzen dürfen: Karten, Apple Pay, Google Pay, Klarna, SEPA-Lastschrift.

+ Zahlungsmethoden öffnen +
+ +

Öffne die API-Schlüssel und klicke beim Geheimschlüssel auf „Anzeigen“. Er beginnt mit sk_live_. Für Testzahlungen nimm den Schlüssel aus dem Testmodus (sk_test_).

+ Live-Schlüssel + Test-Schlüssel + +
+ +

Damit Bestellungen automatisch auf „Bezahlt“ springen, auch bei SEPA und Klarna, braucht Stripe eine Rücksende-Adresse. Die richte ich beim Speichern selbst ein.

+ + {c.webhookSecret && } +
+ Lieber von Hand einrichten +
+ Webhooks öffnen + + + +
+
+
+ +

Ich prüfe den Schlüssel direkt bei Stripe. Danach schaltest du unter Zahlungsarten ein, was im Shop erscheinen soll.

+
+
+
+
+ ); +} + +// ---------- PayPal ---------- + +async function PaypalWizard({ ok }: { ok: boolean }) { + const c = (await getCredentials()).paypal; + const has = Boolean(c.clientId && c.clientSecret); + return ( + + + + +

Du brauchst ein PayPal-Geschäftskonto. Ein privates Konto lässt sich dort kostenlos umwandeln.

+ PayPal Business +
+ +
    +
  1. Im PayPal-Entwicklerbereich mit deinem Geschäftskonto anmelden.
  2. +
  3. Oben auf „Live“ stellen (oder „Sandbox“ zum Testen) und „Create App“ klicken.
  4. +
  5. Einen Namen eingeben, z. B. „Sanamare Shop“, Typ „Merchant“.
  6. +
  7. Client-ID und Secret kopieren und hier einfügen.
  8. +
+ Live-Apps + Sandbox-Apps + + +
+ +

Ob die Daten zu Live oder Sandbox gehören, erkenne ich selbst. Danach schaltest du PayPal unter Zahlungsarten ein.

+
+
+
+
+ ); +} + +// ---------- DHL ---------- + +async function DhlWizard({ ok }: { ok: boolean }) { + const c = await getDhlConfig(); + return ( + + + + +

Im Testmodus brauchst du nur den API-Schlüssel aus Schritt 2. Die Labels sind dann Muster und können nicht verschickt werden. Für echte Labels brauchst du ein DHL-Geschäftskundenkonto.

+ + DHL-Geschäftskunde werden +
+ +
    +
  1. Im DHL-Entwicklerportal kostenlos registrieren.
  2. +
  3. Unter „My Apps“ eine App anlegen und die APIs „Parcel DE Shipping (Post & Parcel Germany)“ und „Shipment Tracking – Unified“ auswählen.
  4. +
  5. Nach der Freigabe den „API Key“ der App kopieren.
  6. +
+ Registrieren + My Apps + +
+ +

Nur für echte Labels. Lege im Geschäftskundenportal unter Benutzerverwaltung einen Systembenutzer an und trag ihn hier ein. Im Testmodus leer lassen.

+ Geschäftskundenportal +
+ + +
+
+ +

Deine EKP (10 Ziffern) steht im Geschäftskundenportal unter Vertragsdaten. Daraus bilde ich die Abrechnungsnummern für DHL Paket und Paket International. Hast du andere Nummern, trag sie direkt ein.

+ +
+ Abrechnungsnummern selbst eintragen +
+ + +
+
+
+ +

Ich lege zum Test ein Probelabel an, das nicht gedruckt wird. Absender und Paketgewichte stellst du unter DHL-Versand ein.

+ +
+
+
+
+ ); +} + +// ---------- Google ---------- + +async function GoogleWizard({ ok }: { ok: boolean }) { + const c = (await getLoginProviders()).google; + const has = Boolean(c.clientId && c.clientSecret); + return ( + + + + +

Mit deinem Google-Konto anmelden und ein Projekt anlegen, z. B. „Sanamare“. Das ist kostenlos.

+ Projekt anlegen +
+ +

Unter „Google Auth Platform“ auf „Jetzt starten“ klicken: App-Name „Sanamare“, deine E-Mail als Support-Adresse, Zielgruppe „Extern“. Danach unter „Zielgruppe“ die App veröffentlichen, sonst können sich nur Testnutzer anmelden.

+ Google Auth Platform + Zielgruppe +
+ +

Neuen Client vom Typ „Webanwendung“ erstellen und diese zwei Werte eintragen:

+ Client erstellen + + +
+ +

Nach dem Erstellen zeigt Google beide Werte an.

+ + +
+ +

Ich prüfe die Daten direkt bei Google.

+ +
+
+
+
+ ); +} + +// ---------- Apple ---------- + +async function AppleWizard({ ok }: { ok: boolean }) { + const c = (await getLoginProviders()).apple; + const has = Boolean(c.servicesId && c.teamId && c.keyId && c.privateKey); + const domain = new URL(callbackUrl("apple")).host; + return ( + + + + +

„Mit Apple anmelden“ braucht eine Mitgliedschaft im Apple Developer Program (99 € im Jahr). Deine Team-ID steht danach in den Mitgliedsdaten.

+ Mitglied werden + Mitgliedsdaten (Team-ID) + +
+ +

Apple verlangt eine App-ID als Grundlage, auch ohne echte App. Neue App-ID anlegen, Beschreibung „Sanamare“, Bundle-ID z. B. de.sanamare.shop, und bei den Fähigkeiten „Sign in with Apple“ ankreuzen.

+ App-ID anlegen +
+ +

Neue Services-ID anlegen, z. B. de.sanamare.login. Danach „Sign in with Apple“ ankreuzen, auf „Configure“ klicken, die App-ID aus Schritt 2 wählen und diese Werte eintragen:

+ Services-ID anlegen + + + +
+ +

Neuen Schlüssel mit „Sign in with Apple“ erstellen und mit der App-ID aus Schritt 2 verknüpfen. Die .p8-Datei lässt sich nur einmal herunterladen, also gut aufheben.

+ Schlüssel erstellen + + +
+ +

Ich prüfe die Angaben direkt bei Apple.

+ +
+
+
+
+ ); +} + +const WIZARDS: Record Promise> = { + stripe: StripeWizard, + paypal: PaypalWizard, + dhl: DhlWizard, + google: GoogleWizard, + apple: AppleWizard, +}; diff --git a/src/app/admin/(panel)/verbindungen/actions.ts b/src/app/admin/(panel)/verbindungen/actions.ts new file mode 100644 index 0000000..8ec805f --- /dev/null +++ b/src/app/admin/(panel)/verbindungen/actions.ts @@ -0,0 +1,184 @@ +"use server"; +import { revalidatePath } from "next/cache"; +import { assertPermission, audit } from "@/lib/auth"; +import { fail, ok, type ActionResult } from "@/lib/action-result"; +import { getCredentials, saveCredentials } from "@/lib/payments/credentials"; +import { getDhlConfig, saveDhlConfig, splitStreet } from "@/lib/dhl"; +import { getSettings } from "@/lib/settings"; +import { getLoginProviders, saveLoginProviders } from "@/lib/social/config"; +import { isValidApplePrivateKey } from "@/lib/social/oauth"; +import { createStripeWebhook, detectPaypalMode, forgetTest, saveDetectedPaypal, testDhlConnection, testLogin, testPaypal, testStripe, type IntegrationKey } from "@/lib/integrations"; + +const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim(); +// Leere Geheimfelder behalten den gespeicherten Wert +const keep = (v: string, old: string) => (v ? v : old); +const done = (r: { ok: boolean; message: string }) => { + revalidatePath("/admin/verbindungen", "layout"); + revalidatePath("/admin/zahlung"); + revalidatePath("/admin/dhl"); + return r.ok ? ok(r.message) : fail(r.message); +}; + +export async function saveStripe(_prev: ActionResult, fd: FormData): Promise { + const user = await assertPermission("payments.edit"); + const c = await getCredentials(); + const secretKey = keep(str(fd, "secretKey"), c.stripe.secretKey); + if (!secretKey) return fail("Bitte füge den Geheimschlüssel aus Schritt 2 ein.", { secretKey: "Bitte einfügen" }); + if (/^pk_/.test(secretKey)) return fail("Das ist der veröffentlichbare Schlüssel (pk_…). Gebraucht wird der Geheimschlüssel, er beginnt mit sk_live_ oder sk_test_.", { secretKey: "sk_… gesucht" }); + if (!/^(sk|rk)_(test|live)_/.test(secretKey)) return fail("Der Geheimschlüssel beginnt mit sk_live_ oder sk_test_.", { secretKey: "Ungültiges Format" }); + const changedKey = secretKey !== c.stripe.secretKey; + let webhookSecret = keep(str(fd, "webhookSecret"), changedKey ? "" : c.stripe.webhookSecret); + let note = ""; + const next = { ...c, stripe: { ...c.stripe, secretKey, webhookSecret } }; + const test = await testStripe(next); + if (!test.ok) return fail(test.message, { secretKey: "Wird abgelehnt" }); + if (fd.get("autoWebhook") === "on" && (!webhookSecret || changedKey || fd.get("renewWebhook") === "on")) { + try { + webhookSecret = await createStripeWebhook(secretKey); + note = " Webhook automatisch eingerichtet."; + } catch (e) { + note = ` Den Webhook konnte ich nicht automatisch anlegen (${e instanceof Error ? e.message : e}). Richte ihn bitte von Hand ein, siehe unten.`; + } + } + next.stripe.webhookSecret = webhookSecret; + await saveCredentials(next); + await audit(user, "Stripe eingerichtet", secretKey.includes("_test_") ? "Testmodus" : "Live"); + const final = await testStripe(next); + return done({ ok: final.ok, message: final.message + note }); +} + +export async function savePaypal(_prev: ActionResult, fd: FormData): Promise { + const user = await assertPermission("payments.edit"); + const c = await getCredentials(); + const clientId = str(fd, "clientId"); + const clientSecret = keep(str(fd, "clientSecret"), c.paypal.clientSecret); + if (!clientId || !clientSecret) return fail("Bitte füge Client-ID und Secret aus Schritt 2 ein."); + let sandbox: boolean | null; + try { + sandbox = await detectPaypalMode(clientId, clientSecret); + } catch (e) { + return fail(`PayPal ist nicht erreichbar: ${e instanceof Error ? e.message : e}`); + } + if (sandbox === null) return fail("PayPal kennt diese Zugangsdaten weder im Live- noch im Sandbox-Modus. Prüfe, ob Client-ID und Secret zur selben App gehören.", { clientSecret: "Wird abgelehnt" }); + await saveDetectedPaypal(clientId, clientSecret, sandbox); + await audit(user, "PayPal eingerichtet", sandbox ? "Sandbox" : "Live"); + return done({ ok: true, message: `PayPal verbunden. Erkannt: ${sandbox ? "Sandbox-Zugang (Testzahlungen)" : "Live-Zugang (echte Zahlungen)"}.` }); +} + +export async function saveDhlConnection(_prev: ActionResult, fd: FormData): Promise { + const user = await assertPermission("shipping.edit"); + const c = await getDhlConfig(); + const sandbox = fd.get("sandbox") === "on"; + const ekp = str(fd, "ekp").replace(/\s/g, ""); + if (ekp && !/^\d{10}$/.test(ekp)) return fail("Die EKP hat 10 Ziffern.", { ekp: "10 Ziffern" }); + let billingNational = str(fd, "billingNational").replace(/\s/g, ""); + let billingInternational = str(fd, "billingInternational").replace(/\s/g, ""); + // Aus der EKP die üblichen Abrechnungsnummern bilden: Verfahren 01 (Paket) bzw. 53 (Paket International), Teilnahme 01 + if (ekp && !billingNational) billingNational = `${ekp}0101`; + if (ekp && !billingInternational) billingInternational = `${ekp}5301`; + const errors: Record = {}; + if (billingNational && !/^\d{14}$/.test(billingNational)) errors.billingNational = "14 Ziffern"; + if (billingInternational && !/^\d{14}$/.test(billingInternational)) errors.billingInternational = "14 Ziffern"; + if (Object.keys(errors).length) return fail("Bitte prüfe die Abrechnungsnummern.", errors); + const apiKey = keep(str(fd, "apiKey"), c.apiKey); + if (!apiKey) return fail("Bitte füge den API-Schlüssel aus Schritt 2 ein.", { apiKey: "Bitte einfügen" }); + const next = { + ...c, + sandbox, + apiKey, + username: str(fd, "username"), + password: keep(str(fd, "password"), c.password), + billingNational, + billingInternational, + enabled: fd.get("enabled") === "on", + }; + if (!sandbox && (!next.username || !next.password || !next.billingNational)) return fail("Für echte Labels fehlen Benutzername, Passwort oder Abrechnungsnummer. Zum Ausprobieren kannst du den Testmodus einschalten."); + // Absender beim ersten Mal aus den Shop-Angaben übernehmen, damit der Test sofort geht + if (!next.shipperName || !next.shipperStreet) { + const g = (await getSettings()).general; + const [street, house] = splitStreet(g.street); + const [zip, ...city] = g.zipCity.split(" "); + next.shipperName ||= g.company; + next.shipperStreet ||= street; + next.shipperHouse ||= house; + next.shipperZip ||= /^\d{5}$/.test(zip ?? "") ? zip : ""; + next.shipperCity ||= city.join(" "); + next.shipperEmail ||= g.email; + next.shipperPhone ||= g.phone; + } + await saveDhlConfig(next); + await audit(user, "DHL eingerichtet", sandbox ? "Sandbox" : "Live"); + const r = await testDhlConnection(); + return done(r); +} + +export async function saveGoogle(_prev: ActionResult, fd: FormData): Promise { + const user = await assertPermission("settings.edit"); + const c = await getLoginProviders(); + const clientId = str(fd, "clientId"); + const clientSecret = keep(str(fd, "clientSecret"), c.google.clientSecret); + if (!clientId || !clientSecret) return fail("Bitte füge Client-ID und Client-Secret aus Schritt 4 ein."); + if (!clientId.endsWith(".apps.googleusercontent.com")) return fail("Die Client-ID endet auf .apps.googleusercontent.com.", { clientId: "Bitte prüfen" }); + const next = { ...c, google: { enabled: fd.get("enabled") === "on", clientId, clientSecret } }; + const r = await testLogin("google", next); + if (!r.ok) next.google.enabled = false; + await saveLoginProviders(next); + await audit(user, "Google-Anmeldung eingerichtet", next.google.enabled ? "an" : "aus"); + return done(r.ok ? { ok: true, message: `${r.message}${next.google.enabled ? " Der Knopf erscheint jetzt im Shop." : " Schalte „Im Shop anbieten“ ein, damit der Knopf erscheint."}` } : { ok: false, message: `${r.message} Gespeichert, aber noch nicht im Shop angeboten.` }); +} + +export async function saveApple(_prev: ActionResult, fd: FormData): Promise { + const user = await assertPermission("settings.edit"); + const c = await getLoginProviders(); + const privateKey = keep(str(fd, "privateKey").replace(/\r\n/g, "\n"), c.apple.privateKey); + if (privateKey && !isValidApplePrivateKey(privateKey)) return fail("Der Schlüssel lässt sich nicht lesen. Wähle die heruntergeladene .p8-Datei aus.", { privateKey: "Ungültig" }); + const next = { + ...c, + apple: { + enabled: fd.get("enabled") === "on", + servicesId: str(fd, "servicesId"), + teamId: str(fd, "teamId").toUpperCase(), + keyId: str(fd, "keyId").toUpperCase(), + privateKey, + }, + }; + if (!next.apple.servicesId || !next.apple.teamId || !next.apple.keyId || !privateKey) return fail("Es fehlen noch Angaben: Services-ID, Team-ID, Key-ID und die .p8-Datei."); + const r = await testLogin("apple", next); + if (!r.ok) next.apple.enabled = false; + await saveLoginProviders(next); + await audit(user, "Apple-Anmeldung eingerichtet", next.apple.enabled ? "an" : "aus"); + return done(r.ok ? { ok: true, message: `${r.message}${next.apple.enabled ? " Der Knopf erscheint jetzt im Shop." : " Schalte „Im Shop anbieten“ ein, damit der Knopf erscheint."}` } : { ok: false, message: `${r.message} Gespeichert, aber noch nicht im Shop angeboten.` }); +} + +const PERMS: Record = { stripe: "payments.edit", paypal: "payments.edit", dhl: "shipping.edit", google: "settings.edit", apple: "settings.edit" }; + +export async function disconnect(fd: FormData) { + const key = str(fd, "provider") as IntegrationKey; + if (!(key in PERMS)) return; + const user = await assertPermission(PERMS[key]); + if (key === "stripe" || key === "paypal") { + const c = await getCredentials(); + if (key === "stripe") c.stripe = { publishableKey: "", secretKey: "", webhookSecret: "" }; + else c.paypal = { clientId: "", clientSecret: "", sandbox: true }; + await saveCredentials(c); + } else if (key === "dhl") { + const c = await getDhlConfig(); + await saveDhlConfig({ ...c, apiKey: "", password: "", enabled: false }); + } else { + const c = await getLoginProviders(); + if (key === "google") c.google = { enabled: false, clientId: "", clientSecret: "" }; + else c.apple = { enabled: false, servicesId: "", teamId: "", keyId: "", privateKey: "" }; + await saveLoginProviders(c); + } + await forgetTest(key); + await audit(user, "Verbindung entfernt", key); + revalidatePath("/admin/verbindungen", "layout"); +} + +export async function retest(_prev: ActionResult, fd: FormData): Promise { + const key = str(fd, "provider") as IntegrationKey; + if (!(key in PERMS)) return fail("Unbekannter Anbieter."); + await assertPermission(PERMS[key]); + const r = key === "stripe" ? await testStripe() : key === "paypal" ? await testPaypal() : key === "dhl" ? await testDhlConnection() : await testLogin(key); + return done(r); +} diff --git a/src/app/admin/(panel)/verbindungen/page.tsx b/src/app/admin/(panel)/verbindungen/page.tsx new file mode 100644 index 0000000..f263ede --- /dev/null +++ b/src/app/admin/(panel)/verbindungen/page.tsx @@ -0,0 +1,32 @@ +import Link from "next/link"; +import { can, requireAdmin } from "@/lib/auth"; +import { INTEGRATIONS, getStatuses } from "@/lib/integrations"; +import { PageHead } from "@/components/admin/ui"; +import { StatusPill } from "@/components/admin/IntegrationStatus"; + +export default async function IntegrationsPage() { + const user = await requireAdmin(); + const statuses = await getStatuses(); + const list = INTEGRATIONS.filter((i) => can(user, i.permission)); + return ( +
+ +
+ {list.map((i) => { + const s = statuses[i.key]; + return ( + +
+

{i.name}

+ +
+

{i.purpose}

+ {s.configured ? (s.lastTest ? s.lastTest.message : "Noch nicht getestet") : i.effort} + {s.configured ? "Ansehen" : "Einrichten"} + + ); + })} +
+
+ ); +} diff --git a/src/app/admin/(panel)/zahlung/actions.ts b/src/app/admin/(panel)/zahlung/actions.ts index 03b71ac..5c2b222 100644 --- a/src/app/admin/(panel)/zahlung/actions.ts +++ b/src/app/admin/(panel)/zahlung/actions.ts @@ -5,64 +5,9 @@ import { assertPermission, audit } from "@/lib/auth"; import { fail, ok, type ActionResult } from "@/lib/action-result"; import { parsePrice } from "@/lib/money"; import { getDefinition } from "@/lib/payments/catalog"; -import { getCredentials, saveCredentials } from "@/lib/payments/credentials"; const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim(); -export async function saveProviderCredentials(_prev: ActionResult, fd: FormData): Promise { - const user = await assertPermission("payments.edit"); - const current = await getCredentials(); - // Leere Geheimfelder behalten den gespeicherten Wert - const keep = (v: string, old: string) => (v ? v : old); - const stripeSecret = keep(str(fd, "stripeSecretKey"), current.stripe.secretKey); - if (stripeSecret && !/^(sk|rk)_(test|live)_/.test(stripeSecret)) return fail("Der Stripe-Geheimschlüssel beginnt mit sk_live_ oder sk_test_.", { stripeSecretKey: "Ungültiges Format" }); - await saveCredentials({ - stripe: { - publishableKey: str(fd, "stripePublishableKey"), - secretKey: fd.get("stripeClear") === "on" ? "" : stripeSecret, - webhookSecret: fd.get("stripeClear") === "on" ? "" : keep(str(fd, "stripeWebhookSecret"), current.stripe.webhookSecret), - }, - paypal: { - clientId: str(fd, "paypalClientId"), - clientSecret: fd.get("paypalClear") === "on" ? "" : keep(str(fd, "paypalClientSecret"), current.paypal.clientSecret), - sandbox: fd.get("paypalSandbox") === "on", - }, - }); - await audit(user, "Zahlungs-Zugangsdaten geändert"); - revalidatePath("/admin/zahlung"); - return ok("Zugangsdaten gespeichert."); -} - -export async function testProvider(_prev: ActionResult, fd: FormData): Promise { - await assertPermission("payments.edit"); - const provider = str(fd, "provider"); - const c = await getCredentials(); - try { - if (provider === "stripe") { - if (!c.stripe.secretKey) return fail("Es ist noch kein Stripe-Schlüssel gespeichert."); - const res = await fetch("https://api.stripe.com/v1/balance", { headers: { Authorization: `Bearer ${c.stripe.secretKey}` }, cache: "no-store" }); - const data = await res.json(); - if (!res.ok) return fail(`Stripe lehnt ab: ${data?.error?.message ?? res.status}`); - return ok(`Stripe verbunden (${data.livemode ? "Live-Modus" : "Testmodus"}).`); - } - if (provider === "paypal") { - if (!c.paypal.clientId || !c.paypal.clientSecret) return fail("Es sind noch keine PayPal-Zugangsdaten gespeichert."); - const base = c.paypal.sandbox ? "https://api-m.sandbox.paypal.com" : "https://api-m.paypal.com"; - const res = await fetch(`${base}/v1/oauth2/token`, { - method: "POST", - headers: { Authorization: "Basic " + Buffer.from(`${c.paypal.clientId}:${c.paypal.clientSecret}`).toString("base64"), "Content-Type": "application/x-www-form-urlencoded" }, - body: "grant_type=client_credentials", - cache: "no-store", - }); - if (!res.ok) return fail("PayPal lehnt die Zugangsdaten ab. Prüfe Client-ID, Secret und den Sandbox-Schalter."); - return ok(`PayPal verbunden (${c.paypal.sandbox ? "Sandbox" : "Live"}).`); - } - } catch (e) { - return fail(`Keine Verbindung: ${e instanceof Error ? e.message : e}`); - } - return fail("Unbekannter Anbieter."); -} - export async function savePaymentMethod(_prev: ActionResult, fd: FormData): Promise { const user = await assertPermission("payments.edit"); const id = str(fd, "id"); diff --git a/src/app/admin/(panel)/zahlung/page.tsx b/src/app/admin/(panel)/zahlung/page.tsx index 156a51d..c3b4ae6 100644 --- a/src/app/admin/(panel)/zahlung/page.tsx +++ b/src/app/admin/(panel)/zahlung/page.tsx @@ -2,43 +2,32 @@ import { db } from "@/lib/db"; import { requireAdmin } from "@/lib/auth"; import { centsToInput, formatPrice } from "@/lib/money"; import { getDefinition } from "@/lib/payments/catalog"; -import { getCredentials, isProviderReady, mask } from "@/lib/payments/credentials"; +import Link from "next/link"; +import { getCredentials, isProviderReady } from "@/lib/payments/credentials"; +import { getStatuses } from "@/lib/integrations"; +import { StatusPill } from "@/components/admin/IntegrationStatus"; import { Field, TextareaField } from "@/components/Field"; import { AdminForm } from "@/components/admin/AdminForm"; -import { TestButton } from "@/components/admin/TestButton"; import { Card, PageHead, Pill, Switch } from "@/components/admin/ui"; -import { savePaymentMethod, saveProviderCredentials, testProvider } from "./actions"; +import { savePaymentMethod } from "./actions"; export default async function PaymentsPage() { await requireAdmin("payments.edit"); - const [methods, creds] = await Promise.all([db.paymentMethod.findMany({ orderBy: { sort: "asc" } }), getCredentials()]); - const appUrl = (process.env.APP_URL ?? "https://sanamare.maaxxs-coding.de").replace(/\/$/, ""); + const [methods, creds, statuses] = await Promise.all([db.paymentMethod.findMany({ orderBy: { sort: "asc" } }), getCredentials(), getStatuses()]); return (
- + -

Zugangsdaten

- - {creds.stripe.secretKey ? (creds.stripe.secretKey.includes("_test_") ? "Testmodus" : "Live") : "Nicht verbunden"}}> - - - -
- Webhook in Stripe anlegen mit der Adresse {appUrl}/api/webhooks/stripe und den Ereignissen checkout.session.completed, checkout.session.async_payment_succeeded und checkout.session.async_payment_failed. Nötig vor allem für SEPA, weil die Bestätigung dort später kommt. -
- {creds.stripe.secretKey && } -
- {creds.paypal.clientSecret ? (creds.paypal.sandbox ? "Sandbox" : "Live") : "Nicht verbunden"}}> - - - - {creds.paypal.clientSecret && } - -
-
-
Stripe
-
PayPal
-
+ +
    + {(["stripe", "paypal"] as const).map((k) => ( +
  • + {k === "stripe" ? "Stripe (Karte, Apple Pay, Google Pay, Klarna, SEPA)" : "PayPal"} + +
  • + ))} +
+

Zahlungsarten im Shop

{methods.map((m) => { @@ -57,7 +46,7 @@ export default async function PaymentsPage() {
- + {def?.fields.map((f) => diff --git a/src/components/admin/CopyValue.tsx b/src/components/admin/CopyValue.tsx new file mode 100644 index 0000000..e4706c5 --- /dev/null +++ b/src/components/admin/CopyValue.tsx @@ -0,0 +1,34 @@ +"use client"; +import { useState } from "react"; +import { Icon } from "../Icon"; + +/** Wert zum Übernehmen beim Anbieter, mit Kopieren-Knopf. */ +export function CopyValue({ label, value }: { label: string; value: string }) { + const [copied, setCopied] = useState(false); + const copy = async () => { + try { + await navigator.clipboard.writeText(value); + } catch { + // Fallback für Browser ohne Clipboard-API (z. B. ohne HTTPS) + const t = document.createElement("textarea"); + t.value = value; + document.body.appendChild(t); + t.select(); + document.execCommand("copy"); + t.remove(); + } + setCopied(true); + setTimeout(() => setCopied(false), 2000); + }; + return ( +
+ {label} +
+ {value} + +
+
+ ); +} diff --git a/src/components/admin/IntegrationStatus.tsx b/src/components/admin/IntegrationStatus.tsx new file mode 100644 index 0000000..b016d29 --- /dev/null +++ b/src/components/admin/IntegrationStatus.tsx @@ -0,0 +1,10 @@ +import type { IntegrationStatus } from "@/lib/integrations"; +import { Pill } from "./ui"; + +export function StatusPill({ s }: { s: IntegrationStatus }) { + if (!s.configured) return Nicht eingerichtet; + if (s.lastTest && !s.lastTest.ok) return Fehler; + if (!s.active) return Eingerichtet, aus; + if (s.mode && s.mode !== "Live") return {s.mode}; + return Verbunden; +} diff --git a/src/components/admin/KeyFileInput.tsx b/src/components/admin/KeyFileInput.tsx new file mode 100644 index 0000000..06cce55 --- /dev/null +++ b/src/components/admin/KeyFileInput.tsx @@ -0,0 +1,30 @@ +"use client"; +import { useState } from "react"; + +/** Liest eine Schlüsseldatei (z. B. Apples .p8) im Browser und schickt ihren Inhalt als Formularfeld mit. */ +export function KeyFileInput({ name, label, accept, saved, hint }: { name: string; label: string; accept: string; saved: boolean; hint?: string }) { + const [content, setContent] = useState(""); + const [file, setFile] = useState(""); + const [error, setError] = useState(""); + const onChange = async (e: React.ChangeEvent) => { + const f = e.target.files?.[0]; + setError(""); + if (!f) return; + const text = await f.text(); + if (!text.includes("PRIVATE KEY")) { + setError("Das ist keine Schlüsseldatei. Gesucht ist die .p8-Datei von Apple."); + setContent(""); + return; + } + setFile(f.name); + setContent(text); + }; + return ( +
+ {label} + + + {error ? {error} : {file ? `${file} wird beim Speichern übernommen.` : saved ? "Ein Schlüssel ist gespeichert. Nur auswählen, wenn du ihn ersetzen willst." : hint}} +
+ ); +} diff --git a/src/components/admin/Setup.tsx b/src/components/admin/Setup.tsx new file mode 100644 index 0000000..b6226a6 --- /dev/null +++ b/src/components/admin/Setup.tsx @@ -0,0 +1,27 @@ +import { Icon } from "../Icon"; + +/** Nummerierte Schritte einer geführten Einrichtung. */ +export function Steps({ children }: { children: React.ReactNode }) { + return
    {children}
; +} + +export function Step({ n, title, done, children }: { n: number; title: string; done?: boolean; children: React.ReactNode }) { + return ( +
  • + +
    +

    {title}{done && (erledigt)}

    + {children} +
    +
  • + ); +} + +/** Link zur passenden Seite beim Anbieter, öffnet in neuem Tab. */ +export function OpenLink({ href, children }: { href: string; children: React.ReactNode }) { + return ( + + {children} + + ); +} diff --git a/src/components/admin/nav.ts b/src/components/admin/nav.ts index 70abd76..1e54d1f 100644 --- a/src/components/admin/nav.ts +++ b/src/components/admin/nav.ts @@ -38,10 +38,10 @@ export const ADMIN_NAV: { group: string; items: NavItem[] }[] = [ group: "Einstellungen", items: [ { href: "/admin/einstellungen", label: "Allgemein & Kasse", icon: "settings", permission: "settings.edit" }, + { href: "/admin/verbindungen", label: "Verbindungen", icon: "external", permission: "settings.edit" }, { href: "/admin/zahlung", label: "Zahlungsarten", icon: "card", permission: "payments.edit" }, { href: "/admin/versand", label: "Versand", icon: "truck", permission: "shipping.edit" }, { href: "/admin/dhl", label: "DHL-Versand", icon: "box", permission: "shipping.edit" }, - { href: "/admin/anmeldung", label: "Anmeldung", icon: "lock", permission: "settings.edit" }, { href: "/admin/team", label: "Team", icon: "users", permission: "users.manage" }, { href: "/admin/rollen", label: "Rollen & Rechte", icon: "shield", permission: "roles.manage" }, { href: "/admin/protokoll", label: "Protokoll", icon: "history", permission: "audit.view" }, diff --git a/src/lib/integrations.ts b/src/lib/integrations.ts new file mode 100644 index 0000000..b90ed5e --- /dev/null +++ b/src/lib/integrations.ts @@ -0,0 +1,177 @@ +import "server-only"; +import { db } from "./db"; +import { getCredentials, saveCredentials, type PaymentCredentials } from "./payments/credentials"; +import { stripeRequest } from "./payments/stripe"; +import { getDhlConfig, testConnection } from "./dhl"; +import { appUrl, getLoginProviders, isConfigured, type LoginProviders } from "./social/config"; +import { appleClientSecret } from "./social/oauth"; +import type { Permission } from "./permissions"; + +export type IntegrationKey = "stripe" | "paypal" | "dhl" | "google" | "apple"; +export type TestResult = { ok: boolean; message: string; at: string }; +export type IntegrationStatus = { key: IntegrationKey; configured: boolean; mode: string; active: boolean; lastTest: TestResult | null }; + +export const INTEGRATIONS: { key: IntegrationKey; name: string; purpose: string; permission: Permission; effort: string }[] = [ + { key: "stripe", name: "Stripe", purpose: "Kreditkarte, Apple Pay, Google Pay, Klarna und SEPA-Lastschrift", permission: "payments.edit", effort: "ca. 5 Minuten, ein Schlüssel" }, + { key: "paypal", name: "PayPal", purpose: "Bezahlen mit PayPal", permission: "payments.edit", effort: "ca. 5 Minuten, zwei Werte" }, + { key: "dhl", name: "DHL", purpose: "Versandlabels aus der Bestellung und Sendungsverfolgung", permission: "shipping.edit", effort: "ca. 15 Minuten, Geschäftskundenkonto nötig" }, + { key: "google", name: "Google", purpose: "„Mit Google anmelden“ für Kunden und Team", permission: "settings.edit", effort: "ca. 10 Minuten, zwei Werte" }, + { key: "apple", name: "Apple", purpose: "„Mit Apple anmelden“ für Kunden und Team", permission: "settings.edit", effort: "ca. 15 Minuten, Apple-Developer-Konto nötig" }, +]; + +const TESTS_KEY = "integration_tests"; + +export async function getLastTests(): Promise>> { + const row = await db.setting.findUnique({ where: { key: TESTS_KEY } }); + return (row?.value ?? {}) as Partial>; +} + +async function remember(key: IntegrationKey, r: { ok: boolean; message: string } | null) { + const current = await getLastTests(); + const value = { ...current } as Record; + if (r) value[key] = { ...r, at: new Date().toISOString() }; + else delete value[key]; + await db.setting.upsert({ where: { key: TESTS_KEY }, create: { key: TESTS_KEY, value }, update: { value } }); +} + +export async function forgetTest(key: IntegrationKey) { + await remember(key, null); +} + +export async function getStatuses(): Promise> { + const [creds, dhl, login, tests] = await Promise.all([getCredentials(), getDhlConfig(), getLoginProviders(), getLastTests()]); + const s = (key: IntegrationKey, configured: boolean, mode: string, active: boolean): IntegrationStatus => ({ key, configured, mode, active, lastTest: configured ? (tests[key] ?? null) : null }); + return { + stripe: s("stripe", Boolean(creds.stripe.secretKey), creds.stripe.secretKey.includes("_test_") ? "Testmodus" : "Live", Boolean(creds.stripe.secretKey)), + paypal: s("paypal", Boolean(creds.paypal.clientId && creds.paypal.clientSecret), creds.paypal.sandbox ? "Sandbox" : "Live", Boolean(creds.paypal.clientSecret)), + dhl: s("dhl", Boolean(dhl.apiKey), dhl.sandbox ? "Sandbox" : "Live", dhl.enabled), + google: s("google", isConfigured("google", login), "", login.google.enabled), + apple: s("apple", isConfigured("apple", login), "", login.apple.enabled), + }; +} + +// ---------- Stripe ---------- + +export const STRIPE_WEBHOOK_EVENTS = ["checkout.session.completed", "checkout.session.async_payment_succeeded", "checkout.session.async_payment_failed"]; +export const stripeWebhookUrl = () => `${appUrl()}/api/webhooks/stripe`; + +export async function testStripe(c?: PaymentCredentials) { + const creds = c ?? (await getCredentials()); + let r: { ok: boolean; message: string }; + if (!creds.stripe.secretKey) r = { ok: false, message: "Es ist noch kein Stripe-Schlüssel gespeichert." }; + else { + try { + const data = await stripeRequest<{ livemode: boolean }>(creds.stripe.secretKey, "/balance", undefined, "GET"); + r = { ok: true, message: `Stripe verbunden (${data.livemode ? "Live" : "Testmodus"}).${creds.stripe.webhookSecret ? " Zahlungsbestätigungen kommen per Webhook an." : " Webhook fehlt noch."}` }; + } catch (e) { + const msg = e instanceof Error ? e.message : String(e); + r = { ok: false, message: msg === "fetch failed" ? "Stripe ist gerade nicht erreichbar. Bitte später noch einmal testen." : `Stripe lehnt ab: ${msg}` }; + } + } + await remember("stripe", r); + return r; +} + +/** Legt den Webhook in Stripe an (oder ersetzt unseren alten) und gibt den Signaturschlüssel zurück. */ +export async function createStripeWebhook(secretKey: string) { + const url = stripeWebhookUrl(); + const list = await stripeRequest<{ data: { id: string; url: string }[] }>(secretKey, "/webhook_endpoints?limit=100", undefined, "GET"); + // Den Signaturschlüssel zeigt Stripe nur beim Anlegen, deshalb einen vorhandenen Endpunkt für diese Adresse ersetzen + for (const ep of list.data.filter((e) => e.url === url)) await stripeRequest(secretKey, `/webhook_endpoints/${ep.id}`, undefined, "DELETE"); + const p = new URLSearchParams({ url, description: "Sanamare Shop" }); + for (const e of STRIPE_WEBHOOK_EVENTS) p.append("enabled_events[]", e); + const created = await stripeRequest<{ secret: string }>(secretKey, "/webhook_endpoints", p); + return created.secret; +} + +// ---------- PayPal ---------- + +async function paypalToken(clientId: string, secret: string, sandbox: boolean) { + const res = await fetch(`${sandbox ? "https://api-m.sandbox.paypal.com" : "https://api-m.paypal.com"}/v1/oauth2/token`, { + method: "POST", + headers: { Authorization: "Basic " + Buffer.from(`${clientId}:${secret}`).toString("base64"), "Content-Type": "application/x-www-form-urlencoded" }, + body: "grant_type=client_credentials", + cache: "no-store", + }); + return res.ok; +} + +/** Erkennt selbst, ob die Zugangsdaten zu Live oder Sandbox gehören. null = passt zu keinem. */ +export async function detectPaypalMode(clientId: string, secret: string): Promise { + if (await paypalToken(clientId, secret, false)) return false; + if (await paypalToken(clientId, secret, true)) return true; + return null; +} + +export async function testPaypal() { + const c = await getCredentials(); + let r: { ok: boolean; message: string }; + if (!c.paypal.clientId || !c.paypal.clientSecret) r = { ok: false, message: "Es sind noch keine PayPal-Zugangsdaten gespeichert." }; + else { + try { + r = (await paypalToken(c.paypal.clientId, c.paypal.clientSecret, c.paypal.sandbox)) + ? { ok: true, message: `PayPal verbunden (${c.paypal.sandbox ? "Sandbox" : "Live"}).` } + : { ok: false, message: "PayPal lehnt Client-ID oder Secret ab." }; + } catch (e) { + r = { ok: false, message: `PayPal ist nicht erreichbar: ${e instanceof Error ? e.message : e}` }; + } + } + await remember("paypal", r); + return r; +} + +export async function saveDetectedPaypal(clientId: string, clientSecret: string, sandbox: boolean) { + const c = await getCredentials(); + await saveCredentials({ ...c, paypal: { clientId, clientSecret, sandbox } }); +} + +// ---------- DHL ---------- + +export async function testDhlConnection() { + const r = await testConnection(await getDhlConfig()); + await remember("dhl", r); + return r; +} + +// ---------- Google & Apple ---------- + +/** + * Prüft Client-ID und Secret, ohne dass sich jemand anmelden muss: Wir tauschen einen + * absichtlich ungültigen Code. "invalid_grant" heißt, der Anbieter kennt den Client. + */ +async function probeToken(url: string, body: URLSearchParams) { + const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" }, body, cache: "no-store" }); + const data = (await res.json().catch(() => ({}))) as { error?: string; error_description?: string }; + return data.error ?? (res.ok ? "ok" : `HTTP ${res.status}`); +} + +export async function testLogin(provider: "google" | "apple", login?: LoginProviders) { + const c = login ?? (await getLoginProviders()); + let r: { ok: boolean; message: string }; + if (!isConfigured(provider, c)) r = { ok: false, message: "Es fehlen noch Angaben." }; + else { + try { + if (provider === "google") { + const err = await probeToken("https://oauth2.googleapis.com/token", new URLSearchParams({ code: "sanamare-test", client_id: c.google.clientId, client_secret: c.google.clientSecret, redirect_uri: `${appUrl()}/api/auth/google/callback`, grant_type: "authorization_code" })); + r = err === "invalid_grant" + ? { ok: true, message: "Google kennt Client-ID und Secret. Die Anmeldung ist bereit." } + : err === "invalid_client" || err === "unauthorized_client" + ? { ok: false, message: "Google lehnt Client-ID oder Secret ab. Prüfe, ob beide aus demselben OAuth-Client stammen." } + : err === "redirect_uri_mismatch" + ? { ok: false, message: "Die Weiterleitungs-URI ist bei Google nicht eingetragen. Kopiere sie aus Schritt 3." } + : { ok: false, message: `Google meldet: ${err}` }; + } else { + const err = await probeToken("https://appleid.apple.com/auth/token", new URLSearchParams({ code: "sanamare-test", client_id: c.apple.servicesId, client_secret: appleClientSecret(c.apple), redirect_uri: `${appUrl()}/api/auth/apple/callback`, grant_type: "authorization_code" })); + r = err === "invalid_grant" + ? { ok: true, message: "Apple kennt Services-ID, Team-ID und Schlüssel. Die Anmeldung ist bereit." } + : err === "invalid_client" + ? { ok: false, message: "Apple lehnt die Angaben ab. Meist passt die Services-ID, die Team-ID oder die Key-ID nicht zum Schlüssel." } + : { ok: false, message: `Apple meldet: ${err}` }; + } + } catch (e) { + r = { ok: false, message: `Keine Verbindung: ${e instanceof Error ? e.message : e}` }; + } + } + await remember(provider, r); + return r; +} diff --git a/src/lib/payments/stripe.ts b/src/lib/payments/stripe.ts index 0c57cab..8d4ebb4 100644 --- a/src/lib/payments/stripe.ts +++ b/src/lib/payments/stripe.ts @@ -4,7 +4,7 @@ import type { Order } from "@prisma/client"; const API = "https://api.stripe.com/v1"; -async function stripeRequest(secretKey: string, path: string, params?: URLSearchParams, method = "POST"): Promise { +export async function stripeRequest(secretKey: string, path: string, params?: URLSearchParams, method = "POST"): Promise { const res = await fetch(`${API}${path}`, { method, headers: { diff --git a/src/lib/social/oauth.ts b/src/lib/social/oauth.ts index 0b1eb2a..e629903 100644 --- a/src/lib/social/oauth.ts +++ b/src/lib/social/oauth.ts @@ -52,7 +52,7 @@ export function isValidApplePrivateKey(pem: string) { } /** Apple verlangt als Client-Secret ein mit dem .p8-Schlüssel signiertes JWT (ES256). */ -function appleClientSecret(c: LoginProviders["apple"]) { +export function appleClientSecret(c: LoginProviders["apple"]) { const now = Math.floor(Date.now() / 1000); const header = b64url(JSON.stringify({ alg: "ES256", kid: c.keyId })); const claims = b64url(JSON.stringify({ iss: c.teamId, iat: now, exp: now + 300, aud: "https://appleid.apple.com", sub: c.servicesId })); diff --git a/src/styles/admin.css b/src/styles/admin.css index a2b0f8a..bd709c4 100644 --- a/src/styles/admin.css +++ b/src/styles/admin.css @@ -187,3 +187,32 @@ a.ad-kpi:hover { border-color: var(--line-strong); } .ad-template__confirm { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } .ad-legal { list-style: none; margin: 0; padding: 0; display: grid; gap: var(--space-3); } .ad-legal li { display: flex; justify-content: space-between; align-items: center; gap: var(--space-3); font-size: 14px; } + +/* Geführte Einrichtung */ +.ad-steps { list-style: none; margin: 0; padding: 0; display: grid; gap: var(--space-6); counter-reset: step; } +.ad-step { display: grid; grid-template-columns: 32px 1fr; gap: var(--space-4); } +.ad-step__num { width: 32px; height: 32px; border-radius: 50%; border: 1px solid var(--line); display: grid; place-items: center; font-size: 14px; font-weight: 600; background: var(--surface-raised, #fff); } +.ad-step.is-done .ad-step__num { background: var(--gold); border-color: var(--gold); color: var(--ink); } +.ad-step__body h3 { margin: 4px 0 var(--space-2); font-size: 16px; font-weight: 600; } +.ad-step__body p { margin: 0 0 var(--space-3); font-size: 14px; line-height: 21px; color: var(--ink-muted); } +.ad-step__body ol, .ad-step__body ul { margin: 0 0 var(--space-3); padding-left: 20px; font-size: 14px; line-height: 21px; color: var(--ink-muted); } +.ad-step__body .sm-field { margin-top: var(--space-3); } +.ad-openlink { display: inline-flex; align-items: center; gap: 6px; font-size: 14px; font-weight: 500; color: var(--link); text-decoration: underline; text-underline-offset: 3px; margin: 0 var(--space-4) var(--space-3) 0; } +.ad-copy { margin: 0 0 var(--space-3); } +.ad-copy__label { display: block; font-size: 12px; color: var(--ink-subtle); margin-bottom: 4px; } +.ad-copy__row { display: flex; gap: 8px; align-items: center; } +.ad-copy__row code { flex: 1; min-width: 0; overflow-wrap: anywhere; padding: 8px 10px; border: 1px solid var(--line); border-radius: var(--radius-md); background: var(--surface); font-size: 13px; } +.ad-file { font-size: 14px; } +.ad-result { display: flex; gap: 8px; align-items: flex-start; padding: var(--space-4) var(--space-5); border-radius: var(--radius-md); font-size: 14px; line-height: 20px; margin-bottom: var(--space-5); border: 1px solid var(--line); } +.ad-result--ok { border-color: var(--success, #2f7a52); } +.ad-result--err { border-color: var(--danger); } +.ad-result small { display: block; color: var(--ink-subtle); } + +/* Übersicht Verbindungen */ +.ad-integrations { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: var(--space-4); } +.ad-integration { display: grid; gap: var(--space-3); padding: var(--space-5); border: 1px solid var(--line); border-radius: var(--radius-md); background: var(--surface-raised, #fff); text-decoration: none; color: inherit; } +.ad-integration:hover { border-color: var(--gold); } +.ad-integration__head { display: flex; justify-content: space-between; align-items: center; gap: var(--space-3); } +.ad-integration h2 { margin: 0; font-size: 18px; font-weight: 600; } +.ad-integration p { margin: 0; font-size: 14px; line-height: 20px; color: var(--ink-muted); } +.ad-integration small { font-size: 12px; color: var(--ink-subtle); }