Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
π Fix upcoming events predicate for viewers west of UTC (#2518)
Luke Vella0f44bbb7c66b
diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/dashboard-home.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/dashboard-home.tsxindex 901618278..3bcc96e50 100644--- a/apps/web/src/app/[locale]/(space)/(dashboard)/dashboard-home.tsx+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/dashboard-home.tsx@@ -19,10 +19,13 @@ import { HoverPrefetchLink } from "@/components/hover-prefetch-link";import { Trans } from "@/i18n/client";import { IfFeatureEnabled, useFeatureFlag } from "@/lib/feature-flags/client";import { trpc } from "@/trpc/client";+import { getBrowserTimeZone } from "@/utils/date-time-utils";import { PasswordSetupAlert } from "./password-setup-alert";export function DashboardHome() {- const [stats] = trpc.dashboard.stats.useSuspenseQuery();+ const [stats] = trpc.dashboard.stats.useSuspenseQuery({+ timeZone: getBrowserTimeZone(),+ });const isEmailLoginEnabled = useFeatureFlag("emailLogin");return (diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/events/events-infinite-list.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/events/events-infinite-list.tsxindex bd772cde5..61c3812ff 100644--- a/apps/web/src/app/[locale]/(space)/(dashboard)/events/events-infinite-list.tsx+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/events/events-infinite-list.tsx@@ -9,6 +9,7 @@ import { ScheduledEventListItem } from "@/features/scheduled-event/components/scimport type { Status } from "@/features/scheduled-event/schema";import { Trans } from "@/i18n/client";import { trpc } from "@/trpc/client";+import { getBrowserTimeZone } from "@/utils/date-time-utils";interface EventsInfiniteListProps {status?: Status;@@ -35,6 +36,7 @@ export function EventsInfiniteList({status,search,member,+ timeZone: getBrowserTimeZone(),},{getNextPageParam: (lastPage) => lastPage.nextCursor,diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/events/page.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/events/page.tsxindex 542a4e75a..3c89c26ea 100644--- a/apps/web/src/app/[locale]/(space)/(dashboard)/events/page.tsx+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/events/page.tsx@@ -2,6 +2,7 @@ import { dehydrate, HydrationBoundary } from "@tanstack/react-query";import type { Metadata } from "next";import { getTranslation } from "@/i18n/server";import { createPrivateSSRHelper } from "@/trpc/server/create-ssr-helper";+import { getBrowserTimeZone } from "@/utils/date-time-utils";import { EventsPage } from "./events-page";import { eventsSearchParamsSchema } from "./schema";@@ -19,6 +20,9 @@ export default async function Page(props: {status,search: q,member,+ // Server zone, matching what the SSR pass of EventsInfiniteList+ // computes; the client refetches with the browser zone if it differs.+ timeZone: getBrowserTimeZone(),}),]);diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/page.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/page.tsxindex 52bacea14..8e549032f 100644--- a/apps/web/src/app/[locale]/(space)/(dashboard)/page.tsx+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/page.tsx@@ -2,12 +2,17 @@ import { dehydrate, HydrationBoundary } from "@tanstack/react-query";import type { Metadata } from "next";import { getTranslation } from "@/i18n/server";import { createPrivateSSRHelper } from "@/trpc/server/create-ssr-helper";+import { getBrowserTimeZone } from "@/utils/date-time-utils";import { DashboardHome } from "./dashboard-home";export default async function Page() {const helpers = await createPrivateSSRHelper();- await helpers.dashboard.stats.prefetch();+ // 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() });return (<HydrationBoundary state={dehydrate(helpers.queryClient)}>diff --git a/apps/web/src/features/scheduled-event/data.ts b/apps/web/src/features/scheduled-event/data.tsindex 115f9ea6c..35628cbf7 100644--- a/apps/web/src/features/scheduled-event/data.ts+++ b/apps/web/src/features/scheduled-event/data.ts@@ -4,7 +4,10 @@ import { parseConferencing } from "@/features/conferencing/data";import type { Conferencing } from "@/features/conferencing/schema";import { parseLocation } from "@/features/location/data";import type { Location } from "@/features/location/schema";-import { dayjs } from "@/lib/dayjs";+import {+ pastScheduledEventWhere,+ upcomingScheduledEventWhere,+} from "./predicates";import type { Status } from "./schema";export function getPublicScheduledEvent(id: string) {@@ -278,23 +281,18 @@ export const getUpcomingEvents = async ({page = 1,pageSize = 20,spaceId,+ timeZone,}: {search?: string;member?: string;page?: number;pageSize?: number;spaceId: string;+ timeZone: string;}) => {- const now = new Date();- const todayStart = dayjs().startOf("day").utc().toDate();-const where: Prisma.ScheduledEventWhereInput = {...buildBaseWhere(spaceId, search, member),- status: "confirmed",- OR: [- { allDay: false, start: { gte: now } },- { allDay: true, start: { gte: todayStart } },- ],+ ...upcomingScheduledEventWhere({ now: new Date(), timeZone }),};const [totalCount, allEvents] = await prisma.$transaction([@@ -329,23 +327,18 @@ export const getPastEvents = async ({page = 1,pageSize = 20,spaceId,+ timeZone,}: {search?: string;member?: string;page?: number;pageSize?: number;spaceId: string;+ timeZone: string;}) => {- const now = new Date();- const todayStart = dayjs().startOf("day").utc().toDate();-const where: Prisma.ScheduledEventWhereInput = {...buildBaseWhere(spaceId, search, member),- status: "confirmed",- OR: [- { allDay: false, start: { lt: now } },- { allDay: true, start: { lt: todayStart } },- ],+ ...pastScheduledEventWhere({ now: new Date(), timeZone }),};const [totalCount, allEvents] = await prisma.$transaction([@@ -469,6 +462,7 @@ export const getEventsChronological = async ({page = 1,pageSize = 20,spaceId,+ timeZone,}: {status?: Status;search?: string;@@ -476,20 +470,21 @@ export const getEventsChronological = async ({page?: number;pageSize?: number;spaceId: string;+ timeZone: string;}) => {const commonParams = { search, member, page, pageSize, spaceId };switch (status) {case "upcoming":- return getUpcomingEvents(commonParams);+ return getUpcomingEvents({ ...commonParams, timeZone });case "past":- return getPastEvents(commonParams);+ return getPastEvents({ ...commonParams, timeZone });case "unconfirmed":return getUnconfirmedEvents(commonParams);case "canceled":return getCanceledEvents(commonParams);default:// If no status specified, default to upcoming- return getUpcomingEvents(commonParams);+ return getUpcomingEvents({ ...commonParams, timeZone });}};diff --git a/apps/web/src/features/scheduled-event/predicates.test.ts b/apps/web/src/features/scheduled-event/predicates.test.tsnew file mode 100644index 000000000..857f76911--- /dev/null+++ b/apps/web/src/features/scheduled-event/predicates.test.ts@@ -0,0 +1,146 @@+import { describe, expect, it } from "vitest";+import {+ pastScheduledEventWhere,+ upcomingScheduledEventWhere,+} from "./predicates";++type TestEvent = {+ status: string;+ deletedAt: Date | null;+ allDay: boolean;+ start: Date;+ end: Date;+};++type Where =+ | ReturnType<typeof upcomingScheduledEventWhere>+ | ReturnType<typeof pastScheduledEventWhere>;++// Interprets the Prisma where clause against an in-memory event so the tests+// exercise the exact predicate the queries send to the database.+function matchesWhere(where: Where, event: TestEvent) {+ if (event.status !== where.status || event.deletedAt !== where.deletedAt) {+ return false;+ }+ return where.OR.some((arm) => {+ if (arm.allDay !== event.allDay) {+ return false;+ }+ if ("gt" in arm.end && arm.end.gt !== undefined) {+ return event.end.getTime() > arm.end.gt.getTime();+ }+ if ("lte" in arm.end && arm.end.lte !== undefined) {+ return event.end.getTime() <= arm.end.lte.getTime();+ }+ throw new Error("Unexpected end filter shape");+ });+}++function allDayEvent({ start, end }: { start: string; end: string }) {+ return {+ status: "confirmed",+ deletedAt: null,+ allDay: true,+ start: new Date(`${start}T00:00:00Z`),+ end: new Date(`${end}T00:00:00Z`),+ } satisfies TestEvent;+}++function timedEvent({ start, end }: { start: string; end: string }) {+ return {+ status: "confirmed",+ deletedAt: null,+ allDay: false,+ start: new Date(start),+ end: new Date(end),+ } satisfies TestEvent;+}++// 3pm July 1 in Honolulu (UTC-10)+const honolulu = {+ now: new Date("2025-07-02T01:00:00Z"),+ timeZone: "Pacific/Honolulu",+};++describe("upcomingScheduledEventWhere", () => {+ it("keeps today's all-day event upcoming for a viewer west of UTC", () => {+ // Stored as UTC midnight; end is exclusive (start + 1 day)+ const event = allDayEvent({ start: "2025-07-01", end: "2025-07-02" });++ expect(matchesWhere(upcomingScheduledEventWhere(honolulu), event)).toBe(+ true,+ );+ expect(matchesWhere(pastScheduledEventWhere(honolulu), event)).toBe(false);+ });++ it("moves the same all-day event to past for a viewer already on the next day", () => {+ const event = allDayEvent({ start: "2025-07-01", end: "2025-07-02" });+ const utcViewer = { now: honolulu.now, timeZone: "UTC" };++ expect(matchesWhere(upcomingScheduledEventWhere(utcViewer), event)).toBe(+ false,+ );+ expect(matchesWhere(pastScheduledEventWhere(utcViewer), event)).toBe(true);+ });++ it("keeps a multi-day all-day span upcoming through its final day", () => {+ const event = allDayEvent({ start: "2025-06-29", end: "2025-07-02" });++ expect(matchesWhere(upcomingScheduledEventWhere(honolulu), event)).toBe(+ true,+ );+ });++ it("counts an in-progress timed event as upcoming", () => {+ const event = timedEvent({+ start: "2025-07-02T00:30:00Z",+ end: "2025-07-02T01:30:00Z",+ });++ expect(matchesWhere(upcomingScheduledEventWhere(honolulu), event)).toBe(+ true,+ );+ });+});++describe("pastScheduledEventWhere", () => {+ it("is the exact negation of upcoming for the same inputs", () => {+ const events = [+ allDayEvent({ start: "2025-06-30", end: "2025-07-01" }),+ allDayEvent({ start: "2025-07-01", end: "2025-07-02" }),+ allDayEvent({ start: "2025-07-02", end: "2025-07-03" }),+ allDayEvent({ start: "2025-06-29", end: "2025-07-02" }),+ // Boundary: all-day event ending exactly at today's UTC midnight+ allDayEvent({ start: "2025-06-28", end: "2025-07-01" }),+ timedEvent({+ start: "2025-07-01T22:00:00Z",+ end: "2025-07-02T00:00:00Z",+ }),+ timedEvent({+ start: "2025-07-02T00:30:00Z",+ end: "2025-07-02T01:30:00Z",+ }),+ timedEvent({+ start: "2025-07-02T02:00:00Z",+ end: "2025-07-02T03:00:00Z",+ }),+ // Boundary: timed event ending exactly at now+ timedEvent({+ start: "2025-07-02T00:00:00Z",+ end: "2025-07-02T01:00:00Z",+ }),+ ];++ for (const viewer of [+ honolulu,+ { now: honolulu.now, timeZone: "UTC" },+ { now: honolulu.now, timeZone: "Asia/Tokyo" },+ ]) {+ const upcoming = upcomingScheduledEventWhere(viewer);+ const past = pastScheduledEventWhere(viewer);+ for (const event of events) {+ expect(matchesWhere(upcoming, event)).toBe(!matchesWhere(past, event));+ }+ }+ });+});diff --git a/apps/web/src/features/scheduled-event/predicates.ts b/apps/web/src/features/scheduled-event/predicates.tsnew file mode 100644index 000000000..d49236a06--- /dev/null+++ b/apps/web/src/features/scheduled-event/predicates.ts@@ -0,0 +1,49 @@+import type { Prisma } from "@rallly/database";+import {+ calendarDateToUTCMidnight,+ getCalendarDate,+} from "@/lib/datetime/utils";++// For allDay rows, `start`/`end` are calendar dates encoded as UTC midnight,+// not instants, so they must be compared against "today in the viewer's zone"+// encoded the same way. `end` is stored exclusive (start + 1 day), so+// `end > todayUtcMidnight` keeps an event through its final day and handles+// multi-day spans. The timed arm uses `end > now` so in-progress meetings+// still count as upcoming. A single core with the gt/lte complements side by+// side makes past the exact negation of upcoming structurally, so the two+// cannot drift apart.+function scheduledEventWhere({+ now,+ timeZone,+ past,+}: {+ now: Date;+ timeZone: string;+ past: boolean;+}) {+ const todayUtcMidnight = calendarDateToUTCMidnight(+ getCalendarDate(now, timeZone),+ );+ return {+ status: "confirmed",+ deletedAt: null,+ OR: [+ { allDay: false, end: past ? { lte: now } : { gt: now } },+ {+ allDay: true,+ end: past ? { lte: todayUtcMidnight } : { gt: todayUtcMidnight },+ },+ ],+ } satisfies Prisma.ScheduledEventWhereInput;+}++export function upcomingScheduledEventWhere(args: {+ now: Date;+ timeZone: string;+}) {+ return scheduledEventWhere({ ...args, past: false });+}++export function pastScheduledEventWhere(args: { now: Date; timeZone: string }) {+ return scheduledEventWhere({ ...args, past: true });+}diff --git a/apps/web/src/lib/datetime/schema.ts b/apps/web/src/lib/datetime/schema.tsindex b414316bf..ec4efcacc 100644--- a/apps/web/src/lib/datetime/schema.ts+++ b/apps/web/src/lib/datetime/schema.ts@@ -1,5 +1,12 @@import * as z from "zod";+import { normalizeTimeZone } from "./utils";export const timeFormatSchema = z.enum(["hours12", "hours24"]);+export const timeZoneSchema = z+ .string()+ .refine((value) => normalizeTimeZone(value) !== undefined, {+ message: "Invalid IANA time zone",+ });+export const weekStartSchema = z.coerce.number().int().min(0).max(6);diff --git a/apps/web/src/lib/datetime/utils.test.ts b/apps/web/src/lib/datetime/utils.test.tsindex 3848ae596..037d0fecd 100644--- a/apps/web/src/lib/datetime/utils.test.ts+++ b/apps/web/src/lib/datetime/utils.test.ts@@ -1,5 +1,9 @@import { describe, expect, it } from "vitest";-import { normalizeTimeZone } from "./utils";+import {+ calendarDateToUTCMidnight,+ getCalendarDate,+ normalizeTimeZone,+} from "./utils";describe("normalizeTimeZone", () => {it("returns a valid IANA zone unchanged", () => {@@ -18,3 +22,31 @@ describe("normalizeTimeZone", () => {expect(normalizeTimeZone("garbage")).toBeUndefined();});});++describe("getCalendarDate", () => {+ // 2025-07-02T01:00:00Z = 3pm July 1 in Honolulu (UTC-10)+ const instant = new Date("2025-07-02T01:00:00Z");++ it("returns the previous calendar date west of UTC", () => {+ expect(getCalendarDate(instant, "Pacific/Honolulu")).toBe("2025-07-01");+ });++ it("returns the UTC calendar date in UTC", () => {+ expect(getCalendarDate(instant, "UTC")).toBe("2025-07-02");+ });++ it("returns the next calendar date east of UTC", () => {+ // 2025-07-01T20:00:00Z = 5am July 2 in Tokyo (UTC+9)+ expect(+ getCalendarDate(new Date("2025-07-01T20:00:00Z"), "Asia/Tokyo"),+ ).toBe("2025-07-02");+ });+});++describe("calendarDateToUTCMidnight", () => {+ it("encodes a calendar date as UTC midnight", () => {+ expect(calendarDateToUTCMidnight("2025-07-01").toISOString()).toBe(+ "2025-07-01T00:00:00.000Z",+ );+ });+});diff --git a/apps/web/src/lib/datetime/utils.ts b/apps/web/src/lib/datetime/utils.tsindex b8cbb752a..4b0ccbe91 100644--- a/apps/web/src/lib/datetime/utils.ts+++ b/apps/web/src/lib/datetime/utils.ts@@ -13,6 +13,27 @@ export function toISODate(value: DateInput) {return toDate(value).toISOString().slice(0, 10);}+/**+ * The calendar date (YYYY-MM-DD) at the given instant in the given zone.+ * en-CA is the locale whose date format is ISO 8601.+ */+export function getCalendarDate(now: Date, timeZone: string): string {+ return new Intl.DateTimeFormat("en-CA", {+ timeZone,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ }).format(now);+}++/**+ * Encodes a calendar date the same way allDay event dates are stored in the+ * database: as UTC midnight of that date.+ */+export function calendarDateToUTCMidnight(date: string): Date {+ return new Date(`${date}T00:00:00Z`);+}+/*** Returns the given zone if it's a valid IANA identifier, otherwise* undefined. Guards against empty strings and corrupt stored values, whichdiff --git a/apps/web/src/trpc/routers/dashboard.ts b/apps/web/src/trpc/routers/dashboard.tsindex 8ac570dac..90c3e6666 100644--- a/apps/web/src/trpc/routers/dashboard.ts+++ b/apps/web/src/trpc/routers/dashboard.ts@@ -1,62 +1,59 @@import type { Prisma } from "@rallly/database";import { prisma } from "@rallly/database";+import * as z from "zod";+import { upcomingScheduledEventWhere } from "@/features/scheduled-event/predicates";import type { MemberAbilityContext } from "@/features/space/member/ability";import { defineAbilityForMember } from "@/features/space/member/ability";import { getTotalSeatsForSpace } from "@/features/space/utils";-import { dayjs } from "@/lib/dayjs";+import { timeZoneSchema } from "@/lib/datetime/schema";+import { normalizeTimeZone } from "@/lib/datetime/utils";import { router, spaceProcedure } from "../trpc";export const dashboard = router({- stats: spaceProcedure.query(async ({ ctx }) => {- const { space } = ctx;- const now = new Date();- const todayStart = dayjs()- .tz(ctx.user.timeZone ?? "UTC")- .startOf("day")- .toDate();+ 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,- deletedAt: null,- status: "confirmed",- OR: [- { allDay: false, start: { gte: now } },- { allDay: true, start: { gte: todayStart } },- ],- };+ 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 [+ 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);+ const ability = defineAbilityForMember({+ user: { id: ctx.user.id },+ space,+ } satisfies MemberAbilityContext);- return {- openPollCount,- upcomingEventCount,- memberCount,- seatCount,- hasNoAccounts: accountCount === 0,- canManageBilling: ability.can("manage", "Billing"),- };- }),+ return {+ openPollCount,+ upcomingEventCount,+ memberCount,+ seatCount,+ hasNoAccounts: accountCount === 0,+ canManageBilling: ability.can("manage", "Billing"),+ };+ }),});diff --git a/apps/web/src/trpc/routers/events.ts b/apps/web/src/trpc/routers/events.tsindex 1588166cd..21b89abc5 100644--- a/apps/web/src/trpc/routers/events.ts+++ b/apps/web/src/trpc/routers/events.ts@@ -12,6 +12,8 @@ import { formatLocationText } from "@/features/location/utils";import { getEventsChronological } from "@/features/scheduled-event/data";import { formatEventDateTime } from "@/features/scheduled-event/utils";import { defineAbilityForMember } from "@/features/space/member/ability";+import { timeZoneSchema } from "@/lib/datetime/schema";+import { normalizeTimeZone } from "@/lib/datetime/utils";import { createIcsEvent } from "@/utils/ics";import { router, spaceProcedure } from "../trpc";@@ -24,12 +26,15 @@ export const events = router({.optional(),search: z.string().optional(),member: z.string().optional(),+ timeZone: timeZoneSchema.optional(),cursor: z.number().optional().default(1),limit: z.number().max(100).optional().default(20),}),).query(async ({ ctx, input }) => {const { cursor: page, limit: pageSize, status, search, member } = input;+ const timeZone =+ input.timeZone ?? normalizeTimeZone(ctx.user.timeZone) ?? "UTC";const result = await getEventsChronological({status,@@ -38,6 +43,7 @@ export const events = router({page,pageSize,spaceId: ctx.space.id,+ timeZone,});let nextCursor: number | undefined;diff --git a/packages/database/prisma/migrations/20260703161929_add_scheduled_event_space_status_start_index/migration.sql b/packages/database/prisma/migrations/20260703161929_add_scheduled_event_space_status_start_index/migration.sqlnew file mode 100644index 000000000..f51d413f9--- /dev/null+++ b/packages/database/prisma/migrations/20260703161929_add_scheduled_event_space_status_start_index/migration.sql@@ -0,0 +1,2 @@+-- CreateIndex+CREATE INDEX "scheduled_events_space_id_status_start_idx" ON "scheduled_events"("space_id", "status", "start");diff --git a/packages/database/prisma/models/event.prisma b/packages/database/prisma/models/event.prismaindex e8a57809c..e10c611f7 100644--- a/packages/database/prisma/models/event.prisma+++ b/packages/database/prisma/models/event.prisma@@ -50,6 +50,7 @@ model ScheduledEvent {@@index([spaceId])@@index([userId])@@index([eventTypeId])+ @@index([spaceId, status, start])@@map("scheduled_events")}