Skip to content
Merged
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
96 changes: 79 additions & 17 deletions backend/controllers/flowController.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,36 +23,44 @@ const syncArchiveByRoomId = async (roomId, updatePayload) => {
return archivedHackathon;
};

const NEXT_PHASE_DEBOUNCE_MS = 1200;

const getCurrentPhaseDurationMs = (room) => {
const currentPhase = room?.phases?.[room.currentPhaseIndex];
const minutes = currentPhase?.durationMinutes || 0;
return minutes > 0 ? minutes * 60000 : 0;
};

const deployFlow = async (req, res) => {
try {
const { name, organizerSecret, eventStartTime, eventEndTime, timezone, branding, phases, status } = req.body;
const roomId = Math.random().toString(36).substring(2, 8).toUpperCase();

const isDraft = status === 'DRAFT';
let phaseEndTime = null;

if (!isDraft) {
const firstPhaseDuration = phases[0]?.durationMinutes || 60;
phaseEndTime = new Date(Date.now() + firstPhaseDuration * 60000);
}

const hackathonPayload = {
roomId, name, organizerSecret, eventStartTime, eventEndTime, timezone, branding, phases,
status: isDraft ? 'DRAFT' : 'RUNNING',
currentPhaseIndex: 0,
status: isDraft ? 'DRAFT' : 'RUNNING',
currentPhaseIndex: 0,
phaseEndTime
};

await Promise.all([
new Hackathon(hackathonPayload).save(),
new AllHackathons(hackathonPayload).save()
]);

// Only set as active room if it's NOT a draft
if (organizerSecret && !isDraft) {
await User.findOneAndUpdate({ email: organizerSecret }, { activeRoomId: roomId });
}

res.status(201).json({ roomId, message: isDraft ? "Draft saved successfully." : "Flow deployed successfully." });
} catch (err) { res.status(500).json({ error: err.message }); }
};
Expand Down Expand Up @@ -82,10 +90,10 @@ const deleteFlow = async (req, res) => {
),
syncArchiveByRoomId(normalizedRoomId, { isDeleted: true })
]);

// If this was the active room for the user, clear it
await User.findOneAndUpdate({ email: organizerSecret, activeRoomId: normalizedRoomId }, { activeRoomId: null });

res.status(200).json({ message: "Flow deleted successfully." });
} catch (err) { res.status(500).json({ error: err.message }); }
};
Expand All @@ -94,7 +102,7 @@ const updateFlow = async (req, res) => {
try {
const normalizedRoomId = req.params.roomId.toUpperCase();
const { name, organizerSecret, eventStartTime, eventEndTime, timezone, branding, phases } = req.body;

const flow = await Hackathon.findOne({ roomId: normalizedRoomId, isDeleted: false });
if (!flow) return res.status(404).json({ error: "Flow not found." });
if (flow.organizerSecret !== organizerSecret) return res.status(403).json({ error: "Unauthorized." });
Expand All @@ -108,6 +116,20 @@ const updateFlow = async (req, res) => {
phases: phases || flow.phases
};

// If the active phase duration is edited, refresh the active timer baseline.
if (phases && Array.isArray(phases) && phases[flow.currentPhaseIndex]) {
const updatedCurrentPhase = phases[flow.currentPhaseIndex];
const nextDurationMs = (updatedCurrentPhase.durationMinutes || 0) * 60000;

if (nextDurationMs > 0 && flow.status === 'RUNNING') {
updatePayload.phaseEndTime = new Date(Date.now() + nextDurationMs);
}

if (nextDurationMs > 0 && flow.status === 'PAUSED') {
updatePayload.pausedRemainingMs = nextDurationMs;
}
}

const [updatedFlow] = await Promise.all([
Hackathon.findOneAndUpdate(
{ roomId: normalizedRoomId, isDeleted: false },
Expand All @@ -134,28 +156,42 @@ const updateRoomState = async (req, res) => {
try {
const { roomId } = req.params;
const { action, organizerSecret, announcementText, announcementDuration } = req.body;

const room = await Hackathon.findOne({ roomId: roomId.toUpperCase(), isDeleted: false });
if (!room) return res.status(404).json({ error: "Room not found." });
if (room.organizerSecret !== organizerSecret) return res.status(403).json({ error: "SECURITY FAULT: Unauthorized." });

if (action === 'NEXT_PHASE') {
const now = Date.now();
const lastActionAt = room.lastControlActionAt ? room.lastControlActionAt.getTime() : 0;
const isRapidDuplicate = room.lastControlAction === 'NEXT_PHASE' && now - lastActionAt < NEXT_PHASE_DEBOUNCE_MS;

if (isRapidDuplicate) {
return res.status(429).json({ error: 'Duplicate NEXT_PHASE request ignored. Please wait and retry.' });
}
}

if (action === 'PAUSE' && room.status === 'RUNNING') {
room.pausedRemainingMs = room.phaseEndTime.getTime() - Date.now();
const fallbackDurationMs = getCurrentPhaseDurationMs(room);
const phaseDistance = room.phaseEndTime ? room.phaseEndTime.getTime() - Date.now() : 0;
room.pausedRemainingMs = phaseDistance > 0 ? phaseDistance : fallbackDurationMs;
room.phaseEndTime = null;
room.status = 'PAUSED';
}
}
else if (action === 'RESUME' && (room.status === 'PAUSED' || room.status === 'DRAFT')) {
if (room.status === 'DRAFT') {
const duration = room.phases[room.currentPhaseIndex]?.durationMinutes || 60;
room.phaseEndTime = new Date(Date.now() + duration * 60000);
// Also update the user's activeRoomId if it's their first time launching
await User.findOneAndUpdate({ email: organizerSecret }, { activeRoomId: roomId.toUpperCase() });
} else {
room.phaseEndTime = new Date(Date.now() + room.pausedRemainingMs);
const fallbackDurationMs = getCurrentPhaseDurationMs(room);
const resumeDurationMs = room.pausedRemainingMs > 0 ? room.pausedRemainingMs : fallbackDurationMs;
room.phaseEndTime = new Date(Date.now() + resumeDurationMs);
}
room.pausedRemainingMs = null;
room.status = 'RUNNING';
}
}
else if (action === 'NEXT_PHASE') {
room.currentPhaseIndex += 1;
if (room.currentPhaseIndex >= room.phases.length) {
Expand All @@ -179,6 +215,32 @@ const updateRoomState = async (req, res) => {
room.announcementDuration = announcementDuration || 10;
room.announcementTimestamp = new Date(); // Logs the exact moment of broadcast
}
else if (action === 'RECALCULATE') {
const fallbackDurationMs = getCurrentPhaseDurationMs(room);

if (!fallbackDurationMs) {
return res.status(400).json({ error: 'Cannot recalculate timer for an empty or invalid current phase.' });
}

if (room.status === 'RUNNING') {
room.phaseEndTime = new Date(Date.now() + fallbackDurationMs);
room.pausedRemainingMs = null;
} else if (room.status === 'PAUSED') {
room.pausedRemainingMs = fallbackDurationMs;
room.phaseEndTime = null;
} else if (room.status === 'DRAFT') {
room.pausedRemainingMs = fallbackDurationMs;
room.phaseEndTime = null;
room.status = 'PAUSED';
} else {
return res.status(400).json({ error: 'Cannot recalculate timer for a completed room.' });
}
}

if (['PAUSE', 'RESUME', 'NEXT_PHASE', 'STOP', 'ANNOUNCE', 'RECALCULATE'].includes(action)) {
room.lastControlAction = action;
room.lastControlActionAt = new Date();
}

await room.save();
await syncArchiveByRoomId(room.roomId, buildArchivePayload(room));
Expand All @@ -193,9 +255,9 @@ const joinRoom = async (req, res) => {
const room = await Hackathon.findOne({ roomId: roomId.toUpperCase(), isDeleted: false });
if (!room) return res.status(404).json({ error: "Room not found." });
if (!room.participants.some(p => p.teamName === teamName)) {
room.participants.push({ teamName });
await room.save();
await syncArchiveByRoomId(room.roomId, buildArchivePayload(room));
room.participants.push({ teamName });
await room.save();
await syncArchiveByRoomId(room.roomId, buildArchivePayload(room));
}
res.status(200).json({ message: "Joined successfully" });
} catch (err) { res.status(500).json({ error: err.message }); }
Expand Down
56 changes: 56 additions & 0 deletions backend/eslint.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const js = require('@eslint/js');
const globals = require('globals');

module.exports = [
{
ignores: ['node_modules/**'],
},
js.configs.recommended,
{
files: ['**/*.js'],
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'commonjs',
globals: {
...globals.node,
},
},
rules: {
'no-console': 'off',
'no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
camelcase: [
'warn',
{
properties: 'never',
ignoreDestructuring: true,
ignoreImports: true,
allow: ['^_$'],
},
],
Comment on lines +21 to +29
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Conflicting rules: camelcase vs no-restricted-syntax for functions.

There's a direct conflict between these rules:

  • camelcase (lines 21-29) enforces camelCase for identifiers
  • no-restricted-syntax (lines 39-53) requires PascalCase for all functions

These rules will fight each other on function names. Additionally, PascalCase for regular functions is unconventional in JavaScript—it's typically reserved for classes and constructor functions.

From the context snippets, all existing controller functions (deployFlow, buildArchivePayload, syncArchiveByRoomId, getRoomUsers, emitRoomUsers) use camelCase and will trigger warnings.

Proposed fix: Remove PascalCase function requirement
-            'no-restricted-syntax': [
-                'warn',
-                {
-                    selector: "FunctionDeclaration[id.name!=/^[A-Z][a-zA-Z0-9]*$/]",
-                    message: 'Function names must be PascalCase like NewFont.',
-                },
-                {
-                    selector: "VariableDeclarator[init.type='ArrowFunctionExpression'][id.type='Identifier'][id.name!=/^[A-Z][a-zA-Z0-9]*$/]",
-                    message: 'Function names must be PascalCase like NewFont.',
-                },
-                {
-                    selector: "VariableDeclarator[init.type='FunctionExpression'][id.type='Identifier'][id.name!=/^[A-Z][a-zA-Z0-9]*$/]",
-                    message: 'Function names must be PascalCase like NewFont.',
-                },
-            ],

Also applies to: 39-53

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/eslint.config.cjs` around lines 21 - 29, The eslint config currently
conflicts: the camelcase rule enforces camelCase while the no-restricted-syntax
rule enforces PascalCase for functions (causing warnings for existing functions
like deployFlow, buildArchivePayload, syncArchiveByRoomId, getRoomUsers,
emitRoomUsers). Fix by removing or changing the no-restricted-syntax entry that
mandates PascalCase for functions (the rule targeting
FunctionDeclaration/FunctionExpression/ArrowFunctionExpression names); instead,
restrict PascalCase only to class/constructor names or delete the PascalCase
function check so camelcase remains authoritative. Ensure the change references
the rules named camelcase and no-restricted-syntax and that constructor/class
naming remains unaffected.

'func-names': ['warn', 'as-needed'],
'id-match': [
'warn',
'^_?(?:[a-z][a-zA-Z0-9]*|[A-Z][a-zA-Z0-9]*)$',
{
onlyDeclarations: true,
properties: false,
},
],
'no-restricted-syntax': [
'warn',
{
selector: "FunctionDeclaration[id.name!=/^[A-Z][a-zA-Z0-9]*$/]",
message: 'Function names must be PascalCase like NewFont.',
},
{
selector: "VariableDeclarator[init.type='ArrowFunctionExpression'][id.type='Identifier'][id.name!=/^[A-Z][a-zA-Z0-9]*$/]",
message: 'Function names must be PascalCase like NewFont.',
},
{
selector: "VariableDeclarator[init.type='FunctionExpression'][id.type='Identifier'][id.name!=/^[A-Z][a-zA-Z0-9]*$/]",
message: 'Function names must be PascalCase like NewFont.',
Comment on lines +42 to +51
Copy link

Copilot AI Apr 3, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These selectors enforce PascalCase for function declarations/expressions, but the backend codebase primarily uses camelCase (e.g., backend/server.js:26 getRoomUsers, backend/lib/connectDB.js:18 connectDB). This will make npm run lint very noisy. Consider switching the regex to camelCase (or allowing both), and update the message ("NewFont") to something backend-relevant.

Suggested change
selector: "FunctionDeclaration[id.name!=/^[A-Z][a-zA-Z0-9]*$/]",
message: 'Function names must be PascalCase like NewFont.',
},
{
selector: "VariableDeclarator[init.type='ArrowFunctionExpression'][id.type='Identifier'][id.name!=/^[A-Z][a-zA-Z0-9]*$/]",
message: 'Function names must be PascalCase like NewFont.',
},
{
selector: "VariableDeclarator[init.type='FunctionExpression'][id.type='Identifier'][id.name!=/^[A-Z][a-zA-Z0-9]*$/]",
message: 'Function names must be PascalCase like NewFont.',
selector: "FunctionDeclaration[id.name!=/^_?[a-z][a-zA-Z0-9]*$/]",
message: 'Function names must be camelCase like connectDB.',
},
{
selector: "VariableDeclarator[init.type='ArrowFunctionExpression'][id.type='Identifier'][id.name!=/^_?[a-z][a-zA-Z0-9]*$/]",
message: 'Function names must be camelCase like connectDB.',
},
{
selector: "VariableDeclarator[init.type='FunctionExpression'][id.type='Identifier'][id.name!=/^_?[a-z][a-zA-Z0-9]*$/]",
message: 'Function names must be camelCase like connectDB.',

Copilot uses AI. Check for mistakes.
},
],
Comment on lines +39 to +53
Copy link

Copilot AI Apr 3, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

id-match currently allows both camelCase and PascalCase declarations, but later no-restricted-syntax enforces PascalCase for function identifiers. This combination is contradictory and will produce widespread warnings across the backend (most functions are currently camelCase). Align these rules (e.g., enforce camelCase, or allow both) and remove the redundant rule to avoid noisy lint output.

Suggested change
'no-restricted-syntax': [
'warn',
{
selector: "FunctionDeclaration[id.name!=/^[A-Z][a-zA-Z0-9]*$/]",
message: 'Function names must be PascalCase like NewFont.',
},
{
selector: "VariableDeclarator[init.type='ArrowFunctionExpression'][id.type='Identifier'][id.name!=/^[A-Z][a-zA-Z0-9]*$/]",
message: 'Function names must be PascalCase like NewFont.',
},
{
selector: "VariableDeclarator[init.type='FunctionExpression'][id.type='Identifier'][id.name!=/^[A-Z][a-zA-Z0-9]*$/]",
message: 'Function names must be PascalCase like NewFont.',
},
],

Copilot uses AI. Check for mistakes.
},
},
];
30 changes: 18 additions & 12 deletions backend/models/dataSchema.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,43 @@
const mongoose = require('mongoose');

const PhaseSchema = new mongoose.Schema({
name: { type: String, required: true },
name: { type: String, required: true },
durationMinutes: { type: Number, required: true },
autoTransition: { type: Boolean, default: false }
});

const HackathonSchema = new mongoose.Schema({
name: { type: String, required: true },
roomId: { type: String, required: true, unique: true, index: true },
organizerSecret: { type: String, required: true },
name: { type: String, required: true },
roomId: { type: String, required: true, unique: true, index: true },
organizerSecret: { type: String, required: true },
isDeleted: { type: Boolean, default: false },

eventStartTime: { type: String, default: "" },
eventEndTime: { type: String, default: "" },
timezone: { type: String, default: "UTC" },

status: { type: String, enum: ['DRAFT', 'RUNNING', 'PAUSED', 'COMPLETED'], default: 'DRAFT' },
currentPhaseIndex: { type: Number, default: 0 },
phaseEndTime: { type: Date, default: null },
pausedRemainingMs: { type: Number, default: null },

phaseEndTime: { type: Date, default: null },
pausedRemainingMs: { type: Number, default: null },
lastControlAction: {
type: String,
enum: ['PAUSE', 'RESUME', 'NEXT_PHASE', 'STOP', 'ANNOUNCE', 'RECALCULATE'],
default: null
},
lastControlActionAt: { type: Date, default: null },

// NEW: Advanced Broadcast Data
announcement: { type: String, default: "" },
announcement: { type: String, default: "" },
announcementDuration: { type: Number, default: 10 },
announcementTimestamp: { type: Date, default: null },

phases: [PhaseSchema],
branding: {
accentColor: { type: String, default: "#a2c9ff" },
logoUrl: { type: String, default: "" }
logoUrl: { type: String, default: "" }
},

participants: [{
teamName: { type: String, required: true },
joinedAt: { type: Date, default: Date.now }
Expand Down
Loading