This commit is contained in:
Ccjcarkbla
2026-06-30 11:49:26 -04:00
parent e192aecb2f
commit 7a35165bfd
16 changed files with 559 additions and 153 deletions
@@ -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(() => {});
},
};
+2
View File
@@ -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 },
});
+25 -3
View File
@@ -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);
+46 -9
View File
@@ -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 };
+98 -7
View File
@@ -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,
});
}