diff --git a/Makefile b/Makefile index 31ab44683..c31613303 100644 --- a/Makefile +++ b/Makefile @@ -637,10 +637,15 @@ WORKER_DEV_ENV := \ # the docker postgres. # The sandbox's mock inbox vendor API; empty keeps the real vendors. MAILVENDOR_SANDBOX_URL ?= +# The store runs against the in-process GraphKit simulator in dev; set both to use a sandbox key. +GRAPHKIT_API_URL ?= fake +GRAPHKIT_API_KEY ?= backend: $(GO_DEV_ENV) \ $(AI_DEV_ENV) \ MAILVENDOR_SANDBOX_URL=$(MAILVENDOR_SANDBOX_URL) \ + GRAPHKIT_API_URL=$(GRAPHKIT_API_URL) \ + GRAPHKIT_API_KEY=$(GRAPHKIT_API_KEY) \ API_HOST=0.0.0.0:8080 \ FORMS_DOMAIN=localhost:$(FORMS_PORT) \ PORTAL_DOMAIN=localhost:$(PORTAL_PORT) \ diff --git a/admin/src/app/dashboard/HealthPage.tsx b/admin/src/app/dashboard/HealthPage.tsx index d123f6a87..c75df920e 100644 --- a/admin/src/app/dashboard/HealthPage.tsx +++ b/admin/src/app/dashboard/HealthPage.tsx @@ -1,16 +1,17 @@ import { Link, useSearchParams } from "react-router-dom"; -import { Activity, ListChecks } from "lucide-react"; +import { Activity, ListChecks, Plug } from "lucide-react"; import { PageHeader } from "@/components/layout/PageHeader"; import { PageTabs } from "@/components/layout/PageTabs"; import { Button } from "@/components/ui/button"; import { useInstanceHealth } from "@/hooks/useInstanceHealth"; import { FindingsTab } from "./health/FindingsTab"; import { ServicesTab } from "./health/ServicesTab"; +import { IntegrationsTab } from "./health/IntegrationsTab"; import { InstanceMonitoringPanel } from "./InstanceMonitoringPanel"; import { useAdminPerm } from "@/hooks/useAdminPerm"; import { AdminPerm } from "@/lib/auth/permissions"; -const TAB_IDS = ["findings", "services", "operations"] as const; +const TAB_IDS = ["findings", "services", "operations", "integrations"] as const; type TabId = (typeof TAB_IDS)[number]; function isTabId(v: string | null): v is TabId { @@ -21,7 +22,8 @@ export default function HealthPage() { const canConfigure = useAdminPerm(AdminPerm.ManageSettings); const [params, setParams] = useSearchParams(); const raw = params.get("tab"); - const tab: TabId = isTabId(raw) ? raw : "findings"; + // Integrations hold write-only credentials, so the tab exists only for manage-settings. + const tab: TabId = isTabId(raw) && (raw !== "integrations" || canConfigure) ? raw : "findings"; // The findings count comes from the shared cache the sidebar badge reads, // so the tab badge and the nav badge never disagree. @@ -61,12 +63,21 @@ export default function HealthPage() { }, { id: "services", label: "Services", icon: Activity }, { id: "operations", label: "Operations", icon: Activity }, + ...(canConfigure ? [{ id: "integrations", label: "Integrations", icon: Plug }] : []), ]} value={tab} onChange={setTab} /> - {tab === "findings" ? : tab === "services" ? : } + {tab === "findings" ? ( + + ) : tab === "services" ? ( + + ) : tab === "integrations" ? ( + + ) : ( + + )} ); } diff --git a/admin/src/app/dashboard/OrganizationDetailPage.tsx b/admin/src/app/dashboard/OrganizationDetailPage.tsx index e1c3525d4..21c55ee33 100644 --- a/admin/src/app/dashboard/OrganizationDetailPage.tsx +++ b/admin/src/app/dashboard/OrganizationDetailPage.tsx @@ -278,6 +278,11 @@ function OrgProperties({ org }: { org: AdminOrgDetail }) { )} + + + Domains, mailboxes, orders + +
Lifecycle
diff --git a/admin/src/app/dashboard/configuration/SettingsTab.tsx b/admin/src/app/dashboard/configuration/SettingsTab.tsx index 995af3b8b..9e0d337bc 100644 --- a/admin/src/app/dashboard/configuration/SettingsTab.tsx +++ b/admin/src/app/dashboard/configuration/SettingsTab.tsx @@ -18,11 +18,14 @@ import { getInstanceSettings, putInstanceSettings, type InstanceSettings, + type StoreSettings, type UsageSettings, } from "@/lib/api/client/admin/instance"; +import { getStorePricing } from "@/lib/api/client/admin/store"; import { RangeHint, SettingsGroup, SettingsRow } from "./SettingsLayout"; const SETTINGS_KEY = ["admin", "instance", "settings"]; +const STORE_PRICING_KEY = ["admin", "store", "pricing"]; // The backend clamps to the same band; matching it here keeps the operator // from spending a round-trip to learn the range. @@ -430,6 +433,90 @@ function formatUSD(n: number): string { return `$${n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 4 })}`; } +// Store retail pricing, mirroring the store section of internal/app/instancesettings. +const MICROS_PER_USD = 1_000_000; +const MICROS_PER_CENT = 10_000; +const STORE_USD_MAX = 100; +const STORE_PERCENT_MAX = 500; +// The preview prices this extension from the live wholesale list. +const STORE_PREVIEW_TLD = "com"; + +const STORE_LEAD_MIN = 2; +const STORE_LEAD_MAX = 10; +const STORE_MIN_CARD_FLOOR = 0.5; + +const STORE_DEFAULTS: StoreSettings = { + mailbox_monthly_micros: 3_000_000, + domain_markup_percent: 0, + domain_markup_fixed_micros: 0, + mailbox_bill_lead_days: 5, + min_card_charge_micros: 10_000_000, +}; + +interface StoreForm { + mailboxMonthly: string; + markupPercent: string; + markupFixed: string; + billLead: string; + minCard: string; +} + +function microsToDollars(micros: number): string { + const usd = micros / MICROS_PER_USD; + return micros % MICROS_PER_CENT === 0 ? usd.toFixed(2) : String(usd); +} + +function dollarsToMicros(raw: string): number { + return Math.round(Number(raw) * MICROS_PER_USD); +} + +function toStoreForm(s: StoreSettings | undefined): StoreForm { + const store = { ...STORE_DEFAULTS, ...s }; + return { + mailboxMonthly: microsToDollars(store.mailbox_monthly_micros), + markupPercent: String(store.domain_markup_percent), + markupFixed: microsToDollars(store.domain_markup_fixed_micros), + billLead: String(store.mailbox_bill_lead_days ?? 5), + minCard: microsToDollars(store.min_card_charge_micros ?? 10_000_000), + }; +} + +// Dollars to at most micro-dollar precision, between zero and max. +function dollarsValid(raw: string, max: number): boolean { + return /^\d+(\.\d{1,6})?$/.test(raw.trim()) && Number(raw) <= max; +} + +function storeFormValid(f: StoreForm): boolean { + return ( + dollarsValid(f.mailboxMonthly, STORE_USD_MAX) && + syncFieldValid(f.markupPercent, 0, STORE_PERCENT_MAX) && + dollarsValid(f.markupFixed, STORE_USD_MAX) && + syncFieldValid(f.billLead, STORE_LEAD_MIN, STORE_LEAD_MAX) && + dollarsValid(f.minCard, STORE_USD_MAX) && + Number(f.minCard) >= STORE_MIN_CARD_FLOOR + ); +} + +// Retail domain price: wholesale plus the percent plus the fixed amount, rounded up to the cent. +function retailDomainMicros(wholesale: number, percent: number, fixed: number): number { + const exact = wholesale * (100 + percent) + fixed * 100; + return Math.ceil(exact / (100 * MICROS_PER_CENT)) * MICROS_PER_CENT; +} + +function mailboxPreview(f: StoreForm): string { + return `Customers pay ${formatUSD(dollarsToMicros(f.mailboxMonthly) / MICROS_PER_USD)} per mailbox per month`; +} + +// What a .com sells for at the form's markup, from the live wholesale price. +function domainPreview(f: StoreForm, wholesaleMicros: number): string { + const percent = Number(f.markupPercent); + const fixed = dollarsToMicros(f.markupFixed); + const wholesale = formatUSD(wholesaleMicros / MICROS_PER_USD); + if (percent === 0 && fixed === 0) return `a .${STORE_PREVIEW_TLD} costs ${wholesale} at cost`; + const retail = formatUSD(retailDomainMicros(wholesaleMicros, percent, fixed) / MICROS_PER_USD); + return `a .${STORE_PREVIEW_TLD} that costs ${wholesale} wholesale sells for ${retail}`; +} + interface FormState { linksEnabled: boolean; ttlHours: string; @@ -442,6 +529,7 @@ interface FormState { authGraceHours: string; autoVendorReconnect: boolean; usage: UsageForm; + store: StoreForm; } function toForm(s: InstanceSettings): FormState { @@ -485,6 +573,7 @@ function toForm(s: InstanceSettings): FormState { authGraceHours: String(s.deliverability.auth_grace_hours), autoVendorReconnect: s.mailbox_signin?.auto_vendor_reconnect ?? true, usage: toUsageForm(s.usage), + store: toStoreForm(s.store), }; } @@ -550,6 +639,10 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) { ); const usageDirty = !!server && !!form && usageSignature(form.usage) !== usageSignature(toUsageForm(server.usage)); + const storeDirty = + !!server && + !!form && + JSON.stringify(form.store) !== JSON.stringify(toStoreForm(server.store)); const dirty = !!server && !!form && @@ -563,6 +656,7 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) { trackingDirty || placementDirty || usageDirty || + storeDirty || syncDirty); useEffect(() => { @@ -592,6 +686,8 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) { ) && Object.values(form.usage.units).every(priceValid); + const storeValid = form !== null && storeFormValid(form.store); + const authGrace = form ? Number(form.authGraceHours) : NaN; const authGraceValid = form !== null && @@ -642,6 +738,12 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) { ); return; } + if (!storeValid) { + toast.error( + `The mailbox price and the fixed domain markup must be dollar amounts from $0 to $${STORE_USD_MAX}, and the domain markup a whole percent from 0 to ${STORE_PERCENT_MAX}`, + ); + return; + } if (!authGraceValid) { toast.error( `The authentication grace period must be a whole number of hours between ${AUTH_GRACE_MIN_HOURS} and ${AUTH_GRACE_MAX_HOURS}`, @@ -698,6 +800,13 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) { Object.entries(form.usage.units).map(([k, v]) => [k, Number(v)]), ), }, + store: { + mailbox_monthly_micros: dollarsToMicros(form.store.mailboxMonthly), + domain_markup_percent: Number(form.store.markupPercent), + domain_markup_fixed_micros: dollarsToMicros(form.store.markupFixed), + mailbox_bill_lead_days: Number(form.store.billLead), + min_card_charge_micros: dollarsToMicros(form.store.minCard), + }, }); } @@ -923,6 +1032,11 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) { onChange={(usage) => setForm({ ...form, usage })} /> + setForm({ ...form, store })} + /> + void; +}) { + const pricingQ = useQuery({ + queryKey: STORE_PRICING_KEY, + queryFn: getStorePricing, + retry: false, + staleTime: 5 * 60_000, + }); + const comWholesale = pricingQ.data?.domains.find((d) => d.tld === STORE_PREVIEW_TLD)?.register_micros; + const valid = storeFormValid(store); + return ( + + What a workspace pays for the domains and mailboxes it buys under Buy mailboxes, + charged from its balance. Only used when the store is configured with{" "} + GRAPHKIT_API_KEY. A change applies + to quotes made after it; a mailbox already bought keeps the monthly price it was + bought at. A self-hosted instance with billing off charges workspaces nothing and + its partner account pays, so these prices do nothing there. + + } + > + onChange({ ...store, mailboxMonthly: v })} + valid={dollarsValid(store.mailboxMonthly, STORE_USD_MAX)} + error={`Enter a dollar amount between 0 and ${STORE_USD_MAX}.`} + inputMode="decimal" + /> + onChange({ ...store, markupPercent: v })} + valid={syncFieldValid(store.markupPercent, 0, STORE_PERCENT_MAX)} + error={`Enter a whole number between 0 and ${STORE_PERCENT_MAX}.`} + /> + onChange({ ...store, markupFixed: v })} + valid={dollarsValid(store.markupFixed, STORE_USD_MAX)} + error={`Enter a dollar amount between 0 and ${STORE_USD_MAX}.`} + inputMode="decimal" + /> + onChange({ ...store, billLead: v })} + valid={syncFieldValid(store.billLead, STORE_LEAD_MIN, STORE_LEAD_MAX)} + error={`Enter a whole number between ${STORE_LEAD_MIN} and ${STORE_LEAD_MAX}.`} + /> + onChange({ ...store, minCard: v })} + valid={dollarsValid(store.minCard, STORE_USD_MAX) && Number(store.minCard) >= STORE_MIN_CARD_FLOOR} + error={`Enter a dollar amount between ${STORE_MIN_CARD_FLOOR.toFixed(2)} and ${STORE_USD_MAX}.`} + inputMode="decimal" + /> +
+ {!valid ? ( + "Fix the values above to see what customers pay." + ) : pricingQ.isLoading ? ( +
+ {mailboxPreview(store)}; + + loading the live .{STORE_PREVIEW_TLD} price +
+ ) : comWholesale === undefined ? ( + <> + {mailboxPreview(store)}.{" "} + Live price unavailable + + ) : ( + `${mailboxPreview(store)}; ${domainPreview(store, comWholesale)}.` + )} +
+
+ ); +} + // One numeric setting: the field sits on the right, the range under the help. function NumberRow({ id, diff --git a/admin/src/app/dashboard/health/IntegrationsTab.test.tsx b/admin/src/app/dashboard/health/IntegrationsTab.test.tsx new file mode 100644 index 000000000..8737c184b --- /dev/null +++ b/admin/src/app/dashboard/health/IntegrationsTab.test.tsx @@ -0,0 +1,75 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { StoreConnection } from "@/lib/api/client/admin/store"; +import { StoreConnectionCard } from "./IntegrationsTab"; + +const state = vi.hoisted(() => ({ conn: undefined as StoreConnection | undefined })); +vi.mock("@tanstack/react-query", () => ({ + useQuery: () => ({ data: state.conn, isLoading: false, isError: false, refetch: vi.fn() }), + useMutation: () => ({ mutate: vi.fn(), isPending: false }), + useQueryClient: () => ({}), +})); +vi.mock("@/components/ConfirmDialog", () => ({ useConfirm: () => vi.fn() })); +vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } })); + +function conn(over: Partial = {}): StoreConnection { + return { + source: "settings", + configured: true, + mode: "live", + api_url: "https://gk.example/v1/infrastructure", + default_api_url: "https://api.graphkit.com/v1/infrastructure", + api_key_set: true, + webhook_secret_set: false, + webhook_url: "https://api.example/v1/webhooks/graphkit", + sealing_available: true, + updated_at: "2026-11-01T00:00:00Z", + updated_by: "user-1", + purchases_without_connection: null, + ...over, + }; +} + +function render() { + const html = renderToStaticMarkup(); + return new DOMParser().parseFromString(html, "text/html"); +} + +const buttons = (doc: Document) => [...doc.querySelectorAll("button")].map((b) => b.textContent?.trim()); + +beforeEach(() => { + state.conn = conn(); +}); + +describe("GraphKit connection card", () => { + it("renders an environment connection read-only", () => { + state.conn = conn({ source: "environment" }); + const doc = render(); + expect(doc.body.textContent).toContain("Configured by the environment"); + expect(doc.body.textContent).toContain("https://gk.example/v1/infrastructure"); + expect(doc.querySelector("input[type=password]")).toBeNull(); + expect(doc.querySelector("#graphkit-url")).toBeNull(); + expect(buttons(doc)).not.toContain("Save"); + expect(buttons(doc)).not.toContain("Disconnect"); + }); + + it("offers Disconnect for stored settings and starts secrets empty", () => { + const doc = render(); + expect(buttons(doc)).toContain("Disconnect"); + const secrets = [...doc.querySelectorAll("input[type=password]")]; + expect(secrets).toHaveLength(2); + for (const s of secrets) expect(s.value).toBe(""); + expect(doc.querySelector("#graphkit-url")?.value).toBe("https://gk.example/v1/infrastructure"); + expect(doc.body.textContent).toContain("Not set"); + }); + + it("blocks saving without the credentials key and reports unconnected purchases", () => { + state.conn = conn({ source: "none", configured: false, api_key_set: false, sealing_available: false, purchases_without_connection: { mailboxes: 3, domains: 1 } }); + const doc = render(); + expect(doc.body.textContent).toContain("CREDENTIALS_ENCRYPTION_KEY must be set"); + expect(doc.body.textContent).toContain("3 mailboxes and 1 domain were bought here"); + const save = [...doc.querySelectorAll("button")].find((b) => b.textContent?.includes("Save")); + expect(save?.hasAttribute("disabled")).toBe(true); + expect(buttons(doc)).not.toContain("Disconnect"); + }); +}); diff --git a/admin/src/app/dashboard/health/IntegrationsTab.tsx b/admin/src/app/dashboard/health/IntegrationsTab.tsx new file mode 100644 index 000000000..a74574d04 --- /dev/null +++ b/admin/src/app/dashboard/health/IntegrationsTab.tsx @@ -0,0 +1,342 @@ +// Integrations tab of Setup and health: the GraphKit connection behind the domain and mailbox store. + +import { useState, type FormEvent } from "react"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { toast } from "sonner"; +import { AlertTriangle, Check, Copy, FlaskConical, Save, Unplug } from "lucide-react"; +import { useConfirm } from "@/components/ConfirmDialog"; +import { ErrorState } from "@/components/ErrorState"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Callout, Panel, StatusBadge } from "@/components/ui/kit"; +import { Skeleton } from "@/components/ui/skeleton"; +import { INSTANCE_HEALTH_KEY } from "@/hooks/useInstanceHealth"; +import { APIError, ReauthCancelledError } from "@/lib/api/client"; +import { + deleteStoreConnection, + getStoreConnection, + saveStoreConnection, + STORE_CONNECTION_KEY, + testStoreConnection, + type StoreConnection, + type StoreConnectionInput, + type StoreConnectionTest, +} from "@/lib/api/client/admin/store"; +import { MODE_TONE } from "../store/format"; + +export function IntegrationsTab() { + return ( +
+ +
+ ); +} + +const ERROR_TEXT: Record = { + store_configured_by_environment: "GRAPHKIT_* environment variables configure the store, so it cannot be changed here.", + store_sealing_unavailable: "Set CREDENTIALS_ENCRYPTION_KEY before saving a GraphKit API key here.", + graphkit_url_invalid: "The API URL is not a valid GraphKit URL.", + graphkit_key_required: "Enter an API key. None is stored yet.", + graphkit_key_reentry_required: "Enter the API key again to use a different API URL.", + graphkit_key_rejected: "GraphKit rejected this API key.", + graphkit_unreachable: "GraphKit could not be reached at this URL.", +}; + +function errorText(e: unknown): string { + if (e instanceof APIError && e.code && ERROR_TEXT[e.code]) return ERROR_TEXT[e.code]; + return e instanceof Error && e.message ? e.message : "The request failed"; +} + +function trimSlash(u: string): string { + return u.replace(/\/+$/, ""); +} + +function money(micros: number, currency: string): string { + try { + return new Intl.NumberFormat("en-US", { style: "currency", currency: currency || "USD" }).format(micros / 1_000_000); + } catch { + return `${(micros / 1_000_000).toFixed(2)} ${currency}`; + } +} + +const MODE_LABEL: Record = { + live: "Live", + sandbox: "Sandbox", + simulator: "Simulator", + off: "Off", +}; + +export function StoreConnectionCard() { + const q = useQuery({ queryKey: STORE_CONNECTION_KEY, queryFn: getStoreConnection, retry: false }); + return ( + {MODE_LABEL[q.data.mode] ?? q.data.mode}} + > + {q.isLoading ? ( +
+ + + +
+ ) : q.isError || !q.data ? ( + void q.refetch()} /> + ) : ( + // Remount on every server change so the form starts from what is stored. + + )} +
+ ); +} + +function SecretStatus({ set }: { set: boolean }) { + return {set ? "Set" : "Not set"}; +} + +function ConnectionForm({ conn }: { conn: StoreConnection }) { + const qc = useQueryClient(); + const confirm = useConfirm(); + const fromEnv = conn.source === "environment"; + const [apiUrl, setApiUrl] = useState(conn.api_url); + const [apiKey, setApiKey] = useState(""); + const [secret, setSecret] = useState(""); + const [result, setResult] = useState<{ ok: StoreConnectionTest } | { error: string } | null>(null); + + const input = (): StoreConnectionInput => ({ + api_url: apiUrl.trim() || conn.default_api_url, + api_key: apiKey.trim() || undefined, + webhook_secret: secret.trim() || undefined, + }); + + async function refresh(next: StoreConnection) { + qc.setQueryData(STORE_CONNECTION_KEY, next); + await Promise.all([ + qc.invalidateQueries({ queryKey: ["admin", "store"] }), + qc.invalidateQueries({ queryKey: INSTANCE_HEALTH_KEY }), + ]); + } + + const testMut = useMutation({ + mutationFn: testStoreConnection, + onSuccess: (ok) => setResult({ ok }), + onError: (e) => { + if (!(e instanceof ReauthCancelledError)) setResult({ error: errorText(e) }); + }, + }); + const saveMut = useMutation({ + mutationFn: saveStoreConnection, + onSuccess: async (next) => { + toast.success("GraphKit API key saved"); + await refresh(next); + }, + onError: (e) => { + if (!(e instanceof ReauthCancelledError)) toast.error(errorText(e)); + }, + }); + const deleteMut = useMutation({ + mutationFn: deleteStoreConnection, + onSuccess: async (next) => { + toast.success("GraphKit disconnected"); + await refresh(next); + }, + onError: (e) => { + if (!(e instanceof ReauthCancelledError)) toast.error(errorText(e)); + }, + }); + + const busy = testMut.isPending || saveMut.isPending || deleteMut.isPending; + // The stored key is only sent to the URL it was saved with. + const urlChanged = conn.api_key_set && trimSlash(apiUrl.trim() || conn.default_api_url) !== trimSlash(conn.api_url); + const keyMissing = (!conn.api_key_set || urlChanged) && !apiKey.trim(); + const saveBlocked = !conn.sealing_available + ? "Set CREDENTIALS_ENCRYPTION_KEY to save a GraphKit API key here." + : keyMissing + ? urlChanged + ? "Enter the API key again to use a different API URL." + : "Enter an API key to save. None is stored yet." + : null; + + function edit(set: (v: string) => void) { + return (v: string) => { + set(v); + setResult(null); + }; + } + + function onSubmit(e: FormEvent) { + e.preventDefault(); + if (fromEnv || saveBlocked || busy) return; + saveMut.mutate(input()); + } + + async function disconnect() { + const ok = await confirm({ + title: "Disconnect GraphKit?", + description: + "The store stops now. New purchases, renewals, monthly billing and Google mailbox connections pause until an API key is added again. The stored API key and webhook secret are deleted.", + confirmLabel: "Disconnect", + destructive: true, + }); + if (ok) deleteMut.mutate(); + } + + const pending = conn.purchases_without_connection; + + return ( +
+ {pending && ( + + {pending.mailboxes} {pending.mailboxes === 1 ? "mailbox" : "mailboxes"} and {pending.domains}{" "} + {pending.domains === 1 ? "domain" : "domains"} were bought here. Renewals, monthly billing and Google + mailbox connections are paused until GraphKit is configured. + + )} + + {fromEnv ? ( +
+ Configured by the environment + GRAPHKIT_* environment variables win over these settings. +
+ ) : ( + !conn.sealing_available && ( + + CREDENTIALS_ENCRYPTION_KEY must be set before GraphKit can be saved here, because the API key and + webhook secret are stored encrypted with it. + + ) + )} + +
+
+ + {fromEnv ? ( +
{conn.api_url}
+ ) : ( + edit(setApiUrl)(e.target.value)} + autoComplete="off" + spellCheck={false} + /> + )} +
+
+ + {!fromEnv && ( + edit(setApiKey)(e.target.value)} + autoComplete="new-password" + placeholder={conn.api_key_set && !urlChanged ? "Leave blank to keep the stored key" : "Required"} + /> + )} +
+
+ + {!fromEnv && ( + edit(setSecret)(e.target.value)} + autoComplete="new-password" + placeholder={conn.webhook_secret_set ? "Leave blank to keep the stored secret" : "From GraphKit"} + /> + )} +
+
+ {!fromEnv && ( +

+ Secrets are never shown again once saved. Leave a field blank to keep the stored value. +

+ )} + +
+ +
+ e.target.select()} /> + +
+

+ In GraphKit, register this URL as your webhook endpoint and paste the signing secret it gives you above. +

+
+ + {result && } + + {!fromEnv && ( +
+ + + {conn.source === "settings" && ( + + )} + {saveBlocked && {saveBlocked}} + {!saveBlocked && conn.updated_at && ( + Saved {new Date(conn.updated_at).toLocaleString()} + )} +
+ )} + + ); +} + +function TestResult({ result }: { result: { ok: StoreConnectionTest } | { error: string } }) { + if ("error" in result) { + return {result.error}; + } + const t = result.ok; + const com = + t.com_register_micros != null + ? `.com ${money(t.com_register_micros, t.currency)} to register${t.com_renew_micros != null ? `, ${money(t.com_renew_micros, t.currency)} to renew` : ""}` + : null; + return ( + + Balance {money(t.balance_micros, t.currency)} + {com && `. ${com}`} + + ); +} + +function CopyButton({ value }: { value: string }) { + const [copied, setCopied] = useState(false); + return ( + + ); +} diff --git a/admin/src/app/dashboard/partners/PartnerDetailPage.tsx b/admin/src/app/dashboard/partners/PartnerDetailPage.tsx new file mode 100644 index 000000000..fbb253aa6 --- /dev/null +++ b/admin/src/app/dashboard/partners/PartnerDetailPage.tsx @@ -0,0 +1,453 @@ +// One partner: its settings, keys, webhook and callback secrets, and the workspaces it manages. +// Reading needs view_organizations; every change needs manage_organizations and a fresh confirmation. + +import { useState, type FormEvent } from "react"; +import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { Link, useParams } from "react-router-dom"; +import { Copy, KeyRound, Plus } from "lucide-react"; +import { toast } from "sonner"; +import { PageHeader } from "@/components/layout/PageHeader"; +import { Panel, Property, PropertyList, StatusBadge } from "@/components/ui/kit"; +import { ErrorState } from "@/components/ErrorState"; +import { DataTable, type Column } from "@/components/data/DataTable"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { useConfirm } from "@/components/ConfirmDialog"; +import { useAdminPerm } from "@/hooks/useAdminPerm"; +import { AdminPerm } from "@/lib/auth/permissions"; +import { PartnerStatements } from "./PartnerStatements"; +import { + createPartnerKey, + getPartner, + listPartnerOrganizations, + revokePartnerKey, + rotatePartnerWebhookSecret, + setPartnerCallbackKey, + updatePartner, + type AdminPartnerDetail, + type AdminPartnerKey, + type AdminPartnerOrganization, + type AdminPartnerUpdate, + type PartnerMode, +} from "@/lib/api/client/admin/partners"; + +const FIELD_LABEL = "text-xs font-medium text-muted-foreground"; +const MICROS = 1_000_000; + +function usdFromMicros(m: number): string { + return (m / MICROS).toLocaleString(undefined, { style: "currency", currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 6 }); +} + +const STATE_TONE = { active: "success", suspended: "warning", cancelled: "danger" } as const; + +const ORG_COLUMNS: Column[] = [ + { + id: "name", + header: "Workspace", + cell: (o) => + o.organization_id ? ( + + {o.organization_name || o.organization_id} + + ) : ( + Deleted + ), + csv: (o) => o.organization_name ?? "", + }, + { id: "external", header: "Partner's id", cell: (o) => {o.external_id}, csv: (o) => o.external_id }, + { id: "mode", header: "Mode", cell: (o) => {o.mode}, csv: (o) => o.mode }, + { + id: "state", + header: "State", + cell: (o) => ( + + {o.state} + + ), + csv: (o) => o.state, + }, + { id: "group", header: "Group", cell: (o) => o.group_name || o.group_external_id || "None", csv: (o) => o.group_external_id ?? "" }, + { id: "cap", header: "Sends / mailbox / day", align: "right", cell: (o) => o.campaign_sends_per_mailbox_per_day, csv: (o) => o.campaign_sends_per_mailbox_per_day }, + { + id: "deletes", + header: "Deletes", + cell: (o) => (o.deletes_at ? new Date(o.deletes_at).toLocaleDateString() : ""), + csv: (o) => o.deletes_at ?? "", + }, +]; + +export default function PartnerDetailPage() { + const { id = "" } = useParams(); + const q = useQuery({ queryKey: ["admin", "partners", id], queryFn: () => getPartner(id), enabled: !!id }); + const p = q.data; + + if (q.error) { + return ( + <> + + void q.refetch()} /> + + ); + } + + return ( + <> + {p.status} : undefined} + /> + {p && ( +
+ + + + + + +
+ )} + + ); +} + +function usePartnerWrite(id: string, fn: (v: T) => Promise, done: string) { + const qc = useQueryClient(); + return useMutation({ + mutationFn: fn, + onSuccess: (res) => { + if (res && typeof res === "object" && "keys" in res) qc.setQueryData(["admin", "partners", id], res as AdminPartnerDetail); + void qc.invalidateQueries({ queryKey: ["admin", "partners"] }); + toast.success(done); + }, + onError: (e: Error) => toast.error(e.message || "That change did not save."), + }); +} + +function PartnerStatusCard({ partner: p }: { partner: AdminPartnerDetail }) { + const confirm = useConfirm(); + const canManage = useAdminPerm(AdminPerm.ManageOrganizations); + const suspended = p.status === "suspended"; + const toggle = usePartnerWrite(p.id, () => updatePartner(p.id, { status: suspended ? "active" : "suspended" }), suspended ? "Partner resumed" : "Partner suspended"); + + async function run() { + const ok = await confirm({ + title: suspended ? `Resume ${p.name}?` : `Suspend ${p.name}?`, + description: suspended + ? "Its keys work again. Workspaces it manages keep their own state." + : "Every one of its keys answers partner_suspended until it is resumed. Workspaces it manages keep running as they are.", + confirmLabel: suspended ? "Resume" : "Suspend", + destructive: !suspended, + }); + if (ok) await toggle.mutateAsync(undefined).catch(() => undefined); + } + + return ( + + + {p.slug} + + Billed through {p.display_name} + {p.allowed_plans.join(", ") || "None"} + + + {p.status} + {canManage && ( + + )} + + + + ); +} + +function PartnerSettingsCard({ partner: p }: { partner: AdminPartnerDetail }) { + const canManage = useAdminPerm(AdminPerm.ManageOrganizations); + const [form, setForm] = useState(() => ({ + name: p.name, + display_name: p.display_name, + allowed_hosts: p.allowed_hosts.join(", "), + delegation_domains: (p.delegation_domains ?? []).join(", "), + webhook_url: p.webhook_url ?? "", + callback_base_url: p.callback_base_url ?? "", + sending: String(p.wholesale_sending_warmup_day_micros / MICROS), + warmup: String(p.wholesale_warmup_only_day_micros / MICROS), + rate: String(p.rate_limit_per_second), + })); + const set = (k: keyof typeof form) => (e: { target: { value: string } }) => setForm((f) => ({ ...f, [k]: e.target.value })); + const save = usePartnerWrite(p.id, (body: AdminPartnerUpdate) => updatePartner(p.id, body), "Partner saved"); + + function submit(e: FormEvent) { + e.preventDefault(); + const toMicros = (v: string) => Math.round(Number(v || "0") * MICROS); + save.mutate({ + name: form.name.trim(), + display_name: form.display_name.trim(), + allowed_hosts: form.allowed_hosts.split(/[\s,]+/).filter(Boolean), + delegation_domains: form.delegation_domains.split(/[\s,]+/).filter(Boolean), + webhook_url: form.webhook_url.trim(), + callback_base_url: form.callback_base_url.trim(), + wholesale_sending_warmup_day_micros: toMicros(form.sending), + wholesale_warmup_only_day_micros: toMicros(form.warmup), + rate_limit_per_second: Number(form.rate), + }); + } + + const field = (id: keyof typeof form, label: string, hint?: string, placeholder?: string) => ( +
+ + + {hint &&

{hint}

} +
+ ); + + return ( + +
+ {field("name", "Name")} + {field("display_name", "Display name", 'Members read "Billed through" this name.')} + {field("allowed_hosts", "Allowed hosts", "Hosts a return URL the partner sends may point at, separated by commas.", "app.example.com")} + {field("rate", "Requests per second", "20 to 1000, across all of the partner's keys.")} + {field( + "delegation_domains", + "Delegation domains", + "Domains you have confirmed the partner controls, separated by commas. A mailbox the partner attaches by delegation connects only on one of these, or on a domain its workspace verified.", + "mail.example.com", + )} + {field("webhook_url", "Webhook URL", "HTTPS. Events are signed with the webhook secret below.", "https://api.example.com/webhooks/warmbly")} + {field("callback_base_url", "Token callback base", "Where per-mailbox access tokens are requested.", "https://api.example.com/v1/warmbly")} + {field("sending", "Wholesale, sending and warmup (USD per mailbox-day)", `Now ${usdFromMicros(p.wholesale_sending_warmup_day_micros)}.`)} + {field("warmup", "Wholesale, warmup only (USD per mailbox-day)", `Now ${usdFromMicros(p.wholesale_warmup_only_day_micros)}.`)} + {canManage && ( +
+ +
+ )} +
+
+ ); +} + +function SecretOnce({ secret, onClose, title, hint }: { secret: string | null; onClose: () => void; title: string; hint: string }) { + return ( + !v && onClose()}> + + + {title} + {hint} + +
+ e.target.select()} /> + +
+ + + +
+
+ ); +} + +function PartnerKeysCard({ partner: p }: { partner: AdminPartnerDetail }) { + const confirm = useConfirm(); + const canManage = useAdminPerm(AdminPerm.ManageOrganizations); + const [secret, setSecret] = useState(null); + const create = usePartnerWrite(p.id, async (mode: PartnerMode) => { + const k = await createPartnerKey(p.id, { mode }); + setSecret(k.secret); + return k; + }, "Key created"); + const revoke = usePartnerWrite(p.id, (keyId: string) => revokePartnerKey(p.id, keyId), "Key revoked"); + + async function askRevoke(k: AdminPartnerKey) { + const ok = await confirm({ + title: `Revoke ${k.key_prefix}…${k.key_suffix}?`, + description: "Anything using this key stops working at once.", + confirmLabel: "Revoke", + destructive: true, + }); + if (ok) await revoke.mutateAsync(k.id).catch(() => undefined); + } + + return ( + + + + + ) + } + bodyClassName="p-0" + > + {p.keys.length === 0 ? ( +

No keys yet.

+ ) : ( +
    + {p.keys.map((k) => ( +
  • + + + {k.key_prefix}…{k.key_suffix} + + {k.mode} + + {k.revoked_at + ? `Revoked ${new Date(k.revoked_at).toLocaleDateString()}` + : k.last_used_at + ? `Used ${new Date(k.last_used_at).toLocaleString()}` + : "Never used"} + + {canManage && !k.revoked_at && ( + + )} +
  • + ))} +
+ )} + setSecret(null)} + title="Copy the key now" + hint="This is the only time the key is shown. Give it to the partner over a secure channel." + /> +
+ ); +} + +function PartnerSecretsCard({ partner: p }: { partner: AdminPartnerDetail }) { + const confirm = useConfirm(); + const canManage = useAdminPerm(AdminPerm.ManageOrganizations); + const [secret, setSecret] = useState(null); + const [callbackKey, setCallbackKey] = useState(""); + const rotate = usePartnerWrite(p.id, async () => { + const r = await rotatePartnerWebhookSecret(p.id); + setSecret(r.secret); + return r; + }, "Webhook secret rotated"); + const saveCallback = usePartnerWrite(p.id, (key: string) => setPartnerCallbackKey(p.id, key), "Callback key saved"); + + async function askRotate() { + if (p.webhook_secret_set) { + const ok = await confirm({ + title: "Rotate the webhook secret?", + description: "Events are signed with both the new and the old secret for a day, then with the new one only.", + confirmLabel: "Rotate", + }); + if (!ok) return; + } + await rotate.mutateAsync(undefined).catch(() => undefined); + } + + return ( + +
+
+
Webhook signing secret
+
+ {p.webhook_secret_set + ? `Set${p.webhook_secret_rotated_at ? `, rotated ${new Date(p.webhook_secret_rotated_at).toLocaleString()}` : ""}` + : "Not set: no events are delivered until it is."} +
+ {canManage && ( + + )} +
+
{ + e.preventDefault(); + saveCallback.mutate(callbackKey.trim(), { onSuccess: () => setCallbackKey("") }); + }} + > + +
+ setCallbackKey(e.target.value)} + disabled={!canManage} + /> + {canManage && ( + + )} +
+
+
+ setSecret(null)} + title="Copy the webhook secret now" + hint="The partner verifies every event with it. This is the only time it is shown." + /> +
+ ); +} + +function PartnerOrganizations({ partnerId }: { partnerId: string }) { + const q = useInfiniteQuery({ + queryKey: ["admin", "partners", partnerId, "organizations"], + queryFn: ({ pageParam }) => listPartnerOrganizations(partnerId, pageParam || undefined), + initialPageParam: "", + getNextPageParam: (last) => (last.pagination.has_more ? (last.pagination.next_cursor ?? undefined) : undefined), + }); + const rows = q.data?.pages.flatMap((p) => p.data) ?? []; + return ( + + o.id} + loading={q.isLoading} + error={q.error} + onRetry={() => void q.refetch()} + emptyTitle="No workspaces" + emptyHint="The partner creates them through its API." + csvName="partner-workspaces" + noun="workspaces" + /> + {q.hasNextPage && ( +
+ +
+ )} +
+ ); +} diff --git a/admin/src/app/dashboard/partners/PartnerStatements.tsx b/admin/src/app/dashboard/partners/PartnerStatements.tsx new file mode 100644 index 000000000..ef49b4baa --- /dev/null +++ b/admin/src/app/dashboard/partners/PartnerStatements.tsx @@ -0,0 +1,78 @@ +// A partner's monthly statement: enabled mailbox-days per workspace at its wholesale rates. Closed months are final. + +import { useState } from "react"; +import { useQuery } from "@tanstack/react-query"; +import { Panel, Property, PropertyList, StatusBadge } from "@/components/ui/kit"; +import { DataTable, type Column } from "@/components/data/DataTable"; +import { getPartnerStatement, listPartnerStatements, type AdminPartnerStatementLine } from "@/lib/api/client/admin/partners"; + +function usd(m: number): string { + return (m / 1_000_000).toLocaleString(undefined, { style: "currency", currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 6 }); +} + +function thisMonth(): string { + return new Date().toISOString().slice(0, 7); +} + +const LINE_COLUMNS: Column[] = [ + { id: "external", header: "Partner's workspace id", cell: (l) => {l.external_id}, csv: (l) => l.external_id }, + { id: "sw", header: "Sending & warmup days", align: "right", cell: (l) => l.sending_warmup_days, csv: (l) => l.sending_warmup_days }, + { id: "wo", header: "Warmup only days", align: "right", cell: (l) => l.warmup_only_days, csv: (l) => l.warmup_only_days }, + { id: "amount", header: "Amount", align: "right", cell: (l) => usd(l.amount_micros), csv: (l) => l.amount_micros / 1_000_000 }, +]; + +export function PartnerStatements({ partnerId }: { partnerId: string }) { + const [month, setMonth] = useState(thisMonth); + const closed = useQuery({ queryKey: ["admin", "partners", partnerId, "statements"], queryFn: () => listPartnerStatements(partnerId) }); + const st = useQuery({ queryKey: ["admin", "partners", partnerId, "statements", month], queryFn: () => getPartnerStatement(partnerId, month) }); + const months = Array.from(new Set([thisMonth(), ...(closed.data?.data ?? []).map((s) => s.month)])); + const s = st.data; + return ( + setMonth(e.target.value)} + className="h-8 rounded-md border border-input bg-background px-2 text-sm" + > + {months.map((m) => ( + + ))} + + } + bodyClassName="p-0" + > + {s && ( + + + {s.closed_at ? "Closed" : "Running"} + + + {s.sending_warmup_days} days at {usd(s.sending_warmup_day_micros)} + + + {s.warmup_only_days} days at {usd(s.warmup_only_day_micros)} + + {usd(s.amount_micros)} + + )} + l.external_id} + loading={st.isLoading} + error={st.error} + onRetry={() => void st.refetch()} + emptyTitle="No enabled mailboxes" + emptyHint="Days count once the partner turns a mailbox on." + csvName={`partner-statement-${month}`} + noun="workspaces" + /> + + ); +} diff --git a/admin/src/app/dashboard/partners/PartnersPage.tsx b/admin/src/app/dashboard/partners/PartnersPage.tsx new file mode 100644 index 000000000..78d64e16a --- /dev/null +++ b/admin/src/app/dashboard/partners/PartnersPage.tsx @@ -0,0 +1,164 @@ +// Partners: resellers that create and run workspaces through /v1/partner. The partner API answers +// nothing until one exists here (or from `warmblyctl partner create`). + +import { useState, type FormEvent } from "react"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useNavigate } from "react-router-dom"; +import { Plus } from "lucide-react"; +import { toast } from "sonner"; +import { PageHeader } from "@/components/layout/PageHeader"; +import { DataTable, type Column } from "@/components/data/DataTable"; +import { StatusBadge } from "@/components/ui/kit"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { useAdminPerm } from "@/hooks/useAdminPerm"; +import { AdminPerm } from "@/lib/auth/permissions"; +import { createPartner, listPartners, type AdminPartner } from "@/lib/api/client/admin/partners"; + +const FIELD_LABEL = "text-xs font-medium text-muted-foreground"; + +const COLUMNS: Column[] = [ + { id: "name", header: "Partner", cell: (p) => {p.name}, csv: (p) => p.name }, + { id: "slug", header: "Slug", cell: (p) => {p.slug}, csv: (p) => p.slug }, + { id: "display", header: "Members see", cell: (p) => `Billed through ${p.display_name}`, csv: (p) => p.display_name }, + { + id: "status", + header: "Status", + cell: (p) => {p.status}, + csv: (p) => p.status, + }, + { id: "webhook", header: "Webhook", cell: (p) => (p.webhook_url && p.webhook_secret_set ? "Set" : "Not set"), csv: (p) => p.webhook_url ?? "" }, +]; + +export default function PartnersPage() { + const nav = useNavigate(); + const canManage = useAdminPerm(AdminPerm.ManageOrganizations); + const [creating, setCreating] = useState(false); + const q = useQuery({ queryKey: ["admin", "partners"], queryFn: listPartners }); + const rows = q.data?.data ?? []; + + return ( + <> + + {canManage && ( + + )} + + + p.id} + loading={q.isLoading} + error={q.error} + onRetry={() => void q.refetch()} + onRowClick={(p) => nav(`/partners/${p.id}`)} + emptyTitle="No partners" + emptyHint="The partner API is off on this instance until a partner exists. Add one only for a reseller you have an agreement with." + csvName="partners" + noun="partners" + /> + + ); +} + +function NewPartnerDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (v: boolean) => void }) { + return ( + + + + New partner + + Adds a reseller with no keys yet. Issue a test key on the next page, then a live one when it is ready. + + + onOpenChange(false)} /> + + + ); +} + +function NewPartnerForm({ onClose }: { onClose: () => void }) { + const nav = useNavigate(); + const qc = useQueryClient(); + const [slug, setSlug] = useState(""); + const [name, setName] = useState(""); + const [display, setDisplay] = useState(""); + const [hosts, setHosts] = useState(""); + const ready = /^[a-z0-9][a-z0-9-]{1,39}$/.test(slug.trim()) && !!name.trim(); + + const create = useMutation({ + mutationFn: () => + createPartner({ + slug: slug.trim(), + name: name.trim(), + display_name: display.trim() || undefined, + allowed_hosts: hosts.split(/[\s,]+/).filter(Boolean), + }), + onSuccess: (p) => { + qc.setQueryData(["admin", "partners", p.id], p); + void qc.invalidateQueries({ queryKey: ["admin", "partners"], exact: true }); + toast.success("Partner created"); + onClose(); + nav(`/partners/${p.id}`); + }, + }); + + function submit(e: FormEvent) { + e.preventDefault(); + if (ready && !create.isPending) create.mutate(); + } + + return ( +
+
+ + setSlug(e.target.value.toLowerCase())} autoFocus /> +

Lowercase letters, digits and dashes. It cannot be changed later.

+
+
+ + setName(e.target.value)} /> +
+
+ + setDisplay(e.target.value)} /> +

Members of its workspaces read "Billed through {display || name || "…"}".

+
+
+ + setHosts(e.target.value)} /> +

Hosts a return URL the partner sends may point at, separated by commas.

+
+ {create.error && ( +

+ {create.error.message || "Failed to create the partner."} +

+ )} + + + + +
+ ); +} diff --git a/admin/src/app/dashboard/store/EconomicsTab.tsx b/admin/src/app/dashboard/store/EconomicsTab.tsx new file mode 100644 index 000000000..d840c7102 --- /dev/null +++ b/admin/src/app/dashboard/store/EconomicsTab.tsx @@ -0,0 +1,135 @@ +// Store economics: GraphKit's wholesale price against the retail price this +// instance charges, per mailbox provider and per domain TLD, and the month's totals. + +import { useQuery } from "@tanstack/react-query"; +import { Wallet } from "lucide-react"; +import { EmptyState, Section, Stat, StatGrid } from "@/components/ui/kit"; +import { Skeleton } from "@/components/ui/skeleton"; +import { ErrorState } from "@/components/ErrorState"; +import { APIError } from "@/lib/api/client"; +import { getStoreEconomics } from "@/lib/api/client/admin/store"; +import { relative } from "@/app/dashboard/jobs/format"; +import { TONE_TEXT } from "@/lib/tones"; +import { cn } from "@/lib/utils"; +import { providerLabel, usd } from "./format"; + +const TH = "h-9 px-3 text-left text-xs font-medium text-muted-foreground whitespace-nowrap"; +const TD = "px-3 py-2 tabular-nums whitespace-nowrap"; + +function marginPct(retail: number, wholesale: number): string { + if (retail <= 0) return "—"; + return `${Math.round(((retail - wholesale) / retail) * 100)}%`; +} + +function Margin({ micros }: { micros: number }) { + return {usd(micros)}; +} + +export function EconomicsTab() { + const q = useQuery({ queryKey: ["admin", "store", "economics"], queryFn: getStoreEconomics, staleTime: 5 * 60_000, retry: false }); + if (q.isLoading) return ; + if (q.error instanceof APIError && q.error.code === "store_disabled") { + return ; + } + if (q.error || !q.data) return q.refetch()} />; + const e = q.data; + + return ( +
+ + + + + + +

+ Prices in {e.currency.toUpperCase()}, read from GraphKit {relative(e.updated_at)}. Mailbox totals only; domain income lands once a year per domain. +

+ +
+
+ + + + + + + + + + + + + + + {e.mailboxes.map((m) => ( + + + + + + + + + + + ))} + {e.mailboxes.length === 0 && ( + + + + )} + +
ProviderWholesaleRetailMarginMargin %Scheduled changeLiveMonthly margin
{providerLabel(m.provider)}{usd(m.wholesale_monthly_micros)}{usd(m.retail_monthly_micros)}{marginPct(m.retail_monthly_micros, m.wholesale_monthly_micros)} + {m.scheduled_wholesale_monthly_micros != null ? ( + m.retail_monthly_micros && TONE_TEXT.danger)}> + {usd(m.scheduled_wholesale_monthly_micros)} + {m.scheduled_from && from {new Date(m.scheduled_from).toLocaleDateString()}} + + ) : ( + None + )} + {m.live_count.toLocaleString()}
No mailbox prices
+
+
+ +
+
+ + + + + + + + + + + + + + + {e.domains.map((d) => ( + + + + + + + + + + + ))} + {e.domains.length === 0 && ( + + + + )} + +
TLDMin yearsRegister wholesaleRegister retailRegister marginRenew wholesaleRenew retailRenew margin
.{d.tld.replace(/^\./, "")}{d.min_years}{usd(d.wholesale_register_micros)}{usd(d.retail_register_micros)}{usd(d.wholesale_renew_micros)}{usd(d.retail_renew_micros)}
No domain prices
+
+
+
+ ); +} diff --git a/admin/src/app/dashboard/store/HealthTab.tsx b/admin/src/app/dashboard/store/HealthTab.tsx new file mode 100644 index 000000000..ee716e071 --- /dev/null +++ b/admin/src/app/dashboard/store/HealthTab.tsx @@ -0,0 +1,220 @@ +// Store health: which GraphKit environment the store talks to, the partner +// balance that pays for every order, whether webhooks and the two loops are +// keeping up, and the counts an operator acts on, each linking to its list. + +import { Link } from "react-router-dom"; +import { AlertTriangle, Bell, Wallet } from "lucide-react"; +import { Callout, EmptyState, Panel, Property, PropertyList, Section, StatusBadge } from "@/components/ui/kit"; +import { Skeleton } from "@/components/ui/skeleton"; +import { ErrorState } from "@/components/ErrorState"; +import type { StoreHealth, StoreLoopStatus } from "@/lib/api/client/admin/store"; +import { absolute, humanSeconds, relative } from "@/app/dashboard/jobs/format"; +import { TONE_TEXT, type Tone } from "@/lib/tones"; +import { cn } from "@/lib/utils"; +import { MODE_TONE, storeLink, usd } from "./format"; +import { useStoreHealth } from "./useStoreHealth"; + +// Webhooks only arrive on change, so a quiet day is normal; past this the reconciler is the only source. +const WEBHOOK_STALE_MS = 24 * 60 * 60 * 1000; +// A loop this far behind has stopped keeping the store current. +const LOOP_LAG_WARN_SECONDS = 60 * 60; + +export function HealthTab() { + const q = useStoreHealth(); + if (q.isLoading) return ; + if (q.error || !q.data) return q.refetch()} />; + const h = q.data; + if (!h.enabled || h.mode === "off") { + return ( + + ); + } + return ( +
+
+ + {h.mode} + + {h.metered ? "charges workspaces" : "unmetered: charges nothing"} +
+ +
+ + + + +
+ +
+ +
+ +
+ {(h.uncollected ?? []).length === 0 ? ( +
+ Every mailbox period was paid before it started +
+ ) : ( +
    + {(h.uncollected ?? []).map((m) => ( +
  • + + {m.email} + + GraphKit to {absolute(m.period_end)}, paid to {absolute(m.paid_through)} + +
  • + ))} +
+ )} +
+ +
+ {h.alerts.length === 0 ? ( +
No recent alerts
+ ) : ( +
    + {h.alerts.map((a, i) => ( +
  • + + {a.title} + {a.code} + + {relative(a.at)} + +
  • + ))} +
+ )} +
+
+ ); +} + +function BalancePanel({ h }: { h: StoreHealth }) { + const b = h.partner_balance; + const low = !!b && b.balance_micros <= b.low_threshold_micros; + return ( + + {!b ? ( + + {h.partner_balance_error === "store_unavailable" ? "GraphKit did not answer the balance read." : "No balance reported."} + + ) : ( + <> +
+ {usd(b.balance_micros)} + {b.currency.toUpperCase()} +
+
+ Low below {usd(b.low_threshold_micros)} + {!b.livemode && ", sandbox funds"} +
+ {low && ( + + Top up the partner account before orders and renewals start failing. + + )} + + )} +
+ ); +} + +function WebhookPanel({ h }: { h: StoreHealth }) { + const stale = !h.last_webhook_at || Date.now() - new Date(h.last_webhook_at).getTime() > WEBHOOK_STALE_MS; + return ( + + + + + {stale && } + {relative(h.last_webhook_at)} + + + {h.events_cursor_set ? "Set" : Not set} + + {stale &&

Nothing in the last day. The reconciler still catches changes, more slowly.

} +
+ ); +} + +function loopTone(loop: StoreLoopStatus): Tone { + const s = loop.last_status.toLowerCase(); + if (s === "error" || s === "failed") return "danger"; + if (loop.lag_seconds > LOOP_LAG_WARN_SECONDS) return "warning"; + return "success"; +} + +function LoopPanel({ title, hint, loop }: { title: string; hint: string; loop: StoreLoopStatus | null }) { + if (!loop) { + return ( + +

Has not run yet on this instance.

+
+ ); + } + const tone = loopTone(loop); + return ( + + {loop.last_status || "unknown"} + + } + > + + + {humanSeconds(loop.lag_seconds)} + + + {relative(loop.last_finished_at)} + + + {relative(loop.last_started_at)} + + {loop.last_error && ( + + {loop.last_error} + + )} + + + ); +} + +function CountGrid({ h }: { h: StoreHealth }) { + const c = h.counts; + const items: { label: string; value: number; to: string; tone: Tone }[] = [ + { label: "Open orders", value: c.orders_open, to: storeLink("orders", { status: "open" }), tone: "info" }, + { label: "Stuck orders", value: c.orders_stuck, to: storeLink("orders", { stuck: "true" }), tone: "danger" }, + { label: "Failed orders, 7 days", value: c.orders_failed_7d, to: storeLink("orders", { status: "failed" }), tone: "danger" }, + { label: "Failed connects", value: c.connects_failed, to: storeLink("mailboxes", { connect_state: "failed" }), tone: "danger" }, + { label: "Billing failures", value: c.mailboxes_billing_failed, to: storeLink("mailboxes", { billing_failed: "true" }), tone: "danger" }, + { label: "Renewal failures", value: c.domains_renewal_failed, to: storeLink("domains", { renewal_failed: "true" }), tone: "danger" }, + { label: "Expiring in 30 days", value: c.domains_expiring_30d, to: storeLink("domains", { expiring_days: "30" }), tone: "warning" }, + { label: "Live mailboxes", value: c.mailboxes_live, to: storeLink("mailboxes", { status: "active" }), tone: "neutral" }, + { label: "Live domains", value: c.domains_live, to: storeLink("domains", { status: "active" }), tone: "neutral" }, + ]; + return ( +
+ {items.map((it) => ( + +
{it.label}
+
0 && it.tone !== "neutral" ? TONE_TEXT[it.tone] : "text-foreground")}> + {it.value.toLocaleString()} +
+ + ))} +
+ ); +} diff --git a/admin/src/app/dashboard/store/RefundDialog.tsx b/admin/src/app/dashboard/store/RefundDialog.tsx new file mode 100644 index 000000000..7fc19d338 --- /dev/null +++ b/admin/src/app/dashboard/store/RefundDialog.tsx @@ -0,0 +1,201 @@ +// Refunds a store order to the workspace balance: one quote line's charge, or +// an amount with a reason, capped at what was charged and not yet refunded. +// The idempotency key belongs to the request body, so a retried click after a +// timeout reuses it and the server never pays twice. + +import { useRef, useState } from "react"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { toast } from "sonner"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Textarea } from "@/components/ui/textarea"; +import { Segmented } from "@/components/ui/kit"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { ReauthCancelledError } from "@/lib/api/client"; +import { refundStoreOrder, type AdminStoreOrder, type StoreRefund } from "@/lib/api/client/admin/store"; +import { cn } from "@/lib/utils"; +import { dollarsToMicros, newIdempotencyKey, refundableMicros, usd } from "./format"; +import { storeErrorText } from "./useStoreAction"; + +type Mode = "line" | "amount"; + +export function RefundDialog({ + order, + open, + onOpenChange, + onRefunded, +}: { + order: AdminStoreOrder; + open: boolean; + onOpenChange: (open: boolean) => void; + onRefunded: (order: AdminStoreOrder) => void; +}) { + return ( + + + {open && onOpenChange(false)} />} + + + ); +} + +function RefundForm({ + order, + onDone, + onCancel, +}: { + order: AdminStoreOrder; + onDone: (order: AdminStoreOrder) => void; + onCancel: () => void; +}) { + const qc = useQueryClient(); + const cap = refundableMicros(order); + const refunded = new Set(order.refunded_lines ?? []); + const openLines = order.lines.map((l, i) => ({ line: l, index: i })).filter((x) => !refunded.has(x.index) && x.line.amount_micros > 0); + const [mode, setMode] = useState(openLines.length > 0 ? "line" : "amount"); + const [line, setLine] = useState(openLines[0]?.index ?? null); + const [amount, setAmount] = useState(""); + const [reason, setReason] = useState(""); + const keyFor = useRef<{ body: string; key: string } | null>(null); + + const micros = dollarsToMicros(amount); + const amountError = + mode !== "amount" || micros === null + ? null + : Number.isNaN(micros) || micros <= 0 + ? "Enter an amount in dollars, like 12.50" + : micros > cap + ? `At most ${usd(cap)} is left to refund` + : null; + + const body: StoreRefund | null = + mode === "line" + ? line === null + ? null + : { line } + : micros && !amountError && reason.trim() + ? { amount_micros: micros, reason: reason.trim() } + : null; + + const refund = useMutation({ + mutationFn: (req: { body: StoreRefund; key: string }) => refundStoreOrder(order.id, req.body, req.key), + onSuccess: (res) => { + toast.success(res.refunded_micros > 0 ? `Refunded ${usd(res.refunded_micros)} to the workspace balance` : "Already refunded; nothing more was paid"); + qc.invalidateQueries({ queryKey: ["admin", "store"] }); + onDone(res.order); + }, + onError: (e) => { + if (!(e instanceof ReauthCancelledError)) toast.error(storeErrorText(e)); + }, + }); + + function submit() { + if (!body) return; + const sig = JSON.stringify(body); + if (keyFor.current?.body !== sig) keyFor.current = { body: sig, key: newIdempotencyKey() }; + refund.mutate({ body, key: keyFor.current.key }); + } + + const lineAmount = line !== null ? order.lines[line]?.amount_micros : undefined; + const total = mode === "line" ? lineAmount : micros && !Number.isNaN(micros) ? micros : undefined; + + return ( + <> + + Refund to the workspace balance + + {order.organization_name} was charged {usd(order.charged_micros)} and has had {usd(order.refunded_micros)} back. + Up to {usd(cap)} can still be refunded. The money goes to the workspace's balance, not the card. + + + +
+ + + {mode === "line" ? ( + openLines.length === 0 ? ( +

Every line with a charge has been refunded.

+ ) : ( +
+ {openLines.map(({ line: l, index }) => ( + + ))} +
+ ) + ) : ( + <> +
+ + setAmount(e.target.value)} + aria-invalid={!!amountError} + /> + {amountError &&

{amountError}

} +
+
+ +