added submission history, data insights, download all functionality

This commit is contained in:
2026-06-01 12:54:56 +02:00
parent 9a6fa22d84
commit bee7b74e53
19 changed files with 1863 additions and 110 deletions

198
website/js/pages/coaches.js Normal file
View File

@ -0,0 +1,198 @@
import { apiGet } from '../api.js';
import { showToast } from '../app.js';
let coachesList = [];
let expandedCoachId = null;
let recentByCoach = {};
let filterSearch = '';
export async function coachesPage() {
const app = document.getElementById('app');
app.innerHTML = `
<div class="page-header">
<h1>Coach activity</h1>
<div class="actions"><a href="#/" class="btn">&larr; Dashboard</a></div>
</div>
<div id="coachesContent"><div class="spinner"></div></div>
`;
try {
const data = await apiGet('coaches.php');
coachesList = data.coaches || [];
renderCoaches();
} catch (e) {
showToast(e.message, 'error');
document.getElementById('coachesContent').innerHTML =
`<p class="error-text">${esc(e.message)}</p>`;
}
}
function coachSearchText(c) {
return [c.username, c.coachID, c.supervisorUsername].filter(Boolean).join(' ');
}
function coachHasUploads(c) {
return (c.totalSubmissions ?? 0) > 0;
}
function filteredCoaches() {
const q = filterSearch.trim().toLowerCase();
if (!q) return coachesList;
return coachesList.filter(c => coachSearchText(c).toLowerCase().includes(q));
}
function renderCoaches() {
const el = document.getElementById('coachesContent');
if (!coachesList.length) {
el.innerHTML = `<div class="card empty-state"><h3>No coaches</h3></div>`;
return;
}
el.innerHTML = `
<div class="card">
<p class="data-toolbar-hint" style="margin:0 0 12px">Track uploads and client load per coach. Expand a row for recent submissions.</p>
<div class="filter-bar">
<input type="search" id="coachListSearch" class="filter-search"
placeholder="Search coach or supervisor…" value="${esc(filterSearch)}">
<span class="data-toolbar-hint" id="coachListCount"></span>
</div>
<div class="table-wrapper">
<table class="data-table">
<thead>
<tr>
<th>Coach</th><th>Supervisor</th><th>Clients</th>
<th>Total uploads</th><th>7d</th><th>30d</th><th>Last upload</th>
</tr>
</thead>
<tbody id="coachTableBody"></tbody>
</table>
</div>
</div>
`;
document.getElementById('coachListSearch').addEventListener('input', (e) => {
filterSearch = e.target.value;
const filtered = filteredCoaches();
if (
expandedCoachId &&
!filtered.some(c => c.coachID === expandedCoachId && coachHasUploads(c))
) {
expandedCoachId = null;
}
renderCoachTableBody();
});
renderCoachTableBody();
}
function coachRowHTML(c) {
const canExpand = coachHasUploads(c);
const expanded = canExpand && expandedCoachId === c.coachID;
const recent = recentByCoach[c.coachID] || [];
const expandControl = canExpand
? `<button type="button" class="btn btn-sm btn-link coach-expand-btn" data-coach="${esc(c.coachID)}">${expanded ? '▼' : '▶'}</button> `
: '';
return `
<tr class="coach-row" data-coach="${esc(c.coachID)}">
<td>${expandControl}<strong>${esc(c.username)}</strong></td>
<td>${esc(c.supervisorUsername || '—')}</td>
<td>${c.clientCount ?? 0}</td>
<td>${c.totalSubmissions ?? 0}</td>
<td>${c.submissionsLast7d ?? 0}</td>
<td>${c.submissionsLast30d ?? 0}</td>
<td>${esc(c.lastSubmissionAt || '—')}</td>
</tr>
${expanded ? `
<tr class="coach-detail-row">
<td colspan="7">
<div class="coach-recent-panel">
${recent.length ? `
<table class="data-table data-table-compact">
<thead>
<tr><th>When</th><th>Client</th><th>Questionnaire</th><th>Ver.</th></tr>
</thead>
<tbody>
${recent.map(s => `
<tr>
<td>${esc(s.submittedAt)}</td>
<td><code>${esc(s.clientCode)}</code></td>
<td>${esc(s.questionnaireName)}</td>
<td>${s.version}</td>
</tr>
`).join('')}
</tbody>
</table>
` : '<p class="data-toolbar-hint">Loading…</p>'}
</div>
</td>
</tr>` : ''}`;
}
function renderCoachTableBody() {
const body = document.getElementById('coachTableBody');
const countEl = document.getElementById('coachListCount');
if (!body) return;
const filtered = filteredCoaches();
if (!filtered.length) {
body.innerHTML = `
<tr>
<td colspan="7" style="text-align:center;color:var(--text-secondary);padding:24px">
No coaches match
</td>
</tr>`;
if (countEl) {
countEl.textContent = filterSearch.trim()
? `0 of ${coachesList.length} coaches`
: '';
}
return;
}
body.innerHTML = filtered.map(c => coachRowHTML(c)).join('');
if (countEl) {
const q = filterSearch.trim();
countEl.textContent = q
? `${filtered.length} of ${coachesList.length} coaches`
: `${coachesList.length} coach${coachesList.length === 1 ? '' : 'es'}`;
}
body.querySelectorAll('.coach-expand-btn').forEach(btn => {
btn.addEventListener('click', () => toggleCoach(btn.dataset.coach));
});
}
async function toggleCoach(coachID) {
const coach = coachesList.find(c => c.coachID === coachID);
if (!coach || !coachHasUploads(coach)) {
return;
}
if (expandedCoachId === coachID) {
expandedCoachId = null;
renderCoachTableBody();
return;
}
expandedCoachId = coachID;
renderCoachTableBody();
if (!recentByCoach[coachID]) {
try {
const data = await apiGet(
`coaches.php?coachID=${encodeURIComponent(coachID)}&recent=1`
);
recentByCoach[coachID] = data.submissions || [];
} catch (e) {
showToast(e.message, 'error');
recentByCoach[coachID] = [];
}
renderCoachTableBody();
}
}
function esc(s) {
const d = document.createElement('div');
d.textContent = s ?? '';
return d.innerHTML;
}

View File

@ -11,9 +11,22 @@ export function devPage() {
const app = document.getElementById('app');
app.innerHTML = `
<div class="page-header">
<h1>Dev import</h1>
<h1>Admin Settings</h1>
</div>
<div class="card" style="max-width:720px;margin-bottom:16px">
<h2 style="margin:0 0 8px;font-size:1.1rem">Export all response data (ZIP)</h2>
<p class="field-hint" style="margin:0 0 14px">
Download one CSV per questionnaire in a single ZIP (full server data).
<strong>Current data</strong> uses live answers;
<strong>All versions</strong> includes every upload (one row per submission).
</p>
<div style="display:flex;flex-wrap:wrap;gap:10px">
<button type="button" class="btn btn-primary" id="exportAllCurrentZipBtn">Export all — current data (ZIP)</button>
<button type="button" class="btn" id="exportAllVersionsZipBtn">Export all — all versions (ZIP)</button>
</div>
</div>
<div class="card" style="max-width:720px">
<h2 style="margin:0 0 8px;font-size:1.1rem">Dev import</h2>
<p class="field-hint callout-warn">
<strong>Local / test only.</strong> Imports prefixed dev users (<code>dev_*</code>),
clients (<code>DEV-CL-*</code>), and completed questionnaire runs.
@ -150,6 +163,8 @@ export function devPage() {
}
});
wireAdminZipExport();
document.getElementById('devImportBtn').addEventListener('click', async () => {
if (!parsedFixture) return;
const btn = document.getElementById('devImportBtn');
@ -184,3 +199,62 @@ export function devPage() {
}
});
}
function filenameFromContentDisposition(res, fallback) {
const disp = res.headers.get('Content-Disposition');
if (!disp) return fallback;
const m = /filename="([^"]+)"/i.exec(disp);
return m ? m[1] : fallback;
}
async function downloadExportZip(url, defaultFilename) {
const token = localStorage.getItem('qdb_token');
const res = await fetch(url, {
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) {
const err = await res.json().catch(() => ({ error: 'Download failed' }));
throw new Error(err.error?.message || err.error || 'Download failed');
}
const blob = await res.blob();
const blobUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = blobUrl;
a.download = filenameFromContentDisposition(res, defaultFilename);
a.click();
URL.revokeObjectURL(blobUrl);
}
function wireAdminZipExport() {
document.getElementById('exportAllCurrentZipBtn')?.addEventListener('click', async () => {
const btn = document.getElementById('exportAllCurrentZipBtn');
btn.disabled = true;
const prev = btn.textContent;
btn.textContent = 'Preparing ZIP…';
try {
await downloadExportZip('../api/export?exportAll=1', 'responses_export_current.zip');
showToast('ZIP download started (current data)', 'success');
} catch (e) {
showToast(e.message, 'error');
} finally {
btn.disabled = false;
btn.textContent = prev;
}
});
document.getElementById('exportAllVersionsZipBtn')?.addEventListener('click', async () => {
const btn = document.getElementById('exportAllVersionsZipBtn');
btn.disabled = true;
const prev = btn.textContent;
btn.textContent = 'Preparing ZIP…';
try {
await downloadExportZip('../api/export?exportAll=1&allVersions=1', 'responses_export_all_versions.zip');
showToast('ZIP download started (all versions)', 'success');
} catch (e) {
showToast(e.message, 'error');
} finally {
btn.disabled = false;
btn.textContent = prev;
}
});
}

View File

@ -124,6 +124,9 @@ function renderExportTableBody() {
body.querySelectorAll('.export-btn').forEach(btn => {
btn.addEventListener('click', onExportCsvClick);
});
body.querySelectorAll('.export-btn-all').forEach(btn => {
btn.addEventListener('click', onExportAllVersionsClick);
});
}
function exportRowHTML(q) {
@ -134,11 +137,14 @@ function exportRowHTML(q) {
<td><span class="badge badge-${(q.state || 'draft').toLowerCase()}">${esc(q.state || 'draft')}</span></td>
<td>${q.questionCount || 0}</td>
<td>${q.completedCount ?? 0}</td>
<td>
<button class="btn btn-sm btn-primary export-btn" data-id="${esc(q.questionnaireID)}" data-name="${esc(q.name)}" data-version="${esc(q.version)}">
Export CSV
<td class="export-actions-cell">
<button class="btn btn-sm btn-primary export-btn" data-id="${esc(q.questionnaireID)}" data-name="${esc(q.name)}" data-version="${esc(q.version)}" data-all="0">
Export current
</button>
<a href="#/questionnaire/${esc(q.questionnaireID)}/results" class="btn btn-sm">View Results</a>
<button class="btn btn-sm export-btn-all" data-id="${esc(q.questionnaireID)}" data-name="${esc(q.name)}">
All versions
</button>
<a href="#/questionnaire/${esc(q.questionnaireID)}/results" class="btn btn-sm">Results</a>
</td>
</tr>`;
}
@ -176,32 +182,56 @@ function wireExportActions() {
});
}
async function downloadExportCsv(btn, url, filename) {
const token = localStorage.getItem('qdb_token');
const res = await fetch(url, {
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) {
const err = await res.json().catch(() => ({ error: 'Download failed' }));
throw new Error(err.error?.message || err.error || 'Download failed');
}
const blob = await res.blob();
const blobUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = blobUrl;
a.download = filename;
a.click();
URL.revokeObjectURL(blobUrl);
}
async function onExportCsvClick(ev) {
const btn = ev.currentTarget;
btn.disabled = true;
btn.textContent = 'Downloading...';
const prev = btn.textContent;
btn.textContent = 'Downloading…';
try {
const token = localStorage.getItem('qdb_token');
const res = await fetch(`../api/export.php?questionnaireID=${encodeURIComponent(btn.dataset.id)}&format=csv`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) {
const err = await res.json().catch(() => ({ error: 'Download failed' }));
throw new Error(err.error);
}
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${btn.dataset.name}_v${btn.dataset.version}.csv`;
a.click();
URL.revokeObjectURL(url);
const url = `../api/export?questionnaireID=${encodeURIComponent(btn.dataset.id)}`;
await downloadExportCsv(btn, url, `${btn.dataset.name}_v${btn.dataset.version}.csv`);
showToast('Download started', 'success');
} catch (e) {
showToast(e.message, 'error');
} finally {
btn.disabled = false;
btn.textContent = 'Export CSV';
btn.textContent = prev;
}
}
async function onExportAllVersionsClick(ev) {
const btn = ev.currentTarget;
btn.disabled = true;
const prev = btn.textContent;
btn.textContent = 'Downloading…';
try {
const url = `../api/export?questionnaireID=${encodeURIComponent(btn.dataset.id)}&allVersions=1`;
const stamp = new Date().toISOString().slice(0, 10);
await downloadExportCsv(btn, url, `${btn.dataset.name}_all_versions_${stamp}.csv`);
showToast('All versions download started', 'success');
} catch (e) {
showToast(e.message, 'error');
} finally {
btn.disabled = false;
btn.textContent = prev;
}
}

View File

@ -0,0 +1,328 @@
import { apiGet, apiPut } from '../api.js';
import { showToast } from '../app.js';
let overview = null;
let staleClients = [];
let followupSearch = '';
export async function insightsPage() {
const app = document.getElementById('app');
app.innerHTML = `
<div class="page-header">
<h1>Insights</h1>
<div class="actions"><a href="#/" class="btn">&larr; Dashboard</a></div>
</div>
<div id="insightsContent"><div class="spinner"></div></div>
`;
try {
const [ov, stale] = await Promise.all([
apiGet('analytics.php?overview=1'),
apiGet('analytics.php?staleClients=1'),
]);
overview = ov;
staleClients = stale.clients || [];
renderInsights();
} catch (e) {
showToast(e.message, 'error');
document.getElementById('insightsContent').innerHTML =
`<p class="error-text">${esc(e.message)}</p>`;
}
}
function renderInsights() {
const el = document.getElementById('insightsContent');
const ov = overview || {};
const kpiCards = `
<div class="insights-kpi-grid">
<div class="insights-kpi card">
<div class="insights-kpi-value">${ov.clientCount ?? 0}</div>
<div class="insights-kpi-label">Clients</div>
</div>
<div class="insights-kpi card">
<div class="insights-kpi-value">${ov.clientsWithCompletions ?? 0}</div>
<div class="insights-kpi-label">With completions</div>
</div>
<div class="insights-kpi card">
<div class="insights-kpi-value">${ov.submissionsLast7d ?? 0}</div>
<div class="insights-kpi-label">Uploads (7 days)</div>
</div>
<div class="insights-kpi card">
<div class="insights-kpi-value">${ov.submissionsLast30d ?? 0}</div>
<div class="insights-kpi-label">Uploads (30 days)</div>
</div>
</div>
`;
const uploadChart = verticalBarChart(
(ov.submissionsByDay || []).map(d => ({
label: formatChartDay(d.date),
value: d.count,
title: `${d.date}: ${d.count} upload(s)`,
})),
{ emptyLabel: 'No uploads in this period' }
);
const withoutCompletions = Math.max(0, (ov.clientCount ?? 0) - (ov.clientsWithCompletions ?? 0));
const engagementChart = horizontalBarChart([
{ label: 'With completions', value: ov.clientsWithCompletions ?? 0 },
{ label: 'No completions yet', value: withoutCompletions },
], { suffix: '' });
const idleChart = horizontalBarChart(idleBucketItems(staleClients), {
suffix: '',
variant: 'warn',
});
const completionChart = horizontalBarChart(
(ov.questionnaires || []).map(q => ({
label: q.name,
value: q.completionRatio ?? 0,
title: `${q.name}: ${q.completionRatio ?? 0}%`,
})),
{ suffix: '%', max: 100 }
);
const qRows = (ov.questionnaires || []).map(q => `
<tr>
<td><strong>${esc(q.name)}</strong></td>
<td>${q.completedCount ?? 0} / ${q.eligibleCount ?? 0}</td>
<td>${q.completionRatio ?? 0}%</td>
</tr>
`).join('');
el.innerHTML = `
${kpiCards}
<div class="insights-charts-grid">
<div class="card insights-chart-card">
<h3>Uploads per day</h3>
<p class="insights-chart-hint">Last 14 days</p>
${uploadChart}
</div>
<div class="card insights-chart-card">
<h3>Client engagement</h3>
<p class="insights-chart-hint">Among clients in your scope</p>
${engagementChart}
</div>
<div class="card insights-chart-card">
<h3>Days since last activity</h3>
<p class="insights-chart-hint">Clients with at least one completion</p>
${idleChart}
</div>
</div>
<div class="card" style="margin-top:20px">
<h3 style="margin:0 0 8px">Completion by questionnaire</h3>
<p class="insights-chart-hint" style="margin:0 0 12px">Share of clients who completed each active questionnaire</p>
${completionChart}
<div class="table-wrapper">
<table class="data-table">
<thead>
<tr><th>Questionnaire</th><th>Completed</th><th>Rate</th></tr>
</thead>
<tbody>${qRows || '<tr><td colspan="3">No active questionnaires</td></tr>'}</tbody>
</table>
</div>
</div>
<div class="card" style="margin-top:20px">
<h3 style="margin:0 0 8px">Needs follow-up</h3>
<p class="data-toolbar-hint" style="margin:0 0 12px">
Clients who completed at least one questionnaire, sorted by longest time since any upload activity.
</p>
<div class="filter-bar">
<input type="search" id="followupListSearch" class="filter-search"
placeholder="Search client, coach, questionnaire, note…" value="${esc(followupSearch)}">
<span class="data-toolbar-hint" id="followupListCount"></span>
</div>
<div class="table-wrapper">
<table class="data-table">
<thead>
<tr>
<th>Client</th><th>Coach</th><th>First completed</th><th>First at</th>
<th>Last activity</th><th>Days idle</th><th>Note</th>
</tr>
</thead>
<tbody id="followupTableBody"></tbody>
</table>
</div>
</div>
`;
document.getElementById('followupListSearch').addEventListener('input', (e) => {
followupSearch = e.target.value;
renderFollowupTableBody();
});
renderFollowupTableBody();
}
function followupSearchText(c) {
return [
c.clientCode,
c.coachUsername,
c.firstQuestionnaireName,
c.firstQuestionnaireID,
c.note,
c.firstCompletedAt,
c.lastActivityAt,
c.daysSinceLastActivity != null ? String(c.daysSinceLastActivity) : '',
].filter(Boolean).join(' ');
}
function filteredFollowupClients() {
const q = followupSearch.trim().toLowerCase();
if (!q) return staleClients;
return staleClients.filter(c => followupSearchText(c).toLowerCase().includes(q));
}
function followupRowHTML(c) {
return `
<tr data-client="${esc(c.clientCode)}">
<td><code>${esc(c.clientCode)}</code></td>
<td>${esc(c.coachUsername)}</td>
<td>${esc(c.firstQuestionnaireName || '—')}</td>
<td>${esc(c.firstCompletedAt || '—')}</td>
<td>${esc(c.lastActivityAt || '—')}</td>
<td>${c.daysSinceLastActivity != null ? c.daysSinceLastActivity : '—'}</td>
<td>
<textarea class="followup-note-input" rows="2" data-client="${esc(c.clientCode)}"
placeholder="Follow-up note…">${esc(c.note || '')}</textarea>
<button type="button" class="btn btn-sm save-note-btn" data-client="${esc(c.clientCode)}">Save</button>
</td>
</tr>`;
}
function renderFollowupTableBody() {
const body = document.getElementById('followupTableBody');
const countEl = document.getElementById('followupListCount');
if (!body) return;
const filtered = filteredFollowupClients();
if (!filtered.length) {
body.innerHTML = `
<tr>
<td colspan="7" style="text-align:center;color:var(--text-secondary);padding:24px">
${staleClients.length ? 'No clients match' : 'No clients'}
</td>
</tr>`;
if (countEl) {
countEl.textContent = followupSearch.trim() && staleClients.length
? `0 of ${staleClients.length} clients`
: '';
}
return;
}
body.innerHTML = filtered.map(c => followupRowHTML(c)).join('');
if (countEl) {
const q = followupSearch.trim();
countEl.textContent = q
? `${filtered.length} of ${staleClients.length} clients`
: `${staleClients.length} client${staleClients.length === 1 ? '' : 's'}`;
}
body.querySelectorAll('.save-note-btn').forEach(btn => {
btn.addEventListener('click', () => {
const tr = btn.closest('tr');
const ta = tr?.querySelector('.followup-note-input');
saveNote(btn.dataset.client, ta);
});
});
}
async function saveNote(clientCode, ta) {
if (!ta) return;
try {
await apiPut('analytics.php', { clientCode, note: ta.value.trim() });
const row = staleClients.find(c => c.clientCode === clientCode);
if (row) row.note = ta.value.trim();
showToast('Note saved', 'success');
} catch (e) {
showToast(e.message, 'error');
}
}
function esc(s) {
const d = document.createElement('div');
d.textContent = s ?? '';
return d.innerHTML;
}
function formatChartDay(isoDate) {
if (!isoDate) return '';
const d = new Date(isoDate + 'T12:00:00');
if (Number.isNaN(d.getTime())) return isoDate.slice(5);
return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}
function chartMax(values, fallbackMax = 1) {
const m = Math.max(0, ...values);
return m > 0 ? m : fallbackMax;
}
function verticalBarChart(items, { emptyLabel = 'No data' } = {}) {
if (!items.length) {
return `<p class="insights-chart-hint">${esc(emptyLabel)}</p>`;
}
const max = chartMax(items.map(i => i.value));
return `
<div class="insights-vchart" role="img" aria-label="Bar chart">
${items.map(item => {
const pct = max ? Math.round((100 * item.value) / max) : 0;
return `
<div class="insights-vchart-col" title="${esc(item.title || `${item.label}: ${item.value}`)}">
<div class="insights-vchart-bar-wrap">
<div class="insights-vchart-bar" style="height:${pct}%"></div>
</div>
<span class="insights-vchart-value">${item.value}</span>
<span class="insights-vchart-label">${esc(item.label)}</span>
</div>`;
}).join('')}
</div>`;
}
function horizontalBarChart(items, { suffix = '%', max: fixedMax, variant = '' } = {}) {
if (!items.length) {
return '<p class="insights-chart-hint">No data</p>';
}
const max = fixedMax ?? chartMax(items.map(i => i.value));
const fillClass = variant === 'warn' ? 'insights-hchart-fill--warn'
: variant === 'muted' ? 'insights-hchart-fill--muted'
: '';
return `
<div class="insights-hchart" role="img" aria-label="Bar chart">
${items.map(item => {
const pct = max ? Math.round((100 * item.value) / max) : 0;
const display = suffix === '%' ? `${item.value}${suffix}` : String(item.value);
return `
<div class="insights-hchart-row" title="${esc(item.title || `${item.label}: ${display}`)}">
<span class="insights-hchart-label">${esc(item.label)}</span>
<div class="insights-hchart-track">
<div class="insights-hchart-fill ${fillClass}" style="width:${pct}%"></div>
</div>
<span class="insights-hchart-num">${esc(display)}</span>
</div>`;
}).join('')}
</div>`;
}
function idleBucketItems(clients) {
const buckets = [
{ label: '07 days', value: 0 },
{ label: '830 days', value: 0 },
{ label: '3190 days', value: 0 },
{ label: '90+ days', value: 0 },
{ label: 'No uploads yet', value: 0 },
];
for (const c of clients) {
const d = c.daysSinceLastActivity;
if (d == null) buckets[4].value += 1;
else if (d <= 7) buckets[0].value += 1;
else if (d <= 30) buckets[1].value += 1;
else if (d <= 90) buckets[2].value += 1;
else buckets[3].value += 1;
}
return buckets.filter(b => b.value > 0);
}