Files
HiveGrid-Wireframes/hivegrid-cloud/apps/web/app/routes/admin/marketing-integrations.tsx
T

229 lines
10 KiB
TypeScript

/**
* Admin marketing-integrations CRUD (Phase 05 #79).
*
* Lists every `MarketingIntegration`, lets operators add a new outbound
* adapter (Slack / Discord / Mailchimp / HubSpot / Brevo / custom
* webhook), toggle enable / disable, and delete. Sensitive fields
* (webhookUrl, apiKey, accessToken, signingSecret) are encrypted at
* rest via `marketingIntegrations.db.server.ts`. The list view masks
* secrets — edit requires re-entering them.
*/
import { ActionFunctionArgs, Form, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
import { useTranslation } from "react-i18next";
import {
createMarketingIntegration,
deleteMarketingIntegration,
listMarketingIntegrations,
maskConfig,
updateMarketingIntegration,
type MarketingIntegrationType,
} from "~/utils/leads/marketingIntegrations.db.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTranslations } from "~/locale/i18next.server";
import { useLocaleFormatters } from "~/locale/format";
const TRIGGER_EVENTS = [
"marketing.lead.captured",
"marketing.lead.qualified",
"marketing.lead.convertedtotrial",
"marketing.lead.convertedtocustomer",
] as const;
const TYPES: MarketingIntegrationType[] = ["slack", "discord", "mailchimp", "hubspot", "brevo", "webhook"];
type Loader = Awaited<ReturnType<typeof loader>>;
type LoaderData = Loader extends Response ? never : Loader;
export const loader = async ({ request }: LoaderFunctionArgs) => {
await verifyUserHasPermission(request, "admin.marketing.integrations.view");
const integrations = await listMarketingIntegrations();
// Mask config before sending to the client so secrets never leave the server.
const items = integrations.map((i) => ({
id: i.id,
type: i.type,
name: i.name,
enabled: i.enabled,
triggerEvents: i.triggerEvents,
maskedConfig: maskConfig(i.config),
lastDeliveredAt: i.lastDeliveredAt,
lastError: i.lastError,
}));
return { items };
};
export const action = async ({ request }: ActionFunctionArgs) => {
await verifyUserHasPermission(request, "admin.marketing.integrations.manage");
const { t } = await getTranslations(request);
const form = await request.formData();
const op = form.get("op")?.toString();
if (op === "create") {
const type = form.get("type")?.toString();
const name = form.get("name")?.toString()?.trim() ?? "";
const triggerEvents = (form.getAll("triggerEvents") as string[]).filter((e) =>
TRIGGER_EVENTS.includes(e as (typeof TRIGGER_EVENTS)[number]),
);
const configRaw = form.get("config")?.toString() ?? "{}";
if (!type || !TYPES.includes(type as MarketingIntegrationType)) {
return { error: t("admin.marketingIntegrations.errors.invalidType") };
}
if (name.length === 0) return { error: t("admin.marketingIntegrations.errors.nameRequired") };
if (triggerEvents.length === 0) return { error: t("admin.marketingIntegrations.errors.triggerRequired") };
let config: Record<string, unknown>;
try {
const parsed = JSON.parse(configRaw);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("must be object");
config = parsed as Record<string, unknown>;
} catch {
return { error: t("admin.marketingIntegrations.errors.invalidConfig") };
}
await createMarketingIntegration({
type: type as MarketingIntegrationType,
name,
triggerEvents,
config,
});
return redirect("/admin/marketing-integrations");
}
if (op === "toggle") {
const id = form.get("id")?.toString();
const enabled = form.get("enabled")?.toString() === "true";
if (!id) return { error: t("admin.marketingIntegrations.errors.idRequired") };
await updateMarketingIntegration(id, { enabled });
return redirect("/admin/marketing-integrations");
}
if (op === "delete") {
const id = form.get("id")?.toString();
if (!id) return { error: t("admin.marketingIntegrations.errors.idRequired") };
await deleteMarketingIntegration(id);
return redirect("/admin/marketing-integrations");
}
return { error: t("admin.marketingIntegrations.errors.unknownOperation") };
};
export default function MarketingIntegrationsAdmin() {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const { items } = useLoaderData() as LoaderData;
const actionData = useActionData() as { error?: string } | undefined;
return (
<div className="mx-auto mb-12 max-w-5xl space-y-5 px-4 py-4 sm:px-6 lg:px-8">
<header className="border-border border-b pb-4">
<h1 className="text-lg font-medium">{t("admin.marketingIntegrations.title")}</h1>
<p className="text-muted-foreground text-sm">
{t("admin.marketingIntegrations.description")}
</p>
</header>
{actionData?.error ? (
<div className="rounded-md border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-900">
{actionData.error}
</div>
) : null}
<section className="rounded-md border p-4">
<h2 className="text-sm font-semibold uppercase tracking-wide">{t("admin.marketingIntegrations.form.addTitle")}</h2>
<Form method="post" className="mt-3 grid gap-2 sm:grid-cols-2">
<input type="hidden" name="op" value="create" />
<label className="space-y-1 text-xs text-muted-foreground">
<span>{t("admin.marketingIntegrations.form.type")}</span>
<select name="type" className="border-border block w-full rounded-md border px-2 py-1 text-sm">
{TYPES.map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</select>
</label>
<label className="space-y-1 text-xs text-muted-foreground">
<span>{t("shared.name")}</span>
<input name="name" type="text" required className="border-border block w-full rounded-md border px-2 py-1 text-sm" />
</label>
<label className="space-y-1 text-xs text-muted-foreground sm:col-span-2">
<span>{t("admin.marketingIntegrations.form.triggerEvents")}</span>
<div className="flex flex-wrap gap-2">
{TRIGGER_EVENTS.map((ev) => (
<label key={ev} className="flex items-center gap-1 text-xs">
<input type="checkbox" name="triggerEvents" value={ev} /> {ev}
</label>
))}
</div>
</label>
<label className="space-y-1 text-xs text-muted-foreground sm:col-span-2">
<span>{t("admin.marketingIntegrations.form.configJson")}</span>
<textarea
name="config"
rows={4}
defaultValue='{ "webhookUrl": "https://hooks.slack.com/..." }'
className="border-border block w-full rounded-md border px-2 py-1 font-mono text-xs"
/>
</label>
<div className="sm:col-span-2">
<button type="submit" className="bg-primary text-primary-foreground rounded-md px-3 py-1.5 text-sm">
{t("admin.marketingIntegrations.form.addTitle")}
</button>
</div>
</Form>
</section>
<section className="space-y-2">
<h2 className="text-sm font-semibold uppercase tracking-wide">{t("admin.marketingIntegrations.configuredTitle")}</h2>
{items.length === 0 ? (
<p className="text-muted-foreground text-sm">{t("admin.marketingIntegrations.empty")}</p>
) : (
<ul className="divide-border divide-y rounded-md border">
{items.map((it) => (
<li key={it.id} className="space-y-1 p-3 text-sm">
<div className="flex items-center justify-between">
<div>
<span className="font-medium">{it.name}</span>{" "}
<span className="text-muted-foreground text-xs">({it.type})</span>{" "}
{it.enabled ? (
<span className="rounded bg-emerald-100 px-1.5 py-0.5 text-xs text-emerald-800">{t("shared.enabled")}</span>
) : (
<span className="rounded bg-gray-100 px-1.5 py-0.5 text-xs text-gray-700">{t("shared.disabled")}</span>
)}
</div>
<div className="flex gap-2">
<Form method="post">
<input type="hidden" name="op" value="toggle" />
<input type="hidden" name="id" value={it.id} />
<input type="hidden" name="enabled" value={(!it.enabled).toString()} />
<button type="submit" className="rounded border px-2 py-1 text-xs">
{it.enabled ? t("shared.disable") : t("shared.enable")}
</button>
</Form>
<Form method="post" onSubmit={(e) => { if (!window.confirm(t("admin.marketingIntegrations.confirmDelete"))) e.preventDefault(); }}>
<input type="hidden" name="op" value="delete" />
<input type="hidden" name="id" value={it.id} />
<button type="submit" className="rounded border border-rose-200 bg-rose-50 px-2 py-1 text-xs text-rose-700">
{t("shared.delete")}
</button>
</Form>
</div>
</div>
<div className="text-muted-foreground text-xs">
{t("admin.marketingIntegrations.card.triggers")}: {it.triggerEvents.join(", ") || t("shared.none")}
</div>
<pre className="bg-muted overflow-x-auto rounded p-2 font-mono text-[11px] leading-snug">
{JSON.stringify(it.maskedConfig, null, 2)}
</pre>
{it.lastDeliveredAt ? (
<div className="text-muted-foreground text-xs">
{t("admin.marketingIntegrations.card.lastDelivered")}: {formatters.dateTime(it.lastDeliveredAt)}
</div>
) : null}
{it.lastError ? (
<div className="text-xs text-rose-700">{t("admin.marketingIntegrations.card.lastError")}: {it.lastError}</div>
) : null}
</li>
))}
</ul>
)}
</section>
</div>
);
}