/* Shared project layer for the Work Package Suite. Projects are the top-level container — every SOP and Work Package belongs to one. Project records live in the SQL database (via /api/projects); this adapter is API-first and falls back to a localStorage mirror so the suite still works in local dev / offline. Included by the home page and the suite. */ (function (global) { 'use strict'; var API = '/api'; var LS_PROJECTS = 'wp_projects'; // local mirror of the project list var LS_ACTIVE = 'wp_active_project'; // active project id var LS_ACTIVE_OBJ = 'wp_active_project_obj'; function uid() { return 'proj_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6); } function esc(v) { return v == null ? '' : String(v).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); } function readLocal() { try { return JSON.parse(localStorage.getItem(LS_PROJECTS) || '[]') || []; } catch (e) { return []; } } function writeLocal(list) { try { localStorage.setItem(LS_PROJECTS, JSON.stringify(list)); } catch (e) {} } function cacheUpsert(p) { var list = readLocal(); var ix = list.findIndex(function (x) { return x.id === p.id; }); if (ix >= 0) list[ix] = p; else list.unshift(p); writeLocal(list); } function cacheRemove(id) { writeLocal(readLocal().filter(function (x) { return x.id !== id; })); } // Subscribers to the active project. Deliberately a plain array and a plain // callback — this is one value with a handful of readers, not a reason for a // state library. A throwing subscriber must not stop the others being told. var activeSubs = []; function notifyActive(p) { activeSubs.slice().forEach(function (fn) { try { fn(p); } catch (e) {} }); } var SAMPLE_PROJECT = { name: 'Micron FMCS Install (sample)', number: '26-67-008', client: 'Micron Technology, Inc.', division: 'Semiconductor', site: 'Boise, ID — Fab', sample: true }; var ProjectData = { SAMPLE: SAMPLE_PROJECT, esc: esc, // Returns the project list. Tries the API; falls back to the local mirror. list: function () { return fetch(API + '/projects', { headers: { 'Accept': 'application/json' } }) .then(function (r) { if (!r.ok) throw 0; return r.json(); }) .then(function (rows) { writeLocal(rows); return rows; }) .catch(function () { return readLocal(); }); }, // D7 / T9.8: the way back in, for project admins. The server filters the // answer by per-project role; everyone else simply receives []. listArchivedProjects: function () { return fetch(API + '/projects?archived=only', { headers: { 'Accept': 'application/json' } }) .then(function (r) { if (!r.ok) throw 0; return r.json(); }) .then(function (rows) { return (rows || []).filter(function (p) { return p.archived; }); }) .catch(function () { return []; }); }, get: function (id) { return fetch(API + '/projects/' + encodeURIComponent(id)) .then(function (r) { if (!r.ok) throw 0; return r.json(); }) .catch(function () { return readLocal().find(function (x) { return x.id === id; }) || null; }); }, // Create or update. Assigns an id when new. Mirrors to localStorage either way. save: function (p) { if (!p.id) p.id = uid(); return fetch(API + '/projects', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(p) }) .then(function (r) { if (!r.ok) throw 0; return r.json(); }) .then(function (saved) { cacheUpsert(saved); return saved; }) .catch(function () { cacheUpsert(p); return p; }); // offline / no API → local only }, // Deleting a project cascades its SOPs and work packages, and the server // allows it only for a Project Admin. Drop it from the local cache ONLY if // the server actually deleted it (or it was already gone) — removing it on a // 403 would hide a project that still exists for everyone else. remove: function (id) { return fetch(API + '/projects/' + encodeURIComponent(id), { method: 'DELETE' }) .then(function (r) { if (r.ok || r.status === 404) { cacheRemove(id); return true; } return r.json().catch(function () { return null; }).then(function (j) { throw new Error((j && j.detail) || ('Could not delete the project (HTTP ' + r.status + ').')); }); }); }, // Archiving a project lives in the admin console (html/admin.js), which doesn't // load this file — deliberately not mirrored here, so there's only one // implementation of it rather than two that can disagree. // ── active project context ──────────────────────────────────────────────── // setActive is the ONLY thing in the app that writes LS_ACTIVE / LS_ACTIVE_OBJ. // Everything that displays the active project reads it back through getActive() // or subscribes with onActiveChange(). Keep it that way: F1 was two readers with // their own copies, and the global one lost. getActiveId: function () { try { return localStorage.getItem(LS_ACTIVE) || ''; } catch (e) { return ''; } }, getActive: function () { try { return JSON.parse(localStorage.getItem(LS_ACTIVE_OBJ) || 'null'); } catch (e) { return null; } }, setActive: function (p) { try { if (p) { // Several callers know only the id — a deep link resolving before the // record arrives (field.js, wp-creation-app.js, work-package-suite-app.js // all call setActive({id}) first and the full record second). Writing that // stub verbatim erases the name, and the app bar then renders "(unnamed)". // Merging keeps the fuller record; fields the caller does supply still win. var prev = this.getActive(); if (prev && prev.id === p.id) p = Object.assign({}, prev, p); localStorage.setItem(LS_ACTIVE, p.id); localStorage.setItem(LS_ACTIVE_OBJ, JSON.stringify(p)); } else { localStorage.removeItem(LS_ACTIVE); localStorage.removeItem(LS_ACTIVE_OBJ); } } catch (e) {} notifyActive(p || null); // A caller that knew only the id leaves the store holding a stub, and every // reader then renders "(unnamed)" — field.js sets {id} on boot and resolves the // record into a variable of its own. Fill the stub in from the cached list, or // from the API when the cache has not loaded yet. The re-entry carries a name, // so it cannot loop; the id re-check stops a slow response from overwriting a // project the user has since switched to. if (p && p.id && !p.name) { var self = this; var cached = readLocal().filter(function (x) { return x.id === p.id; })[0]; if (cached && cached.name) { self.setActive(cached); return; } try { if (self.get) { self.get(p.id).then(function (full) { if (full && full.name && self.getActiveId() === full.id) self.setActive(full); }).catch(function () {}); } } catch (e) {} } }, // Subscribe to active-project changes. Returns an unsubscribe function. // The app bar uses this instead of holding its own copy of the value. onActiveChange: function (fn) { if (typeof fn !== 'function') return function () {}; activeSubs.push(fn); return function () { activeSubs = activeSubs.filter(function (f) { return f !== fn; }); }; }, // Per-project namespacing for the SOP/WP localStorage keys, e.g. // key('wp_iwp_v1') → 'wp_iwp_v1__proj_ab12' // Falls back to the bare key when no project is active. key: function (base) { var id = this.getActiveId(); return id ? base + '__' + id : base; } }; // ── Server sync for SOPs and Work Packages ───────────────────────────────── // SOPs and WPs are authoritative on the server (so every user of a project sees // the same data). To avoid rewriting the two apps, we keep their existing // localStorage keys as a per-browser CACHE: pullProject() hydrates those exact // keys from the API on page load, and the push* helpers write through to the // API whenever the apps save. The apps' own (synchronous) reads are unchanged. // (Original author: C-West8, "storing data in DB instead of client only"; // reintegrated on top of the BIM/per-package work.) function nsKey(base, id) { return id ? base + '__' + id : base; } function currentUser() { try { return (window.WP_USER && (window.WP_USER.username || window.WP_USER.full_name)) || ''; } catch (e) { return ''; } } // A saved Work Package is a flat object in the browser; the API splits it into // promoted columns + a `data` blob. We store the whole flat object in `data` // for perfect round-tripping (so BIM fields, kind, projectLinks, etc. all // survive), and mirror the few fields the API promotes to columns. function pkgToServer(p, projectId) { return { id: p.id, project_id: p.projectId || projectId || null, parent_id: p.instanceOf || null, number: p.number || '', subject: p.subject || '', type: p.type || '', status: p.status || 'Draft', assignee_id: p.assigneeId || null, created_by: p.createdBy || currentUser(), data: p }; } function serverToPkg(row) { var p = Object.assign({}, row.data || {}); // full flat object lives in data p.id = row.id; p.projectId = row.project_id || p.projectId || ''; if (row.number) p.number = row.number; if (row.subject != null) p.subject = row.subject; if (row.type != null) p.type = row.type; if (row.status) p.status = row.status; // honor server-side status changes if (row.parent_id) p.instanceOf = row.parent_id; p.archived = !!row.archived_at; p.assigneeId = row.assignee_id || ''; return p; } // Pull this project's SOP + WPs from the API into the localStorage keys the // apps read. Resolves even on failure (offline / no API) so boot continues. ProjectData.pullProject = function (projectId) { if (!projectId) return Promise.resolve(); var jobs = []; jobs.push( fetch(API + '/sops/latest?complete=true&project_id=' + encodeURIComponent(projectId), { headers: { 'Accept': 'application/json' } }) .then(function (r) { return r.ok ? r.json() : null; }) .then(function (sopRow) { if (sopRow && sopRow.data) { var d = sopRow.data; // { sop, state } as written by pushSOP if (d.sop) localStorage.setItem(nsKey('wp_suite_sop', projectId), JSON.stringify(d.sop)); if (d.state) localStorage.setItem(nsKey('wp_suite_state', projectId), JSON.stringify(d.state)); // BL-018: only a row in the shape pushSOP writes counts as complete. // Marking '1' for ANY row meant a malformed record opened the gate. if (d.sop && d.state) { localStorage.setItem(nsKey('wp_suite_sop_complete', projectId), '1'); } } }).catch(function () {}) ); jobs.push( fetch(API + '/wps?full=true&project_id=' + encodeURIComponent(projectId), { headers: { 'Accept': 'application/json' } }) .then(function (r) { return r.ok ? r.json() : null; }) .then(function (rows) { if (Array.isArray(rows)) { localStorage.setItem(nsKey('wp_iwp_v1', projectId), JSON.stringify(rows.map(serverToPkg))); } }).catch(function () {}) ); return Promise.all(jobs).then(function () {}); }; // ── Durable write-through outbox ─────────────────────────────────────────── // SOP/WP saves must survive a flaky network, a reload, or a crash — otherwise a // silently-failed POST leaves the browser and server divergent. Instead of a // fire-and-forget request, each mutation is appended to a localStorage-backed // queue and flushed to the API with retry + backoff. The API upserts by id and // DELETE is idempotent, so re-sending a queued op is always safe. The app's own // local cache still updates immediately, so rendering never waits on the network. var OUTBOX_KEY = 'wp_sync_outbox_v1'; var _flushTimer = null, _backoff = 0, _flushing = false; // D26. `_held` is set when the server answers 401: the session ended, so the // queue waits for a good sign-in. It is cleared ONLY by `wp-auth-ready` (a page // load with a good session check), never by the online event, the timer or tab // focus, because none of those prove the session is back. var _held = false; // D26. Changes the device could not store (localStorage full) stay here, in page // memory, and are still sent. They are lost if the page closes, so the badge says // they are not saved on this device. They are never dropped without a word. var _mem = []; var _deviceFull = false; function qRead() { try { return JSON.parse(localStorage.getItem(OUTBOX_KEY) || '[]') || []; } catch (e) { return []; } } // Returns true when the list is stored. A storage error used to be swallowed here, // so a full device lost the change and nobody knew (D26, fault 2). function qWrite(list) { try { localStorage.setItem(OUTBOX_KEY, JSON.stringify(list)); return true; } catch (e) { return false; } } // Stored ops plus any held only in memory, stored ones first (send order). function qAll() { var q = qRead(); if (!_mem.length) return q; var ids = {}; q.forEach(function (o) { ids[o.opId] = true; }); return q.concat(_mem.filter(function (o) { return !ids[o.opId]; })); } // Remove one op everywhere it can be held. function qDrop(opId) { _mem = _mem.filter(function (o) { return o.opId !== opId; }); qWrite(qRead().filter(function (o) { return o.opId !== opId; })); } function readQueueMode() { try { return window.WP_SESSION_MODE === 'readqueue'; } catch (e) { return false; } } function sameUser(a, b) { return String(a || '').toLowerCase() === String(b || '').toLowerCase(); } // Append an op, coalescing by (kind,key) so only the latest write per entity is // queued. A delete supersedes any pending upsert for the same id. Returns true // when the change is stored on this device, false when it is only in memory. function enqueue(op) { var supersedes = (op.kind === 'wp-del') ? function (o) { return o.key === op.key && (o.kind === 'wp' || o.kind === 'wp-del'); } : function (o) { return o.kind === op.kind && o.key === op.key; }; var q = qRead().filter(function (o) { return !supersedes(o); }); _mem = _mem.filter(function (o) { return !supersedes(o); }); op.opId = op.kind + ':' + op.key + ':' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6); op.tries = 0; op.owner = currentUser(); // D26: sent only when this person is signed in q.push(op); var stored = qWrite(q); if (stored) { // Room again: bring anything held in memory onto the device. if (_mem.length && qWrite(q.concat(_mem))) _mem = []; _deviceFull = _mem.length > 0; } else { _mem.push(op); _deviceFull = true; } notifySync(); scheduleFlush(0); return stored; } function opRequest(op) { if (op.kind === 'wp-del') { return fetch(API + '/wps/' + encodeURIComponent(op.key), { method: 'DELETE' }); } return fetch(API + (op.kind === 'sop' ? '/sops' : '/wps'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(op.body) }); } // Apply `fn` to the op with this id, wherever it is held (device or memory). function patchOp(opId, fn) { var q = qRead(), hit = false; for (var i = 0; i < q.length; i++) { if (q[i].opId === opId) { fn(q[i]); hit = true; break; } } if (hit) qWrite(q); for (var j = 0; j < _mem.length; j++) { if (_mem[j].opId === opId) { fn(_mem[j]); break; } } } function bumpTries(opId, err) { patchOp(opId, function (o) { o.tries = (o.tries || 0) + 1; o.lastErr = err; }); } // Permanently-failed op (a 4xx client error) — keep it for visibility but stop // retrying, so a rejected write can't loop forever. `err` is the server's own // explanation when it sent one; it is what the sync badge shows the user. function markDead(opId, err) { patchOp(opId, function (o) { o.dead = true; o.lastErr = err; }); } // True when this op is waiting for another person to sign in (D26). An op with no // owner (queued before the sign-in check finished) can be sent by anyone, which is // what every op did before owners existed. function foreignOp(o) { var me = currentUser(); return !!o.owner && !sameUser(o.owner, me); } function liveOps() { return qAll().filter(function (o) { return !o.dead; }); } function sendableOps() { return liveOps().filter(function (o) { return !foreignOp(o); }); } // Attempt every live op that belongs to the signed-in person; successes are // removed. A 401 HOLDS the queue (D26): the session ended, which says nothing // about the changes, so nothing is marked dead and no try is counted. A 403 or // other 4xx is marked dead (it will not succeed on retry); transient failures // (429/5xx/network) stay queued. function flush() { if (_flushing) return Promise.resolve(); // D27: opened offline after the session ended (read and queue). Changes are kept // and wait; nothing is sent until a page load gets a good answer from the server. if (_held || readQueueMode()) { notifySync(); return Promise.resolve(); } var q = sendableOps(); if (!q.length) { notifySync(); return Promise.resolve(); } _flushing = true; notifySync(); var chain = Promise.resolve(), anyFail = false, halted = false; q.forEach(function (op) { chain = chain.then(function () { if (halted) return; // a 401 stops the run; later ops keep their place return opRequest(op).then(function (r) { var status = r ? r.status : 0; var done = r && (r.ok || (op.kind === 'wp-del' && status === 404)); // 404 on delete = already gone if (done) { qDrop(op.opId); } else if (status === 401) { halted = true; _held = true; } else if (status >= 400 && status < 500 && status !== 429) { // Refused once, refused forever — so the only useful thing left is the // reason. A 409 here is the archived-project gate, whose detail tells // the user the project is read-only and how to get it unarchived; a // bare "HTTP 409" would leave them staring at a change that vanished. return r.json().catch(function () { return null; }).then(function (j) { var detail = (j && typeof j.detail === 'string' && j.detail) || ''; var why = status === 403 ? 'You no longer have access to this project.' + (detail ? ' (' + detail + ')' : '') : (detail || ('HTTP ' + status)); markDead(op.opId, why); }); } else { anyFail = true; bumpTries(op.opId, 'HTTP ' + status); } }).catch(function (e) { anyFail = true; bumpTries(op.opId, String(e)); }); }); }); return chain.then(function () { _flushing = false; notifySync(); if (_held) return; // wait for wp-auth-ready; no timer retries a dead session if (sendableOps().length) { _backoff = anyFail ? Math.min((_backoff || 5000) * 2, 60000) : 0; scheduleFlush(_backoff || 15000); } else { _backoff = 0; } }); } function scheduleFlush(delay) { if (_flushTimer) return; // one pending flush at a time _flushTimer = setTimeout(function () { _flushTimer = null; flush(); }, delay || 0); } // ── sync status (drives the indicator + any listeners) ────────────────────── // `failed` stays the total not-getting-through count (what listeners already // read); `dead` splits out the ops the server has permanently refused, with the // first reason it gave, because those two states need different words. // D26 adds: `held` (the session ended; the queue waits for a sign-in), `others` // and `otherOwner` (changes that belong to someone else, waiting for them), // `deviceFull` and `unsaved` (changes that exist only in page memory). function syncCounts() { var q = qAll(), pending = 0, failed = 0, dead = 0, reason = '', others = 0, otherOwner = ''; for (var i = 0; i < q.length; i++) { if (q[i].dead) { dead++; if (!reason && q[i].lastErr) reason = String(q[i].lastErr); } else if (foreignOp(q[i])) { others++; if (!otherOwner) otherOwner = String(q[i].owner); } else if ((q[i].tries || 0) >= 3) failed++; else pending++; } return { pending: pending, failed: failed + dead, dead: dead, reason: reason, syncing: _flushing, held: _held, others: others, otherOwner: otherOwner, deviceFull: _deviceFull, unsaved: _mem.length }; } ProjectData.syncStatus = syncCounts; function notifySync() { var c = syncCounts(); try { document.dispatchEvent(new CustomEvent('wp-sync-changed', { detail: c })); } catch (e) {} renderSyncBadge(c); } // The sync badge (D26, BL-061). It reports the OUTBOX: whether saved records have // reached the project. This was gated on being the top-level window so it was not // drawn twice (the suite page and the embedded creator); B7/T7.1 dissolved that // frame, so there is one document and one badge. The 'storage' listener below // stays: it is what keeps two TABS in step, which is a different thing. var _badgeHideTimer = null, _badgePlaceTimer = null, _hadWork = false; // BL-011 (fixed at T9.9): the badge used to mount on the FIRST SYNC EVENT, // which is async, so the three fixed overlays on the SOP page landed in a // different DOM order run to run and every index-keyed comparison saw // phantom diffs. Mounting the (hidden) holder at DOMContentLoaded puts the // three in script order, deterministically. document.addEventListener('DOMContentLoaded', function () { renderSyncBadge(null); }); // BL-061: the console pages (Admin, User Directory) never queue project work, and // the badge used to sit over their bottom-right buttons. They opt out with // data-wp-no-sync-badge on
. function badgeExempt() { return !!(document.body && document.body.hasAttribute('data-wp-no-sync-badge')); } // Discard the changes the project refused. The person has read the reason and // chose to dismiss it; nothing else ever removes a queued change by itself. function dismissRejected() { _mem = _mem.filter(function (o) { return !o.dead; }); qWrite(qRead().filter(function (o) { return !o.dead; })); notifySync(); } function signInUrl() { return 'login.html?next=' + encodeURIComponent(location.pathname + location.search); } // One place decides what the badge says. B5: every string names the PROJECT, so it // cannot be read as the draft indicator (WPAutosave.mountIndicator), which speaks // for the form. tone is one of neutral, ok, warn, error. function badgeModel(c) { var n; if (c.deviceFull) { n = c.unsaved; return { tone: 'error', text: '✕ ' + n + ' change' + (n === 1 ? ' is' : 's are') + ' not saved on this device. Keep this page open until it is sent to the project.' }; } if (readQueueMode()) { return { tone: 'warn', text: 'Working offline. Sign in again when you have a signal to send your changes to the project.', signIn: true }; } if (c.held) { return { tone: 'warn', text: '⚠ Sign in again to send your changes to the project. They are kept on this device.', signIn: true }; } if (c.dead) { return { tone: 'error', text: '✕ ' + c.dead + ' change' + (c.dead === 1 ? '' : 's') + ' rejected by the project. Not saved.', reason: c.reason, dismiss: true }; } if (c.failed) { return { tone: 'warn', text: '⚠ ' + c.failed + ' change' + (c.failed === 1 ? '' : 's') + ' not yet sent to the project. Retrying.' }; } if (c.pending) { return { tone: 'neutral', text: '↻ Sending ' + c.pending + ' change' + (c.pending === 1 ? '' : 's') + ' to the project…' }; } if (c.others) { return { tone: 'warn', text: '⚠ ' + c.others + ' change' + (c.others === 1 ? ' belongs' : 's belong') + ' to ' + c.otherOwner + '. ' + (c.others === 1 ? 'It goes' : 'They go') + ' to the project when ' + c.otherOwner + ' signs in.' }; } // Nothing to report. "Everything sent" follows real work only: on a page that // never queued anything it is noise that sits over the controls (BL-061). if (!_hadWork) return null; return { tone: 'ok', text: '✓ Everything sent to the project', autoHide: true }; } var TONES = { neutral: ['var(--cds-text-secondary)', 'var(--cds-border-subtle)', 'var(--cds-layer)'], ok: ['var(--wp-status-success-text)', 'var(--wp-status-success-border-a)', 'var(--wp-status-success-bg)'], warn: ['var(--wp-status-warning-text)', 'var(--cds-support-warning)', 'var(--wp-status-warning-bg)'], error: ['var(--wp-status-error-text)', 'var(--wp-status-error-border-a)', 'var(--wp-status-error-bg)'] }; function ensureBadgeStyle() { if (document.getElementById('wp-sync-badge-style')) return; var st = document.createElement('style'); st.id = 'wp-sync-badge-style'; // Controls are real and