T5.5 - CR-006: section toggles, and X4 resolved rather than deferred

X4 first, because the brief asks for it explicitly.

IMPLEMENTATION.md sequences CR-006 after B7 on the grounds that the toggles must
suppress sections inside the creator, which is an iframe child until T7.1. The
wave file puts it in wave 5 anyway, and its last done-when is written to
accommodate exactly that: "toggle state propagates into the creator, OR the PR
documents exactly where it does not and why".

It propagates. Both ways, by two separate paths, because they fail differently:

  ON THE CREATOR'S OWN BOOT the flags ride on the SOP, which the creator already
  reads - ProjectData.pullProject hydrates it from the server. Nothing crosses
  the frame boundary at all, so this path is unaffected by B7 either way. It
  covers a reload, a fresh tab, the standalone creator page, and a colleague
  opening the project on another machine.

  WHILE THE FRAME IS OPEN the wizard hands the change straight across
  (pushSectionsToCreator -> cw.applySopSections), the same shape T5.3 used for
  the dashboard filter. Without it, flipping a toggle would appear to do nothing
  until a reload.

T7.1 removes the second path, not the first. That is the whole of the X4
exposure and it is one function, commented as such. Building CR-006 after B7
would not have made the SOP-borne path any different; it would only have saved
writing the hand-off.

What it does

  Ten sections, one shared list (html/wp-sections.js) read by the wizard, the
  creator's form and the creator's rendered document. Three surfaces meant three
  chances to drift, which is how "Assets is off, except in the export" happens.

  Off means NOT RENDERED - form, detail view and PDF export. It never means
  deleted. renderPackage() was rebuilt from one long string into a list of
  (section, html) blocks so a suppressed section leaves no empty heading and the
  survivors renumber 1.0, 2.0, 3.0 instead of leaving a hole. The print window
  reuses that same HTML, so the export needed no separate change.

  Absent means ON. A SOP saved before today mentions no sections, and reading
  that as "all off" would blank every project in the estate the moment this
  shipped. WPSections.normalize is the one place that decision lives.

  html/wp-sections.js               new - the shared list, defaults, normalize
  html/work-package-suite.html      step 12, a 12th rail button
  html/work-package-suite-app.js    the toggles, state.sections, the hand-off
  html/work-package-suite-styles.css the toggle rows
  html/wp-creation-index.html       stable ids on the five unnamed cards
  html/wp-creation-app.js           WP_SECTION_NODES, applySopSections,
                                    renderPackage rebuilt as blocks
  tests/sections_check.py           new - 53 checks

Done when
  [x] all 10 sections are toggleable - each one driven off and back on
  [x] a section toggled off is absent from the form, the detail view and the
      PDF export - checked by content marker, not by heading, so "the section
      is gone" and "the section was empty" cannot be confused
  [x] toggling off then on restores prior data with no loss - and the sharper
      version: a package EDITED while Assets is off still carries its assets
      through collectPackage(), which is what Save uses
  [x] new SOPs default to all sections on
  [x] toggle state propagates into the creator - both paths, separately

Two things worth arguing with

  General Information is toggleable, because CR-006 enumerates it. Turning it
  off leaves nothing to identify a package by. The row says so in its own note
  rather than being quietly excluded from the list.

  Location has no card of its own - it is a field inside General Information's
  grid, and its toggle governs that one row. CR-004 gives it structured
  building/floor/sector fields in wave 6, at which point one line of
  WP_SECTION_NODES changes. Written down because "the toggle does nothing" and
  "the toggle governs one row" look identical from outside.

  Approvals & Sign-offs is NOT toggleable and is not one of the ten. A package
  nobody signed is not a shorter package.

Verified one at a time
  sections_check  53/53  new
  stepper_check   70/70  (STEP_COUNT 11 -> 12)
  locations_check 58/58  (its "step 11 is last" check now asserts the thing that
                          is actually invariant - the wizard's navigation follows)
  browser_check   71/71
  a11y            22/22
  url_state       23/23
  autosave        34/34
  aggregates      16/16
  pipeline        43/43
  launcher        58/58
  f_items         F1-F5 FIXED, F6 REPRODUCES (T7.2)

No colour literal added: still 0 across all page sheets and inline blocks. Each
toggle says its state three ways - the checkbox, the words "In use" / "Not used",
and the rule down its left edge (C1).

Question for the PR, per CLAUDE.md: the toggles are SOP-wide, so a project
cannot use Kitting on install packages and not on BIM ones. BL-000b already
records the field-level version of this question; the per-WP-type version is the
same shape and is not recorded anywhere yet.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-08-16 11:25:05 -05:00
parent 2081c1ad3c
commit ae30c58337
10 changed files with 882 additions and 49 deletions

View File

@@ -21,14 +21,6 @@ roughly 11,900 lines" — the line count is right, the other two are not. See D1
| `html/login.html` | login | 163 | `theme-light.css` | `login.js` | neither |
| `html/index.html` | launcher | 703 | `theme-light.css`, `wp-chrome.css` | `auth-guard`, `wp-format`, `feedback-config`, `project-data`, `help`, *(inline 418700)*, `wp-chrome` | neither |
| `html/work-package-suite.html` | SOP wizard | 437 | `theme-light.css`, `wp-chrome.css`, `work-package-suite-styles.css` | `auth-guard`, `wp-format`, `feedback-config`, `project-data`, `help`, `work-package-suite-app`, `wp-chrome` | **hosts** |
> **The SOP wizard has 11 steps, not 10, since `T5.4`.** `CR-005`'s location list was
> **appended** as step 11 rather than inserted beside Project, where it belongs by
> subject: renumbering 210 would touch every `sop-step-N` id, every `collectStepData`
> case, every gate key and the analytics history, for an ordering change. The count
> lives in one place — `LAST_STEP` in `work-package-suite-app.js` — and reordering is
> cheap once nothing depends on the numbers. `tests/stepper_check.py` names it
> `STEP_COUNT` for the same reason.
| `html/wp-creation-index.html` | creator | 401 | `theme-light.css`, `wp-creation-styles.css` | `auth-guard`, `wp-format`, `feedback-config`, `project-data`, `help`, `wp-creation-app` | **child** |
| `html/admin.html` | admin | 219 | `theme-light.css`, `wp-chrome.css`, `console.css`, `wp-sidenav.css` | `auth-guard`, `wp-format`, `console-util`, `admin`, `wp-chrome`, `wp-sidenav` | neither |
| `html/users.html` | directory/users | 106 | `theme-light.css`, `wp-chrome.css`, `console.css`, `wp-sidenav.css` | `auth-guard`, `wp-format`, `console-util`, `users`, `wp-chrome`, `wp-sidenav` | neither |
@@ -38,6 +30,18 @@ No script anywhere in `html/` uses `defer`, `async`, or `type="module"`. Every o
render-blocking classic script. `auth-guard.js` and `wp-format.js` load in `<head>`; the rest
load at the end of `<body>`.
Wave 5 added two `<head>` scripts, both shared: `wp-sections.js` (the `CR-006` section list,
read by the wizard *and* the creator, so the two cannot disagree about what "Assets is off"
means) joins `wp-url.js` and `wp-autosave.js`.
> **The SOP wizard has 12 steps, not 10, since wave 5.** `T5.4` appended Locations (11) and
> `T5.5` appended Sections (12). Both were **appended** rather than inserted where they
> belong by subject: renumbering 210 would touch every `sop-step-N` id, every
> `collectStepData` case, every gate key and the analytics history, for an ordering change.
> The count lives in one place — `LAST_STEP` in `work-package-suite-app.js` — and reordering
> is cheap once nothing depends on the numbers. `tests/stepper_check.py` names it
> `STEP_COUNT` for the same reason.
### The iframe boundary (matters for `B7` / `T7.1`)
`work-package-suite.html:383` declares `<iframe id="wp-frame">` with **no `src`**.
@@ -235,6 +239,7 @@ python tests/stepper_check.py # A4/S9 — ten real buttons, keyboard opera
python tests/launcher_check.py # B3 — can a brand-new account get started? 58 checks
python tests/pipeline_check.py # B4 surface — server counts, shareable links 43 checks
python tests/locations_check.py # CR-005 — codes not labels, nothing deleted 58 checks
python tests/sections_check.py # CR-006 — off means hidden, never deleted 53 checks
```
`pipeline_check.py` reads the dashboard's state out of the **iframe's DOM**, not its

View File

@@ -36,6 +36,11 @@ let state = {
signoffRoles: [{role:'Superintendent',name:''},{role:'Foreman',name:''}],
wpTypes: [],
governance: {woformat:'', wosize:'', issuance:[], disciplines:['Mechanical','Electrical','Tech'], discMode:'choice', instanceSuffix:'letter', sizeHoursMax:''},
// CR-006: which work package sections this project uses. Present from the start
// rather than filled in lazily, because sopIsDirty() fingerprints this object —
// adding a key on first read would make merely LOOKING at step 12 count as an
// unsaved change and fire T4.3's guard on the way out.
sections: (typeof WPSections !== 'undefined') ? WPSections.defaults() : {},
quality: {qcreq:'', photo:'', hold:''},
platforms: {tracking:'CxAlloy', commissioning:'CxAlloy', trackingUrl:'', commissioningUrl:''},
sequence: [],
@@ -458,6 +463,11 @@ function restoreSavedSOP(){
state = savedState;
sop = savedSop;
sopComplete = true;
// A SOP saved before CR-006 mentions no sections, and "says nothing" has to
// mean every section is on — the alternative would switch them all off for
// every project in the estate. Normalised HERE, before the dirty fingerprint
// is taken, so filling the gap does not read as an edit.
if(typeof WPSections !== 'undefined') state.sections = WPSections.normalize(state.sections);
// A SOP saved before the team was account-backed has no teamIds; default them
// so the pickers render (the stored names show as "(no account)" until linked).
if(!state.teamIds) state.teamIds = {pm:'', apm:'', cm:'', qm:''};
@@ -1501,6 +1511,93 @@ document.addEventListener('DOMContentLoaded', function(){
}
});
// ── STEP 12: WORK PACKAGE SECTIONS (CR-006) ───────────────────────────────────
// Which sections of a work package this project uses. The list itself lives in
// wp-sections.js, shared with the creator so the two cannot disagree about what
// "Assets is off" means.
//
// Toggling a section OFF never deletes anything — it stops the section rendering,
// in the form, in the package and in the export. Whatever was captured stays on
// the package and comes back intact. That is the difference between this and
// removing a field, and it is the reason CR-002 and CR-016 are expressed here.
function sopSections(){
if(typeof WPSections === 'undefined') return {};
state.sections = WPSections.normalize(state.sections);
return state.sections;
}
function renderSectionToggles(){
const host = document.getElementById('section-toggles');
if(!host || typeof WPSections === 'undefined') return;
const on = sopSections();
host.innerHTML = WPSections.LIST.map(sec => `
<label class="section-toggle${on[sec.id] ? '' : ' is-off'}" for="sec-${escAttr(sec.id)}">
<input type="checkbox" id="sec-${escAttr(sec.id)}" data-section="${escAttr(sec.id)}"
${on[sec.id] ? 'checked' : ''}>
<span class="section-toggle-body">
<span class="section-toggle-name">${escAttr(sec.label)}</span>
<span class="section-toggle-note">${escAttr(sec.note)}</span>
</span>
<span class="section-toggle-state">${on[sec.id] ? 'In use' : 'Not used'}</span>
</label>`).join('');
renderSectionSummary();
}
function renderSectionSummary(){
const el = document.getElementById('section-summary');
if(!el || typeof WPSections === 'undefined') return;
const off = WPSections.offList(sopSections());
el.textContent = off.length
? `${off.length} section${off.length===1?'':'s'} turned off: ${off.join(', ')}. `
+ 'Their data is retained and returns if they are turned back on.'
: 'Every section is in use. Turn off anything this project does not need.';
}
document.addEventListener('DOMContentLoaded', function(){
const host = document.getElementById('section-toggles');
if(!host) return;
host.addEventListener('change', function(e){
const t = e.target;
if(!t || !t.dataset || !t.dataset.section) return;
const on = sopSections();
on[t.dataset.section] = !!t.checked;
const wrap = t.closest('.section-toggle');
if(wrap){
wrap.classList.toggle('is-off', !t.checked);
const st = wrap.querySelector('.section-toggle-state');
if(st) st.textContent = t.checked ? 'In use' : 'Not used';
}
renderSectionSummary();
// The creator may already be loaded in the frame next door. Hand the change
// across rather than waiting for a reload — see pushSectionsToCreator.
pushSectionsToCreator();
});
});
// X4, the sequencing note this task had to resolve: the creator is an iframe
// child until T7.1, so the SOP it reads is the one hydrated into localStorage by
// ProjectData.pullProject at ITS boot. A toggle flipped in the wizard afterwards
// is invisible to an already-loaded frame.
//
// Two paths, therefore, and both are needed:
// • on the creator's own boot, applySOP() reads SOP.sections — this covers a
// reload, a fresh tab, and the standalone creator page;
// • while the frame is open, this hands the change straight across, the same
// way T5.3 hands the dashboard filter across.
// What T7.1 removes is the second path, not the first.
function pushSectionsToCreator(){
const frame = document.getElementById('wp-frame');
if(!frame) return false;
try {
const cw = frame.contentWindow;
if(cw && typeof cw.applySopSections === 'function'){
cw.applySopSections(sopSections());
return true;
}
} catch(e){ /* cross-document timing; the creator picks it up on its next boot */ }
return false;
}
// ── STEP GATES (A4 / S9) ──────────────────────────────────────────────────────
// validateStep() guarded steps 1, 5 and 6 with three hand-written conditions and
// three hand-written messages. The rail needs the same answer for every step, not
@@ -1526,8 +1623,8 @@ const STEP_GATES = {
const STEP_LABELS = {1:'Project', 2:'Team', 3:'Sign-offs', 4:'WP types', 5:'Governance',
6:'Quality', 7:'Platforms', 8:'Sequence', 9:'Constraints', 10:'Sources',
11:'Locations'};
const LAST_STEP = 11;
11:'Locations', 12:'Sections'};
const LAST_STEP = 12;
// Steps you have actually been on. A stepper's tick means "done", and a step you
// have never opened is not done however its defaults happen to read — step 6's QC
@@ -1771,6 +1868,7 @@ function updateStepUI(){
// actually opened rather than on every page load. locLoad() is idempotent and
// no-ops once it has the list.
if(currentStep === 11 && typeof locLoad === 'function') locLoad();
if(currentStep === 12 && typeof renderSectionToggles === 'function') renderSectionToggles();
// Update buttons
document.getElementById('sop-prev-btn').disabled = currentStep === 1;
@@ -1913,6 +2011,9 @@ function completeSOP(){
state.platforms.trackingUrl ? {label:'Tracking — '+state.platforms.tracking, system:state.platforms.tracking, url:state.platforms.trackingUrl} : null,
state.platforms.commissioningUrl ? {label:'Commissioning — '+state.platforms.commissioning, system:state.platforms.commissioning, url:state.platforms.commissioningUrl} : null
].filter(Boolean),
// CR-006. Rides on the SOP because the creator already reads the SOP: this is
// what makes the toggles reach a work package without a second channel.
sections: (typeof WPSections !== 'undefined') ? WPSections.normalize(state.sections) : {},
quality: {
qcReq: state.quality.qcreq,
photo: state.quality.photo,

View File

@@ -699,6 +699,41 @@ body.embed-full { overflow: hidden; }
}
.loc-addrow input { flex: 1 1 200px; min-width: 0; }
/* ══ SECTION TOGGLES — CR-006 (step 12) ═══════════════════════════════════════
Ten rows, each a real <label> wrapping a real checkbox, so the whole row is a
target and the browser gives the keyboard and screen-reader behaviour for
free. The state is said in words as well as by the tick (C1). */
#section-toggles { display: flex; flex-direction: column; margin-top: var(--wp-s3); }
.section-toggle {
display: flex;
align-items: flex-start;
gap: var(--wp-s3);
padding: var(--wp-s3);
border: 1px solid var(--border);
border-left: 3px solid var(--success);
background: var(--bg-card);
margin-bottom: -1px; /* collapse the hairline between rows */
cursor: pointer;
}
.section-toggle:hover { background: var(--bg); }
.section-toggle input { flex: none; width: 18px; height: 18px; margin-top: 2px; }
.section-toggle-body { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; gap: var(--wp-s1); }
.section-toggle-name { font-size: 14px; font-weight: 600; color: var(--text); }
.section-toggle-note { font-size: 12px; color: var(--text-light); }
.section-toggle-state {
flex: none;
font-size: 11px;
font-weight: 600;
color: var(--text-light);
white-space: nowrap;
}
/* Off is said three ways: the box is unticked, the row says "Not used", and the
rule down its left edge goes from green to grey. Colour is the one nobody has
to be able to see. */
.section-toggle.is-off { border-left-color: var(--border-strong); }
.section-toggle.is-off .section-toggle-name { color: var(--text-light); }
/* .field-error is declared once, in theme-light.css — the launcher's create form
and T5.8's step validation use the same component. */

View File

@@ -13,6 +13,9 @@
<script src="wp-url.js"></script>
<!-- Autosave, unsaved-work guard, draft recovery (S2). -->
<script src="wp-autosave.js"></script>
<!-- Which work package sections this project uses (CR-006). Shared with the
creator so the two cannot disagree about what "Assets is off" means. -->
<script src="wp-sections.js"></script>
<link rel="icon" href="favicon.ico" sizes="any">
<link rel="manifest" href="manifest.webmanifest">
<meta name="theme-color" content="#161616">
@@ -84,7 +87,7 @@
where-you-are and opens on demand. -->
<button type="button" class="step-rail-toggle" id="step-rail-toggle"
aria-expanded="false" aria-controls="step-rail-list">
<span class="step-rail-toggle-text">Step <span id="step-rail-pos">1</span> of <span id="step-rail-total">11</span> · <span id="step-rail-here">Project</span></span>
<span class="step-rail-toggle-text">Step <span id="step-rail-pos">1</span> of <span id="step-rail-total">12</span> · <span id="step-rail-here">Project</span></span>
<span class="step-rail-toggle-chev" aria-hidden="true"></span>
</button>
<ol class="step-rail-list" id="step-rail-list">
@@ -105,6 +108,7 @@
reorder once nothing depends on them; a renumbering buried in a
feature diff is not. -->
<li class="step-rail-item"><button type="button" class="step-btn" data-step="11"><span class="step-btn-marker" aria-hidden="true">11</span><span class="step-btn-body"><span class="step-btn-label">Locations</span><span class="step-btn-state"></span></span></button></li>
<li class="step-rail-item"><button type="button" class="step-btn" data-step="12"><span class="step-btn-marker" aria-hidden="true">12</span><span class="step-btn-body"><span class="step-btn-label">Sections</span><span class="step-btn-state"></span></span></button></li>
</ol>
<!-- Why a step you asked for did not open. role="alert" because a refused
navigation is an error and waiting for a pause to say so is too late
@@ -447,6 +451,22 @@
</div>
</div>
<!-- STEP 12: WORK PACKAGE SECTIONS (CR-006)
The structural fix behind most removal requests in the plan: rather
than deleting fields globally, each project turns on only the
sections it uses. CR-002 and CR-016 are expressed through these. -->
<div class="step" id="sop-step-12" style="display: none;">
<h2>12. Work Package Sections</h2>
<div class="notice">Turn off the parts of a work package this project does not
use. A section that is off does not appear in the creation form, in the work
package itself, or in the PDF export. <strong>Nothing is deleted.</strong>
Anything already captured stays on the package and comes back intact if the
section is turned on again — which is what makes this different from removing
a field.</div>
<div id="section-toggles"></div>
<p class="field-hint" id="section-summary" role="status"></p>
</div>
</div>
<!-- SOP NAVIGATION -->

View File

@@ -120,6 +120,9 @@ function applySOP(){
if(!pkgAssets.length){ pkgAssets=[{tag:'',desc:'',link:''}]; buildAssets(); }
if(!pkgWorkSteps.length){ pkgWorkSteps=['']; buildWorkSteps(); }
updateNumber(); updateReleaseBanner();
// CR-006. Last, after every builder has rendered its card — applying it earlier
// would be undone by whichever builder touched the same card afterwards.
applySopSections(SOP && SOP.sections);
}
// Per-package kind. A project whose SOP has bimEnabled produces both install (IWP)
// and BIM (EWP) packages; the kind selector tailors which fields, WP types, and
@@ -1178,22 +1181,40 @@ function savePackage(view){
document.getElementById('loadingOverlay').classList.add('active');
setTimeout(()=>{ document.getElementById('loadingOverlay').classList.remove('active'); if(view) renderPackage(pkg); }, 400);
}
// The package as a document — this is both the detail view and, via
// printPackage(), the PDF export: the print window reuses #pkg-doc's HTML, so a
// section suppressed here is suppressed in both. That is why CR-006 needed one
// change rather than two.
//
// Built as a LIST of (section id, html) blocks rather than one long string, so a
// section this project has turned off is dropped and what survives is numbered
// 1.0, 2.0, 3.0 — not 1.0, 3.0, 4.0 with a hole where Assets used to be.
let _lastRenderedPkg = null;
function renderPackage(pkg){
_lastRenderedPkg = pkg;
const r = pkg.constraints ? {open:pkg.constraints.filter(c=>c.status==='open').length,total:pkg.constraints.length} : {open:0,total:0};
const readyTxt = pkg.status==='Issue' ? 'ON HOLD' : (r.open===0?'RELEASE-READY':(r.open+' OPEN CONSTRAINTS'));
const kindLbl = pkg.kind==='ewp' ? 'BIM (EWP)' : 'IWP';
let h=`<h1>${esc(pkg.number||'(no number)')} — Work Package</h1>
let head=`<h1>${esc(pkg.number||'(no number)')} — Work Package</h1>
<div class="doc-subtitle">${esc(pkg.project)} · ${kindLbl} · TYPE: ${esc(pkg.type).toUpperCase()} · STATUS: ${esc(pkg.status).toUpperCase()} · ${readyTxt}</div>`;
const costDesc = (COST_CODES.find(c=>c.split('|')[0]===pkg.cost)||'').split('|')[1];
// Project system links travel with the WP; fall back to the live SOP for older packages.
const plinks = (pkg.projectLinks&&pkg.projectLinks.length) ? pkg.projectLinks : ((SOP&&SOP.projectLinks)||[]);
h+=`<h2>1.0 General Information</h2><table><tbody>
// Each entry is [section id, title, body]. `null` bodies are skipped, which is
// how a section that simply has no content behaves — different from a section
// this project does not use, which never reaches the list at all.
const blocks = [];
const add = (id, title, body) => { if(body != null && sectionOn(id)) blocks.push([title, body]); };
add('general', 'General Information', `<table><tbody>
<tr><th style="width:200px">WP Number</th><td>${cell(pkg.number)}</td></tr>
<tr><th>Subject</th><td>${cell(pkg.subject)}</td></tr>
<tr><th>Type</th><td>${cell(pkg.type)}</td></tr>
${pkg.disciplines&&pkg.disciplines.length?`<tr><th>Discipline(s)</th><td>${esc(pkg.disciplines.join(', '))}${pkg.split?' <span style="color:var(--accent);font-size:10px">[MASTER — split into instances]</span>':''}${pkg.instanceOf?` <span style="color:var(--accent);font-size:10px">[instance of ${esc(pkg.parentNumber||'')}]</span>`:''}</td></tr>`:''}
<tr><th>System / Facility Code / UPN</th><td>${cell(pkg.system)}</td></tr>
<tr><th>Location</th><td>${cell(pkg.location)}</td></tr>
${sectionOn('location')?`<tr><th>Location</th><td>${cell(pkg.location)}</td></tr>`:''}
<tr><th>Cost Code</th><td>${pkg.cost?esc(pkg.cost)+(costDesc?' — '+esc(costDesc):''):ns()}</td></tr>
<tr><th>Acumatica Task</th><td>${cell(pkg.wbs)}</td></tr>
<tr><th>Assignees</th><td>${cell(pkg.assignees)}</td></tr>
@@ -1204,9 +1225,20 @@ function renderPackage(pkg){
${plinks.length?`<tr><th>Project Systems</th><td>${plinks.map(l=>esc(l.label)+': '+linkify(l.url)).join('<br>')}</td></tr>`:''}
${pkg.bimlink?`<tr><th>Enabled by (BIM)</th><td>${/^https?:\/\//i.test(pkg.bimlink)?linkify(pkg.bimlink):cell(pkg.bimlink)}</td></tr>`:''}
${(pkg.lod||pkg.iff||pkg.modelArea||pkg.clash||pkg.scanLink)?`<tr><th>BIM / Model</th><td>${[pkg.modelArea?'Area: '+esc(pkg.modelArea):'', pkg.clash?'Coordination: '+esc(pkg.clash):'', pkg.iff?'IFF #: '+esc(pkg.iff):'', pkg.scanLink?'Scan: '+linkify(pkg.scanLink):'', pkg.lod?'LOD: '+esc(pkg.lod)+' (legacy)':''].filter(Boolean).join('<br>')}</td></tr>`:''}
</tbody></table>`;
if(pkg.assets&&pkg.assets.length){ h+=`<h2>2.0 Assets (controls.dev)</h2><table><thead><tr><th style="width:180px">Asset Tag / ID</th><th>Description</th><th>controls.dev Link</th></tr></thead><tbody>`;
pkg.assets.forEach(a=>h+=`<tr><td>${cell(a.tag)}</td><td>${cell(a.desc)}</td><td>${a.link?linkify(a.link):ns()}</td></tr>`); h+=`</tbody></table>`; }
</tbody></table>`);
// Location has no block of its own yet — it is a row inside General
// Information, suppressed above. CR-004 gives it structured fields in wave 6
// and this is where its own block will go. Recorded rather than left implicit,
// because "the toggle does nothing" and "the toggle governs one row" look the
// same from outside.
if(pkg.assets&&pkg.assets.length){
let t=`<table><thead><tr><th style="width:180px">Asset Tag / ID</th><th>Description</th><th>controls.dev Link</th></tr></thead><tbody>`;
pkg.assets.forEach(a=>t+=`<tr><td>${cell(a.tag)}</td><td>${cell(a.desc)}</td><td>${a.link?linkify(a.link):ns()}</td></tr>`);
add('assets', 'Assets (controls.dev)', t+`</tbody></table>`);
}
let scopeHtml;
if(pkg.scope && Object.keys(pkg.scope).length){ // per-discipline scope sections
scopeHtml = Object.keys(pkg.scope).map(d=>{
@@ -1219,7 +1251,7 @@ function renderPackage(pkg){
const stepsArr = pkg.workSteps && pkg.workSteps.length ? pkg.workSteps : (pkg.work?String(pkg.work).split('\n').filter(Boolean):[]);
scopeHtml = stepsArr.length ? '<ol style="margin:0;padding-left:18px">'+stepsArr.map(s=>`<li>${esc(s)}</li>`).join('')+'</ol>' : ns();
}
h+=`<h2>3.0 Scope & Work</h2><table><tbody>
add('scope', 'Scope & Work', `<table><tbody>
<tr><th style="width:200px">Description of Work</th><td>${scopeHtml}</td></tr>
<tr><th>Labor Est. Hrs.</th><td>${cell(pkg.hours)}</td></tr>
<tr><th>Predecessor packages</th><td>${
@@ -1229,42 +1261,60 @@ function renderPackage(pkg){
}</td></tr>
<tr><th>Sequence phase</th><td>${pkg.seq?esc(pkg.seq):ns()}</td></tr>
${pkg.gateOverride?`<tr><th>Released early</th><td><strong>Predecessor gate overridden.</strong><br>${esc(pkg.gateOverride.reason||'')}<br><span style="color:var(--text-dim)">${esc(pkg.gateOverride.by||'')} · ${esc(pkg.gateOverride.at?wpFormatDateTime(pkg.gateOverride.at):'')}</span></td></tr>`:''}
</tbody></table>`;
</tbody></table>`);
if(pkg.materials&&pkg.materials.length){ const showDisc=pkg.materials.some(m=>m.discipline);
h+=`<h2>4.0 Material List</h2><table><thead><tr><th style="width:80px">Qty</th><th style="width:80px">Unit</th><th>Description</th>${showDisc?'<th style="width:120px">Discipline</th>':''}</tr></thead><tbody>`;
pkg.materials.forEach(m=>h+=`<tr><td>${cell(m.qty)}</td><td>${cell(m.unit)}</td><td>${cell(m.desc)}</td>${showDisc?`<td>${cell(m.discipline)}</td>`:''}</tr>`); h+=`</tbody></table>`; }
if(pkg.attachments&&pkg.attachments.length){ h+=`<h2>5.0 Drawings & Attachments</h2><table><thead><tr><th>Document</th><th style="width:60px">Rev</th><th>Link / Note</th></tr></thead><tbody>`;
pkg.attachments.forEach(a=>h+=`<tr><td>${cell(a.doc)}</td><td>${cell(a.rev)}</td><td>${a.link?linkify(a.link):ns()}</td></tr>`); h+=`</tbody></table>`; }
h+=`<h2>6.0 Kitting & MIMO</h2><table><tbody>
let t=`<table><thead><tr><th style="width:80px">Qty</th><th style="width:80px">Unit</th><th>Description</th>${showDisc?'<th style="width:120px">Discipline</th>':''}</tr></thead><tbody>`;
pkg.materials.forEach(m=>t+=`<tr><td>${cell(m.qty)}</td><td>${cell(m.unit)}</td><td>${cell(m.desc)}</td>${showDisc?`<td>${cell(m.discipline)}</td>`:''}</tr>`);
add('materials', 'Material List', t+`</tbody></table>`); }
if(pkg.attachments&&pkg.attachments.length){
let t=`<table><thead><tr><th>Document</th><th style="width:60px">Rev</th><th>Link / Note</th></tr></thead><tbody>`;
pkg.attachments.forEach(a=>t+=`<tr><td>${cell(a.doc)}</td><td>${cell(a.rev)}</td><td>${a.link?linkify(a.link):ns()}</td></tr>`);
add('drawings', 'Drawings & Attachments', t+`</tbody></table>`); }
add('kitting', 'Kitting & MIMO', `<table><tbody>
<tr><th style="width:200px">Kitting Status</th><td>${cell(pkg.kitStatus)}</td></tr>
<tr><th>Warehouse Owner</th><td>${cell(pkg.kitOwner)}</td></tr>
<tr><th>Kitting Need Date</th><td>${cell(pkg.kitDate)}</td></tr>
<tr><th>MIMO Sch. Time / Location</th><td>${cell(pkg.mimoTime)} ${pkg.mimoLoc?'· '+esc(pkg.mimoLoc):''}</td></tr>
</tbody></table>`;
h+=`<h2>7.0 Constraints — Release Readiness</h2><table><thead><tr><th>Constraint</th><th style="width:90px">Status</th><th>Comment</th></tr></thead><tbody>`;
</tbody></table>`);
let ct=`<table><thead><tr><th>Constraint</th><th style="width:90px">Status</th><th>Comment</th></tr></thead><tbody>`;
(pkg.constraints||[]).forEach(c=>{ const lbl=c.status==='cleared'?'Cleared':c.status==='na'?'N/A':'Open'; const col=c.status==='cleared'?'var(--accent-green)':c.status==='na'?'var(--text-dim)':'var(--red)';
h+=`<tr><td>${esc(c.name)}</td><td style="color:${col};font-weight:700">${lbl}</td><td>${cell(c.comment)}</td></tr>`; });
h+=`</tbody></table>`;
h+=`<h2>8.0 Quality & Hold Points</h2><table><tbody>
ct+=`<tr><td>${esc(c.name)}</td><td style="color:${col};font-weight:700">${lbl}</td><td>${cell(c.comment)}</td></tr>`; });
add('constraints', 'Constraints — Release Readiness', ct+`</tbody></table>`);
add('qaqc', 'Quality & Hold Points', `<table><tbody>
<tr><th style="width:200px">QC</th><td>${cell(pkg.qc)}${pkg.overrides&&pkg.overrides.wp_qc?` <span style="color:var(--accent-amber)">(overridden: ${esc(pkg.overrides.wp_qc)})</span>`:(pkg.qcFromSOP?' <span style="color:var(--accent);font-size:10px">[from SOP]</span>':'')}</td></tr>
<tr><th>Photo Documentation</th><td>${cell(pkg.photo)}${pkg.overrides&&pkg.overrides.wp_photo?` <span style="color:var(--accent-amber)">(overridden: ${esc(pkg.overrides.wp_photo)})</span>`:(pkg.photoFromSOP?' <span style="color:var(--accent);font-size:10px">[from SOP]</span>':'')}</td></tr>
<tr><th>Witness / Hold Points</th><td>${cell(pkg.hold)}</td></tr>
</tbody></table>`;
</tbody></table>`);
if(pkg.holds&&pkg.holds.length){
h+=`<h2>8.5 Hold Log</h2><table><thead><tr><th style="width:150px">Logged</th><th style="width:200px">Constraint</th><th>Details</th><th style="width:120px">Support</th></tr></thead><tbody>`;
let t=`<table><thead><tr><th style="width:150px">Logged</th><th style="width:200px">Constraint</th><th>Details</th><th style="width:120px">Support</th></tr></thead><tbody>`;
pkg.holds.forEach(hd=>{ const when=hd.ts?wpFormatDateTime(hd.ts):''; const sup=[hd.doc?linkify(hd.doc):'', hd.photo?'<span style="color:var(--accent-green)">photo attached</span>':''].filter(Boolean).join('<br>')||ns();
h+=`<tr><td>${esc(when)}</td><td>${cell(hd.constraint)}</td><td>${cell(hd.details)}</td><td>${sup}</td></tr>`; });
h+=`</tbody></table>`;
t+=`<tr><td>${esc(when)}</td><td>${cell(hd.constraint)}</td><td>${cell(hd.details)}</td><td>${sup}</td></tr>`; });
// The hold LOG belongs to QA/QC — it is the record of the hold points that
// section defines, so it goes with it rather than surviving on its own.
add('qaqc', 'Hold Log', t+`</tbody></table>`);
}
h+=`<h2>9.0 Approvals & Sign-offs</h2><table><thead><tr><th>Role</th><th>Name</th><th style="width:120px">Date</th><th style="width:80px">Signed</th></tr></thead><tbody>`;
(pkg.signoffs||[]).forEach(s=>h+=`<tr><td>${esc(s.role)}</td><td>${cell(s.name)}</td><td>${cell(s.date)}</td><td>${s.signed?'✓':'—'}</td></tr>`);
h+=`</tbody></table>`;
if(pkg.actualHrs||pkg.installedQty||pkg.redlines||pkg.lessons){ h+=`<h2>10.0 Closeout</h2><table><tbody>
// Approvals are not one of CR-006's ten sections and are not toggleable: a
// package nobody signed is not a shorter package, it is an unapproved one.
let st=`<table><thead><tr><th>Role</th><th>Name</th><th style="width:120px">Date</th><th style="width:80px">Signed</th></tr></thead><tbody>`;
(pkg.signoffs||[]).forEach(s=>st+=`<tr><td>${esc(s.role)}</td><td>${cell(s.name)}</td><td>${cell(s.date)}</td><td>${s.signed?'✓':'—'}</td></tr>`);
blocks.push(['Approvals & Sign-offs', st+`</tbody></table>`]);
if(pkg.actualHrs||pkg.installedQty||pkg.redlines||pkg.lessons){
add('closeout', 'Closeout', `<table><tbody>
<tr><th style="width:200px">Actual Hrs.</th><td>${cell(pkg.actualHrs)}</td></tr>
<tr><th>Installed Quantity</th><td>${cell(pkg.installedQty)}</td></tr>
<tr><th>Redlines / As-Built</th><td>${cell(pkg.redlines)}</td></tr>
<tr><th>Lessons Learned</th><td>${cell(pkg.lessons)}</td></tr>
</tbody></table>`; }
</tbody></table>`); }
let h = head + blocks.map(([title, body], i) => `<h2>${i+1}.0 ${esc(title)}</h2>${body}`).join('');
h+=`<p style="margin-top:18px;color:var(--text-dim);font-size:11px">Pushed to: ${cell(pkg.track)}</p>`;
document.getElementById('pkg-doc').innerHTML=h; showOutput();
}
@@ -1325,7 +1375,9 @@ function buildSectionNav(){
const nav=document.getElementById('section-nav'); if(!nav) return;
const chips=[];
document.querySelectorAll('.main > .card').forEach((card,i)=>{
if(card.id==='saved-card' || card.style.display==='none') return;
// `hidden` is how CR-006 suppresses a section; the chip strip is a table of
// contents for the form, so it has to lose the same entries.
if(card.id==='saved-card' || card.style.display==='none' || card.hidden) return;
const h=card.querySelector('.section-title, .sub-heading'); if(!h) return;
const clone=h.cloneNode(true); clone.querySelectorAll('.help-tip').forEach(x=>x.remove());
const label=clone.textContent.trim().replace(/\s+/g,' '); if(!label) return;
@@ -1368,6 +1420,69 @@ function updateStickyStatus(){
else { el.className='sticky-status ss-notready'; el.textContent=`${r.open} of ${r.total} constraint${r.open===1?'':'s'} open`+(r.blocking.length?` · ${r.blocking.length} predecessor${r.blocking.length===1?'':'s'}`:''); }
}
// ── SECTION TOGGLES (CR-006 / T5.5) ──────────────────────────────────────────
// Which sections this project uses. The list is wp-sections.js, shared with the
// SOP wizard; this file owns the mapping from a section id to the DOM it governs
// and to the blocks renderPackage() emits.
//
// NOTHING HERE WRITES TO A PACKAGE. A section that is off is not rendered — in
// the form, in the package view or in the export. Everything captured while it
// was on stays on the package, and turning it back on shows it again. That is
// the whole of CR-006's contract, and the reason CR-002 and CR-016 are toggles.
// Location is a field inside General Information's grid today rather than a card
// of its own; CR-004 gives it structured fields in wave 6 and only this line
// changes then.
const WP_SECTION_NODES = {
general: ['#general-card'],
location: ['#location-card'],
scope: ['#scope-card'],
assets: ['#asset-card'],
materials: ['#material-card'],
kitting: ['#mimo-card'],
drawings: ['#drawings-card'],
constraints: ['#constraint-card'],
qaqc: ['#quality-card'],
closeout: ['#closeout-card'],
};
let wpSections = (typeof WPSections !== 'undefined') ? WPSections.defaults() : {};
function sectionOn(id){
if(typeof WPSections === 'undefined') return true;
return WPSections.isOn(wpSections, id);
}
/* Apply a section map to the form. Called from applySOP() on boot — which covers
a reload, a fresh tab and the standalone page — and from the SOP wizard next
door while the frame is already open (X4). Exposed on window deliberately: the
wizard is a different document and can only reach a global. */
function applySopSections(sections){
if(typeof WPSections === 'undefined') return wpSections;
wpSections = WPSections.normalize(sections);
Object.keys(WP_SECTION_NODES).forEach(id => {
const on = wpSections[id];
WP_SECTION_NODES[id].forEach(sel => {
document.querySelectorAll(sel).forEach(el => {
// `hidden` rather than display:none — several of these cards are shown
// and hidden by other code (showOutput, showDashboard, the BIM flag) with
// inline display, and two mechanisms fighting over one property is how a
// section comes back on its own.
el.hidden = !on;
el.dataset.sectionOff = on ? '' : '1';
});
});
});
// The section chips are a table of contents for the form, so they have to lose
// the same entries.
if(typeof buildSectionNav === 'function') buildSectionNav();
// A package already on screen is re-rendered, or the view keeps showing a
// section the form no longer has.
if(currentView === 'Package View' && _lastRenderedPkg) renderPackage(_lastRenderedPkg);
return wpSections;
}
window.applySopSections = applySopSections;
// ── SAVED PACKAGES ───────────────────────────────────────────────────────────
const STORE_KEY='wp_iwp_v1';
// Per-project namespaced key so each project keeps its own packages in the browser.

View File

@@ -13,6 +13,9 @@
<script src="wp-url.js"></script>
<!-- Autosave, unsaved-work guard, draft recovery (S2). -->
<script src="wp-autosave.js"></script>
<!-- Which sections this project uses (CR-006). The same file the SOP wizard
reads, so "Assets is off" means one thing in both. -->
<script src="wp-sections.js"></script>
<link rel="icon" href="favicon.ico" sizes="any">
<link rel="manifest" href="manifest.webmanifest">
<meta name="theme-color" content="#161616">
@@ -132,7 +135,9 @@
</div>
<!-- GENERAL INFORMATION -->
<div class="card">
<!-- CR-006 gives every toggleable section a stable id. The map lives in
wp-creation-app.js (WP_SECTION_NODES); the ids are what it addresses. -->
<div class="card" id="general-card">
<div class="section-header"><div class="section-title">General Information</div>
<div class="section-desc">Parameters in <span style="color:var(--accent)">blue</span> are inherited from the project SOP. Fill the rest for this package.</div></div>
<div class="field-grid">
@@ -156,7 +161,10 @@
<div class="field-grid">
<div class="field"><label>WP type <span class="req">*</span></label><select id="wp_type" onchange="onTypeChange()"></select><div class="field-hint sop-hint">from SOP types</div></div>
<div class="field"><label>System / facility code / UPN</label><input type="text" id="wp_system" placeholder="ties to controls.dev / COIN"></div>
<div class="field"><label>Location</label><input type="text" id="wp_location" placeholder="building / level / sector / room"></div>
<!-- Location is its own CR-006 section while still living inside General
Information's grid. CR-004 gives it structured building/floor/sector
fields of its own in wave 6; only this wrapper's contents change then. -->
<div class="field" id="location-card"><label>Location</label><input type="text" id="wp_location" placeholder="building / level / sector / room"></div>
<div class="field"><label>Cost code</label><select id="wp_cost"></select><div class="field-hint sop-hint">Acumatica cost codes</div></div>
<div class="field"><label>Acumatica task</label><input type="text" id="wp_wbs" placeholder="Acumatica task no."></div>
</div>
@@ -208,7 +216,7 @@
</div>
<!-- SCOPE & WORK -->
<div class="card">
<div class="card" id="scope-card">
<div class="sub-heading">Scope & Work<span class="help-tip" data-tip="Ordered steps the crew performs. With multiple disciplines selected, each gets its own scope section and status. Use Split by Discipline to break a large package into WP01A / WP01B / WP01C instances.">i</span></div>
<div id="flat-scope">
<div class="field"><label>Description of work (sequenced steps)</label>
@@ -243,7 +251,7 @@
</div>
<!-- DRAWINGS / ATTACHMENTS -->
<div class="card">
<div class="card" id="drawings-card">
<div class="sub-heading">Drawings & Attachments</div>
<div id="sop-ref-links" class="sop-ref-links"></div>
<div class="table-wrap"><table><thead><tr><th>Document / Drawing</th><th style="width:90px">Rev</th><th>Link / Note</th><th style="width:44px"></th></tr></thead><tbody id="attach-body"></tbody></table></div>
@@ -281,7 +289,7 @@
</div>
<!-- QUALITY & HOLD POINTS -->
<div class="card">
<div class="card" id="quality-card">
<div class="sub-heading">Quality, Inspection & Hold Points</div>
<div class="field-grid">
<div class="field"><label>QC required</label><input type="text" id="wp_qc" placeholder="from SOP" readonly>

94
html/wp-sections.js Normal file
View File

@@ -0,0 +1,94 @@
/* Work package section toggles — CR-006 / T5.5.
---------------------------------------------------------------------------
The structural fix behind most of the removal requests in the plan. Rather
than deleting fields globally, each project turns on only the sections it
uses: it is what lets Micron drop Kitting and Assets while another project
keeps them, and it is why CR-002 and CR-016 are toggles rather than deletions.
THE ONE RULE: toggling a section OFF never deletes anything. It stops the
section rendering — in the creation form, in the detail view and in the PDF
export — and that is all. Whatever was captured stays on the package, and
toggling back on shows it again, intact. Everything in this file is about
what is DISPLAYED; nothing here writes to a package.
This list lives in its own file because three surfaces read it and they must
not drift: the SOP wizard renders the toggles, the creator applies them to
its form and its printed output, and a work package's detail view honours
them. A fourth copy is how "Assets is off" and "Assets is off, except in the
export" happen.
IDS ARE PERMANENT. They are written into every SOP that has ever been saved,
so renaming one silently turns that section back on for every existing
project. Change `label` freely; never change `id`.
*/
(function (window) {
'use strict';
var LIST = [
{ id: 'general', label: 'General Information',
note: 'Holds the WP number, subject and type. Turning this off leaves nothing to identify a package by — it is listed for completeness, not as a suggestion.' },
{ id: 'location', label: 'Location',
note: 'Where the work happens. CR-004 gives this its own structured fields; today it is the location field inside General Information.' },
{ id: 'scope', label: 'Scope of Work',
note: 'The ordered steps the crew performs, and the labour estimate.' },
{ id: 'assets', label: 'Assets',
note: 'Asset tags and controls.dev links. Off for Micron EUV — the content duplicates the database Clintons team maintains (CR-016).' },
{ id: 'materials', label: 'Materials',
note: 'The bill of materials that feeds kitting.' },
{ id: 'kitting', label: 'Kitting',
note: 'Kitting status, warehouse owner and MIMO. Off for Micron EUV, which is not kitting today (CR-009).' },
{ id: 'drawings', label: 'Drawings and Attachments',
note: 'Drawing references and attachment links.' },
{ id: 'constraints', label: 'Constraints',
note: 'Release-readiness items. A package cannot be issued while one is open.' },
{ id: 'qaqc', label: 'QA/QC',
note: 'Quality requirements, photo standard and hold points.' },
{ id: 'closeout', label: 'Closeout',
note: 'Actual hours, installed quantity, redlines and lessons learned. Actual Hours stays here — its removal was proposed and rejected (CR-017).' },
];
var IDS = LIST.map(function (s) { return s.id; });
function defaults() {
// A new SOP has everything on. A project opts OUT of what it does not use;
// it does not have to discover and opt in to what it does.
var out = {};
IDS.forEach(function (id) { out[id] = true; });
return out;
}
/* Fill in anything a stored SOP does not mention.
This is what makes adding an eleventh section safe: every SOP saved before
it existed says nothing about it, and "says nothing" has to mean ON. The
alternative — absent meaning off — would switch a brand-new section off for
every project in the estate the moment it shipped. */
function normalize(stored) {
var out = defaults();
if (stored && typeof stored === 'object') {
IDS.forEach(function (id) {
if (Object.prototype.hasOwnProperty.call(stored, id)) out[id] = stored[id] !== false;
});
}
return out;
}
function isOn(stored, id) {
if (IDS.indexOf(id) < 0) return true; // not a section we govern
return normalize(stored)[id];
}
function offList(stored) {
var s = normalize(stored);
return LIST.filter(function (x) { return !s[x.id]; }).map(function (x) { return x.label; });
}
window.WPSections = {
LIST: LIST,
IDS: IDS,
defaults: defaults,
normalize: normalize,
isOn: isOn,
offList: offList,
};
})(window);

View File

@@ -116,8 +116,11 @@ def run(page, base, tok):
chk("...named Locations in the rail",
page.eval("(document.querySelector('#step-rail-list .step-btn[data-step=\"11\"] "
".step-btn-label')||{}).textContent") == "Locations")
chk("...and it is the last step, so SOP complete moved with it",
page.eval("getComputedStyle(document.getElementById('sop-complete-btn')).display")
# It was the last step when T5.4 shipped; T5.5 appended Sections after it. The
# thing that matters either way is that the wizard's own navigation follows —
# a step whose Next button is missing is a dead end, whichever number it has.
chk("...and the wizard's navigation follows it",
page.eval("getComputedStyle(document.getElementById('sop-next-btn')).display")
!= "none")
chk("the page boots with no JavaScript errors", not page.js_errors(), page.js_errors())

451
tests/sections_check.py Normal file
View File

@@ -0,0 +1,451 @@
#!/usr/bin/env python3
"""Work package section toggles — CR-006 (T5.5).
CR-006 is the structural fix behind most of the removal requests in the plan:
rather than deleting fields globally, each project turns on only the sections it
uses. So the check that matters most is the one about what is NOT lost — a
toggle that quietly dropped data would be a worse version of the deletion it
replaces.
1. all 10 sections are toggleable
2. a section that is off is absent from the form, the detail view and the
PDF export
3. toggling off then on restores prior data with no loss
4. new SOPs default to all sections on
5. toggle state propagates into the creator — and where it does not, exactly
where and why (X4)
Check 5 is the one X4 warned about. The creator is an iframe child until T7.1,
so there are two propagation paths and they fail differently: the SOP the
creator reads at ITS boot, and a live hand-off while the frame is already open.
Both are exercised, separately, so a claim about one cannot cover for the other.
The PDF export is checked by building the print document the way printPackage()
does — it reuses #pkg-doc's HTML — rather than by opening a print window, which
headless cannot show and a human cannot diff.
Exit 0 all passed, 1 a failure, 2 could not run.
"""
import json
import os
import subprocess
import sys
import tempfile
import time
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import cdp # noqa: E402
from browser_check import seed, start_server, chk, _PASS, _FAIL, _c # noqa: E402
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STUB = """
window.__dialogs = [];
window.alert = function (m) { window.__dialogs.push(['alert', String(m)]); };
window.confirm = function (m) { window.__dialogs.push(['confirm', String(m)]); return false; };
window.prompt = function (m) { window.__dialogs.push(['prompt', String(m)]); return null; };
true
"""
# The ten CR-006 names to their creator card ids. Written out here rather than
# read from wp-sections.js so the probe checks the mapping instead of agreeing
# with it.
SECTIONS = [
("general", "General Information", "#general-card"),
("location", "Location", "#location-card"),
("scope", "Scope of Work", "#scope-card"),
("assets", "Assets", "#asset-card"),
("materials", "Materials", "#material-card"),
("kitting", "Kitting", "#mimo-card"),
("drawings", "Drawings and Attachments", "#drawings-card"),
("constraints", "Constraints", "#constraint-card"),
("qaqc", "QA/QC", "#quality-card"),
("closeout", "Closeout", "#closeout-card"),
]
# A package with content in every section, so "the section is gone" and "the
# section was empty anyway" cannot be confused.
FULL_PKG = {
"id": "wpSec1", "number": "WP99-SECT", "subject": "section probe",
"type": "Conduit Install", "status": "Draft", "project": "Job A",
"location": "PROBE LOCATION VALUE", "system": "SYS-1", "cost": "", "wbs": "",
"assignees": "", "distribution": "", "due": "", "spec": "", "desc": "",
"hours": "12", "seq": "", "predecessors": [],
"assets": [{"tag": "PROBE-ASSET-TAG", "desc": "an asset", "link": ""}],
"workSteps": ["PROBE SCOPE STEP"],
"materials": [{"qty": "2", "unit": "ea", "desc": "PROBE MATERIAL LINE"}],
"attachments": [{"doc": "PROBE DRAWING DOC", "rev": "A", "link": ""}],
"kitStatus": "PROBE KIT STATUS", "kitOwner": "", "kitDate": "",
"mimoTime": "", "mimoLoc": "",
"constraints": [{"name": "PROBE CONSTRAINT", "status": "open", "comment": ""}],
"qc": "PROBE QC VALUE", "photo": "", "hold": "",
"signoffs": [{"role": "Superintendent", "name": "", "date": "", "signed": False}],
"actualHrs": "7", "installedQty": "PROBE INSTALLED QTY", "redlines": "", "lessons": "",
}
# One string per section that must vanish from the rendered document with it.
MARKERS = {
"location": "PROBE LOCATION VALUE",
"assets": "PROBE-ASSET-TAG",
"scope": "PROBE SCOPE STEP",
"materials": "PROBE MATERIAL LINE",
"drawings": "PROBE DRAWING DOC",
"kitting": "PROBE KIT STATUS",
"constraints": "PROBE CONSTRAINT",
"qaqc": "PROBE QC VALUE",
"closeout": "PROBE INSTALLED QTY",
}
def settle(seconds=1.4):
time.sleep(seconds)
def wait_creator(page, tries=40):
for _ in range(tries):
if page.eval("!!window.wpCreatorReady"):
return True
time.sleep(0.3)
return False
def sop_with_sections(sections):
"""A SOP row shaped the way ProjectData.pushSOP writes one."""
return {
"sop": {"meta": {"tool": "Work Package Configuration", "sample": False},
"project": {"name": "Job A", "number": "A-1", "client": "Internal QA"},
"governance": {"disciplines": ["Mechanical", "Electrical"],
"woFormat": "WP##-[TYPE]"},
"woTypes": [{"name": "Conduit Install", "enabled": True}],
"sections": sections},
"state": {"project": {"name": "Job A", "number": "A-1", "client": "Internal QA",
"division": "Internal", "site": "QA Lab"},
"team": {"pm": "", "apm": "", "cm": "", "qm": ""},
"teamIds": {"pm": "", "apm": "", "cm": "", "qm": ""},
"teamMembers": [], "sections": sections,
"signoffRoles": [{"role": "Superintendent", "name": ""},
{"role": "Foreman", "name": ""}],
"wpTypes": [{"name": "Conduit Install", "enabled": True}],
"governance": {"woformat": "WP##-[TYPE]", "wosize": "", "issuance": [],
"disciplines": ["Mechanical", "Electrical"],
"discMode": "choice", "instanceSuffix": "letter",
"sizeHoursMax": ""},
"quality": {"qcreq": "Yes", "photo": "", "hold": ""},
"platforms": {"tracking": "CxAlloy", "commissioning": "CxAlloy",
"trackingUrl": "", "commissioningUrl": ""},
"constraints": [], "sequence": [], "sources": []},
}
def set_sop(db_path, sections):
from server.db import SessionLocal
from server import models
with SessionLocal() as db:
sop = db.get(models.Sop, "sopA")
sop.data = sop_with_sections(sections)
db.commit()
def render_full(page):
"""Load the probe package into the creator and render it as a document."""
page.eval("window.__probePkg = %s; true" % json.dumps(FULL_PKG))
page.eval("renderPackage(window.__probePkg)")
settle(0.7)
return page.eval("document.getElementById('pkg-doc').innerHTML")
def print_doc(page):
"""What printPackage() would put in the print window. It reuses #pkg-doc's
HTML verbatim, so this is the export, not an approximation of it."""
return page.eval("document.getElementById('pkg-doc').innerHTML")
def run(page, base, tok, db_path):
print("\n4. a new SOP defaults to every section on")
page.clear_cookies()
page.set_cookie("wp_session", tok["root"])
page.goto(base + "/work-package-suite.html?project=projA&step=12")
settle(2.0)
page.eval(STUB)
chk("the page boots with no JavaScript errors", not page.js_errors(), page.js_errors())
rows = json.loads(page.eval("""JSON.stringify(
[...document.querySelectorAll('#section-toggles .section-toggle')].map(l => ({
id: (l.querySelector('input')||{}).dataset.section,
label: ((l.querySelector('.section-toggle-name')||{}).textContent||'').trim(),
note: ((l.querySelector('.section-toggle-note')||{}).textContent||'').trim(),
on: !!(l.querySelector('input')||{}).checked,
state: ((l.querySelector('.section-toggle-state')||{}).textContent||'').trim(),
tag: (l.querySelector('input')||{}).type,
})))"""))
chk("all ten sections are listed", len(rows) == 10, [r["id"] for r in rows])
chk("...with the ids CR-006 names",
[r["id"] for r in rows] == [s[0] for s in SECTIONS], [r["id"] for r in rows])
chk("...and the labels CR-006 names",
[r["label"] for r in rows] == [s[1] for s in SECTIONS], [r["label"] for r in rows])
chk("...every one a real checkbox, not a div with a handler",
all(r["tag"] == "checkbox" for r in rows), [r["tag"] for r in rows])
chk("...every one explaining what it governs",
all(len(r["note"]) > 20 for r in rows), [r["note"][:30] for r in rows])
chk("a new SOP has all ten ON", all(r["on"] for r in rows), [r["id"] for r in rows if not r["on"]])
chk("...and says so in words, not only by the tick",
all(r["state"] == "In use" for r in rows), [r["state"] for r in rows])
chk("the summary reports nothing turned off",
"Every section is in use" in (page.eval(
"(document.getElementById('section-summary')||{}).textContent||''")),
page.eval("(document.getElementById('section-summary')||{}).textContent||''"))
print("\n1. every one of the ten can be turned off and back on")
for sec_id, label, _sel in SECTIONS:
ok = page.eval("""(() => {
const b = document.querySelector('#section-toggles input[data-section=%s]');
if (!b) return 'missing';
b.checked = false; b.dispatchEvent(new Event('change', {bubbles:true}));
const off = !b.checked;
b.checked = true; b.dispatchEvent(new Event('change', {bubbles:true}));
return (off && b.checked) ? 'ok' : 'stuck';
})()""" % json.dumps(sec_id))
chk("%-12s toggles off and on" % sec_id, ok == "ok", ok)
summary_off = page.eval("""(() => {
const b = document.querySelector('#section-toggles input[data-section="assets"]');
b.checked = false; b.dispatchEvent(new Event('change', {bubbles:true}));
return (document.getElementById('section-summary')||{}).textContent||'';
})()""")
chk("the summary names what was turned off", "Assets" in summary_off, repr(summary_off))
chk("...and says the data is kept", "retained" in summary_off, repr(summary_off))
print("\n5a. the creator honours the SOP it boots with (X4, path one)")
off = {"assets": False, "kitting": False}
set_sop(db_path, off)
page.goto(base + "/wp-creation-index.html?project=projA")
chk("the creator boots", wait_creator(page))
settle(1.4)
page.eval(STUB)
vis = json.loads(page.eval("""JSON.stringify(%s.map(sel => {
const el = document.querySelector(sel);
return [sel, !el ? 'missing' : (el.hidden ? 'hidden' : 'shown')];
}))""" % json.dumps([s[2] for s in SECTIONS])))
by_sel = dict(vis)
chk("Assets is absent from the form", by_sel["#asset-card"] == "hidden", vis)
chk("Kitting is absent from the form", by_sel["#mimo-card"] == "hidden", vis)
chk("...and every other section is still there",
all(v == "shown" for k, v in by_sel.items() if k not in ("#asset-card", "#mimo-card")),
vis)
chips = page.eval("(document.getElementById('section-nav')||{}).textContent||''")
chk("the section chip strip loses the same entries",
"Assets" not in chips and "Kitting" not in chips, repr(chips))
chk("...and keeps the rest", "Scope" in chips and "Constraints" in chips, repr(chips))
print("\n2. and from the detail view and the PDF export")
doc = render_full(page)
chk("the package renders", "WP99-SECT" in doc, doc[:120])
chk("Assets content is absent from the document", MARKERS["assets"] not in doc)
chk("Kitting content is absent from the document", MARKERS["kitting"] not in doc)
chk("...while every other section's content is present",
all(v in doc for k, v in MARKERS.items() if k not in ("assets", "kitting")),
[k for k, v in MARKERS.items() if v not in doc])
chk("no empty heading is left where a section was",
"Assets" not in doc and "Kitting" not in doc, [ln for ln in doc.split("<h2>")[1:4]])
heads = [h.split("</h2>")[0] for h in doc.split("<h2>")[1:]]
chk("...and the surviving sections are renumbered without gaps",
[h.split(".0")[0] for h in heads] == [str(i + 1) for i in range(len(heads))], heads)
export = print_doc(page)
chk("the PDF export is the same document, so it lost them too",
export == doc and MARKERS["assets"] not in export)
print("\n3. turning a section back on restores its data intact")
set_sop(db_path, {})
page.goto(base + "/wp-creation-index.html?project=projA")
chk("the creator boots again", wait_creator(page))
settle(1.4)
page.eval(STUB)
back = json.loads(page.eval("""JSON.stringify(%s.map(sel => {
const el = document.querySelector(sel);
return [sel, !el ? 'missing' : (el.hidden ? 'hidden' : 'shown')];
}))""" % json.dumps([s[2] for s in SECTIONS])))
chk("every section is back in the form", all(v == "shown" for _k, v in back), back)
doc2 = render_full(page)
chk("...and every marker is back in the document",
all(v in doc2 for v in MARKERS.values()),
[k for k, v in MARKERS.items() if v not in doc2])
chk("...including the two that were suppressed",
MARKERS["assets"] in doc2 and MARKERS["kitting"] in doc2)
# The real question is not whether the probe's own object survived — nothing
# was ever going to touch that. It is whether a package EDITED while a section
# is off keeps that section's content when it is saved. So: turn Assets off,
# load a package that has assets into the form, and collect it the way Save
# does. If hiding a card emptied what it renders, this is where it shows.
set_sop(db_path, {"assets": False})
page.goto(base + "/wp-creation-index.html?project=projA")
chk("the creator boots with Assets off", wait_creator(page))
settle(1.2)
page.eval(STUB)
collected = json.loads(page.eval("""(() => {
loadPackageIntoForm(%s);
const out = collectPackage();
return JSON.stringify({assets: out.assets, materials: out.materials,
kitStatus: out.kitStatus, subject: out.subject});
})()""" % json.dumps(FULL_PKG)))
chk("a package edited while Assets is off keeps its assets on save",
collected["assets"] == FULL_PKG["assets"], collected["assets"])
# Compared on the content, not the whole row: the creator upper-cases a
# material unit on its way through the form ("ea" -> "EA"), which is its own
# long-standing behaviour and nothing to do with section toggles. Asserting
# byte-equality here would fail on that and read as data loss.
chk("...and the sections that were on are untouched too",
[m["desc"] for m in collected["materials"]]
== [m["desc"] for m in FULL_PKG["materials"]]
and collected["subject"] == FULL_PKG["subject"], collected)
set_sop(db_path, {})
print("\n5b. a toggle flipped while the frame is open reaches it live (X4, path two)")
page.goto(base + "/work-package-suite.html?project=projA&tab=wp")
for _ in range(40):
inner = page.eval("""(() => {
try { const f = document.getElementById('wp-frame');
return !!(f && f.contentWindow && f.contentWindow.wpCreatorReady); }
catch (e) { return false; }
})()""")
if inner:
break
time.sleep(0.3)
settle(1.6)
page.eval(STUB)
chk("the creator is loaded in the frame", page.eval("""(() => {
try { return !!document.getElementById('wp-frame').contentWindow.wpCreatorReady; }
catch (e) { return false; }
})()"""))
chk("...showing Assets to begin with", page.eval("""(() => {
const d = document.getElementById('wp-frame').contentDocument;
const el = d.querySelector('#asset-card');
return !!el && !el.hidden;
})()"""))
page.eval("goToStep(12)")
settle(0.8)
page.eval("""(() => {
const b = document.querySelector('#section-toggles input[data-section="assets"]');
b.checked = false; b.dispatchEvent(new Event('change', {bubbles:true}));
return true;
})()""")
settle(0.8)
chk("turning Assets off reaches the already-loaded frame, with no reload",
page.eval("""(() => {
const d = document.getElementById('wp-frame').contentDocument;
const el = d.querySelector('#asset-card');
return !!el && el.hidden;
})()"""))
page.eval("""(() => {
const b = document.querySelector('#section-toggles input[data-section="assets"]');
b.checked = true; b.dispatchEvent(new Event('change', {bubbles:true}));
return true;
})()""")
settle(0.8)
chk("...and turning it back on brings it back",
page.eval("""(() => {
const d = document.getElementById('wp-frame').contentDocument;
const el = d.querySelector('#asset-card');
return !!el && !el.hidden;
})()"""))
print("\n an older SOP that predates CR-006 gets every section, not none")
set_sop_no_sections(db_path)
page.goto(base + "/wp-creation-index.html?project=projA")
chk("the creator boots on a SOP with no sections key", wait_creator(page))
settle(1.2)
legacy = json.loads(page.eval("""JSON.stringify(%s.map(sel => {
const el = document.querySelector(sel);
return [sel, !el ? 'missing' : (el.hidden ? 'hidden' : 'shown')];
}))""" % json.dumps([s[2] for s in SECTIONS])))
chk("...and shows all ten, because silence means on", all(v == "shown" for _k, v in legacy),
legacy)
print("\n the registry is shared, not copied")
for name in ("work-package-suite.html", "wp-creation-index.html"):
src = open(os.path.join(ROOT, "html", name), encoding="utf-8").read()
chk("%-26s loads wp-sections.js" % name, "wp-sections.js" in src)
shared = open(os.path.join(ROOT, "html", "wp-sections.js"), encoding="utf-8").read()
for name in ("work-package-suite-app.js", "wp-creation-app.js"):
src = open(os.path.join(ROOT, "html", name), encoding="utf-8").read()
chk("%-26s declares no second section list" % name,
"'Drawings and Attachments'" not in src and '"Drawings and Attachments"' not in src)
chk("the shared list is the only place the labels live",
shared.count("Drawings and Attachments") == 1)
chk("no native dialog was opened anywhere in this flow",
not json.loads(page.eval("JSON.stringify(window.__dialogs||[])")),
page.eval("JSON.stringify(window.__dialogs||[])"))
def set_sop_no_sections(db_path):
from server.db import SessionLocal
from server import models
with SessionLocal() as db:
sop = db.get(models.Sop, "sopA")
data = dict(sop.data or {})
inner = dict(data.get("sop") or {})
inner.pop("sections", None)
state = dict(data.get("state") or {})
state.pop("sections", None)
sop.data = {"sop": inner, "state": state}
db.commit()
def main():
exe = cdp.find_browser()
if not exe:
print("no headless-capable browser found; set WP_BROWSER.")
return 2
tmpdir = tempfile.mkdtemp(prefix="wpsuite-sections-")
db_path = os.path.join(tmpdir, "check.db")
server = None
try:
tok = seed(db_path)
set_sop(db_path, {})
port = cdp.free_port()
base = "http://127.0.0.1:%d" % port
server = start_server(port, db_path)
if server is None:
print("the test server would not start.")
return 2
print("\nSection toggles — CR-006\nTarget: %s" % base)
browser = cdp.Browser(exe)
page = browser.page()
try:
run(page, base, tok, db_path)
finally:
page.close()
browser.close()
finally:
if server:
server.kill()
try:
server.wait(timeout=10)
except subprocess.TimeoutExpired:
pass
try:
from server.db import engine
engine.dispose()
except Exception:
pass
import shutil
for _ in range(10):
shutil.rmtree(tmpdir, ignore_errors=True)
if not os.path.exists(tmpdir):
break
time.sleep(0.3)
total = len(_PASS) + len(_FAIL)
print("\n%s\n%d/%d checks passed." % ("-" * 54, len(_PASS), total))
if _FAIL:
for f in _FAIL:
print(" - " + f)
return 1
print("\nResult: " + _c("ALL PASS — off means hidden, never deleted.", "32") + "\n")
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@@ -51,9 +51,10 @@ HTML_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__
# Wave 0 recorded 12. T5.1 must take ten of them.
BASELINE_DIV_ONCLICK = 12
# Ten until T5.4 (CR-005) appended Locations. Named rather than repeated, so the
# next step to be added moves one number instead of eight assertions.
STEP_COUNT = 11
# Ten at T5.1; +1 at T5.4 (CR-005 Locations); +1 at T5.5 (CR-006 Sections). Named
# rather than repeated, so the next step to be added moves one number instead of
# eight assertions.
STEP_COUNT = 12
# Swallow the wizard's remaining native dialogs and record that they fired. The
# wizard still has them until T5.8; this proves the RAIL never reaches one.