import { useTranslation } from "react-i18next"; import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router"; import { useActionData, useParams, useSubmit } from "react-router"; import { getTranslations } from "~/locale/i18next.server"; import { getTenant, getTenantBySlug, getTenantUsers, 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 { getOrPersistTenantSubscription, getTenantSubscription, updateTenantSubscriptionCustomerId, type TenantSubscriptionWithDetails, } from "~/utils/db/tenantSubscriptions.db.server"; import { getAllSubscriptionProducts } from "~/utils/db/subscriptionProducts.db.server"; import { createStripeCustomer, isStripeTestMode } from "~/utils/stripe.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 { TenantUserType } from "~/application/enums/tenants/TenantUserType"; import { getUserInfo, validateCSRFToken } from "~/utils/session.server"; import EventsService from "~/modules/events/services/.server/EventsService"; import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto"; import { findEntityByName, type EntityWithDetails } from "~/utils/db/entities/entities.db.server"; import { RowsApi } from "~/utils/api/.server/RowsApi"; import { getAllTenantTypes, getTenantTypeOptions } from "~/utils/db/tenants/tenantTypes.db.server"; 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"; export const meta: MetaFunction = ({ data }) => [{ title: data?.title }]; type LoaderData = { title: string; tenant: TenantWithDetails; users: Awaited>; subscription: TenantSubscriptionWithDetails | null; subscriptionProducts: SubscriptionProductDto[]; isStripeTest: boolean; tenantSettingsEntity: EntityWithDetails | null; tenantTypes: Awaited>; }; export const loader = async ({ request, params }: LoaderFunctionArgs) => { await verifyUserHasPermission(request, "admin.account.view"); const { t } = await getTranslations(request); const tenant = await getTenant(params.id!); if (!tenant) { throw redirect(adminPath("accounts", { mode: "host-aware" })); } const [users, subscription, subscriptionProducts, tenantSettingsEntity, tenantTypes] = await Promise.all([ adminGetAllTenantUsers(tenant.id), getTenantSubscription(params.id ?? ""), getAllSubscriptionProducts(), findEntityByName({ tenantId: null, name: "tenantSettings" }), getTenantTypeOptions(), ]); const data: LoaderData = { title: `${t("models.tenant.object")} | ${process.env.APP_NAME}`, tenant, users, subscription, subscriptionProducts, isStripeTest: isStripeTestMode(), tenantSettingsEntity, tenantTypes, }; return data; }; type ActionData = { updateSubscriptionSuccess?: string; updateDetailsError?: string; updateSubscriptionError?: 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 tenant = await getTenant(params.id ?? ""); 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() ?? ""; const typeIds = form.getAll("typeIds[]").map((t) => t.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") }); } let tenantTypes = await getAllTenantTypes(); typeIds.forEach((type) => { if (!tenantTypes.find((t) => t.id === type)) { return badRequest({ updateDetailsError: t("admin.accounts.errors.invalidTenantType"), }); } }); 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(params.id!); 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 })); const tenantSettingsEntity = await findEntityByName({ tenantId: null, name: "tenantSettings" }); if (tenantSettingsEntity) { try { await RowsApi.createCustom({ entity: tenantSettingsEntity, tenantId: existing.id, t, form, row: existing?.tenantSettingsRow?.row as Parameters[0]["row"], rowCreateInput: { tenantSettingsRow: { create: { tenantId: existing.id } } }, request, }); } catch { return badRequest({ updateDetailsError: t("admin.accounts.errors.updateDetailsFailed") }); } } 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, }); await updateTenant(existing, { name, icon, slug, typeIds }); return Response.json({ success: t("settings.tenant.updated"), }); } else if (action === "create-stripe-customer") { if (!tenant) { return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.invalidTenant") }); } const tenantUsers = await getTenantUsers(params.id ?? ""); if (tenantUsers.length === 0) { return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.noUsers") }); } const tenantOwner = tenantUsers.find((user) => user.type === TenantUserType.OWNER); if (!tenantOwner) { return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.noOwner") }); } const tenantSubscription = await getOrPersistTenantSubscription(tenant.id); if (tenantSubscription.stripeCustomerId) { return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.customerAlreadySet") }); } const stripeCustomer = await createStripeCustomer(tenantOwner.user.email, tenant.name); if (!stripeCustomer) { return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.createFailed") }); } await updateTenantSubscriptionCustomerId(tenant.id, { stripeCustomerId: stripeCustomer.id, }); const data: ActionData = { updateSubscriptionSuccess: t("admin.accounts.subscriptionCustomer.actions.created"), }; return data; } else if (action === "delete-tenant") { await EventsService.create({ request, event: "account.deleted", tenantId: null, userId: userInfo.userId, data: { tenant: { id: tenant.id, name: tenant.name }, user: { id: currentUser.id, email: currentUser.email } } satisfies AccountDeletedDto, }); await deleteAndCancelTenant({ tenantId: tenant.id, userId: currentUser.id }); return redirect(adminPath("accounts", { mode: "host-aware" })); } else { return badRequest({ updateDetailsError: t("shared.invalidForm") }); } }; export default function TenantRoute() { const adminData = useAdminData(); const rootData = useRootData(); const params = useParams(); const data = useLoaderData(); const actionData = useActionData(); const { t } = useTranslation(); const submit = useSubmit(); const errorModal = useRef(null); const successModal = useRef(null); const confirmDelete = useRef(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 (
{/*Separator */}
{/* Tenant Users */} {getUserHasPermission(adminData, "admin.account.users") && (
{/*Separator */}
)} {/* Tenant Subscription */} {/* {getUserHasPermission(adminData, "admin.account.subscription") && ( <>

{t("models.subscriptionProduct.object")}

)} */} {/*Danger */} {getUserHasPermission(adminData, "admin.account.delete") && (

{t("admin.accounts.danger.deleteAccountTitle")}

{t("admin.accounts.danger.deleteAccountDescription")}

{t("settings.danger.deleteAccount")}
)}
); }