r2.2
This commit is contained in:
+11
-3
@@ -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);
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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); });
|
||||
@@ -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,
|
||||
|
||||
@@ -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); }
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -74,9 +74,9 @@
|
||||
const el = document.getElementById('pagination');
|
||||
if (!meta || meta.totalPages <= 1) { el.innerHTML = ''; return; }
|
||||
el.innerHTML = `
|
||||
<button class="btn btn-ghost btn-sm" ${_page <= 1 ? 'disabled' : ''} onclick="changePage(${_page - 1})">Previous</button>
|
||||
<button class="btn btn-ghost btn-sm" ${_page <= 1 ? 'disabled' : ''} data-action="page" data-page="${_page - 1}">Previous</button>
|
||||
<span class="pagination-info">Page ${meta.page} of ${meta.totalPages}</span>
|
||||
<button class="btn btn-ghost btn-sm" ${_page >= meta.totalPages ? 'disabled' : ''} onclick="changePage(${_page + 1})">Next</button>`;
|
||||
<button class="btn btn-ghost btn-sm" ${_page >= meta.totalPages ? 'disabled' : ''} data-action="page" data-page="${_page + 1}">Next</button>`;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
@@ -92,7 +92,7 @@
|
||||
<td>${new Date(s.endAt).toLocaleString()}</td>
|
||||
<td><span class="badge badge-${s.status === 'scheduled' ? 'default' : s.status === 'completed' ? 'success' : 'danger'}">${s.status}</span></td>
|
||||
<td class="table-actions">
|
||||
${s.status === 'scheduled' ? `<button class="btn btn-danger btn-sm" onclick="cancelSession(${s.id})">Cancel</button>` : ''}
|
||||
${s.status === 'scheduled' ? `<button class="btn btn-danger btn-sm" data-action="cancel" data-id="${s.id}">Cancel</button>` : ''}
|
||||
</td>
|
||||
</tr>`).join('')}
|
||||
</tbody></table>`;
|
||||
@@ -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);
|
||||
|
||||
@@ -61,7 +61,7 @@
|
||||
${data.map(c => `<tr>
|
||||
<td>${c.name}</td>
|
||||
<td>${c.videoCount ?? '—'}</td>
|
||||
<td><button class="btn btn-danger btn-sm" onclick="deleteCategory(${c.id})">Delete</button></td>
|
||||
<td><button class="btn btn-danger btn-sm" data-action="delete" data-id="${c.id}">Delete</button></td>
|
||||
</tr>`).join('')}
|
||||
</tbody></table>`;
|
||||
} 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) => {
|
||||
|
||||
@@ -91,7 +91,7 @@
|
||||
<td>${cw.workout?.name || '—'}</td>
|
||||
<td><span class="badge badge-${cw.status === 'completed' ? 'success' : 'default'}">${cw.status}</span></td>
|
||||
<td>${cw.dueDate ? new Date(cw.dueDate).toLocaleDateString() : '—'}</td>
|
||||
<td><button class="btn btn-danger btn-sm" onclick="removeWorkout(${cw.id})">Remove</button></td>
|
||||
<td><button class="btn btn-danger btn-sm" data-action="remove" data-id="${cw.id}">Remove</button></td>
|
||||
</tr>`).join('')}
|
||||
</tbody></table>`;
|
||||
} catch { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Failed to load.</p></div>'; }
|
||||
@@ -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}`);
|
||||
|
||||
@@ -71,15 +71,19 @@
|
||||
const el = document.getElementById('pagination');
|
||||
if (!meta || meta.totalPages <= 1) { el.innerHTML = ''; return; }
|
||||
el.innerHTML = `
|
||||
<button class="btn btn-ghost btn-sm" ${_page <= 1 ? 'disabled' : ''} onclick="changePage(${_page - 1})">Previous</button>
|
||||
<button class="btn btn-ghost btn-sm" ${_page <= 1 ? 'disabled' : ''} data-action="page" data-page="${_page - 1}">Previous</button>
|
||||
<span class="pagination-info">Page ${meta.page} of ${meta.totalPages}</span>
|
||||
<button class="btn btn-ghost btn-sm" ${_page >= meta.totalPages ? 'disabled' : ''} onclick="changePage(${_page + 1})">Next</button>`;
|
||||
<button class="btn btn-ghost btn-sm" ${_page >= meta.totalPages ? 'disabled' : ''} data-action="page" data-page="${_page + 1}">Next</button>`;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
@@ -84,8 +84,8 @@
|
||||
el.innerHTML = _items.map((item, i) => `
|
||||
<div class="slot-row" data-idx="${i}">
|
||||
<input class="form-input" type="text" value="${item.text?.replace(/"/g, '"') || ''}" placeholder="e.g. 21 Thrusters 95/65 lb" maxlength="200"
|
||||
onchange="_items[${i}].text = this.value" style="flex:1;">
|
||||
<button class="btn btn-danger btn-sm" type="button" onclick="removeItem(${i})">Remove</button>
|
||||
data-action="edit" data-idx="${i}" style="flex:1;">
|
||||
<button class="btn btn-danger btn-sm" type="button" data-action="remove" data-idx="${i}">Remove</button>
|
||||
</div>`).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();
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
|
||||
<div class="card" style="margin-bottom:var(--space-6);">
|
||||
<div class="card-header">
|
||||
<h2 class="card-title">Exercises</h2>
|
||||
<h2 class="card-title">Exercises <span id="slot-count" class="badge" style="font-size:var(--text-xs);margin-left:var(--space-2);">0 / 4</span></h2>
|
||||
<button class="btn btn-secondary btn-sm" type="button" id="add-slot-btn">+ Add Exercise</button>
|
||||
</div>
|
||||
<div id="slots-list"></div>
|
||||
@@ -54,13 +54,18 @@
|
||||
|
||||
<!-- Video picker modal -->
|
||||
<div class="modal-overlay" id="video-modal" style="display:none;">
|
||||
<div class="modal">
|
||||
<div class="modal modal-wide">
|
||||
<div class="modal-header">
|
||||
<h2 class="modal-title">Pick a Video</h2>
|
||||
<button class="modal-close" id="modal-close">×</button>
|
||||
</div>
|
||||
<input class="form-input" type="search" id="modal-search" placeholder="Search videos…" style="margin-bottom:var(--space-4);">
|
||||
<div id="modal-video-list" class="modal-scroll"></div>
|
||||
<div style="padding:var(--space-4) var(--space-6) var(--space-3);display:flex;gap:var(--space-3);">
|
||||
<input class="form-input" type="search" id="modal-search" placeholder="Search videos…" style="flex:1;">
|
||||
<select class="form-select" id="modal-category" style="width:180px;">
|
||||
<option value="">All Categories</option>
|
||||
</select>
|
||||
</div>
|
||||
<div id="modal-video-list" class="modal-scroll modal-video-grid" style="padding:0 var(--space-6) var(--space-6);"></div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
@@ -71,64 +76,124 @@
|
||||
|
||||
<script src="/js/core.js"></script>
|
||||
<script>
|
||||
const MAX_SLOTS = 4;
|
||||
let _slots = [];
|
||||
let _videos = [];
|
||||
let _pickingSlotIdx = null;
|
||||
|
||||
function renderSlots() {
|
||||
const el = document.getElementById('slots-list');
|
||||
if (!_slots.length) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">No exercises yet.</p></div>'; return; }
|
||||
document.getElementById('slot-count').textContent = `${_slots.length} / ${MAX_SLOTS}`;
|
||||
document.getElementById('add-slot-btn').disabled = _slots.length >= MAX_SLOTS;
|
||||
|
||||
if (!_slots.length) {
|
||||
el.innerHTML = '<div class="empty-state"><p class="empty-state-text">No exercises yet. Add up to 4.</p></div>';
|
||||
return;
|
||||
}
|
||||
el.innerHTML = _slots.map((s, i) => `
|
||||
<div class="slot-row" data-idx="${i}">
|
||||
<div class="slot-pick">
|
||||
<span class="slot-num">${i + 1}</span>
|
||||
<div class="slot-pick" style="flex:1;">
|
||||
${s.video
|
||||
? `<span class="slot-video-name">${s.video.description}</span>`
|
||||
: `<button class="btn btn-ghost btn-sm" type="button" onclick="openPicker(${i})">Pick Video</button>`}
|
||||
? `<span class="slot-video-name">${s.video.description}</span>
|
||||
<button class="btn btn-ghost btn-sm" type="button" data-action="pick" data-idx="${i}" style="margin-left:var(--space-2);">Change</button>`
|
||||
: `<button class="btn btn-ghost btn-sm" type="button" data-action="pick" data-idx="${i}">Pick Video</button>`}
|
||||
</div>
|
||||
<input class="form-input slot-reps" type="number" placeholder="Reps" min="1" value="${s.reps || ''}" onchange="updateReps(${i}, this.value)" style="width:90px;">
|
||||
<input class="form-input slot-sets" type="number" placeholder="Sets" min="1" value="${s.sets || ''}" onchange="updateSets(${i}, this.value)" style="width:90px;">
|
||||
<button class="btn btn-danger btn-sm" type="button" onclick="removeSlot(${i})">Remove</button>
|
||||
<input class="form-input slot-reps" type="number" placeholder="Reps" min="1" value="${s.reps || ''}" data-action="reps" data-idx="${i}" style="width:80px;">
|
||||
<button class="btn btn-danger btn-sm" type="button" data-action="remove" data-idx="${i}">✕</button>
|
||||
</div>`).join('');
|
||||
}
|
||||
|
||||
function openPicker(idx) {
|
||||
_pickingSlotIdx = idx;
|
||||
document.getElementById('modal-search').value = '';
|
||||
document.getElementById('modal-category').value = '';
|
||||
document.getElementById('video-modal').style.display = 'flex';
|
||||
loadModalVideos('');
|
||||
loadModalVideos();
|
||||
}
|
||||
|
||||
async function loadModalVideos(search) {
|
||||
async function loadModalVideos() {
|
||||
const el = document.getElementById('modal-video-list');
|
||||
el.innerHTML = '<p class="text-secondary">Loading…</p>';
|
||||
const search = document.getElementById('modal-search').value.trim();
|
||||
const category = document.getElementById('modal-category').value;
|
||||
el.innerHTML = '<p class="text-secondary" style="grid-column:1/-1;padding:var(--space-4);">Loading…</p>';
|
||||
try {
|
||||
const res = await Api.get('/api/v1/videos', { limit: 50, search });
|
||||
const jwt = Auth.getJwt();
|
||||
const selectedOrg = Auth.getSelectedOrg();
|
||||
const orgParam = selectedOrg ? `&orgId=${selectedOrg.id}` : '';
|
||||
|
||||
const res = await Api.get('/api/v1/videos', { limit: 60, search: search || undefined, category: category || undefined });
|
||||
if (!res.ok) throw new Error();
|
||||
const { data } = await res.json();
|
||||
if (!data.length) { el.innerHTML = '<p class="text-secondary">No videos found.</p>'; return; }
|
||||
if (!data.length) {
|
||||
el.innerHTML = '<p class="text-secondary" style="grid-column:1/-1;padding:var(--space-4);">No videos found.</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
el.innerHTML = data.map(v => `
|
||||
<div class="modal-video-item" onclick="selectVideo(${v.id}, '${v.description?.replace(/'/g, "\\'")}')">
|
||||
${v.description || 'Untitled'}
|
||||
<div class="modal-video-card" data-video-id="${v.id}" data-video-desc="${(v.description || '').replace(/"/g, '"')}">
|
||||
<div class="modal-video-thumb">
|
||||
${v.fileExists
|
||||
? `<video preload="metadata" src="${v.streamUrl}?token=${encodeURIComponent(jwt)}${orgParam}" muted></video>`
|
||||
: `<div class="video-missing-placeholder"><span>Missing</span></div>`}
|
||||
</div>
|
||||
<div class="modal-video-info">
|
||||
<p class="modal-video-name">${v.description || 'Untitled'}</p>
|
||||
${v.category ? `<span class="badge" style="font-size:10px;">${v.category}</span>` : ''}
|
||||
</div>
|
||||
</div>`).join('');
|
||||
} catch { el.innerHTML = '<p class="text-secondary">Failed to load.</p>'; }
|
||||
}
|
||||
|
||||
function selectVideo(id, description) {
|
||||
if (_pickingSlotIdx === null) return;
|
||||
_slots[_pickingSlotIdx].video = { id, description };
|
||||
document.getElementById('video-modal').style.display = 'none';
|
||||
renderSlots();
|
||||
el.querySelectorAll('video').forEach(vid => {
|
||||
vid.addEventListener('error', () => {
|
||||
vid.closest('.modal-video-thumb').innerHTML = '<div class="video-missing-placeholder"><span>Missing</span></div>';
|
||||
});
|
||||
});
|
||||
} catch {
|
||||
el.innerHTML = '<p class="text-secondary" style="grid-column:1/-1;padding:var(--space-4);">Failed to load videos.</p>';
|
||||
}
|
||||
}
|
||||
|
||||
function updateReps(idx, val) { _slots[idx].reps = val ? parseInt(val) : null; }
|
||||
function updateSets(idx, val) { _slots[idx].sets = val ? parseInt(val) : null; }
|
||||
function removeSlot(idx) { _slots.splice(idx, 1); renderSlots(); }
|
||||
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
await Page.init(['Owner', 'Coach']);
|
||||
renderSlots();
|
||||
|
||||
// Load categories for modal filter
|
||||
try {
|
||||
const res = await Api.get('/api/v1/categories');
|
||||
if (res.ok) {
|
||||
const { data } = await res.json();
|
||||
const sel = document.getElementById('modal-category');
|
||||
data.forEach(c => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = c.name; opt.textContent = c.name;
|
||||
sel.appendChild(opt);
|
||||
});
|
||||
}
|
||||
} catch {}
|
||||
|
||||
document.getElementById('add-slot-btn').addEventListener('click', () => {
|
||||
_slots.push({ video: null, reps: null, sets: null });
|
||||
if (_slots.length >= MAX_SLOTS) return;
|
||||
_slots.push({ video: null, reps: null });
|
||||
renderSlots();
|
||||
});
|
||||
|
||||
document.getElementById('slots-list').addEventListener('click', (e) => {
|
||||
const btn = e.target.closest('button[data-action]');
|
||||
if (!btn) return;
|
||||
const idx = parseInt(btn.dataset.idx, 10);
|
||||
if (btn.dataset.action === 'pick') openPicker(idx);
|
||||
if (btn.dataset.action === 'remove') { _slots.splice(idx, 1); renderSlots(); }
|
||||
});
|
||||
|
||||
document.getElementById('slots-list').addEventListener('change', (e) => {
|
||||
const input = e.target.closest('input[data-action="reps"]');
|
||||
if (input) { const idx = parseInt(input.dataset.idx, 10); _slots[idx].reps = input.value ? parseInt(input.value) : null; }
|
||||
});
|
||||
|
||||
document.getElementById('modal-video-list').addEventListener('click', (e) => {
|
||||
const card = e.target.closest('[data-video-id]');
|
||||
if (!card || _pickingSlotIdx === null) return;
|
||||
_slots[_pickingSlotIdx].video = { id: parseInt(card.dataset.videoId, 10), description: card.dataset.videoDesc };
|
||||
document.getElementById('video-modal').style.display = 'none';
|
||||
renderSlots();
|
||||
});
|
||||
|
||||
@@ -137,10 +202,10 @@
|
||||
});
|
||||
|
||||
let debounce;
|
||||
document.getElementById('modal-search').addEventListener('input', (e) => {
|
||||
clearTimeout(debounce);
|
||||
debounce = setTimeout(() => loadModalVideos(e.target.value), 300);
|
||||
document.getElementById('modal-search').addEventListener('input', () => {
|
||||
clearTimeout(debounce); debounce = setTimeout(loadModalVideos, 300);
|
||||
});
|
||||
document.getElementById('modal-category').addEventListener('change', loadModalVideos);
|
||||
|
||||
document.getElementById('workout-form').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
@@ -155,11 +220,14 @@
|
||||
name,
|
||||
workoutDate: document.getElementById('workout-date').value || null,
|
||||
notes: document.getElementById('notes').value.trim() || null,
|
||||
slots: _slots.filter(s => s.video).map((s, i) => ({
|
||||
videoId: s.video.id, order: i, reps: s.reps, sets: s.sets
|
||||
})),
|
||||
};
|
||||
|
||||
// Map slots → video1..4 / number1..4
|
||||
_slots.filter(s => s.video).slice(0, MAX_SLOTS).forEach((s, i) => {
|
||||
payload[`video${i + 1}`] = s.video.id;
|
||||
if (s.reps) payload[`number${i + 1}`] = s.reps;
|
||||
});
|
||||
|
||||
btn.disabled = true; btn.textContent = 'Saving…';
|
||||
try {
|
||||
const res = await Api.post('/api/v1/workouts', payload);
|
||||
|
||||
@@ -54,7 +54,7 @@
|
||||
<td>${w.wodType || '—'}</td>
|
||||
<td class="table-actions">
|
||||
<a href="/crossfit-display.html?id=${w.id}" class="btn btn-ghost btn-sm" target="_blank">Display</a>
|
||||
<button class="btn btn-danger btn-sm" onclick="deleteWod(${w.id})">Delete</button>
|
||||
<button class="btn btn-danger btn-sm" data-action="delete" data-id="${w.id}">Delete</button>
|
||||
</td>
|
||||
</tr>`).join('')}
|
||||
</tbody></table>`;
|
||||
@@ -69,9 +69,9 @@
|
||||
const el = document.getElementById('pagination');
|
||||
if (!meta || meta.totalPages <= 1) { el.innerHTML = ''; return; }
|
||||
el.innerHTML = `
|
||||
<button class="btn btn-ghost btn-sm" ${_page <= 1 ? 'disabled' : ''} onclick="changePage(${_page - 1})">Previous</button>
|
||||
<button class="btn btn-ghost btn-sm" ${_page <= 1 ? 'disabled' : ''} data-action="page" data-page="${_page - 1}">Previous</button>
|
||||
<span class="pagination-info">Page ${meta.page} of ${meta.totalPages}</span>
|
||||
<button class="btn btn-ghost btn-sm" ${_page >= meta.totalPages ? 'disabled' : ''} onclick="changePage(${_page + 1})">Next</button>`;
|
||||
<button class="btn btn-ghost btn-sm" ${_page >= meta.totalPages ? 'disabled' : ''} data-action="page" data-page="${_page + 1}">Next</button>`;
|
||||
}
|
||||
|
||||
function changePage(p) { _page = p; loadWods(); }
|
||||
@@ -87,6 +87,14 @@
|
||||
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
await Page.init(['Owner', 'Coach']);
|
||||
document.getElementById('wod-list').addEventListener('click', (e) => {
|
||||
const btn = e.target.closest('button[data-action="delete"]');
|
||||
if (btn) deleteWod(parseInt(btn.dataset.id, 10));
|
||||
});
|
||||
document.getElementById('pagination').addEventListener('click', (e) => {
|
||||
const btn = e.target.closest('button[data-action="page"]');
|
||||
if (btn) changePage(parseInt(btn.dataset.page, 10));
|
||||
});
|
||||
loadWods();
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -76,21 +76,27 @@
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
await Page.init(['Owner', 'Coach']);
|
||||
|
||||
// Load today's workout
|
||||
// Load today's workouts
|
||||
try {
|
||||
const res = await Api.get('/api/v1/workouts/today');
|
||||
if (res.ok) {
|
||||
const { data } = await res.json();
|
||||
if (data?.length) {
|
||||
const w = data[0];
|
||||
document.getElementById('today-workout-body').innerHTML = `
|
||||
<div class="card-body">
|
||||
<p class="text-lg font-bold">${w.name}</p>
|
||||
<p class="text-secondary">${w.videos?.length ?? 0} exercises</p>
|
||||
<div class="mt-4 flex gap-3">
|
||||
<a href="/workout-view.html?id=${w.id}" class="btn btn-primary btn-sm">View</a>
|
||||
<a href="/workout-display.html?id=${w.id}" class="btn btn-ghost btn-sm" target="_blank">Display</a>
|
||||
document.getElementById('today-workout-body').innerHTML = data.map(w => `
|
||||
<div style="padding:var(--space-4) 0;border-bottom:1px solid var(--surface-border);">
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;gap:var(--space-3);">
|
||||
<div>
|
||||
<p style="font-weight:var(--weight-semibold);">${w.name}</p>
|
||||
<p class="card-meta">${w.videos?.length ?? 0} exercise${w.videos?.length !== 1 ? 's' : ''}</p>
|
||||
</div>
|
||||
<div style="display:flex;gap:var(--space-2);flex-shrink:0;">
|
||||
<a href="/workout-view.html?id=${w.id}" class="btn btn-ghost btn-sm">View</a>
|
||||
<a href="/workout-display.html?id=${w.id}" class="btn btn-primary btn-sm" target="_blank">Display</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>`).join('') +
|
||||
`<div style="padding-top:var(--space-3);">
|
||||
<a href="/create-workout.html" class="btn btn-ghost btn-sm">+ Add Another</a>
|
||||
</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 413 B |
Binary file not shown.
|
After Width: | Height: | Size: 1.5 KiB |
+80
-39
@@ -5,12 +5,25 @@
|
||||
const Auth = (() => {
|
||||
const JWT_KEY = 'vf_jwt';
|
||||
const DEVICE_KEY = 'vf_device';
|
||||
const ORG_KEY = 'vf_selected_org';
|
||||
|
||||
function getJwt() { return localStorage.getItem(JWT_KEY); }
|
||||
function setJwt(t) { localStorage.setItem(JWT_KEY, t); }
|
||||
function getDeviceToken() { return localStorage.getItem(DEVICE_KEY); }
|
||||
function setDeviceToken(t) { localStorage.setItem(DEVICE_KEY, t); }
|
||||
function clearSession() { localStorage.removeItem(JWT_KEY); localStorage.removeItem(DEVICE_KEY); }
|
||||
function clearSession() {
|
||||
localStorage.removeItem(JWT_KEY);
|
||||
localStorage.removeItem(DEVICE_KEY);
|
||||
localStorage.removeItem(ORG_KEY);
|
||||
}
|
||||
|
||||
function getSelectedOrg() {
|
||||
try { return JSON.parse(localStorage.getItem(ORG_KEY)); } catch { return null; }
|
||||
}
|
||||
function setSelectedOrg(org) {
|
||||
if (org) localStorage.setItem(ORG_KEY, JSON.stringify(org));
|
||||
else localStorage.removeItem(ORG_KEY);
|
||||
}
|
||||
|
||||
function decodeJwt(token) {
|
||||
try {
|
||||
@@ -56,7 +69,11 @@ const Auth = (() => {
|
||||
} catch {}
|
||||
}
|
||||
|
||||
return { getJwt, setJwt, getDeviceToken, setDeviceToken, clearSession, decodeJwt, isTokenExpiringSoon, tryDeviceLogin, autoRefreshIfNeeded };
|
||||
return {
|
||||
getJwt, setJwt, getDeviceToken, setDeviceToken, clearSession,
|
||||
getSelectedOrg, setSelectedOrg,
|
||||
decodeJwt, isTokenExpiringSoon, tryDeviceLogin, autoRefreshIfNeeded,
|
||||
};
|
||||
})();
|
||||
|
||||
// ── Api ───────────────────────────────────────────────────────────────────────
|
||||
@@ -69,11 +86,13 @@ const Api = (() => {
|
||||
if (!(options.body instanceof FormData) && options.body) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
// Scope requests to selected org when SystemAdmin is browsing an org
|
||||
const selectedOrg = Auth.getSelectedOrg();
|
||||
if (selectedOrg?.id) headers['X-Org-Id'] = String(selectedOrg.id);
|
||||
|
||||
const res = await fetch(url, { ...options, headers });
|
||||
|
||||
if (res.status === 401 && retry) {
|
||||
// Try device login once
|
||||
const refreshed = await Auth.tryDeviceLogin();
|
||||
if (refreshed) return _fetch(url, options, false);
|
||||
Auth.clearSession();
|
||||
@@ -97,42 +116,65 @@ const Api = (() => {
|
||||
// ── Nav ───────────────────────────────────────────────────────────────────────
|
||||
const Nav = (() => {
|
||||
const NAV_LINKS = [
|
||||
{ label: 'Dashboard', href: '/dashboard.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'Videos', href: '/videos.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'Workouts', href: '/workouts.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'Timers', href: '/timers.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'CrossFit', href: '/crossfit.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'Clients', href: '/clients.html', roles: ['Owner', 'Coach'], feature: 'client-management' },
|
||||
{ label: 'Calendar', href: '/calendar.html', roles: ['Owner', 'Coach'], feature: 'calendar' },
|
||||
{ label: 'My Workouts', href: '/my-workouts.html', roles: ['Client'] },
|
||||
{ label: 'My Schedule', href: '/my-schedule.html', roles: ['Client'], feature: 'calendar' },
|
||||
{ label: 'Settings', href: '/settings.html', roles: ['Owner'] },
|
||||
{ label: 'Audit Log', href: '/audit-log.html', roles: ['Owner'] },
|
||||
{ label: 'System Admin',href: '/sysadmin.html', roles: ['SystemAdmin'] },
|
||||
{ label: 'Profile', href: '/profile.html', roles: ['Owner', 'Coach', 'Client', 'SystemAdmin'] },
|
||||
{ label: 'Log Out', href: '#', action: 'logout', roles: ['Owner', 'Coach', 'Client', 'SystemAdmin'] },
|
||||
{ label: 'Dashboard', href: '/dashboard.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'Videos', href: '/videos.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'Workouts', href: '/workouts.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'Timers', href: '/timers.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'CrossFit', href: '/crossfit.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'Clients', href: '/clients.html', roles: ['Owner', 'Coach'], feature: 'client-management' },
|
||||
{ label: 'Calendar', href: '/calendar.html', roles: ['Owner', 'Coach'], feature: 'calendar' },
|
||||
{ label: 'My Workouts', href: '/my-workouts.html', roles: ['Client'] },
|
||||
{ label: 'My Schedule', href: '/my-schedule.html', roles: ['Client'], feature: 'calendar' },
|
||||
{ label: 'Settings', href: '/settings.html', roles: ['Owner'] },
|
||||
{ label: 'Audit Log', href: '/audit-log.html', roles: ['Owner'] },
|
||||
{ label: 'System Admin', href: '/sysadmin.html', roles: ['SystemAdmin'] },
|
||||
{ label: 'Profile', href: '/profile.html', roles: ['Owner', 'Coach', 'Client', 'SystemAdmin'] },
|
||||
{ label: 'Log Out', href: '#', action: 'logout', roles: ['Owner', 'Coach', 'Client', 'SystemAdmin'] },
|
||||
];
|
||||
|
||||
function init(currentPage) {
|
||||
const drawer = document.getElementById('nav-drawer');
|
||||
const scrim = document.getElementById('drawer-scrim');
|
||||
const hamb = document.getElementById('nav-hamburger');
|
||||
const drawer = document.getElementById('nav-drawer');
|
||||
const scrim = document.getElementById('drawer-scrim');
|
||||
const hamb = document.getElementById('nav-hamburger');
|
||||
const navList = document.getElementById('nav-list');
|
||||
if (!drawer || !navList) return;
|
||||
|
||||
const user = Page.currentUser();
|
||||
const user = Page.currentUser();
|
||||
const orgFeatures = (window._orgFeatures || []);
|
||||
const selectedOrg = Auth.getSelectedOrg();
|
||||
const isSaWithOrg = user?.role === 'SystemAdmin' && !!selectedOrg;
|
||||
|
||||
navList.innerHTML = '';
|
||||
|
||||
// Org-context indicator for SystemAdmin
|
||||
if (isSaWithOrg) {
|
||||
const li = document.createElement('li');
|
||||
li.className = 'nav-org-context';
|
||||
li.innerHTML = `Org: <strong>${selectedOrg.name}</strong>`;
|
||||
const exitBtn = document.createElement('button');
|
||||
exitBtn.className = 'btn btn-ghost btn-sm';
|
||||
exitBtn.textContent = 'Exit';
|
||||
exitBtn.style.marginLeft = 'var(--space-2)';
|
||||
exitBtn.addEventListener('click', () => {
|
||||
Auth.setSelectedOrg(null);
|
||||
window.location.href = '/sysadmin.html';
|
||||
});
|
||||
li.appendChild(exitBtn);
|
||||
navList.appendChild(li);
|
||||
}
|
||||
|
||||
NAV_LINKS.forEach(link => {
|
||||
if (!link.roles.includes(user?.role)) return;
|
||||
// SystemAdmin with an org context can see all Owner/Coach pages
|
||||
const roleMatch = link.roles.includes(user?.role) ||
|
||||
(isSaWithOrg && link.roles.some(r => r === 'Owner' || r === 'Coach'));
|
||||
if (!roleMatch) return;
|
||||
if (link.feature && !orgFeatures.includes(link.feature)) return;
|
||||
|
||||
const li = document.createElement('li');
|
||||
const a = document.createElement('a');
|
||||
a.textContent = link.label;
|
||||
a.href = link.href;
|
||||
if (link.href === currentPage || window.location.pathname.endsWith(link.href)) {
|
||||
if (window.location.pathname.endsWith(link.href) || link.href === currentPage) {
|
||||
a.classList.add('active');
|
||||
}
|
||||
if (link.action === 'logout') {
|
||||
@@ -152,10 +194,8 @@ const Nav = (() => {
|
||||
}
|
||||
|
||||
function toggle() {
|
||||
const drawer = document.getElementById('nav-drawer');
|
||||
const scrim = document.getElementById('drawer-scrim');
|
||||
drawer?.classList.toggle('open');
|
||||
scrim?.classList.toggle('open');
|
||||
document.getElementById('nav-drawer')?.classList.toggle('open');
|
||||
document.getElementById('drawer-scrim')?.classList.toggle('open');
|
||||
}
|
||||
|
||||
function close() {
|
||||
@@ -175,10 +215,8 @@ const Branding = (() => {
|
||||
const { data } = await res.json();
|
||||
apply(data);
|
||||
window._orgFeatures = data.features || [];
|
||||
// Set app name in banner
|
||||
const titleEl = document.getElementById('app-name');
|
||||
if (titleEl && data.appName) titleEl.textContent = data.appName;
|
||||
// Set logo if present
|
||||
const logoEl = document.getElementById('banner-logo');
|
||||
if (logoEl && data.logoPath) { logoEl.src = data.logoPath; logoEl.style.display = ''; }
|
||||
} catch {}
|
||||
@@ -186,11 +224,11 @@ const Branding = (() => {
|
||||
|
||||
function apply(branding) {
|
||||
const root = document.documentElement.style;
|
||||
if (branding.primaryColor) root.setProperty('--color-primary', branding.primaryColor);
|
||||
if (branding.secondaryColor) root.setProperty('--color-secondary', branding.secondaryColor);
|
||||
if (branding.workColor) root.setProperty('--color-work', branding.workColor);
|
||||
if (branding.restColor) root.setProperty('--color-rest', branding.restColor);
|
||||
if (branding.moveColor) root.setProperty('--color-move', branding.moveColor);
|
||||
if (branding.primaryColor) root.setProperty('--color-primary', branding.primaryColor);
|
||||
if (branding.secondaryColor) root.setProperty('--color-secondary', branding.secondaryColor);
|
||||
if (branding.workColor) root.setProperty('--color-work', branding.workColor);
|
||||
if (branding.restColor) root.setProperty('--color-rest', branding.restColor);
|
||||
if (branding.moveColor) root.setProperty('--color-move', branding.moveColor);
|
||||
}
|
||||
|
||||
return { load, apply };
|
||||
@@ -221,10 +259,14 @@ const Page = (() => {
|
||||
}
|
||||
|
||||
if (allowedRoles && !allowedRoles.includes(user.role)) {
|
||||
if (user.role === 'Client') window.location.href = '/my-workouts.html';
|
||||
else if (user.role === 'SystemAdmin') window.location.href = '/sysadmin.html';
|
||||
else window.location.href = '/dashboard.html';
|
||||
return;
|
||||
// SystemAdmin with a selected org can browse org-scoped pages
|
||||
const isOrgScoped = user.role === 'SystemAdmin' && !!Auth.getSelectedOrg();
|
||||
if (!isOrgScoped) {
|
||||
if (user.role === 'Client') window.location.href = '/my-workouts.html';
|
||||
else if (user.role === 'SystemAdmin') window.location.href = '/sysadmin.html';
|
||||
else window.location.href = '/dashboard.html';
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await Branding.load();
|
||||
@@ -256,7 +298,6 @@ function toast(message, type = 'info', duration = 3000) {
|
||||
// ── Back-forward cache (bfcache) re-init ──────────────────────────────────────
|
||||
window.addEventListener('pageshow', (e) => {
|
||||
if (e.persisted && window._socketClient) {
|
||||
// Re-connect socket on bfcache restore
|
||||
window._socketClient.connect?.();
|
||||
}
|
||||
});
|
||||
|
||||
+30
-12
@@ -7,25 +7,43 @@ const Display = (() => {
|
||||
function renderWorkout(workout) {
|
||||
const nameEl = document.getElementById('display-workout-name');
|
||||
const dateEl = document.getElementById('display-workout-date');
|
||||
const listEl = document.getElementById('display-workout-list');
|
||||
const gridEl = document.getElementById('display-video-grid');
|
||||
|
||||
if (nameEl) nameEl.textContent = workout.name || '';
|
||||
if (dateEl && workout.workoutDate) {
|
||||
dateEl.textContent = new Date(workout.workoutDate).toLocaleDateString('en-US', { month: 'long', day: 'numeric' });
|
||||
}
|
||||
|
||||
if (listEl) {
|
||||
listEl.innerHTML = '';
|
||||
(workout.videos || []).filter(s => s.video).forEach(slot => {
|
||||
const li = document.createElement('li');
|
||||
li.className = 'display-workout-item';
|
||||
li.innerHTML = `
|
||||
<span class="display-workout-item-name">${slot.video.description || 'Exercise'}</span>
|
||||
${slot.reps ? `<span class="display-workout-item-reps">${slot.reps} reps</span>` : ''}
|
||||
`;
|
||||
listEl.appendChild(li);
|
||||
});
|
||||
if (!gridEl) return;
|
||||
|
||||
const slots = (workout.videos || []).filter(s => s.video);
|
||||
const count = Math.min(slots.length, 4);
|
||||
|
||||
if (!count) {
|
||||
gridEl.innerHTML = '<div class="display-no-videos">No exercises assigned.</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
const jwt = Auth.getJwt();
|
||||
const selectedOrg = Auth.getSelectedOrg();
|
||||
const orgParam = selectedOrg ? `&orgId=${selectedOrg.id}` : '';
|
||||
|
||||
gridEl.className = `display-video-grid panes-${count}`;
|
||||
gridEl.innerHTML = slots.slice(0, 4).map(slot => {
|
||||
const streamSrc = slot.video.streamUrl
|
||||
? `${slot.video.streamUrl}?token=${encodeURIComponent(jwt || '')}${orgParam}`
|
||||
: '';
|
||||
return `
|
||||
<div class="display-pane">
|
||||
${streamSrc
|
||||
? `<video class="display-pane-video" src="${streamSrc}" autoplay loop muted playsinline></video>`
|
||||
: `<div class="display-pane-missing">Missing Video</div>`}
|
||||
${slot.reps ? `<div class="display-pane-corner">${slot.reps}</div>` : ''}
|
||||
<div class="display-pane-overlay">
|
||||
<span class="display-pane-name">${slot.video.description || 'Exercise'}</span>
|
||||
</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderCrossfit(workout) {
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
</div>
|
||||
<div class="flex gap-3 align-center">
|
||||
<span class="badge badge-${s.status === 'scheduled' ? 'default' : s.status === 'completed' ? 'success' : 'danger'}">${s.status}</span>
|
||||
${s.status === 'scheduled' ? `<button class="btn btn-danger btn-sm" onclick="cancelSession(${s.id})">Cancel</button>` : ''}
|
||||
${s.status === 'scheduled' ? `<button class="btn btn-danger btn-sm" data-action="cancel" data-id="${s.id}">Cancel</button>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
</div>`).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();
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -57,7 +57,7 @@
|
||||
</div>
|
||||
<div class="flex gap-3">
|
||||
<span class="badge badge-${cw.status === 'completed' ? 'success' : 'default'}">${cw.status}</span>
|
||||
${cw.status !== 'completed' ? `<button class="btn btn-primary btn-sm" onclick="markComplete(${cw.id})">Mark Done</button>` : ''}
|
||||
${cw.status !== 'completed' ? `<button class="btn btn-primary btn-sm" data-action="complete" data-id="${cw.id}">Mark Done</button>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
${cw.workout?.videos?.length ? `<p class="text-secondary mt-2">${cw.workout.videos.length} exercises</p>` : ''}
|
||||
@@ -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 => {
|
||||
|
||||
@@ -135,8 +135,8 @@
|
||||
<td><span class="badge badge-${u.isActive ? 'success' : 'danger'}">${u.isActive ? 'Active' : 'Inactive'}</span></td>
|
||||
<td class="table-actions">
|
||||
${u.isActive
|
||||
? `<button class="btn btn-danger btn-sm" onclick="toggleUser(${u.id}, false)">Deactivate</button>`
|
||||
: `<button class="btn btn-secondary btn-sm" onclick="toggleUser(${u.id}, true)">Activate</button>`}
|
||||
? `<button class="btn btn-danger btn-sm" data-action="toggle" data-id="${u.id}" data-active="false">Deactivate</button>`
|
||||
: `<button class="btn btn-secondary btn-sm" data-action="toggle" data-id="${u.id}" data-active="true">Activate</button>`}
|
||||
</td>
|
||||
</tr>`).join('')}
|
||||
</tbody></table>`;
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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 ─────────────────────────────────────────────────────── */
|
||||
|
||||
@@ -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 ────────────────────────────────────────────────────── */
|
||||
|
||||
+3
-1
@@ -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',
|
||||
];
|
||||
|
||||
|
||||
@@ -85,14 +85,21 @@
|
||||
if (!res.ok) throw new Error();
|
||||
const { data } = await res.json();
|
||||
if (!data.length) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">No organisations.</p></div>'; return; }
|
||||
el.innerHTML = `<table class="table"><thead><tr><th>Name</th><th>Slug</th><th>Created</th><th>Features</th></tr></thead><tbody>
|
||||
el.innerHTML = `<table class="table"><thead><tr><th>Name</th><th>Slug</th><th>Created</th><th>Features</th><th></th></tr></thead><tbody>
|
||||
${data.map(o => `<tr>
|
||||
<td>${o.name}</td>
|
||||
<td><code>${o.slug}</code></td>
|
||||
<td>${new Date(o.createdAt).toLocaleDateString()}</td>
|
||||
<td>${(o.features || []).join(', ') || '—'}</td>
|
||||
<td><button class="btn btn-sm btn-primary" data-org-id="${o.id}" data-org-name="${o.name.replace(/"/g, '"')}">View</button></td>
|
||||
</tr>`).join('')}
|
||||
</tbody></table>`;
|
||||
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 = '<div class="empty-state"><p class="empty-state-text">Failed to load.</p></div>'; }
|
||||
}
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@
|
||||
<td>${t.timerType}</td>
|
||||
<td>${timerSummary(t)}</td>
|
||||
<td class="table-actions">
|
||||
<button class="btn btn-primary btn-sm" onclick="launchTimer(${t.id}, '${t.name.replace(/'/g, "\\'")}')">Launch</button>
|
||||
<button class="btn btn-primary btn-sm" data-action="launch" data-id="${t.id}" data-name="${t.name.replace(/"/g, '"')}">Launch</button>
|
||||
</td>
|
||||
</tr>`).join('')}
|
||||
</tbody></table>`;
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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 = '<div class="empty-state"><p class="empty-state-text">Failed to load.</p></div>'; return; }
|
||||
const { data, meta } = await res.json();
|
||||
if (!data.length) { grid.innerHTML = '<div class="empty-state"><p class="empty-state-text">No videos found.</p></div>'; return; }
|
||||
|
||||
const jwt = Auth.getJwt();
|
||||
const selectedOrg = Auth.getSelectedOrg();
|
||||
const orgParam = selectedOrg ? `&orgId=${selectedOrg.id}` : '';
|
||||
grid.innerHTML = data.map(v => `
|
||||
<div class="video-card">
|
||||
<div class="video-card-thumb">
|
||||
${v.thumbnailPath ? `<img src="${v.thumbnailPath}" alt="">` : '<div class="video-card-thumb-placeholder"></div>'}
|
||||
<div class="video-card-player">
|
||||
${v.fileExists
|
||||
? `<video controls preload="none" src="${v.streamUrl}?token=${encodeURIComponent(jwt)}${orgParam}" style="width:100%;height:100%;display:block;background:#000;"></video>`
|
||||
: `<div class="video-missing-placeholder"><span>Missing Video</span></div>`}
|
||||
</div>
|
||||
<div class="video-card-body">
|
||||
<p class="video-card-title">${v.description || 'Untitled'}</p>
|
||||
${v.category ? `<span class="badge">${v.category.name}</span>` : ''}
|
||||
${v.category ? `<span class="badge">${v.category}</span>` : ''}
|
||||
</div>
|
||||
</div>`).join('');
|
||||
|
||||
grid.querySelectorAll('video').forEach(vid => {
|
||||
vid.addEventListener('error', () => {
|
||||
vid.closest('.video-card-player').innerHTML = `<div class="video-missing-placeholder"><span>Missing Video</span></div>`;
|
||||
});
|
||||
});
|
||||
|
||||
renderPagination(meta);
|
||||
} catch {
|
||||
grid.innerHTML = '<div class="empty-state"><p class="empty-state-text">Error loading videos.</p></div>';
|
||||
@@ -79,9 +90,9 @@
|
||||
const el = document.getElementById('pagination');
|
||||
if (!meta || meta.totalPages <= 1) { el.innerHTML = ''; return; }
|
||||
el.innerHTML = `
|
||||
<button class="btn btn-ghost btn-sm" ${_page <= 1 ? 'disabled' : ''} onclick="changePage(${_page - 1})">Previous</button>
|
||||
<button class="btn btn-ghost btn-sm" ${_page <= 1 ? 'disabled' : ''} data-action="page" data-page="${_page - 1}">Previous</button>
|
||||
<span class="pagination-info">Page ${meta.page} of ${meta.totalPages}</span>
|
||||
<button class="btn btn-ghost btn-sm" ${_page >= meta.totalPages ? 'disabled' : ''} onclick="changePage(${_page + 1})">Next</button>`;
|
||||
<button class="btn btn-ghost btn-sm" ${_page >= meta.totalPages ? 'disabled' : ''} data-action="page" data-page="${_page + 1}">Next</button>`;
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -8,18 +8,12 @@
|
||||
<link rel="stylesheet" href="/styles/display.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="display-container phase-idle" id="timer-container">
|
||||
<div class="display-container" id="display-container">
|
||||
<div class="display-status-bar">
|
||||
<span class="display-status-label" id="display-workout-name">Loading…</span>
|
||||
<span class="display-status-right" id="display-workout-date"></span>
|
||||
</div>
|
||||
|
||||
<div class="display-main">
|
||||
<ul class="display-workout-list" id="display-workout-list"></ul>
|
||||
</div>
|
||||
|
||||
<div class="touch-zone touch-zone-left" id="touch-left"></div>
|
||||
<div class="touch-zone touch-zone-right" id="touch-right"></div>
|
||||
<div class="display-video-grid" id="display-video-grid"></div>
|
||||
</div>
|
||||
|
||||
<div id="display-offline-banner" class="display-offline-banner">Offline — last known data shown</div>
|
||||
@@ -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);
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -73,15 +73,19 @@
|
||||
const el = document.getElementById('pagination');
|
||||
if (!meta || meta.totalPages <= 1) { el.innerHTML = ''; return; }
|
||||
el.innerHTML = `
|
||||
<button class="btn btn-ghost btn-sm" ${_page <= 1 ? 'disabled' : ''} onclick="changePage(${_page - 1})">Previous</button>
|
||||
<button class="btn btn-ghost btn-sm" ${_page <= 1 ? 'disabled' : ''} data-action="page" data-page="${_page - 1}">Previous</button>
|
||||
<span class="pagination-info">Page ${meta.page} of ${meta.totalPages}</span>
|
||||
<button class="btn btn-ghost btn-sm" ${_page >= meta.totalPages ? 'disabled' : ''} onclick="changePage(${_page + 1})">Next</button>`;
|
||||
<button class="btn btn-ghost btn-sm" ${_page >= meta.totalPages ? 'disabled' : ''} data-action="page" data-page="${_page + 1}">Next</button>`;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user