Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

♻️ Move space creation from registration to setup (#2713)

Luke Vella0d804dbde5ee
diff --git a/apps/web/src/app/[locale]/setup/actions.ts b/apps/web/src/app/[locale]/setup/actions.ts
index 3f082011e..b2f3da893 100644
--- a/apps/web/src/app/[locale]/setup/actions.ts
+++ b/apps/web/src/app/[locale]/setup/actions.ts
@@ -1,11 +1,9 @@
"use server";
-import { subject } from "@casl/ability";
import * as z from "zod";
import { adoptOrphanedPolls } from "@/features/poll/mutations";
-import { getActiveSpaceForUser } from "@/features/space/data";
-import { defineAbilityForMember } from "@/features/space/member/ability";
-import { createSpace, updateSpace } from "@/features/space/mutations";
+import { getOwnedSpace } from "@/features/space/data";
+import { createSpace } from "@/features/space/mutations";
import { identifyGroup, track } from "@/lib/posthog";
import { authActionClient } from "@/lib/safe-action/server";
@@ -18,76 +16,74 @@ const setupSpaceSchema = z.discriminatedUnion("spaceType", [
]);
/**
- * Names the user's space during onboarding: renames the active space when
- * they're allowed to (every new account owns an auto-created "Personal"
- * space), or creates one when they have none. A member of someone else's
- * space who owns no space of their own gets nothing renamed or relabeled.
+ * Creates the user's space at the end of onboarding — registration doesn't
+ * create one, so this is where every account gets theirs. Accounts that
+ * already own a space (pre-existing accounts sent through setup to backfill
+ * profile fields, or a re-submit) only retry poll adoption: setup never
+ * renames or duplicates an existing space.
*/
export const setupSpaceAction = authActionClient
.metadata({ actionName: "setup_space" })
.inputSchema(setupSpaceSchema)
.action(async ({ ctx, parsedInput }) => {
+ const ownedSpace = await getOwnedSpace(ctx.user.id);
+
+ if (ownedSpace) {
+ // Create and adopt aren't atomic: a previous submit may have created
+ // the space and failed before adoption, so retries still pull
+ // orphaned polls in (a no-op when there are none).
+ await adoptOrphanedPolls({
+ userId: ctx.user.id,
+ spaceId: ownedSpace.id,
+ });
+ return;
+ }
+
const name =
parsedInput.spaceType === "work"
? parsedInput.organizationName
: "Personal";
- const existingSpace = await getActiveSpaceForUser(ctx.user.id);
+ const space = await createSpace({
+ name,
+ ownerId: ctx.user.id,
+ });
- let spaceId: string | null = null;
+ // Guest linking migrates polls without a space; pull them into the one
+ // just created.
+ await adoptOrphanedPolls({
+ userId: ctx.user.id,
+ spaceId: space.id,
+ });
- if (!existingSpace) {
- const space = await createSpace({
+ identifyGroup({
+ distinctId: ctx.user.id,
+ groupType: "space",
+ groupKey: space.id,
+ properties: {
+ type: parsedInput.spaceType,
name,
- ownerId: ctx.user.id,
- });
- // Guest linking into an account without a space migrates polls with
- // no space; pull them into the one just created.
- await adoptOrphanedPolls({
- userId: ctx.user.id,
- spaceId: space.id,
- });
- spaceId = space.id;
- } else {
- const ability = defineAbilityForMember({
- user: ctx.user,
- space: existingSpace,
- });
-
- if (ability.can("update", subject("Space", existingSpace))) {
- await updateSpace({
- spaceId: existingSpace.id,
- name,
- });
- spaceId = existingSpace.id;
- }
- }
+ tier: space.tier,
+ member_count: 1,
+ seat_count: 1,
+ },
+ });
- if (spaceId) {
- identifyGroup({
- groupType: "space",
- groupKey: spaceId,
- properties: {
- type: parsedInput.spaceType,
+ track(ctx.user, {
+ event: "space_setup",
+ properties: {
+ space_type: parsedInput.spaceType,
+ // The register event $sets these from the user row at creation
+ // time, which for OTP signups is an empty name and no timezone.
+ // The form updates both right before this action runs, so patch
+ // the person profile here.
+ $set: {
+ name: ctx.user.name,
+ timeZone: ctx.user.timeZone ?? undefined,
},
- });
-
- track(ctx.user, {
- event: "space_setup",
- properties: {
- space_type: parsedInput.spaceType,
- // The register event $sets these from the user row at creation
- // time, which for OTP signups is an empty name and no timezone.
- // The form updates both right before this action runs, so patch
- // the person profile here.
- $set: {
- name: ctx.user.name,
- timeZone: ctx.user.timeZone ?? undefined,
- },
- },
- groups: {
- space: spaceId,
- },
- });
- }
+ },
+ groups: {
+ space: space.id,
+ },
+ });
});
diff --git a/apps/web/src/app/[locale]/setup/components/setup-form.tsx b/apps/web/src/app/[locale]/setup/components/setup-form.tsx
index 09de60898..d5546bf1b 100644
--- a/apps/web/src/app/[locale]/setup/components/setup-form.tsx
+++ b/apps/web/src/app/[locale]/setup/components/setup-form.tsx
@@ -14,7 +14,6 @@ import {
import { Input } from "@rallly/ui/input";
import { RadioGroup, RadioGroupItem } from "@rallly/ui/radio-group";
import { BriefcaseIcon, UserIcon } from "lucide-react";
-import { useRouter } from "next/navigation";
import React from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
@@ -24,6 +23,7 @@ import { Trans, useTranslation } from "@/i18n/client";
import { authClient } from "@/lib/auth-client";
import { getLocaleDefaults } from "@/lib/datetime/locales";
import type { TimeFormat } from "@/lib/datetime/types";
+import { useLocale } from "@/lib/locale/client";
import { useSafeAction } from "@/lib/safe-action/client";
import { getBrowserTimeZone } from "@/lib/utils/date-time-utils";
@@ -85,8 +85,8 @@ export function SetupForm({
defaultTimeZone?: string;
defaultTimeFormat?: TimeFormat;
}) {
- const { t, i18n } = useTranslation();
- const router = useRouter();
+ const { t } = useTranslation();
+ const { locale } = useLocale();
const schema = useSetupFormSchema();
const setupSpace = useSafeAction(setupSpaceAction);
@@ -95,8 +95,7 @@ export function SetupForm({
defaultValues: {
name: defaultName,
timeZone: defaultTimeZone || getBrowserTimeZone(),
- timeFormat:
- defaultTimeFormat ?? getLocaleDefaults(i18n.language).timeFormat,
+ timeFormat: defaultTimeFormat ?? getLocaleDefaults(locale).timeFormat,
spaceType: "personal" as const,
organizationName: "",
},
@@ -119,7 +118,7 @@ export function SetupForm({
name,
timeZone,
timeFormat,
- locale: i18n.language,
+ locale,
});
if (res.error) {
@@ -129,20 +128,15 @@ export function SetupForm({
return;
}
- const result = await setupSpace.executeAsync(
+ // Server errors surface through the global useSafeAction toast;
+ // the button unlocks (hasSucceeded stays false) so the user can
+ // retry. On success the hook refreshes the router and the page
+ // redirects onward while the button stays loading.
+ await setupSpace.executeAsync(
spaceType === "work"
? { spaceType, organizationName: organizationName.trim() }
: { spaceType },
);
-
- // Server errors surface through the global useSafeAction toast;
- // stay on the form so the user can retry. On success the hook
- // refreshes the router and the page redirects onward.
- if (result?.serverError || result?.validationErrors) {
- return;
- }
-
- router.refresh();
},
)}
className="space-y-4"
@@ -296,9 +290,7 @@ export function SetupForm({
type="submit"
variant="primary"
size="lg"
- loading={
- form.formState.isSubmitting || form.formState.isSubmitSuccessful
- }
+ loading={form.formState.isSubmitting || setupSpace.hasSucceeded}
className="w-full"
>
<Trans i18nKey="continue" defaults="Continue" />
diff --git a/apps/web/src/features/auth/mutations.ts b/apps/web/src/features/auth/mutations.ts
index 4396dfb26..b2d08e9d6 100644
--- a/apps/web/src/features/auth/mutations.ts
+++ b/apps/web/src/features/auth/mutations.ts
@@ -54,8 +54,9 @@ export const linkAnonymousUser = async (
});
if (!spaceId) {
- // Reached when the guest links before the user-create hook has
- // provisioned the space, or when the user's only memberships are
+ // Reached when the guest links into a brand-new account that hasn't
+ // been through /setup yet (setup creates the space and adopts these
+ // orphaned polls), or when the user's only memberships are
// ineffective (non-owner rows in hobby spaces). Transfer ownership
// anyway — the anonymous user is deleted right after linking and
// polls cascade with it — and leave spaceId null.
diff --git a/apps/web/src/features/space/data.ts b/apps/web/src/features/space/data.ts
index f60b15f7f..8db1874f3 100644
--- a/apps/web/src/features/space/data.ts
+++ b/apps/web/src/features/space/data.ts
@@ -181,6 +181,13 @@ export const getActiveSpace = cache(async () => {
return space;
});
+export const getOwnedSpace = cache(async (userId: string) => {
+ return prisma.space.findFirst({
+ where: { ownerId: userId },
+ select: { id: true },
+ });
+});
+
export const getActiveSpaceForUser = cache(async (userId: string) => {
const spaceMember = await prisma.spaceMember.findFirst({
where: effectiveSpaceMemberWhere({ userId }),
diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.ts
index 6592057ae..10045d072 100644
--- a/apps/web/src/lib/auth.ts
+++ b/apps/web/src/lib/auth.ts
@@ -27,8 +27,6 @@ import { env } from "@/env";
import { linkAnonymousUser } from "@/features/auth/mutations";
import { isEmailBlocked, isTemporaryEmail } from "@/features/auth/utils";
import { getStripe } from "@/features/billing/service";
-import { adoptOrphanedPolls } from "@/features/poll/mutations";
-import { createSpace } from "@/features/space/mutations";
import type { UserDTO } from "@/features/user/schema";
import { getTranslation } from "@/i18n/server";
import { getLocale } from "@/i18n/server/get-locale";
@@ -40,7 +38,7 @@ import {
LOCALE_COOKIE_OPTIONS,
} from "@/lib/locale/constants";
import { getPathname } from "@/lib/pathname";
-import { identifyGroup, track } from "@/lib/posthog";
+import { track } from "@/lib/posthog";
import { getValueByPath } from "@/lib/utils/get-value-by-path";
import { buildSafeRedirectUrl } from "@/lib/utils/redirect";
@@ -475,40 +473,8 @@ export const authLib = betterAuth({
if (user.isAnonymous) {
return;
}
- // check if user exists in prisma
- const existingUser = await prisma.user.findUnique({
- where: {
- id: user.id,
- },
- });
-
- if (existingUser) {
- // create a space for the user
- const space = await createSpace({
- name: "Personal",
- ownerId: user.id,
- });
-
- // Guest linking can run before this hook (a sign-in that
- // creates the account links the anonymous user first), leaving
- // migrated polls without a space. Adopt them now.
- await adoptOrphanedPolls({
- userId: user.id,
- spaceId: space.id,
- });
-
- identifyGroup({
- groupType: "space",
- groupKey: space.id,
- properties: {
- name: space.name,
- member_count: 1,
- seat_count: 1,
- tier: "hobby",
- },
- });
- }
-
+ // No space is created here — /setup owns space creation, and the
+ // active-space gate keeps redirecting there until it happens.
track(
{ id: user.id, isGuest: false },
{
diff --git a/apps/web/src/lib/posthog.ts b/apps/web/src/lib/posthog.ts
index cd14ebb5b..b8f4f238d 100644
--- a/apps/web/src/lib/posthog.ts
+++ b/apps/web/src/lib/posthog.ts
@@ -86,18 +86,20 @@ export function getClientAnonymousDistinctId(req: NextRequest) {
const GROUP_IDENTIFY_DISTINCT_ID = "server_group_identify";
/**
- * Update properties on a group (e.g. poll, space). Group identify events are
- * not attributed to the acting user — actor attribution belongs on the
- * accompanying track() event.
+ * Update properties on a group (e.g. poll, space). Pass distinctId to
+ * attribute the group identify to the acting user; without it the event
+ * captures under a shared server id (see above — never a real person, so
+ * actor attribution then belongs on the accompanying track() event).
*/
export function identifyGroup(group: {
groupType: string;
groupKey: string;
properties?: Record<string, unknown>;
+ distinctId?: string;
}) {
posthog()?.groupIdentify({
...group,
- distinctId: GROUP_IDENTIFY_DISTINCT_ID,
+ distinctId: group.distinctId ?? GROUP_IDENTIFY_DISTINCT_ID,
});
}