From 1a5b7d60e786f125d06b9c1555377bcca905c7b9 Mon Sep 17 00:00:00 2001 From: Rajkumar Date: Mon, 23 Nov 2026 22:54:01 +0530 Subject: [PATCH] feat: polling feature initialized and implemented --- .../src/components/poll/ActivePollOverlay.tsx | 357 +++++++++++++++ .../src/components/poll/CreatePollModal.tsx | 311 ++++++++++++++ .../components/poll/PollComponents.test.tsx | 230 ++++++++++ .../components/poll/RecordedPollsModal.tsx | 168 ++++++++ apps/frontend/src/components/poll/types.ts | 30 ++ apps/frontend/src/screens/LiveQuiz.test.tsx | 132 ++++++ apps/frontend/src/screens/LiveQuiz.tsx | 207 ++++++++- .../src/controllers/sessionController.test.ts | 59 ++- .../src/controllers/sessionController.ts | 27 +- apps/http-server/src/routes/session.ts | 6 +- apps/ws-server/src/redis.ts | 3 +- .../src/utils/handleMessages.poll.test.ts | 406 ++++++++++++++++++ apps/ws-server/src/utils/handleMessages.ts | 144 +++++++ apps/ws-server/src/utils/pollManager.ts | 262 +++++++++++ packages/db/.gitignore | 1 + .../migration.sql | 61 +++ packages/db/prisma/schema.prisma | 52 +++ 17 files changed, 2448 insertions(+), 8 deletions(-) create mode 100644 apps/frontend/src/components/poll/ActivePollOverlay.tsx create mode 100644 apps/frontend/src/components/poll/CreatePollModal.tsx create mode 100644 apps/frontend/src/components/poll/PollComponents.test.tsx create mode 100644 apps/frontend/src/components/poll/RecordedPollsModal.tsx create mode 100644 apps/frontend/src/components/poll/types.ts create mode 100644 apps/ws-server/src/utils/handleMessages.poll.test.ts create mode 100644 apps/ws-server/src/utils/pollManager.ts create mode 100644 packages/db/prisma/migrations/20261123180000_add_poll_tables/migration.sql diff --git a/apps/frontend/src/components/poll/ActivePollOverlay.tsx b/apps/frontend/src/components/poll/ActivePollOverlay.tsx new file mode 100644 index 0000000..80ab3e2 --- /dev/null +++ b/apps/frontend/src/components/poll/ActivePollOverlay.tsx @@ -0,0 +1,357 @@ +import { useState, useEffect } from "react"; +import { BiCheckCircle, BiSave, BiStop, BiX } from "react-icons/bi"; +import { LuCheck, LuChevronDown, LuChevronUp, LuClock, LuUsers } from "react-icons/lu"; +import type { Poll } from "./types"; + +interface ActivePollOverlayProps { + poll: Poll; + isOrganizer: boolean; + participantId?: string; + onVote: (optionId: string) => void; + onEndPoll: () => void; + onRecordPoll: () => void; + onDismissPoll: () => void; + isConnected: boolean; +} + +export default function ActivePollOverlay({ + poll, + isOrganizer, + onVote, + onEndPoll, + onRecordPoll, + onDismissPoll, + isConnected, +}: ActivePollOverlayProps) { + const [minimized, setMinimized] = useState(false); + const [secondsRemaining, setSecondsRemaining] = useState(null); + + const hasVoted = Boolean(poll.votedOptionId); + const isEnded = poll.status === "ENDED"; + const showResults = isOrganizer || hasVoted || isEnded; + + // Countdown timer if duration was specified + useEffect(() => { + if (!poll.duration || isEnded) { + setSecondsRemaining(null); + return; + } + + const elapsed = Math.floor((Date.now() - poll.createdAt) / 1000); + const initialRemaining = Math.max(0, poll.duration - elapsed); + setSecondsRemaining(initialRemaining); + + if (initialRemaining <= 0) return; + + const interval = setInterval(() => { + setSecondsRemaining((prev) => { + if (prev === null || prev <= 1) { + clearInterval(interval); + return 0; + } + return prev - 1; + }); + }, 1000); + + return () => clearInterval(interval); + }, [poll.createdAt, poll.duration, isEnded]); + + // Find leading option + const maxVotes = Math.max(...poll.options.map((o) => o.voteCount), 0); + + // Minimized compact pill view + if (minimized) { + return ( +
setMinimized(false)} + role="region" + aria-label="Active Poll Minimized" + > + + + + +
+ + {isEnded ? "Poll Ended" : "Live Poll"} + + + {poll.question} + +
+
+ + {poll.totalVotes} +
+ +
+ ); + } + + return ( +
+
+ {/* Top ambient glow */} +
+ + {/* Header Bar */} +
+
+ + + + + + {isEnded ? "Poll Closed" : "Live Poll"} + + + {typeof poll.questionIndex === "number" && ( + + Q#{poll.questionIndex + 1} + + )} +
+ +
+ {secondsRemaining !== null && !isEnded && ( + + {secondsRemaining}s + + )} + +
+ + + {poll.totalVotes} {poll.totalVotes === 1 ? "vote" : "votes"} + +
+ + + + {isOrganizer && ( + + )} +
+
+ + {/* Poll Question */} +

+ {poll.question} +

+ + {/* Options / Results */} +
+ {poll.options.map((option) => { + const isVotedByMe = poll.votedOptionId === option.id; + const isLeader = maxVotes > 0 && option.voteCount === maxVotes; + + if (showResults) { + return ( +
+ {/* Background progress fill bar */} +
+ +
+
+ + {option.text} + + {isVotedByMe && ( + + Your Vote + + )} +
+ +
+ + {option.voteCount} {option.voteCount === 1 ? "vote" : "votes"} + + + {option.percentage}% + +
+
+ + {/* Horizontal mini bar underneath */} +
+
+
+
+ ); + } + + // Voting Mode for Participant (Not yet voted) + return ( + + ); + })} +
+ + {/* Voting status / Notice for participant */} + {!isOrganizer && ( +
+ {hasVoted ? ( +

+ ✓ You voted. Live results update automatically as others vote. +

+ ) : isEnded ? ( +

+ This poll has closed. +

+ ) : ( +

+ Tap an option above to submit your vote! +

+ )} +
+ )} + + {/* Organizer Controls */} + {isOrganizer && ( +
+
+ {/* Record Result Button */} + {poll.isRecorded ? ( +
+ + + Recorded{" "} + {poll.recordedAt + ? new Date(poll.recordedAt).toLocaleTimeString([], { + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }) + : ""} + +
+ ) : ( + + )} + + {/* End Poll Button */} + {!isEnded && ( + + )} +
+ + +
+ )} + + {/* Participant close if ended */} + {!isOrganizer && isEnded && ( +
+ +
+ )} +
+
+ ); +} diff --git a/apps/frontend/src/components/poll/CreatePollModal.tsx b/apps/frontend/src/components/poll/CreatePollModal.tsx new file mode 100644 index 0000000..8b0a70a --- /dev/null +++ b/apps/frontend/src/components/poll/CreatePollModal.tsx @@ -0,0 +1,311 @@ +import { useState } from "react"; +import { BiPoll, BiPlus, BiTrash, BiX } from "react-icons/bi"; +import { LuSparkles, LuTimer } from "react-icons/lu"; +import type { PollPreset } from "./types"; + +interface CreatePollModalProps { + isOpen: boolean; + onClose: () => void; + onSubmit: (data: { + question: string; + options: string[]; + duration?: number; + }) => void; + currentQuestionText?: string; + questionIndex?: number; +} + +const PRESETS: PollPreset[] = [ + { + label: "Yes / No", + icon: "👍", + question: "Quick poll: Do you agree with this concept?", + options: ["Yes", "No"], + }, + { + label: "Understanding", + icon: "💡", + question: "How well did you understand this question?", + options: ["Understood completely", "Partially understood", "Need explanation"], + }, + { + label: "Difficulty", + icon: "⚡", + question: "What did you think of the difficulty?", + options: ["Too Easy", "Just Right", "Very Tough"], + }, + { + label: "A / B / C / D", + icon: "🔤", + question: "Which option seemed most plausible to you?", + options: ["Option A", "Option B", "Option C", "Option D"], + }, +]; + +const DURATIONS = [ + { label: "No Timer", value: undefined }, + { label: "15s", value: 15 }, + { label: "30s", value: 30 }, + { label: "45s", value: 45 }, + { label: "60s", value: 60 }, +]; + +export default function CreatePollModal({ + isOpen, + onClose, + onSubmit, + currentQuestionText, + questionIndex, +}: CreatePollModalProps) { + const [question, setQuestion] = useState(""); + const [options, setOptions] = useState(["", ""]); + const [duration, setDuration] = useState(undefined); + const [error, setError] = useState(""); + + if (!isOpen) return null; + + const handleApplyPreset = (preset: PollPreset) => { + setQuestion(preset.question); + setOptions([...preset.options]); + setError(""); + }; + + const handleUseQuestionAsPrompt = () => { + if (currentQuestionText) { + setQuestion(`Thoughts on: "${currentQuestionText}"?`); + setOptions(["Agreed with correct answer", "Tricked by a distractor", "Guessed"]); + setError(""); + } + }; + + const handleAddOption = () => { + if (options.length >= 6) return; + setOptions([...options, ""]); + }; + + const handleRemoveOption = (index: number) => { + if (options.length <= 2) return; + setOptions(options.filter((_, idx) => idx !== index)); + }; + + const handleOptionChange = (index: number, value: string) => { + const updated = [...options]; + updated[index] = value; + setOptions(updated); + if (error) setError(""); + }; + + const handleSubmit = (e: React.FormEvent) => { + e.preventDefault(); + const cleanQuestion = question.trim(); + if (!cleanQuestion) { + setError("Please provide a question for the poll."); + return; + } + + const cleanOptions = options.map((o) => o.trim()).filter((o) => o.length > 0); + if (cleanOptions.length < 2) { + setError("Please provide at least 2 non-empty options."); + return; + } + + onSubmit({ + question: cleanQuestion, + options: cleanOptions, + duration, + }); + + onClose(); + }; + + return ( +
+
+ {/* Top ambient glow */} +
+ + {/* Header */} +
+
+
+ +
+
+

+ Create Live Poll +

+ {typeof questionIndex === "number" && ( +

+ During Question #{questionIndex + 1} +

+ )} +
+
+ +
+ + {/* Quick Presets */} +
+
+ + {currentQuestionText && ( + + )} +
+
+ {PRESETS.map((preset) => ( + + ))} +
+
+ +
+ {/* Question Input */} +
+ + { + setQuestion(e.target.value); + if (error) setError(""); + }} + className="w-full bg-zinc-900/90 border border-pink-700/40 focus:border-pink-500 rounded-xl px-4 py-3 text-white placeholder-zinc-500 font-secondary text-base outline-none transition-all shadow-inner" + maxLength={200} + /> +
+ + {/* Options */} +
+
+ + {options.length < 6 && ( + + )} +
+ +
+ {options.map((opt, idx) => ( +
+ + #{idx + 1} + + handleOptionChange(idx, e.target.value)} + className="flex-1 bg-zinc-900/80 border border-zinc-700/60 focus:border-pink-500 rounded-xl px-3.5 py-2.5 text-white placeholder-zinc-500 font-secondary text-sm outline-none transition-all" + maxLength={80} + /> + {options.length > 2 && ( + + )} +
+ ))} +
+
+ + {/* Duration */} +
+ +
+ {DURATIONS.map((d) => ( + + ))} +
+
+ + {error && ( +

+ {error} +

+ )} + + {/* Buttons */} +
+ + +
+
+
+
+ ); +} diff --git a/apps/frontend/src/components/poll/PollComponents.test.tsx b/apps/frontend/src/components/poll/PollComponents.test.tsx new file mode 100644 index 0000000..f6aa29c --- /dev/null +++ b/apps/frontend/src/components/poll/PollComponents.test.tsx @@ -0,0 +1,230 @@ +import { render, screen, fireEvent } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, expect, it, vi } from "vitest"; +import CreatePollModal from "./CreatePollModal"; +import ActivePollOverlay from "./ActivePollOverlay"; +import RecordedPollsModal from "./RecordedPollsModal"; +import type { Poll } from "./types"; + +describe("CreatePollModal", () => { + it("renders nothing when isOpen is false", () => { + const { container } = render( + + ); + expect(container.firstChild).toBeNull(); + }); + + it("applies a preset template when clicked", async () => { + const user = userEvent.setup(); + render(); + + const yesNoPreset = screen.getByRole("button", { name: /Yes \/ No/i }); + await user.click(yesNoPreset); + + const questionInput = screen.getByLabelText(/Poll Question \/ Prompt/i) as HTMLInputElement; + expect(questionInput.value).toContain("Do you agree"); + + const optionInputs = screen.getAllByPlaceholderText(/Option/i) as HTMLInputElement[]; + expect(optionInputs[0]?.value).toBe("Yes"); + expect(optionInputs[1]?.value).toBe("No"); + }); + + it("allows adding and removing custom options", async () => { + const user = userEvent.setup(); + render(); + + expect(screen.getAllByPlaceholderText(/Option/i)).toHaveLength(2); + + const addBtn = screen.getByRole("button", { name: /Add Option/i }); + await user.click(addBtn); + expect(screen.getAllByPlaceholderText(/Option/i)).toHaveLength(3); + + const removeBtns = screen.getAllByLabelText(/Remove option/i); + await user.click(removeBtns[0]!); + expect(screen.getAllByPlaceholderText(/Option/i)).toHaveLength(2); + }); + + it("shows error and prevents submission with empty question", async () => { + const user = userEvent.setup(); + const onSubmit = vi.fn(); + render(); + + const submitBtn = screen.getByRole("button", { name: /Launch Poll/i }); + await user.click(submitBtn); + + expect(onSubmit).not.toHaveBeenCalled(); + expect(screen.getByRole("alert")).toHaveTextContent(/Please provide a question/i); + }); + + it("submits valid poll data with duration and cleaned options", async () => { + const user = userEvent.setup(); + const onSubmit = vi.fn(); + const onClose = vi.fn(); + render(); + + await user.type(screen.getByLabelText(/Poll Question \/ Prompt/i), "Which framework?"); + const optionInputs = screen.getAllByPlaceholderText(/Option/i); + await user.type(optionInputs[0]!, "React"); + await user.type(optionInputs[1]!, "Vue"); + + await user.click(screen.getByRole("button", { name: "30s" })); + + await user.click(screen.getByRole("button", { name: /Launch Poll/i })); + + expect(onSubmit).toHaveBeenCalledWith({ + question: "Which framework?", + options: ["React", "Vue"], + duration: 30, + }); + expect(onClose).toHaveBeenCalled(); + }); +}); + +describe("ActivePollOverlay", () => { + const samplePoll: Poll = { + id: "poll-1", + sessionId: "sess-1", + question: "Do you like this UI?", + status: "ACTIVE", + isRecorded: false, + totalVotes: 10, + createdAt: Date.now(), + options: [ + { id: "opt-1", text: "Love it", order: 0, voteCount: 7, percentage: 70 }, + { id: "opt-2", text: "Needs work", order: 1, voteCount: 3, percentage: 30 }, + ], + }; + + it("shows voting buttons for participant who hasn't voted yet", async () => { + const onVote = vi.fn(); + render( + + ); + + expect(screen.getByText("Do you like this UI?")).toBeInTheDocument(); + expect(screen.getByText("Tap an option above to submit your vote!")).toBeInTheDocument(); + + const voteButtons = screen.getAllByRole("button", { name: /Love it|Needs work/i }); + fireEvent.click(voteButtons[0]!); + expect(onVote).toHaveBeenCalledWith("opt-1"); + }); + + it("displays live percentage results when participant has voted", () => { + const votedPoll: Poll = { + ...samplePoll, + votedOptionId: "opt-1", + }; + + render( + + ); + + expect(screen.getByText("70%")).toBeInTheDocument(); + expect(screen.getByText("30%")).toBeInTheDocument(); + expect(screen.getByText(/Your Vote/i)).toBeInTheDocument(); + }); + + it("provides organizer controls to End, Record, and Dismiss poll", async () => { + const user = userEvent.setup(); + const onEndPoll = vi.fn(); + const onRecordPoll = vi.fn(); + const onDismissPoll = vi.fn(); + + render( + + ); + + const endBtn = screen.getByRole("button", { name: /End Poll/i }); + await user.click(endBtn); + expect(onEndPoll).toHaveBeenCalled(); + + const recordBtn = screen.getByRole("button", { name: /Record Result/i }); + await user.click(recordBtn); + expect(onRecordPoll).toHaveBeenCalled(); + + const dismissBtn = screen.getByRole("button", { name: /Close & Dismiss/i }); + await user.click(dismissBtn); + expect(onDismissPoll).toHaveBeenCalled(); + }); + + it("shows Recorded badge when poll is already recorded", () => { + const recordedPoll: Poll = { + ...samplePoll, + isRecorded: true, + recordedAt: Date.now(), + }; + + render( + + ); + + expect(screen.getByText(/Recorded/i)).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: /Record Result/i })).not.toBeInTheDocument(); + }); +}); + +describe("RecordedPollsModal", () => { + it("shows empty state when no polls recorded", () => { + render(); + expect(screen.getByText(/No polls recorded yet/i)).toBeInTheDocument(); + }); + + it("renders list of recorded polls with breakdowns", () => { + const polls: Poll[] = [ + { + id: "poll-1", + sessionId: "sess-1", + question: "How was question 1?", + status: "ENDED", + isRecorded: true, + totalVotes: 15, + createdAt: Date.now(), + recordedAt: Date.now(), + questionIndex: 0, + options: [ + { id: "o1", text: "Easy", order: 0, voteCount: 10, percentage: 67 }, + { id: "o2", text: "Hard", order: 1, voteCount: 5, percentage: 33 }, + ], + }, + ]; + + render(); + expect(screen.getByText("How was question 1?")).toBeInTheDocument(); + expect(screen.getByText("15 votes")).toBeInTheDocument(); + expect(screen.getByText("67%")).toBeInTheDocument(); + expect(screen.getByText("33%")).toBeInTheDocument(); + expect(screen.getByText("Q#1")).toBeInTheDocument(); + }); +}); diff --git a/apps/frontend/src/components/poll/RecordedPollsModal.tsx b/apps/frontend/src/components/poll/RecordedPollsModal.tsx new file mode 100644 index 0000000..aa76eb2 --- /dev/null +++ b/apps/frontend/src/components/poll/RecordedPollsModal.tsx @@ -0,0 +1,168 @@ +import { BiPoll, BiX } from "react-icons/bi"; +import { LuClock, LuUsers } from "react-icons/lu"; +import type { Poll } from "./types"; + +interface RecordedPollsModalProps { + isOpen: boolean; + onClose: () => void; + polls: Poll[]; +} + +export default function RecordedPollsModal({ + isOpen, + onClose, + polls, +}: RecordedPollsModalProps) { + if (!isOpen) return null; + + return ( +
+
+ {/* Top ambient glow */} +
+ + {/* Header */} +
+
+
+ +
+
+

+ Recorded Polls +

+

+ {polls.length} {polls.length === 1 ? "poll recorded" : "polls recorded"} this session +

+
+
+ +
+ + {/* Content */} + {polls.length === 0 ? ( +
+ +

+ No polls recorded yet +

+

+ Create a poll during any question and click "Record Result" to save its outcome here permanently. +

+
+ ) : ( +
+ {polls.map((poll, idx) => { + const maxVotes = Math.max(...poll.options.map((o) => o.voteCount), 0); + const formattedDate = poll.recordedAt || poll.createdAt + ? new Date(poll.recordedAt || poll.createdAt).toLocaleTimeString([], { + hour: "2-digit", + minute: "2-digit", + }) + : null; + + return ( +
+
+
+
+ + Poll #{polls.length - idx} + + {typeof poll.questionIndex === "number" && ( + + Q#{poll.questionIndex + 1} + + )} + {formattedDate && ( + + {formattedDate} + + )} +
+

+ {poll.question} +

+
+ +
+ + {poll.totalVotes} votes +
+
+ + {/* Options breakdown */} +
+ {poll.options.map((opt) => { + const isLeader = maxVotes > 0 && opt.voteCount === maxVotes; + return ( +
+
+ +
+ + {opt.text} + +
+ + {opt.voteCount} + + + {opt.percentage}% + +
+
+
+ ); + })} +
+
+ ); + })} +
+ )} + +
+ +
+
+
+ ); +} diff --git a/apps/frontend/src/components/poll/types.ts b/apps/frontend/src/components/poll/types.ts new file mode 100644 index 0000000..23ecd75 --- /dev/null +++ b/apps/frontend/src/components/poll/types.ts @@ -0,0 +1,30 @@ +export interface PollOption { + id: string; + text: string; + order: number; + voteCount: number; + percentage: number; +} + +export interface Poll { + id: string; + sessionId: string; + question: string; + questionIndex?: number | null; + status: 'ACTIVE' | 'ENDED'; + isRecorded: boolean; + totalVotes: number; + createdAt: number; + endedAt?: number | null; + recordedAt?: number | null; + duration?: number | null; + options: PollOption[]; + votedOptionId?: string | null; +} + +export interface PollPreset { + label: string; + icon: string; + question: string; + options: string[]; +} diff --git a/apps/frontend/src/screens/LiveQuiz.test.tsx b/apps/frontend/src/screens/LiveQuiz.test.tsx index 84da45d..be137ee 100644 --- a/apps/frontend/src/screens/LiveQuiz.test.tsx +++ b/apps/frontend/src/screens/LiveQuiz.test.tsx @@ -272,3 +272,135 @@ describe('LiveQuiz final leaderboard', () => { expect(player.closest('div[class*="ring-2"]')).not.toBeNull(); }); }); + +describe('LiveQuiz polling integration', () => { + it('shows Create Poll button for organizer and not for participant', async () => { + const view = renderLive('/live/session-1', true); + await firstJoinMessage(); + expect(screen.getByRole('button', { name: /Create Poll/i })).toBeInTheDocument(); + view.unmount(); + + // Switch to participant + localStorage.setItem('rexial:participant:session-2', 'participant-1'); + renderLive('/live/session-2', false); + await waitFor(() => expect(sockets[1]?.sent.length).toBeGreaterThan(0)); + expect(screen.queryByRole('button', { name: /Create Poll/i })).not.toBeInTheDocument(); + }); + + it('organizer can open modal and launch poll', async () => { + const user = userEvent.setup(); + renderLive('/live/session-1', true); + await firstJoinMessage(); + + await user.click(screen.getByRole('button', { name: /Create Poll/i })); + expect(screen.getByRole('dialog')).toBeInTheDocument(); + + await user.type(screen.getByLabelText(/Poll Question \/ Prompt/i), 'Enjoying the quiz?'); + const optionInputs = screen.getAllByPlaceholderText(/Option/i); + await user.type(optionInputs[0]!, 'Yes'); + await user.type(optionInputs[1]!, 'No'); + + await user.click(screen.getByRole('button', { name: /Launch Poll/i })); + + const pollCreateMessages = sentOfType('poll:create'); + expect(pollCreateMessages).toHaveLength(1); + expect(pollCreateMessages[0]!.payload).toMatchObject({ + sessionId: 'session-1', + question: 'Enjoying the quiz?', + options: ['Yes', 'No'], + }); + }); + + it('renders active poll and allows participant to vote', async () => { + const user = userEvent.setup(); + localStorage.setItem('rexial:participant:session-1', 'participant-1'); + renderLive('/live/session-1', false); + await firstJoinMessage(); + + deliver('poll:started', { + poll: { + id: 'poll-100', + sessionId: 'session-1', + question: 'Live mid-question poll?', + status: 'ACTIVE', + isRecorded: false, + totalVotes: 0, + createdAt: Date.now(), + options: [ + { id: 'opt-yes', text: 'Yes definitely', order: 0, voteCount: 0, percentage: 0 }, + { id: 'opt-no', text: 'No', order: 1, voteCount: 0, percentage: 0 }, + ], + }, + }); + + expect(await screen.findByText('Live mid-question poll?')).toBeInTheDocument(); + const voteBtn = screen.getByRole('button', { name: /Yes definitely/i }); + await user.click(voteBtn); + + const voteMessages = sentOfType('poll:vote'); + expect(voteMessages).toHaveLength(1); + expect(voteMessages[0]!.payload).toMatchObject({ + sessionId: 'session-1', + pollId: 'poll-100', + optionId: 'opt-yes', + participantId: 'participant-1', + }); + }); + + it('organizer can record the poll result at the moment', async () => { + const user = userEvent.setup(); + renderLive('/live/session-1', true); + await firstJoinMessage(); + + deliver('poll:started', { + poll: { + id: 'poll-200', + sessionId: 'session-1', + question: 'Rate this question difficulty', + status: 'ACTIVE', + isRecorded: false, + totalVotes: 5, + createdAt: Date.now(), + options: [ + { id: 'opt-easy', text: 'Easy', order: 0, voteCount: 4, percentage: 80 }, + { id: 'opt-hard', text: 'Hard', order: 1, voteCount: 1, percentage: 20 }, + ], + }, + }); + + expect(await screen.findByText('Rate this question difficulty')).toBeInTheDocument(); + const recordBtn = screen.getByRole('button', { name: /Record Result/i }); + await user.click(recordBtn); + + const recordMessages = sentOfType('poll:record'); + expect(recordMessages).toHaveLength(1); + expect(recordMessages[0]!.payload).toMatchObject({ + sessionId: 'session-1', + pollId: 'poll-200', + }); + + deliver('poll:recorded', { + pollId: 'poll-200', + recordedAt: Date.now(), + poll: { + id: 'poll-200', + sessionId: 'session-1', + question: 'Rate this question difficulty', + status: 'ACTIVE', + isRecorded: true, + recordedAt: Date.now(), + totalVotes: 5, + createdAt: Date.now(), + options: [ + { id: 'opt-easy', text: 'Easy', order: 0, voteCount: 4, percentage: 80 }, + { id: 'opt-hard', text: 'Hard', order: 1, voteCount: 1, percentage: 20 }, + ], + }, + }); + + expect(await screen.findByText(/Poll result recorded successfully!/i)).toBeInTheDocument(); + expect(screen.getByText(/^Recorded/i)).toBeInTheDocument(); + }); +}); + + diff --git a/apps/frontend/src/screens/LiveQuiz.tsx b/apps/frontend/src/screens/LiveQuiz.tsx index 5abde77..94b9aaf 100644 --- a/apps/frontend/src/screens/LiveQuiz.tsx +++ b/apps/frontend/src/screens/LiveQuiz.tsx @@ -3,12 +3,16 @@ import { useAuthStore } from "../store/authStore"; import { lazy, Suspense, useEffect, useRef, useState } from "react"; import { LuUserSearch } from "react-icons/lu"; import { getAvatar, getAvatarColor } from "../utils/Avatars"; -import { BiCheckCircle, BiXCircle } from "react-icons/bi"; +import { BiCheckCircle, BiPoll, BiXCircle } from "react-icons/bi"; import BgBoss from "../components/BgBoss"; import { FaSpinner } from "react-icons/fa6"; -import { MdViewInAr } from "react-icons/md"; +import { MdHistory, MdViewInAr } from "react-icons/md"; import { participantTokenKey, streamingEnabled } from "../services/streamApi"; import { downloadLeaderboardCsv } from "../utils/leaderboardCsv"; +import CreatePollModal from "../components/poll/CreatePollModal"; +import ActivePollOverlay from "../components/poll/ActivePollOverlay"; +import RecordedPollsModal from "../components/poll/RecordedPollsModal"; +import type { Poll } from "../components/poll/types"; // The LiveKit client is most of a megabyte; only a live video quiz loads it. const LiveStage = lazy(() => import("../components/live/LiveStage")); @@ -69,6 +73,13 @@ function LiveQuiz({ isOrganizer = false }: LiveQuizProps) { const [liveVideo, setLiveVideo] = useState(false); const [startError, setStartError] = useState(''); + // Live polling state + const [activePoll, setActivePoll] = useState(null); + const [showCreatePoll, setShowCreatePoll] = useState(false); + const [showRecordedPolls, setShowRecordedPolls] = useState(false); + const [recordedPolls, setRecordedPolls] = useState([]); + const [pollNotice, setPollNotice] = useState(null); + // How many in the room have answered the question in flight. Reset on each @@ -332,6 +343,9 @@ function LiveQuiz({ isOrganizer = false }: LiveQuizProps) { if (typeof payload.questionIndex === 'number') { setQIndex(payload.questionIndex); } + if (payload.activePoll) { + setActivePoll(payload.activePoll); + } setGameState(payload.expired ? GameState.RESULTS : GameState.QUESTION); break; case 'quiz:timer-tick': @@ -383,6 +397,42 @@ function LiveQuiz({ isOrganizer = false }: LiveQuizProps) { case 'quiz:ended': setGameState(GameState.ENDED); break; + case 'poll:snapshot': + case 'poll:started': + setActivePoll(payload.poll); + break; + case 'poll:updated': + setActivePoll((prev) => (prev ? { ...prev, ...payload.poll } : payload.poll)); + break; + case 'poll:voted': + setActivePoll((prev) => (prev ? { ...prev, votedOptionId: payload.optionId } : prev)); + break; + case 'poll:ended': + setActivePoll((prev) => (prev ? { ...prev, ...payload.poll, status: 'ENDED' } : payload.poll)); + break; + case 'poll:recorded': + setActivePoll((prev) => + prev && prev.id === payload.pollId + ? { ...prev, isRecorded: true, recordedAt: payload.recordedAt } + : prev + ); + if (payload.poll) { + setRecordedPolls((prev) => { + if (prev.some((p) => p.id === payload.pollId)) { + return prev.map((p) => (p.id === payload.pollId ? payload.poll : p)); + } + return [payload.poll, ...prev]; + }); + } + setPollNotice("Poll result recorded successfully!"); + setTimeout(() => setPollNotice(null), 3500); + break; + case 'poll:dismissed': + setActivePoll(null); + break; + case 'poll:recorded-list': + setRecordedPolls(payload.polls || []); + break; } }; @@ -444,6 +494,80 @@ function LiveQuiz({ isOrganizer = false }: LiveQuizProps) { sendMessage({ type: 'quiz:start', payload: { sessionId } }); }; + const handleCreatePoll = (data: { question: string; options: string[]; duration?: number }) => { + sendMessage({ + type: 'poll:create', + payload: { + sessionId, + question: data.question, + options: data.options, + duration: data.duration, + questionIndex: qIndex, + token: isOrganizer ? token : undefined, + }, + }); + }; + + const handleVotePoll = (optionId: string) => { + if (!activePoll) return; + sendMessage({ + type: 'poll:vote', + payload: { + sessionId, + pollId: activePoll.id, + optionId, + participantId, + }, + }); + }; + + const handleEndPoll = () => { + if (!activePoll) return; + sendMessage({ + type: 'poll:end', + payload: { + sessionId, + pollId: activePoll.id, + token: isOrganizer ? token : undefined, + }, + }); + }; + + const handleRecordPoll = () => { + if (!activePoll) return; + sendMessage({ + type: 'poll:record', + payload: { + sessionId, + pollId: activePoll.id, + token: isOrganizer ? token : undefined, + }, + }); + }; + + const handleDismissPoll = () => { + if (!activePoll) return; + sendMessage({ + type: 'poll:dismiss', + payload: { + sessionId, + pollId: activePoll.id, + token: isOrganizer ? token : undefined, + }, + }); + }; + + const handleOpenRecordedPolls = () => { + setShowRecordedPolls(true); + sendMessage({ + type: 'poll:get-recorded', + payload: { + sessionId, + token: isOrganizer ? token : undefined, + }, + }); + }; + const handleNext = () => { const nextIdx = qIndex + 1; const sent = sendMessage({ @@ -1128,6 +1252,85 @@ function LiveQuiz({ isOrganizer = false }: LiveQuizProps) { /> )} + + {/* Organizer Live Poll Controls */} + {isOrganizer && gameState !== GameState.ENDED && ( +
+ + + +
+ )} + + {/* Toast Notice for Recorded Poll */} + {pollNotice && ( +
+ + {pollNotice} +
+ )} + + {/* Active Poll Overlay */} + {activePoll && ( + + )} + + {/* Create Poll Modal */} + {showCreatePoll && ( + setShowCreatePoll(false)} + onSubmit={handleCreatePoll} + currentQuestionText={currentQuestion?.text} + questionIndex={qIndex} + /> + )} + + {/* Recorded Polls History Modal */} + {showRecordedPolls && ( + setShowRecordedPolls(false)} + polls={recordedPolls} + /> + )} + {renderScreen()} ); diff --git a/apps/http-server/src/controllers/sessionController.test.ts b/apps/http-server/src/controllers/sessionController.test.ts index 1c62198..a1ce549 100644 --- a/apps/http-server/src/controllers/sessionController.test.ts +++ b/apps/http-server/src/controllers/sessionController.test.ts @@ -1,15 +1,22 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import type { Request, Response } from "express"; -const { findUnique, participantCreate, transaction } = vi.hoisted(() => ({ +const { findUnique, participantCreate, transaction, pollFindMany } = vi.hoisted(() => ({ findUnique: vi.fn(), participantCreate: vi.fn(), transaction: vi.fn(), + pollFindMany: vi.fn(), })); -vi.mock("@repo/db", () => ({ prisma: { quiz: { findUnique }, $transaction: transaction } })); +vi.mock("@repo/db", () => ({ + prisma: { + quiz: { findUnique }, + poll: { findMany: pollFindMany }, + $transaction: transaction, + }, +})); -import { joinQuizController } from "./sessionController"; +import { getSessionPollsController, joinQuizController } from "./sessionController"; const run = async (body: unknown) => { const req = { body } as unknown as Request; @@ -81,3 +88,49 @@ describe("joinQuizController", () => { expect(res.json).toHaveBeenCalledWith({ success: false, error: "Quiz not found" }); }); }); + +describe("getSessionPollsController", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("returns polls for the session", async () => { + const mockPolls = [ + { + id: "poll-1", + sessionId: "session-1", + question: "Do you like polls?", + totalVotes: 5, + options: [ + { id: "opt-1", text: "Yes", voteCount: 4, order: 0 }, + { id: "opt-2", text: "No", voteCount: 1, order: 1 }, + ], + }, + ]; + pollFindMany.mockResolvedValue(mockPolls); + + const req = { params: { sessionId: "session-1" } } as unknown as Request; + const res = { status: vi.fn().mockReturnThis(), json: vi.fn() } as unknown as Response; + + await getSessionPollsController(req, res); + + expect(res.status).toHaveBeenCalledWith(200); + expect(res.json).toHaveBeenCalledWith({ polls: mockPolls }); + expect(pollFindMany).toHaveBeenCalledWith({ + where: { sessionId: "session-1" }, + include: { options: { orderBy: { order: "asc" } } }, + orderBy: { createdAt: "desc" }, + }); + }); + + it("returns 400 when sessionId is missing", async () => { + const req = { params: {} } as unknown as Request; + const res = { status: vi.fn().mockReturnThis(), json: vi.fn() } as unknown as Response; + + await getSessionPollsController(req, res); + + expect(res.status).toHaveBeenCalledWith(400); + expect(res.json).toHaveBeenCalledWith({ success: false, error: "Session ID is required" }); + }); +}); + diff --git a/apps/http-server/src/controllers/sessionController.ts b/apps/http-server/src/controllers/sessionController.ts index 558af57..7d9bf5c 100644 --- a/apps/http-server/src/controllers/sessionController.ts +++ b/apps/http-server/src/controllers/sessionController.ts @@ -146,4 +146,29 @@ export const getLeaderboardController = async (req: Request, res: Response) => { console.log("error while getting dashboard", error) return errorResponse(res, 500, 'Internal server error'); } -} \ No newline at end of file +} + +// logic for getting recorded polls for a quiz session +export const getSessionPollsController = async (req: Request, res: Response) => { + try { + const sessionId = req.params.sessionId; + if (!sessionId) { + return errorResponse(res, 400, "Session ID is required"); + } + + const polls = await prisma.poll.findMany({ + where: { sessionId: String(sessionId) }, + include: { + options: { + orderBy: { order: 'asc' }, + }, + }, + orderBy: { createdAt: 'desc' }, + }); + + return res.status(200).json({ polls }); + } catch (error) { + console.log("error while getting session polls", error); + return errorResponse(res, 500, 'Internal server error'); + } +}; diff --git a/apps/http-server/src/routes/session.ts b/apps/http-server/src/routes/session.ts index 7634512..ea570f4 100644 --- a/apps/http-server/src/routes/session.ts +++ b/apps/http-server/src/routes/session.ts @@ -1,5 +1,5 @@ import { Router } from "express"; -import { getLeaderboardController, joinQuizController } from "../controllers/sessionController"; +import { getLeaderboardController, getSessionPollsController, joinQuizController } from "../controllers/sessionController"; import { optionalAuthMiddleware } from "../middlewares/authmiddleware"; const router = Router(); @@ -13,6 +13,10 @@ router.post("/join", optionalAuthMiddleware, joinQuizController) // get leaderboard router.get('/:sessionId/leaderboard', getLeaderboardController); +// get session polls +router.get('/:sessionId/polls', getSessionPollsController); + + diff --git a/apps/ws-server/src/redis.ts b/apps/ws-server/src/redis.ts index ec32879..25f584a 100644 --- a/apps/ws-server/src/redis.ts +++ b/apps/ws-server/src/redis.ts @@ -1,4 +1,5 @@ -import {Redis} from 'ioredis'; +import 'dotenv/config'; +import { Redis } from 'ioredis'; const redisConfig = { host: process.env.REDIS_HOST || 'redis', diff --git a/apps/ws-server/src/utils/handleMessages.poll.test.ts b/apps/ws-server/src/utils/handleMessages.poll.test.ts new file mode 100644 index 0000000..459cba2 --- /dev/null +++ b/apps/ws-server/src/utils/handleMessages.poll.test.ts @@ -0,0 +1,406 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import jwt from "jsonwebtoken"; +import WebSocket from "ws"; + +const mocks = vi.hoisted(() => ({ + prisma: { + quizOrganizer: { findFirst: vi.fn() }, + quizSession: { updateMany: vi.fn(), update: vi.fn() }, + participant: { findUnique: vi.fn() }, + poll: { upsert: vi.fn(), create: vi.fn(), findMany: vi.fn() }, + }, + broadcastToSession: vi.fn(), + getCachedSession: vi.fn(), + getCachedParticipants: vi.fn(), + getCachedQuestions: vi.fn(), + getCachedLeaderboard: vi.fn(), + appendCachedParticipant: vi.fn(), + invalidateSession: vi.fn(), + invalidateLeaderboard: vi.fn(), + clearSessionCache: vi.fn(), + drainSession: vi.fn(), + endQuizSession: vi.fn(), + startQuestionTimer: vi.fn(), + closeQuestionWindow: vi.fn(), +})); + +vi.mock("@repo/db", () => ({ prisma: mocks.prisma })); +vi.mock("../redis.js", () => ({ cache: {} })); +vi.mock("./broadcastTosession.js", () => ({ broadcastToSession: mocks.broadcastToSession })); +vi.mock("./endQuizSession.js", () => ({ endQuizSession: mocks.endQuizSession })); +vi.mock("./leaderboard.js", () => ({ getLeaderboard: vi.fn() })); +vi.mock("./cache.js", () => ({ + getCachedSession: mocks.getCachedSession, + getCachedQuestions: mocks.getCachedQuestions, + getCachedParticipants: mocks.getCachedParticipants, + getCachedLeaderboard: mocks.getCachedLeaderboard, + invalidateParticipants: vi.fn(), + appendCachedParticipant: mocks.appendCachedParticipant, + invalidateLeaderboard: mocks.invalidateLeaderboard, + invalidateSession: mocks.invalidateSession, + clearSessionCache: mocks.clearSessionCache, +})); +vi.mock("./timeManager.js", () => ({ + startQuestionTimer: mocks.startQuestionTimer, + timerDeadlineKey: (id: string) => `deadline:${id}`, + currentQuestionKey: (id: string) => `current:${id}`, + closeQuestionWindow: mocks.closeQuestionWindow, + finishQuestionEarly: vi.fn(), +})); +vi.mock("./answerQueue.js", () => ({ + enqueueAnswer: vi.fn(), + countAnswered: vi.fn(), + drainSession: mocks.drainSession, +})); + +import { handleMessage } from "./handleMessages.js"; +import { clearSessionPolls } from "./pollManager.js"; +import type { Client } from "../index.js"; + +const SECRET = "test-secret"; +const hostToken = () => jwt.sign({ userId: "host-1" }, SECRET); + +let nextSession = 0; +let sessionId: string; + +function makeClient(overrides: Partial = {}): Client { + return { + ws: { readyState: WebSocket.OPEN, send: vi.fn(), terminate: vi.fn() } as unknown as WebSocket, + sessionId: "", + role: "PARTICIPANT", + isAlive: true, + ...overrides, + }; +} + +function sent(client: Client) { + return (client.ws.send as ReturnType).mock.calls.map(([raw]) => JSON.parse(raw)); +} + +function broadcasts() { + return mocks.broadcastToSession.mock.calls.map(([sid, type, payload]) => ({ sid, type, payload })); +} + +async function joinedHost(): Promise { + mocks.prisma.quizOrganizer.findFirst.mockResolvedValue({ id: "org-1" }); + const host = makeClient(); + await handleMessage(host, { + type: "join", + payload: { sessionId, role: "ORGANIZER", token: hostToken() }, + }); + mocks.prisma.quizOrganizer.findFirst.mockClear(); + (host.ws.send as ReturnType).mockClear(); + return host; +} + +async function joinedParticipant(participantId = "p-1"): Promise { + mocks.prisma.participant.findUnique.mockResolvedValue({ id: participantId, username: "Player" }); + const p = makeClient({ participantId }); + await handleMessage(p, { + type: "join", + payload: { sessionId, role: "PARTICIPANT", participantId }, + }); + mocks.prisma.participant.findUnique.mockClear(); + (p.ws.send as ReturnType).mockClear(); + return p; +} + +describe("Live polling feature", () => { + beforeEach(() => { + vi.clearAllMocks(); + sessionId = `sess-poll-${++nextSession}`; + clearSessionPolls(sessionId); + process.env.JWT_SECRET = SECRET; + }); + + it("allows organizer to create a poll and broadcasts poll:started", async () => { + const host = await joinedHost(); + + await handleMessage(host, { + type: "poll:create", + payload: { + sessionId, + token: hostToken(), + question: "Is this question too hard?", + options: ["Yes, very", "Just right", "Too easy"], + questionIndex: 2, + }, + }); + + const startEvents = broadcasts().filter(b => b.type === "poll:started"); + expect(startEvents.length).toBe(1); + expect(startEvents[0]?.payload.poll).toMatchObject({ + question: "Is this question too hard?", + status: "ACTIVE", + totalVotes: 0, + questionIndex: 2, + }); + expect(startEvents[0]?.payload.poll.options).toHaveLength(3); + expect(startEvents[0]?.payload.poll.options[0].text).toBe("Yes, very"); + }); + + it("rejects poll:create from a regular participant", async () => { + const p = await joinedParticipant(); + + await handleMessage(p, { + type: "poll:create", + payload: { + sessionId, + question: "Unauthorized poll", + options: ["A", "B"], + }, + }); + + const startEvents = broadcasts().filter(b => b.type === "poll:started"); + expect(startEvents.length).toBe(0); + const errors = sent(p).filter(m => m.type === "error"); + expect(errors.length).toBeGreaterThan(0); + }); + + it("rejects poll with empty question or fewer than 2 options", async () => { + const host = await joinedHost(); + + await handleMessage(host, { + type: "poll:create", + payload: { + sessionId, + token: hostToken(), + question: "", + options: ["Option 1"], + }, + }); + + const startEvents = broadcasts().filter(b => b.type === "poll:started"); + expect(startEvents.length).toBe(0); + const errors = sent(host).filter(m => m.type === "error"); + expect(errors[0]?.payload.code).toBe("INVALID_POLL"); + }); + + it("allows participant to vote and updates percentages in real-time", async () => { + const host = await joinedHost(); + const p1 = await joinedParticipant("p-1"); + const p2 = await joinedParticipant("p-2"); + + await handleMessage(host, { + type: "poll:create", + payload: { + sessionId, + token: hostToken(), + question: "Vote?", + options: ["Option A", "Option B"], + }, + }); + + const pollStarted = broadcasts().find(b => b.type === "poll:started")?.payload.poll; + const optA = pollStarted.options[0].id; + const optB = pollStarted.options[1].id; + + // p1 votes for A + await handleMessage(p1, { + type: "poll:vote", + payload: { + sessionId, + pollId: pollStarted.id, + optionId: optA, + participantId: "p-1", + }, + }); + + const updateEvents1 = broadcasts().filter(b => b.type === "poll:updated"); + expect(updateEvents1.length).toBe(1); + const poll1 = updateEvents1[0]?.payload.poll; + expect(poll1.totalVotes).toBe(1); + expect(poll1.options.find((o: any) => o.id === optA).voteCount).toBe(1); + expect(poll1.options.find((o: any) => o.id === optA).percentage).toBe(100); + + // p2 votes for B + await handleMessage(p2, { + type: "poll:vote", + payload: { + sessionId, + pollId: pollStarted.id, + optionId: optB, + participantId: "p-2", + }, + }); + + const updateEvents2 = broadcasts().filter(b => b.type === "poll:updated"); + expect(updateEvents2.length).toBe(2); + const poll2 = updateEvents2[1]?.payload.poll; + expect(poll2.totalVotes).toBe(2); + expect(poll2.options.find((o: any) => o.id === optA).percentage).toBe(50); + expect(poll2.options.find((o: any) => o.id === optB).percentage).toBe(50); + }); + + it("prevents double voting from the same participant", async () => { + const host = await joinedHost(); + const p1 = await joinedParticipant("p-1"); + + await handleMessage(host, { + type: "poll:create", + payload: { + sessionId, + token: hostToken(), + question: "Vote?", + options: ["Option A", "Option B"], + }, + }); + + const pollStarted = broadcasts().find(b => b.type === "poll:started")?.payload.poll; + const optA = pollStarted.options[0].id; + const optB = pollStarted.options[1].id; + + // First vote succeeds + await handleMessage(p1, { + type: "poll:vote", + payload: { + sessionId, + pollId: pollStarted.id, + optionId: optA, + participantId: "p-1", + }, + }); + + // Second vote should fail + await handleMessage(p1, { + type: "poll:vote", + payload: { + sessionId, + pollId: pollStarted.id, + optionId: optB, + participantId: "p-1", + }, + }); + + const errors = sent(p1).filter(m => m.type === "error"); + expect(errors[0]?.payload.code).toBe("ALREADY_VOTED"); + }); + + it("allows organizer to end the poll and locks results", async () => { + const host = await joinedHost(); + const p1 = await joinedParticipant("p-1"); + + await handleMessage(host, { + type: "poll:create", + payload: { + sessionId, + token: hostToken(), + question: "Vote?", + options: ["A", "B"], + }, + }); + + const pollStarted = broadcasts().find(b => b.type === "poll:started")?.payload.poll; + + await handleMessage(host, { + type: "poll:end", + payload: { + sessionId, + token: hostToken(), + pollId: pollStarted.id, + }, + }); + + const endEvents = broadcasts().filter(b => b.type === "poll:ended"); + expect(endEvents.length).toBe(1); + expect(endEvents[0]?.payload.poll.status).toBe("ENDED"); + + // Voting after end is rejected + await handleMessage(p1, { + type: "poll:vote", + payload: { + sessionId, + pollId: pollStarted.id, + optionId: pollStarted.options[0].id, + participantId: "p-1", + }, + }); + + const errors = sent(p1).filter(m => m.type === "error"); + expect(errors[0]?.payload.code).toBe("POLL_INACTIVE"); + }); + + it("allows organizer to record the poll result at the moment", async () => { + const host = await joinedHost(); + mocks.prisma.poll.upsert.mockResolvedValue({ id: "saved-1" }); + + await handleMessage(host, { + type: "poll:create", + payload: { + sessionId, + token: hostToken(), + question: "Important Poll", + options: ["Yes", "No"], + }, + }); + + const pollStarted = broadcasts().find(b => b.type === "poll:started")?.payload.poll; + + await handleMessage(host, { + type: "poll:record", + payload: { + sessionId, + token: hostToken(), + pollId: pollStarted.id, + }, + }); + + const recordEvents = broadcasts().filter(b => b.type === "poll:recorded"); + expect(recordEvents.length).toBe(1); + expect(recordEvents[0]?.payload.pollId).toBe(pollStarted.id); + expect(recordEvents[0]?.payload.poll.isRecorded).toBe(true); + expect(mocks.prisma.poll.upsert).toHaveBeenCalled(); + }); + + it("allows organizer to dismiss poll and get recorded polls", async () => { + const host = await joinedHost(); + mocks.prisma.poll.upsert.mockResolvedValue({ id: "saved-1" }); + + await handleMessage(host, { + type: "poll:create", + payload: { + sessionId, + token: hostToken(), + question: "Dismiss me later", + options: ["A", "B"], + }, + }); + + const pollStarted = broadcasts().find(b => b.type === "poll:started")?.payload.poll; + + // Record it + await handleMessage(host, { + type: "poll:record", + payload: { + sessionId, + token: hostToken(), + pollId: pollStarted.id, + }, + }); + + // Get recorded + await handleMessage(host, { + type: "poll:get-recorded", + payload: { + sessionId, + token: hostToken(), + }, + }); + + const listMessage = sent(host).find(m => m.type === "poll:recorded-list"); + expect(listMessage?.payload.polls.length).toBe(1); + + // Dismiss it + await handleMessage(host, { + type: "poll:dismiss", + payload: { + sessionId, + token: hostToken(), + pollId: pollStarted.id, + }, + }); + + const dismissEvents = broadcasts().filter(b => b.type === "poll:dismissed"); + expect(dismissEvents.length).toBe(1); + }); +}); diff --git a/apps/ws-server/src/utils/handleMessages.ts b/apps/ws-server/src/utils/handleMessages.ts index 0b21b3c..3fffa2e 100644 --- a/apps/ws-server/src/utils/handleMessages.ts +++ b/apps/ws-server/src/utils/handleMessages.ts @@ -31,6 +31,17 @@ import { isSessionOrganizer, sendError, } from "./organizerAuth.js"; +import { + createPoll, + votePoll, + endPoll, + recordPoll, + dismissPoll, + getActivePoll, + getRecordedPolls, + sanitizePoll, + clearSessionPolls, +} from "./pollManager.js"; /** @@ -162,6 +173,8 @@ async function sendQuizStateSnapshot(client: Client, sessionId: string) { })), }; + const activePoll = getActivePoll(sessionId); + if (client.ws.readyState !== WebSocket.OPEN) return; client.ws.send(JSON.stringify({ @@ -175,6 +188,7 @@ async function sendQuizStateSnapshot(client: Client, sessionId: string) { alreadyAnswered: !!existingAnswer, selectedAnswerId: existingAnswer?.answerId ?? null, expired: timeLeft <= 0, + activePoll: activePoll ? sanitizePoll(activePoll, client.participantId) : null, }, })); } @@ -603,13 +617,143 @@ export const handleMessage = async (client: Client, data: any) => { await endQuizSession(sessionId); await clearSessionCache(sessionId); + clearSessionPolls(sessionId); broadcastToSession(sessionId, 'quiz:leaderboard', { leaderboard }); broadcastToSession(sessionId, 'quiz:ended'); break; } + + case 'poll:create': { + const sessionId = authorizeOrganizerAction(client, payload); + if (!sessionId) break; + + const { question, options, questionIndex, duration } = payload; + if (!question || typeof question !== 'string' || question.trim().length === 0) { + sendError(client, 'INVALID_POLL', 'Poll question cannot be empty.'); + break; + } + if (!Array.isArray(options) || options.filter((o: unknown) => typeof o === 'string' && o.trim().length > 0).length < 2) { + sendError(client, 'INVALID_POLL', 'Poll must have at least two options.'); + break; + } + + const poll = createPoll( + sessionId, + question, + options, + questionIndex, + duration, + () => { + const expired = getActivePoll(sessionId); + if (expired) { + broadcastToSession(sessionId, 'poll:ended', { + poll: sanitizePoll(expired), + }); + } + } + ); + + broadcastToSession(sessionId, 'poll:started', { + poll: sanitizePoll(poll), + }); + break; + } + + case 'poll:vote': { + const { sessionId, pollId, optionId, participantId } = payload; + const voterId = client.participantId || participantId; + if (!voterId || !sessionId || !pollId || !optionId) break; + + const result = votePoll(sessionId, pollId, optionId, voterId); + if (!result.success || !result.poll) { + sendError(client, result.error || 'VOTE_FAILED', 'Could not record your vote.'); + break; + } + + broadcastToSession(sessionId, 'poll:updated', { + poll: sanitizePoll(result.poll), + }); + + if (client.ws.readyState === WebSocket.OPEN) { + client.ws.send(JSON.stringify({ + type: 'poll:voted', + payload: { + pollId, + optionId, + }, + })); + } + break; + } + + case 'poll:end': { + const sessionId = authorizeOrganizerAction(client, payload); + if (!sessionId) break; + + const { pollId } = payload; + if (!pollId) break; + + const poll = endPoll(sessionId, pollId); + if (!poll) break; + + broadcastToSession(sessionId, 'poll:ended', { + poll: sanitizePoll(poll), + }); + break; + } + + case 'poll:record': { + const sessionId = authorizeOrganizerAction(client, payload); + if (!sessionId) break; + + const { pollId } = payload; + if (!pollId) break; + + const result = await recordPoll(sessionId, pollId); + if (!result.success || !result.poll) { + sendError(client, result.error || 'RECORD_FAILED', 'Could not record poll result.'); + break; + } + + broadcastToSession(sessionId, 'poll:recorded', { + pollId, + recordedAt: result.poll.recordedAt, + poll: sanitizePoll(result.poll), + }); + break; + } + + case 'poll:dismiss': { + const sessionId = authorizeOrganizerAction(client, payload); + if (!sessionId) break; + + const { pollId } = payload; + if (!pollId) break; + + dismissPoll(sessionId, pollId); + broadcastToSession(sessionId, 'poll:dismissed', { pollId }); + break; + } + + case 'poll:get-recorded': { + const sessionId = authorizeOrganizerAction(client, payload); + if (!sessionId) break; + + const recorded = getRecordedPolls(sessionId); + if (client.ws.readyState === WebSocket.OPEN) { + client.ws.send(JSON.stringify({ + type: 'poll:recorded-list', + payload: { + polls: recorded.map(p => sanitizePoll(p)), + }, + })); + } + break; + } } } + diff --git a/apps/ws-server/src/utils/pollManager.ts b/apps/ws-server/src/utils/pollManager.ts new file mode 100644 index 0000000..e18e287 --- /dev/null +++ b/apps/ws-server/src/utils/pollManager.ts @@ -0,0 +1,262 @@ +import { randomUUID } from "crypto"; +import { prisma } from "@repo/db"; + +export interface PollOptionState { + id: string; + text: string; + order: number; + voteCount: number; + percentage: number; +} + +export interface ActivePoll { + id: string; + sessionId: string; + question: string; + questionIndex?: number | null | undefined; + status: 'ACTIVE' | 'ENDED'; + isRecorded: boolean; + totalVotes: number; + createdAt: number; + endedAt?: number | null | undefined; + recordedAt?: number | null | undefined; + duration?: number | null | undefined; + options: PollOptionState[]; + voters: Map; // participantId -> optionId +} + +// Active poll per session: at most one active poll per session at any time. +const activePolls = new Map(); + +// In-memory cache of recorded polls per session +const recordedPollsCache = new Map(); + +// Timers for polls with duration +const pollTimers = new Map(); + +export function getActivePoll(sessionId: string): ActivePoll | null { + return activePolls.get(sessionId) ?? null; +} + +export function sanitizePoll(poll: ActivePoll, participantId?: string) { + return { + id: poll.id, + sessionId: poll.sessionId, + question: poll.question, + questionIndex: poll.questionIndex, + status: poll.status, + isRecorded: poll.isRecorded, + totalVotes: poll.totalVotes, + createdAt: poll.createdAt, + endedAt: poll.endedAt ?? null, + recordedAt: poll.recordedAt ?? null, + duration: poll.duration ?? null, + options: poll.options.map(opt => ({ + id: opt.id, + text: opt.text, + order: opt.order, + voteCount: opt.voteCount, + percentage: opt.percentage, + })), + votedOptionId: participantId ? (poll.voters.get(participantId) ?? null) : null, + }; +} + +export function createPoll( + sessionId: string, + question: string, + options: string[], + questionIndex?: number, + duration?: number, + onExpire?: () => void, +): ActivePoll { + // Clear any existing active poll timer + const existingTimer = pollTimers.get(sessionId); + if (existingTimer) { + clearTimeout(existingTimer); + pollTimers.delete(sessionId); + } + + const pollId = randomUUID(); + const cleanOptions: PollOptionState[] = options + .filter(opt => opt && typeof opt === 'string' && opt.trim().length > 0) + .map((text, idx) => ({ + id: randomUUID(), + text: text.trim(), + order: idx, + voteCount: 0, + percentage: 0, + })); + + const poll: ActivePoll = { + id: pollId, + sessionId, + question: question.trim(), + questionIndex: typeof questionIndex === 'number' ? questionIndex : null, + status: 'ACTIVE', + isRecorded: false, + totalVotes: 0, + createdAt: Date.now(), + endedAt: null, + recordedAt: null, + duration: duration && duration > 0 ? duration : null, + options: cleanOptions, + voters: new Map(), + }; + + activePolls.set(sessionId, poll); + + if (duration && duration > 0) { + const timer = setTimeout(() => { + pollTimers.delete(sessionId); + endPoll(sessionId, poll.id); + if (onExpire) onExpire(); + }, duration * 1000); + pollTimers.set(sessionId, timer); + } + + return poll; +} + +export function votePoll( + sessionId: string, + pollId: string, + optionId: string, + participantId: string, +): { success: boolean; poll?: ActivePoll; error?: string } { + const poll = activePolls.get(sessionId); + if (!poll || poll.id !== pollId) { + return { success: false, error: 'POLL_NOT_FOUND' }; + } + if (poll.status !== 'ACTIVE') { + return { success: false, error: 'POLL_INACTIVE' }; + } + if (poll.voters.has(participantId)) { + return { success: false, error: 'ALREADY_VOTED' }; + } + const option = poll.options.find(o => o.id === optionId); + if (!option) { + return { success: false, error: 'INVALID_OPTION' }; + } + + poll.voters.set(participantId, optionId); + option.voteCount++; + poll.totalVotes++; + + // Recalculate percentage for all options + for (const opt of poll.options) { + opt.percentage = poll.totalVotes > 0 + ? Math.round((opt.voteCount / poll.totalVotes) * 100) + : 0; + } + + return { success: true, poll }; +} + +export function endPoll(sessionId: string, pollId: string): ActivePoll | null { + const poll = activePolls.get(sessionId); + if (!poll || poll.id !== pollId) return null; + + const timer = pollTimers.get(sessionId); + if (timer) { + clearTimeout(timer); + pollTimers.delete(sessionId); + } + + poll.status = 'ENDED'; + poll.endedAt = Date.now(); + return poll; +} + +export async function recordPoll(sessionId: string, pollId: string): Promise<{ success: boolean; poll?: ActivePoll; error?: string }> { + const poll = activePolls.get(sessionId); + if (!poll || poll.id !== pollId) { + return { success: false, error: 'POLL_NOT_FOUND' }; + } + + poll.isRecorded = true; + poll.recordedAt = Date.now(); + + // Cache in session's recorded polls list + const sessionRecorded = recordedPollsCache.get(sessionId) ?? []; + if (!sessionRecorded.some(p => p.id === poll.id)) { + sessionRecorded.push({ + ...poll, + voters: new Map(poll.voters), + options: poll.options.map(o => ({ ...o })), + }); + recordedPollsCache.set(sessionId, sessionRecorded); + } + + // Persist to Prisma DB + try { + await prisma.poll.upsert({ + where: { id: poll.id }, + update: { + isRecorded: true, + recordedAt: new Date(poll.recordedAt), + status: poll.status, + totalVotes: poll.totalVotes, + endedAt: poll.endedAt ? new Date(poll.endedAt) : null, + options: { + update: poll.options.map(opt => ({ + where: { id: opt.id }, + data: { voteCount: opt.voteCount }, + })), + }, + }, + create: { + id: poll.id, + sessionId: poll.sessionId, + question: poll.question, + questionIndex: poll.questionIndex ?? null, + status: poll.status, + isRecorded: true, + totalVotes: poll.totalVotes, + createdAt: new Date(poll.createdAt), + endedAt: poll.endedAt ? new Date(poll.endedAt) : null, + recordedAt: new Date(poll.recordedAt), + options: { + create: poll.options.map(opt => ({ + id: opt.id, + text: opt.text, + order: opt.order, + voteCount: opt.voteCount, + })), + }, + }, + }); + } catch (err) { + console.error(`[pollManager] Failed to persist poll ${poll.id} to DB:`, err); + } + + return { success: true, poll }; +} + +export function dismissPoll(sessionId: string, pollId: string): boolean { + const poll = activePolls.get(sessionId); + if (!poll || poll.id !== pollId) return false; + + const timer = pollTimers.get(sessionId); + if (timer) { + clearTimeout(timer); + pollTimers.delete(sessionId); + } + + activePolls.delete(sessionId); + return true; +} + +export function getRecordedPolls(sessionId: string): ActivePoll[] { + return recordedPollsCache.get(sessionId) ?? []; +} + +export function clearSessionPolls(sessionId: string) { + const timer = pollTimers.get(sessionId); + if (timer) { + clearTimeout(timer); + pollTimers.delete(sessionId); + } + activePolls.delete(sessionId); + recordedPollsCache.delete(sessionId); +} diff --git a/packages/db/.gitignore b/packages/db/.gitignore index 2a62a19..f57a885 100644 --- a/packages/db/.gitignore +++ b/packages/db/.gitignore @@ -7,3 +7,4 @@ tsconfig.tsbuildinfo /src/generated/prisma +/.generated_nobody_backup diff --git a/packages/db/prisma/migrations/20261123180000_add_poll_tables/migration.sql b/packages/db/prisma/migrations/20261123180000_add_poll_tables/migration.sql new file mode 100644 index 0000000..d60a9f9 --- /dev/null +++ b/packages/db/prisma/migrations/20261123180000_add_poll_tables/migration.sql @@ -0,0 +1,61 @@ +-- CreateTable +CREATE TABLE "Poll" ( + "id" TEXT NOT NULL, + "question" TEXT NOT NULL, + "questionIndex" INTEGER, + "status" TEXT NOT NULL DEFAULT 'ACTIVE', + "isRecorded" BOOLEAN NOT NULL DEFAULT false, + "totalVotes" INTEGER NOT NULL DEFAULT 0, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "endedAt" TIMESTAMP(3), + "recordedAt" TIMESTAMP(3), + "sessionId" TEXT NOT NULL, + + CONSTRAINT "Poll_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "PollOption" ( + "id" TEXT NOT NULL, + "text" TEXT NOT NULL, + "order" INTEGER NOT NULL DEFAULT 0, + "voteCount" INTEGER NOT NULL DEFAULT 0, + "pollId" TEXT NOT NULL, + + CONSTRAINT "PollOption_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "PollVote" ( + "id" TEXT NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "pollId" TEXT NOT NULL, + "optionId" TEXT NOT NULL, + "participantId" TEXT NOT NULL, + + CONSTRAINT "PollVote_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "Poll_sessionId_idx" ON "Poll"("sessionId"); + +-- CreateIndex +CREATE INDEX "PollOption_pollId_idx" ON "PollOption"("pollId"); + +-- CreateIndex +CREATE INDEX "PollVote_pollId_idx" ON "PollVote"("pollId"); + +-- CreateIndex +CREATE UNIQUE INDEX "PollVote_pollId_participantId_key" ON "PollVote"("pollId", "participantId"); + +-- AddForeignKey +ALTER TABLE "Poll" ADD CONSTRAINT "Poll_sessionId_fkey" FOREIGN KEY ("sessionId") REFERENCES "QuizSession"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "PollOption" ADD CONSTRAINT "PollOption_pollId_fkey" FOREIGN KEY ("pollId") REFERENCES "Poll"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "PollVote" ADD CONSTRAINT "PollVote_pollId_fkey" FOREIGN KEY ("pollId") REFERENCES "Poll"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "PollVote" ADD CONSTRAINT "PollVote_optionId_fkey" FOREIGN KEY ("optionId") REFERENCES "PollOption"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma index e3bf52a..48aafed 100644 --- a/packages/db/prisma/schema.prisma +++ b/packages/db/prisma/schema.prisma @@ -128,6 +128,7 @@ model QuizSession { quiz Quiz @relation(fields: [quizId], references: [id], onDelete: Cascade) participants Participant[] + polls Poll[] } model Participant { @@ -185,3 +186,54 @@ model ApiRequestLog { @@index([createdAt]) @@index([userId]) } + +model Poll { + id String @id @default(uuid()) + question String + questionIndex Int? + status String @default("ACTIVE") + isRecorded Boolean @default(false) + totalVotes Int @default(0) + createdAt DateTime @default(now()) + endedAt DateTime? + recordedAt DateTime? + + sessionId String + session QuizSession @relation(fields: [sessionId], references: [id], onDelete: Cascade) + + options PollOption[] + votes PollVote[] + + @@index([sessionId]) +} + +model PollOption { + id String @id @default(uuid()) + text String + order Int @default(0) + voteCount Int @default(0) + + pollId String + poll Poll @relation(fields: [pollId], references: [id], onDelete: Cascade) + + votes PollVote[] + + @@index([pollId]) +} + +model PollVote { + id String @id @default(uuid()) + createdAt DateTime @default(now()) + + pollId String + poll Poll @relation(fields: [pollId], references: [id], onDelete: Cascade) + + optionId String + option PollOption @relation(fields: [optionId], references: [id], onDelete: Cascade) + + participantId String + + @@unique([pollId, participantId]) + @@index([pollId]) +} +