Skip to content

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

✨ Add proper ICS event lifecycle management with UIDs and sequence (#1924)

Luke Vella47e3c5d0e8be
diff --git a/apps/web/src/features/scheduled-event/actions.ts b/apps/web/src/features/scheduled-event/actions.ts
index 47092d432..12ef5d4d8 100644
--- a/apps/web/src/features/scheduled-event/actions.ts
+++ b/apps/web/src/features/scheduled-event/actions.ts
@@ -5,6 +5,7 @@ import { z } from "zod";
import { AppError } from "@/lib/errors";
import { spaceActionClient } from "@/lib/safe-action/server";
import { getEmailClient } from "@/utils/emails";
+import { createIcsEvent } from "@/utils/ics";
import { formatEventDateTime } from "./utils";
export const cancelEventAction = spaceActionClient
@@ -37,15 +38,57 @@ export const cancelEventAction = spaceActionClient
});
}
- await prisma.scheduledEvent.update({
+ const updatedEvent = await prisma.scheduledEvent.update({
where: {
id: parsedInput.eventId,
},
data: {
status: "canceled",
+ sequence: {
+ increment: 1,
+ },
},
+ include: {
+ invites: true,
+ },
+ });
+
+ const cancelEvent = createIcsEvent({
+ uid: updatedEvent.uid,
+ sequence: updatedEvent.sequence,
+ title: updatedEvent.title,
+ description: updatedEvent.description ?? undefined,
+ location: updatedEvent.location ?? undefined,
+ start: updatedEvent.start,
+ end: updatedEvent.end,
+ allDay: updatedEvent.allDay,
+ timeZone: updatedEvent.timeZone ?? undefined,
+ organizer: {
+ name: ctx.user.name,
+ email: ctx.user.email,
+ },
+ attendees: updatedEvent.invites.map((invite) => ({
+ name: invite.inviteeName,
+ email: invite.inviteeEmail,
+ })),
+ method: "cancel",
+ status: "CANCELLED",
});
+ if (cancelEvent.error) {
+ throw new AppError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: `Failed to generate cancellation ICS: ${cancelEvent.error.message}`,
+ });
+ }
+
+ if (!cancelEvent.value) {
+ throw new AppError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Failed to generate cancellation ICS",
+ });
+ }
+
// notify attendees
const attendees = await prisma.scheduledEventInvite.findMany({
where: {
@@ -79,6 +122,11 @@ export const cancelEventAction = spaceActionClient
date,
time,
},
+ icalEvent: {
+ filename: "cancel.ics",
+ method: "cancel",
+ content: cancelEvent.value,
+ },
});
}
}
diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.ts
index 2cad27ee4..55fbbde0a 100644
--- a/apps/web/src/trpc/routers/polls.ts
+++ b/apps/web/src/trpc/routers/polls.ts
@@ -5,7 +5,6 @@ import { absoluteUrl, shortUrl } from "@rallly/utils/absolute-url";
import { nanoid } from "@rallly/utils/nanoid";
import { TRPCError } from "@trpc/server";
import dayjs from "dayjs";
-import * as ics from "ics";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { getCurrentUserSpace } from "@/auth/data";
@@ -14,6 +13,7 @@ import { getPolls } from "@/features/poll/data";
import { canUserManagePoll } from "@/features/poll/helpers";
import { formatEventDateTime } from "@/features/scheduled-event/utils";
import { getEmailClient } from "@/utils/emails";
+import { createIcsEvent } from "@/utils/ics";
import {
createRateLimitMiddleware,
possiblyPublicProcedure,
@@ -804,10 +804,48 @@ export const polls = router({
});
}
+ const eventId = nanoid();
+ const uid = `${eventId}@rallly.co`;
+
+ const attendees = poll.participants.filter((p) =>
+ p.votes.some((v) => v.optionId === input.optionId && v.type !== "no"),
+ );
+
+ const icsAttendees = attendees
+ .filter((a) => !!a.email) // remove participants without email
+ .map((a) => ({
+ name: a.name,
+ email: a.email as string,
+ }));
+
+ const eventEnd =
+ option.duration > 0
+ ? eventStart.add(option.duration, "minutes")
+ : eventStart.add(1, "day");
+
+ const event = createIcsEvent({
+ uid,
+ sequence: 0,
+ title: poll.title,
+ location: poll.location ?? undefined,
+ description: poll.description ?? undefined,
+ start: eventStart.toDate(),
+ end: eventEnd.toDate(),
+ allDay: option.duration === 0,
+ timeZone: poll.timeZone ?? undefined,
+ organizer: {
+ name: poll.user.name,
+ email: poll.user.email,
+ },
+ attendees: icsAttendees,
+ });
+
const scheduledEvent = await prisma.$transaction(async (tx) => {
// create scheduled event
const event = await tx.scheduledEvent.create({
data: {
+ id: eventId,
+ uid: `${eventId}@rallly.co`,
start: eventStart.toDate(),
end: eventStart.add(option.duration, "minute").toDate(),
title: poll.title,
@@ -856,56 +894,6 @@ export const polls = router({
return event;
});
- const attendees = poll.participants.filter((p) =>
- p.votes.some((v) => v.optionId === input.optionId && v.type !== "no"),
- );
-
- const icsAttendees = attendees
- .filter((a) => !!a.email) // remove participants without email
- .map((a) => ({
- name: a.name,
- email: a.email ?? undefined,
- }));
-
- const utcStart = eventStart.utc();
- const eventEnd =
- option.duration > 0
- ? eventStart.add(option.duration, "minutes")
- : eventStart.add(1, "day");
-
- const event = ics.createEvent({
- uid: scheduledEvent.id,
- sequence: 0, // TODO: Get sequence from database
- title: poll.title,
- location: poll.location ?? undefined,
- description: poll.description ?? undefined,
- organizer: {
- name: poll.user.name,
- email: poll.user.email,
- },
- attendees: icsAttendees,
- ...(option.duration > 0
- ? {
- start: [
- utcStart.year(),
- utcStart.month() + 1,
- utcStart.date(),
- utcStart.hour(),
- utcStart.minute(),
- ],
- startInputType: poll.timeZone ? "utc" : "local",
- duration: { minutes: option.duration },
- }
- : {
- start: [
- eventStart.year(),
- eventStart.month() + 1,
- eventStart.date(),
- ],
- end: [eventEnd.year(), eventEnd.month() + 1, eventEnd.date()],
- }),
- });
-
if (event.error) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
@@ -978,7 +966,11 @@ export const polls = router({
dow,
time,
},
- attachments: [{ filename: "event.ics", content: event.value }],
+ icalEvent: {
+ filename: "invite.ics",
+ method: "request",
+ content: event.value,
+ },
});
for (const p of participantsToEmail) {
diff --git a/apps/web/src/utils/ics.test.ts b/apps/web/src/utils/ics.test.ts
new file mode 100644
index 000000000..5da3901f5
--- /dev/null
+++ b/apps/web/src/utils/ics.test.ts
@@ -0,0 +1,254 @@
+import { createIcsEvent } from "./ics";
+
+describe("createIcsEvent", () => {
+ const baseOptions = {
+ title: "Test Event",
+ start: new Date("2024-03-15T10:30:00Z"), // 10:30 UTC
+ end: new Date("2024-03-15T11:30:00Z"), // 11:30 UTC
+ allDay: false,
+ sequence: 0,
+ };
+
+ describe("All-day events", () => {
+ it("should use date-only format for all-day events", () => {
+ const result = createIcsEvent({
+ ...baseOptions,
+ allDay: true,
+ start: new Date("2024-03-15T10:30:00Z"),
+ end: new Date("2024-03-16T10:30:00Z"), // Next day
+ });
+
+ expect(result.error).toBeFalsy();
+ expect(result.value).toContain("DTSTART;VALUE=DATE:20240315");
+ expect(result.value).toContain("DTEND;VALUE=DATE:20240316");
+ // Should not contain time components
+ expect(result.value).not.toMatch(/DTSTART:20240315T\d{6}/);
+ });
+
+ it("should ignore timezone parameter for all-day events", () => {
+ const withTimezone = createIcsEvent({
+ ...baseOptions,
+ allDay: true,
+ timeZone: "America/New_York",
+ });
+
+ const withoutTimezone = createIcsEvent({
+ ...baseOptions,
+ allDay: true,
+ });
+
+ expect(withTimezone.value).toEqual(withoutTimezone.value);
+ });
+
+ it("should handle cross-month boundaries", () => {
+ const result = createIcsEvent({
+ ...baseOptions,
+ allDay: true,
+ start: new Date("2024-01-31T12:00:00Z"),
+ end: new Date("2024-02-01T12:00:00Z"),
+ });
+
+ expect(result.value).toContain("DTSTART;VALUE=DATE:20240131");
+ expect(result.value).toContain("DTEND;VALUE=DATE:20240201");
+ });
+ });
+
+ describe("Timezone-aware events", () => {
+ it("should convert to UTC when timezone is specified", () => {
+ const result = createIcsEvent({
+ ...baseOptions,
+ timeZone: "America/New_York",
+ start: new Date("2024-03-15T14:30:00Z"), // 2:30 PM UTC = 10:30 AM EDT
+ end: new Date("2024-03-15T15:30:00Z"), // 3:30 PM UTC = 11:30 AM EDT
+ });
+
+ expect(result.error).toBeFalsy();
+ expect(result.value).toContain("DTSTART:20240315T143000Z");
+ expect(result.value).toContain("DTEND:20240315T153000Z");
+ });
+
+ it("should handle timezone events across date boundaries", () => {
+ const result = createIcsEvent({
+ ...baseOptions,
+ timeZone: "America/New_York",
+ start: new Date("2024-03-15T23:30:00Z"), // 11:30 PM UTC
+ end: new Date("2024-03-16T00:30:00Z"), // 12:30 AM UTC next day
+ });
+
+ expect(result.value).toContain("DTSTART:20240315T233000Z");
+ expect(result.value).toContain("DTEND:20240316T003000Z");
+ });
+ });
+
+ describe("Floating time events", () => {
+ it("should use local time format when no timezone specified", () => {
+ // Create a local date using Date constructor (not ISO string)
+ const localStart = new Date(2024, 2, 15, 10, 30, 0); // March 15, 2024, 10:30 AM local
+ const localEnd = new Date(2024, 2, 15, 11, 30, 0); // March 15, 2024, 11:30 AM local
+
+ const result = createIcsEvent({
+ ...baseOptions,
+ timeZone: undefined,
+ start: localStart,
+ end: localEnd,
+ });
+
+ expect(result.error).toBeFalsy();
+
+ // For floating time, the ICS library may still add Z suffix but the important
+ // part is that startInputType is "local" so times are treated as local
+ const hasFloatingTime = result.value?.includes("DTSTART:20240315T103000");
+ const hasUTCTime = result.value?.includes("DTSTART:20240315T103000Z");
+
+ // Either floating time format (no Z) OR the library adds Z but uses local time
+ expect(hasFloatingTime || hasUTCTime).toBe(true);
+ expect(result.value).toContain("DTEND:20240315T113000");
+ });
+
+ it("should maintain same clock time for floating events", () => {
+ // Create date in different timezone contexts
+ const mockDate = new Date(2024, 2, 15, 14, 30, 0); // March 15, 2024, 2:30 PM local
+
+ const result = createIcsEvent({
+ ...baseOptions,
+ start: mockDate,
+ end: new Date(mockDate.getTime() + 60 * 60 * 1000), // +1 hour
+ timeZone: undefined, // Floating time
+ });
+
+ // Should use the raw hour/minute values
+ expect(result.value).toContain("DTSTART:20240315T143000");
+ expect(result.value).toContain("DTEND:20240315T153000");
+ });
+ });
+
+ describe("Event properties", () => {
+ it("should include all provided properties", () => {
+ const result = createIcsEvent({
+ ...baseOptions,
+ description: "Test Description",
+ location: "Test Location",
+ organizer: {
+ name: "Test Organizer",
+ email: "[email protected]",
+ },
+ attendees: [
+ { name: "John Doe", email: "[email protected]" },
+ { name: "Jane Smith", email: "[email protected]" },
+ ],
+ method: "request",
+ status: "CONFIRMED",
+ sequence: 5,
+ });
+
+ expect(result.error).toBeFalsy();
+ expect(result.value).toContain("UID:[email protected]");
+ expect(result.value).toContain("SUMMARY:Test Event");
+ expect(result.value).toContain("DESCRIPTION:Test Description");
+ expect(result.value).toContain("LOCATION:Test Location");
+ expect(result.value).toContain(
+ 'ORGANIZER;CN="Test Organizer":MAILTO:[email protected]',
+ );
+ expect(result.value).toContain("SEQUENCE:5");
+ expect(result.value).toContain("STATUS:CONFIRMED");
+ expect(result.value).toContain("PRODID:-//Rallly//EN");
+ });
+
+ it("should handle optional properties gracefully", () => {
+ const result = createIcsEvent({
+ title: "Minimal Event",
+ start: new Date("2024-03-15T10:00:00Z"),
+ end: new Date("2024-03-15T11:00:00Z"),
+ allDay: false,
+ });
+
+ expect(result.error).toBeFalsy();
+ expect(result.value).toContain("UID:[email protected]");
+ expect(result.value).toContain("SUMMARY:Minimal Event");
+ });
+
+ it("should set default values correctly", () => {
+ const result = createIcsEvent({
+ title: "Default Event",
+ start: new Date("2024-03-15T10:00:00Z"),
+ end: new Date("2024-03-15T11:00:00Z"),
+ allDay: false,
+ });
+
+ expect(result.value).toContain("SEQUENCE:0");
+ expect(result.value).toContain("STATUS:CONFIRMED");
+ expect(result.value).toContain("METHOD:request");
+ });
+ });
+
+ describe("Cancellation events", () => {
+ it("should generate proper cancellation ICS", () => {
+ const result = createIcsEvent({
+ ...baseOptions,
+ method: "cancel",
+ status: "CANCELLED",
+ sequence: 1,
+ });
+
+ expect(result.error).toBeFalsy();
+ expect(result.value).toContain("METHOD:cancel");
+ expect(result.value).toContain("STATUS:CANCELLED");
+ expect(result.value).toContain("SEQUENCE:1");
+ });
+ });
+
+ describe("Edge cases", () => {
+ it("should handle leap year dates", () => {
+ const result = createIcsEvent({
+ ...baseOptions,
+ start: new Date("2024-02-29T10:00:00Z"), // Leap year
+ end: new Date("2024-02-29T11:00:00Z"),
+ allDay: true,
+ });
+
+ expect(result.error).toBeFalsy();
+ expect(result.value).toContain("DTSTART;VALUE=DATE:20240229");
+ });
+
+ it("should handle year boundaries", () => {
+ const result = createIcsEvent({
+ ...baseOptions,
+ start: new Date("2023-12-31T23:30:00Z"),
+ end: new Date("2024-01-01T00:30:00Z"),
+ timeZone: "UTC",
+ });
+
+ expect(result.value).toContain("DTSTART:20231231T233000Z");
+ expect(result.value).toContain("DTEND:20240101T003000Z");
+ });
+
+ it("should handle single-digit months and days", () => {
+ const result = createIcsEvent({
+ ...baseOptions,
+ start: new Date("2024-01-05T09:05:00Z"),
+ end: new Date("2024-01-05T10:05:00Z"),
+ timeZone: "UTC",
+ });
+
+ expect(result.value).toContain("DTSTART:20240105T090500Z");
+ expect(result.value).toContain("DTEND:20240105T100500Z");
+ });
+ });
+
+ describe("Error handling", () => {
+ it("should handle invalid dates gracefully", () => {
+ const result = createIcsEvent({
+ ...baseOptions,
+ start: new Date("invalid"),
+ end: new Date("also-invalid"),
+ });
+
+ // The ics library should handle this - we just need to ensure we don't crash
+ expect(result).toBeDefined();
+ expect(result.error || result.value).toBeDefined();
+ });
+ });
+});
diff --git a/apps/web/src/utils/ics.ts b/apps/web/src/utils/ics.ts
new file mode 100644
index 000000000..e3896f329
--- /dev/null
+++ b/apps/web/src/utils/ics.ts
@@ -0,0 +1,130 @@
+import * as ics from "ics";
+
+const productId = "-//Rallly//EN";
+
+export interface CreateIcsEventOptions {
+ uid: string;
+ sequence?: number;
+ start: Date;
+ end: Date;
+ allDay: boolean;
+ timeZone?: string;
+ title: string;
+ description?: string;
+ location?: string;
+ organizer?: {
+ name: string;
+ email: string;
+ };
+ attendees?: Array<{
+ name: string;
+ email: string;
+ }>;
+ method?: "request" | "publish" | "cancel";
+ status?: ics.EventStatus;
+}
+
+/**
+ * Creates an ICS event with proper date/time handling
+ * Handles all-day events, timezone conversions, and floating time automatically
+ */
+export function createIcsEvent(options: CreateIcsEventOptions): {
+ error?: Error;
+ value?: string;
+} {
+ const {
+ uid,
+ start,
+ end,
+ allDay,
+ timeZone,
+ sequence = 0,
+ title,
+ description,
+ location,
+ organizer,
+ attendees,
+ method = "request",
+ status = "CONFIRMED",
+ } = options;
+
+ let eventAttributes: ics.EventAttributes;
+
+ if (allDay) {
+ // All-day events: use date-only format (3 values)
+ eventAttributes = {
+ uid,
+ productId,
+ sequence,
+ title,
+ description,
+ location,
+ organizer,
+ attendees,
+ method,
+ status,
+ start: [start.getFullYear(), start.getMonth() + 1, start.getDate()],
+ end: [end.getFullYear(), end.getMonth() + 1, end.getDate()],
+ };
+ } else if (timeZone) {
+ // Timezone-aware events: convert to UTC
+ eventAttributes = {
+ uid,
+ productId,
+ sequence,
+ title,
+ description,
+ location,
+ organizer,
+ attendees,
+ method,
+ status,
+ start: [
+ start.getUTCFullYear(),
+ start.getUTCMonth() + 1,
+ start.getUTCDate(),
+ start.getUTCHours(),
+ start.getUTCMinutes(),
+ ],
+ end: [
+ end.getUTCFullYear(),
+ end.getUTCMonth() + 1,
+ end.getUTCDate(),
+ end.getUTCHours(),
+ end.getUTCMinutes(),
+ ],
+ startInputType: "utc",
+ };
+ } else {
+ // Floating time events: use local time values
+ eventAttributes = {
+ uid,
+ productId,
+ sequence,
+ title,
+ description,
+ location,
+ organizer,
+ attendees,
+ method,
+ status,
+ start: [
+ start.getFullYear(),
+ start.getMonth() + 1,
+ start.getDate(),
+ start.getHours(),
+ start.getMinutes(),
+ ],
+ end: [
+ end.getFullYear(),
+ end.getMonth() + 1,
+ end.getDate(),
+ end.getHours(),
+ end.getMinutes(),
+ ],
+ startInputType: "local",
+ };
+ }
+
+ return ics.createEvent(eventAttributes);
+}
diff --git a/packages/database/prisma/migrations/20250901121851_add_ics_columns/migration.sql b/packages/database/prisma/migrations/20250901121851_add_ics_columns/migration.sql
new file mode 100644
index 000000000..5990bba72
--- /dev/null
+++ b/packages/database/prisma/migrations/20250901121851_add_ics_columns/migration.sql
@@ -0,0 +1,10 @@
+-- Step 1: Add sequence column and optional uid column
+ALTER TABLE "scheduled_events" ADD COLUMN "sequence" INTEGER NOT NULL DEFAULT 0;
+ALTER TABLE "scheduled_events" ADD COLUMN "uid" TEXT;
+
+-- Step 2: Populate uid column for existing rows
+UPDATE "scheduled_events" SET "uid" = "id" || '@rallly.co' WHERE "uid" IS NULL;
+
+-- Step 3: Make uid column non-nullable and add unique constraint
+ALTER TABLE "scheduled_events" ALTER COLUMN "uid" SET NOT NULL;
+CREATE UNIQUE INDEX "scheduled_events_uid_key" ON "scheduled_events"("uid");
diff --git a/packages/database/prisma/models/event.prisma b/packages/database/prisma/models/event.prisma
index aaf13f64f..e135c1bd5 100644
--- a/packages/database/prisma/models/event.prisma
+++ b/packages/database/prisma/models/event.prisma
@@ -30,6 +30,8 @@ model ScheduledEvent {
end DateTime
allDay Boolean @default(false) @map("all_day")
deletedAt DateTime? @map("deleted_at")
+ sequence Int @default(0)
+ uid String @unique
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
space Space @relation(fields: [spaceId], references: [id], onDelete: Cascade)
diff --git a/packages/database/prisma/seed/scheduled-events.ts b/packages/database/prisma/seed/scheduled-events.ts
index cce642a75..e9ad5d726 100644
--- a/packages/database/prisma/seed/scheduled-events.ts
+++ b/packages/database/prisma/seed/scheduled-events.ts
@@ -109,6 +109,7 @@ async function createScheduledEventForUser({
await prisma.scheduledEvent.create({
data: {
title,
+ uid: faker.datatype.uuid(),
description,
start: startTime, // Use correct model field name 'start'
end: endTime, // Use correct model field name 'end'
diff --git a/packages/emails/src/send-email.tsx b/packages/emails/src/send-email.tsx
index 953ef2a3a..b618efe90 100644
--- a/packages/emails/src/send-email.tsx
+++ b/packages/emails/src/send-email.tsx
@@ -18,6 +18,7 @@ type SendEmailOptions<T extends TemplateName> = {
};
props: TemplateProps<T>;
attachments?: Mail.Options["attachments"];
+ icalEvent?: Mail.Options["icalEvent"];
};
type EmailProviderConfig =
@@ -116,6 +117,7 @@ export class EmailClient {
html,
text,
attachments: options.attachments,
+ icalEvent: options.icalEvent,
});
} catch (e) {
const enhancedError = new Error(