Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions frontend/src/Pages/DebateRoom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -860,6 +860,7 @@ const DebateRoom: React.FC = () => {
botStance={state.botStance}
botDesc={bot.desc}
topic={debateData?.topic}
messages={state.messages}
onClose={() => {
setJudgmentData(null);
navigate("/startDebate");
Expand Down
87 changes: 57 additions & 30 deletions frontend/src/Pages/OnlineDebateRoom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -702,6 +702,38 @@ const OnlineDebateRoom = (): JSX.Element => {
[isRoomOwner, setPopup, setRatingSummary, startJudgmentPolling]
);

const gatherTranscriptsForRole = useCallback(
(role: DebateRole) => {
const rolePhases =
role === "for"
? [
DebatePhase.OpeningFor,
DebatePhase.CrossForQuestion,
DebatePhase.CrossForAnswer,
DebatePhase.ClosingFor,
]
: [
DebatePhase.OpeningAgainst,
DebatePhase.CrossAgainstAnswer,
DebatePhase.CrossAgainstQuestion,
DebatePhase.ClosingAgainst,
];

return rolePhases.reduce((acc, phase) => {
const storageKey = `${roomId}_${phase}_${role}`;
const stored = storageKey ? localStorage.getItem(storageKey) : null;
const fromState = speechTranscripts[phase] ?? "";
const combined =
(typeof fromState === "string" && fromState.trim().length > 0
? fromState
: stored || "") || "";
acc[phase] = combined.trim().length > 0 ? combined : "No response";
return acc;
}, {} as { [key in DebatePhase]?: string });
},
[roomId, speechTranscripts]
);

// Log message history, collect transcripts, and send to backend
const logMessageHistory = useCallback(async () => {
if (submissionStartedRef.current) {
Expand Down Expand Up @@ -730,35 +762,6 @@ const OnlineDebateRoom = (): JSX.Element => {

submissionStartedRef.current = true;

const gatherTranscriptsForRole = (role: DebateRole) => {
const rolePhases =
role === "for"
? [
DebatePhase.OpeningFor,
DebatePhase.CrossForQuestion,
DebatePhase.CrossForAnswer,
DebatePhase.ClosingFor,
]
: [
DebatePhase.OpeningAgainst,
DebatePhase.CrossAgainstAnswer,
DebatePhase.CrossAgainstQuestion,
DebatePhase.ClosingAgainst,
];

return rolePhases.reduce((acc, phase) => {
const storageKey = `${roomId}_${phase}_${role}`;
const stored = storageKey ? localStorage.getItem(storageKey) : null;
const fromState = speechTranscripts[phase] ?? "";
const combined =
(typeof fromState === "string" && fromState.trim().length > 0
? fromState
: stored || "") || "";
acc[phase] = combined.trim().length > 0 ? combined : "No response";
return acc;
}, {} as { [key in DebatePhase]?: string });
};

const ownerTranscripts = gatherTranscriptsForRole(localRole);
const opponentRole: DebateRole = localRole === "for" ? "against" : "for";
const opponentTranscripts = gatherTranscriptsForRole(opponentRole);
Expand Down Expand Up @@ -822,7 +825,7 @@ const OnlineDebateRoom = (): JSX.Element => {
localRole,
roomId,
isRoomOwner,
speechTranscripts,
gatherTranscriptsForRole,
opponentUser,
roomParticipants,
currentUser,
Expand Down Expand Up @@ -2610,6 +2613,30 @@ const OnlineDebateRoom = (): JSX.Element => {
opponentAvatarUrl={opponentUser?.avatarUrl || null}
ratingSummary={ratingSummary}
topic={topic}
messages={[
...Object.entries(gatherTranscriptsForRole("for")).map(
([phase, text]) => ({
sender: "Debater",
side: "for" as const,
phase,
text: text || "",
})
),
...Object.entries(gatherTranscriptsForRole("against")).map(
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
([phase, text]) => ({
sender: "Debater",
side: "against" as const,
phase,
text: text || "",
})
),
]
.filter((m) => Boolean(m.text))
.sort(
(a, b) =>
phaseOrder.indexOf(a.phase as DebatePhase) -
phaseOrder.indexOf(b.phase as DebatePhase)
)}
onClose={() => {
setShowJudgment(false);
navigate("/startDebate");
Expand Down
13 changes: 13 additions & 0 deletions frontend/src/Pages/TeamDebateRoom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2510,6 +2510,19 @@ const TeamDebateRoom: React.FC = () => {
forRole={localRole === "for" ? "Your Team" : "Opponent Team"}
againstRole={localRole === "against" ? "Your Team" : "Opponent Team"}
topic={topic}
matchType="Team Debate"
messages={Object.entries(speechTranscripts)
.map(([phase, text]) => ({
sender: 'Speaker',
side: phase.toLowerCase().includes('against')
? ('against' as const)
: phase.toLowerCase().includes('for')
? ('for' as const)
: undefined,
phase,
text: typeof text === 'string' ? text : JSON.stringify(text),
}))
.filter((m) => Boolean(m.text))}
onClose={() => {
setShowJudgment(false);
navigate("/startDebate");
Expand Down
126 changes: 125 additions & 1 deletion frontend/src/components/JudgementPopup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ import { Button } from './ui/button'; // Adjust the path as needed
import { useNavigate } from 'react-router-dom';
import { ShareVictoryCardModal } from './ShareVictoryCard/ShareVictoryCardModal';
import { DebateVictoryCardData } from './ShareVictoryCard/types';
import {
downloadDebateReportPdf,
DebateReportData,
DebateReportScoreRow,
DebateReportMessage,
} from '../utils/debateReportPdf';

// Define both possible JudgmentData types
type JudgmentDataUserBot = {
Expand Down Expand Up @@ -84,6 +90,8 @@ type JudgmentPopupProps = {
opponentAvatarUrl?: string | null;
ratingSummary?: RatingSummary | null;
topic?: string;
matchType?: string;
messages?: DebateReportMessage[];
onClose: () => void;
};

Expand Down Expand Up @@ -128,6 +136,8 @@ const JudgmentPopup: React.FC<JudgmentPopupProps> = ({
opponentAvatarUrl,
ratingSummary,
topic,
matchType,
messages,
onClose,
}) => {
const navigate = useNavigate();
Expand Down Expand Up @@ -200,6 +210,8 @@ const player2Avatar = resolvedAgainstAvatar || opponentAvatar;
const player2Desc = isUserBotFormat
? (botDesc || 'AI Opponent')
: (resolvedAgainstName || 'Debater');
const resolvedMatchType =
matchType || (isUserBotFormat ? 'AI Bot Arena' : '1v1 Ranked Debate');

const formatChange = (value: number) =>
`${value >= 0 ? '+' : ''}${value.toFixed(2)}`;
Expand Down Expand Up @@ -349,6 +361,112 @@ const player2RatingSummary =

const recommendedSkills = recommendSkills();

const handleDownloadDebateReport = () => {
const p1Total = getScoreAndReason('total', 'player1').score;
const p2Total = getScoreAndReason('total', 'player2').score;

const scoreBreakdown: DebateReportScoreRow[] = [];

const openingP1 = getScoreAndReason('opening_statement', 'player1');
const openingP2 = getScoreAndReason('opening_statement', 'player2');
scoreBreakdown.push({
roundName: 'Opening Statements',
player1Score: openingP1.score,
player1Feedback: openingP1.reason,
player2Score: openingP2.score,
player2Feedback: openingP2.reason,
});

if (isUserBotFormat) {
const crossP1 = getScoreAndReason('cross_examination', 'player1');
const crossP2 = getScoreAndReason('cross_examination', 'player2');
scoreBreakdown.push({
roundName: 'Cross-Examination & Rebuttals',
player1Score: crossP1.score,
player1Feedback: crossP1.reason,
player2Score: crossP2.score,
player2Feedback: crossP2.reason,
});

const ansP1 = getScoreAndReason('answers', 'player1');
const ansP2 = getScoreAndReason('answers', 'player2');
scoreBreakdown.push({
roundName: 'Cross-Examination Answers',
player1Score: ansP1.score,
player1Feedback: ansP1.reason,
player2Score: ansP2.score,
player2Feedback: ansP2.reason,
});
} else {
const crossQP1 = getScoreAndReason('cross_examination_questions', 'player1');
const crossQP2 = getScoreAndReason('cross_examination_questions', 'player2');
scoreBreakdown.push({
roundName: 'Cross-Examination Questions',
player1Score: crossQP1.score,
player1Feedback: crossQP1.reason,
player2Score: crossQP2.score,
player2Feedback: crossQP2.reason,
});

const crossAP1 = getScoreAndReason('cross_examination_answers', 'player1');
const crossAP2 = getScoreAndReason('cross_examination_answers', 'player2');
scoreBreakdown.push({
roundName: 'Cross-Examination Answers',
player1Score: crossAP1.score,
player1Feedback: crossAP1.reason,
player2Score: crossAP2.score,
player2Feedback: crossAP2.reason,
});
}

const closingP1 = getScoreAndReason('closing', 'player1');
const closingP2 = getScoreAndReason('closing', 'player2');
scoreBreakdown.push({
roundName: 'Closing Arguments',
player1Score: closingP1.score,
player1Feedback: closingP1.reason,
player2Score: closingP2.score,
player2Feedback: closingP2.reason,
});

const reportData: DebateReportData = {
topic: topic || localStorage.getItem('debateTopic') || 'Competitive Debate',
matchType: resolvedMatchType,
player1: {
name: player1Name,
stance: player1Stance || 'For',
totalScore: p1Total,
ratingImpact: player1RatingSummary
? `${formatRating(player1RatingSummary.rating)} (${formatChange(player1RatingSummary.change)})`
: undefined,
},
player2: {
name: player2Name,
stance: player2Stance || 'Against',
totalScore: p2Total,
ratingImpact: player2RatingSummary
? `${formatRating(player2RatingSummary.rating)} (${formatChange(player2RatingSummary.change)})`
: undefined,
},
scoreBreakdown,
verdict: {
winner: judgment?.verdict?.winner || 'Debate Completed',
reason:
judgment?.verdict?.reason ||
judgment?.verdict?.opponent_analysis ||
'Debate concluded successfully.',
congratulations: judgment?.verdict?.congratulations,
},
coachRecommendations: recommendedSkills.map((s) => ({
title: s.title,
description: s.description,
})),
messages,
};

downloadDebateReportPdf(reportData);
};

return (

<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-2 sm:p-4">
Expand Down Expand Up @@ -760,6 +878,12 @@ const player2RatingSummary =
>
πŸ† Share Victory Card
</Button>
<Button
onClick={handleDownloadDebateReport}
className='bg-gradient-to-r from-amber-500 to-orange-600 hover:from-amber-600 hover:to-orange-700 text-white px-6 py-3 rounded-full text-lg font-semibold transition-all duration-200 transform hover:scale-105 shadow-md'
>
πŸ“„ Download Debate Report
</Button>
<Button
onClick={handleGoHome}
className='bg-orange-500 hover:bg-orange-600 text-white px-6 py-3 rounded-full text-lg font-semibold transition-all duration-200 transform hover:scale-105 mr-4'
Expand All @@ -781,7 +905,7 @@ const player2RatingSummary =
const totalScores = (judgment as any)?.total || {};
const cardData: DebateVictoryCardData = {
topic: topic || localStorage.getItem('debateTopic') || 'Competitive Debate',
matchType: isUserBotFormat ? 'AI Bot Arena' : '1v1 Ranked Debate',
matchType: resolvedMatchType,
winner: {
name: isWinnerBot ? player2Name : player1Name,
avatarUrl: isWinnerBot ? player2Avatar : player1Avatar,
Expand Down
42 changes: 42 additions & 0 deletions frontend/src/components/__tests__/JudgementPopup.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import JudgmentPopup from '../JudgementPopup';
import * as debateReportPdf from '../../utils/debateReportPdf';

const s = (score: number, reason: string) => ({ score, reason });

Expand Down Expand Up @@ -118,4 +119,45 @@ describe('JudgmentPopup', () => {
await userEvent.click(screen.getByRole('button', { name: 'Back to Home' }));
expect(screen.getByText('start debate page')).toBeInTheDocument();
});

it('renders the Download Debate Report button', () => {
renderPopup();
expect(
screen.getByRole('button', { name: 'πŸ“„ Download Debate Report' })
).toBeInTheDocument();
});

it('includes the answers row even when scores are zero and reasons are empty', async () => {
const spy = vi.spyOn(debateReportPdf, 'downloadDebateReportPdf').mockImplementation(() => {});
const zeroAnswersJudgment = {
...userBotJudgment(),
answers: { user: s(0, ''), bot: s(0, '') },
};

renderPopup({ judgment: zeroAnswersJudgment });
await userEvent.click(screen.getByRole('button', { name: 'πŸ“„ Download Debate Report' }));

expect(spy).toHaveBeenCalledTimes(1);
const reportArg = spy.mock.calls[0][0];
expect(reportArg.scoreBreakdown.map((r) => r.roundName)).toContain(
'Cross-Examination Answers'
);
expect(reportArg.matchType).toBe('AI Bot Arena');
spy.mockRestore();
});

it('uses explicit matchType when provided and defaults to 1v1 Ranked Debate otherwise', async () => {
const spy = vi.spyOn(debateReportPdf, 'downloadDebateReportPdf').mockImplementation(() => {});

renderPopup({ judgment: forAgainstJudgment, matchType: 'Team Debate' });
await userEvent.click(screen.getByRole('button', { name: 'πŸ“„ Download Debate Report' }));
expect(spy.mock.calls[0][0].matchType).toBe('Team Debate');

renderPopup({ judgment: forAgainstJudgment });
const buttons = screen.getAllByRole('button', { name: 'πŸ“„ Download Debate Report' });
await userEvent.click(buttons[1]);
expect(spy.mock.calls[1][0].matchType).toBe('1v1 Ranked Debate');

spy.mockRestore();
});
});
Loading
Loading