UX enhancements on data views

This commit is contained in:
2026-05-26 17:07:18 +02:00
parent 9d783b60a9
commit ea3a423186
8 changed files with 558 additions and 43 deletions

View File

@ -16,6 +16,17 @@ if (!is_array($order) || empty($order)) { http_response_code(500); echo "header_
if (!is_array($labels)) $labels = []; if (!is_array($labels)) $labels = [];
if (!is_array($vals)) $vals = []; if (!is_array($vals)) $vals = [];
function qdb_header_question_key(string $headerId): string {
if ($headerId === 'client_code') {
return 'client_code';
}
$dash = strpos($headerId, '-');
if ($dash === false) {
return $headerId;
}
return substr($headerId, $dash + 1);
}
function t_val(string $id, string $raw, array $vals): string { function t_val(string $id, string $raw, array $vals): string {
if ($raw === '' || $raw === 'None' || $raw === 'Done' || $raw === 'Not Done') return $raw; if ($raw === '' || $raw === 'None' || $raw === 'Done' || $raw === 'Not Done') return $raw;
$norm = strtolower(preg_replace('/[^a-z0-9]+/i', '_', $raw)); $norm = strtolower(preg_replace('/[^a-z0-9]+/i', '_', $raw));
@ -92,10 +103,11 @@ try {
} }
echo '<style> echo '<style>
table{border-collapse:collapse;width:100%;} #qdb-table{border-collapse:separate;border-spacing:0;width:100%;}
th,td{border:1px solid #ddd;padding:6px 8px;text-align:left;vertical-align:top;} #qdb-table th,#qdb-table td{border:1px solid #ddd;padding:6px 8px;text-align:left;vertical-align:top;}
thead th{background:#f7f7f7;position:sticky;top:0;z-index:1;} #qdb-table thead tr:nth-child(1) th{position:sticky;top:0;z-index:4;background:#f7f7f7;box-shadow:0 1px 0 #ddd;}
thead tr:nth-child(2) th{background:#fafafa;} #qdb-table thead tr:nth-child(2) th{position:sticky;top:var(--head1h,34px);z-index:3;background:#fafafa;box-shadow:0 1px 0 #ddd;}
#qdb-table thead tr:nth-child(1) th.chkcol{z-index:5;}
.nowrap{white-space:nowrap;} .nowrap{white-space:nowrap;}
.chkcol{width:36px;text-align:center;} .chkcol{width:36px;text-align:center;}
</style>'; </style>';
@ -108,13 +120,16 @@ try {
echo '<tr><th class="chkcol"></th>'; echo '<tr><th class="chkcol"></th>';
foreach ($order as $id) { foreach ($order as $id) {
$key = qdb_header_question_key($id);
$lbl = $labels[$id] ?? ''; $lbl = $labels[$id] ?? '';
echo '<th>'.htmlspecialchars($lbl).'</th>'; $title = $lbl !== '' ? $lbl : $id;
echo '<th class="col-key" title="'.htmlspecialchars($title).'">'.htmlspecialchars($key).'</th>';
} }
echo '</tr></thead><tbody>'; echo '</tr></thead><tbody>';
foreach ($clients as $client) { foreach ($clients as $client) {
echo '<tr data-client="'.htmlspecialchars($client).'">'; $rowClass = stripos($client, 'DEV-CL-') === 0 ? ' row-test-data' : '';
echo '<tr class="'.trim($rowClass).'" data-client="'.htmlspecialchars($client).'">';
echo '<td class="chkcol"><input type="checkbox" class="rowchk"></td>'; echo '<td class="chkcol"><input type="checkbox" class="rowchk"></td>';
foreach ($order as $id) { foreach ($order as $id) {
if ($id === 'client_code') { if ($id === 'client_code') {

View File

@ -16,16 +16,32 @@
.role-admin { background:#e3f2fd; color:#1565c0; } .role-admin { background:#e3f2fd; color:#1565c0; }
.role-supervisor { background:#fff3e0; color:#e65100; } .role-supervisor { background:#fff3e0; color:#e65100; }
.role-coach { background:#e8f5e9; color:#2e7d32; } .role-coach { background:#e8f5e9; color:#2e7d32; }
.table-wrap { overflow-x: auto; border-radius: 8px; } .table-wrap { overflow: auto; border-radius: 8px; -webkit-overflow-scrolling: touch; }
table { border-collapse: collapse; width: 100%; margin: 8px 0 24px; } #qdb-table { border-collapse: separate; border-spacing: 0; width: 100%; margin: 0; }
th, td { border: 1px solid #ddd; padding: 6px 8px; text-align: left; } #qdb-table th, #qdb-table td { border: 1px solid #ddd; padding: 6px 8px; text-align: left; }
#qdb-table thead tr:nth-child(1) th { position: sticky; top: 0; z-index: 3; background: #f7f7f7; } #qdb-table thead tr:nth-child(1) th {
#qdb-table thead tr:nth-child(2) th { position: sticky; top: var(--head1h, 34px); z-index: 2; background: #f7f7f7; } position: sticky; top: 0; z-index: 4;
background: #f7f7f7; box-shadow: 0 1px 0 #ddd;
}
#qdb-table thead tr:nth-child(2) th {
position: sticky; top: var(--head1h, 34px); z-index: 3;
background: #fafafa; box-shadow: 0 1px 0 #ddd;
}
#qdb-table thead tr:nth-child(1) th.chkcol {
z-index: 5;
}
.row-highlight { animation: hi 1.2s ease-in-out 0s 1; } .row-highlight { animation: hi 1.2s ease-in-out 0s 1; }
@keyframes hi { 0% { background:#fff9c4; } 100% { background:transparent; } } @keyframes hi { 0% { background:#fff9c4; } 100% { background:transparent; } }
.find-wrap { margin-left:auto; display:flex; gap:6px; align-items:center; } .find-wrap { margin-left:auto; display:flex; gap:6px; align-items:center; }
.find-wrap input[type="text"] { padding:6px 8px; border:1px solid #ccc; border-radius:8px; min-width:160px; } .find-wrap input[type="text"] { padding:6px 8px; border:1px solid #ccc; border-radius:8px; min-width:160px; }
#qdb-table th:nth-child(3), #qdb-table td:nth-child(3) { max-width:260px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } #qdb-table th:nth-child(3), #qdb-table td:nth-child(3) { max-width:260px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
#qdb-table tbody tr.row-test-data td { background:#fffde7; }
#qdb-table tbody tr.row-test-data:hover td { background:#fff9c4; }
#qdb-table tbody tr.row-filter-hidden { display:none; }
#qdb-table th.col-highlight { outline:2px solid #2563eb; outline-offset:-2px; }
.db-toolbar { display:flex; flex-wrap:wrap; gap:8px; align-items:center; margin-bottom:10px; }
.db-toolbar input, .db-toolbar select { padding:6px 8px; border:1px solid #ccc; border-radius:8px; font-size:14px; }
.db-toolbar label { font-size:14px; }
input[type="text"], input[type="password"], select { padding:8px; border:1px solid #ccc; border-radius:8px; font-size:14px; } input[type="text"], input[type="password"], select { padding:8px; border:1px solid #ccc; border-radius:8px; font-size:14px; }
.form-group { margin-bottom: 12px; } .form-group { margin-bottom: 12px; }
.form-group label { display:block; margin-bottom:4px; font-weight:500; } .form-group label { display:block; margin-bottom:4px; font-weight:500; }
@ -141,6 +157,23 @@
</div> </div>
</div> </div>
<div class="db-toolbar" id="dbToolbar" style="display:none">
<label>Filter rows <input id="filterRows" type="search" placeholder="Client code contains…" style="min-width:200px"></label>
<label>Test data
<select id="testDataFilter">
<option value="">Show all</option>
<option value="test">Test only (DEV-CL-*)</option>
<option value="hide-test">Hide test data</option>
</select>
</label>
<label>Go to column
<input id="findColumn" type="text" list="columnKeys" placeholder="Question key…" style="min-width:160px">
<datalist id="columnKeys"></datalist>
</label>
<button type="button" id="findColumnBtn">Go</button>
<span id="visibleRowCount" class="muted"></span>
</div>
<div class="table-wrap" id="tableWrap"> <div class="table-wrap" id="tableWrap">
<div id="dbContainer"><em>Loading...</em></div> <div id="dbContainer"><em>Loading...</em></div>
</div> </div>
@ -346,7 +379,13 @@ function sizeTableArea() {
const rect = wrap.getBoundingClientRect(); const rect = wrap.getBoundingClientRect();
const avail = window.innerHeight - rect.top - 16; const avail = window.innerHeight - rect.top - 16;
wrap.style.maxHeight = (avail > 200 ? avail : 200) + 'px'; wrap.style.maxHeight = (avail > 200 ? avail : 200) + 'px';
wrap.style.overflowY = 'auto'; wrap.style.overflow = 'auto';
const table = document.querySelector('#qdb-table');
if (table?.tHead?.rows?.[0]) {
const h1 = table.tHead.rows[0].getBoundingClientRect().height || 34;
table.style.setProperty('--head1h', `${Math.round(h1)}px`);
}
} }
async function loadDbView() { async function loadDbView() {
@ -385,6 +424,8 @@ async function loadDbView() {
$('#exportSelectedBtn').onclick = () => exportSelectedToXLSX(); $('#exportSelectedBtn').onclick = () => exportSelectedToXLSX();
buildClientSearchList(); buildClientSearchList();
buildColumnKeyList();
setupDbTableFilters();
const findInput = $('#findClient'); const findInput = $('#findClient');
const findBtn = $('#findBtn'); const findBtn = $('#findBtn');
@ -393,10 +434,15 @@ async function loadDbView() {
if (e.key === 'Enter') { e.preventDefault(); findBtn.click(); } if (e.key === 'Enter') { e.preventDefault(); findBtn.click(); }
}); });
if (table.tHead && table.tHead.rows.length >= 1) { const colInput = $('#findColumn');
const h1 = table.tHead.rows[0].getBoundingClientRect().height || 34; const colBtn = $('#findColumnBtn');
table.style.setProperty('--head1h', `${Math.round(h1)}px`); if (colBtn) colBtn.onclick = () => gotoColumn(colInput?.value?.trim() || '');
if (colInput) {
colInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') { e.preventDefault(); gotoColumn(colInput.value.trim()); }
});
} }
sizeTableArea(); sizeTableArea();
} catch (e) { } catch (e) {
$('#dbContainer').innerHTML = '<b>Error:</b> ' + e.message; $('#dbContainer').innerHTML = '<b>Error:</b> ' + e.message;
@ -438,6 +484,96 @@ function exportSelectedToXLSX() {
XLSX.writeFile(wb, 'SelectedClients.xlsx'); XLSX.writeFile(wb, 'SelectedClients.xlsx');
} }
/* ---------- DB TABLE FILTERS / NAV ---------- */
function isTestClientCode(code) {
return String(code || '').trim().toUpperCase().startsWith('DEV-CL-');
}
function buildColumnKeyList() {
const table = document.querySelector('#qdb-table');
const dl = document.querySelector('#columnKeys');
if (!table || !dl) return;
dl.innerHTML = '';
const head = table.tHead?.rows?.[0];
if (!head) return;
const keys = new Set();
for (let i = 1; i < head.cells.length; i++) {
const id = head.cells[i].getAttribute('data-id') || '';
if (!id) continue;
if (id === 'client_code') keys.add('client_code');
else {
const dash = id.indexOf('-');
keys.add(dash >= 0 ? id.slice(dash + 1) : id);
}
}
Array.from(keys).sort((a, b) => a.localeCompare(b, undefined, { numeric: true }))
.forEach(k => { const opt = document.createElement('option'); opt.value = k; dl.appendChild(opt); });
}
function setupDbTableFilters() {
const table = document.querySelector('#qdb-table');
const toolbar = $('#dbToolbar');
if (!table || !toolbar) return;
toolbar.style.display = '';
const filterInput = $('#filterRows');
const testFilter = $('#testDataFilter');
const countEl = $('#visibleRowCount');
function applyFilters() {
const q = (filterInput?.value || '').trim().toLowerCase();
const mode = testFilter?.value || '';
let visible = 0;
table.querySelectorAll('tbody tr').forEach(tr => {
const code = (tr.getAttribute('data-client') || tr.cells[1]?.textContent || '').trim();
const matchText = !q || code.toLowerCase().includes(q);
const isTest = isTestClientCode(code);
const matchTest = mode === 'test' ? isTest : mode === 'hide-test' ? !isTest : true;
const show = matchText && matchTest;
tr.classList.toggle('row-filter-hidden', !show);
if (show) visible++;
});
if (countEl) countEl.textContent = `${visible} row(s) visible`;
}
filterInput?.addEventListener('input', applyFilters);
testFilter?.addEventListener('change', applyFilters);
applyFilters();
}
function gotoColumn(query) {
if (!query) return;
const table = document.querySelector('#qdb-table');
if (!table) return;
const q = query.toLowerCase();
const head = table.tHead?.rows?.[0];
if (!head) return;
table.querySelectorAll('th.col-highlight').forEach(th => th.classList.remove('col-highlight'));
let targetIdx = -1;
for (let i = 1; i < head.cells.length; i++) {
const th = head.cells[i];
const id = (th.getAttribute('data-id') || '').toLowerCase();
const keyCell = table.tHead.rows[1]?.cells[i];
const key = (keyCell?.textContent || '').trim().toLowerCase();
if (id === q || key === q || id.endsWith('-' + q) || id.includes(q)) {
targetIdx = i;
th.classList.add('col-highlight');
th.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
break;
}
}
if (targetIdx < 0) {
alert('No column matching "' + query + '"');
return;
}
table.querySelectorAll('tbody td:nth-child(' + (targetIdx + 1) + ')').forEach(td => {
td.style.outline = '1px solid #93c5fd';
setTimeout(() => { td.style.outline = ''; }, 2000);
});
}
/* ---------- CLIENT SEARCH ---------- */ /* ---------- CLIENT SEARCH ---------- */
function buildClientSearchList() { function buildClientSearchList() {
const table = document.querySelector('#qdb-table'); const table = document.querySelector('#qdb-table');

View File

@ -258,13 +258,16 @@ body {
border-top: 1px solid var(--border); border-top: 1px solid var(--border);
} }
/* Tables */ /* Tables — scroll inside wrapper so sticky headers stay visible */
.table-wrapper { .table-wrapper {
overflow-x: auto; overflow: auto;
max-height: min(72vh, calc(100vh - 220px));
-webkit-overflow-scrolling: touch;
} }
table.data-table { table.data-table {
width: 100%; width: 100%;
border-collapse: collapse; border-collapse: separate;
border-spacing: 0;
font-size: .875rem; font-size: .875rem;
} }
table.data-table th, table.data-table th,
@ -282,11 +285,42 @@ table.data-table th {
background: #f8fafc; background: #f8fafc;
position: sticky; position: sticky;
top: 0; top: 0;
z-index: 1; z-index: 2;
box-shadow: 0 1px 0 var(--border);
} }
table.data-table tr:hover td { table.data-table tr:hover td {
background: #f8fafc; background: #f8fafc;
} }
table.data-table tbody tr.row-test-data td {
background: #fffde7;
}
table.data-table tbody tr.row-test-data:hover td {
background: #fff9c4;
}
#qdb-table tbody tr.row-test-data td {
background: #fffde7;
}
#qdb-table tbody tr.row-test-data:hover td {
background: #fff9c4;
}
table.data-table .sticky-col {
position: sticky;
left: 0;
z-index: 1;
background: var(--surface);
box-shadow: 2px 0 4px rgba(0, 0, 0, 0.06);
}
table.data-table thead th.sticky-col {
z-index: 5;
top: 0;
background: #f8fafc;
}
table.data-table tbody tr.row-test-data td.sticky-col {
background: #fffde7;
}
table.data-table tbody tr.row-test-data:hover td.sticky-col {
background: #fff9c4;
}
th.sortable { cursor: pointer; user-select: none; } th.sortable { cursor: pointer; user-select: none; }
th.sortable::after { content: ' \2195'; opacity: .4; } th.sortable::after { content: ' \2195'; opacity: .4; }
th.sort-asc::after { content: ' \2191'; opacity: 1; } th.sort-asc::after { content: ' \2191'; opacity: 1; }
@ -484,6 +518,42 @@ th.sort-desc::after { content: ' \2193'; opacity: 1; }
font-size: .85rem; font-size: .85rem;
background: var(--surface); background: var(--surface);
} }
.filter-bar input[type="search"],
.filter-bar input[type="text"].filter-search {
min-width: 180px;
}
.pagination-bar {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
margin-top: 12px;
font-size: .85rem;
color: var(--text-secondary);
}
.pagination-bar .btn {
min-width: 2.5rem;
}
.data-toolbar-hint {
font-size: .8rem;
color: var(--text-secondary);
}
#qdb-table th.col-key {
font-size: .75rem;
font-weight: 500;
text-transform: none;
letter-spacing: 0;
max-width: 140px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
#qdb-table thead tr:nth-child(1) th[data-id] {
font-size: .7rem;
max-width: 120px;
overflow: hidden;
text-overflow: ellipsis;
}
/* Empty state */ /* Empty state */
.empty-state { .empty-state {

View File

@ -1,5 +1,6 @@
import { apiGet, apiPost } from '../api.js'; import { apiGet, apiPost } from '../api.js';
import { showToast } from '../app.js'; import { showToast } from '../app.js';
import { isDevTestClientCode, isDevTestUsername, testDataRowClassForClient } from '../test-data.js';
let coaches = []; let coaches = [];
let clients = []; let clients = [];
@ -61,8 +62,9 @@ function renderAssignments() {
<ul class="coach-list" id="coachList"> <ul class="coach-list" id="coachList">
${coaches.map(c => { ${coaches.map(c => {
const count = (clientsByCoach[c.coachID] || []).length; const count = (clientsByCoach[c.coachID] || []).length;
const coachTest = isDevTestUsername(c.username) ? ' row-test-data' : '';
return ` return `
<li class="coach-list-item" data-id="${c.coachID}"> <li class="coach-list-item${coachTest}" data-id="${c.coachID}">
<div class="coach-name">${esc(c.username)}</div> <div class="coach-name">${esc(c.username)}</div>
${c.supervisorUsername ${c.supervisorUsername
? `<div class="coach-supervisor">${esc(c.supervisorUsername)}</div>` ? `<div class="coach-supervisor">${esc(c.supervisorUsername)}</div>`
@ -88,6 +90,11 @@ function renderAssignments() {
).join('')} ).join('')}
</select> </select>
<input type="text" id="clientSearch" placeholder="Search client code..." style="width:160px"> <input type="text" id="clientSearch" placeholder="Search client code..." style="width:160px">
<select id="clientTestFilter">
<option value="">All clients</option>
<option value="test">Test only</option>
<option value="hide-test">Hide test</option>
</select>
</div> </div>
</div> </div>
<div style="display:flex;gap:6px"> <div style="display:flex;gap:6px">
@ -95,7 +102,7 @@ function renderAssignments() {
<button class="btn btn-sm" id="clearSelBtn">Clear</button> <button class="btn btn-sm" id="clearSelBtn">Clear</button>
</div> </div>
</div> </div>
<div class="table-wrapper" style="max-height:420px;overflow-y:auto"> <div class="table-wrapper" style="max-height:420px">
<table class="data-table"> <table class="data-table">
<thead> <thead>
<tr> <tr>
@ -141,6 +148,7 @@ function renderAssignments() {
// Wire filters // Wire filters
document.getElementById('filterByCoach').addEventListener('change', renderClientRows); document.getElementById('filterByCoach').addEventListener('change', renderClientRows);
document.getElementById('clientSearch').addEventListener('input', renderClientRows); document.getElementById('clientSearch').addEventListener('input', renderClientRows);
document.getElementById('clientTestFilter').addEventListener('change', renderClientRows);
// Wire select all / clear // Wire select all / clear
document.getElementById('selectAllBtn').addEventListener('click', () => { document.getElementById('selectAllBtn').addEventListener('click', () => {
@ -166,6 +174,7 @@ function renderClientRows() {
const body = document.getElementById('clientTableBody'); const body = document.getElementById('clientTableBody');
const coachFilter = document.getElementById('filterByCoach').value; const coachFilter = document.getElementById('filterByCoach').value;
const search = document.getElementById('clientSearch').value.trim().toLowerCase(); const search = document.getElementById('clientSearch').value.trim().toLowerCase();
const testMode = document.getElementById('clientTestFilter')?.value || '';
let visible = clients; let visible = clients;
if (coachFilter === '__unassigned__') { if (coachFilter === '__unassigned__') {
@ -176,6 +185,11 @@ function renderClientRows() {
if (search) { if (search) {
visible = visible.filter(c => c.clientCode.toLowerCase().includes(search)); visible = visible.filter(c => c.clientCode.toLowerCase().includes(search));
} }
if (testMode === 'test') {
visible = visible.filter(c => isDevTestClientCode(c.clientCode));
} else if (testMode === 'hide-test') {
visible = visible.filter(c => !isDevTestClientCode(c.clientCode));
}
if (!visible.length) { if (!visible.length) {
body.innerHTML = `<tr><td colspan="3" style="text-align:center;color:var(--text-secondary);padding:24px">No clients match the current filter</td></tr>`; body.innerHTML = `<tr><td colspan="3" style="text-align:center;color:var(--text-secondary);padding:24px">No clients match the current filter</td></tr>`;
@ -184,7 +198,7 @@ function renderClientRows() {
} }
body.innerHTML = visible.map(c => ` body.innerHTML = visible.map(c => `
<tr> <tr class="${testDataRowClassForClient(c.clientCode).trim()}">
<td><input type="checkbox" class="client-cb" data-code="${esc(c.clientCode)}" value="${esc(c.clientCode)}"></td> <td><input type="checkbox" class="client-cb" data-code="${esc(c.clientCode)}" value="${esc(c.clientCode)}"></td>
<td><strong>${esc(c.clientCode)}</strong></td> <td><strong>${esc(c.clientCode)}</strong></td>
<td>${c.coachUsername ? esc(c.coachUsername) : '<span style="color:var(--text-secondary);font-style:italic">Unassigned</span>'}</td> <td>${c.coachUsername ? esc(c.coachUsername) : '<span style="color:var(--text-secondary);font-style:italic">Unassigned</span>'}</td>

View File

@ -1,8 +1,14 @@
import { apiGet, apiPost, apiDelete } from '../api.js'; import { apiGet, apiPost, apiDelete } from '../api.js';
import { showToast } from '../app.js'; import { showToast } from '../app.js';
import { isDevTestClientCode, testDataRowClassForClient } from '../test-data.js';
const PAGE_SIZE = 50;
let clientsList = []; let clientsList = [];
let coachesList = []; let coachesList = [];
let filterSearch = '';
let filterTestData = '';
let page = 0;
export async function clientsPage() { export async function clientsPage() {
const app = document.getElementById('app'); const app = document.getElementById('app');
@ -62,6 +68,15 @@ function renderClients() {
container.innerHTML = ` container.innerHTML = `
<div class="card"> <div class="card">
<div class="filter-bar">
<input type="search" id="clientListSearch" class="filter-search" placeholder="Search client code…" value="${esc(filterSearch)}">
<select id="clientTestFilter">
<option value="">All clients</option>
<option value="test" ${filterTestData === 'test' ? 'selected' : ''}>Test data only</option>
<option value="hide-test" ${filterTestData === 'hide-test' ? 'selected' : ''}>Hide test data</option>
</select>
<span class="data-toolbar-hint" id="clientListCount"></span>
</div>
<div class="table-wrapper"> <div class="table-wrapper">
<table class="data-table"> <table class="data-table">
<thead> <thead>
@ -71,25 +86,85 @@ function renderClients() {
<th>Actions</th> <th>Actions</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody id="clientsTableBody"></tbody>
${clientsList.map(c => clientRowHTML(c)).join('')}
</tbody>
</table> </table>
</div> </div>
<div class="pagination-bar" id="clientsPagination"></div>
</div>`; </div>`;
container.querySelectorAll('.delete-client-btn').forEach(btn => { document.getElementById('clientListSearch').addEventListener('input', (e) => {
filterSearch = e.target.value.trim();
page = 0;
renderClientTableBody();
});
document.getElementById('clientTestFilter').addEventListener('change', (e) => {
filterTestData = e.target.value;
page = 0;
renderClientTableBody();
});
renderClientTableBody();
}
function getFilteredClientsList() {
let list = clientsList;
if (filterSearch) {
const q = filterSearch.toLowerCase();
list = list.filter(c => (c.clientCode || '').toLowerCase().includes(q));
}
if (filterTestData === 'test') {
list = list.filter(c => isDevTestClientCode(c.clientCode));
} else if (filterTestData === 'hide-test') {
list = list.filter(c => !isDevTestClientCode(c.clientCode));
}
return list;
}
function renderClientTableBody() {
const body = document.getElementById('clientsTableBody');
const countEl = document.getElementById('clientListCount');
const filtered = getFilteredClientsList();
const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
if (page >= totalPages) page = totalPages - 1;
const slice = filtered.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE);
if (countEl) {
countEl.textContent = `${filtered.length} client${filtered.length === 1 ? '' : 's'}`;
}
if (!slice.length) {
body.innerHTML = `<tr><td colspan="3" style="text-align:center;color:var(--text-secondary);padding:24px">No clients match</td></tr>`;
} else {
body.innerHTML = slice.map(c => clientRowHTML(c)).join('');
body.querySelectorAll('.delete-client-btn').forEach(btn => {
btn.addEventListener('click', () => deleteClient(btn.dataset.code)); btn.addEventListener('click', () => deleteClient(btn.dataset.code));
}); });
} }
const pag = document.getElementById('clientsPagination');
if (!pag) return;
if (filtered.length <= PAGE_SIZE) {
pag.innerHTML = '';
return;
}
const from = page * PAGE_SIZE + 1;
const to = Math.min((page + 1) * PAGE_SIZE, filtered.length);
pag.innerHTML = `
<button type="button" class="btn btn-sm" id="clientsPagePrev" ${page <= 0 ? 'disabled' : ''}>Prev</button>
<span>Rows ${from}${to} of ${filtered.length}</span>
<button type="button" class="btn btn-sm" id="clientsPageNext" ${page >= totalPages - 1 ? 'disabled' : ''}>Next</button>
`;
document.getElementById('clientsPagePrev')?.addEventListener('click', () => { page--; renderClientTableBody(); });
document.getElementById('clientsPageNext')?.addEventListener('click', () => { page++; renderClientTableBody(); });
}
function clientRowHTML(c) { function clientRowHTML(c) {
const coach = c.coachUsername const coach = c.coachUsername
? `<strong>${esc(c.coachUsername)}</strong>` ? `<strong>${esc(c.coachUsername)}</strong>`
: `<span style="color:var(--text-secondary);font-style:italic">Unassigned</span>`; : `<span style="color:var(--text-secondary);font-style:italic">Unassigned</span>`;
return ` return `
<tr> <tr class="${testDataRowClassForClient(c.clientCode).trim()}">
<td><strong>${esc(c.clientCode)}</strong></td> <td><strong>${esc(c.clientCode)}</strong></td>
<td>${coach}</td> <td>${coach}</td>
<td> <td>
@ -104,7 +179,8 @@ async function deleteClient(clientCode) {
await apiDelete('clients.php', { clientCode }); await apiDelete('clients.php', { clientCode });
clientsList = clientsList.filter(c => c.clientCode !== clientCode); clientsList = clientsList.filter(c => c.clientCode !== clientCode);
showToast(`Client "${clientCode}" deleted`, 'success'); showToast(`Client "${clientCode}" deleted`, 'success');
renderClients(); if (!clientsList.length) renderClients();
else renderClientTableBody();
} catch (e) { } catch (e) {
showToast(e.message, 'error'); showToast(e.message, 'error');
} }

View File

@ -1,5 +1,12 @@
import { apiGet } from '../api.js'; import { apiGet } from '../api.js';
import { showToast } from '../app.js'; import { showToast } from '../app.js';
import {
isDevTestClientCode,
questionLocalKey,
testDataRowClassForClient,
} from '../test-data.js';
const PAGE_SIZE = 50;
let sortCol = null; let sortCol = null;
let sortDir = 'asc'; let sortDir = 'asc';
@ -11,6 +18,10 @@ let filterSupervisor = '';
let filterStatus = ''; let filterStatus = '';
let filterDateFrom = ''; let filterDateFrom = '';
let filterDateTo = ''; let filterDateTo = '';
let filterSearch = '';
let filterTestData = '';
let filterQuestion = '';
let page = 0;
export async function resultsPage(params) { export async function resultsPage(params) {
const app = document.getElementById('app'); const app = document.getElementById('app');
@ -21,6 +32,10 @@ export async function resultsPage(params) {
filterStatus = ''; filterStatus = '';
filterDateFrom = ''; filterDateFrom = '';
filterDateTo = ''; filterDateTo = '';
filterSearch = '';
filterTestData = '';
filterQuestion = '';
page = 0;
app.innerHTML = ` app.innerHTML = `
<div class="page-header"> <div class="page-header">
@ -78,47 +93,93 @@ function renderResults() {
to to
<input type="date" id="filterDateTo" value="${esc(filterDateTo)}"> <input type="date" id="filterDateTo" value="${esc(filterDateTo)}">
</label> </label>
<input type="search" id="filterSearch" class="filter-search" placeholder="Search client code…" value="${esc(filterSearch)}">
<select id="filterTestData">
<option value="">All clients</option>
<option value="test" ${filterTestData === 'test' ? 'selected' : ''}>Test data only</option>
<option value="hide-test" ${filterTestData === 'hide-test' ? 'selected' : ''}>Hide test data</option>
</select>
<input type="search" id="filterQuestion" placeholder="Go to question key…" value="${esc(filterQuestion)}" style="min-width:160px" list="questionKeyList">
<datalist id="questionKeyList"></datalist>
<button type="button" class="btn btn-sm" id="gotoQuestionBtn">Go to column</button>
<button type="button" class="btn btn-sm" id="clearFiltersBtn">Clear filters</button> <button type="button" class="btn btn-sm" id="clearFiltersBtn">Clear filters</button>
<span style="margin-left:auto;font-size:.85rem;color:var(--text-secondary)" id="resultCount"></span> <span style="margin-left:auto;font-size:.85rem;color:var(--text-secondary)" id="resultCount"></span>
<a id="exportCsvLink" class="btn btn-sm" href="#">Export CSV</a> <a id="exportCsvLink" class="btn btn-sm" href="#">Export CSV</a>
</div> </div>
<p class="data-toolbar-hint" style="margin-top:8px">Question columns show keys; hover headers for full text. Test rows (DEV-CL-*) have a yellow background.</p>
</div> </div>
<div class="card"> <div class="card">
<div class="table-wrapper"> <div class="table-wrapper" id="resultsTableWrap">
<table class="data-table" id="resultsTable"> <table class="data-table" id="resultsTable">
<thead><tr id="resultsHead"></tr></thead> <thead><tr id="resultsHead"></tr></thead>
<tbody id="resultsBody"></tbody> <tbody id="resultsBody"></tbody>
</table> </table>
</div> </div>
<div class="pagination-bar" id="paginationBar"></div>
</div> </div>
`; `;
const qKeyList = document.getElementById('questionKeyList');
qKeyList.innerHTML = questionsDef
.map(q => `<option value="${esc(questionLocalKey(q.questionID, q.defaultText))}"></option>`)
.join('');
document.getElementById('filterSupervisor').addEventListener('change', (e) => { document.getElementById('filterSupervisor').addEventListener('change', (e) => {
filterSupervisor = e.target.value; filterSupervisor = e.target.value;
page = 0;
renderTableRows(); renderTableRows();
}); });
document.getElementById('filterCoach').addEventListener('change', (e) => { document.getElementById('filterCoach').addEventListener('change', (e) => {
filterCoach = e.target.value; filterCoach = e.target.value;
page = 0;
renderTableRows(); renderTableRows();
}); });
document.getElementById('filterStatus').addEventListener('change', (e) => { document.getElementById('filterStatus').addEventListener('change', (e) => {
filterStatus = e.target.value; filterStatus = e.target.value;
page = 0;
renderTableRows(); renderTableRows();
}); });
document.getElementById('filterDateFrom').addEventListener('change', (e) => { document.getElementById('filterDateFrom').addEventListener('change', (e) => {
filterDateFrom = e.target.value; filterDateFrom = e.target.value;
page = 0;
renderTableRows(); renderTableRows();
}); });
document.getElementById('filterDateTo').addEventListener('change', (e) => { document.getElementById('filterDateTo').addEventListener('change', (e) => {
filterDateTo = e.target.value; filterDateTo = e.target.value;
page = 0;
renderTableRows(); renderTableRows();
}); });
document.getElementById('filterSearch').addEventListener('input', (e) => {
filterSearch = e.target.value.trim();
page = 0;
renderTableRows();
});
document.getElementById('filterTestData').addEventListener('change', (e) => {
filterTestData = e.target.value;
page = 0;
renderTableRows();
});
document.getElementById('gotoQuestionBtn').addEventListener('click', () => {
filterQuestion = document.getElementById('filterQuestion').value.trim();
scrollToQuestionColumn(filterQuestion);
});
document.getElementById('filterQuestion').addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
filterQuestion = e.target.value.trim();
scrollToQuestionColumn(filterQuestion);
}
});
document.getElementById('clearFiltersBtn').addEventListener('click', () => { document.getElementById('clearFiltersBtn').addEventListener('click', () => {
filterCoach = ''; filterCoach = '';
filterSupervisor = ''; filterSupervisor = '';
filterStatus = ''; filterStatus = '';
filterDateFrom = ''; filterDateFrom = '';
filterDateTo = ''; filterDateTo = '';
filterSearch = '';
filterTestData = '';
filterQuestion = '';
page = 0;
renderResults(); renderResults();
}); });
document.getElementById('exportCsvLink').addEventListener('click', (e) => { document.getElementById('exportCsvLink').addEventListener('click', (e) => {
@ -140,17 +201,24 @@ function renderTableHead() {
{ key: 'sumPoints', label: 'Score' }, { key: 'sumPoints', label: 'Score' },
{ key: 'completedAt', label: 'Completed' }, { key: 'completedAt', label: 'Completed' },
]; ];
const questionCols = questionsDef.map(q => ({ const questionCols = questionsDef.map(q => {
const qKey = questionLocalKey(q.questionID, q.defaultText);
return {
key: `q_${q.questionID}`, key: `q_${q.questionID}`,
label: q.defaultText, label: qKey,
title: q.defaultText || qKey,
questionID: q.questionID, questionID: q.questionID,
})); questionKey: qKey,
};
});
const allCols = [...fixedCols, ...questionCols]; const allCols = [...fixedCols, ...questionCols];
head.innerHTML = allCols.map(col => { head.innerHTML = allCols.map((col, idx) => {
let cls = 'sortable'; let cls = 'sortable';
if (sortCol === col.key) cls += sortDir === 'asc' ? ' sort-asc' : ' sort-desc'; if (sortCol === col.key) cls += sortDir === 'asc' ? ' sort-asc' : ' sort-desc';
return `<th class="${cls}" data-key="${col.key}" title="${esc(col.label)}">${esc(col.label)}</th>`; if (idx === 0) cls += ' sticky-col';
const title = col.title ? ` title="${esc(col.title)}"` : '';
return `<th class="${cls}" data-key="${col.key}"${title}>${esc(col.label)}</th>`;
}).join(''); }).join('');
head.querySelectorAll('th.sortable').forEach(th => { head.querySelectorAll('th.sortable').forEach(th => {
@ -158,12 +226,31 @@ function renderTableHead() {
const key = th.dataset.key; const key = th.dataset.key;
if (sortCol === key) sortDir = sortDir === 'asc' ? 'desc' : 'asc'; if (sortCol === key) sortDir = sortDir === 'asc' ? 'desc' : 'asc';
else { sortCol = key; sortDir = 'asc'; } else { sortCol = key; sortDir = 'asc'; }
page = 0;
renderTableHead(); renderTableHead();
renderTableRows(); renderTableRows();
}); });
}); });
} }
function scrollToQuestionColumn(query) {
if (!query) return;
const q = query.toLowerCase();
const th = [...document.querySelectorAll('#resultsHead th')].find(el => {
const key = (el.dataset.key || '').toLowerCase();
const text = (el.textContent || '').trim().toLowerCase();
const title = (el.getAttribute('title') || '').toLowerCase();
return text === q || title === q || key.endsWith(q) || text.includes(q);
});
if (!th) {
showToast(`No column matching "${query}"`, 'error');
return;
}
th.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
th.style.outline = '2px solid var(--primary)';
setTimeout(() => { th.style.outline = ''; }, 2000);
}
function getCoachFilterOptions() { function getCoachFilterOptions() {
const map = new Map(); const map = new Map();
allClients.forEach(c => { allClients.forEach(c => {
@ -203,9 +290,49 @@ function getFilteredClients() {
return true; return true;
}); });
} }
if (filterSearch) {
const q = filterSearch.toLowerCase();
clients = clients.filter(c => (c.clientCode || '').toLowerCase().includes(q));
}
if (filterTestData === 'test') {
clients = clients.filter(c => isDevTestClientCode(c.clientCode));
} else if (filterTestData === 'hide-test') {
clients = clients.filter(c => !isDevTestClientCode(c.clientCode));
}
return clients; return clients;
} }
function renderPagination(totalRows) {
const bar = document.getElementById('paginationBar');
if (!bar) return;
const totalPages = Math.max(1, Math.ceil(totalRows / PAGE_SIZE));
if (page >= totalPages) page = totalPages - 1;
if (page < 0) page = 0;
if (totalRows <= PAGE_SIZE) {
bar.innerHTML = totalRows
? `<span>${totalRows} row${totalRows === 1 ? '' : 's'}</span>`
: '';
return;
}
const from = page * PAGE_SIZE + 1;
const to = Math.min((page + 1) * PAGE_SIZE, totalRows);
bar.innerHTML = `
<button type="button" class="btn btn-sm" id="pagePrev" ${page <= 0 ? 'disabled' : ''}>Prev</button>
<span>Rows ${from}${to} of ${totalRows} (page ${page + 1}/${totalPages})</span>
<button type="button" class="btn btn-sm" id="pageNext" ${page >= totalPages - 1 ? 'disabled' : ''}>Next</button>
`;
document.getElementById('pagePrev')?.addEventListener('click', () => {
page--;
renderTableRows();
});
document.getElementById('pageNext')?.addEventListener('click', () => {
page++;
renderTableRows();
});
}
function dateInputToUnixStart(yyyyMmDd) { function dateInputToUnixStart(yyyyMmDd) {
const [y, m, d] = yyyyMmDd.split('-').map(Number); const [y, m, d] = yyyyMmDd.split('-').map(Number);
return Math.floor(new Date(y, m - 1, d).getTime() / 1000); return Math.floor(new Date(y, m - 1, d).getTime() / 1000);
@ -237,11 +364,17 @@ function renderTableRows() {
document.getElementById('resultCount').textContent = `${clients.length} client${clients.length === 1 ? '' : 's'}`; document.getElementById('resultCount').textContent = `${clients.length} client${clients.length === 1 ? '' : 's'}`;
renderPagination(clients.length);
if (!clients.length) { if (!clients.length) {
body.innerHTML = `<tr><td colspan="99" style="text-align:center;color:var(--text-secondary);padding:30px">No results found</td></tr>`; body.innerHTML = `<tr><td colspan="99" style="text-align:center;color:var(--text-secondary);padding:30px">No results found</td></tr>`;
return; return;
} }
const totalPages = Math.max(1, Math.ceil(clients.length / PAGE_SIZE));
if (page >= totalPages) page = totalPages - 1;
clients = clients.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE);
// Build option text lookup // Build option text lookup
const optionMap = {}; const optionMap = {};
questionsDef.forEach(q => { questionsDef.forEach(q => {
@ -269,8 +402,8 @@ function renderTableRows() {
return '<td>—</td>'; return '<td>—</td>';
}).join(''); }).join('');
return `<tr> return `<tr class="${testDataRowClassForClient(c.clientCode).trim()}">
<td>${esc(c.clientCode)}</td> <td class="sticky-col">${esc(c.clientCode)}</td>
<td>${esc(coachDisplayName(c))}</td> <td>${esc(coachDisplayName(c))}</td>
<td>${esc(supervisorDisplayName(c))}</td> <td>${esc(supervisorDisplayName(c))}</td>
<td>${statusBadge}</td> <td>${statusBadge}</td>
@ -313,7 +446,7 @@ function exportCSV() {
}); });
const headers = ['clientCode', 'coach', 'supervisor', 'status', 'sumPoints', 'completedAt', const headers = ['clientCode', 'coach', 'supervisor', 'status', 'sumPoints', 'completedAt',
...questionsDef.map(q => q.defaultText)]; ...questionsDef.map(q => questionLocalKey(q.questionID, q.defaultText))];
const rows = clients.map(c => { const rows = clients.map(c => {
const base = [ const base = [

View File

@ -1,5 +1,6 @@
import { apiGet, apiPost, apiDelete } from '../api.js'; import { apiGet, apiPost, apiDelete } from '../api.js';
import { getRole, getUser, showToast } from '../app.js'; import { getRole, getUser, showToast } from '../app.js';
import { isDevTestUsername, testDataRowClassForUser } from '../test-data.js';
// Roles an admin can create; supervisors can only create coaches // Roles an admin can create; supervisors can only create coaches
const CREATEABLE_ROLES = { const CREATEABLE_ROLES = {
@ -10,6 +11,8 @@ const CREATEABLE_ROLES = {
let usersList = []; let usersList = [];
let supervisorsList = []; let supervisorsList = [];
let callerRole = ''; let callerRole = '';
let filterSearch = '';
let filterTestData = '';
export async function usersPage() { export async function usersPage() {
callerRole = getRole(); callerRole = getRole();
@ -86,8 +89,19 @@ function renderUsers() {
{ label: 'Coaches', key: 'coach' }, { label: 'Coaches', key: 'coach' },
]; ];
container.innerHTML = groups.map(group => { container.innerHTML = `
const users = byRole[group.key] || []; <div class="card" style="margin-bottom:16px">
<div class="filter-bar">
<input type="search" id="userListSearch" class="filter-search" placeholder="Search username…" value="${esc(filterSearch)}">
<select id="userTestFilter">
<option value="">All users</option>
<option value="test" ${filterTestData === 'test' ? 'selected' : ''}>Test data only (dev_*)</option>
<option value="hide-test" ${filterTestData === 'hide-test' ? 'selected' : ''}>Hide test data</option>
</select>
</div>
</div>
` + groups.map(group => {
const users = filterUsers(byRole[group.key] || []);
if (!users.length) return ''; if (!users.length) return '';
return ` return `
<div class="card" style="margin-bottom:16px"> <div class="card" style="margin-bottom:16px">
@ -111,11 +125,34 @@ function renderUsers() {
</div>`; </div>`;
}).join(''); }).join('');
document.getElementById('userListSearch')?.addEventListener('input', (e) => {
filterSearch = e.target.value.trim();
renderUsers();
});
document.getElementById('userTestFilter')?.addEventListener('change', (e) => {
filterTestData = e.target.value;
renderUsers();
});
container.querySelectorAll('.delete-user-btn').forEach(btn => { container.querySelectorAll('.delete-user-btn').forEach(btn => {
btn.addEventListener('click', () => deleteUser(btn.dataset.id, btn.dataset.name)); btn.addEventListener('click', () => deleteUser(btn.dataset.id, btn.dataset.name));
}); });
} }
function filterUsers(users) {
let list = users;
if (filterSearch) {
const q = filterSearch.toLowerCase();
list = list.filter(u => (u.username || '').toLowerCase().includes(q));
}
if (filterTestData === 'test') {
list = list.filter(u => isDevTestUsername(u.username));
} else if (filterTestData === 'hide-test') {
list = list.filter(u => !isDevTestUsername(u.username));
}
return list;
}
function userRowHTML(u, myUsername) { function userRowHTML(u, myUsername) {
const isSelf = u.username === myUsername; const isSelf = u.username === myUsername;
const detail = u.role === 'coach' const detail = u.role === 'coach'
@ -134,7 +171,7 @@ function userRowHTML(u, myUsername) {
); );
return ` return `
<tr> <tr class="${testDataRowClassForUser(u.username).trim()}">
<td> <td>
<strong>${esc(u.username)}</strong> <strong>${esc(u.username)}</strong>
${isSelf ? '<span class="badge badge-you">You</span>' : ''} ${isSelf ? '<span class="badge badge-you">You</span>' : ''}

34
website/js/test-data.js Normal file
View File

@ -0,0 +1,34 @@
/** Dev fixture prefixes (import script / dev_fixture.php). */
export function isDevTestClientCode(code) {
const c = String(code ?? '').trim();
return c.toUpperCase().startsWith('DEV-CL-');
}
export function isDevTestUsername(username) {
return String(username ?? '').trim().toLowerCase().startsWith('dev_');
}
export function testDataRowClassForClient(clientCode) {
return isDevTestClientCode(clientCode) ? ' row-test-data' : '';
}
export function testDataRowClassForUser(username) {
return isDevTestUsername(username) ? ' row-test-data' : '';
}
/** Local question key from full questionID (hash__q5 → q5). */
export function questionLocalKey(questionID, fallback = '') {
const id = String(questionID ?? '');
const sep = id.lastIndexOf('__');
if (sep >= 0) return id.slice(sep + 2);
return fallback || id;
}
/** header_order.json column id → question key (questionnaire_x-y → y). */
export function headerColumnQuestionKey(headerId) {
const id = String(headerId ?? '');
if (id === 'client_code') return 'client_code';
const dash = id.indexOf('-');
if (dash < 0) return id;
return id.slice(dash + 1);
}