Skip to content

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

♻️ Convert dashboard stats from tRPC to a server component read (#2864)

Luke Vella70d36f416b15
diff --git a/CLAUDE.md b/CLAUDE.md
index d1a9d47f9..e3498ab8a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -239,8 +239,13 @@ These rules prepare the app for Next.js `cacheComponents` (static shell + stream
import { Trans } from "@/i18n/client";
<Trans i18nKey="menu" defaults="Menu" />
```
-- On the server, use `getTranslations` from `@/i18n/server`:
- ```ts
- const { t } = await getTranslations();
+- On the server, use `getTranslation` from `@/i18n/server`:
+ ```tsx
+ import { Trans } from "react-i18next/TransWithoutContext";
+ import { getTranslation } from "@/i18n/server";
+
+ const { t, i18n } = await getTranslation();
t("menu", { defaultValue: "Menu" });
- ```
\ No newline at end of file
+ <Trans t={t} i18n={i18n} ns="app" i18nKey="menu" defaults="Menu" />;
+ ```
+ Server JSX must use `Trans` from `react-i18next/TransWithoutContext` (the context-ful `Trans` from `@/i18n/client` needs React context and cannot render in a server component) and must pass both `t` and `i18n` — omitting `i18n` falls back to the module-global instance, which can carry another request's language under concurrency.
\ No newline at end of file
diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/dashboard-home.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/dashboard-home.tsx
index 74db189fb..157c22c2d 100644
--- a/apps/web/src/app/[locale]/(space)/(dashboard)/dashboard-home.tsx
+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/dashboard-home.tsx
@@ -1,6 +1,5 @@
-"use client";
-
import { Tile, TileDescription, TileGrid, TileTitle } from "@rallly/ui/tile";
+import { Trans } from "react-i18next/TransWithoutContext";
import { HoverPrefetchLink } from "@/components/hover-prefetch-link";
import {
BillingPageIcon,
@@ -16,57 +15,93 @@ import {
PageHeader,
PageTitle,
} from "@/components/page-layout";
-import { Trans } from "@/i18n/client";
-import { IfFeatureEnabled, useFeatureFlag } from "@/lib/feature-flags/client";
-import { getBrowserTimeZone } from "@/lib/utils/date-time-utils";
-import { trpc } from "@/trpc/client";
+import { getTranslation } from "@/i18n/server";
+import { isFeatureEnabled } from "@/lib/feature-flags/server";
import { PasswordSetupAlert } from "./password-setup-alert";
-export function DashboardHome() {
- const [stats] = trpc.dashboard.stats.useSuspenseQuery({
- timeZone: getBrowserTimeZone(),
- });
- const isEmailLoginEnabled = useFeatureFlag("emailLogin");
+export async function DashboardHome({
+ openPollCount,
+ upcomingEventCount,
+ memberCount,
+ seatCount,
+ hasNoAccounts,
+ canManageBilling,
+}: {
+ openPollCount: number;
+ upcomingEventCount: number;
+ memberCount: number;
+ seatCount: number;
+ hasNoAccounts: boolean;
+ canManageBilling: boolean;
+}) {
+ const { t, i18n } = await getTranslation();
return (
<PageContainer>
<PageHeader>
<PageTitle>
- <Trans i18nKey="home" defaults="Home" />
+ <Trans t={t} i18n={i18n} ns="app" i18nKey="home" defaults="Home" />
</PageTitle>
</PageHeader>
<PageContent className="space-y-8">
- {stats.hasNoAccounts && isEmailLoginEnabled ? (
+ {hasNoAccounts && isFeatureEnabled("emailLogin") ? (
<PasswordSetupAlert />
) : null}
<div className="space-y-4">
<h2 className="text-muted-foreground text-sm">
- <Trans i18nKey="homeActionsTitle" defaults="Actions" />
+ <Trans
+ t={t}
+ i18n={i18n}
+ ns="app"
+ i18nKey="homeActionsTitle"
+ defaults="Actions"
+ />
</h2>
<TileGrid>
<Tile render={<HoverPrefetchLink href="/new" />}>
<CreatePageIcon />
<TileTitle>
- <Trans i18nKey="create" defaults="Create" />
+ <Trans
+ t={t}
+ i18n={i18n}
+ ns="app"
+ i18nKey="create"
+ defaults="Create"
+ />
</TileTitle>
</Tile>
</TileGrid>
</div>
<div className="space-y-4">
<h2 className="text-muted-foreground text-sm">
- <Trans i18nKey="content" defaults="Content" />
+ <Trans
+ t={t}
+ i18n={i18n}
+ ns="app"
+ i18nKey="content"
+ defaults="Content"
+ />
</h2>
<TileGrid>
<Tile render={<HoverPrefetchLink href="/polls" />}>
<PollPageIcon />
<TileTitle>
- <Trans i18nKey="polls" defaults="Polls" />
+ <Trans
+ t={t}
+ i18n={i18n}
+ ns="app"
+ i18nKey="polls"
+ defaults="Polls"
+ />
</TileTitle>
<TileDescription>
<Trans
+ t={t}
+ i18n={i18n}
+ ns="app"
i18nKey="openPollCount"
defaults="{count} open"
- values={{ count: stats.openPollCount }}
+ values={{ count: openPollCount }}
/>
</TileDescription>
</Tile>
@@ -74,13 +109,22 @@ export function DashboardHome() {
<Tile render={<HoverPrefetchLink href="/events" />}>
<EventPageIcon />
<TileTitle>
- <Trans i18nKey="events" defaults="Events" />
+ <Trans
+ t={t}
+ i18n={i18n}
+ ns="app"
+ i18nKey="events"
+ defaults="Events"
+ />
</TileTitle>
<TileDescription>
<Trans
+ t={t}
+ i18n={i18n}
+ ns="app"
i18nKey="upcomingEventCount"
defaults="{count} upcoming"
- values={{ count: stats.upcomingEventCount }}
+ values={{ count: upcomingEventCount }}
/>
</TileDescription>
</Tile>
@@ -88,47 +132,75 @@ export function DashboardHome() {
</div>
<div className="space-y-4">
<h2 className="text-muted-foreground text-sm">
- <Trans i18nKey="manage" defaults="Manage" />
+ <Trans
+ t={t}
+ i18n={i18n}
+ ns="app"
+ i18nKey="manage"
+ defaults="Manage"
+ />
</h2>
<TileGrid>
<Tile render={<HoverPrefetchLink href="/settings/general" />}>
<SettingsPageIcon />
<TileTitle>
- <Trans i18nKey="settings" defaults="Settings" />
+ <Trans
+ t={t}
+ i18n={i18n}
+ ns="app"
+ i18nKey="settings"
+ defaults="Settings"
+ />
</TileTitle>
</Tile>
<Tile render={<HoverPrefetchLink href="/settings/members" />}>
<MembersPageIcon />
<TileTitle>
- <Trans i18nKey="members" defaults="Members" />
+ <Trans
+ t={t}
+ i18n={i18n}
+ ns="app"
+ i18nKey="members"
+ defaults="Members"
+ />
</TileTitle>
<TileDescription>
<Trans
+ t={t}
+ i18n={i18n}
+ ns="app"
i18nKey="memberCount"
defaults="{count, plural, =0 {No members} one {1 member} other {# members}}"
- values={{ count: stats.memberCount }}
+ values={{ count: memberCount }}
/>
</TileDescription>
</Tile>
- <IfFeatureEnabled feature="billing">
- {stats.canManageBilling && (
- <Tile render={<HoverPrefetchLink href="/settings/billing" />}>
- <BillingPageIcon />
- <TileTitle>
- <Trans i18nKey="billing" defaults="Billing" />
- </TileTitle>
- <TileDescription>
- <Trans
- i18nKey="seatCount"
- defaults="{count, plural, =0 {No seats} one {1 seat} other {# seats}}"
- values={{ count: stats.seatCount }}
- />
- </TileDescription>
- </Tile>
- )}
- </IfFeatureEnabled>
+ {isFeatureEnabled("billing") && canManageBilling ? (
+ <Tile render={<HoverPrefetchLink href="/settings/billing" />}>
+ <BillingPageIcon />
+ <TileTitle>
+ <Trans
+ t={t}
+ i18n={i18n}
+ ns="app"
+ i18nKey="billing"
+ defaults="Billing"
+ />
+ </TileTitle>
+ <TileDescription>
+ <Trans
+ t={t}
+ i18n={i18n}
+ ns="app"
+ i18nKey="seatCount"
+ defaults="{count, plural, =0 {No seats} one {1 seat} other {# seats}}"
+ values={{ count: seatCount }}
+ />
+ </TileDescription>
+ </Tile>
+ ) : null}
</TileGrid>
</div>
</PageContent>
diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/page.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/page.tsx
index df8251bec..67d7f0fb1 100644
--- a/apps/web/src/app/[locale]/(space)/(dashboard)/page.tsx
+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/page.tsx
@@ -1,23 +1,35 @@
-import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
import type { Metadata } from "next";
+import { loadPollStatusCounts } from "@/features/poll/loaders";
+import {
+ getActiveSpace,
+ loadUpcomingEventCount,
+} from "@/features/space/loaders";
+import { defineAbilityForMember } from "@/features/space/member/ability";
+import { loadUserHasNoAccounts, requireUser } from "@/features/user/loaders";
import { getTranslation } from "@/i18n/server";
-import { getBrowserTimeZone } from "@/lib/utils/date-time-utils";
-import { createPrivateSSRHelper } from "@/trpc/server/create-ssr-helper";
import { DashboardHome } from "./dashboard-home";
export default async function Page() {
- const helpers = await createPrivateSSRHelper();
+ const [user, space, pollStatusCounts, upcomingEventCount, hasNoAccounts] =
+ await Promise.all([
+ requireUser(),
+ getActiveSpace(),
+ loadPollStatusCounts(),
+ loadUpcomingEventCount(),
+ loadUserHasNoAccounts(),
+ ]);
- // On the server this resolves to the server's zone — the same value the SSR
- // pass of DashboardHome computes — so the suspense query hits the prefetched
- // cache instead of fetching during SSR. The client refetches with the real
- // browser zone after hydration when it differs.
- await helpers.dashboard.stats.prefetch({ timeZone: getBrowserTimeZone() });
+ const ability = defineAbilityForMember({ user: { id: user.id }, space });
return (
- <HydrationBoundary state={dehydrate(helpers.queryClient)}>
- <DashboardHome />
- </HydrationBoundary>
+ <DashboardHome
+ openPollCount={pollStatusCounts.open}
+ upcomingEventCount={upcomingEventCount}
+ memberCount={space.memberCount}
+ seatCount={space.seatCount}
+ hasNoAccounts={hasNoAccounts}
+ canManageBilling={ability.can("manage", "Billing")}
+ />
);
}
diff --git a/apps/web/src/features/poll/loaders.ts b/apps/web/src/features/poll/loaders.ts
new file mode 100644
index 000000000..0d7aea2ae
--- /dev/null
+++ b/apps/web/src/features/poll/loaders.ts
@@ -0,0 +1,10 @@
+import "server-only";
+
+import { cache } from "react";
+import { getPollStatusCounts } from "@/features/poll/data";
+import { getActiveSpace } from "@/features/space/loaders";
+
+export const loadPollStatusCounts = cache(async () => {
+ const space = await getActiveSpace();
+ return getPollStatusCounts({ spaceId: space.id });
+});
diff --git a/apps/web/src/features/scheduled-event/data.ts b/apps/web/src/features/scheduled-event/data.ts
index 9aac646ce..8ce865400 100644
--- a/apps/web/src/features/scheduled-event/data.ts
+++ b/apps/web/src/features/scheduled-event/data.ts
@@ -269,6 +269,21 @@ function buildBaseWhere(
}
// Get upcoming events (confirmed events in the future)
+export async function getUpcomingEventCount({
+ spaceId,
+ timeZone,
+}: {
+ spaceId: string;
+ timeZone: string;
+}) {
+ return prisma.scheduledEvent.count({
+ where: {
+ spaceId,
+ ...upcomingScheduledEventWhere({ now: new Date(), timeZone }),
+ },
+ });
+}
+
export const getUpcomingEvents = async ({
search,
member,
diff --git a/apps/web/src/features/space/loaders.ts b/apps/web/src/features/space/loaders.ts
index 5a072624d..df4db0144 100644
--- a/apps/web/src/features/space/loaders.ts
+++ b/apps/web/src/features/space/loaders.ts
@@ -3,13 +3,17 @@ import "server-only";
import { notFound, redirect } from "next/navigation";
import { cache } from "react";
+import { getUpcomingEventCount } from "@/features/scheduled-event/data";
import {
getActiveSpaceForUser,
getOwnedSpace,
getSpaceSeatCount,
getTotalSeatsForSpace,
} from "@/features/space/data";
+import { requireUser } from "@/features/user/loaders";
import { getSessionState } from "@/lib/auth";
+import { getDeviceTimeZone } from "@/lib/datetime/server";
+import { normalizeTimeZone } from "@/lib/datetime/utils";
import { InvalidSessionError } from "@/lib/errors/invalid-session-error";
import { getPathname } from "@/lib/pathname";
import { buildSafeRedirectUrl } from "@/lib/utils/redirect";
@@ -91,6 +95,27 @@ export const getActiveSpace = cache(async () => {
return space;
});
+/**
+ * Upcoming event count for the signed-in user's active space. Lives here
+ * rather than in scheduled-event/loaders.ts because account-deletion (user)
+ * imports scheduled-event, so a scheduled-event → space/user loader would
+ * close a feature import cycle; space → scheduled-event is a forward edge.
+ */
+export const loadUpcomingEventCount = cache(async () => {
+ const [user, space, deviceTimeZone] = await Promise.all([
+ requireUser(),
+ getActiveSpace(),
+ getDeviceTimeZone(),
+ ]);
+
+ // Upcoming is measured against the viewer's present, so the device zone
+ // wins; the stored preference is a fallback for devices whose zone cookie
+ // hasn't been set yet.
+ const timeZone = deviceTimeZone ?? normalizeTimeZone(user.timeZone) ?? "UTC";
+
+ return getUpcomingEventCount({ spaceId: space.id, timeZone });
+});
+
/**
* Seat usage for the signed-in user's active space. Session scoped —
* server component/page use only, per getActiveSpace.
diff --git a/apps/web/src/features/user/loaders.ts b/apps/web/src/features/user/loaders.ts
index d568c06be..1f8b00818 100644
--- a/apps/web/src/features/user/loaders.ts
+++ b/apps/web/src/features/user/loaders.ts
@@ -3,7 +3,7 @@ import "server-only";
import { notFound, redirect } from "next/navigation";
import { cache } from "react";
import { isInitialAdmin } from "@/features/instance-settings/utils";
-import { getUser } from "@/features/user/data";
+import { getUser, getUserHasNoAccounts } from "@/features/user/data";
import type { UserDTO } from "@/features/user/schema";
import { getSession, getSessionState } from "@/lib/auth";
import { InvalidSessionError } from "@/lib/errors/invalid-session-error";
@@ -91,3 +91,12 @@ export const requireAdmin = cache(async () => {
return user;
});
+
+/**
+ * Whether the signed-in user has no auth accounts (no password, no OAuth
+ * link) — OTP-only accounts that should be nudged to set up a password.
+ */
+export const loadUserHasNoAccounts = cache(async () => {
+ const user = await requireUser();
+ return getUserHasNoAccounts(user.id);
+});
diff --git a/apps/web/src/lib/datetime/server.ts b/apps/web/src/lib/datetime/server.ts
index d3ed17b5a..06a82d512 100644
--- a/apps/web/src/lib/datetime/server.ts
+++ b/apps/web/src/lib/datetime/server.ts
@@ -16,6 +16,18 @@ import { normalizeTimeFormat, normalizeTimeZone } from "@/lib/datetime/utils";
* preferences instead. No zone means the viewer's first ever request —
* components render times client-side once the zone is known.
*/
+/**
+ * The viewer's current zone as reported by the device cookie, ignoring the
+ * session zone override — the override is a poll-viewing aid ("see what
+ * other participants see"), not a statement about where the viewer is now.
+ * Use for classifying moments against the viewer's present (e.g. upcoming
+ * counts); use getDeviceDateTimeConfig for display on public pages.
+ */
+export async function getDeviceTimeZone() {
+ const cookieStore = await cookies();
+ return normalizeTimeZone(cookieStore.get(TIME_ZONE_COOKIE_NAME)?.value);
+}
+
export async function getDeviceDateTimeConfig() {
const cookieStore = await cookies();
diff --git a/apps/web/src/trpc/routers/dashboard.ts b/apps/web/src/trpc/routers/dashboard.ts
deleted file mode 100644
index d1e29a6ab..000000000
--- a/apps/web/src/trpc/routers/dashboard.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import type { Prisma } from "@rallly/database";
-import { prisma } from "@rallly/database";
-import * as z from "zod";
-import { upcomingScheduledEventWhere } from "@/features/scheduled-event/utils";
-import { getTotalSeatsForSpace } from "@/features/space/data";
-import type { MemberAbilityContext } from "@/features/space/member/ability";
-import { defineAbilityForMember } from "@/features/space/member/ability";
-import { timeZoneSchema } from "@/lib/datetime/schema";
-import { normalizeTimeZone } from "@/lib/datetime/utils";
-import { router, spaceProcedure } from "../trpc";
-
-export const dashboard = router({
- stats: spaceProcedure
- .input(z.object({ timeZone: timeZoneSchema.optional() }).optional())
- .query(async ({ ctx, input }) => {
- const { space } = ctx;
- const timeZone =
- input?.timeZone ?? normalizeTimeZone(ctx.user.timeZone) ?? "UTC";
-
- const upcomingEventsWhere: Prisma.ScheduledEventWhereInput = {
- spaceId: space.id,
- ...upcomingScheduledEventWhere({ now: new Date(), timeZone }),
- };
-
- const [
- openPollCount,
- upcomingEventCount,
- memberCount,
- seatCount,
- accountCount,
- ] = await Promise.all([
- prisma.poll.count({
- where: {
- spaceId: space.id,
- status: "open",
- deleted: false,
- },
- }),
- prisma.scheduledEvent.count({ where: upcomingEventsWhere }),
- prisma.spaceMember.count({ where: { spaceId: space.id } }),
- getTotalSeatsForSpace(space.id),
- prisma.account.count({ where: { userId: ctx.user.id } }),
- ]);
-
- const ability = defineAbilityForMember({
- user: { id: ctx.user.id },
- space,
- } satisfies MemberAbilityContext);
-
- return {
- openPollCount,
- upcomingEventCount,
- memberCount,
- seatCount,
- hasNoAccounts: accountCount === 0,
- canManageBilling: ability.can("manage", "Billing"),
- };
- }),
-});
diff --git a/apps/web/src/trpc/routers/index.ts b/apps/web/src/trpc/routers/index.ts
index c7e5ba8fe..16bd70e47 100644
--- a/apps/web/src/trpc/routers/index.ts
+++ b/apps/web/src/trpc/routers/index.ts
@@ -4,7 +4,6 @@ import { mergeRouters, router } from "../trpc";
import { auth } from "./auth";
import { billing } from "./billing";
import { calendars } from "./calendars";
-import { dashboard } from "./dashboard";
import { eventTypes } from "./event-types";
import { events } from "./events";
import { polls } from "./polls";
@@ -14,7 +13,6 @@ export const appRouter = mergeRouters(
router({
auth,
billing,
- dashboard,
eventTypes,
events,
polls,