Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/utils/api/.server/TenantsApi.ts
T
2026-07-08 16:15:37 +02:00

49 lines
1.7 KiB
TypeScript

import { getTranslations } from "~/locale/i18next.server";
import { createTenant } from "../../db/tenants.db.server";
import { getUser, updateUserDefaultTenantId } from "../../db/users.db.server";
import { getUserInfo } from "../../session.server";
import { TenantTypesApi } from "./TenantTypesApi";
import EventsService from "../../../modules/events/services/.server/EventsService";
import { AccountCreatedDto } from "~/modules/events/dtos/AccountCreatedDto";
import { autosubscribeToTrialOrFreePlan } from "../../services/.server/pricingService";
import { appPath } from "../../app/CanonicalUrlUtils";
export namespace TenantsApi {
export async function create({ request, name, slug }: { request: Request; name: string; slug?: string }) {
const { t } = await getTranslations(request);
let userInfo = await getUserInfo(request);
const user = await getUser(userInfo.userId);
if (!user) {
throw new Error("User not found");
}
if (!name) {
throw new Error("Name is required");
}
const tenant = await createTenant({ name, slug });
await updateUserDefaultTenantId({ defaultTenantId: tenant.id }, user.id);
await autosubscribeToTrialOrFreePlan({ request, t, tenantId: tenant.id, userId: user.id });
await EventsService.create({
request,
event: "account.created",
tenantId: tenant.id,
userId: user.id,
data: {
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
user: { id: user.id, email: user.email },
} satisfies AccountCreatedDto,
});
await TenantTypesApi.setTenantTypes({ tenantId: tenant.id });
return {
redirectTo: appPath({ tenantSlug: tenant.slug, path: "dashboard", mode: "host-aware" }),
tenant,
user,
};
}
}