Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Set a video call when editing a poll; lock scheduled polls (#3406)
Luke Vellab180b2b87610
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 18b0f27cb..448bb5828 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -91,6 +91,7 @@"authErrorsUserBanned": "This account has been banned. Please contact support if you believe this is an error.","back": "Back","backToHome": "Back to home",+ "backToPoll": "Back to poll","banned": "Banned","banUser": "Ban user","banUserDesc": "Are you sure you want to ban <b>{email}</b>? They will be signed out and won't be able to log in.",@@ -822,6 +823,8 @@"save": "Save","saved": "Saved","saving": "Saving...",+ "scheduledPollLockedDescription": "A scheduled poll can no longer be edited.",+ "scheduledPollLockedTitle": "This poll is scheduled","schedulePoll": "Schedule","schedulePollDescription": "Select a final date for your event.","schedulePollError": "Failed to schedule poll",diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-details/page.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-details/components/edit-details-form.tsxsimilarity index 73%rename from apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-details/page.tsxrename to apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-details/components/edit-details-form.tsxindex 7f7849080..1af2a8321 100644--- a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-details/page.tsx+++ b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-details/components/edit-details-form.tsx@@ -13,12 +13,22 @@ import { Form } from "@rallly/ui/form";import { useRouter } from "next/navigation";import { useForm } from "react-hook-form";import { Link } from "@/components/link";+import type { ConferencingOptions } from "@/features/conferencing/components/conferencing-field";+import {+ toConferencingFormValues,+ toPollConferencing,+} from "@/features/conferencing/components/conferencing-field";import { PollDetailsForm } from "@/features/poll/components/forms/poll-details-form";+import type { PollDetailsData } from "@/features/poll/components/forms/types";import { useUpdatePollMutation } from "@/features/poll/components/mutations";import { usePoll } from "@/features/poll/components/poll-context";import { Trans } from "@/i18n/client";-const Page = () => {+export function EditDetailsForm({+ conferencing,+}: {+ conferencing: ConferencingOptions;+}) {const { poll } = usePoll();const { mutate: updatePollMutation, isPending: isUpdating } =useUpdatePollMutation();@@ -30,11 +40,12 @@ const Page = () => {router.push(pollLink);};- const form = useForm({+ const form = useForm<PollDetailsData>({defaultValues: {title: poll.title,location: poll.location ?? "",description: poll.description ?? "",+ ...toConferencingFormValues(poll.conferencing),},});@@ -44,7 +55,13 @@ const Page = () => {onSubmit={form.handleSubmit((data) => {//submitupdatePollMutation(- { pollId: poll.id, ...data },+ {+ pollId: poll.id,+ title: data.title,+ location: data.location,+ description: data.description,+ conferencing: toPollConferencing(data) ?? null,+ },{onSuccess: (res) => {if (res.ok) {@@ -68,7 +85,7 @@ const Page = () => {</CardDescription></CardHeader><CardContent>- <PollDetailsForm />+ <PollDetailsForm conferencing={conferencing} /></CardContent><CardFooter className="justify-between"><Link href={pollLink} className={buttonVariants()}>@@ -82,6 +99,4 @@ const Page = () => {</form></Form>);-};--export default Page;+}diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-details/page.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-details/page.tsxnew file mode 100644index 000000000..cd80efa2c--- /dev/null+++ b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-details/page.tsx@@ -0,0 +1,21 @@+import { Suspense } from "react";+import { loadPollConferencingOptions } from "@/features/poll/loaders";+import { EditDetailsForm } from "./components/edit-details-form";++async function EditDetails({ params }: { params: Promise<{ urlId: string }> }) {+ const { urlId } = await params;+ const conferencing = await loadPollConferencingOptions(urlId);+ return <EditDetailsForm conferencing={conferencing} />;+}++export default function Page({+ params,+}: {+ params: Promise<{ urlId: string }>;+}) {+ return (+ <Suspense>+ <EditDetails params={params} />+ </Suspense>+ );+}diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-options/page.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-options/page.tsxsimilarity index 100%rename from apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-options/page.tsxrename to apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-options/page.tsxdiff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-settings/page.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-settings/page.tsxsimilarity index 100%rename from apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-settings/page.tsxrename to apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-settings/page.tsxdiff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/layout.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/layout.tsxnew file mode 100644index 000000000..1e44cc770--- /dev/null+++ b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/layout.tsx@@ -0,0 +1,53 @@+"use client";+import { buttonVariants } from "@rallly/ui";+import { Card } from "@rallly/ui/card";+import { CalendarCheck2Icon } from "lucide-react";+import type React from "react";+import {+ EmptyState,+ EmptyStateDescription,+ EmptyStateFooter,+ EmptyStateIcon,+ EmptyStateTitle,+} from "@/components/empty-state";+import { Link } from "@/components/link";+import { usePoll } from "@/features/poll/client";+import { Trans } from "@/i18n/client";++// A booked event keeps its own copy of the poll's details, so edits made after+// booking would never reach it. The server rejects them too; this covers deep+// links to the edit pages.+export default function Layout({ children }: { children: React.ReactNode }) {+ const poll = usePoll();++ if (poll.status !== "scheduled") {+ return children;+ }++ return (+ <Card>+ <EmptyState>+ <EmptyStateIcon>+ <CalendarCheck2Icon />+ </EmptyStateIcon>+ <EmptyStateTitle>+ <Trans+ i18nKey="scheduledPollLockedTitle"+ defaults="This poll is scheduled"+ />+ </EmptyStateTitle>+ <EmptyStateDescription>+ <Trans+ i18nKey="scheduledPollLockedDescription"+ defaults="A scheduled poll can no longer be edited."+ />+ </EmptyStateDescription>+ <EmptyStateFooter>+ <Link href={`/poll/${poll.id}`} className={buttonVariants()}>+ <Trans i18nKey="backToPoll" defaults="Back to poll" />+ </Link>+ </EmptyStateFooter>+ </EmptyState>+ </Card>+ );+}diff --git a/apps/web/src/features/conferencing/components/conferencing-field.tsx b/apps/web/src/features/conferencing/components/conferencing-field.tsxindex 0a58a4b21..fc199d0cc 100644--- a/apps/web/src/features/conferencing/components/conferencing-field.tsx+++ b/apps/web/src/features/conferencing/components/conferencing-field.tsx@@ -13,7 +13,10 @@ import React from "react";import { Controller, useFormContext } from "react-hook-form";import { Link } from "@/components/link";import { ConferencingProviderIcon } from "@/features/conferencing/components/conferencing-provider-icon";-import type { ConferencingProvider } from "@/features/conferencing/schema";+import type {+ ConferencingProvider,+ PollConferencing,+} from "@/features/conferencing/schema";import { conferencingProviderLabels } from "@/features/conferencing/utils";import { Trans, useTranslation } from "@/i18n/client";@@ -31,6 +34,37 @@ type ConferencingFormValues = {conferencingLabel?: string;};+export const toPollConferencing = (+ data: ConferencingFormValues,+): PollConferencing | undefined => {+ switch (data.conferencingProvider) {+ case "zoom":+ case "meet":+ case "teams":+ return { provider: data.conferencingProvider };+ case "custom": {+ const uri = data.conferencingUrl?.trim();+ return {+ provider: "custom",+ label: data.conferencingLabel?.trim() ?? "",+ ...(uri ? { uri } : {}),+ };+ }+ default:+ return undefined;+ }+};++export const toConferencingFormValues = (+ conferencing: PollConferencing | null,+): Required<ConferencingFormValues> => ({+ conferencingProvider: conferencing?.provider ?? "",+ conferencingUrl:+ conferencing?.provider === "custom" ? (conferencing.uri ?? "") : "",+ conferencingLabel:+ conferencing?.provider === "custom" ? conferencing.label : "",+});+// Menu entries for the shared "Add location" menu. Renders nothing once a// choice is made: an event carries one meeting link.export function ConferencingProviderMenuItems({diff --git a/apps/web/src/features/poll/components/create-poll.tsx b/apps/web/src/features/poll/components/create-poll.tsxindex 62cf18628..b3563967b 100644--- a/apps/web/src/features/poll/components/create-poll.tsx+++ b/apps/web/src/features/poll/components/create-poll.tsx@@ -19,6 +19,7 @@ import { useForm, useFormContext } from "react-hook-form";import useFormPersist from "react-hook-form-persist";import { Link } from "@/components/link";import type { ConferencingOptions } from "@/features/conferencing/components/conferencing-field";+import { toPollConferencing } from "@/features/conferencing/components/conferencing-field";import { PollDetailsForm } from "@/features/poll/components/forms/poll-details-form";import PollOptionsForm from "@/features/poll/components/forms/poll-options-form/poll-options-form";import { PollSettingsForm } from "@/features/poll/components/forms/poll-settings";@@ -31,30 +32,6 @@ import { setFlash } from "@/lib/flash/client";import { getBrowserTimeZone } from "@/lib/utils/date-time-utils";import { trpc } from "@/trpc/client";-const toPollConferencing = (- data: Pick<- NewEventData,- "conferencingProvider" | "conferencingUrl" | "conferencingLabel"- >,-) => {- switch (data.conferencingProvider) {- case "zoom":- case "meet":- case "teams":- return { provider: data.conferencingProvider };- case "custom": {- const uri = data.conferencingUrl?.trim();- return {- provider: "custom" as const,- label: data.conferencingLabel?.trim() ?? "",- ...(uri ? { uri } : {}),- };- }- default:- return undefined;- }-};-const required = <T,>(v: T | undefined): T => {if (!v) {throw new Error("Required value is missing");diff --git a/apps/web/src/features/poll/components/forms/poll-details-form.tsx b/apps/web/src/features/poll/components/forms/poll-details-form.tsxindex 739f445ac..9d42d0fb0 100644--- a/apps/web/src/features/poll/components/forms/poll-details-form.tsx+++ b/apps/web/src/features/poll/components/forms/poll-details-form.tsx@@ -24,8 +24,7 @@ import { useFormValidation } from "@/lib/utils/form-validation";import { LazyRichTextEditor } from "./lazy-rich-text-editor";import type { NewEventData } from "./types";-// `conferencing` is absent on forms that don't support video calls (the edit-// form); "Add location" then opens the address field directly.+// Without `conferencing`, "Add location" opens the address field directly.export const PollDetailsForm = ({conferencing,}: {diff --git a/apps/web/src/features/poll/components/manage-poll.tsx b/apps/web/src/features/poll/components/manage-poll.tsxindex b0ce26f47..e35b8e510 100644--- a/apps/web/src/features/poll/components/manage-poll.tsx+++ b/apps/web/src/features/poll/components/manage-poll.tsx@@ -79,6 +79,10 @@ const ManagePoll: React.FunctionComponent<{const scheduleDialog = useDialog();const isFree = useIsFree();const { exportToCsv } = useCsvExporter();+ // Edits made after booking would never reach the booked event.+ const canEdit = poll.status !== "scheduled";+ const canChangeStatus =+ poll.status !== "scheduled" && poll.status !== "canceled";return (<>@@ -92,26 +96,30 @@ const ManagePoll: React.FunctionComponent<{<ChevronDownIcon data-icon="inline-end" /></DropdownMenuTrigger><DropdownMenuContent align="end">- <DropdownMenuItem- render={<Link href={`/poll/${poll.id}/edit-details`} />}- >- <PencilIcon />- <Trans i18nKey="editDetails" />- </DropdownMenuItem>- <DropdownMenuItem- render={<Link href={`/poll/${poll.id}/edit-options`} />}- >- <TableIcon />- <Trans i18nKey="editOptions" />- </DropdownMenuItem>- <DropdownMenuItem- render={<Link href={`/poll/${poll.id}/edit-settings`} />}- >- <Settings2Icon />- <Trans i18nKey="editSettings" defaults="Edit settings" />- </DropdownMenuItem>- <DropdownMenuSeparator />- {poll.status === "scheduled" || poll.status === "canceled" ? null : (+ {canEdit ? (+ <>+ <DropdownMenuItem+ render={<Link href={`/poll/${poll.id}/edit-details`} />}+ >+ <PencilIcon />+ <Trans i18nKey="editDetails" />+ </DropdownMenuItem>+ <DropdownMenuItem+ render={<Link href={`/poll/${poll.id}/edit-options`} />}+ >+ <TableIcon />+ <Trans i18nKey="editOptions" />+ </DropdownMenuItem>+ <DropdownMenuItem+ render={<Link href={`/poll/${poll.id}/edit-settings`} />}+ >+ <Settings2Icon />+ <Trans i18nKey="editSettings" defaults="Edit settings" />+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ </>+ ) : null}+ {canChangeStatus ? (<><DropdownMenuItemdisabled={!!poll.event}@@ -132,9 +140,9 @@ const ManagePoll: React.FunctionComponent<{{isFree ? <ProBadge /> : null}</DropdownMenuItem><OpenCloseToggle />+ <DropdownMenuSeparator /></>- )}- <DropdownMenuSeparator />+ ) : null}<DropdownMenuItem onClick={exportToCsv}><DownloadIcon /><Trans i18nKey="exportToCsv" defaults="Export to CSV" />diff --git a/apps/web/src/features/poll/loaders.ts b/apps/web/src/features/poll/loaders.tsindex 0710ab096..00a7e73bc 100644--- a/apps/web/src/features/poll/loaders.ts+++ b/apps/web/src/features/poll/loaders.ts@@ -3,6 +3,7 @@ import "server-only";import { shortUrl } from "@rallly/utils/absolute-url";import { notFound, redirect } from "next/navigation";import { cache } from "react";+import { loadConferencingOptions } from "@/features/conferencing/loaders";import {canUserManagePoll,getPoll,@@ -19,6 +20,7 @@ import {maskParticipantsForViewer,} from "@/features/poll/utils";import { loadActiveSpaceContentScope } from "@/features/space/loaders";+import { getUser } from "@/features/user/data";import { getSession } from "@/lib/auth";export const loadPollStatusCounts = cache(async () => {@@ -131,3 +133,15 @@ export const loadAdminPoll = cache(async (pollId: string) => {user,};});++// The meeting is minted from the poll owner's account at booking, whoever+// edits the poll, so the form offers what the owner can use.+export const loadPollConferencingOptions = cache(async (pollId: string) => {+ const { poll } = await loadAdminPoll(pollId);+ const owner = poll.userId ? await getUser(poll.userId) : null;+ const host = owner && !owner.isGuest ? owner : null;+ return loadConferencingOptions({+ userId: host?.id ?? null,+ email: host?.email ?? null,+ });+});diff --git a/apps/web/src/features/poll/mutations.test.ts b/apps/web/src/features/poll/mutations.test.tsindex 24bb3ce6a..befdfbff1 100644--- a/apps/web/src/features/poll/mutations.test.ts+++ b/apps/web/src/features/poll/mutations.test.ts@@ -230,6 +230,21 @@ describe("closePoll", () => {});});+ it("leaves a scheduled poll unchanged", async () => {+ mockFindFirst.mockResolvedValue({ ...openPoll, status: "scheduled" });++ const result = await closePoll({ pollId: "p1", spaceId });++ expect(mockUpdate).not.toHaveBeenCalled();+ expect(mockActivityCreateMany).not.toHaveBeenCalled();+ expect(result).toEqual({+ id: "p1",+ status: "scheduled",+ conferencing: null,+ participantCount: 2,+ });+ });+it("records a poll_closed activity alongside the close", async () => {mockFindFirst.mockResolvedValue(openPoll);mockUpdate.mockResolvedValue(closedPoll);diff --git a/apps/web/src/features/poll/mutations.ts b/apps/web/src/features/poll/mutations.tsindex 3250caf55..cb253a455 100644--- a/apps/web/src/features/poll/mutations.ts+++ b/apps/web/src/features/poll/mutations.ts@@ -148,7 +148,8 @@ export const createPoll = async ({/*** Closes a poll manually. Idempotent: closing an already-closed poll returns* the poll unchanged without altering its `closedReason` (so a poll auto-closed- * by the cron job keeps `closedReason: "auto"`). Returns `null` when the poll+ * by the cron job keeps `closedReason: "auto"`). A scheduled poll is final and+ * is returned unchanged too. Returns `null` when the poll* does not exist in the space, letting the caller surface a 404.** `userId` attributes the activity event when the actor is known; API key@@ -177,7 +178,7 @@ export const closePoll = async ({return null;}- if (poll.status === "closed") {+ if (poll.status === "closed" || poll.status === "scheduled") {return toPollResponse(poll);}diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.tsindex 47593df11..8f39eccf5 100644--- a/apps/web/src/trpc/routers/polls.ts+++ b/apps/web/src/trpc/routers/polls.ts@@ -1,4 +1,4 @@-import { prisma } from "@rallly/database";+import { Prisma, prisma } from "@rallly/database";import { sendFinalizeHostEmail } from "@rallly/emails/templates/finalized-host";import { sendFinalizeParticipantEmail } from "@rallly/emails/templates/finalized-participant";import { sendNewPollEmail } from "@rallly/emails/templates/new-poll";@@ -406,6 +406,8 @@ export const polls = router({title: z.string().trim().optional(),timeZone: timeZoneInput,location: z.string().trim().optional(),+ // Omitted leaves it unchanged; null removes it.+ conferencing: pollConferencingSchema.nullable().optional(),description: z.string().trim()@@ -433,6 +435,47 @@ export const polls = router({});}+ const current = await prisma.poll.findUnique({+ where: { id: pollId },+ select: { status: true, userId: true, conferencing: true },+ });++ if (!current) {+ throw new TRPCError({ code: "NOT_FOUND" });+ }++ // The booked event holds its own copy of the poll's details, so an edit+ // after booking would never reach it.+ if (current.status === "scheduled") {+ throw new TRPCError({+ code: "CONFLICT",+ message: "A scheduled poll cannot be edited",+ });+ }++ // The meeting is minted from the owner's account at booking, whoever+ // edits. Checked only when the provider changes, so an unrelated edit+ // still saves after the owner disconnects.+ const conferencing = input.conferencing;+ const priorConferencing = parsePollConferencing(current.conferencing, {+ pollId,+ });+ if (+ conferencing &&+ conferencing.provider !== "custom" &&+ conferencing.provider !== priorConferencing?.provider+ ) {+ const connected = current.userId+ ? await getConnectedConferencingProviders(current.userId)+ : [];+ if (!connected.includes(conferencing.provider)) {+ throw new TRPCError({+ code: "PRECONDITION_FAILED",+ message: "Conferencing provider is not connected",+ });+ }+ }+const moderation = await moderateContent({userId: ctx.user.id,userEmail: ctx.user.email,@@ -440,6 +483,10 @@ export const polls = router({Title: input.title || "",Description: input.description || "",Location: input.location || "",+ Conferencing:+ conferencing?.provider === "custom"+ ? `${conferencing.label} ${moderatedLinkText(conferencing.uri)}`+ : "",},});@@ -496,6 +543,7 @@ export const polls = router({select: {title: true,location: true,+ conferencing: true,description: true,timeZone: true,hideParticipants: true,@@ -597,14 +645,17 @@ export const polls = router({});const kind = (maxDuration._max.duration ?? 0) > 0 ? "time" : "date";- await tx.poll.update({- select: { id: true },+ // Conditional on status so a booking that lands after the check above+ // rolls this edit back instead of it silently missing the event.+ const { count: updated } = await tx.poll.updateMany({where: {id: pollId,+ status: { not: "scheduled" },},data: {title: input.title,location: input.location,+ conferencing: conferencing === null ? Prisma.DbNull : conferencing,description: input.description,// Date-only polls are floating: keep timeZone null so it stays the// single source of truth for whether options are timezone-bound.@@ -618,6 +669,13 @@ export const polls = router({},});+ if (updated === 0) {+ throw new TRPCError({+ code: "CONFLICT",+ message: "A scheduled poll cannot be edited",+ });+ }+// The effective persisted timeZone: forced null for date-only polls,// untouched when the input omits it.const nextTimeZone =@@ -635,6 +693,11 @@ export const polls = router({(input.location || null) !== (prior.location || null)) ||(input.description !== undefined &&(input.description || null) !== (prior.description || null)) ||+ (conferencing !== undefined &&+ JSON.stringify(conferencing) !==+ JSON.stringify(+ parsePollConferencing(prior.conferencing, { pollId }),+ )) ||nextTimeZone !== prior.timeZone ||(input.hideParticipants !== undefined &&input.hideParticipants !== prior.hideParticipants) ||@@ -1107,7 +1170,7 @@ export const polls = router({const uid = `${eventId}@rallly.co`;// A second booking would mint a second meeting and orphan the first- // event, so a poll is booked once; reopen it to book again.+ // event, so a poll is booked once.if (poll.status === "scheduled") {throw new TRPCError({code: "CONFLICT",@@ -1415,11 +1478,12 @@ export const polls = router({await prisma.$transaction(async (tx) => {// Conditional transition: only the call that actually flips the// status appends a lifecycle event, so repeated or concurrent calls- // can't record a reopen that didn't happen.+ // can't record a reopen that didn't happen. Scheduling is final: the+ // booked event has already gone out to attendees.const { count } = await tx.poll.updateMany({where: {id: input.pollId,- status: { not: "open" },+ status: { notIn: ["open", "scheduled"] },},data: {status: "open",@@ -1428,6 +1492,16 @@ export const polls = router({});if (count === 0) {+ const current = await tx.poll.findUnique({+ where: { id: input.pollId },+ select: { status: true },+ });+ if (current?.status === "scheduled") {+ throw new TRPCError({+ code: "CONFLICT",+ message: "A scheduled poll cannot be reopened",+ });+ }return;}@@ -1486,11 +1560,12 @@ export const polls = router({// mutations: an already-closed poll keeps its closedReason (so an// auto-close stays "auto"), and only the call that actually flips// the status appends a lifecycle event — repeated or concurrent- // calls can't record a close that didn't happen.+ // calls can't record a close that didn't happen. A scheduled poll is+ // final; closing it would let reopen delete the booked event.const { count } = await tx.poll.updateMany({where: {id: input.pollId,- status: { not: "closed" },+ status: { notIn: ["closed", "scheduled"] },},data: {status: "closed",