diff --git a/V2/app/core/schemas/timers.js b/V2/app/core/schemas/timers.js index b403ef9..962ff6b 100644 --- a/V2/app/core/schemas/timers.js +++ b/V2/app/core/schemas/timers.js @@ -7,12 +7,13 @@ const nonNegInt = z.number().int().min(0); const createTimer = z.object({ name: z.string().min(1).max(200), - totalTime: positiveInt, + timerMode: z.enum(['group', 'crossfit']).optional(), + workoutDate: z.string().optional().nullable(), + exerciseCount: positiveInt, + setCount: positiveInt, setTime: positiveInt, restTime: nonNegInt.default(0), moveTime: nonNegInt.default(0), - setCount: positiveInt, - exerciseCount: positiveInt, lapCount: positiveInt.default(1), }); diff --git a/V2/app/core/socket.js b/V2/app/core/socket.js index 849a27e..7356b4f 100644 --- a/V2/app/core/socket.js +++ b/V2/app/core/socket.js @@ -32,6 +32,19 @@ function init(httpServer) { io.on('connection', (socket) => { logger.debug({ userId: socket.data.user?.id }, 'Socket connected'); + socket.on('timer:join', ({ sessionId } = {}) => { + if (!sessionId) return; + socket.join(sessionId); + // Lazy require avoids load-time circular dependency + const timerSvc = require('../modules/timers/service'); + const engine = timerSvc.getSessionEngine(sessionId); + if (engine) socket.emit('timer:state', engine.getState()); + }); + + socket.on('timer:leave', ({ sessionId } = {}) => { + if (sessionId) socket.leave(sessionId); + }); + socket.on('disconnect', (reason) => { logger.debug({ userId: socket.data.user?.id, reason }, 'Socket disconnected'); }); diff --git a/V2/app/modules/org/routes.js b/V2/app/modules/org/routes.js index eb6b681..784196f 100644 --- a/V2/app/modules/org/routes.js +++ b/V2/app/modules/org/routes.js @@ -48,6 +48,15 @@ router.patch('/', authenticateToken, authenticateRole(OWNERS), validate(updateOr } catch (err) { next(err); } }); +router.get('/branding/public', async (req, res, next) => { + try { + const org = await models.Organization.findOne({ order: [['id', 'ASC']] }); + if (!org) return ok(res, {}); + const branding = await svc.getBranding(models, org.id); + ok(res, branding); + } catch (err) { next(err); } +}); + router.get('/branding', authenticateToken, async (req, res, next) => { try { if (!req.user.organizationId) return ok(res, {}); diff --git a/V2/app/modules/timers/migrations/019-timers-timermode.js b/V2/app/modules/timers/migrations/019-timers-timermode.js new file mode 100644 index 0000000..d5fdf3e --- /dev/null +++ b/V2/app/modules/timers/migrations/019-timers-timermode.js @@ -0,0 +1,20 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const tableDesc = await queryInterface.describeTable('Timers').catch(() => null); + if (!tableDesc) return; + + const addIfMissing = async (col, def) => { + if (!tableDesc[col]) await queryInterface.addColumn('Timers', col, def); + }; + + await addIfMissing('timerMode', { type: Sequelize.STRING }); + await addIfMissing('workoutDate', { type: Sequelize.DATEONLY }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('Timers', 'timerMode').catch(() => {}); + await queryInterface.removeColumn('Timers', 'workoutDate').catch(() => {}); + }, +}; diff --git a/V2/app/modules/timers/model.js b/V2/app/modules/timers/model.js index a7e7cc6..4b0ce0d 100644 --- a/V2/app/modules/timers/model.js +++ b/V2/app/modules/timers/model.js @@ -12,6 +12,8 @@ module.exports = (sequelize, DataTypes) => { setCount: { type: DataTypes.INTEGER, allowNull: false }, exerciseCount: { type: DataTypes.INTEGER, allowNull: false }, lapCount: { type: DataTypes.INTEGER, defaultValue: 1 }, + timerMode: { type: DataTypes.STRING }, + workoutDate: { type: DataTypes.DATEONLY }, createdByUserId: { type: DataTypes.INTEGER }, }); diff --git a/V2/app/modules/timers/routes.js b/V2/app/modules/timers/routes.js index cb4bbea..3b5d39f 100644 --- a/V2/app/modules/timers/routes.js +++ b/V2/app/modules/timers/routes.js @@ -46,6 +46,14 @@ router.get('/session/active', authenticateToken, authenticateRole(COACH_PLUS), a } catch (err) { next(err); } }); +router.get('/session/:sessionId', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + const engine = svc.getSessionEngine(req.params.sessionId); + if (!engine) return next(new AppError('NOT_FOUND', 'Session not found.', 404)); + ok(res, engine.getState()); + } catch (err) { next(err); } +}); + router.get('/:id', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { try { const timer = await svc.getTimerById(models, parseInt(req.params.id, 10), req.user.organizationId); @@ -55,13 +63,27 @@ router.get('/:id', authenticateToken, authenticateRole(COACH_PLUS), async (req, router.delete('/session', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { try { - const { sessionId } = req.body; - if (!sessionId) return next(new AppError('VALIDATION_FAILED', 'sessionId required.', 400)); - await svc.stopTimer(req, sessionId, req.user.organizationId); + await svc.stopActiveSession(req, req.user.organizationId); noContent(res); } catch (err) { next(err); } }); +router.post('/session/pause', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { svc.pauseSession(req.user.organizationId); noContent(res); } catch (err) { next(err); } +}); + +router.post('/session/resume', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { svc.resumeSession(req.user.organizationId); noContent(res); } catch (err) { next(err); } +}); + +router.post('/session/restart-set', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { svc.restartSet(req.user.organizationId); noContent(res); } catch (err) { next(err); } +}); + +router.post('/session/restart-lap', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { svc.restartLap(req.user.organizationId); noContent(res); } catch (err) { next(err); } +}); + router.delete('/:id', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { try { await svc.deleteTimer(models, req, parseInt(req.params.id, 10), req.user.organizationId); diff --git a/V2/app/modules/timers/service.js b/V2/app/modules/timers/service.js index 8a7aa6f..f749842 100644 --- a/V2/app/modules/timers/service.js +++ b/V2/app/modules/timers/service.js @@ -19,7 +19,9 @@ async function getTimerById(models, id, orgId) { } async function createTimer(models, req, orgId, data) { - const timer = await models.Timer.create({ ...data, organizationId: orgId, createdByUserId: req.user.id }); + const { exerciseCount, setCount, setTime, restTime, moveTime, lapCount } = data; + const totalTime = lapCount * (exerciseCount * (setCount * setTime + (setCount - 1) * restTime) + (exerciseCount - 1) * moveTime); + const timer = await models.Timer.create({ ...data, totalTime, organizationId: orgId, createdByUserId: req.user.id }); await auditLog(req, 'timer.create', 'timer', timer.id, { name: data.name }); return timer; } @@ -57,14 +59,18 @@ async function launchTimer(models, req, timerId, orgId) { return { sessionId }; } -async function stopTimer(req, sessionId, orgId) { - const session = activeSessions.get(sessionId); - if (!session || session.orgId !== orgId) { - throw new AppError('NOT_FOUND', 'Active timer session not found.', 404); +async function stopActiveSession(req, orgId) { + let found = false; + for (const [sessionId, session] of activeSessions) { + if (session.orgId === orgId) { + session.engine.stop(); + activeSessions.delete(sessionId); + await auditLog(req, 'timer.stop', null, null, { sessionId }); + found = true; + break; + } } - session.engine.stop(); - activeSessions.delete(sessionId); - await auditLog(req, 'timer.stop', null, null, { sessionId }); + if (!found) throw new AppError('NOT_FOUND', 'No active timer session found.', 404); } function getActiveSession(orgId) { @@ -80,4 +86,35 @@ function getSessionEngine(sessionId) { return activeSessions.get(sessionId)?.engine ?? null; } -module.exports = { getTimers, getTimerById, createTimer, deleteTimer, launchTimer, stopTimer, getActiveSession, getSessionEngine }; +function _getActiveEngine(orgId) { + for (const [, session] of activeSessions) { + if (session.orgId === orgId) return session.engine; + } + return null; +} + +function pauseSession(orgId) { + const engine = _getActiveEngine(orgId); + if (!engine) throw new AppError('NOT_FOUND', 'No active timer session.', 404); + engine.pause(); +} + +function resumeSession(orgId) { + const engine = _getActiveEngine(orgId); + if (!engine) throw new AppError('NOT_FOUND', 'No active timer session.', 404); + engine.resume(); +} + +function restartSet(orgId) { + const engine = _getActiveEngine(orgId); + if (!engine) throw new AppError('NOT_FOUND', 'No active timer session.', 404); + engine.restartSet(); +} + +function restartLap(orgId) { + const engine = _getActiveEngine(orgId); + if (!engine) throw new AppError('NOT_FOUND', 'No active timer session.', 404); + engine.restartLap(); +} + +module.exports = { getTimers, getTimerById, createTimer, deleteTimer, launchTimer, stopActiveSession, getActiveSession, getSessionEngine, pauseSession, resumeSession, restartSet, restartLap }; diff --git a/V2/app/modules/timers/timer-engine.js b/V2/app/modules/timers/timer-engine.js index 7e77c70..2f2563d 100644 --- a/V2/app/modules/timers/timer-engine.js +++ b/V2/app/modules/timers/timer-engine.js @@ -37,14 +37,94 @@ class TimerEngine { this.io.to(this.roomId).emit('timer:stopped', { sessionId: this.roomId }); } + pause() { + if (this.status !== 'running') return; + const now = process.hrtime.bigint(); + this._pausedPhaseRemainingMs = Math.max(0, Number((this.phaseEndTime - now) / NS_PER_MS)); + this._pausedTotalRemainingMs = Math.max(0, Number((this.sessionEndTime - now) / NS_PER_MS)); + this._clearInterval(); + this.status = 'paused'; + this.io.to(this.roomId).emit('timer:paused', this._snapshot()); + } + + resume() { + if (this.status !== 'paused') return; + const now = process.hrtime.bigint(); + this.phaseEndTime = now + BigInt(Math.round(this._pausedPhaseRemainingMs)) * NS_PER_MS; + this.sessionEndTime = now + BigInt(Math.round(this._pausedTotalRemainingMs)) * NS_PER_MS; + this.status = 'running'; + this._lastEmittedSecond = -1; + this._interval = setInterval(() => this._tick(), 100); + this.io.to(this.roomId).emit('timer:state', this._snapshot()); + } + + restartSet() { + const now = process.hrtime.bigint(); + this.phase = 'set'; + this._lastEmittedSecond = -1; + this.phaseEndTime = now + BigInt(this.config.setTime) * NS_PER_MS * BigInt(1000); + + if (this.status === 'paused') { + this._pausedPhaseRemainingMs = this.config.setTime * 1000; + this.io.to(this.roomId).emit('timer:paused', this._snapshot()); + } else { + if (this.status !== 'running') { + this.status = 'running'; + this._interval = setInterval(() => this._tick(), 100); + } + this.io.to(this.roomId).emit('timer:phase-change', this._snapshot()); + } + } + + restartLap() { + const { setTime, restTime, moveTime, setCount, exerciseCount, lapCount } = this.config; + const now = process.hrtime.bigint(); + this.currentSet = 1; + this.currentExercise = 1; + this.phase = 'set'; + this._lastEmittedSecond = -1; + this.phaseEndTime = now + BigInt(setTime) * NS_PER_MS * BigInt(1000); + + const remainingLaps = lapCount - this.currentLap + 1; + const lapSec = exerciseCount * (setCount * setTime + Math.max(0, setCount - 1) * restTime) + + Math.max(0, exerciseCount - 1) * moveTime; + const totalRemainingMs = remainingLaps * lapSec * 1000; + this.sessionEndTime = now + BigInt(Math.round(totalRemainingMs)) * NS_PER_MS; + + if (this.status === 'paused') { + this._pausedPhaseRemainingMs = setTime * 1000; + this._pausedTotalRemainingMs = totalRemainingMs; + this.io.to(this.roomId).emit('timer:paused', this._snapshot()); + } else { + if (this.status !== 'running') { + this.status = 'running'; + this._interval = setInterval(() => this._tick(), 100); + } + this.io.to(this.roomId).emit('timer:state', this._snapshot()); + } + } + getState() { return this._snapshot(); } + _phaseTotalMs() { + const { setTime, restTime, moveTime } = this.config; + if (this.phase === 'set') return setTime * 1000; + if (this.phase === 'rest') return restTime * 1000; + return moveTime * 1000; + } + _snapshot() { - const now = process.hrtime.bigint(); - const phaseRemainingMs = Number((this.phaseEndTime - now) / NS_PER_MS); - const totalRemainingMs = Number((this.sessionEndTime - now) / NS_PER_MS); + let phaseRemainingMs, totalRemainingMs; + if (this.status === 'paused') { + phaseRemainingMs = this._pausedPhaseRemainingMs ?? 0; + totalRemainingMs = this._pausedTotalRemainingMs ?? 0; + } else { + const now = process.hrtime.bigint(); + phaseRemainingMs = Number((this.phaseEndTime - now) / NS_PER_MS); + totalRemainingMs = Number((this.sessionEndTime - now) / NS_PER_MS); + } return { status: this.status, phase: this.phase, @@ -56,6 +136,10 @@ class TimerEngine { setCount: this.config.setCount, phaseRemainingMs: Math.max(0, phaseRemainingMs), totalRemainingMs: Math.max(0, totalRemainingMs), + phaseTotalMs: this._phaseTotalMs(), + setTimeMs: this.config.setTime * 1000, + restTimeMs: this.config.restTime * 1000, + moveTimeMs: this.config.moveTime * 1000, phaseEndTime: Number(this.phaseEndTime / NS_PER_MS), // ms epoch }; } @@ -73,10 +157,17 @@ class TimerEngine { this.io.to(this.roomId).emit('timer:tick', { phaseRemainingMs: Math.max(0, phaseRemainingMs), totalRemainingMs: Math.max(0, totalRemainingMs), - phase: this.phase, - currentLap: this.currentLap, - currentExercise: this.currentExercise, - currentSet: this.currentSet, + phaseTotalMs: this._phaseTotalMs(), + setTimeMs: this.config.setTime * 1000, + restTimeMs: this.config.restTime * 1000, + moveTimeMs: this.config.moveTime * 1000, + phase: this.phase, + currentLap: this.currentLap, + currentExercise: this.currentExercise, + currentSet: this.currentSet, + lapCount: this.config.lapCount, + exerciseCount: this.config.exerciseCount, + setCount: this.config.setCount, }); } diff --git a/V2/app/public/create-timer.html b/V2/app/public/create-timer.html index 0aac451..ecf7f37 100644 --- a/V2/app/public/create-timer.html +++ b/V2/app/public/create-timer.html @@ -30,84 +30,48 @@ -
Time between exercises to transition.
+ +Time to transition to next exercise.