713 lines
30 KiB
TypeScript
713 lines
30 KiB
TypeScript
import { useTranslation } from "react-i18next";
|
|
import { ActionFunction, Link, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData, useNavigation } from "react-router";
|
|
import { useActionData, useParams, useSubmit } from "react-router";
|
|
import { Activity, ArrowRight, CreditCard, ExternalLink, KeyRound, ShieldAlert, Users } from "lucide-react";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { getTenant, getTenantBySlug, updateTenant, type TenantWithDetails } from "~/utils/db/tenants.db.server";
|
|
import UpdateTenantDetailsForm from "~/components/core/tenants/UpdateTenantDetailsForm";
|
|
import { createAdminLog } from "~/utils/db/logs.db.server";
|
|
import UsersTable from "~/components/core/users/UsersTable";
|
|
import { adminGetAllTenantUsers, getUser } from "~/utils/db/users.db.server";
|
|
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
|
import { getTenantSubscription, type TenantSubscriptionWithDetails } from "~/utils/db/tenantSubscriptions.db.server";
|
|
import { getAllSubscriptionProducts } from "~/utils/db/subscriptionProducts.db.server";
|
|
import { Fragment, useEffect, useRef } from "react";
|
|
import ErrorModal, { RefErrorModal } from "~/components/ui/modals/ErrorModal";
|
|
import SuccessModal, { RefSuccessModal } from "~/components/ui/modals/SuccessModal";
|
|
import { useAdminData } from "~/utils/data/useAdminData";
|
|
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
|
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
|
import { deleteAndCancelTenant, isReservedTenantSlug, normalizeTenantSlug } from "~/utils/services/tenantService";
|
|
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
|
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
|
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
|
import EventsService from "~/modules/events/services/.server/EventsService";
|
|
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
|
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
|
import SettingSection from "~/components/ui/sections/SettingSection";
|
|
import { AccountDeletedDto } from "~/modules/events/dtos/AccountDeletedDto";
|
|
import { AccountUpdatedDto } from "~/modules/events/dtos/AccountUpdatedDto";
|
|
import { useRootData } from "~/utils/data/useRootData";
|
|
import { absoluteAppPath } from "~/utils/app/CrossHostUrls";
|
|
import { Badge, type BadgeColor } from "~/components/ui/badge";
|
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
|
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
|
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
|
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
|
import { AdminPageHeader } from "~/components/screens/admin/AdminPageHeader";
|
|
import {
|
|
ADMIN_TENANT_NOTE_CATEGORIES,
|
|
buildAdminConnectorListVM,
|
|
buildAdminTenantNoteListVM,
|
|
type AdminConnectorListVM,
|
|
type AdminTenantNoteListVM,
|
|
type ConnectorOverrideState,
|
|
} from "@hivegrid/view-models";
|
|
import { AdminTenantOperationsPanel } from "~/components/screens/admin/AdminTenantOperationsPanel";
|
|
import { AdminActionInputError } from "~/services/admin/admin-action-audit.server";
|
|
import { AdminBillingError, extendTenantTrial } from "~/services/admin/billing-admin.server";
|
|
import { AdminConnectorError, getTenantConnectorRows, setTenantFeatureConnector } from "~/services/admin/subscription-assembly.server";
|
|
import { createTenantNote, deleteTenantNote, getTenantNoteRows, TenantNoteError } from "~/services/admin/tenant-notes.server";
|
|
import { db } from "~/utils/db.server";
|
|
import { useSaveToast } from "~/hooks/use-save-toast";
|
|
|
|
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
|
|
|
type TenantSupportTone = "success" | "warning" | "danger" | "neutral";
|
|
|
|
type TenantSupportMetric = {
|
|
id: string;
|
|
labelKey: string;
|
|
value: string;
|
|
detailKey: string;
|
|
tone: TenantSupportTone;
|
|
href?: string;
|
|
};
|
|
|
|
type TenantSupportAction = {
|
|
id: string;
|
|
labelKey: string;
|
|
detailKey: string;
|
|
href: string;
|
|
external?: boolean;
|
|
};
|
|
|
|
type TenantSupportSummary = {
|
|
status: TenantSupportTone;
|
|
statusLabelKey: string;
|
|
statusDetail: string | null;
|
|
ownerEmail: string | null;
|
|
planCode: string | null;
|
|
seatQuantity: number | null;
|
|
billingStatus: string | null;
|
|
providerSummaryKey: string;
|
|
metrics: TenantSupportMetric[];
|
|
actions: TenantSupportAction[];
|
|
};
|
|
|
|
type LoaderData = {
|
|
title: string;
|
|
tenant: TenantWithDetails;
|
|
users: Awaited<ReturnType<typeof adminGetAllTenantUsers>>;
|
|
subscription: TenantSubscriptionWithDetails | null;
|
|
subscriptionProducts: SubscriptionProductDto[];
|
|
supportSummary: TenantSupportSummary;
|
|
connectors: AdminConnectorListVM;
|
|
notes: AdminTenantNoteListVM;
|
|
trial: { status: string | null; trialEndsAtIso: string | null };
|
|
};
|
|
|
|
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
|
await verifyUserHasPermission(request, "admin.account.view");
|
|
const { t } = await getTranslations(request);
|
|
const tenantId = params.id;
|
|
if (!tenantId) {
|
|
throw redirect(adminPath("accounts", { mode: "host-aware" }));
|
|
}
|
|
|
|
return runWithRlsContext({ tenantId }, async () => {
|
|
const tenant = await getTenant(tenantId);
|
|
if (!tenant) {
|
|
throw redirect(adminPath("accounts", { mode: "host-aware" }));
|
|
}
|
|
const [users, subscription, subscriptionProducts, connectorRows, noteRows, trialSubscription] = await Promise.all([
|
|
adminGetAllTenantUsers(tenant.id),
|
|
getTenantSubscription(tenantId),
|
|
getAllSubscriptionProducts(),
|
|
getTenantConnectorRows(tenantId),
|
|
getTenantNoteRows(tenantId),
|
|
db.tenantSubscription.findUnique({ where: { tenantId }, select: { status: true, trialEndsAt: true } }),
|
|
]);
|
|
const data: LoaderData = {
|
|
title: `${t("models.tenant.object")} | ${process.env.APP_NAME}`,
|
|
tenant,
|
|
users,
|
|
subscription,
|
|
subscriptionProducts,
|
|
supportSummary: buildTenantSupportSummary({ tenant, users, subscription }),
|
|
connectors: buildAdminConnectorListVM({ rows: connectorRows }),
|
|
notes: buildAdminTenantNoteListVM({ rows: noteRows }),
|
|
trial: {
|
|
status: trialSubscription?.status ?? null,
|
|
trialEndsAtIso: trialSubscription?.trialEndsAt?.toISOString() ?? null,
|
|
},
|
|
};
|
|
return data;
|
|
});
|
|
};
|
|
|
|
type ActionData = {
|
|
intent?: string;
|
|
ok?: boolean;
|
|
messageKey?: string;
|
|
updateSubscriptionSuccess?: string;
|
|
updateDetailsError?: string;
|
|
updateSubscriptionError?: string;
|
|
opsSuccess?: string;
|
|
opsError?: string;
|
|
};
|
|
|
|
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
|
export const action: ActionFunction = async ({ request, params }) => {
|
|
await verifyUserHasPermission(request, "admin.account.settings.update");
|
|
const { t } = await getTranslations(request);
|
|
const userInfo = await getUserInfo(request);
|
|
const currentUser = await getUser(userInfo.userId);
|
|
if (!currentUser) {
|
|
return badRequest({ updateDetailsError: t("shared.invalidUser") });
|
|
}
|
|
await validateCSRFToken(request);
|
|
const form = await request.formData();
|
|
const action = form.get("action")?.toString() ?? "";
|
|
const tenantId = params.id;
|
|
if (!tenantId) {
|
|
return redirect(adminPath("accounts", { mode: "host-aware" }));
|
|
}
|
|
|
|
return runWithRlsContext({ tenantId }, async () => {
|
|
const tenant = await getTenant(tenantId);
|
|
if (!tenant) {
|
|
return redirect(adminPath("accounts", { mode: "host-aware" }));
|
|
}
|
|
|
|
if (action === "edit") {
|
|
const name = form.get("name")?.toString() ?? "";
|
|
const slug = normalizeTenantSlug(form.get("slug")?.toString() ?? "");
|
|
const icon = form.get("icon")?.toString() ?? "";
|
|
|
|
if ((name?.length ?? 0) < 1) {
|
|
return badRequest({
|
|
updateDetailsError: t("settings.tenant.errors.nameRequired"),
|
|
});
|
|
}
|
|
if (!slug || slug.length < 1) {
|
|
return badRequest({ updateDetailsError: t("settings.tenant.errors.slugRequired") });
|
|
}
|
|
|
|
if (isReservedTenantSlug(slug)) {
|
|
return badRequest({
|
|
updateDetailsError: t("settings.tenant.errors.reservedSlug", { slug }),
|
|
});
|
|
}
|
|
if (slug.includes(" ")) {
|
|
return badRequest({
|
|
updateDetailsError: t("settings.tenant.errors.slugWhitespace"),
|
|
});
|
|
}
|
|
|
|
const existing = await getTenant(tenantId);
|
|
if (!existing) {
|
|
return badRequest({ updateDetailsError: t("admin.accounts.errors.invalidTenant") });
|
|
}
|
|
|
|
if (existing.slug !== slug) {
|
|
const existingSlug = await getTenantBySlug(slug);
|
|
if (existingSlug) {
|
|
return badRequest({
|
|
updateDetailsError: t("settings.tenant.errors.slugTaken"),
|
|
});
|
|
}
|
|
}
|
|
await createAdminLog(request, "settings.tenant.updateDetails", JSON.stringify({ name, slug }));
|
|
|
|
await EventsService.createTenantEventWithMutation(
|
|
{
|
|
request,
|
|
event: "account.updated",
|
|
tenantId: tenant.id,
|
|
userId: currentUser.id,
|
|
data: {
|
|
id: tenant.id,
|
|
new: { name, slug },
|
|
old: { name: tenant.name, slug: tenant.slug },
|
|
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
|
} satisfies AccountUpdatedDto,
|
|
},
|
|
() => updateTenant(existing, { name, icon, slug })
|
|
);
|
|
return Response.json({
|
|
intent: "edit",
|
|
ok: true,
|
|
messageKey: "admin.accounts.toast.updated",
|
|
} satisfies ActionData);
|
|
} else if (action === "trial-extend" || action === "connector-set" || action === "note-create" || action === "note-delete") {
|
|
const actor = { actorUserId: currentUser.id, actorEmail: currentUser.email, request };
|
|
try {
|
|
if (action === "trial-extend") {
|
|
await extendTenantTrial({
|
|
tenantId: tenant.id,
|
|
days: form.get("days")?.toString() ?? "",
|
|
reason: form.get("reason")?.toString() ?? "",
|
|
...actor,
|
|
});
|
|
return Response.json({ opsSuccess: t("admin.tenantOps.trial.extended") } satisfies ActionData);
|
|
}
|
|
if (action === "connector-set") {
|
|
const state = form.get("state")?.toString() ?? "";
|
|
if (state !== "enabled" && state !== "disabled" && state !== "inherit") {
|
|
return badRequest({ opsError: t("shared.invalidForm") });
|
|
}
|
|
await setTenantFeatureConnector({
|
|
tenantId: tenant.id,
|
|
featureKey: form.get("featureKey")?.toString() ?? "",
|
|
state: state satisfies ConnectorOverrideState,
|
|
reason: form.get("reason")?.toString() ?? "",
|
|
...actor,
|
|
});
|
|
return Response.json({ opsSuccess: t("admin.connectors.updated") } satisfies ActionData);
|
|
}
|
|
if (action === "note-create") {
|
|
await createTenantNote({
|
|
tenantId: tenant.id,
|
|
noteText: form.get("noteText")?.toString() ?? "",
|
|
category: form.get("category")?.toString() ?? null,
|
|
pinned: form.get("pinned")?.toString() === "true",
|
|
authorUserId: currentUser.id,
|
|
actorEmail: currentUser.email,
|
|
request,
|
|
});
|
|
return Response.json({ opsSuccess: t("admin.tenantNotes.created") } satisfies ActionData);
|
|
}
|
|
await deleteTenantNote({
|
|
noteId: form.get("noteId")?.toString() ?? "",
|
|
tenantId: tenant.id,
|
|
...actor,
|
|
});
|
|
return Response.json({ opsSuccess: t("admin.tenantNotes.deleted") } satisfies ActionData);
|
|
} catch (error) {
|
|
if (error instanceof AdminActionInputError || error instanceof AdminConnectorError || error instanceof TenantNoteError) {
|
|
return badRequest({ opsError: t(error.i18nKey) });
|
|
}
|
|
if (error instanceof AdminBillingError) {
|
|
return badRequest({ opsError: t(error.i18nKey) });
|
|
}
|
|
// Unexpected failures (e.g. the audit writer refusing an unauditable
|
|
// action) surface as a Klartext banner instead of a naked 500 page.
|
|
// eslint-disable-next-line no-console
|
|
console.error("admin tenant-ops action failed", { action, tenantId }, error);
|
|
return badRequest({ opsError: t("admin.tenantOps.errors.actionFailed") });
|
|
}
|
|
} else if (action === "delete-tenant") {
|
|
await deleteAndCancelTenant({
|
|
request,
|
|
tenantId: tenant.id,
|
|
userId: currentUser.id,
|
|
eventData: { tenant: { id: tenant.id, name: tenant.name }, user: { id: currentUser.id, email: currentUser.email } } satisfies AccountDeletedDto,
|
|
});
|
|
return redirect(`${adminPath("accounts", { mode: "host-aware" })}?toast=${encodeURIComponent("admin.accounts.toast.deleted")}`);
|
|
} else {
|
|
return badRequest({ updateDetailsError: t("shared.invalidForm") });
|
|
}
|
|
});
|
|
};
|
|
|
|
export default function TenantRoute() {
|
|
const adminData = useAdminData();
|
|
const rootData = useRootData();
|
|
const params = useParams();
|
|
const data = useLoaderData<LoaderData>();
|
|
const actionData = useActionData<ActionData>();
|
|
const { t } = useTranslation();
|
|
const submit = useSubmit();
|
|
const navigation = useNavigation();
|
|
useSaveToast(actionData, { intents: ["edit"] });
|
|
|
|
const errorModal = useRef<RefErrorModal>(null);
|
|
const successModal = useRef<RefSuccessModal>(null);
|
|
const confirmDelete = useRef<RefConfirmModal>(null);
|
|
|
|
useEffect(() => {
|
|
if (actionData?.updateSubscriptionSuccess) {
|
|
successModal.current?.show(actionData?.updateSubscriptionSuccess);
|
|
} else if (actionData?.updateSubscriptionError) {
|
|
errorModal.current?.show(actionData?.updateSubscriptionError);
|
|
} else if (actionData?.updateDetailsError) {
|
|
errorModal.current?.show(actionData?.updateDetailsError);
|
|
}
|
|
}, [actionData]);
|
|
|
|
function deleteAccount() {
|
|
confirmDelete.current?.show(t("settings.danger.confirmDeleteTenant"), t("shared.confirm"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
|
}
|
|
function confirmDeleteTenant() {
|
|
const form = new FormData();
|
|
form.set("action", "delete-tenant");
|
|
form.set("csrf", rootData.csrf ?? "");
|
|
submit(form, { method: "post" });
|
|
}
|
|
|
|
return (
|
|
<div className="flex w-full flex-col">
|
|
<AdminPageHeader title={data.tenant.name} description={t("admin.accounts.detailPageDescription", { slug: data.tenant.slug })} />
|
|
<EditPageLayout
|
|
fullWidth
|
|
menu={[
|
|
{ title: t("models.tenant.plural"), routePath: adminPath("accounts", { mode: "host-aware" }) },
|
|
{ title: data.tenant?.name ?? "", routePath: adminPath(`accounts/${params.id ?? ""}`, { mode: "host-aware" }) },
|
|
]}
|
|
>
|
|
<TenantSupportConsole data={data} />
|
|
|
|
<div className="block">
|
|
<div className="py-5">
|
|
<div className="border-border border-t"></div>
|
|
</div>
|
|
</div>
|
|
|
|
{/* AK-P19 DoD #3: trial extension, connector assembly, operator notes */}
|
|
{getUserHasPermission(adminData, "admin.account.settings.update") && (
|
|
<Fragment>
|
|
<AdminTenantOperationsPanel
|
|
connectors={data.connectors}
|
|
notes={data.notes}
|
|
trial={data.trial}
|
|
noteCategories={ADMIN_TENANT_NOTE_CATEGORIES}
|
|
csrf={rootData.csrf ?? ""}
|
|
submitting={navigation.state === "submitting"}
|
|
feedback={{ success: actionData?.opsSuccess, error: actionData?.opsError }}
|
|
/>
|
|
|
|
<div className="block">
|
|
<div className="py-5">
|
|
<div className="border-border border-t"></div>
|
|
</div>
|
|
</div>
|
|
</Fragment>
|
|
)}
|
|
|
|
<SettingSection title={t("settings.tenant.general")} description={t("settings.tenant.generalDescription")}>
|
|
<div className="mt-5 md:col-span-2 md:mt-0">
|
|
<UpdateTenantDetailsForm tenant={data.tenant} disabled={!getUserHasPermission(adminData, "admin.account.settings.update")} />
|
|
</div>
|
|
</SettingSection>
|
|
|
|
{/*Separator */}
|
|
<div className="block">
|
|
<div className="py-5">
|
|
<div className="border-border border-t"></div>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Tenant Users */}
|
|
{getUserHasPermission(adminData, "admin.account.users") && (
|
|
<Fragment>
|
|
<SettingSection title={t("models.user.plural")}>
|
|
<div className="mt-5 md:col-span-2 md:mt-0">
|
|
<UsersTable
|
|
items={data.users}
|
|
canImpersonate={getUserHasPermission(adminData, "admin.users.impersonate")}
|
|
canChangePassword={getUserHasPermission(adminData, "admin.users.changePassword")}
|
|
canSetUserRoles={false}
|
|
canDelete={getUserHasPermission(adminData, "admin.users.delete")}
|
|
/>
|
|
</div>
|
|
</SettingSection>
|
|
|
|
{/*Separator */}
|
|
<div className="block">
|
|
<div className="py-5">
|
|
<div className="border-border border-t"></div>
|
|
</div>
|
|
</div>
|
|
</Fragment>
|
|
)}
|
|
|
|
{/* Tenant Subscription */}
|
|
{/* {getUserHasPermission(adminData, "admin.account.subscription") && (
|
|
<>
|
|
<div className="md:grid lg:grid-cols-3 md:gap-2">
|
|
<div className="md:col-span-1">
|
|
<div className="sm:px-0">
|
|
<h3 className="text-lg font-medium leading-6 text-foreground">{t("models.subscriptionProduct.object")}</h3>
|
|
</div>
|
|
</div>
|
|
<div className="mt-5 md:mt-0 md:col-span-2">
|
|
<UpdateTenantSubscriptionForm
|
|
tenant={data.tenant}
|
|
subscription={data.subscription}
|
|
subscriptionProducts={data.subscriptionProducts}
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="block">
|
|
<div className="py-5">
|
|
<div className="border-t border-border"></div>
|
|
</div>
|
|
</div>
|
|
</>
|
|
)} */}
|
|
|
|
{/*Danger */}
|
|
{getUserHasPermission(adminData, "admin.account.delete") && (
|
|
<SettingSection title={t("settings.danger.title")} description={t("settings.danger.description")} tone="danger">
|
|
<div className="mt-12 md:col-span-2 md:mt-0">
|
|
<div>
|
|
<input hidden type="text" name="action" value="deleteAccount" readOnly />
|
|
<div className="">
|
|
<div className="">
|
|
<h3 className="text-foreground text-lg leading-6 font-medium">{t("admin.accounts.danger.deleteAccountTitle")}</h3>
|
|
<div className="text-muted-foreground mt-2 max-w-xl text-sm leading-5">
|
|
<p>{t("admin.accounts.danger.deleteAccountDescription")}</p>
|
|
</div>
|
|
<div className="mt-4">
|
|
<ButtonPrimary destructive={true} onClick={deleteAccount}>
|
|
{t("settings.danger.deleteAccount")}
|
|
</ButtonPrimary>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</SettingSection>
|
|
)}
|
|
|
|
<ConfirmModal ref={confirmDelete} onYes={confirmDeleteTenant} />
|
|
<SuccessModal ref={successModal} />
|
|
<ErrorModal ref={errorModal} />
|
|
</EditPageLayout>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export function buildTenantSupportSummary({
|
|
tenant,
|
|
users,
|
|
subscription,
|
|
}: {
|
|
tenant: TenantWithDetails;
|
|
users: Awaited<ReturnType<typeof adminGetAllTenantUsers>>;
|
|
subscription: TenantSubscriptionWithDetails | null;
|
|
}): TenantSupportSummary {
|
|
const owner = tenant.users.find((item) => item.type === TenantUserType.OWNER)?.user ?? users[0] ?? null;
|
|
const activeUsers = users.filter((user) =>
|
|
user.tenants.some((membership) => membership.tenantId === tenant.id && membership.status === TenantUserStatus.ACTIVE)
|
|
).length;
|
|
const hasLago = Boolean(subscription?.lagoCustomerId);
|
|
const hasMollie = Boolean(subscription?.mollieCustomerId);
|
|
const billingAttention = Boolean(
|
|
subscription?.status === "past_due" || subscription?.status === "frozen" || subscription?.pastDueSince || subscription?.frozenAt
|
|
);
|
|
const status: TenantSupportTone = !tenant.active || tenant.deactivatedReason ? "danger" : billingAttention ? "warning" : "success";
|
|
|
|
return {
|
|
status,
|
|
statusLabelKey:
|
|
tenant.active && !tenant.deactivatedReason ? "admin.accounts.supportConsole.status.active" : "admin.accounts.supportConsole.status.inactive",
|
|
statusDetail: tenant.deactivatedReason,
|
|
ownerEmail: owner?.email ?? null,
|
|
planCode: subscription?.planCode ?? null,
|
|
seatQuantity: subscription?.seatQuantity ?? null,
|
|
billingStatus: subscription?.status ?? null,
|
|
providerSummaryKey:
|
|
hasLago && hasMollie
|
|
? "admin.accounts.supportConsole.providers.complete"
|
|
: hasLago || hasMollie
|
|
? "admin.accounts.supportConsole.providers.partial"
|
|
: "admin.accounts.supportConsole.providers.missing",
|
|
metrics: [
|
|
{
|
|
id: "users",
|
|
labelKey: "admin.accounts.supportConsole.metrics.users.label",
|
|
value: String(activeUsers),
|
|
detailKey: "admin.accounts.supportConsole.metrics.users.detail",
|
|
tone: activeUsers > 0 ? "success" : "warning",
|
|
href: adminPath(`accounts/users?tenantId=${tenant.id}`, { mode: "host-aware" }),
|
|
},
|
|
{
|
|
id: "billing",
|
|
labelKey: "admin.accounts.supportConsole.metrics.billing.label",
|
|
value: subscription?.status ?? "-",
|
|
detailKey: billingAttention
|
|
? "admin.accounts.supportConsole.metrics.billing.detailAttention"
|
|
: "admin.accounts.supportConsole.metrics.billing.detailOk",
|
|
tone: billingAttention ? "warning" : subscription ? "success" : "neutral",
|
|
href: adminPath("system/billing", { mode: "host-aware" }),
|
|
},
|
|
{
|
|
id: "providers",
|
|
labelKey: "admin.accounts.supportConsole.metrics.providers.label",
|
|
value: [hasLago ? "Lago" : null, hasMollie ? "Mollie" : null].filter(Boolean).join(" / ") || "-",
|
|
detailKey:
|
|
hasLago && hasMollie ? "admin.accounts.supportConsole.metrics.providers.detailOk" : "admin.accounts.supportConsole.metrics.providers.detailMissing",
|
|
tone: hasLago && hasMollie ? "success" : "warning",
|
|
href: adminPath("system/billing", { mode: "host-aware" }),
|
|
},
|
|
],
|
|
actions: [
|
|
{
|
|
id: "open-tenant",
|
|
labelKey: "admin.accounts.supportConsole.actions.openTenant.label",
|
|
detailKey: "admin.accounts.supportConsole.actions.openTenant.detail",
|
|
href: "",
|
|
external: true,
|
|
},
|
|
{
|
|
id: "users",
|
|
labelKey: "admin.accounts.supportConsole.actions.users.label",
|
|
detailKey: "admin.accounts.supportConsole.actions.users.detail",
|
|
href: adminPath(`accounts/users?tenantId=${tenant.id}`, { mode: "host-aware" }),
|
|
},
|
|
{
|
|
id: "audit",
|
|
labelKey: "admin.accounts.supportConsole.actions.audit.label",
|
|
detailKey: "admin.accounts.supportConsole.actions.audit.detail",
|
|
href: adminPath(`audit?tenantId=${tenant.id}`, { mode: "host-aware" }),
|
|
},
|
|
{
|
|
id: "security",
|
|
labelKey: "admin.accounts.supportConsole.actions.security.label",
|
|
detailKey: "admin.accounts.supportConsole.actions.security.detail",
|
|
href: adminPath(`accounts/${tenant.id}/security`, { mode: "host-aware" }),
|
|
},
|
|
{
|
|
id: "events",
|
|
labelKey: "admin.accounts.supportConsole.actions.events.label",
|
|
detailKey: "admin.accounts.supportConsole.actions.events.detail",
|
|
href: adminPath(`events?tenantId=${tenant.id}`, { mode: "host-aware" }),
|
|
},
|
|
],
|
|
};
|
|
}
|
|
|
|
function TenantSupportConsole({ data }: { data: LoaderData }) {
|
|
const { t } = useTranslation();
|
|
const rootData = useRootData();
|
|
const summary = data.supportSummary;
|
|
const appHref = absoluteAppPath(rootData.routing, data.tenant.slug, "dashboard");
|
|
|
|
return (
|
|
<div className="space-y-4">
|
|
<Card className="gap-5 rounded-lg py-5">
|
|
<CardHeader>
|
|
<div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
|
|
<div className="min-w-0 space-y-3">
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<Badge color={toneToBadgeColor(summary.status)} withColorDot>
|
|
{t(summary.statusLabelKey)}
|
|
</Badge>
|
|
<Badge color={summary.billingStatus === "past_due" || summary.billingStatus === "frozen" ? "yellow" : "gray"} withColorDot>
|
|
{summary.billingStatus ?? t("admin.accounts.supportConsole.billing.noSubscription")}
|
|
</Badge>
|
|
</div>
|
|
<div>
|
|
<CardTitle className="text-xl leading-7">{t("admin.accounts.supportConsole.title")}</CardTitle>
|
|
<CardDescription className="mt-1 max-w-3xl leading-5">{t("admin.accounts.supportConsole.description")}</CardDescription>
|
|
</div>
|
|
</div>
|
|
<div className="flex flex-wrap gap-2">
|
|
<Link
|
|
to={appHref}
|
|
target="_blank"
|
|
rel="noreferrer"
|
|
className="border-border bg-background hover:bg-surface-neutral-secondary inline-flex items-center gap-2 rounded-md border px-3 py-2 text-sm font-medium"
|
|
>
|
|
{t("admin.accounts.supportConsole.openInApp")}
|
|
<ExternalLink className="size-4" aria-hidden="true" />
|
|
</Link>
|
|
<Link
|
|
to={adminPath(`audit?tenantId=${data.tenant.id}`, { mode: "host-aware" })}
|
|
className="border-border bg-background hover:bg-surface-neutral-secondary inline-flex items-center gap-2 rounded-md border px-3 py-2 text-sm font-medium"
|
|
>
|
|
{t("admin.accounts.supportConsole.openAudit")}
|
|
<Activity className="size-4" aria-hidden="true" />
|
|
</Link>
|
|
</div>
|
|
</div>
|
|
</CardHeader>
|
|
<CardContent className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(280px,0.45fr)]">
|
|
<div className="grid gap-3 md:grid-cols-3">
|
|
{summary.metrics.map((metric) => (
|
|
<SupportMetricCard key={metric.id} metric={metric} />
|
|
))}
|
|
</div>
|
|
<dl className="bg-background grid gap-3 rounded-md border p-4 text-sm">
|
|
<SupportDetail label={t("admin.accounts.supportConsole.fields.slug")} value={`/${data.tenant.slug}`} />
|
|
<SupportDetail label={t("admin.accounts.supportConsole.fields.owner")} value={summary.ownerEmail ?? t("shared.none")} />
|
|
<SupportDetail label={t("admin.accounts.supportConsole.fields.plan")} value={summary.planCode ?? t("shared.none")} />
|
|
<SupportDetail
|
|
label={t("admin.accounts.supportConsole.fields.seats")}
|
|
value={summary.seatQuantity ? String(summary.seatQuantity) : t("shared.none")}
|
|
/>
|
|
<SupportDetail label={t("admin.accounts.supportConsole.fields.providers")} value={t(summary.providerSummaryKey)} />
|
|
{summary.statusDetail ? (
|
|
<SupportDetail label={t("admin.accounts.supportConsole.fields.reason")} value={summary.statusDetail} tone="danger" />
|
|
) : null}
|
|
</dl>
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
|
|
{summary.actions.map((action) => (
|
|
<SupportActionCard key={action.id} action={{ ...action, href: action.id === "open-tenant" ? appHref : action.href }} />
|
|
))}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function SupportMetricCard({ metric }: { metric: TenantSupportMetric }) {
|
|
const { t } = useTranslation();
|
|
const content = (
|
|
<div className="bg-background hover:bg-surface-neutral-secondary/60 flex h-full min-h-28 flex-col justify-between gap-3 rounded-md border p-4 transition-colors">
|
|
<div className="flex items-start justify-between gap-3">
|
|
<div className="min-w-0">
|
|
<p className="truncate text-sm leading-5 font-medium">{t(metric.labelKey)}</p>
|
|
<p className="text-text-neutral-tertiary mt-1 text-xs leading-4">{t(metric.detailKey)}</p>
|
|
</div>
|
|
<MetricIcon id={metric.id} tone={metric.tone} />
|
|
</div>
|
|
<p className="truncate text-2xl leading-7 font-semibold">{metric.value}</p>
|
|
</div>
|
|
);
|
|
|
|
if (!metric.href) return content;
|
|
return (
|
|
<Link to={metric.href} className="focus-visible:shadow-focus block focus-visible:outline-none">
|
|
{content}
|
|
</Link>
|
|
);
|
|
}
|
|
|
|
function SupportActionCard({ action }: { action: TenantSupportAction }) {
|
|
const { t } = useTranslation();
|
|
return (
|
|
<Link
|
|
to={action.href}
|
|
target={action.external ? "_blank" : undefined}
|
|
rel={action.external ? "noreferrer" : undefined}
|
|
className="border-border bg-background hover:bg-surface-neutral-secondary/60 focus-visible:shadow-focus flex min-h-24 items-start justify-between gap-3 rounded-lg border p-4 transition-colors focus-visible:outline-none"
|
|
>
|
|
<div className="min-w-0">
|
|
<p className="text-sm leading-5 font-medium">{t(action.labelKey)}</p>
|
|
<p className="text-text-neutral-tertiary mt-1 text-xs leading-4">{t(action.detailKey)}</p>
|
|
</div>
|
|
<ArrowRight className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
|
|
</Link>
|
|
);
|
|
}
|
|
|
|
function SupportDetail({ label, value, tone = "neutral" }: { label: string; value: string; tone?: TenantSupportTone }) {
|
|
return (
|
|
<div className="grid grid-cols-[7rem_minmax(0,1fr)] gap-3">
|
|
<dt className="text-text-neutral-tertiary">{label}</dt>
|
|
<dd className={tone === "danger" ? "text-red-700" : "text-foreground truncate font-medium"}>{value}</dd>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function MetricIcon({ id, tone }: { id: string; tone: TenantSupportTone }) {
|
|
const className = tone === "danger" ? "text-red-600" : tone === "warning" ? "text-yellow-600" : tone === "success" ? "text-green-600" : "text-gray-500";
|
|
if (id === "users") return <Users className={`size-4 shrink-0 ${className}`} aria-hidden="true" />;
|
|
if (id === "billing") return <CreditCard className={`size-4 shrink-0 ${className}`} aria-hidden="true" />;
|
|
if (id === "providers") return <KeyRound className={`size-4 shrink-0 ${className}`} aria-hidden="true" />;
|
|
return <ShieldAlert className={`size-4 shrink-0 ${className}`} aria-hidden="true" />;
|
|
}
|
|
|
|
function toneToBadgeColor(tone: TenantSupportTone): BadgeColor {
|
|
if (tone === "success") return "green";
|
|
if (tone === "danger") return "red";
|
|
if (tone === "warning") return "yellow";
|
|
return "gray";
|
|
}
|