diff --git a/V2/app/core/auth.js b/V2/app/core/auth.js index 5893c6e..19bb634 100644 --- a/V2/app/core/auth.js +++ b/V2/app/core/auth.js @@ -9,12 +9,12 @@ const FEATURE_CACHE_TTL = 5 * 60 * 1000; // 5 minutes function authenticateToken(req, res, next) { const header = req.headers.authorization; - if (!header || !header.startsWith('Bearer ')) { + // ?token= fallback for browser-native requests (video/audio elements, downloads) + const token = (header && header.startsWith('Bearer ')) ? header.slice(7) : req.query.token; + if (!token) { return next(new AppError('AUTH_REQUIRED', 'Authentication required.', 401)); } - const token = header.slice(7); - jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] }, async (err, decoded) => { if (err) { return next(new AppError('AUTH_INVALID', 'Invalid or expired token.', 401)); @@ -41,6 +41,14 @@ function authenticateToken(req, res, next) { organizationId: user.organizationId, }; + // Allow SystemAdmin to scope API calls to a specific org via header or query param + if (user.role === 'SystemAdmin') { + const fromHeader = parseInt(req.headers['x-org-id'], 10); + const fromQuery = parseInt(req.query.orgId, 10); + const orgId = !isNaN(fromHeader) ? fromHeader : !isNaN(fromQuery) ? fromQuery : NaN; + if (!isNaN(orgId)) req.user.organizationId = orgId; + } + next(); } catch (dbErr) { next(dbErr); diff --git a/V2/app/core/schemas/videos.js b/V2/app/core/schemas/videos.js index 4706bb5..a1fa335 100644 --- a/V2/app/core/schemas/videos.js +++ b/V2/app/core/schemas/videos.js @@ -4,7 +4,7 @@ const { z } = require('zod'); const uploadVideo = z.object({ description: z.string().max(500).optional().default(''), - category: z.string().min(1).max(100), + category: z.string().min(1).max(100).optional(), }); const createCategory = z.object({ diff --git a/V2/app/core/schemas/workouts.js b/V2/app/core/schemas/workouts.js index 1f65126..2a3fb86 100644 --- a/V2/app/core/schemas/workouts.js +++ b/V2/app/core/schemas/workouts.js @@ -4,7 +4,8 @@ const { z } = require('zod'); const createWorkout = z.object({ name: z.string().min(1).max(200), - workoutDate: z.string().datetime().optional(), + workoutDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().nullable(), + notes: z.string().max(2000).optional().nullable(), video1: z.number().int().positive().nullable().optional(), video2: z.number().int().positive().nullable().optional(), video3: z.number().int().positive().nullable().optional(), diff --git a/V2/app/migrate_v1.js b/V2/app/migrate_v1.js new file mode 100644 index 0000000..34641ec --- /dev/null +++ b/V2/app/migrate_v1.js @@ -0,0 +1,164 @@ +'use strict'; + +/** + * One-time migration: site/database.sqlite → V2/app/vitfit.sqlite + * + * Run from V2/app/: node migrate_v1.js + * Safe to re-run — uses INSERT OR IGNORE so duplicates are skipped. + */ + +const sqlite3 = require('sqlite3').verbose(); +const path = require('path'); +const fs = require('fs'); + +const OLD_DB = path.resolve(__dirname, '../../site/database.sqlite'); +const NEW_DB = path.resolve(__dirname, './vitfit.sqlite'); +const OLD_UPL = path.resolve(__dirname, '../../site/public/uploads'); +const NEW_UPL = path.resolve(__dirname, './uploads'); +const ORG_ID = 1; // VitalityFitness org already exists +const OWNER_ID = 1; // Tyler (Owner) used as createdByUserId + +function db(filePath, flags = sqlite3.OPEN_READWRITE) { + return new sqlite3.Database(filePath, flags); +} +const run = (d, sql, p = []) => new Promise((ok, fail) => d.run(sql, p, function(e) { e ? fail(e) : ok(this); })); +const all = (d, sql, p = []) => new Promise((ok, fail) => d.all(sql, p, (e, r) => e ? fail(e) : ok(r))); +const get = (d, sql, p = []) => new Promise((ok, fail) => d.get(sql, p, (e, r) => e ? fail(e) : ok(r))); + +async function bumpSeq(d, table, minVal) { + const row = await get(d, 'SELECT seq FROM sqlite_sequence WHERE name = ?', [table]); + if (!row) { + await run(d, 'INSERT INTO sqlite_sequence (name, seq) VALUES (?, ?)', [table, minVal]); + } else if (row.seq < minVal) { + await run(d, 'UPDATE sqlite_sequence SET seq = ? WHERE name = ?', [minVal, table]); + } +} + +function mimeFromFilename(name) { + const ext = path.extname(name).toLowerCase(); + return { '.mp4': 'video/mp4', '.mov': 'video/quicktime', '.avi': 'video/x-msvideo', + '.mkv': 'video/x-matroska', '.webm': 'video/webm' }[ext] || 'video/mp4'; +} + +function mapRole(oldRole) { + if (oldRole === 'Coach') return 'Coach'; + return 'Owner'; // Admin → Owner +} + +async function migrate() { + const old = db(OLD_DB, sqlite3.OPEN_READONLY); + const nw = db(NEW_DB); + + console.log('Starting migration...\n'); + + // ── 1. Categories ──────────────────────────────────────────────────────────── + const oldCats = await all(old, 'SELECT * FROM Categories'); + await run(nw, 'BEGIN'); + let catCount = 0; + for (const c of oldCats) { + const result = await run(nw, + 'INSERT OR IGNORE INTO Categories (organizationId, name, createdAt, updatedAt) VALUES (?,?,?,?)', + [ORG_ID, c.name, c.createdAt, c.updatedAt || c.createdAt]); + if (result.changes) catCount++; + } + await run(nw, 'COMMIT'); + console.log(`✓ Categories: ${catCount}/${oldCats.length} inserted`); + + // ── 2. Videos (keep original IDs so workout references stay valid) ─────────── + const oldVideos = await all(old, 'SELECT * FROM Videos ORDER BY id'); + await run(nw, 'BEGIN'); + let vidCount = 0; + for (const v of oldVideos) { + const result = await run(nw, + `INSERT OR IGNORE INTO Videos + (id, organizationId, filename, description, category, mimeType, fileSizeBytes, createdAt, updatedAt) + VALUES (?,?,?,?,?,?,?,?,?)`, + [v.id, ORG_ID, v.filename, v.description, v.category, + mimeFromFilename(v.filename), null, v.createdAt, v.updatedAt || v.createdAt]); + if (result.changes) vidCount++; + } + // Advance the sequence past the highest inserted ID + const maxVidId = oldVideos.reduce((m, v) => Math.max(m, v.id), 0); + await bumpSeq(nw, 'Videos', maxVidId); + await run(nw, 'COMMIT'); + console.log(`✓ Videos: ${vidCount}/${oldVideos.length} inserted (IDs preserved)`); + + // ── 3. Workouts ────────────────────────────────────────────────────────────── + const oldWorkouts = await all(old, 'SELECT * FROM Workouts ORDER BY id'); + await run(nw, 'BEGIN'); + let wkCount = 0; + for (const w of oldWorkouts) { + const result = await run(nw, + `INSERT OR IGNORE INTO Workouts + (id, organizationId, name, workoutDate, video1, video2, video3, video4, + number1, number2, number3, number4, createdByUserId, createdAt, updatedAt) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, + [w.id, ORG_ID, w.name, w.workoutDate, + w.video1, w.video2, w.video3, w.video4, + w.number1, w.number2, w.number3, w.number4, + OWNER_ID, w.createdAt, w.createdAt]); + if (result.changes) wkCount++; + } + const maxWkId = oldWorkouts.reduce((m, w) => Math.max(m, w.id), 0); + await bumpSeq(nw, 'Workouts', maxWkId); + await run(nw, 'COMMIT'); + console.log(`✓ Workouts: ${wkCount}/${oldWorkouts.length} inserted`); + + // ── 4. Timers ──────────────────────────────────────────────────────────────── + const oldTimers = await all(old, 'SELECT * FROM Timers'); + await run(nw, 'BEGIN'); + let timCount = 0; + for (const t of oldTimers) { + const result = await run(nw, + `INSERT OR IGNORE INTO Timers + (organizationId, name, totalTime, setTime, restTime, moveTime, + setCount, exerciseCount, lapCount, createdByUserId, createdAt, updatedAt) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`, + [ORG_ID, 'Imported Timer', t.totalTime, t.setTime, t.restTime, t.moveTime, + t.setCount, t.exerciseCount, t.lapCount, OWNER_ID, t.createdAt, t.createdAt]); + if (result.changes) timCount++; + } + await run(nw, 'COMMIT'); + console.log(`✓ Timers: ${timCount}/${oldTimers.length} inserted`); + + // ── 5. Users (old IDs may conflict → assign new sequential IDs) ────────────── + const oldUsers = await all(old, 'SELECT * FROM Users ORDER BY id'); + await run(nw, 'BEGIN'); + let usrCount = 0; + for (const u of oldUsers) { + // Skip if username already exists in new DB + const existing = await get(nw, 'SELECT id FROM Users WHERE username = ?', [u.username]); + if (existing) { console.log(` ↳ skipped existing user: ${u.username}`); continue; } + const result = await run(nw, + `INSERT INTO Users + (organizationId, username, email, password, role, isActive, createdAt, updatedAt) + VALUES (?,?,?,?,?,1,?,?)`, + [ORG_ID, u.username, null, u.password, mapRole(u.role), + u.createdAt, u.updatedAt || u.createdAt]); + if (result.changes) usrCount++; + } + await run(nw, 'COMMIT'); + console.log(`✓ Users: ${usrCount}/${oldUsers.length} inserted (Admin→Owner, Coach→Coach)`); + + // ── 6. Copy existing video files ───────────────────────────────────────────── + if (!fs.existsSync(NEW_UPL)) fs.mkdirSync(NEW_UPL, { recursive: true }); + let copied = 0, missing = 0; + const oldFiles = fs.existsSync(OLD_UPL) ? fs.readdirSync(OLD_UPL) : []; + for (const file of oldFiles) { + const src = path.join(OLD_UPL, file); + const dest = path.join(NEW_UPL, file); + if (!fs.existsSync(dest)) { fs.copyFileSync(src, dest); copied++; } + } + missing = oldVideos.length - oldFiles.length; + console.log(`✓ Video files: ${copied} copied to uploads/`); + if (missing > 0) { + console.log(` ⚠ ${missing} video files not found locally — copy them from`); + console.log(` wherever the old uploads folder lives into: ${NEW_UPL}`); + } + + old.close(); + nw.close(); + console.log('\nMigration complete.'); +} + +migrate().catch(err => { console.error('Migration failed:', err.message); process.exit(1); }); diff --git a/V2/app/modules/sysadmin/routes.js b/V2/app/modules/sysadmin/routes.js index b1cfee1..7b270f8 100644 --- a/V2/app/modules/sysadmin/routes.js +++ b/V2/app/modules/sysadmin/routes.js @@ -68,11 +68,14 @@ router.get('/health', authenticateToken, authenticateRole(SA), async (req, res, if (getActiveSession(org.id)) activeTimerSessions++; } + const mem = process.memoryUsage(); ok(res, { status: 'ok', version: require('../../package.json').version, nodeVersion: process.version, - uptime: Math.floor(process.uptime()), + uptimeSeconds: Math.floor(process.uptime()), + timestamp: new Date().toISOString(), + memoryMb: { rss: Math.round(mem.rss / 1_048_576), heapUsed: Math.round(mem.heapUsed / 1_048_576) }, db: { status: 'ok' }, disk: { free: storage.disk.free, usedPercent: storage.disk.usedPercent }, activeTimerSessions, diff --git a/V2/app/modules/videos/routes.js b/V2/app/modules/videos/routes.js index 384ba92..bb28af4 100644 --- a/V2/app/modules/videos/routes.js +++ b/V2/app/modules/videos/routes.js @@ -36,8 +36,8 @@ function validate(schema) { // GET /videos router.get('/', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { try { - const { category, page = 1, limit = 50 } = req.query; - const { rows, count } = await svc.getVideos(models, req.user.organizationId, { category, page: +page, limit: +limit }); + const { category, search, page = 1, limit = 50 } = req.query; + const { rows, count } = await svc.getVideos(models, req.user.organizationId, { category, search, page: +page, limit: +limit }); collection(res, rows, count, +page, +limit); } catch (err) { next(err); } }); diff --git a/V2/app/modules/videos/service.js b/V2/app/modules/videos/service.js index 7e83371..c87c221 100644 --- a/V2/app/modules/videos/service.js +++ b/V2/app/modules/videos/service.js @@ -3,6 +3,7 @@ const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); +const { Op } = require('sequelize'); const { AppError } = require('../../core/errors'); const { log: auditLog } = require('../../core/audit'); @@ -24,18 +25,24 @@ async function validateMimeType(filePath, allowedMimes) { return mime; } -async function getVideos(models, orgId, { category, page = 1, limit = 50 } = {}) { +async function getVideos(models, orgId, { category, search, page = 1, limit = 50 } = {}) { const where = { organizationId: orgId }; if (category) where.category = category; + if (search) where.description = { [Op.like]: `%${search}%` }; const offset = (page - 1) * limit; const { rows, count } = await models.Video.findAndCountAll({ where, limit, offset, order: [['createdAt', 'DESC']], }); + const uploadsDir = UPLOADS_DIR(); const base = '/api/v1/videos/stream/'; return { - rows: rows.map(v => ({ ...v.toJSON(), streamUrl: base + v.filename })), + rows: rows.map(v => ({ + ...v.toJSON(), + streamUrl: base + v.filename, + fileExists: fs.existsSync(path.join(uploadsDir, v.filename)), + })), count, }; } diff --git a/V2/app/public/audit-log.html b/V2/app/public/audit-log.html index 873579c..ed00420 100644 --- a/V2/app/public/audit-log.html +++ b/V2/app/public/audit-log.html @@ -74,9 +74,9 @@ const el = document.getElementById('pagination'); if (!meta || meta.totalPages <= 1) { el.innerHTML = ''; return; } el.innerHTML = ` - + Page ${meta.page} of ${meta.totalPages} - `; + `; } function changePage(p) { _page = p; loadLogs(); } @@ -98,6 +98,11 @@ }); } + document.getElementById('pagination').addEventListener('click', (e) => { + const btn = e.target.closest('button[data-action="page"]'); + if (btn) changePage(parseInt(btn.dataset.page, 10)); + }); + loadLogs(); let debounce; diff --git a/V2/app/public/calendar.html b/V2/app/public/calendar.html index c6ca1a9..3b703d9 100644 --- a/V2/app/public/calendar.html +++ b/V2/app/public/calendar.html @@ -92,7 +92,7 @@ ${new Date(s.endAt).toLocaleString()} ${s.status} - ${s.status === 'scheduled' ? `` : ''} + ${s.status === 'scheduled' ? `` : ''} `).join('')} `; @@ -113,6 +113,11 @@ document.addEventListener('DOMContentLoaded', async () => { await Page.init(['Owner', 'Coach']); + document.getElementById('session-list').addEventListener('click', (e) => { + const btn = e.target.closest('button[data-action="cancel"]'); + if (btn) cancelSession(parseInt(btn.dataset.id, 10)); + }); + // Default date range: today + 30 days const today = new Date(); const future = new Date(today); future.setDate(future.getDate() + 30); diff --git a/V2/app/public/categories.html b/V2/app/public/categories.html index e79e1ad..f4c0ab2 100644 --- a/V2/app/public/categories.html +++ b/V2/app/public/categories.html @@ -61,7 +61,7 @@ ${data.map(c => ` ${c.name} ${c.videoCount ?? '—'} - + `).join('')} `; } catch { @@ -80,6 +80,10 @@ document.addEventListener('DOMContentLoaded', async () => { await Page.init(['Owner', 'Coach']); + document.getElementById('cat-list').addEventListener('click', (e) => { + const btn = e.target.closest('button[data-action="delete"]'); + if (btn) deleteCategory(parseInt(btn.dataset.id, 10)); + }); loadCategories(); document.getElementById('add-form').addEventListener('submit', async (e) => { diff --git a/V2/app/public/client-profile.html b/V2/app/public/client-profile.html index 3cf40ec..eeb7032 100644 --- a/V2/app/public/client-profile.html +++ b/V2/app/public/client-profile.html @@ -91,7 +91,7 @@ ${cw.workout?.name || '—'} ${cw.status} ${cw.dueDate ? new Date(cw.dueDate).toLocaleDateString() : '—'} - + `).join('')} `; } catch { el.innerHTML = '

Failed to load.

'; } @@ -110,6 +110,11 @@ await Page.init(['Owner', 'Coach']); if (!clientId) { window.location.href = '/clients.html'; return; } + document.getElementById('client-workouts').addEventListener('click', (e) => { + const btn = e.target.closest('button[data-action="remove"]'); + if (btn) removeWorkout(parseInt(btn.dataset.id, 10)); + }); + // Load client info try { const res = await Api.get(`/api/v1/clients/${clientId}`); diff --git a/V2/app/public/clients.html b/V2/app/public/clients.html index 63f2702..ea5e1d8 100644 --- a/V2/app/public/clients.html +++ b/V2/app/public/clients.html @@ -71,15 +71,19 @@ const el = document.getElementById('pagination'); if (!meta || meta.totalPages <= 1) { el.innerHTML = ''; return; } el.innerHTML = ` - + Page ${meta.page} of ${meta.totalPages} - `; + `; } function changePage(p) { _page = p; loadClients(); } document.addEventListener('DOMContentLoaded', async () => { await Page.init(['Owner', 'Coach']); + document.getElementById('pagination').addEventListener('click', (e) => { + const btn = e.target.closest('button[data-action="page"]'); + if (btn) changePage(parseInt(btn.dataset.page, 10)); + }); loadClients(); let debounce; diff --git a/V2/app/public/create-crossfit.html b/V2/app/public/create-crossfit.html index ca79eba..4059449 100644 --- a/V2/app/public/create-crossfit.html +++ b/V2/app/public/create-crossfit.html @@ -84,8 +84,8 @@ el.innerHTML = _items.map((item, i) => `
- + data-action="edit" data-idx="${i}" style="flex:1;"> +
`).join(''); } @@ -95,6 +95,15 @@ await Page.init(['Owner', 'Coach']); renderItems(); + document.getElementById('items-list').addEventListener('change', (e) => { + const inp = e.target.closest('input[data-action="edit"]'); + if (inp) { const idx = parseInt(inp.dataset.idx, 10); if (_items[idx]) _items[idx].text = inp.value; } + }); + document.getElementById('items-list').addEventListener('click', (e) => { + const btn = e.target.closest('button[data-action="remove"]'); + if (btn) removeItem(parseInt(btn.dataset.idx, 10)); + }); + document.getElementById('add-item-btn').addEventListener('click', () => { _items.push({ type: 'text', text: '' }); renderItems(); diff --git a/V2/app/public/create-workout.html b/V2/app/public/create-workout.html index 19947ef..cf5bc84 100644 --- a/V2/app/public/create-workout.html +++ b/V2/app/public/create-workout.html @@ -42,7 +42,7 @@
-

Exercises

+

Exercises 0 / 4

@@ -54,13 +54,18 @@ `).join(''); @@ -70,6 +70,10 @@ document.addEventListener('DOMContentLoaded', async () => { await Page.init(['Client']); + document.getElementById('schedule-list').addEventListener('click', (e) => { + const btn = e.target.closest('button[data-action="cancel"]'); + if (btn) cancelSession(parseInt(btn.dataset.id, 10)); + }); loadSchedule(); }); diff --git a/V2/app/public/my-workouts.html b/V2/app/public/my-workouts.html index 854c481..6eec430 100644 --- a/V2/app/public/my-workouts.html +++ b/V2/app/public/my-workouts.html @@ -57,7 +57,7 @@
${cw.status} - ${cw.status !== 'completed' ? `` : ''} + ${cw.status !== 'completed' ? `` : ''}
${cw.workout?.videos?.length ? `

${cw.workout.videos.length} exercises

` : ''} @@ -78,6 +78,10 @@ document.addEventListener('DOMContentLoaded', async () => { await Page.init(['Client']); + document.getElementById('workout-list').addEventListener('click', (e) => { + const btn = e.target.closest('button[data-action="complete"]'); + if (btn) markComplete(parseInt(btn.dataset.id, 10)); + }); loadMyWorkouts(); document.querySelectorAll('.tab').forEach(btn => { diff --git a/V2/app/public/settings.html b/V2/app/public/settings.html index aa84749..1b77aab 100644 --- a/V2/app/public/settings.html +++ b/V2/app/public/settings.html @@ -135,8 +135,8 @@ ${u.isActive ? 'Active' : 'Inactive'} ${u.isActive - ? `` - : ``} + ? `` + : ``} `).join('')} `; @@ -154,6 +154,11 @@ document.addEventListener('DOMContentLoaded', async () => { await Page.init(['Owner']); + document.getElementById('user-list').addEventListener('click', (e) => { + const btn = e.target.closest('button[data-action="toggle"]'); + if (btn) toggleUser(parseInt(btn.dataset.id, 10), btn.dataset.active === 'true'); + }); + // Tab switching document.querySelectorAll('.tab').forEach(btn => { btn.addEventListener('click', () => { diff --git a/V2/app/public/styles/components.css b/V2/app/public/styles/components.css index 535403f..9e25db3 100644 --- a/V2/app/public/styles/components.css +++ b/V2/app/public/styles/components.css @@ -186,6 +186,92 @@ gap: var(--space-3); } +/* ── Workout slot rows ───────────────────────────────────────────────────── */ +.slot-row { + display: flex; + align-items: center; + gap: var(--space-3); + padding: var(--space-3) 0; + border-bottom: 1px solid var(--surface-border); +} +.slot-row:last-child { border-bottom: none; } +.slot-num { + width: 24px; + text-align: center; + font-size: var(--text-sm); + font-weight: var(--weight-semibold); + color: var(--text-muted); + flex-shrink: 0; +} +.slot-video-name { + font-size: var(--text-sm); + font-weight: var(--weight-medium); + color: var(--text-primary); +} + +/* ── Modal overlay (backdrop used by all modals) ─────────────────────────── */ +.modal-overlay { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.65); + z-index: var(--z-modal); + display: flex; + align-items: center; + justify-content: center; + padding: var(--space-4); +} +.modal-wide { max-width: 780px; } +.modal-scroll { + overflow-y: auto; + max-height: 52vh; + padding: var(--space-1); +} + +/* ── Modal video picker grid ─────────────────────────────────────────────── */ +.modal-video-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); + gap: var(--space-3); +} +.modal-video-card { + border: 2px solid var(--surface-border); + border-radius: var(--radius-md); + overflow: hidden; + cursor: pointer; + transition: border-color var(--transition-fast), box-shadow var(--transition-fast); + background: var(--surface-card); +} +.modal-video-card:hover { + border-color: var(--color-primary); + box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-primary) 20%, transparent); +} +.modal-video-thumb { + width: 100%; + aspect-ratio: 16/9; + background: #000; + overflow: hidden; + position: relative; +} +.modal-video-thumb video { + width: 100%; + height: 100%; + object-fit: cover; + display: block; + pointer-events: none; +} +.modal-video-info { + padding: var(--space-2) var(--space-3); +} +.modal-video-name { + font-size: var(--text-xs); + font-weight: var(--weight-semibold); + color: var(--text-primary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + margin-bottom: var(--space-1); +} + /* ── Toast ───────────────────────────────────────────────────────────────── */ #toast-container { position: fixed; @@ -252,14 +338,53 @@ th { tr:last-child td { border-bottom: none; } tr:hover td { background: var(--surface-hover); } -/* ── Video card ──────────────────────────────────────────────────────────── */ -.video-card { overflow: hidden; } -.video-card video { +/* ── Video grid & cards ──────────────────────────────────────────────────── */ +.video-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); + gap: var(--space-5); +} +.video-card { + background: var(--surface-card); + border: 1px solid var(--surface-border); + border-radius: var(--radius-md); + overflow: hidden; +} +.video-card-player { width: 100%; aspect-ratio: 16/9; background: #000; - border-radius: var(--radius-sm); - margin-bottom: var(--space-3); + position: relative; + overflow: hidden; +} +.video-card-player video { + width: 100%; + height: 100%; + display: block; + object-fit: contain; + background: #000; +} +.video-missing-placeholder { + width: 100%; + height: 100%; + display: flex; + align-items: center; + justify-content: center; + background: var(--surface-hover); + color: var(--text-muted); + font-size: var(--text-sm); +} +.video-card-body { + padding: var(--space-3) var(--space-4); +} +.video-card-title { + font-size: var(--text-sm); + font-weight: var(--weight-semibold); + color: var(--text-primary); + margin-bottom: var(--space-1); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; } /* ── Upload progress ─────────────────────────────────────────────────────── */ diff --git a/V2/app/public/styles/display.css b/V2/app/public/styles/display.css index 0f45560..ad7532e 100644 --- a/V2/app/public/styles/display.css +++ b/V2/app/public/styles/display.css @@ -102,28 +102,85 @@ html, body { .phase-idle .display-status-label { color: var(--color-idle); } .phase-warning .display-status-label { color: var(--color-warning); } -/* ── Workout display ─────────────────────────────────────────────────────── */ -.display-workout-list { +/* ── Workout video pane grid ─────────────────────────────────────────────── */ +.display-video-grid { + flex: 1; + display: grid; + gap: 3px; + background: #000; + min-height: 0; +} +.display-video-grid.panes-1 { + grid-template-columns: 1fr; + grid-template-rows: 1fr; +} +.display-video-grid.panes-2 { + grid-template-columns: 1fr 1fr; + grid-template-rows: 1fr; +} +.display-video-grid.panes-3, +.display-video-grid.panes-4 { + grid-template-columns: 1fr 1fr; + grid-template-rows: 1fr 1fr; +} + +.display-pane { + position: relative; + background: #111; + overflow: hidden; + min-height: 0; +} +.display-pane-video { width: 100%; - max-width: 800px; - list-style: none; + height: 100%; + object-fit: cover; + display: block; } -.display-workout-item { +.display-pane-missing { + width: 100%; + height: 100%; display: flex; - align-items: baseline; - justify-content: space-between; - padding: var(--space-5) 0; - border-bottom: 1px solid rgba(255,255,255,0.08); - font-size: var(--display-font-body); - font-weight: var(--weight-medium); + align-items: center; + justify-content: center; + color: rgba(255,255,255,0.3); + font-size: var(--display-font-label); } -.display-workout-item:last-child { border-bottom: none; } -.display-workout-item-name { flex: 1; } -.display-workout-item-reps { +.display-pane-corner { + position: absolute; + top: var(--space-4); + left: var(--space-5); + font-size: var(--display-font-primary); + font-weight: var(--weight-black); + color: #fff; + text-shadow: 0 2px 12px rgba(0,0,0,0.9); + line-height: 1; + font-variant-numeric: tabular-nums; +} +.display-pane-overlay { + position: absolute; + bottom: 0; + left: 0; + right: 0; + padding: var(--space-4) var(--space-6); + background: linear-gradient(transparent, rgba(0,0,0,0.72)); +} +.display-pane-name { font-size: var(--display-font-label); font-weight: var(--weight-bold); - color: var(--color-primary); - margin-left: var(--space-8); + color: #fff; + text-shadow: 0 1px 4px rgba(0,0,0,0.8); + text-transform: uppercase; + letter-spacing: 0.05em; + line-height: 1.1; +} +.display-no-videos { + width: 100%; + height: 100%; + display: flex; + align-items: center; + justify-content: center; + font-size: var(--display-font-body); + color: rgba(255,255,255,0.4); } /* ── CrossFit display ────────────────────────────────────────────────────── */ diff --git a/V2/app/public/sw.js b/V2/app/public/sw.js index 380b65c..9ea68fd 100644 --- a/V2/app/public/sw.js +++ b/V2/app/public/sw.js @@ -1,7 +1,7 @@ /* VitFit Service Worker — shell-only caching for PWA install */ 'use strict'; -const CACHE_NAME = 'vitfit-v3'; +const CACHE_NAME = 'vitfit-v8'; const SHELL_ASSETS = [ '/', '/index.html', @@ -9,8 +9,10 @@ const SHELL_ASSETS = [ '/styles/base.css', '/styles/layout.css', '/styles/components.css', + '/styles/display.css', '/js/core.js', '/js/socket-client.js', + '/js/display.js', '/manifest.json', ]; diff --git a/V2/app/public/sysadmin.html b/V2/app/public/sysadmin.html index 82273dd..6f8710f 100644 --- a/V2/app/public/sysadmin.html +++ b/V2/app/public/sysadmin.html @@ -85,14 +85,21 @@ if (!res.ok) throw new Error(); const { data } = await res.json(); if (!data.length) { el.innerHTML = '

No organisations.

'; return; } - el.innerHTML = ` + el.innerHTML = `
NameSlugCreatedFeatures
${data.map(o => ` + `).join('')}
NameSlugCreatedFeatures
${o.name} ${o.slug} ${new Date(o.createdAt).toLocaleDateString()} ${(o.features || []).join(', ') || '—'}
`; + el.addEventListener('click', (e) => { + const btn = e.target.closest('button[data-org-id]'); + if (!btn) return; + Auth.setSelectedOrg({ id: parseInt(btn.dataset.orgId, 10), name: btn.dataset.orgName }); + window.location.href = '/dashboard.html'; + }); } catch { el.innerHTML = '

Failed to load.

'; } } diff --git a/V2/app/public/timers.html b/V2/app/public/timers.html index 9350b53..5a73588 100644 --- a/V2/app/public/timers.html +++ b/V2/app/public/timers.html @@ -78,7 +78,7 @@ ${t.timerType} ${timerSummary(t)} - + `).join('')} `; @@ -117,6 +117,10 @@ document.addEventListener('DOMContentLoaded', async () => { await Page.init(['Owner', 'Coach']); + document.getElementById('timer-list').addEventListener('click', (e) => { + const btn = e.target.closest('button[data-action="launch"]'); + if (btn) launchTimer(parseInt(btn.dataset.id, 10), btn.dataset.name); + }); loadActiveSession(); loadTimers(); diff --git a/V2/app/public/upload-video.html b/V2/app/public/upload-video.html index d4f7d66..f784f50 100644 --- a/V2/app/public/upload-video.html +++ b/V2/app/public/upload-video.html @@ -80,7 +80,7 @@ const sel = document.getElementById('category-id'); data.forEach(c => { const opt = document.createElement('option'); - opt.value = c.id; opt.textContent = c.name; + opt.value = c.name; opt.textContent = c.name; sel.appendChild(opt); }); } @@ -102,7 +102,7 @@ fd.append('video', file); fd.append('description', document.getElementById('description').value.trim()); const catId = document.getElementById('category-id').value; - if (catId) fd.append('categoryId', catId); + if (catId) fd.append('category', catId); const thumb = document.getElementById('thumbnail').files[0]; if (thumb) fd.append('thumbnail', thumb); diff --git a/V2/app/public/videos.html b/V2/app/public/videos.html index 068f660..deaa035 100644 --- a/V2/app/public/videos.html +++ b/V2/app/public/videos.html @@ -53,22 +53,33 @@ async function loadVideos() { const grid = document.getElementById('video-grid'); try { - const res = await Api.get('/api/v1/videos', { page: _page, limit: 20, search: _search, categoryId: _category }); + const res = await Api.get('/api/v1/videos', { page: _page, limit: 20, search: _search, category: _category }); if (!res.ok) { grid.innerHTML = '

Failed to load.

'; return; } const { data, meta } = await res.json(); if (!data.length) { grid.innerHTML = '

No videos found.

'; return; } + const jwt = Auth.getJwt(); + const selectedOrg = Auth.getSelectedOrg(); + const orgParam = selectedOrg ? `&orgId=${selectedOrg.id}` : ''; grid.innerHTML = data.map(v => `
-
- ${v.thumbnailPath ? `` : '
'} +
+ ${v.fileExists + ? `` + : `
Missing Video
`}

${v.description || 'Untitled'}

- ${v.category ? `${v.category.name}` : ''} + ${v.category ? `${v.category}` : ''}
`).join(''); + grid.querySelectorAll('video').forEach(vid => { + vid.addEventListener('error', () => { + vid.closest('.video-card-player').innerHTML = `
Missing Video
`; + }); + }); + renderPagination(meta); } catch { grid.innerHTML = '

Error loading videos.

'; @@ -79,9 +90,9 @@ const el = document.getElementById('pagination'); if (!meta || meta.totalPages <= 1) { el.innerHTML = ''; return; } el.innerHTML = ` - + Page ${meta.page} of ${meta.totalPages} - `; + `; } function changePage(p) { _page = p; loadVideos(); } @@ -97,7 +108,7 @@ const sel = document.getElementById('category-filter'); data.forEach(c => { const opt = document.createElement('option'); - opt.value = c.id; opt.textContent = c.name; + opt.value = c.name; opt.textContent = c.name; sel.appendChild(opt); }); } @@ -112,6 +123,11 @@ }); catFilter.addEventListener('change', () => { _category = catFilter.value; _page = 1; loadVideos(); }); + document.getElementById('pagination').addEventListener('click', (e) => { + const btn = e.target.closest('button[data-action="page"]'); + if (btn) changePage(parseInt(btn.dataset.page, 10)); + }); + loadVideos(); }); diff --git a/V2/app/public/workout-display.html b/V2/app/public/workout-display.html index ab174af..95f33a2 100644 --- a/V2/app/public/workout-display.html +++ b/V2/app/public/workout-display.html @@ -8,18 +8,12 @@ -
+
Loading…
- -
-
    -
    - -
    -
    +
    Offline — last known data shown
    @@ -34,7 +28,6 @@ Display.startKeepAlive(); - // Load branding without full auth gate try { const res = await fetch('/api/v1/org/branding/public'); if (res.ok) { const { data } = await res.json(); Display.applyBranding(data); } @@ -43,16 +36,21 @@ async function load() { try { const jwt = Auth.getJwt(); - const headers = jwt ? { Authorization: `Bearer ${jwt}` } : {}; + const selectedOrg = Auth.getSelectedOrg(); + const headers = {}; + if (jwt) headers['Authorization'] = `Bearer ${jwt}`; + if (selectedOrg) headers['X-Org-Id'] = String(selectedOrg.id); const res = await fetch(`/api/v1/workouts/${id}`, { headers }); - if (!res.ok) return; + if (!res.ok) { + document.getElementById('display-workout-name').textContent = 'Workout not found.'; + return; + } const { data } = await res.json(); Display.renderWorkout(data); } catch { Display.setOffline(true); } } load(); - // Refresh every 30s to stay in sync setInterval(load, 30000); }); diff --git a/V2/app/public/workouts.html b/V2/app/public/workouts.html index 5e36166..f129aba 100644 --- a/V2/app/public/workouts.html +++ b/V2/app/public/workouts.html @@ -73,15 +73,19 @@ const el = document.getElementById('pagination'); if (!meta || meta.totalPages <= 1) { el.innerHTML = ''; return; } el.innerHTML = ` - + Page ${meta.page} of ${meta.totalPages} - `; + `; } function changePage(p) { _page = p; loadWorkouts(); } document.addEventListener('DOMContentLoaded', async () => { await Page.init(['Owner', 'Coach']); + document.getElementById('pagination').addEventListener('click', (e) => { + const btn = e.target.closest('button[data-action="page"]'); + if (btn) changePage(parseInt(btn.dataset.page, 10)); + }); loadWorkouts(); let debounce; diff --git a/V2/app/vitfit.sqlite-shm b/V2/app/vitfit.sqlite-shm index 4f38b0e..11662a9 100644 Binary files a/V2/app/vitfit.sqlite-shm and b/V2/app/vitfit.sqlite-shm differ diff --git a/V2/app/vitfit.sqlite-wal b/V2/app/vitfit.sqlite-wal index 452ce9b..68fee31 100644 Binary files a/V2/app/vitfit.sqlite-wal and b/V2/app/vitfit.sqlite-wal differ