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: ['^_$'],
},
],
'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 +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.

This ESLint config warns if any function/arrow-function identifier is not PascalCase, but the backend code uses camelCase for controller functions (e.g. deployFlow, updateRoomState). This will generate noisy lint output and make npm run lint hard to use. Recommend removing these no-restricted-syntax selectors or switching the rule to enforce camelCase for non-component functions.

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