641 lines
51 KiB
JavaScript
641 lines
51 KiB
JavaScript
// Stream S6: Settings › Organizations. Create an organization, edit it, and
|
||
// finish its setup. The form and the JSON editor edit one document; the server
|
||
// (org-admin.mjs) derives every path and calls the same service as the CLI.
|
||
(() => {
|
||
const $ = id => document.getElementById(id);
|
||
const txt = v => String(v ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
||
const ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
||
const markup = `<div id="org-admin" class="org-admin">
|
||
<section class="panel" aria-labelledby="org-start-title" id="org-start">
|
||
<h3 id="org-start-title">Start</h3>
|
||
<p>A new organization starts from the template. Its folders and repositories are set by the server.</p>
|
||
<div class="org-start-row">
|
||
<form id="org-new-form" class="org-inline" novalidate>
|
||
<label for="org-new-id">Organization ID</label>
|
||
<input id="org-new-id" name="id" autocomplete="off" spellcheck="false" placeholder="e.g. acme" aria-describedby="org-new-id-help" required>
|
||
<span id="org-new-id-help" class="org-help">Lowercase letters, digits, dot, dash or underscore.</span>
|
||
<button type="submit" data-write>New organization</button>
|
||
</form>
|
||
<form id="org-open-form" class="org-inline" novalidate>
|
||
<label for="org-open-id">Existing organization</label>
|
||
<select id="org-open-id" name="id"><option value="">Loading…</option></select>
|
||
<button type="submit" class="org-secondary">Open</button>
|
||
</form>
|
||
</div>
|
||
</section>
|
||
<div id="org-status" class="sr-only" role="status" aria-live="polite"></div>
|
||
<div id="org-banner" class="org-banner" role="alert" hidden></div>
|
||
<section id="org-paths" class="panel" hidden aria-labelledby="org-paths-title">
|
||
<h3 id="org-paths-title">Choose how to set up</h3>
|
||
<div class="org-field"><label for="org-preset">Who answers?</label><select id="org-preset"></select><span class="org-help" id="org-preset-help"></span></div>
|
||
<div class="org-field"><label for="org-thinking">How much thinking?</label><select id="org-thinking"></select></div>
|
||
<div class="settings-actions org-path-actions"><button type="button" id="org-quick-open">Quick Setup</button><button type="button" class="org-secondary" id="org-advanced-open">Advanced Setup</button></div>
|
||
</section>
|
||
<section id="org-quick" class="panel" hidden aria-labelledby="org-quick-title">
|
||
<h3 id="org-quick-title">Quick Setup</h3>
|
||
<div class="org-field"><label for="org-project">First project name</label><input id="org-project" value="work" autocomplete="off"><span class="org-help">Lowercase letters, digits, dot, dash or underscore.</span></div>
|
||
<div class="org-field"><label for="org-project-remote">Project remote URL (optional)</label><input id="org-project-remote" type="url" placeholder="https://git.example/team/project"><span class="org-help">Leave blank for local only. The organization checkout is local only.</span></div>
|
||
<label class="org-quick-risk"><input id="org-risk-accept" type="checkbox"> I understand local-only repositories have no copy elsewhere and can be lost.</label>
|
||
<div class="settings-actions"><button type="button" id="org-quick-run">Create and set up organization</button></div>
|
||
<ol id="org-quick-steps" class="org-steps" aria-live="polite"></ol>
|
||
<div class="settings-actions"><button type="button" id="org-quick-open-org" hidden>Open organization</button></div>
|
||
</section>
|
||
<section id="org-editor" class="org-editor" hidden aria-labelledby="org-editor-title">
|
||
<div class="org-editor-head"><h3 id="org-editor-title">New organization</h3><p id="org-editor-verb" class="org-verb"></p></div>
|
||
<div id="org-errors" class="org-errors" hidden tabindex="-1" aria-labelledby="org-errors-title"><h4 id="org-errors-title">Fix these fields</h4><ul></ul></div>
|
||
<div class="org-columns">
|
||
<form id="org-form" class="panel org-form" novalidate aria-label="Organization fields"></form>
|
||
<div class="panel org-json">
|
||
<label for="org-json-text"><span class="org-json-title">Organization document (JSON)</span><span class="org-help">Edits here update the form. Folders and repositories are kept by the server and do not appear.</span></label>
|
||
<textarea id="org-json-text" spellcheck="false" autocomplete="off" aria-describedby="org-json-state" data-path="$"></textarea>
|
||
<p id="org-json-state" class="org-help" aria-live="polite"></p>
|
||
</div>
|
||
</div>
|
||
<div class="settings-actions org-save-row">
|
||
<button type="button" id="org-check" class="org-secondary">Check</button>
|
||
<button type="submit" form="org-form" id="org-save">Save organization</button>
|
||
</div>
|
||
</section>
|
||
<section id="org-receipt" class="panel org-receipt" hidden aria-labelledby="org-receipt-title"></section>
|
||
<section id="org-setup" class="org-setup" hidden aria-labelledby="org-setup-title">
|
||
<h3 id="org-setup-title">Guided setup</h3>
|
||
<p class="org-help">Each step shows the command it equals and the receipt it left. A step whose outcome is unknown stays incomplete until it is read back.</p>
|
||
<ol id="org-steps" class="org-steps"></ol>
|
||
</section>
|
||
<section id="org-archive" class="panel" hidden aria-labelledby="org-archive-title">
|
||
<h3 id="org-archive-title">Archive organization</h3>
|
||
<p>Put this organization away until you restore it.</p>
|
||
<button type="button" id="org-archive-open" data-write>Archive organization</button>
|
||
<div id="org-archive-confirm" tabindex="-1" hidden aria-labelledby="org-archive-confirm-title">
|
||
<h4 id="org-archive-confirm-title">Review archive</h4>
|
||
<ul><li>The organization's bus stops.</li><li>All files stay where they are.</li><li>The organization leaves the switcher.</li><li>Restore brings it back without starting the bus.</li></ul>
|
||
<div class="settings-actions"><button type="button" id="org-archive-cancel" class="org-secondary">Cancel</button><button type="button" id="org-archive-final" data-write>Archive</button></div>
|
||
</div>
|
||
</section>
|
||
<section id="org-archived" class="panel" tabindex="-1" hidden aria-labelledby="org-archived-title">
|
||
<h3 id="org-archived-title">Organization archived</h3>
|
||
<p>Editing and setup are unavailable while archived. Files remain in place; restoring does not start the bus.</p>
|
||
<button type="button" id="org-restore" data-write>Restore organization</button>
|
||
</section>
|
||
<p id="org-archive-error" class="org-field-err" role="alert"></p>
|
||
<section id="org-archive-success" class="panel" hidden tabindex="-1" aria-live="polite"></section>
|
||
<section id="org-delete" class="panel org-delete" hidden aria-labelledby="org-delete-title">
|
||
<h3 id="org-delete-title">Delete organization</h3>
|
||
<p>Move this organization and its local data to the deleted folder.</p>
|
||
<button type="button" id="org-delete-open" data-write>Delete organization</button>
|
||
<div id="org-delete-first" tabindex="-1" hidden aria-labelledby="org-delete-first-title">
|
||
<h4 id="org-delete-first-title">Review deletion</h4>
|
||
<ul><li>The organization's bus stops.</li><li>The organization file, history, runtime, repositories, sessions, run records and its credentials move to the deleted folder.</li><li>The organization leaves the list.</li><li>Remote repositories are untouched.</li></ul>
|
||
<div class="settings-actions"><button type="button" id="org-delete-cancel" class="org-secondary">Cancel</button><button type="button" id="org-delete-continue">Continue</button></div>
|
||
</div>
|
||
<div id="org-delete-second" tabindex="-1" hidden aria-labelledby="org-delete-second-title">
|
||
<h4 id="org-delete-second-title">Confirm deletion</h4>
|
||
<label for="org-delete-confirm">Type the organization ID to confirm</label>
|
||
<input id="org-delete-confirm" autocomplete="off" spellcheck="false">
|
||
<div class="settings-actions"><button type="button" id="org-delete-cancel-second" class="org-secondary">Cancel</button><button type="button" id="org-delete-final" disabled>Delete organization</button></div>
|
||
</div>
|
||
<p id="org-delete-error" class="org-field-err" role="alert"></p><div id="org-delete-progress" aria-live="polite"></div>
|
||
</section>
|
||
<section id="org-delete-success" class="panel" hidden tabindex="-1" aria-live="polite"></section>
|
||
</div>`;
|
||
|
||
function mount() {
|
||
const root = $('org-admin'); if (!root) return () => {};
|
||
let alive = true, canWrite = false, editorDirty = false, presets = [];
|
||
const setupDirty = new Set();
|
||
window.MosaicOrgCreate.hasDraft = () => editorDirty || setupDirty.size > 0 || !!$('org-new-id')?.value.trim();
|
||
// mode: 'create' | 'edit'; doc: the one canonical (browser) document.
|
||
const st = { mode: null, id: null, doc: null, revision: null, state: 'active', held: [], errors: [], setup: null, pending: new Set(), unknown: new Set(), choice: new Map() };
|
||
const status = text => { $('org-status').textContent = ''; setTimeout(() => { if (alive) $('org-status').textContent = text; }, 30); };
|
||
const banner = (text, kind = 'err') => { const b = $('org-banner'); b.hidden = !text; b.className = `org-banner ${kind}`; b.textContent = text || ''; };
|
||
const query = () => new URLSearchParams((location.hash.split('?')[1] || ''));
|
||
const setQuery = (org, step) => {
|
||
const q = new URLSearchParams(); if (org) q.set('org', org); if (step) q.set('step', step);
|
||
const prefix = window.MosaicOrg ? `#/orgs/${encodeURIComponent(window.MosaicOrg.id)}` : '#';
|
||
const next = `${prefix}/settings/organizations${q.toString() ? `?${q}` : ''}`;
|
||
if (location.hash !== next) history.replaceState(null, '', next);
|
||
};
|
||
const verifiedReply = (reply, step) => reply.status === 200 && reply.body.outcome === 'done' && reply.body.step === step;
|
||
async function api(method, url, body) {
|
||
const r = await fetch(url, { method, cache: 'no-store', credentials: 'same-origin', headers: body === undefined ? {} : { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
|
||
let data = null; try { data = await r.json(); } catch { data = null; }
|
||
return { status: r.status, body: data ?? {} };
|
||
}
|
||
|
||
// ---- form <-> document ------------------------------------------------
|
||
const roleNames = () => Object.keys(st.doc?.roles ?? {});
|
||
function field(path, labelText, value, { help = '', readonly = false, list = null, kind = 'input' } = {}) {
|
||
const id = `org-f-${path.replace(/[^A-Za-z0-9]+/g, '-')}`;
|
||
const err = st.errors.find(e => e.path === path);
|
||
const describedby = [help ? `${id}-help` : '', err ? `${id}-err` : ''].filter(Boolean).join(' ');
|
||
const control = kind === 'select'
|
||
? `<select id="${id}" data-path="${txt(path)}"${err ? ' aria-invalid="true"' : ''}${describedby ? ` aria-describedby="${describedby}"` : ''}>${(list || []).map(v => `<option${v === value ? ' selected' : ''}>${txt(v)}</option>`).join('')}${list?.includes(value) ? '' : `<option selected value="${txt(value)}">${txt(value || 'Choose a role')}</option>`}</select>`
|
||
: `<input id="${id}" data-path="${txt(path)}" value="${txt(value)}" autocomplete="off" spellcheck="false"${readonly ? ' readonly' : ''}${err ? ' aria-invalid="true"' : ''}${describedby ? ` aria-describedby="${describedby}"` : ''}>`;
|
||
return `<div class="org-field"><label for="${id}">${labelText}</label>${control}${help ? `<span id="${id}-help" class="org-help">${help}</span>` : ''}${err ? `<span id="${id}-err" class="org-field-err">${txt(err.message)} <code>${txt(path)}</code></span>` : ''}</div>`;
|
||
}
|
||
function renderForm() {
|
||
const d = st.doc ?? {};
|
||
const roles = Object.entries(d.roles ?? {});
|
||
const projects = Object.entries(d.projects ?? {});
|
||
const extra = Object.keys(d).filter(k => !['businessVersion', 'id', 'human', 'arbiters', 'roles', 'projects'].includes(k));
|
||
$('org-form').innerHTML = `
|
||
<h4>Organization</h4>
|
||
${field('$.id', 'Organization ID', st.id ?? '', { readonly: true, help: st.mode === 'edit' ? 'An organization keeps its ID.' : 'Set when you started. Start again for another ID.' })}
|
||
${field('$.human', 'Owner (human ID)', d.human ?? '', { help: 'Who answers for this organization. On this dev instance, local-dev-owner.' })}
|
||
<fieldset><legend>Arbiters</legend>
|
||
${field('$.arbiters.delivery', 'Delivery arbiter', d.arbiters?.delivery ?? '', { kind: 'select', list: roleNames() })}
|
||
${field('$.arbiters.technical', 'Technical arbiter', d.arbiters?.technical ?? '', { kind: 'select', list: roleNames() })}
|
||
</fieldset>
|
||
<fieldset class="org-list"><legend>Roles</legend>
|
||
${roles.map(([name, role], i) => `<div class="org-row" data-role="${txt(name)}">
|
||
${field(`$.roles.${name}`, `Role ${i + 1} name`, name)}
|
||
${field(`$.roles.${name}.definition`, `Role ${i + 1} definition`, role?.definition ?? '', { help: i === 0 ? 'A file under roles/, such as chief-of-staff or assistant.' : '' })}
|
||
<button type="button" class="org-remove" data-remove-role="${txt(name)}" aria-label="Remove role ${txt(name)}">Remove</button></div>`).join('')}
|
||
${st.errors.find(e => e.path === '$.roles') ? `<p class="org-field-err">${txt(st.errors.find(e => e.path === '$.roles').message)} <code>$.roles</code></p>` : ''}
|
||
<button type="button" class="org-secondary" id="org-add-role">Add role</button>
|
||
</fieldset>
|
||
<fieldset class="org-list"><legend>Projects</legend>
|
||
${projects.map(([name], i) => `<div class="org-row" data-project="${txt(name)}">
|
||
${field(`$.projects.${name}`, `Project ${i + 1} ID`, name, { help: i === 0 ? 'Its repository is set up in the guided setup after you save.' : '' })}
|
||
<button type="button" class="org-remove" data-remove-project="${txt(name)}" aria-label="Remove project ${txt(name)}">Remove</button></div>`).join('')}
|
||
${st.errors.find(e => e.path === '$.projects') ? `<p class="org-field-err">${txt(st.errors.find(e => e.path === '$.projects').message)} <code>$.projects</code></p>` : ''}
|
||
<button type="button" class="org-secondary" id="org-add-project">Add project</button>
|
||
</fieldset>
|
||
${extra.length ? `<p class="org-help">Also in the document, edited in the JSON: ${extra.map(k => `<code>${txt(k)}</code>`).join(', ')}.</p>` : ''}
|
||
${st.held.length ? `<p class="org-help">Kept on the server, not shown: ${st.held.map(k => `<code>${txt(k)}</code>`).join(', ')}.</p>` : ''}`;
|
||
}
|
||
function renderJSON(force = false) {
|
||
const t = $('org-json-text');
|
||
if (!force && document.activeElement === t) return;
|
||
t.value = JSON.stringify(st.doc, null, 2);
|
||
t.removeAttribute('aria-invalid'); $('org-json-state').textContent = 'In step with the form.';
|
||
}
|
||
function renameKey(obj, from, to) {
|
||
const out = {}; for (const [k, v] of Object.entries(obj)) out[k === from ? to : k] = v; return out;
|
||
}
|
||
function onFormInput(e) {
|
||
const path = e.target.dataset?.path; if (!path || !st.doc) return;
|
||
const v = e.target.value;
|
||
editorDirty = true;
|
||
if (path === '$.human') st.doc.human = v;
|
||
else if (path === '$.arbiters.delivery' || path === '$.arbiters.technical') { st.doc.arbiters ??= {}; st.doc.arbiters[path.split('.').pop()] = v; }
|
||
else if (/^\$\.roles\.[^.]+\.definition$/.test(path)) { const name = path.split('.')[2]; st.doc.roles[name] = { ...(st.doc.roles[name] ?? {}), definition: v }; }
|
||
else return;
|
||
renderJSON();
|
||
}
|
||
function onFormChange(e) {
|
||
const path = e.target.dataset?.path; if (!path || !st.doc) return;
|
||
const v = e.target.value.trim();
|
||
editorDirty = true;
|
||
let m = path.match(/^\$\.roles\.([^.]+)$/);
|
||
if (m && v !== m[1]) {
|
||
if (!v || Object.hasOwn(st.doc.roles, v)) { e.target.value = m[1]; status(v ? `A role named ${v} already exists.` : 'A role needs a name.'); return; }
|
||
st.doc.roles = renameKey(st.doc.roles, m[1], v);
|
||
for (const k of ['delivery', 'technical']) if (st.doc.arbiters?.[k] === m[1]) st.doc.arbiters[k] = v;
|
||
rerender(`$.roles.${v}`); return;
|
||
}
|
||
m = path.match(/^\$\.projects\.([^.]+)$/);
|
||
if (m && v !== m[1]) {
|
||
if (!v || Object.hasOwn(st.doc.projects, v)) { e.target.value = m[1]; status(v ? `A project named ${v} already exists.` : 'A project needs an ID.'); return; }
|
||
st.doc.projects = renameKey(st.doc.projects, m[1], v);
|
||
rerender(`$.projects.${v}`); return;
|
||
}
|
||
if (path.startsWith('$.arbiters.')) renderJSON();
|
||
}
|
||
function rerender(focusPath) {
|
||
renderForm(); renderJSON();
|
||
if (focusPath) root.querySelector(`[data-path="${CSS.escape(focusPath)}"]`)?.focus();
|
||
}
|
||
function onFormClick(e) {
|
||
const b = e.target.closest('button'); if (!b || !st.doc) return;
|
||
editorDirty = true;
|
||
if (b.id === 'org-add-role') { let n = 1; while (Object.hasOwn(st.doc.roles ??= {}, `role${n}`)) n++; st.doc.roles[`role${n}`] = { definition: '' }; rerender(`$.roles.role${n}`); status(`Added role role${n}.`); }
|
||
else if (b.id === 'org-add-project') { let n = 1; while (Object.hasOwn(st.doc.projects ??= {}, `project${n}`)) n++; st.doc.projects[`project${n}`] = {}; rerender(`$.projects.project${n}`); status(`Added project project${n}.`); }
|
||
else if (b.dataset.removeRole) { delete st.doc.roles[b.dataset.removeRole]; rerender(); $('org-add-role').focus(); status(`Removed role ${b.dataset.removeRole}.`); }
|
||
else if (b.dataset.removeProject) { delete st.doc.projects[b.dataset.removeProject]; rerender(); $('org-add-project').focus(); status(`Removed project ${b.dataset.removeProject}.`); }
|
||
}
|
||
function onJSONInput() {
|
||
editorDirty = true;
|
||
const t = $('org-json-text');
|
||
let parsed;
|
||
try { parsed = JSON.parse(t.value); } catch (err) { t.setAttribute('aria-invalid', 'true'); $('org-json-state').textContent = `Not valid JSON yet: ${err.message}. The form keeps the last valid version.`; return; }
|
||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { t.setAttribute('aria-invalid', 'true'); $('org-json-state').textContent = 'The document must be a JSON object.'; return; }
|
||
t.removeAttribute('aria-invalid');
|
||
st.doc = parsed; renderForm();
|
||
$('org-json-state').textContent = 'Form updated from the JSON.';
|
||
}
|
||
|
||
// ---- errors -----------------------------------------------------------
|
||
function showErrors(errors, intro = 'Fix these fields') {
|
||
st.errors = errors || [];
|
||
renderForm();
|
||
const box = $('org-errors');
|
||
if (!st.errors.length) { box.hidden = true; return; }
|
||
box.querySelector('h4').textContent = intro;
|
||
box.querySelector('ul').innerHTML = st.errors.map((e, i) => `<li><a href="#" data-err="${i}"><strong>${txt(e.field || e.path)}</strong> <code>${txt(e.path)}</code>: ${txt(e.message)}</a></li>`).join('');
|
||
box.hidden = false; box.focus();
|
||
status(`${st.errors.length} ${st.errors.length === 1 ? 'problem' : 'problems'}: ${st.errors.map(e => `${e.field || e.path}, ${e.message}`).join('; ')}`);
|
||
}
|
||
function focusPath(path) {
|
||
const el = root.querySelector(`#org-form [data-path="${CSS.escape(path)}"]`) || $('org-json-text');
|
||
el.focus(); el.scrollIntoView?.({ block: 'center' });
|
||
}
|
||
|
||
// ---- start, open, save ------------------------------------------------
|
||
function openEditor(mode, id, doc, { revision = null, held = [], verb = '', state = 'active' } = {}) {
|
||
Object.assign(st, { mode, id, doc, revision, held, state, errors: [] });
|
||
editorDirty = false; setupDirty.clear(); $('org-new-id').value = '';
|
||
$('org-editor').hidden = false; $('org-delete').hidden = mode !== 'edit'; resetDelete(); resetArchive(); $('org-delete-success').hidden = true;
|
||
$('org-archive').hidden = mode !== 'edit' || state !== 'active'; $('org-archived').hidden = mode !== 'edit' || state !== 'archived';
|
||
$('org-editor-title').textContent = mode === 'create' ? `New organization: ${id}` : `Organization: ${id}`;
|
||
$('org-editor-verb').innerHTML = verb ? `Same as <code>${txt(verb)}</code>` : '';
|
||
$('org-save').textContent = mode === 'create' ? 'Save organization' : 'Save changes';
|
||
$('org-errors').hidden = true;
|
||
renderForm(); renderJSON(true);
|
||
const archived = state === 'archived';
|
||
$('org-form').querySelectorAll('input,select,textarea,button').forEach(el => { el.disabled = archived; });
|
||
$('org-json-text').disabled = archived; $('org-check').disabled = archived; $('org-save').disabled = archived || !canWrite;
|
||
}
|
||
async function startNew(e) {
|
||
e.preventDefault();
|
||
const input = $('org-new-id'), id = input.value.trim();
|
||
if (!ID.test(id)) { input.setAttribute('aria-invalid', 'true'); $('org-new-id-help').textContent = 'Organization ID: use 1-64 lowercase letters, digits, dot, dash or underscore, starting with a letter or digit.'; $('org-new-id-help').classList.add('org-field-err'); input.focus(); status('Organization ID is not valid.'); return; }
|
||
input.removeAttribute('aria-invalid'); $('org-new-id-help').classList.remove('org-field-err'); $('org-new-id-help').textContent = 'Lowercase letters, digits, dot, dash or underscore.';
|
||
const r = await api('GET', '/api/org-presets');
|
||
if (!alive) return;
|
||
if (r.status !== 200) { banner(r.body.message || `Presets could not be read (${r.body.error || r.status}).`); return; }
|
||
presets = r.body.presets;
|
||
st.id = id; st.mode = 'create'; editorDirty = true;
|
||
// A new draft starts with fresh controls; an earlier run locked them only for its own draft.
|
||
$('org-preset').disabled = false; $('org-thinking').disabled = false; $('org-quick-run').disabled = !canWrite; $('org-risk-accept').checked = false;
|
||
$('org-preset').innerHTML = presets.map(p => `<option value="${txt(p.name)}"${p.available.ok ? '' : ' disabled'}>${txt(p.label)}${p.available.ok ? '' : ` — ${txt(p.available.reason)}`}</option>`).join('');
|
||
$('org-preset').value = presets.find(p => p.available.ok)?.name || '';
|
||
updatePreset();
|
||
$('org-paths').hidden = false; $('org-quick').hidden = true; $('org-editor').hidden = true; $('org-receipt').hidden = true; $('org-setup').hidden = true; $('org-delete').hidden = true; $('org-delete-success').hidden = true; $('org-archive').hidden = true; $('org-archived').hidden = true; resetArchive();
|
||
$('org-quick-steps').innerHTML = ''; $('org-quick-open-org').hidden = true; banner(''); setQuery(null);
|
||
$('org-preset').focus();
|
||
}
|
||
function updatePreset() {
|
||
const p = presets.find(v => v.name === $('org-preset').value);
|
||
$('org-preset-help').textContent = p?.description || 'No available presets.';
|
||
$('org-thinking').innerHTML = (p?.thinking.levels || []).map(v => `<option value="${txt(v)}"${v === p.thinking.default ? ' selected' : ''}>${txt(v)}</option>`).join('');
|
||
$('org-quick-open').disabled = !p || !canWrite; $('org-advanced-open').disabled = !p || !canWrite;
|
||
}
|
||
async function selectedTemplate() {
|
||
const q = new URLSearchParams({ id: st.id, preset: $('org-preset').value, thinking: $('org-thinking').value });
|
||
return api('GET', `/api/org-template?${q}`);
|
||
}
|
||
async function openAdvanced() {
|
||
const r = await selectedTemplate(); if (!alive) return;
|
||
if (r.status !== 200) { banner(r.body.message || `Template refused (${r.body.error || r.status}).`); return; }
|
||
$('org-quick').hidden = true; $('org-paths').hidden = true;
|
||
openEditor('create', st.id, r.body.doc, { held: r.body.held || [], verb: r.body.verb });
|
||
root.querySelector('[data-path="$.human"]')?.focus();
|
||
}
|
||
function openQuick() {
|
||
$('org-quick').hidden = false; $('org-editor').hidden = true;
|
||
$('org-project').focus();
|
||
}
|
||
async function quickRun() {
|
||
const project = $('org-project').value.trim(), remote = $('org-project-remote').value.trim();
|
||
if (!ID.test(project)) { $('org-project').setAttribute('aria-invalid', 'true'); banner('Enter a valid project name.'); $('org-project').focus(); return; }
|
||
$('org-project').removeAttribute('aria-invalid');
|
||
if (remote && !/^https:\/\/[^\s/]+\/\S+$/.test(remote)) { banner('Enter an https repository URL or leave it blank.'); $('org-project-remote').focus(); return; }
|
||
if (!$('org-risk-accept').checked) { banner('Accept the risk of local-only repositories to continue.'); $('org-risk-accept').focus(); return; }
|
||
const id = st.id, enc = encodeURIComponent, local = { mode: 'local-only', acceptLocalLossRisk: true };
|
||
const steps = [
|
||
{ title: 'Create organization', verb: `mosaic org create ${id} --from <file>` },
|
||
{ title: 'Initialize organization checkout', verb: `mosaic org queue init ${id} --local-only --accept-local-loss-risk` },
|
||
{ title: `Initialize project repository: ${project}`, verb: `mosaic org project repo init ${id} ${project} ${remote ? `--remote ${remote}` : '--local-only --accept-local-loss-risk'}` },
|
||
{ title: 'Start the bus', verb: `mosaic bus start ${id} --dev-local-owner --detach` },
|
||
{ title: `Create project: ${project}`, verb: `mosaic project create ${project} --repo ${project} --business ${id}` },
|
||
{ title: 'Initialize project records', verb: `mosaic project init ${id} ${project}` },
|
||
];
|
||
const list = $('org-quick-steps');
|
||
list.innerHTML = steps.map((s, i) => `<li class="panel org-step" data-quick-step="${i}" tabindex="-1"><div class="org-step-head"><h4>${txt(s.title)}</h4><span class="org-pill">Not started</span></div><p class="org-verb">Same as <code>${txt(s.verb)}</code></p><p class="org-field-err" role="alert"></p></li>`).join('');
|
||
const run = $('org-quick-run'); run.disabled = true; $('org-quick-open').disabled = true; $('org-advanced-open').disabled = true; $('org-preset').disabled = true; $('org-thinking').disabled = true; banner('');
|
||
let current = 0;
|
||
try {
|
||
const template = await selectedTemplate();
|
||
if (template.status !== 200) throw Error(template.body.message || 'Could not load the template.');
|
||
if (!template.body.doc || typeof template.body.doc !== 'object') throw Error('The template reply could not be read.');
|
||
const doc = template.body.doc; doc.projects = { [project]: {} };
|
||
const requests = [
|
||
['/api/orgs', { id, doc }, 'create'],
|
||
[`/api/orgs/${enc(id)}/setup/queue`, local, 'queue'],
|
||
[`/api/orgs/${enc(id)}/setup/project/${enc(project)}`, remote ? { mode: 'remote', remote } : local, 'project'],
|
||
[`/api/orgs/${enc(id)}/setup/bus`, {}, 'bus'],
|
||
[`/api/orgs/${enc(id)}/chat/projects`, { name: project, repo: project }, 'chat-project'],
|
||
[`/api/orgs/${enc(id)}/setup/records/${enc(project)}`, {}, 'records'],
|
||
];
|
||
for (current = 0; current < requests.length; current++) {
|
||
const card = list.children[current]; card.querySelector('.org-pill').textContent = 'In progress';
|
||
const [url, body, step] = requests[current];
|
||
const result = await api('POST', url, body);
|
||
if (result.status !== 200 && result.status !== 201) throw Error(result.body.message || result.body.errors?.map(e => e.message).join(' ') || `Refused (${result.body.error || result.status}).`);
|
||
// A success status alone is not proof: an unreadable or unexpected reply leaves the outcome unknown, so stop here.
|
||
if (step === 'chat-project' ? !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(result.body.id || '') : result.body.outcome !== 'done' || result.body.step !== step) throw Error('The reply could not be read, so this step\'s outcome is unknown.');
|
||
card.querySelector('.org-pill').textContent = 'Done'; card.classList.add('org-step-done');
|
||
if (result.body.verb) card.querySelector('code').textContent = result.body.verb;
|
||
}
|
||
editorDirty = false; $('org-new-id').value = ''; $('org-quick-open-org').hidden = false; status('Organization setup complete.');
|
||
await refreshList();
|
||
} catch (e) {
|
||
const card = list.children[Math.min(current, steps.length - 1)];
|
||
card.querySelector('.org-pill').textContent = 'Stopped'; card.querySelector('.org-field-err').textContent = current === 4
|
||
? `${e.message} Open the organization and check Projects before creating the project; its outcome may be unknown.`
|
||
: `${e.message} Open the organization to inspect and continue; do not repeat a step whose outcome is unknown.`;
|
||
if (current >= 4) { editorDirty = false; $('org-new-id').value = ''; $('org-quick-open-org').hidden = false; }
|
||
card.classList.add('org-step-warn'); card.focus(); status('Setup stopped.');
|
||
await refreshList();
|
||
}
|
||
}
|
||
async function openExisting(id, { toSetup = false } = {}) {
|
||
const r = await api('GET', `/api/orgs/${encodeURIComponent(id)}/admin`);
|
||
if (!alive) return;
|
||
if (r.status !== 200) { banner(r.status === 404 ? `Organization ${id} is not available.` : r.body.message || `Organization ${id} could not be read (${r.body.error || r.status}).`); return; }
|
||
banner(''); $('org-paths').hidden = true; $('org-quick').hidden = true;
|
||
openEditor('edit', id, r.body.doc, { revision: r.body.revision, held: r.body.held || [], verb: r.body.verb, state: r.body.state || 'active' });
|
||
setQuery(id, toSetup ? 'setup' : null);
|
||
if (st.state === 'archived') $('org-setup').hidden = true; else await loadSetup(id);
|
||
}
|
||
async function check() {
|
||
const r = await api('POST', '/api/org-validate', { id: st.id, doc: st.doc });
|
||
if (!alive) return;
|
||
if (r.status !== 200) { banner(r.body.message || `Check failed (${r.body.error || r.status}).`); return; }
|
||
if (r.body.ok) { showErrors([]); banner('No problems found.', 'ok'); status('No problems found.'); }
|
||
else { banner(''); showErrors(r.body.errors); }
|
||
}
|
||
async function save(e) {
|
||
e.preventDefault();
|
||
if ($('org-json-text').getAttribute('aria-invalid') === 'true') { banner('The JSON is not valid. Fix it or undo the edit before saving.'); $('org-json-text').focus(); return; }
|
||
const button = $('org-save'); button.disabled = true; button.insertAdjacentHTML('beforeend', ' <span class="settings-spinner" aria-hidden="true"></span>');
|
||
try {
|
||
const r = st.mode === 'create'
|
||
? await api('POST', '/api/orgs', { id: st.id, doc: st.doc })
|
||
: await api('POST', `/api/orgs/${encodeURIComponent(st.id)}/admin`, { doc: st.doc, ifRevision: st.revision });
|
||
if (!alive) return;
|
||
if (r.status === 422 && r.body.errors?.length) { banner(''); showErrors(r.body.errors); return; }
|
||
if (r.status === 409 && r.body.error === 'revision-conflict') { banner(`Not saved. ${r.body.message}`); status(`Not saved: ${r.body.message}`); return; }
|
||
if (r.status === 409 && /exists|overlap/.test(r.body.error || '')) { banner(`Not saved. ${st.id} already exists. Open it from Existing organization to edit or finish its setup.`); return; }
|
||
if (r.status === 502) { banner(`The outcome is unknown. Open ${st.id} to read it back before saving again.`, 'warn'); return; }
|
||
if (r.status >= 300) { banner(r.body.message || `Not saved (${r.body.error || r.status}).`); return; }
|
||
showErrors([]); banner('');
|
||
if (st.mode === 'create') {
|
||
// The saved form is no longer a draft. Other drafts still use the normal switch guard.
|
||
editorDirty = false; setupDirty.clear(); $('org-new-id').value = '';
|
||
const id = encodeURIComponent(st.id), next = `#/orgs/${id}/settings/organizations?org=${id}&step=setup&created=1`;
|
||
if (window.MosaicOrg) location.hash = next;
|
||
else { history.replaceState(null, '', next); location.reload(); }
|
||
return;
|
||
}
|
||
showReceipt('Changes saved', r.body);
|
||
await openExisting(st.id);
|
||
} finally { button.disabled = false; button.querySelector('.settings-spinner')?.remove(); }
|
||
}
|
||
function showReceipt(title, body) {
|
||
const box = $('org-receipt');
|
||
box.innerHTML = `<h3 id="org-receipt-title">${txt(title)}</h3><p>Same as <code>${txt(body.verb)}</code></p><pre class="org-pre">${txt(JSON.stringify(body.receipt, null, 2))}</pre>`;
|
||
box.hidden = false; status(`${title}. Receipt shown.`);
|
||
}
|
||
async function refreshList() {
|
||
const r = await api('GET', '/api/org-admin');
|
||
if (!alive) return;
|
||
const sel = $('org-open-id'), selected = sel.value;
|
||
const orgs = r.status === 200 ? r.body.orgs : [];
|
||
sel.innerHTML = orgs.length ? orgs.map(o => `<option value="${txt(o.id)}">${txt(o.id)}${o.state === 'reserved' ? ' (creation did not finish)' : o.state === 'deleting' ? ' (deletion in progress; resume with CLI)' : o.state === 'archived' ? ' (archived)' : ''}</option>`).join('') : `<option value="">${r.status === 200 ? 'None yet' : 'Not available'}</option>`;
|
||
if (orgs.some(o => o.id === selected)) sel.value = selected;
|
||
sel.disabled = !orgs.length; $('org-open-form').querySelector('button').disabled = !orgs.length;
|
||
}
|
||
|
||
// ---- guided setup -----------------------------------------------------
|
||
const STATE = { done: ['Done', 'done'], missing: ['Not started', 'todo'], unknown: ['Incomplete: outcome unknown', 'warn'], unavailable: ['Not available yet', 'off'], failed: ['Incomplete: refused', 'warn'] };
|
||
async function loadSetup(id) {
|
||
const r = await api('GET', `/api/orgs/${encodeURIComponent(id)}/setup`);
|
||
if (!alive) return;
|
||
if (r.status !== 200) { st.setup = null; $('org-setup').hidden = false; $('org-steps').innerHTML = `<li class="panel org-step"><p class="org-field-err">Setup could not be read back (${txt(r.body.error || r.status)}). ${txt(r.body.message || '')}</p><button type="button" class="org-secondary" data-readback>Read back again</button></li>`; return; }
|
||
st.setup = r.body;
|
||
for (const key of [...st.unknown]) if (stepState(key)?.state !== 'unknown') st.unknown.delete(key);
|
||
renderSetup();
|
||
}
|
||
const stepKeys = () => st.setup ? [...(st.setup.notifications ? ['notifications'] : []), 'queue', ...st.setup.projects.map(p => `project:${p.project}`), 'bus'] : [];
|
||
function stepState(key) {
|
||
if (!st.setup) return null;
|
||
if (key === 'notifications') return st.setup.notifications;
|
||
if (key === 'queue') return st.setup.queue;
|
||
if (key === 'bus') return st.setup.bus;
|
||
return st.setup.projects.find(p => `project:${p.project}` === key);
|
||
}
|
||
function renderSetup() {
|
||
const keys = stepKeys(); let blocked = false, firstOpen = null;
|
||
$('org-setup').hidden = false;
|
||
$('org-steps').innerHTML = keys.map((key, i) => {
|
||
const s = { ...stepState(key) }; if (st.unknown.has(key) && s.state !== 'done') s.state = 'unknown';
|
||
if (s.lastError && s.state !== 'done') s.state = s.state === 'unknown' ? 'unknown' : 'failed';
|
||
const [stateLabel, cls] = STATE[s.state] || STATE.unknown;
|
||
const ready = !blocked && s.state !== 'done' && s.state !== 'unavailable';
|
||
if (s.state !== 'done') { if (!firstOpen) firstOpen = key; blocked = true; }
|
||
const title = key === 'notifications' ? 'Notifications' : key === 'queue' ? 'Organization checkout' : key === 'bus' ? 'Start the bus' : `Project repository: ${key.slice(8)}`;
|
||
const git = key !== 'bus' && key !== 'notifications';
|
||
const name = `org-mode-${i}`;
|
||
const busy = st.pending.has(key);
|
||
const c = st.choice.get(key) || {}, remote = c.mode === 'remote';
|
||
return `<li class="panel org-step org-step-${cls}" data-step="${txt(key)}" aria-labelledby="org-step-${i}-title">
|
||
<div class="org-step-head"><h4 id="org-step-${i}-title"><span class="org-step-n">${i + 1}</span> ${txt(title)}</h4><span class="org-pill ${cls}">${txt(stateLabel)}</span></div>
|
||
<p class="org-verb">Same as <code>${txt(s.verb || '')}</code></p>
|
||
${s.message ? `<p class="org-help">${txt(s.message)}</p>` : ''}
|
||
${s.lastError ? `<p class="org-field-err" role="alert">${txt(s.lastError)}</p>` : ''}
|
||
${s.receipt ? `<details${s.state === 'done' ? '' : ' open'}><summary>${key === 'bus' ? 'Bus status' : 'Receipt'}</summary><pre class="org-pre">${txt(JSON.stringify(s.receipt, null, 2))}</pre></details>` : ''}
|
||
${s.state === 'unknown' ? `<div class="settings-actions"><button type="button" class="org-secondary" data-readback="${txt(key)}">Read back</button><span class="org-help">Retry stays off until the step is read back.</span></div>` : ''}
|
||
${s.state !== 'done' && s.state !== 'unknown' && git ? `<fieldset class="org-git" ${ready && canWrite ? '' : 'disabled'}><legend>Where the history lives</legend>
|
||
<label><input type="radio" name="${name}" value="local-only"${remote ? '' : ' checked'}> Local only, on this machine</label>
|
||
<label><input type="radio" name="${name}" value="remote"${remote ? ' checked' : ''}> Remote</label>
|
||
<div class="org-remote"${remote ? '' : ' hidden'}><label for="${name}-remote">Remote repository URL</label><input id="${name}-remote" type="url" inputmode="url" data-remote autocomplete="off" spellcheck="false" placeholder="https://git.example/owner/repo" value="${txt(c.remote || '')}" aria-describedby="${name}-remote-help"${remote && s.lastError ? ' aria-invalid="true"' : ''}><span id="${name}-remote-help" class="org-help">An https URL. It is recorded in the receipt and the organization file; nothing is pushed.</span></div>
|
||
<label class="org-risk"${remote ? ' hidden' : ''}><input type="checkbox" data-risk${c.risk ? ' checked' : ''}${!remote && s.lastError && !c.risk ? ' aria-invalid="true"' : ''}> I accept that a local-only history has no copy anywhere else and is lost with this disk.</label>
|
||
<div class="settings-actions"><button type="button" data-run="${txt(key)}">${busy ? 'Working… <span class="settings-spinner" aria-hidden="true"></span>' : key === 'queue' ? 'Set up checkout' : 'Set up repository'}</button></div>
|
||
</fieldset>` : ''}
|
||
${s.state !== 'done' && s.state !== 'unknown' && key === 'bus' ? `<div class="settings-actions"><button type="button" data-run="bus" ${ready && canWrite && !busy ? '' : 'disabled'}>${busy ? 'Starting… <span class="settings-spinner" aria-hidden="true"></span>' : 'Start the bus'}</button>${ready ? '' : '<span class="org-help">Finish the steps above first.</span>'}</div>` : ''}
|
||
</li>`;
|
||
}).join('');
|
||
for (const card of root.querySelectorAll('.org-step')) if (st.choice.has(card.dataset.step) && card.querySelector('.org-git')) showVerb(card);
|
||
if (!firstOpen) status('Setup complete. Every step has a receipt.');
|
||
return firstOpen;
|
||
}
|
||
function stepOptions(card) {
|
||
const mode = card.querySelector('input[type=radio]:checked')?.value;
|
||
if (mode === 'remote') return { mode, remote: card.querySelector('[data-remote]').value.trim() };
|
||
return { mode: 'local-only', acceptLocalLossRisk: card.querySelector('[data-risk]').checked };
|
||
}
|
||
async function runStep(key) {
|
||
const card = root.querySelector(`[data-step="${CSS.escape(key)}"]`), s = stepState(key);
|
||
const id = st.id; let url, body;
|
||
if (key === 'bus') { url = `/api/orgs/${encodeURIComponent(id)}/setup/bus`; body = {}; }
|
||
else {
|
||
body = stepOptions(card);
|
||
if (body.mode === 'local-only' && !body.acceptLocalLossRisk) { s.lastError = 'Tick the box to accept the local-only risk, or choose Remote.'; renderSetup(); root.querySelector(`[data-step="${CSS.escape(key)}"] [data-risk]`)?.focus(); status(s.lastError); return; }
|
||
url = key === 'queue' ? `/api/orgs/${encodeURIComponent(id)}/setup/queue` : `/api/orgs/${encodeURIComponent(id)}/setup/project/${encodeURIComponent(key.slice(8))}`;
|
||
}
|
||
st.pending.add(key); delete s.lastError; renderSetup();
|
||
let r;
|
||
try { r = await api('POST', url, body); }
|
||
catch { r = { status: 0, body: { error: 'outcome-unknown' } }; }
|
||
st.pending.delete(key);
|
||
if (!alive) return;
|
||
if (r.status === 200 || r.status === 201) {
|
||
setupDirty.delete(key);
|
||
status(`${r.body.existing ? 'Already done; receipt read back' : 'Done'}: ${key === 'queue' ? 'organization checkout' : key === 'bus' ? 'bus' : `repository for ${key.slice(8)}`}.`);
|
||
await loadSetup(id); focusFirstOpen(); return;
|
||
}
|
||
if (r.status === 0 || r.status === 502 || r.body.error === 'outcome-unknown') { st.unknown.add(key); s.lastError = 'The outcome is unknown. Read the step back before retrying.'; }
|
||
else if (r.body.error === 'readback-failed') { st.unknown.add(key); s.lastError = r.body.message; }
|
||
else if (r.body.errors?.length) s.lastError = r.body.errors.map(e => `${e.field}: ${e.message}`).join(' ');
|
||
else s.lastError = r.body.message || `Refused (${r.body.error || r.status}).`;
|
||
status(`Step incomplete: ${s.lastError}`);
|
||
renderSetup(); root.querySelector(`[data-step="${CSS.escape(key)}"] h4`)?.setAttribute('tabindex', '-1'); root.querySelector(`[data-step="${CSS.escape(key)}"] h4`)?.focus();
|
||
}
|
||
function focusFirstOpen() {
|
||
const key = stepKeys().find(k => { const s = stepState(k); return s?.state !== 'done'; });
|
||
const h = key ? root.querySelector(`[data-step="${CSS.escape(key)}"] h4`) : $('org-setup-title');
|
||
if (h) { h.setAttribute('tabindex', '-1'); h.focus(); }
|
||
}
|
||
function onSetupClick(e) {
|
||
const run = e.target.closest('[data-run]'); if (run && !run.disabled) { runStep(run.dataset.run); return; }
|
||
const rb = e.target.closest('[data-readback]');
|
||
if (rb) { const key = rb.dataset.readback; status('Reading the step back.'); st.unknown.delete(key); loadSetup(st.id).then(() => { const s = stepState(key); if (s?.state === 'unknown') st.unknown.add(key); renderSetup(); status(s ? `Read back: ${STATE[s.state]?.[0] || s.state}.` : 'Read back.'); }); }
|
||
}
|
||
// The "Same as" line follows the choice in the card.
|
||
function showVerb(card) {
|
||
const key = card.dataset.step; if (key === 'bus') return;
|
||
const o = stepOptions(card), tail = o.mode === 'remote' ? `--remote ${o.remote || '<https-url>'}` : '--local-only --accept-local-loss-risk';
|
||
const code = card.querySelector('.org-verb code'); if (!code) return;
|
||
code.textContent = key === 'queue' ? `mosaic org queue init ${st.id} ${tail}` : `mosaic org project repo init ${st.id} ${key.slice(8)} ${tail}`;
|
||
}
|
||
// A card's choice survives a re-render (a refusal keeps the URL the person typed).
|
||
function keepChoice(card) {
|
||
const o = stepOptions(card);
|
||
setupDirty.add(card.dataset.step);
|
||
st.choice.set(card.dataset.step, { mode: o.mode, remote: card.querySelector('[data-remote]')?.value ?? '', risk: !!card.querySelector('[data-risk]')?.checked });
|
||
}
|
||
function onSetupChange(e) {
|
||
const card = e.target.closest('.org-step'); if (!card) return;
|
||
if (card.querySelector('.org-git')) keepChoice(card);
|
||
if (e.target.type === 'radio') {
|
||
const remote = e.target.value === 'remote';
|
||
card.querySelector('.org-remote').hidden = !remote; card.querySelector('.org-risk').hidden = remote;
|
||
}
|
||
if (e.target.type === 'radio' || e.target.matches('[data-remote]')) showVerb(card);
|
||
if (e.target.matches('[data-risk]')) e.target.removeAttribute('aria-invalid');
|
||
}
|
||
|
||
function resetArchive() {
|
||
$('org-archive-confirm').hidden = true; $('org-archive-open').hidden = false;
|
||
$('org-archive-error').textContent = ''; $('org-archive-success').hidden = true;
|
||
$('org-archive-final').disabled = !canWrite; $('org-restore').disabled = !canWrite;
|
||
}
|
||
async function refreshOrganizations() {
|
||
const rows = window.MosaicOrg ? await window.MosaicOrg.refreshList() : [];
|
||
await refreshList(); return rows;
|
||
}
|
||
function switchIfCurrentRemoved(id, rows) {
|
||
if (window.MosaicOrg?.id !== id) return false;
|
||
const next = rows.find(row => row.id !== id);
|
||
const hash = next ? `#/orgs/${encodeURIComponent(next.id)}/settings/organizations` : '#/settings/organizations';
|
||
history.replaceState(null, '', hash); location.reload(); return true;
|
||
}
|
||
async function runLifecycle(step) {
|
||
const id = st.id, revision = st.revision, button = $(step === 'archive' ? 'org-archive-final' : 'org-restore');
|
||
button.disabled = true; $('org-archive-error').textContent = '';
|
||
try {
|
||
const reply = await api('POST', `/api/orgs/${encodeURIComponent(id)}/${step}`, { revision });
|
||
if (!alive) return;
|
||
if (!verifiedReply(reply, step)) throw Error('unknown lifecycle outcome');
|
||
const rows = await refreshOrganizations();
|
||
if (step === 'archive' && switchIfCurrentRemoved(id, rows)) return;
|
||
if (step === 'restore' && !window.MosaicOrg) { history.replaceState(null, '', `#/orgs/${encodeURIComponent(id)}/settings/organizations`); location.reload(); return; }
|
||
await openExisting(id);
|
||
if (step === 'restore') {
|
||
const box = $('org-archive-success'); box.textContent = 'Organization restored. The bus remains stopped.'; box.hidden = false; box.focus();
|
||
} else $('org-archived').focus();
|
||
status(`Organization ${step === 'archive' ? 'archived' : 'restored'}.`);
|
||
} catch {
|
||
$('org-archive-error').textContent = `The outcome is unknown. Inspect the organization before retrying: mosaic org ${step} ${id} --if-revision ${revision}.`;
|
||
}
|
||
}
|
||
function resetDelete() {
|
||
$('org-delete-first').hidden = true; $('org-delete-second').hidden = true; $('org-delete-open').hidden = false; $('org-delete-confirm').value = ''; $('org-delete-final').disabled = true; $('org-delete-error').textContent = ''; $('org-delete-progress').innerHTML = '';
|
||
}
|
||
function cancelDelete() { resetDelete(); $('org-delete-open').focus(); }
|
||
async function runDelete() {
|
||
const id = st.id, revision = st.revision, button = $('org-delete-final');
|
||
button.disabled = true; $('org-delete-error').textContent = ''; $('org-delete-progress').innerHTML = '<p>Deletion in progress…</p>';
|
||
try {
|
||
const r = await api('POST', `/api/orgs/${encodeURIComponent(id)}/delete`, { confirm: $('org-delete-confirm').value, revision });
|
||
if (!alive) return;
|
||
if (r.status !== 200) {
|
||
$('org-delete-error').textContent = `The outcome is unknown. ${r.body.message || `Deletion stopped (${r.body.error || r.status}).`} Inspect the receipt and resume with the CLI.`;
|
||
const receipt = r.body.receipt;
|
||
$('org-delete-progress').innerHTML = `<p>Same as <code>${txt(r.body.verb || `mosaic org delete ${id} --confirm ${id}`)}</code></p><ol class="org-steps"><li class="panel org-step">Bus: ${receipt?.bus ? 'Done' : r.body.step === 'bus' ? 'Stopped' : 'Not started'}</li><li class="panel org-step">Local files: ${receipt?.moves?.length || 0} moved; ${txt(r.body.step || 'deletion')} stopped</li><li class="panel org-step">Registry: ${receipt?.registry === 'removed' ? 'Done' : 'Not complete'}</li></ol>`;
|
||
status('Deletion stopped.'); return;
|
||
}
|
||
if (!verifiedReply(r, 'delete')) throw Error('unknown deletion outcome');
|
||
editorDirty = false; setupDirty.clear(); $('org-editor').hidden = true; $('org-setup').hidden = true; $('org-delete').hidden = true; $('org-archive').hidden = true; $('org-archived').hidden = true;
|
||
const box = $('org-delete-success');
|
||
box.innerHTML = `<h3>Organization deleted</h3><p>Same as <code>${txt(r.body.verb)}</code></p><ol class="org-steps"><li class="panel org-step org-step-done">Bus stopped or was already stopped: Done</li><li class="panel org-step org-step-done">Local files moved to the deleted folder: Done</li><li class="panel org-step org-step-done">Organization removed from the list: Done</li></ol><details><summary>Receipt</summary><pre class="org-pre">${txt(JSON.stringify(r.body.receipt, null, 2))}</pre></details>`;
|
||
const rows = await refreshOrganizations(); box.hidden = false; box.focus(); status('Organization deleted.');
|
||
switchIfCurrentRemoved(id, rows);
|
||
} catch { $('org-delete-error').textContent = 'The outcome is unknown. Inspect the receipt and resume with the CLI.'; $('org-delete-progress').innerHTML = `<p>Resume with <code>${txt(`mosaic org delete ${id} --confirm ${id}`)}</code></p>`; }
|
||
}
|
||
|
||
// ---- wiring -----------------------------------------------------------
|
||
const handlers = [
|
||
[$('org-archive-open'), 'click', () => { $('org-archive-open').hidden = true; $('org-archive-confirm').hidden = false; $('org-archive-confirm').focus(); }],
|
||
[$('org-archive-cancel'), 'click', () => { resetArchive(); $('org-archive-open').focus(); }],
|
||
[$('org-archive-final'), 'click', () => runLifecycle('archive')],
|
||
[$('org-restore'), 'click', () => runLifecycle('restore')],
|
||
[$('org-delete-open'), 'click', () => { $('org-delete-open').hidden = true; $('org-delete-first').hidden = false; $('org-delete-first').focus(); }],
|
||
[$('org-delete-cancel'), 'click', cancelDelete],
|
||
[$('org-delete-cancel-second'), 'click', cancelDelete],
|
||
[$('org-delete-continue'), 'click', () => { $('org-delete-first').hidden = true; $('org-delete-second').hidden = false; $('org-delete-confirm').focus(); }],
|
||
[$('org-delete-confirm'), 'input', () => { $('org-delete-final').disabled = $('org-delete-confirm').value !== st.id; }],
|
||
[$('org-delete-final'), 'click', runDelete],
|
||
[$('org-new-form'), 'submit', startNew],
|
||
[$('org-preset'), 'change', updatePreset],
|
||
[$('org-quick-open'), 'click', openQuick],
|
||
[$('org-advanced-open'), 'click', openAdvanced],
|
||
[$('org-quick-run'), 'click', quickRun],
|
||
[$('org-quick-open-org'), 'click', () => { history.replaceState(null, '', `#/orgs/${encodeURIComponent(st.id)}/projects`); location.reload(); }],
|
||
[$('org-open-form'), 'submit', e => { e.preventDefault(); const id = $('org-open-id').value; if (id) openExisting(id); }],
|
||
[$('org-form'), 'submit', save],
|
||
[$('org-form'), 'input', onFormInput],
|
||
[$('org-form'), 'change', onFormChange],
|
||
[$('org-form'), 'click', onFormClick],
|
||
[$('org-json-text'), 'input', onJSONInput],
|
||
[$('org-json-text'), 'blur', () => { if ($('org-json-text').getAttribute('aria-invalid') !== 'true') renderJSON(true); }],
|
||
[$('org-check'), 'click', check],
|
||
[$('org-errors'), 'click', e => { const a = e.target.closest('[data-err]'); if (a) { e.preventDefault(); focusPath(st.errors[Number(a.dataset.err)].path); } }],
|
||
[$('org-steps'), 'click', onSetupClick],
|
||
[$('org-steps'), 'change', onSetupChange],
|
||
[$('org-steps'), 'input', e => { const card = e.target.closest('.org-step'); if (card && e.target.matches('[data-remote]')) { keepChoice(card); showVerb(card); } }],
|
||
];
|
||
for (const [el, ev, fn] of handlers) el.addEventListener(ev, fn);
|
||
fetch('/api/config', { cache: 'no-store' }).then(r => r.json()).then(async config => {
|
||
if (!alive) return;
|
||
canWrite = (config.orgSetup === true || config.send === true) && config.tester !== true && config.user !== true;
|
||
root.querySelectorAll('[data-write]').forEach(el => { el.disabled = !canWrite; });
|
||
const params = query(), org = params.get('org'), setup = params.get('step') === 'setup', created = params.get('created') === '1';
|
||
// ?new=1 ("New organization" in the header menu, the Organization picker and the empty state): focus the ID field, then drop
|
||
// the flag so the same link focuses it again next time. This runs after the page heading took the navigation focus.
|
||
if (params.get('new') === '1' && !org) { $('org-new-id').focus(); setQuery(null, null); }
|
||
await refreshList();
|
||
// Resume: ?org=ID reopens the organization and its setup, read back from the server.
|
||
if (org && ID.test(org)) {
|
||
await openExisting(org, { toSetup: setup });
|
||
if (created && st.setup?.notifications?.receipt) showReceipt('Organization created', st.setup.notifications);
|
||
if (setup) focusFirstOpen();
|
||
}
|
||
}).catch(() => banner('The Console configuration could not be read.'));
|
||
return () => { alive = false; delete window.MosaicOrgCreate.hasDraft; for (const [el, ev, fn] of handlers) el.removeEventListener(ev, fn); };
|
||
}
|
||
window.MosaicOrgCreate = { markup, mount };
|
||
})();
|