import { useTranslation } from "react-i18next"; import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router"; import { useActionData, useSubmit } from "react-router"; import { useAppData } from "~/utils/data/useAppData"; import { getTranslations } from "~/locale/i18next.server"; import { getTenant, getTenantBySlug, updateTenant, type TenantWithDetails } from "~/utils/db/tenants.db.server"; import { getTenantIdFromUrl } from "~/utils/services/.server/urlService"; import UpdateTenantDetailsForm from "~/components/core/tenants/UpdateTenantDetailsForm"; import { createLog } from "~/utils/db/logs.db.server"; import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper"; import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService"; import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary"; import { useEffect, useRef } from "react"; import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal"; import { deleteAndCancelTenant, isReservedTenantSlug, normalizeTenantSlug } from "~/utils/services/tenantService"; import EventsService from "~/modules/events/services/.server/EventsService"; import { getUser } from "~/utils/db/users.db.server"; import { getUserInfo, validateCSRFToken } from "~/utils/session.server"; import { getActiveTenantSubscriptions } from "~/utils/services/.server/subscriptionService"; import { storeFile } from "~/utils/integrations/storageService"; import { auditRejectedUpload } from "~/utils/integrations/storageAudit.server"; import { getTenantTypeOptions } from "~/utils/db/tenants/tenantTypes.db.server"; import EditPageLayout from "~/components/ui/layouts/EditPageLayout"; import SettingSection from "~/components/ui/sections/SettingSection"; import { AccountUpdatedDto } from "~/modules/events/dtos/AccountUpdatedDto"; import { AccountDeletedDto } from "~/modules/events/dtos/AccountDeletedDto"; import toast from "react-hot-toast"; import { appPath } from "~/utils/app/CanonicalUrlUtils"; import { useRootData } from "~/utils/data/useRootData"; import { loadRequiredWebConfig } from "@hivegrid/config"; import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls"; type LoaderData = { title: string; tenant: TenantWithDetails; tenantTypes: Awaited>; }; export const loader = async ({ request, params }: LoaderFunctionArgs) => { const tenantId = await getTenantIdFromUrl(params); await verifyUserHasPermission(request, "app.settings.account.view", tenantId); const { t } = await getTranslations(request); const [tenant, tenantTypes] = await Promise.all([getTenant(tenantId), getTenantTypeOptions()]); if (!tenant) { throw Error(t("shared.notFound")); } const data: LoaderData = { title: `${t("models.tenant.object")} | ${process.env.APP_NAME}`, tenant, tenantTypes, }; return data; }; type ActionData = { updateDetailsError?: string; deleteError?: string; success?: string; }; const badRequest = (data: ActionData) => Response.json(data, { status: 400 }); export const action: ActionFunction = async ({ request, params }) => { const { t } = await getTranslations(request); await validateCSRFToken(request); const userInfo = await getUserInfo(request); const currentUser = await getUser(userInfo.userId); const tenantId = await getTenantIdFromUrl(params); await verifyUserHasPermission(request, "app.settings.account.update", tenantId); const form = await request.formData(); const action = form.get("action")?.toString() ?? ""; const tenant = await getTenant(tenantId); if (!tenant || !currentUser) { return redirect(absoluteAppRootPath(loadRequiredWebConfig().routing)); } 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("settings.tenant.errors.notFound") }); } await createLog(request, tenantId, "settings.tenant.updateDetails", JSON.stringify({ name, slug })); if (existing?.slug !== slug) { const existingSlug = await getTenantBySlug(slug); if (existingSlug) { return badRequest({ updateDetailsError: t("settings.tenant.errors.slugTaken"), }); } let iconStored = icon ? await storeFile({ bucket: "accounts-icons", content: icon, id: tenantId, scan: { context: "avatar", enqueuePostScan: true, onReject: auditRejectedUpload(request, "tenant.account.icon"), filename: `${tenantId}.icon` }, }) : icon; await updateTenant(existing, { name, icon: iconStored, slug }); await EventsService.create({ 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, }); return redirect(appPath({ tenantSlug: slug, path: "settings/account", mode: "host-aware" })); } else { let iconStored = icon ? await storeFile({ bucket: "accounts-icons", content: icon, id: tenantId, scan: { context: "avatar", enqueuePostScan: true, onReject: auditRejectedUpload(request, "tenant.account.icon"), filename: `${tenantId}.icon` }, }) : icon; await updateTenant(existing, { name, icon: iconStored, slug }); await EventsService.create({ 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, }); const actionData: ActionData = { success: t("settings.tenant.updated"), }; return Response.json(actionData); } } else if (action === "delete") { await verifyUserHasPermission(request, "app.settings.account.delete", tenantId); const activeSubscriptions = await getActiveTenantSubscriptions(tenantId); if (activeSubscriptions && activeSubscriptions.products.find((f) => !f.cancelledAt)) { return badRequest({ deleteError: t("settings.tenant.errors.cannotDeleteWithActiveSubscriptions"), }); } await EventsService.create({ request, event: "account.deleted", tenantId: null, userId: currentUser.id, data: { tenant: { id: tenant.id, name: tenant.name }, user: { id: currentUser.id, email: currentUser.email }, } satisfies AccountDeletedDto, }); await deleteAndCancelTenant({ tenantId, userId: userInfo.userId, t }); return redirect(absoluteAppRootPath(loadRequiredWebConfig().routing)); } else { return badRequest({ updateDetailsError: t("shared.invalidForm") }); } }; export const meta: MetaFunction = ({ data }) => [{ title: data?.title }]; export default function TenantRoute() { const data = useLoaderData(); const appData = useAppData(); const actionData = useActionData(); const { t } = useTranslation(); const submit = useSubmit(); const rootData = useRootData(); const confirmDelete = useRef(null); useEffect(() => { if (actionData?.success) { toast.success(actionData.success); } else if (actionData?.updateDetailsError) { toast.error(actionData.updateDetailsError); } else if (actionData?.deleteError) { toast.error(actionData.deleteError); } }, [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"); if (rootData.csrf) { form.set("csrf", rootData.csrf); } submit(form, { method: "post" }); } return ( {/*Separator */}
{/*Danger */}
{t("settings.danger.deleteWorkspace")}
); }