Files
vitfit-r2/V2/app/public/js/core.js
T
2026-10-14 09:51:01 -04:00

321 lines
14 KiB
JavaScript

/* VitFit core.js — loaded on every page */
'use strict';
// ── Auth ──────────────────────────────────────────────────────────────────────
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);
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 {
return JSON.parse(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')));
} catch { return null; }
}
function isTokenExpiringSoon(token) {
const payload = decodeJwt(token);
if (!payload?.exp) return false;
return (payload.exp * 1000 - Date.now()) < 60 * 60 * 1000; // < 1 hour
}
async function tryDeviceLogin(signal) {
const deviceToken = getDeviceToken();
if (!deviceToken) return false;
try {
const res = await fetch('/api/v1/auth/device-login', {
method: 'POST',
signal,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ deviceToken }),
});
if (!res.ok) return false;
const { data } = await res.json();
setJwt(data.jwt);
if (data.deviceToken) setDeviceToken(data.deviceToken);
return true;
} catch { return false; }
}
async function autoRefreshIfNeeded(signal) {
const token = getJwt();
if (!token || !isTokenExpiringSoon(token)) return;
try {
const res = await fetch('/api/v1/auth/refresh-token', {
method: 'POST',
signal,
headers: { Authorization: `Bearer ${token}` },
});
if (res.ok) {
const { data } = await res.json();
setJwt(data.jwt);
}
} catch {}
}
return {
getJwt, setJwt, getDeviceToken, setDeviceToken, clearSession,
getSelectedOrg, setSelectedOrg,
decodeJwt, isTokenExpiringSoon, tryDeviceLogin, autoRefreshIfNeeded,
};
})();
// ── Api ───────────────────────────────────────────────────────────────────────
const Api = (() => {
async function _fetch(url, options = {}, retry = true) {
await Auth.autoRefreshIfNeeded(options.signal);
const jwt = Auth.getJwt();
const headers = { ...(options.headers || {}) };
if (jwt) headers['Authorization'] = `Bearer ${jwt}`;
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) {
const refreshed = await Auth.tryDeviceLogin(options.signal);
if (refreshed) return _fetch(url, options, false);
if (options.signal?.aborted) throw options.signal.reason || new Error('Request aborted');
Auth.clearSession();
Page.showSessionExpiredOverlay();
throw new Error('Session expired');
}
return res;
}
const get = (url, params) => _fetch(url + (params ? '?' + new URLSearchParams(params) : ''));
const post = (url, body) => _fetch(url, { method: 'POST', body: JSON.stringify(body) });
const patch = (url, body) => _fetch(url, { method: 'PATCH', body: JSON.stringify(body) });
const put = (url, body) => _fetch(url, { method: 'PUT', body: JSON.stringify(body) });
const del = (url) => _fetch(url, { method: 'DELETE' });
const upload = (url, formData) => _fetch(url, { method: 'POST', body: formData });
return { fetch: _fetch, get, post, patch, put, del, upload };
})();
// ── 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'] },
];
function init(currentPage) {
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 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 => {
// 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 (window.location.pathname.endsWith(link.href) || link.href === currentPage) {
a.classList.add('active');
}
if (link.action === 'logout') {
a.addEventListener('click', async (e) => {
e.preventDefault();
await Api.post('/api/v1/auth/logout', {}).catch(() => {});
Auth.clearSession();
window.location.href = '/';
});
}
li.appendChild(a);
navList.appendChild(li);
});
hamb?.addEventListener('click', toggle);
scrim?.addEventListener('click', close);
}
function toggle() {
document.getElementById('nav-drawer')?.classList.toggle('open');
document.getElementById('drawer-scrim')?.classList.toggle('open');
}
function close() {
document.getElementById('nav-drawer')?.classList.remove('open');
document.getElementById('drawer-scrim')?.classList.remove('open');
}
return { init, toggle, close };
})();
// ── Branding ──────────────────────────────────────────────────────────────────
const Branding = (() => {
async function load() {
try {
const res = await Api.get('/api/v1/org/branding');
if (!res.ok) return;
const { data } = await res.json();
apply(data);
window._orgFeatures = data.features || [];
const titleEl = document.getElementById('app-name');
if (titleEl && data.appName) titleEl.textContent = data.appName;
const logoEl = document.getElementById('banner-logo');
if (logoEl && data.logoPath) { logoEl.src = data.logoPath; logoEl.style.display = ''; }
} catch {}
}
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.btnPrimaryBg) root.setProperty('--color-btn-primary-bg', branding.btnPrimaryBg);
if (branding.btnSecondaryBg) root.setProperty('--color-btn-secondary-bg', branding.btnSecondaryBg);
if (branding.pageBg) root.setProperty('--color-page-bg', branding.pageBg);
if (branding.popupBg) root.setProperty('--color-popup-bg', branding.popupBg);
if (branding.overlayColor) root.setProperty('--color-overlay', branding.overlayColor);
if (branding.bannerBg) root.setProperty('--color-banner-bg', branding.bannerBg);
if (branding.drawerBg) root.setProperty('--color-drawer-bg', branding.drawerBg);
if (branding.textPrimary) root.setProperty('--text-primary', branding.textPrimary);
if (branding.textSecondary) root.setProperty('--text-secondary', branding.textSecondary);
if (branding.cardBg) root.setProperty('--surface-card', branding.cardBg);
if (branding.inputBg) root.setProperty('--surface-raised', branding.inputBg);
if (branding.hoverBg) root.setProperty('--surface-hover', branding.hoverBg);
if (branding.borderColor) root.setProperty('--surface-border', branding.borderColor);
document.body.dataset.tabStyle = branding.tabStyle || 'underline';
}
return { load, apply };
})();
// ── Page ──────────────────────────────────────────────────────────────────────
const Page = (() => {
function currentUser() {
const token = Auth.getJwt();
if (!token) return null;
const payload = Auth.decodeJwt(token);
if (!payload) return null;
if (payload.exp && payload.exp * 1000 < Date.now()) { Auth.clearSession(); return null; }
return payload;
}
async function init(allowedRoles) {
let user = currentUser();
if (!user) {
const refreshed = await Auth.tryDeviceLogin();
if (refreshed) { user = currentUser(); }
}
if (!user) {
window.location.href = '/';
return;
}
if (allowedRoles && !allowedRoles.includes(user.role)) {
// 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();
Nav.init(window.location.pathname);
}
function showSessionExpiredOverlay() {
document.getElementById('session-expired-overlay')?.classList.add('visible');
}
return { init, currentUser, showSessionExpiredOverlay };
})();
// ── Toast ─────────────────────────────────────────────────────────────────────
function toast(message, type = 'info', duration = 3000) {
let container = document.getElementById('toast-container');
if (!container) {
container = document.createElement('div');
container.id = 'toast-container';
document.body.appendChild(container);
}
const el = document.createElement('div');
el.className = `toast toast-${type}`;
el.textContent = message;
container.appendChild(el);
setTimeout(() => el.remove(), duration);
}
// ── Back-forward cache (bfcache) re-init ──────────────────────────────────────
window.addEventListener('pageshow', (e) => {
if (e.persisted && window._socketClient) {
window._socketClient.connect?.();
}
});