Files
Project-SDE-WP-Suite/html/users.js
Matt Mabrey 1c4d1bbccb T12.5: CR-020 bulk delete with typed confirmation
'Delete selected…' in the bulk bar. The dialog lists every affected
username (scrolling inside the dialog for a long list), says the
delete cannot be undone and offers disable instead, and sends nothing
until the word DELETE is typed in capitals, whatever the count
(confirmed 2026-10-06). Wrong words keep the dialog open with the
reason; cancel sends nothing.

Your own account cannot be selected; if it ever reached the request,
the server refuses that row and the report names it with the reason.

The bulk delete is a prompt-style dialog, so it is covered in
tests/console_dialogs_check.py (its docstring asks for exactly this):
new section 4 drives it in the browser with native dialogs poisoned.
DOM harness: 48/48.
2026-10-06 11:05:01 -07:00

780 lines
40 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* User Directory for the Work Package Suite.
Moved out of the Admin Console because user administration is no longer
admin-only: a PROJECT SUPER USER creates and manages the accounts on the projects
they administer, which means the page has to be reachable by people who must never
see the console's settings, diagnostics or app-wide switches.
ACCESS — three audiences on one page, decided by GET /api/auth/user-scope:
• App admin every account, every control.
• Project super user the accounts on the projects they administer. Controls
appear per row: an account that is also on a job they
don't administer is read-only, and the row says why.
• Everyone else a read-only directory of the people on their own
projects. No controls at all.
The server enforces every one of those rules (server/app.py: require_user_manager,
require_manage_user, visible_user_ids). Nothing here is a security boundary — it is
here so nobody is shown a button that would only 403, and so the reason is on the
page instead of in an alert.
Shared helpers (api, uesc, jsq, the role vocabulary) come from console-util.js. */
let _users = []; // the directory as the server scoped it
let _scope = null; // GET /api/auth/user-scope
let _meId = null;
// CR-020: the rows checked for a bulk action. Client-side UI state only - every
// bulk action is decided and audited by the server, row by row (T12.1).
let _selected = new Set();
let _shownSelectable = []; // ids the current filter shows AND this caller may select
// ── boot ──────────────────────────────────────────────────────────────────────
async function boot(){
document.getElementById('users-main').style.display = '';
_meId = (window.WP_USER && window.WP_USER.id) || null;
const { status, json } = await api('GET','/api/auth/user-scope');
// A failed scope call must not leave the page pretending to be read-only-with-no-
// reason: fall back to the least-privileged rendering and say so.
_scope = (status === 200 && json) ? json : { can_manage_users:false, scope:'projects',
grantable_roles:[], grantable_project_roles:[], managed_projects:[], project_roles:PROJECT_ROLES };
if(status !== 200){
banner('scope-banner','bad','✕ '+apiError(status, json, 'Could not work out what you may do here')+
' Showing the directory read-only.');
} else {
renderScope();
}
renderCreateForm();
renderBulkActions();
loadUsers();
}
function banner(id, kind, text){
const el = document.getElementById(id);
if(!el) return;
if(!text){ el.innerHTML=''; return; }
el.className = 'banner' + (kind ? ' '+kind : '');
el.textContent = text;
}
// What this account may do here, stated once at the top rather than implied by which
// buttons happen to be missing.
function renderScope(){
const el = document.getElementById('scope-banner');
const sub = document.getElementById('dir-sub');
if(!_scope.can_manage_users){
el.innerHTML = '';
if(sub) sub.textContent = 'The people on your projects — who they are, and how to reach them. '+
'Only an administrator or a Project Super User can change accounts.';
return;
}
if(_scope.scope === 'all'){
el.className = 'banner';
el.innerHTML = 'You are an <strong>Administrator</strong>: you manage every account in the suite. '+
'App settings, diagnostics and the default-member rules live in the '+
'<a class="home" href="admin.html">Admin Console</a>.';
if(sub) sub.textContent = 'Every login account in the suite.';
return;
}
const names = (_scope.managed_projects||[]).map(p => p.name || p.number || p.id);
el.className = 'banner';
el.innerHTML = 'You are a <strong>Project Super User</strong> on '+
(names.length === 1 ? uesc(names[0]) : names.length+' projects')+
' — you create and manage the accounts on '+(names.length === 1 ? 'that project' : 'those projects')+
(names.length > 1 ? ': <strong>'+names.map(uesc).join('</strong>, <strong>')+'</strong>' : '')+'. '+
'An account that is also on a project you don’t administer is read-only here.';
if(sub) sub.textContent = 'The people on your projects, and the accounts you administer.';
}
// ── the table ─────────────────────────────────────────────────────────────────
async function loadUsers(){
const wrap = document.getElementById('users-table');
const { status, json } = await api('GET','/api/auth/users');
if(status !== 200 || !Array.isArray(json)){
banner('users-banner','bad','✕ '+apiError(status, json, 'Could not load the directory'));
wrap.innerHTML = ''; return;
}
banner('users-banner','', '');
_users = json;
// Fresh data: any earlier selection may name accounts that changed or are gone.
clearSelection(false);
renderUsers();
}
function manages(){ return !!(_scope && _scope.can_manage_users); }
// ── selection (CR-020, T12.2) ─────────────────────────────────────────────────
// A row is selectable when this caller may change the account. Your own row is
// not: every bulk action that could touch it (disable, demote, delete) is refused
// for your own account, so offering it would only produce a guaranteed failure.
function selectable(u){ return manages() && !!u.manageable && u.id !== _meId; }
// The search box and the filter both decide which rows are shown. Changing either
// clears the selection (decided 2026-10-06), so no row hidden by the filter can
// stay selected and be acted on without being seen.
function filterChanged(){
const had = _selected.size;
clearSelection(false);
renderUsers();
banner('sel-banner', '', had ? 'Selection cleared: the filter changed. Select the rows again.' : '');
}
function clearSelection(announce){
const had = _selected.size;
_selected = new Set();
updateSelectionUI();
banner('sel-banner', '', (announce && had) ? 'Selection cleared.' : '');
}
function setRowSelected(id, on){
if(on) _selected.add(id); else _selected.delete(id);
}
// Select-all acts on the rows the filter shows, never on the whole directory.
function toggleSelectAll(on){
_shownSelectable.forEach(id => setRowSelected(id, on));
banner('sel-banner', '', '');
updateSelectionUI();
}
// Reflect _selected into the page without re-rendering the table, so keyboard
// focus stays on the checkbox that was just used.
function updateSelectionUI(){
const wrap = document.getElementById('users-table');
if(wrap){
wrap.querySelectorAll('input.selbox').forEach(cb => {
const on = _selected.has(cb.dataset.id);
cb.checked = on;
const tr = cb.closest('tr');
if(tr) tr.classList.toggle('is-selected', on);
});
const all = document.getElementById('sel-all');
if(all){
const n = _shownSelectable.filter(id => _selected.has(id)).length;
all.checked = n > 0 && n === _shownSelectable.length;
all.indeterminate = n > 0 && n < _shownSelectable.length;
all.disabled = !_shownSelectable.length;
}
}
const bar = document.getElementById('bulk-bar');
if(bar){
const n = _selected.size;
bar.hidden = n === 0;
const c = document.getElementById('bulk-count');
if(c) c.textContent = n + ' selected';
}
}
// One listener for every checkbox in the table (event delegation): no ids are
// bound into inline handlers, so there is nothing to escape.
document.addEventListener('change', e => {
const t = e.target;
if(!(t instanceof HTMLInputElement)) return;
if(t.id === 'sel-all'){ toggleSelectAll(t.checked); return; }
if(t.classList.contains('selbox')){
setRowSelected(t.dataset.id, t.checked);
banner('sel-banner', '', '');
updateSelectionUI();
}
});
// ── bulk actions (CR-020, T12.3) ──────────────────────────────────────────────
// The toolbar offers only what this caller may do: the roles they may grant, the
// projects they administer, the per-project roles they may hand out. The server
// re-checks every row anyway (T12.1); this is so nobody is offered a choice that
// can only fail.
function renderBulkActions(){
const box = document.getElementById('bulk-actions');
const csvBtn = document.getElementById('csv-btn');
if(csvBtn) csvBtn.hidden = !manages();
if(!box || !manages()) return;
const grantable = PERM_ROLES.filter(r => (_scope.grantable_roles || []).indexOf(r) >= 0);
const projects = (_scope.managed_projects || []).slice()
.sort((a,b) => (a.archived?1:0) - (b.archived?1:0));
const projRoles = PROJECT_SCOPED_ROLES.filter(r => (_scope.grantable_project_roles || []).indexOf(r) >= 0);
const group = (label, inner) => '<div class="bulkgroup" role="group" aria-label="'+uesc(label)+'">'+
'<span class="bulklabel">'+uesc(label)+'</span>'+inner+'</div>';
box.innerHTML =
group('Permissions',
'<select id="bulk-role" aria-label="New permissions role">'+
grantable.map(r => '<option value="'+r+'"'+(r==='project_user'?' selected':'')+'>'+uesc(PERM_LABELS[r])+'</option>').join('')+
'</select>'+
'<button type="button" onclick="bulkRole()">Set permissions</button>') +
group('Sign-in',
'<button type="button" onclick="bulkActive(true)">Enable</button>'+
'<button type="button" onclick="bulkActive(false)">Disable</button>') +
(projects.length ? group('Project access',
'<select id="bulk-project" aria-label="Project">'+
projects.map(p => '<option value="'+uesc(p.id)+'">'+uesc((p.name||'(unnamed)')+(p.number?' '+p.number:'')+
(p.archived?' (archived)':''))+'</option>').join('')+
'</select>'+
'<select id="bulk-project-role" aria-label="Role on that project, for Add">'+
'<option value="">Role: same as account</option>'+
projRoles.map(r => '<option value="'+r+'">Role: '+uesc(PERM_LABELS[r])+' here</option>').join('')+
'</select>'+
'<button type="button" onclick="bulkProject(\'add\')">Add to project</button>'+
'<button type="button" onclick="bulkProject(\'remove\')">Remove from project</button>') : '') +
group('Delete',
'<button type="button" class="danger" onclick="bulkDelete()">Delete selected…</button>');
}
function selectedIds(){ return _users.filter(u => _selected.has(u.id)).map(u => u.id); }
function people(n){ return n + ' user' + (n === 1 ? '' : 's'); }
function selVal(id){ return (document.getElementById(id) || {}).value || ''; }
function selText(id){
const s = document.getElementById(id);
return (s && s.selectedIndex >= 0) ? s.options[s.selectedIndex].text : '';
}
// One path for every bulk action: confirm through the dialog kit with the exact
// count, send, report row by row, reload. A reload clears the selection, which is
// right: the rows may have changed underneath it.
async function runBulk(path, body, ask){
const ids = selectedIds();
if(!ids.length) return;
if(!(await wpConfirmDialog({title: ask.title, okLabel: ask.ok, message: ask.message(ids.length)}))) return;
return sendBulk(path, body, ask.title, ids);
}
async function sendBulk(path, body, title, ids){
bannerHtml('bulk-banner', '', uesc(title)+': working on '+uesc(people(ids.length))+'…');
const { status, json } = await api('POST', path, Object.assign({ user_ids: ids }, body));
if(status !== 200 || !json || !Array.isArray(json.results)){
bannerHtml('bulk-banner', 'bad', '✕ '+uesc(apiError(status, json, title+' failed'))+' Nothing was changed.');
return;
}
showBulkResult(json, title);
loadUsers();
}
// T12.5: delete is permanent (a hard delete, as for one account) and one bad
// multi-select now removes many, so it asks more than the other actions do:
// every affected username is listed, and nothing is sent until the word DELETE
// is typed, whatever the count (confirmed 2026-10-06). Your own account cannot
// be selected; if it ever reached the request, the server refuses that row and
// the report names it.
async function bulkDelete(){
const chosen = _users.filter(u => _selected.has(u.id));
if(!chosen.length) return;
const n = chosen.length;
const typed = await wpPromptDialog({
title: 'Delete '+people(n),
message: 'Delete '+(n === 1 ? 'this account' : 'these '+n+' accounts')+'? Each one, and every project '+
'assignment it has, is removed. This cannot be undone. Disable them instead if you only want to '+
'block sign-in.\n\n'+chosen.map(u => '• '+u.username+(u.full_name ? ' ('+u.full_name+')' : '')).join('\n'),
label: 'Type DELETE to confirm',
value: '',
okLabel: 'Delete '+people(n),
validate: v => v === 'DELETE' ? '' : 'Type DELETE, in capital letters, to confirm.',
});
if(typed !== 'DELETE') return;
return sendBulk('/api/auth/bulk-users/delete', {}, 'Delete accounts', chosen.map(u => u.id));
}
// Every row is accounted for: changed, already so, or failed with the server's
// reason. A batch that partly failed never reads as a success (CR-020).
function showBulkResult(json, title){
const failed = json.results.filter(r => r.status === 'failed');
const parts = [json.ok+' changed'];
if(json.unchanged) parts.push(json.unchanged+' already set');
if(failed.length) parts.push(failed.length+' failed');
const kind = !failed.length ? 'ok' : (json.ok + json.unchanged ? 'warn' : 'bad');
const lead = (failed.length ? (kind === 'bad' ? '✕ ' : '⚠ ') : '✓ ')+uesc(title)+': '+parts.join(', ')+'.';
const list = failed.length
? '<ul>'+failed.map(r => '<li><strong>'+uesc(r.username || r.user_id)+'</strong>: '+uesc(r.reason)+'</li>').join('')+'</ul>'
: '';
bannerHtml('bulk-banner', kind, lead + list);
}
function bannerHtml(id, kind, html){
const el = document.getElementById(id);
if(!el) return;
el.className = 'banner' + (kind ? ' '+kind : '');
el.innerHTML = html;
}
function bulkRole(){
const role = selVal('bulk-role');
if(!role) return;
return runBulk('/api/auth/bulk-users/role', { role }, {
title: 'Set permissions', ok: 'Change permissions',
message: n => 'Set permissions to '+(PERM_LABELS[role] || role)+' for '+people(n)+'?\n\n'+
'Each account is checked on its own. Any that cannot be changed are listed afterwards.'});
}
function bulkActive(on){
return runBulk('/api/auth/bulk-users/active', { is_active: !!on }, {
title: on ? 'Enable accounts' : 'Disable accounts', ok: on ? 'Enable' : 'Disable',
message: n => (on ? 'Enable sign-in for ' : 'Disable sign-in for ')+people(n)+'?'+
(on ? '' : '\n\nA disabled account cannot sign in. Nothing else about it changes.')});
}
function bulkProject(op){
const pid = selVal('bulk-project');
if(!pid) return;
const role = op === 'add' ? selVal('bulk-project-role') : '';
const pname = selText('bulk-project');
return runBulk('/api/auth/bulk-users/projects', { project_id: pid, op, role }, {
title: op === 'add' ? 'Add to project' : 'Remove from project',
ok: op === 'add' ? 'Add' : 'Remove',
message: n => op === 'add'
? 'Add '+people(n)+' to '+pname+' with '+(role ? PERM_LABELS[role]+' on that project' : 'their account role')+'?\n\n'+
'Their other projects, and their roles there, stay as they are.'
: 'Remove '+people(n)+' from '+pname+'?\n\nTheir other projects stay as they are.'});
}
// ── CSV upload (CR-020, T12.4) ────────────────────────────────────────────────
// The file holds usernames only (decided 2026-10-06). The server reads it and
// answers line by line; the accepted accounts become the ordinary selection, so
// the action, its confirmation and its row-by-row report are the same ones the
// checkboxes use. A CSV cannot reach an account a checkbox could not: the bulk
// route re-checks every row.
const CSV_MAX_BYTES = 1024 * 1024;
// Blob.text() where the browser has it, FileReader where it does not (older
// tablet browsers).
function readFileText(file){
if(typeof file.text === 'function') return file.text();
return new Promise((resolve, reject) => {
const r = new FileReader();
r.onload = () => resolve(String(r.result || ''));
r.onerror = () => reject(r.error);
r.readAsText(file);
});
}
function pickCsv(){
const f = document.getElementById('csv-file');
if(f){ f.value = ''; f.click(); }
}
document.addEventListener('change', e => {
if(e.target && e.target.id === 'csv-file' && e.target.files && e.target.files[0]) loadCsv(e.target.files[0]);
});
async function loadCsv(file){
if(file.size > CSV_MAX_BYTES){
bannerHtml('csv-banner', 'bad', '✕ '+uesc(file.name)+' is larger than 1 MB. Split it and load the parts one at a time.');
return;
}
let text = '';
try { text = await readFileText(file); }
catch(_){ bannerHtml('csv-banner', 'bad', '✕ Could not read '+uesc(file.name)+'.'); return; }
bannerHtml('csv-banner', '', 'Reading '+uesc(file.name)+'…');
const { status, json } = await api('POST', '/api/auth/bulk-users/resolve', { text });
if(status !== 200 || !json || !Array.isArray(json.rows)){
bannerHtml('csv-banner', 'bad', '✕ '+uesc(apiError(status, json, 'Could not read the list')));
return;
}
// Show everyone, so every accepted account is a visible, checked row: a
// selection must never include a row the filter hides.
const s = document.getElementById('user-search'), f = document.getElementById('user-filter');
if(s) s.value = '';
if(f) f.value = '';
await loadUsers();
const want = new Set(json.user_ids || []);
_shownSelectable.forEach(id => { if(want.has(id)) _selected.add(id); });
updateSelectionUI();
const missed = [...want].filter(id => !_selected.has(id)).length;
const rejected = json.rows.filter(r => r.status !== 'ok');
const lead = (rejected.length || missed ? '⚠ ' : '✓ ')+uesc(file.name)+': '+json.read+' line'+(json.read===1?'':'s')+' read, '+
_selected.size+' selected'+(rejected.length ? ', '+rejected.length+' rejected' : '')+'.'+
(missed ? ' '+missed+' accepted account'+(missed===1?' is':'s are')+' no longer in the directory; reload and try again.' : '')+
(_selected.size ? ' Pick an action in the bulk bar to apply it to the selected accounts.' : '');
const list = rejected.length
? '<ul>'+rejected.map(r => '<li>Line '+r.line+' ('+uesc(r.text)+'): '+uesc(r.reason)+'</li>').join('')+'</ul>'
: '';
bannerHtml('csv-banner', (rejected.length || missed) ? 'warn' : 'ok', lead + list);
}
function selCell(u){
if(!selectable(u)){
const why = u.id === _meId ? 'Your own account: change it one setting at a time'
: (u.manage_blocked_reason || 'You cannot change this account');
return '<td class="selcell"><span class="selhit" title="'+uesc(why)+'">'+
'<input type="checkbox" disabled aria-label="'+uesc('Cannot select '+u.username+': '+why)+'"></span></td>';
}
return '<td class="selcell"><label class="selhit">'+
'<input type="checkbox" class="selbox" data-id="'+uesc(u.id)+'"'+(_selected.has(u.id)?' checked':'')+
' aria-label="'+uesc('Select '+u.username)+'"></label></td>';
}
function renderUsers(){
const wrap = document.getElementById('users-table');
const q = ((document.getElementById('user-search')||{}).value||'').trim().toLowerCase();
const f = ((document.getElementById('user-filter')||{}).value||'');
const total = _users.length;
const sub = document.getElementById('people-sub');
if(sub){
sub.textContent = manages()
? 'Login accounts you can see. The ones you administer carry controls; the rest are listed for reference.'
: 'Everyone on the projects you can access, plus the administrators.';
}
if(!total){ wrap.innerHTML = '<div class="note">Nobody to show yet.</div>'; return; }
const list = _users.filter(u => {
if(f === 'active' && !u.is_active) return false;
if(f === 'disabled' && u.is_active) return false;
if(f === 'mine' && !u.manageable) return false;
if(!q) return true;
return ((u.username||'')+' '+(u.full_name||'')+' '+(u.email||'')+' '+
(u.project_role||'')+' '+roleLabel(u.role)).toLowerCase().indexOf(q) >= 0;
});
const count = '<div class="note">'+list.length+' of '+total+' '+(total===1?'person':'people')+'</div>';
_shownSelectable = list.filter(selectable).map(u => u.id);
if(!list.length){ wrap.innerHTML = count+'<div class="note">Nothing matches.</div>'; updateSelectionUI(); return; }
const head = manages()
? ['Username','Name','Email',
['Permissions','What this account may do in the app'],
['Project role','Job function on the project — descriptive only'],
['Project access','Which projects this user can access, and their role on each'],
'Status','Last login','Actions']
: ['Name','Username','Email',
['Permissions','What this account may do in the app'],
['Project role','Job function on the project — descriptive only'],
'Status'];
const ths = head.map(h => Array.isArray(h)
? '<th title="'+uesc(h[1])+'">'+uesc(h[0])+'</th>' : '<th>'+uesc(h)+'</th>').join('');
// CR-020: a selection column for anyone who manages accounts. Select-all names
// how many rows it covers, because it covers only what the filter shows.
const selTh = manages()
? '<th class="selcell"><label class="selhit"><input type="checkbox" id="sel-all" aria-label="'+
uesc('Select all '+_shownSelectable.length+' shown that you can change')+'"></label></th>'
: '';
const rows = list.map(manages() ? managerRow : readonlyRow).join('');
wrap.innerHTML = count+'<div class="tscroll"><table class="grid"><thead><tr>'+selTh+ths+
'</tr></thead><tbody>'+rows+'</tbody></table></div>'+legend();
updateSelectionUI();
}
function legend(){
if(!manages()){
return '<div class="note" style="margin-top:10px"><strong>Project role</strong> is the person’s job '+
'function — it feeds the SOP team pickers and notification routing, and grants nothing on its own.</div>';
}
return '<div class="note" style="margin-top:10px"><strong>Permissions</strong> — '+
PERM_ROLES.map(r => '<em>'+uesc(PERM_LABELS[r])+'</em>: '+uesc(PERM_HELP[r])).join(' ')+
' <strong>Project role</strong> is the person’s job function — it feeds the SOP team pickers '+
'and notification routing, and grants nothing on its own.</div>';
}
// The read-only card: name, contact, role. No ids are bound into handlers because
// there are no handlers — that is the point of this rendering.
function readonlyRow(u){
return '<tr>'+
'<td><strong>'+uesc(u.full_name || u.username)+'</strong>'+(u.id===_meId?'<span class="me-tag">you</span>':'')+'</td>'+
'<td>'+uesc(u.username)+'</td>'+
'<td class="ell" title="'+uesc(u.email||'')+'"><span>'+
(u.email ? '<a class="home" href="mailto:'+uesc(u.email)+'">'+uesc(u.email)+'</a>' : '—')+'</span></td>'+
'<td><span class="tag '+roleTagClass(u.role)+'">'+uesc(roleLabel(u.role))+'</span></td>'+
'<td>'+uesc(u.project_role || '—')+'</td>'+
'<td><span class="tag '+(u.is_active?'on':'off')+'">'+(u.is_active?'active':'disabled')+'</span></td>'+
'</tr>';
}
function managerRow(u){
const me = u.id === _meId;
const uid = jsq(u.id), uname = jsq(u.username);
const can = !!u.manageable;
const why = u.manage_blocked_reason || '';
const fmt = s => s ? wpFormatDateTime(s) : '—';
const role = normRole(u.role);
// Your own row never offers the controls that could lock you out of the app.
const roleCell = me
? '<span class="tag '+roleTagClass(role)+'">'+uesc(roleLabel(role))+'</span><span class="me-tag">locked</span>'
: !can
? '<span class="tag '+roleTagClass(role)+'" title="'+uesc(why)+'">'+uesc(roleLabel(role))+'</span>'
: roleSelect(uid, uname, role);
// Job function follows the same permission as everything else on the row. Note a
// super user cannot edit their OWN row: the server refuses account changes to any
// admin or super-user account, including the caller's.
const projRoleCell = can
? projRoleSelect(uid, uname, u.project_role || '')
: projRoleReadonly(u, can, why);
const actions = [];
if(can && !me) actions.push('<button class="mini" onclick="toggleActive(\''+uid+'\','+(!u.is_active)+')">'+
(u.is_active?'Disable':'Enable')+'</button>');
if(can && !me) actions.push('<button class="mini danger" onclick="deleteUser(\''+uid+'\',\''+uname+'\')">Delete</button>');
if(!can && !me) actions.push('<span class="note" style="margin:0" title="'+uesc(why)+'">read-only</span>');
return '<tr'+(can||me ? '' : ' class="is-locked"')+'>'+
selCell(u)+
'<td><strong>'+uesc(u.username)+'</strong>'+(me?'<span class="me-tag">you</span>':'')+'</td>'+
'<td>'+uesc(u.full_name||'')+'</td>'+
// The address is truncated with the full value on the title: a long one used to
// wrap mid-word and push the whole row onto three lines.
'<td class="ell" title="'+uesc(u.email||'')+'"><span>'+uesc(u.email||'')+'</span></td>'+
'<td>'+roleCell+'</td>'+
'<td>'+projRoleCell+'</td>'+
'<td><div class="cellactions">'+projAccessCell(u)+'</div></td>'+
'<td><span class="tag '+(u.is_active?'on':'off')+'">'+(u.is_active?'active':'disabled')+'</span></td>'+
'<td style="white-space:nowrap;color:var(--muted)">'+fmt(u.last_login_at)+'</td>'+
'<td><div class="cellactions">'+actions.join('')+'</div></td>'+
'</tr>';
}
// Only the roles the server said this caller may grant are offered. The account's
// CURRENT role is always included even when it isn't grantable, or the dropdown would
// silently misreport a Project Admin as a Project User the moment it renders.
function roleSelect(uid, uname, role){
const grantable = (_scope && _scope.grantable_roles) || [];
const opts = PERM_ROLES.filter(r => grantable.indexOf(r) >= 0 || r === role);
return '<select class="role-select'+(role==='admin'?' is-admin':'')+
'" title="Change what this account may do" onchange="changeRole(\''+uid+'\',this.value,\''+uname+'\')">'+
opts.map(r => '<option value="'+r+'"'+(role===r?' selected':'')+
(grantable.indexOf(r) < 0 ? ' disabled' : '')+'>'+uesc(PERM_LABELS[r])+'</option>').join('')+
'</select>';
}
function projRoleSelect(uid, uname, pr){
const list = (_scope && _scope.project_roles) || PROJECT_ROLES;
return '<select class="role-select" title="Job function on the project" '+
'onchange="changeProjectRole(\''+uid+'\',this.value,\''+uname+'\')">'+
'<option value=""'+(pr?'':' selected')+'>— none —</option>'+
list.map(r => '<option value="'+uesc(r)+'"'+(pr===r?' selected':'')+'>'+uesc(r)+'</option>').join('')+
// Keep a title that isn't on the list (set via the API or an older record).
(pr && list.indexOf(pr) < 0 ? '<option value="'+uesc(pr)+'" selected>'+uesc(pr)+'</option>' : '')+
'</select>';
}
function projRoleReadonly(u, can, why){
return '<span'+(can?'':' title="'+uesc(why)+'"')+'>'+uesc(u.project_role || '—')+'</span>';
}
// Per-user project access gets its own column: buried among the action buttons, it
// was exactly where you'd fail to find "which projects can this person see, and what
// may they do there".
function projAccessCell(u){
if(normRole(u.role) === 'admin'){
return '<span class="tag admin" title="Admins can access every project">all projects</span>';
}
const n = u.project_count;
const label = (n === undefined || n === null) ? 'Projects…'
: (n === 0 ? 'No projects yet' : n+' project'+(n===1?'':'s'));
if(!u.manageable){
return '<span class="note" style="margin:0" title="'+uesc(u.manage_blocked_reason||'')+'">'+uesc(label)+'</span>';
}
return '<button class="mini'+(n === 0 ? ' danger' : '')+
'" onclick="manageProjects(\''+jsq(u.id)+'\',\''+jsq(u.username)+'\')"'+
' title="Choose which projects this user can access, and their role on each">'+
uesc(label)+'</button>';
}
// ── row actions ───────────────────────────────────────────────────────────────
// Each one reloads on failure so a control can never sit there showing a value the
// server refused.
async function toggleActive(id, makeActive){
const { status, json } = await api('POST','/api/auth/users/'+id+'/active',{is_active:makeActive});
if(status === 200) loadUsers();
else { wpAlertDialog({title:'Change failed', message:'Could not change that account: '+apiError(status, json)}); loadUsers(); }
}
async function changeRole(id, role, username){
const { status, json } = await api('POST','/api/auth/users/'+id+'/role',{role});
if(status !== 200) wpAlertDialog({title:'Change failed', message:'Could not change permissions for '+username+': '+apiError(status, json)});
loadUsers();
}
async function changeProjectRole(id, project_role, username){
const { status, json } = await api('POST','/api/auth/users/'+id+'/project-role',{project_role});
if(status !== 200) wpAlertDialog({title:'Change failed', message:'Could not set the project role for '+username+': '+apiError(status, json)});
loadUsers();
}
async function deleteUser(id, username){
if(!(await wpConfirmDialog({title:'Delete user',
message:'Delete user "'+username+'"?\n\nTheir account and every project assignment go with it. '+
'This cannot be undone — disable the account instead if you only want to block sign-in.',
okLabel:'Delete user'}))) return;
const { status, json } = await api('DELETE','/api/auth/users/'+id);
if(status === 200) loadUsers();
else wpAlertDialog({title:'Delete failed', message:'Could not delete '+username+': '+apiError(status, json)});
}
// ── create ────────────────────────────────────────────────────────────────────
function renderCreateForm(){
const card = document.getElementById('create-card');
if(!card) return;
if(!manages()){ card.style.display = 'none'; return; }
card.style.display = '';
const grantable = _scope.grantable_roles || [];
const roleSel = document.getElementById('nu-role');
roleSel.innerHTML = PERM_ROLES.filter(r => grantable.indexOf(r) >= 0)
.map(r => '<option value="'+r+'"'+(r==='project_user'?' selected':'')+'>'+uesc(PERM_LABELS[r])+'</option>').join('');
const prSel = document.getElementById('nu-project-role');
prSel.innerHTML = '<option value="">Project role…</option>'+
(_scope.project_roles||PROJECT_ROLES).map(r => '<option value="'+uesc(r)+'">'+uesc(r)+'</option>').join('');
// The project picker is REQUIRED for a super user and optional for an admin —
// because a super user's authority over an account comes from the projects it is
// on, so an account created with none is one they instantly cannot manage. The
// server refuses that; the form says so up front rather than after a failed save.
const admin = _scope.scope === 'all';
const projects = _scope.managed_projects || [];
document.getElementById('create-sub').innerHTML = admin
? 'Creates a login account. Assign projects here or later from <strong>Project access</strong> in the table above.'
: 'Creates a login account on your project'+(projects.length===1?'':'s')+
'. You administer users per project, so a new account has to start on at least one of them.';
document.getElementById('nu-projects-label').innerHTML = admin
? 'Projects (optional — you can assign them later)'
: 'Projects <strong>*</strong> — pick at least one';
const live = projects.filter(p => !p.archived);
const list = document.getElementById('nu-project-list');
if(!projects.length){
list.innerHTML = '<div class="note" style="padding:var(--s2)">You don’t administer any project yet.</div>';
} else {
// Archived projects are omitted, not disabled: staffing a frozen job is never
// what you mean when creating an account, and an admin can still assign one
// afterwards from the project-access dialog.
list.innerHTML = (live.length ? live : []).map(p =>
'<div class="pickrow"><label><input type="checkbox" value="'+uesc(p.id)+'"'+
(live.length === 1 ? ' checked' : '')+'>'+
'<span><strong>'+uesc(p.name||'(unnamed)')+'</strong>'+
(p.number ? ' <span style="color:var(--muted)">'+uesc(p.number)+'</span>' : '')+'</span></label></div>').join('')
|| '<div class="note" style="padding:var(--s2)">Every project you administer is archived.</div>';
}
}
async function createUser(){
const msg = document.getElementById('users-create-msg');
const val = id => (document.getElementById(id)||{}).value || '';
// The username entered here MUST match what Okta's identity claim will send for
// this person exactly — this creates the account ahead of their first sign-in,
// and that's how a later Okta sign-in finds this row instead of provisioning a
// second one. See create_user()'s docstring in server/app.py.
const username = val('nu-username').trim();
const project_ids = [...document.querySelectorAll('#nu-project-list input[type=checkbox]:checked')]
.map(c => c.value);
const say = (color, text) => { msg.style.color = color; msg.textContent = text; };
if(!username){ say('var(--red)','Username is required.'); return; }
if(_scope.scope !== 'all' && !project_ids.length){
say('var(--red)','Pick at least one project — you administer users per project.'); return;
}
say('var(--muted)','Creating…');
const { status, json } = await api('POST','/api/auth/users',{
username, project_ids,
full_name: val('nu-fullname').trim(), email: val('nu-email').trim(),
role: val('nu-role'), project_role: val('nu-project-role'),
});
if(status === 200){
say('var(--green)','✓ Created '+username+'.');
['nu-username','nu-fullname','nu-email'].forEach(id => document.getElementById(id).value = '');
loadUsers();
} else {
say('var(--red)','✕ '+apiError(status, json, 'Could not create the account'));
}
}
// ── project access dialog ─────────────────────────────────────────────────────
// For an admin this is the whole of a person's access. For a super user it is their
// slice of it: the server returns only the projects they administer and says how many
// more the person is on, and a save leaves those others untouched.
async function manageProjects(id, username){
const { status, json } = await api('GET','/api/auth/users/'+id+'/projects');
if(status !== 200 || !json){ wpAlertDialog({title:'Could not load projects', message:'Could not load projects: '+apiError(status, json)}); return; }
openProjectModal(id, username, json);
}
function closeProjectModal(){ const m = document.getElementById('proj-modal'); if(m) m.remove(); }
// A project's role dropdown only matters while that project is ticked.
function projRowToggled(cb){
const row = cb.closest('.pickrow');
const sel = row && row.querySelector('select');
if(sel) sel.disabled = !cb.checked;
}
function openProjectModal(userId, username, data){
closeProjectModal();
const projects = (data.projects||[]).slice()
// Live jobs first — an archived one is still listed (an existing assignment has
// to stay removable) but it is finished work, so it doesn't belong at the top of
// a list you're using to staff someone.
.sort((a,b) => (a.archived?1:0) - (b.archived?1:0));
const assigned = new Set(data.assigned||[]);
const roles = data.roles || {};
const userObj = data.user || {};
const isAdmin = normRole(userObj.role) === 'admin';
const acctRole = normRole(userObj.role);
const grantable = data.grantable_project_roles || PROJECT_SCOPED_ROLES;
const items = projects.length ? projects.map(p => {
const on = assigned.has(p.id);
const cur = roles[p.id] || '';
const opts = ['<option value=""'+(cur===''?' selected':'')+'>Same as account ('+
uesc(PERM_LABELS[acctRole]||acctRole)+')</option>']
.concat(PROJECT_SCOPED_ROLES.filter(r => grantable.indexOf(r) >= 0 || r === cur).map(r =>
'<option value="'+r+'"'+(cur===r?' selected':'')+(grantable.indexOf(r)<0?' disabled':'')+'>'+
uesc(PERM_LABELS[r])+' here</option>'));
return '<div class="pickrow">'+
'<label><input type="checkbox" value="'+uesc(p.id)+'"'+(on?' checked':'')+(isAdmin?' disabled':'')+
' onchange="projRowToggled(this)">'+
'<span><strong>'+uesc(p.name||'(unnamed)')+'</strong>'+
(p.number?' <span style="color:var(--muted)">'+uesc(p.number)+'</span>':'')+
(p.archived?' <span class="tag archived" title="Archived — read-only until an admin unarchives it">archived</span>':'')+
'</span></label>'+
'<select class="role-select" data-role-for="'+uesc(p.id)+'"'+(isAdmin||!on?' disabled':'')+'>'+
opts.join('')+'</select>'+
'</div>';
}).join('') : '<div class="note">No projects to choose from.</div>';
const others = data.other_projects || 0;
const intro = isAdmin
? '<div class="banner" style="margin:0 0 10px">This user is an <strong>Administrator</strong> and can '+
'access every project regardless of assignment.</div>'
: '<div class="note" style="margin:0 0 10px">Tick the projects this user may access, and set their role '+
'on each. <strong>Project Admin</strong> can delete work packages, change a completed SOP and delete '+
'that project; <strong>Project Super User</strong> can also manage that project’s user accounts; '+
'<strong>Project User</strong> can do neither. Leave it on <em>Same as account</em> to use their '+
'Permissions setting.</div>'+
(others ? '<div class="banner warn" style="margin:0 0 10px">Also on '+others+' project'+
(others===1?'':'s')+' you don’t administer. Those stay exactly as they are — saving here only '+
'changes the projects listed below.</div>' : '');
const modal = document.createElement('div');
modal.id = 'proj-modal';
modal.className = 'modal-ov';
modal.innerHTML =
'<div class="modal-box">'+
'<div class="modal-head">Project access &amp; permissions — '+uesc(username)+'</div>'+
'<div class="modal-body">'+intro+'<div id="proj-list">'+items+'</div></div>'+
'<div class="modal-foot">'+
'<button onclick="closeProjectModal()">Cancel</button>'+
(isAdmin ? '' : '<button class="primary" id="proj-save">Save</button>')+
'</div>'+
'</div>';
modal.addEventListener('click', e => { if(e.target === modal) closeProjectModal(); });
document.body.appendChild(modal);
const saveBtn = document.getElementById('proj-save');
if(saveBtn) saveBtn.onclick = async () => {
const ids = [...modal.querySelectorAll('#proj-list input[type=checkbox]:checked')].map(c => c.value);
const roleMap = {};
ids.forEach(pid => {
const sel = modal.querySelector('#proj-list select[data-role-for="'+pid+'"]');
if(sel && sel.value) roleMap[pid] = sel.value;
});
const { status, json } = await api('PUT','/api/auth/users/'+userId+'/projects',
{ project_ids: ids, roles: roleMap });
if(status === 200){ closeProjectModal(); loadUsers(); }
else wpAlertDialog({title:'Save failed', message:'Save failed: '+apiError(status, json)});
};
}
document.addEventListener('keydown', e => { if(e.key === 'Escape') closeProjectModal(); });
// ── start ─────────────────────────────────────────────────────────────────────
// auth-guard.js requires a login and publishes window.WP_USER (firing
// 'wp-auth-ready'). Unlike the Admin Console there is no role gate here: everyone
// signed in gets a directory, and what they can DO comes from the scope call.
let _booted = false;
function start(){
if(_booted || !window.WP_USER) return;
_booted = true;
boot();
}
document.addEventListener('wp-auth-ready', start);
start();