The badge words live in one function, badgeModel(). States: sending, retrying, held for sign-in, not saved on this device, rejected (with the reason), read and queue, another person's changes, and all sent. Every state names the project. Sign in is a real link to login.html?next=. Dismiss is a real button and removes only the changes the project refused. Both are 44px or more with a focus ring. BL-061: the console pages (Admin, User Directory) never show the badge. All sent shows only after real work. The badge picks a free spot on the screen. One very dense screen case is left and logged as BL-072. tests/sync_badge_check.py (87 checks). autosave_check reads the new badge words.
726 lines
37 KiB
JavaScript
726 lines
37 KiB
JavaScript
/* 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, '"').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 <body>.
|
|
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 <a> and <button> elements: reachable by keyboard and touch,
|
|
// at least 44px high, with a focus ring from the shared focus token.
|
|
st.textContent =
|
|
'#wp-sync-badge{max-width:min(420px,calc(100vw - 24px));box-sizing:border-box}' +
|
|
'@media (max-width:480px){#wp-sync-badge{max-width:min(300px,calc(100vw - 24px))}}' +
|
|
'#wp-sync-badge .wp-sb-msg{display:flex;flex-direction:column;gap:2px;min-width:0}' +
|
|
'#wp-sync-badge .wp-sb-reason{font-weight:400}' +
|
|
'#wp-sync-badge .wp-sb-ctl{display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box;' +
|
|
'min-width:44px;min-height:44px;padding:0 10px;margin:-6px -12px -6px -4px;border:0;background:transparent;color:inherit;' +
|
|
'font-family:inherit;font-weight:600;font-size:12px;line-height:1.3;text-decoration:underline;cursor:pointer}' +
|
|
'#wp-sync-badge .wp-sb-ctl:focus-visible{outline:2px solid var(--cds-focus);outline-offset:-2px}';
|
|
(document.head || document.documentElement).appendChild(st);
|
|
}
|
|
|
|
// BL-061: keep the badge clear of page controls. Measure every visible control,
|
|
// then put the badge in the first free spot: the four corners first, then any gap
|
|
// on the screen that is big enough, scanning from the bottom up. Page headers and
|
|
// bottom bars fill the width at 390px, so fixed corners alone cannot clear them.
|
|
// If no spot is free, take the one that covers the fewest controls.
|
|
var CONTROLS = 'a[href],button,input,select,textarea,summary,[role="button"],[tabindex]:not([tabindex="-1"])';
|
|
function controlRects(el) {
|
|
var out = [], list = document.querySelectorAll(CONTROLS);
|
|
for (var i = 0; i < list.length; i++) {
|
|
var o = list[i];
|
|
if (o === el || el.contains(o)) continue;
|
|
var b = o.getBoundingClientRect();
|
|
if (!b.width || !b.height || !o.getClientRects().length) continue;
|
|
var cs = window.getComputedStyle(o);
|
|
if (cs.visibility === 'hidden' || cs.display === 'none') continue;
|
|
out.push(b);
|
|
}
|
|
return out;
|
|
}
|
|
function hitCount(rects, x, y, w, h) {
|
|
var n = 0;
|
|
for (var i = 0; i < rects.length; i++) {
|
|
var b = rects[i];
|
|
if (b.left < x + w && b.right > x && b.top < y + h && b.bottom > y) n++;
|
|
}
|
|
return n;
|
|
}
|
|
function placeBadge(el) {
|
|
if (el.style.display === 'none') return;
|
|
var vw = document.documentElement.clientWidth, vh = window.innerHeight;
|
|
// Measure at the left edge, where the box has all the room it will ever have,
|
|
// then pin that width: a box measured near the right edge wraps and grows.
|
|
el.style.width = ''; el.style.right = 'auto'; el.style.bottom = 'auto';
|
|
el.style.left = '0px'; el.style.top = '0px';
|
|
var r = el.getBoundingClientRect(), w = Math.ceil(r.width), h = Math.ceil(r.height), m = 12;
|
|
el.style.width = w + 'px';
|
|
var rects = controlRects(el);
|
|
var spots = [
|
|
[vw - w - m, vh - h - m], [m, vh - h - m], [vw - w - m, m], [m, m]
|
|
];
|
|
// Then every gap, bottom to top, right to left, in 8px steps.
|
|
for (var y = vh - h - m; y >= m; y -= 8) {
|
|
for (var x = vw - w - m; x >= m; x -= 8) spots.push([x, y]);
|
|
}
|
|
var best = spots[0], bestN = Infinity;
|
|
for (var i = 0; i < spots.length; i++) {
|
|
var n = hitCount(rects, spots[i][0], spots[i][1], w, h);
|
|
if (n < bestN) { bestN = n; best = spots[i]; }
|
|
if (n === 0) break;
|
|
}
|
|
el.style.right = 'auto'; el.style.bottom = 'auto';
|
|
el.style.left = Math.max(0, Math.round(best[0])) + 'px';
|
|
el.style.top = Math.max(0, Math.round(best[1])) + 'px';
|
|
}
|
|
|
|
function renderSyncBadge(c) {
|
|
if (!document.body) return;
|
|
var el = document.getElementById('wp-sync-badge');
|
|
if (!el) {
|
|
ensureBadgeStyle();
|
|
el = document.createElement('div');
|
|
el.id = 'wp-sync-badge';
|
|
// S10. Polite: this reports background syncing, and interrupting someone to
|
|
// say a queue drained is exactly the noise that gets aria-live turned off.
|
|
el.setAttribute('role', 'status');
|
|
el.style.cssText = 'position:fixed;right:12px;bottom:12px;z-index:9998;pointer-events:none;display:none;align-items:center;gap:12px;' +
|
|
'font:500 12px/1.3 "IBM Plex Sans",-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;' +
|
|
'padding:6px 12px;border:1px solid var(--cds-border-subtle);background:var(--cds-layer);color:var(--cds-text-secondary);box-shadow:0 1px 4px rgba(0,0,0,.12);transition:opacity .2s;';
|
|
document.body.appendChild(el);
|
|
window.addEventListener('resize', function () { placeBadge(el); });
|
|
}
|
|
if (!c) return; // the eager DOMContentLoaded mount: holder only, no state yet
|
|
if (_badgeHideTimer) { clearTimeout(_badgeHideTimer); _badgeHideTimer = null; }
|
|
if (_badgePlaceTimer) { clearInterval(_badgePlaceTimer); _badgePlaceTimer = null; }
|
|
if (c.pending || c.failed || c.held || c.others || c.deviceFull) _hadWork = true;
|
|
var m = badgeExempt() ? null : badgeModel(c);
|
|
if (!m) { el.style.display = 'none'; el.style.pointerEvents = 'none'; return; }
|
|
|
|
var t = TONES[m.tone] || TONES.neutral;
|
|
el.style.color = t[0]; el.style.borderColor = t[1]; el.style.background = t[2];
|
|
el.style.pointerEvents = (m.signIn || m.dismiss) ? 'auto' : 'none';
|
|
// Rebuild the contents. The container keeps role="status", so a change of text
|
|
// is announced; the controls inside it are ordinary focusable elements.
|
|
while (el.firstChild) el.removeChild(el.firstChild);
|
|
var msg = document.createElement('span');
|
|
msg.className = 'wp-sb-msg';
|
|
var head = document.createElement('span');
|
|
head.textContent = m.text;
|
|
msg.appendChild(head);
|
|
if (m.reason) {
|
|
var why = document.createElement('span');
|
|
why.className = 'wp-sb-reason';
|
|
why.textContent = String(m.reason);
|
|
msg.appendChild(why);
|
|
}
|
|
el.appendChild(msg);
|
|
if (m.signIn) {
|
|
var a = document.createElement('a');
|
|
a.className = 'wp-sb-ctl';
|
|
a.href = signInUrl();
|
|
a.textContent = 'Sign in';
|
|
el.appendChild(a);
|
|
}
|
|
if (m.dismiss) {
|
|
var d = document.createElement('button');
|
|
d.type = 'button';
|
|
d.className = 'wp-sb-ctl';
|
|
d.textContent = 'Dismiss';
|
|
d.addEventListener('click', dismissRejected);
|
|
el.appendChild(d);
|
|
}
|
|
el.style.display = 'inline-flex';
|
|
placeBadge(el);
|
|
if (m.autoHide) {
|
|
_hadWork = false; // the next "sent" needs new work
|
|
_badgeHideTimer = setTimeout(function () { if (el) el.style.display = 'none'; }, 1800);
|
|
} else {
|
|
// A state that stays: re-check the spot now and then, since the page under it changes.
|
|
_badgePlaceTimer = setInterval(function () { placeBadge(el); }, 2000);
|
|
}
|
|
}
|
|
|
|
// Flush triggers: on reconnect, on cross-frame queue changes, on tab focus, and
|
|
// a periodic backstop. Anything left from a previous session flushes on load.
|
|
try {
|
|
window.addEventListener('online', function () { _backoff = 0; scheduleFlush(0); });
|
|
window.addEventListener('storage', function (e) { if (e.key === OUTBOX_KEY) { notifySync(); scheduleFlush(0); } });
|
|
document.addEventListener('visibilitychange', function () { if (!document.hidden) scheduleFlush(0); });
|
|
setInterval(function () { if (sendableOps().length) scheduleFlush(0); }, 20000);
|
|
// D26: the one thing that releases a held queue. auth-guard fires this after a
|
|
// good /api/auth/me (or the offline cache), and the next flush finds out for
|
|
// itself whether the session is really good: a 401 holds the queue again.
|
|
document.addEventListener('wp-session-mode', function () { notifySync(); });
|
|
document.addEventListener('wp-auth-ready', function () { _held = false; _backoff = 0; notifySync(); scheduleFlush(0); });
|
|
} catch (e) {}
|
|
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { notifySync(); scheduleFlush(0); }); }
|
|
else { setTimeout(function () { notifySync(); scheduleFlush(0); }, 0); }
|
|
|
|
// ── public write API (now durable via the outbox) ───────────────────────────
|
|
// Write a completed SOP (plus the builder's raw state). Deterministic id per
|
|
// project so re-completing updates the same row.
|
|
ProjectData.pushSOP = function (projectId, sop, state) {
|
|
if (!projectId) return Promise.resolve(null);
|
|
return Promise.resolve(enqueue({
|
|
kind: 'sop', key: 'sop__' + projectId,
|
|
body: {
|
|
id: 'sop__' + projectId, project_id: projectId,
|
|
name: (sop && sop.project && sop.project.name) || 'SOP',
|
|
number: (sop && sop.project && sop.project.number) || '',
|
|
complete: true, created_by: currentUser(), data: { sop: sop, state: state }
|
|
}
|
|
}));
|
|
};
|
|
|
|
// Upsert a single Work Package. The local cache stays the source of truth for
|
|
// immediate rendering; the outbox guarantees the write reaches the server.
|
|
ProjectData.pushWP = function (p, projectId) {
|
|
if (!p || !p.id) return Promise.resolve(null);
|
|
// D26: resolves false when the device could not store the change (it is still
|
|
// sent from memory, but it is lost if the page closes first).
|
|
return Promise.resolve(enqueue({ kind: 'wp', key: p.id, body: pkgToServer(p, projectId) }));
|
|
};
|
|
|
|
ProjectData.removeWP = function (id) {
|
|
if (!id) return Promise.resolve();
|
|
return Promise.resolve(enqueue({ kind: 'wp-del', key: id }));
|
|
};
|
|
|
|
// Force a flush now and resolve when the queue drains (or a round-trip is done).
|
|
ProjectData.flushSync = function () { _backoff = 0; return flush(); };
|
|
|
|
// Archive / unarchive a Work Package (hide from active lists without deleting).
|
|
// Direct request (not the outbox) — it's a deliberate, low-frequency action and
|
|
// the caller updates the view on the returned result.
|
|
ProjectData.archiveWP = function (id, archived) {
|
|
if (!id) return Promise.resolve(null);
|
|
return fetch(API + '/wps/' + encodeURIComponent(id) + '/archive', {
|
|
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ archived: archived !== false })
|
|
}).then(function (r) { return r.ok ? r.json() : null; }).catch(function () { return null; });
|
|
};
|
|
|
|
// Fetch this project's ARCHIVED packages (full docs) for the dashboard's
|
|
// "show archived" view. Returns app-shaped package objects (p.archived === true).
|
|
ProjectData.listArchived = function (projectId) {
|
|
if (!projectId) return Promise.resolve([]);
|
|
return fetch(API + '/wps?full=true&archived=only&project_id=' + encodeURIComponent(projectId), { headers: { 'Accept': 'application/json' } })
|
|
.then(function (r) { return r.ok ? r.json() : []; })
|
|
.then(function (rows) { return Array.isArray(rows) ? rows.map(serverToPkg) : []; })
|
|
.catch(function () { return []; });
|
|
};
|
|
|
|
// One-time discard of pre-multi-project (un-namespaced) SOP/WP data so stale
|
|
// global state can't leak across projects. (User chose: discard, don't migrate.)
|
|
try {
|
|
if (!localStorage.getItem('wp_ns_migrated_v1')) {
|
|
['wp_suite_sop', 'wp_suite_state', 'wp_suite_sop_complete', 'wp_iwp_v1'].forEach(function (k) {
|
|
try { localStorage.removeItem(k); } catch (e) {}
|
|
});
|
|
localStorage.setItem('wp_ns_migrated_v1', '1');
|
|
}
|
|
} catch (e) {}
|
|
|
|
// A second tab switching project leaves this one showing a project the user is no
|
|
// longer on. The storage event fires only in OTHER tabs, which is exactly the case
|
|
// setActive's own notification cannot cover.
|
|
try {
|
|
global.addEventListener('storage', function (e) {
|
|
if (e.key === LS_ACTIVE_OBJ || e.key === LS_ACTIVE) notifyActive(ProjectData.getActive());
|
|
});
|
|
} catch (e) {}
|
|
|
|
global.ProjectData = ProjectData;
|
|
})(window);
|