// Starter packs SP6 (#1873, design section 8): the owner's workflow list and editor on an // organization's page. GET /api/orgs//workflows reads the org's and each code project's workflows // with the file revision; a save is POST .../workflows/ {revision, workflow, project?} and a delete // DELETE .../workflows/ {revision, project?} (workflow.set.console). The bus checks the shape; this // page marks a step role that resolves to no org definition or role template (and is not `human`) as // naming no current role. Every organization-supplied string goes through esc. (() => { 'use strict'; const esc = x => String(x ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); const base = org => `/api/orgs/${encodeURIComponent(org)}`; const STATES = [['todo', 'To do'], ['in-progress', 'In progress'], ['in-review', 'Review'], ['blocked', 'Blocked'], ['done', 'Done']]; const STATE_LABEL = Object.fromEntries(STATES); // The writer's workflow name rule (organization.mjs PLAN_NAME); a name it would refuse is refused here first. const NAME = /^[a-z][a-z0-9-]{0,63}$/; const NAME_RULE = 'A workflow name is 1 to 64 lowercase letters, digits or dashes, starting with a letter.'; const MISSING = 'names no current role'; const states = new Map(); const guidance = { 'revision-conflict': 'The organization changed since this page read it. Reload the page before saving.', 'organization-busy': 'The organization is busy with another write. Try again shortly.', 'invalid-request': 'The bus refused the workflow. Check each step has a title, a state and one to eight distinct roles.', 'project-not-found': 'That project is not in the organization file.', 'credential-leak': 'The workflow carries a value the credential store holds.', 'read-only': 'This Console was started without send. Workflows can be read, not changed.', 'owner-only': 'Only the owner can read and change workflows.', 'sign-in-required': 'Sign in again to read workflows.', 'cross-origin': 'The request did not come from this Console.', 'not-configured': 'This Console cannot read the organization file.', 'org-unavailable': 'The organization file could not be read.', 'no-bus-host': 'The organization bus is not running.', }; async function call(url, method, body) { const r = await fetch(url, method === 'GET' ? { cache: 'no-store' } : { method, headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); let value = null; try { value = await r.json(); } catch { value = null; } if (!r.ok) throw Error(guidance[value?.error] ?? `The bus refused: ${value?.error ?? 'outcome unknown'}.`); return value; } const plain = v => v !== null && typeof v === 'object' && !Array.isArray(v); async function read(org, s) { const value = await call(`${base(org)}/workflows`, 'GET'); if (!plain(value) || !plain(value.workflows) || !plain(value.projects) || !plain(value.roles) || typeof value.revision !== 'string') throw Error('The workflow read returned an unexpected answer.'); s.data = value; s.known = new Set([...(value.roles.definitions || []), ...(value.roles.templates || []), 'human']); } // E2E6 P1-1: a poll reloads the data but keeps the page's own state: an open editor and its draft, // a pending delete confirmation and the last receipt. async function load(org) { const prev = states.get(org); const s = { data: null, known: new Set(), error: null, editing: prev?.editing ?? null, confirm: prev?.confirm ?? null, status: prev?.status ?? '' }; try { await read(org, s); } catch (error) { // Review P3: a failed poll while an editor is open keeps the last good read, so the fresh section // still carries its data-live-key and graftLive puts the held section, editor and focus back. if (prev?.editing && prev.data) Object.assign(s, { data: prev.data, known: prev.known }); else s.error = error.message; } states.set(org, s); } const scopes = s => [['', 'Organization', s.data.workflows], ...Object.keys(s.data.projects).sort().map(p => [p, `Project ${p}`, s.data.projects[p]])]; const roleChip = (s, role) => s.known.has(role) ? `${esc(role)}` : `${esc(role)} ${MISSING}`; function stepItem(s, step) { const roles = Array.isArray(step?.roles) ? step.roles : []; return `
  • ${esc(step?.title)} ${esc(STATE_LABEL[step?.state] ?? step?.state)} ${roles.map(r => roleChip(s, r)).join(', ')}
  • `; } function workflowItem(org, s, scope, name, w) { const steps = Array.isArray(w?.steps) ? w.steps : []; const confirm = s.confirm && s.confirm.scope === scope && s.confirm.name === name; const actions = !s.data.writable ? '' : confirm ? `

    Delete this workflow?

    ` : `

    `; return `
  • ${esc(w?.title || name)} ${esc(name)} ${w?.description ? `

    ${esc(w.description)}

    ` : ''}
      ${steps.map(st => stepItem(s, st)).join('')}
    ${actions}
  • `; } function stepRow(s, step, i) { const roles = step.roles.split(',').map(r => r.trim()).filter(Boolean); const missing = roles.filter(r => !s.known.has(r)); return `
    Step ${i + 1}

    ${missing.length ? `${missing.map(r => `${esc(r)}`).join(', ')} ${MISSING}` : ''}

    `; } function editor(s) { const e = s.editing; if (!e) return ''; const scopeField = e.isNew ? `` : `

    ${e.scope ? `Project ${esc(e.scope)}` : 'Organization'}, ${esc(e.name)}

    `; return `

    ${e.isNew ? 'New workflow' : 'Edit workflow'}

    ${scopeField} ${e.draft.steps.map((st, i) => stepRow(s, st, i)).join('')}

    Roles name an organization role, a role template, or human.

    `; } function section(org) { const s = states.get(org); if (!s || s.error) return `

    Workflows

    ${esc(s?.error ?? 'Workflows could not be read.')}

    `; const lists = scopes(s).map(([scope, label, flows]) => { const names = Object.keys(flows || {}).sort(); return `

    ${esc(label)}

    ${names.length ? `
      ${names.map(n => workflowItem(org, s, scope, n, flows[n])).join('')}
    ` : '

    No workflows.

    '}
    `; }).join(''); const add = s.data.writable ? (s.editing ? '' : `

    `) : '

    Only the owner, on a Console started with send, can change workflows.

    '; return `

    Workflows

    A workflow lists the steps a task goes through, the state each step puts it in and the roles that do it.

    ${lists}${add}${editor(s)}

    ${esc(s.status)}

    `; } function redraw(org) { const el = [...document.querySelectorAll('[data-workflows-org]')].find(n => n.dataset.workflowsOrg === org); if (el) el.outerHTML = section(org); } // The editor's current values back into the draft, so adding or removing a step keeps what was typed. function capture(root, s) { const form = root.querySelector('[data-wf-editor]'); if (!form || !s.editing) return; const e = s.editing; if (e.isNew) { e.scope = form.elements.scope?.value ?? e.scope; e.name = form.elements.name?.value ?? e.name; } e.draft.title = form.querySelector(':scope > label > input[name="title"]').value; e.draft.description = form.elements.description.value; e.draft.steps = [...form.querySelectorAll('[data-wf-edit-step]')].map(f => ({ title: f.querySelector('[name="title"]').value, state: f.querySelector('[name="state"]').value, roles: f.querySelector('[name="roles"]').value })); } const flowsIn = (s, scope) => scope ? s.data.projects[scope] : s.data.workflows; const target = (s, scope) => scope ? { project: scope } : {}; async function reload(org, s, status) { try { await read(org, s); s.status = status; } catch (error) { s.status = `${status} ${error.message}`; } } document.addEventListener('click', async ev => { const button = ev.target.closest('[data-wf-new],[data-wf-edit],[data-wf-cancel],[data-wf-step-add],[data-wf-step-remove],[data-wf-delete],[data-wf-delete-yes],[data-wf-delete-no]'); if (!button) return; const root = button.closest('[data-workflows-org]'), org = root?.dataset.workflowsOrg, s = states.get(org); if (!s?.data) return; const item = button.closest('[data-wf]'), scope = item?.dataset.wfScope ?? '', name = item?.dataset.wf; if (button.hasAttribute('data-wf-new')) { s.editing = { isNew: true, revision: s.data.revision, scope: '', name: '', draft: { title: '', description: '', steps: [{ title: '', state: 'todo', roles: '' }] } }; } else if (button.hasAttribute('data-wf-edit')) { const w = flowsIn(s, scope)?.[name]; s.editing = { isNew: false, revision: s.data.revision, scope, name, draft: { title: w?.title ?? '', description: w?.description ?? '', steps: (w?.steps ?? []).map(st => ({ title: st.title ?? '', state: st.state ?? 'todo', roles: (st.roles ?? []).join(', ') })) } }; } else if (button.hasAttribute('data-wf-cancel')) { s.editing = null; } else if (button.hasAttribute('data-wf-step-add')) { capture(root, s); s.editing.draft.steps.push({ title: '', state: 'todo', roles: '' }); } else if (button.hasAttribute('data-wf-step-remove')) { capture(root, s); s.editing.draft.steps.splice(Number(button.closest('[data-wf-edit-step]').dataset.wfEditStep), 1); } else if (button.hasAttribute('data-wf-delete')) { s.confirm = { scope, name }; } else if (button.hasAttribute('data-wf-delete-no')) { s.confirm = null; } else if (button.hasAttribute('data-wf-delete-yes')) { button.disabled = true; try { await call(`${base(org)}/workflows/${encodeURIComponent(name)}`, 'DELETE', { revision: s.data.revision, ...target(s, scope) }); s.confirm = null; await reload(org, s, `Deleted ${name}.`); } catch (error) { s.status = error.message; } } redraw(org); }); // Every keystroke goes back into the draft, so any repaint draws what was typed. document.addEventListener('input', ev => { const form = ev.target.closest('[data-wf-editor]'), root = form?.closest('[data-workflows-org]'); if (form && root) { const st = states.get(root.dataset.workflowsOrg); if (st?.editing) capture(root, st); } const field = ev.target.closest('[data-wf-edit-step] [name="roles"]'); if (!field) return; const s = states.get(field.closest('[data-workflows-org]')?.dataset.workflowsOrg); if (!s) return; const missing = field.value.split(',').map(r => r.trim()).filter(r => r && !s.known.has(r)); // textContent and created nodes only: a typed name never becomes markup. const note = field.closest('[data-wf-edit-step]').querySelector('[data-wf-step-missing]'); note.textContent = missing.length ? `${missing.join(', ')} ${MISSING}` : ''; }); document.addEventListener('submit', async ev => { if (!ev.target.matches('[data-wf-editor]')) return; ev.preventDefault(); const root = ev.target.closest('[data-workflows-org]'), org = root?.dataset.workflowsOrg, s = states.get(org); if (!s?.editing) return; capture(root, s); const e = s.editing; if (!NAME.test(e.name)) { s.status = NAME_RULE; redraw(org); return; } // A save is a set: a new workflow under a name the scope already holds would replace it without a word. if (e.isNew && Object.hasOwn(flowsIn(s, e.scope) ?? {}, e.name)) { s.status = `A workflow named ${e.name} already exists here. Edit it instead.`; redraw(org); return; } // E2E6 P2-1: a step role that names no current role is named before the bus refuses it generically. const unknown = e.draft.steps.flatMap((st, i) => st.roles.split(',').map(r => r.trim()).filter(r => r && !s.known.has(r)).map(r => [i + 1, r])); if (unknown.length) { s.status = `${unknown.map(([i, r]) => `Step ${i}: ${r}`).join('; ')} ${unknown.length === 1 ? 'names' : 'name'} no current role. Use an organization role, a role template or human.`; redraw(org); return; } const workflow = { ...(e.draft.title.trim() ? { title: e.draft.title.trim() } : {}), ...(e.draft.description.trim() ? { description: e.draft.description.trim() } : {}), steps: e.draft.steps.map(st => ({ title: st.title.trim(), state: st.state, roles: st.roles.split(',').map(r => r.trim()).filter(Boolean) })), }; const button = ev.target.querySelector('button[type="submit"]'); button.disabled = true; try { // The revision the editor opened on: a change made since then is a revision-conflict, not overwritten. await call(`${base(org)}/workflows/${encodeURIComponent(e.name)}`, 'POST', { revision: e.revision ?? s.data.revision, workflow, ...target(s, e.scope) }); s.editing = null; await reload(org, s, `Saved ${e.name}.`); } catch (error) { s.status = error.message; } redraw(org); }); window.MosaicWorkflows = { load, section }; })();