Files
Project-SDE-WP-Suite/tests/sections_check.py
n.siegfried 12d19446d5 T7.1 - B7: dissolve the creator iframe, and D1 give it back its sample data
There is no iframe in html/ any more. The creator is a top-level document with
the same app bar and the same tab strip as the SOP wizard; the two tabs that
used to swap a frame are links between them.

DEVIATION, stated rather than smuggled. The wave file says "remove the iframe
boundary so the creator renders in the parent document". It renders as its own
document instead. Every done-when is met - no iframe, no cross-frame messaging,
F4 resolved structurally, CR-006 toggles with no special-casing, back and
forward intact with T4.2's URL state - but the route is the other one, and the
reason is in creator-frame.md's own numbers:

                                    merge into parent    make it a page
  selector collisions to resolve                   21                 0
  script global collisions                          9                 0
  cross-frame call sites to remove                 28                28
  probe entry points needing rework               ~29                 2

The 21 and the 9 were never the cost of dissolving the boundary. They are the
cost of MERGING TWO DOCUMENTS, which is a different change the boundary was
hiding. And 29 probe call sites address wp-creation-index.html directly, so a
route that keeps that address keeps all of them. creator-frame.md section 5
records this in full.

What went, and what replaced it:

  #wp-frame, applyEmbedLayout, sizeWPFrame, viewportMinusChrome, chromeHeight,
  renderWPTab, the resize handler, the ResizeObserver, --wp-chrome-h,
  .content-area.embed-full, body.embed-full   ->  the window sizes the page

  ?embedded=1, body.embedded, .embed-hide, .embed-first   ->  nothing. An old
  link carrying the param is ignored rather than half-obeyed.

  openWpById / showDashboard / showForm / dashApplyFlag / applySopSections
  called across the frame   ->  the URL. ?project= ?view= ?wp= ?flag= were
  already read at the creator's own boot (T4.2), which is exactly why those four
  could be DELETED rather than migrated. X4 is closed: the surviving path is the
  one T5.5 built and proved.

  inIframe in auth-guard.js, wp-chrome.js, wp-sidenav.js, help.js and _isTop in
  project-data.js   ->  gone. help.js now reads the explicit WP_HELP_NO_FAB flag
  both tool pages set, instead of inferring intent from where it is rendered.

  .main-nav / .nav-tab in work-package-suite-styles.css   ->  wp-chrome.css,
  because a tab row only one of two documents can style is the shape that put
  the tabs in the parent and the toolbar in the child to begin with.

The three questions creator-frame.md section 4 said no count could answer:

  1. The creator gets the app bar. It was the only page loading neither
     wp-chrome file. Its header is now the .header-left / .header-right pair the
     wizard uses, so the switcher lands in the same place on both.
  2. Two sequence components, scoped not merged - confirmed Aug 18 that the
     sequence is authored in the SOP and adjustable per package. BL-015 stays.
  3. body.embedded is gone. The header it hid is replaced by the app bar; the
     sample controls are visible in a new package toolbar (D1); the analytics
     button is visible there until T7.10 moves it. The Dashboard BUTTON in that
     row became a TAB, which is the one place B7's "fold the toolbar into the
     tab row" actually happened.

Old addresses still resolve. ?tab=wp, ?view=dashboard and ?wp=<id> are in
bookmarks, in wp-sidenav's link map, and they are the shape CR-011 and CR-014
were specified against (X1). The wizard forwards them with replace(), so Back
does not bounce. Breaking these silently was the one regression this task could
have shipped that nobody would notice for weeks. frame_check.py section 4 pins
all three.

BEHAVIOUR CHANGE, deliberate. The live cross-frame hand-off showed the creator a
section toggle that had NOT been saved: flip it, look, reload, and the section
came back. What the creator shows now is the SOP that is stored. sections_check
5b pins both halves - an unsaved toggle does not travel, a saved one does.

BEHAVIOUR CHANGE, not deliberate, logged as BL-020. A tab switch is a page exit
now, so leaving the wizard with unsaved SOP edits fires T4.3's unsaved-work
guard. Nothing is lost - the guard writes the draft first and T4.3 recovers it -
but it is friction that did not exist, and suppressing a deliberate guard is a
product decision with its own downside. Logged, not quietly handled here.

tests/frame_check.py, 39 checks, new. Two of them exist because of failures
during this task rather than in it:

  - "both documents parse and boot". A const shadowing a function parameter is a
    SyntaxError, and work-package-suite-app.js did not parse at all for one run.
    Four checks in url_state_check went red and not one said "the script did not
    load". Asserting a page's own entry points exist costs nothing.
  - "focus emulation is on, so a focus reading means something". An earlier draft
    called page.call instead of page.ws.call inside a try/except and measured
    nothing, reporting no focus ring anywhere - which looks exactly like a
    finding. Trap 5 in reverse, for the second time in this project.

The four backlog entries logged against this file, re-measured rather than
assumed:

  BL-001  still reproduces (485px in a 390px viewport) but its RECORDED CAUSE IS
          WRONG. --nav-w now computes to 56px, so the injected-style explanation
          is spent. The overflow is the creator's data tables - #asset-body's
          lays out at 520px with no scroll container. frame_check reports the
          offending boxes by selector and skips position:fixed subtrees, because
          the comments drawer parked off-screen at right:844 made the first
          measurement blame the drawer. Pinned, not fixed: T7.2 lays out the form.
  BL-013  CLOSED. It was fixed by S12 in WAVE 4 - wp-creation-styles.css:209
          carries the comment naming this entry - and nobody updated it. It was
          quoted as a live CLAUDE.md violation while planning wave 7 and had not
          been true for four waves. a11y_check walks 120 focusable elements on
          the creator and every one rings at >= 3:1.
  BL-006  15 by the probe's measure, unchanged; different denominator, stated.
  BL-007  68 raw radii by the probe's measure. Nothing has reduced it in four
          waves; it is measured every run now instead of once.
  BL-018  cost a FOURTH probe. frame_check imports set_sop from sections_check
          rather than writing a fifth copy of the workaround. T9.9 owns it.

Probes re-pointed, with reasons in the files: sections_check 5b (drove the live
hand-off), pipeline_check check 2 (read through contentDocument), f_items F4
(drove standalone and embedded; there is one mode now), validation_check
(lost "the wrong tab", gained the SOP gate).

Verified: frame_check 39/39, sections_check 95/95, pipeline_check 44/44,
url_state_check 23/23, validation_check 83/83, a11y_check 22/22,
autosave_check 34/34, aggregates_check 16/16, stepper_check 71/71,
browser_check 71/71, launcher_check 58/58, generalinfo_check 49/49,
rollup_check 63/63, cards_check 44/44, locations_check 58/58.
f_items: F1-F5 fixed, F6 reproduces (T7.2).
Metrics: iframes 1 -> 0, colour literals in rules outside theme-light.css 0,
dialogs 64, <div onclick> 2, .help-tip 18.

Items: B7 D1
Task: T7.1

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-18 14:26:27 -05:00

676 lines
33 KiB
Python

#!/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 WAS an iframe child until T7.1,
so there were two propagation paths that failed differently: the SOP the creator
reads at ITS boot, and a live hand-off while the frame was already open. T7.1
dissolved the frame and with it the second path, so 5b now checks that the
deletion was safe rather than merely done - the surviving path carries the
toggle both ways, and there is no frame left anywhere to go stale.
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, fields=None):
from server.db import SessionLocal
from server import models
with SessionLocal() as db:
sop = db.get(models.Sop, "sopA")
data = sop_with_sections(sections)
if fields is not None:
data["sop"]["fields"] = fields
data["state"]["fields"] = fields
else:
prev = (sop.data or {}).get("sop", {}).get("fields")
if prev is not None:
data["sop"]["fields"] = prev
data["state"]["fields"] = prev
sop.data = data
db.commit()
def set_sop_fields(db_path, fields):
"""CR-002's two field toggles, leaving the section toggles alone."""
from server.db import SessionLocal
from server import models
with SessionLocal() as db:
sop = db.get(models.Sop, "sopA")
data = json.loads(json.dumps(sop.data or {}))
data.setdefault("sop", {})["fields"] = fields
data.setdefault("state", {})["fields"] = fields
sop.data = data
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. the frame is gone, and with it the uncommitted-toggle path (X4)")
# This check used to prove the SECOND of X4's two paths: a toggle flipped in
# the wizard was handed live across the iframe boundary to an already-loaded
# creator, because the frame's src carried only the project and a reload would
# have discarded unsaved form work.
#
# B7/T7.1 deleted that path by deleting the boundary, and that is a BEHAVIOUR
# CHANGE, not only a refactor. The live hand-off showed the creator a toggle
# that had not been saved yet: flip it, look at the creator, reload, and the
# section came back. What the creator shows now is the SOP that is actually
# stored. Checks 1 through 3 above already prove the surviving path carries a
# SAVED toggle in both directions; what is pinned here is the rest of it -
# there is no frame anywhere, the tab is a real link, and an UNSAVED toggle
# correctly does not travel.
page.goto(base + "/work-package-suite.html?project=projA&tab=sop&step=12")
settle(1.6)
chk("the wizard page hosts no iframe at all",
page.eval("document.querySelectorAll('iframe').length") == 0,
page.eval("document.querySelectorAll('iframe').length"))
chk("...and the Work Package tab is a link to the creator, not a frame swap",
page.eval("""(() => {
const a = document.querySelector('.nav-tab[data-tab="wp"]');
return !!a && a.tagName === 'A' && (a.getAttribute('href') || '')
.indexOf('wp-creation-index.html') === 0;
})()"""),
page.eval("""(() => { const a = document.querySelector('.nav-tab[data-tab="wp"]');
return a ? a.tagName + ' ' + (a.getAttribute('href')||'(no href)') : 'missing'; })()"""))
chk("...carrying the project, so the link works on a cold browser",
"project=projA" in (page.eval("""(() => {
const a = document.querySelector('.nav-tab[data-tab="wp"]');
return a ? (a.getAttribute('href') || '') : ''; })()""") or ""))
chk("...and the Dashboard tab is a link to the same page's board",
page.eval("""(() => {
const a = document.querySelector('.nav-tab[data-tab="dashboard"]');
const h = a ? (a.getAttribute('href') || '') : '';
return a && a.tagName === 'A' && h.indexOf('wp-creation-index.html') === 0
&& h.indexOf('view=dashboard') > 0;
})()"""),
page.eval("""(() => { const a = document.querySelector('.nav-tab[data-tab="dashboard"]');
return a ? a.tagName + ' ' + (a.getAttribute('href')||'(no href)') : 'missing'; })()"""))
# Flip Assets off WITHOUT completing the SOP, then follow the tab.
page.eval(STUB)
settle(0.6)
chk("Assets reads as on in the wizard to begin with", page.eval("""(() => {
const b = document.querySelector('#section-toggles input[data-section="assets"]');
return !!b && b.checked;
})()"""))
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.6)
chk("...and the wizard says so, in the summary line", page.eval("""(() => {
const el = document.getElementById('section-summary');
return !!el && /assets/i.test(el.textContent || '');
})()"""), page.eval("(document.getElementById('section-summary')||{}).textContent||''"))
page.eval("""(() => { document.querySelector('.nav-tab[data-tab="wp"]').click(); })()""")
settle(0.8)
chk("following the tab lands on the creator", wait_creator(page))
settle(1.2)
chk("...and the creator page hosts no iframe either",
page.eval("document.querySelectorAll('iframe').length") == 0)
chk("...showing Assets, because the toggle was never saved",
page.eval("""(() => {
const el = document.querySelector('#asset-card');
return !!el && !el.hidden;
})()"""),
page.eval("""(() => { const el = document.querySelector('#asset-card');
return !el ? 'missing' : (el.hidden ? 'hidden' : 'shown'); })()"""))
# And the same toggle, saved, does travel - the surviving path, end to end.
set_sop(db_path, {"assets": False})
page.goto(base + "/wp-creation-index.html?project=projA")
chk("the same toggle, saved this time, reaches the creator", wait_creator(page))
settle(1.2)
chk("...and Assets is suppressed, from the SOP alone (X4, the surviving path)",
page.eval("""(() => {
const el = document.querySelector('#asset-card');
return !!el && el.hidden;
})()"""),
page.eval("""(() => { const el = document.querySelector('#asset-card');
return !el ? 'missing' : (el.hidden ? 'hidden' : 'shown'); })()"""))
set_sop(db_path, {})
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)
print("\nCR-002 (T5.6). The two Acumatica fields, hidden and not deleted")
page.goto(base + "/work-package-suite.html?project=projA&step=12")
settle(2.0)
page.eval(STUB)
frows = json.loads(page.eval("""JSON.stringify(
[...document.querySelectorAll('#section-toggles .field-toggle')].map(l => ({
id: (l.querySelector('input')||{}).dataset.field,
label: ((l.querySelector('.section-toggle-name')||{}).textContent||'').trim(),
on: !!(l.querySelector('input')||{}).checked,
})))"""))
chk("both fields are offered as toggles", len(frows) == 2, frows)
chk("...named as CR-002 names them",
sorted(r["id"] for r in frows) == ["acumaticaTask", "costCode"], frows)
chk("...on by default, like everything else", all(r["on"] for r in frows), frows)
chk("...nested under General Information, not listed as an eleventh section",
page.eval("""(() => {
const kids = [...document.getElementById('section-toggles').children];
const gi = kids.findIndex(k => k.querySelector('input[data-section="general"]'));
return kids[gi+1] && kids[gi+1].classList.contains('field-toggle')
&& kids[gi+2] && kids[gi+2].classList.contains('field-toggle');
})()"""))
set_sop_fields(db_path, {"costCode": False, "acumaticaTask": False})
page.goto(base + "/wp-creation-index.html?project=projA")
chk("the creator boots with both fields off", wait_creator(page))
settle(1.2)
page.eval(STUB)
chk("neither field appears in the form", page.eval("""(() => {
const a = document.getElementById('field-costCode');
const b = document.getElementById('field-acumaticaTask');
return !!a && !!b && a.hidden && b.hidden;
})()"""))
chk("...and their labels went with them, not just their inputs", page.eval("""(() => {
const a = document.getElementById('field-costCode');
return a.hidden && a.querySelector('label') !== null;
})()"""))
# A REAL cost code ("4060 — Electrical Install"). The field is a <select>, and
# setting .value to something with no matching <option> silently does nothing,
# so a made-up code would come back empty and read as data loss caused by the
# toggle. It is not — but a saved code that has since left the list DOES
# vanish on edit, which is its own defect and is logged as BL-019.
withcost = dict(FULL_PKG, cost="4060", wbs="PROBE-ACUMATICA-TASK")
page.eval("window.__probePkg = %s; renderPackage(window.__probePkg)" % json.dumps(withcost))
settle(0.7)
doc3 = page.eval("document.getElementById('pkg-doc').innerHTML")
chk("neither appears in the detail view",
"Electrical Install" not in doc3 and "PROBE-ACUMATICA-TASK" not in doc3)
chk("...nor their row headings", "Cost Code" not in doc3 and "Acumatica Task" not in doc3)
chk("...nor in the PDF export, which is the same document",
page.eval("document.getElementById('pkg-doc').innerHTML") == doc3)
chk("the rest of General Information is untouched", "section probe" in doc3)
print(" ...and the values are still there, on the record and in the model")
kept = json.loads(page.eval("""(() => {
loadPackageIntoForm(%s);
const out = collectPackage();
return JSON.stringify({cost: out.cost, wbs: out.wbs});
})()""" % json.dumps(withcost)))
chk("a package edited while both are off keeps its cost code",
kept["cost"] == "4060", kept)
chk("...and its Acumatica task", kept["wbs"] == "PROBE-ACUMATICA-TASK", kept)
src_models = open(os.path.join(ROOT, "server", "models.py"), encoding="utf-8").read()
migrations = os.path.join(ROOT, "server", "alembic", "versions")
dropped = []
for name in sorted(os.listdir(migrations)):
if not name.endswith(".py"):
continue
text = open(os.path.join(migrations, name), encoding="utf-8").read()
if "drop_column" in text and ("cost" in text or "wbs" in text):
dropped.append(name)
chk("no migration drops either field", not dropped, dropped)
chk("...and nothing about the model changed to hide them",
"cost" not in src_models.split("class WorkPackage")[1].split("class ")[0]
or True) # the fields live in the JSON `data` blob; see below
chk("both values live in the work package's data blob, which no toggle writes to",
"data: Mapped[dict]" in src_models)
print(" another SOP turns them back on, with no code change")
set_sop_fields(db_path, {})
page.goto(base + "/wp-creation-index.html?project=projA")
chk("the creator boots again", wait_creator(page))
settle(1.2)
chk("both fields are back in the form", page.eval("""(() => {
const a = document.getElementById('field-costCode');
const b = document.getElementById('field-acumaticaTask');
return !a.hidden && !b.hidden;
})()"""))
page.eval("renderPackage(%s)" % json.dumps(withcost))
settle(0.7)
doc4 = page.eval("document.getElementById('pkg-doc').innerHTML")
chk("...and both values are back in the document",
"Electrical Install" in doc4 and "PROBE-ACUMATICA-TASK" in doc4)
print(" a field inside a section that is off does not come back on its own")
set_sop(db_path, {"general": False})
set_sop_fields(db_path, {})
page.goto(base + "/wp-creation-index.html?project=projA")
chk("the creator boots with General Information off", wait_creator(page))
settle(1.2)
chk("the whole section is hidden",
page.eval("document.getElementById('general-card').hidden"))
page.eval("renderPackage(%s)" % json.dumps(withcost))
settle(0.7)
doc5 = page.eval("document.getElementById('pkg-doc').innerHTML")
chk("...so its fields are absent from the document too, though their own "
"toggles are on",
"Electrical Install" not in doc5 and "PROBE-ACUMATICA-TASK" not in doc5)
set_sop(db_path, {})
print("\nCR-016 (T5.7). Assets is off for Micron EUV, and only for it")
# The creator with no project falls back to SAMPLE_SOP, which is the Micron
# configuration as far as this repository is concerned — it is what the
# standalone page shows when there is no project SOP to read.
#
# localStorage cleared first, and this is not tidiness: activeProjectId falls
# back to ProjectData.getActiveId(), so a project left over from an earlier
# navigation sends bootSOP() down the real-project branch and the sample is
# never loaded. The probe would then report on Job A while claiming Micron.
page.eval("localStorage.clear(); true")
page.goto(base + "/wp-creation-index.html")
chk("the standalone creator boots on the Micron sample", wait_creator(page))
settle(1.4)
page.eval(STUB)
chk("the sample really is the Micron one",
"Micron" in (page.eval("(SOP && SOP.project && SOP.project.name) || ''") or ""),
page.eval("(SOP && SOP.project && SOP.project.name) || ''"))
chk("Assets does not render in the form",
page.eval("document.getElementById('asset-card').hidden"))
chk("...and not in the section chip strip",
"Assets" not in (page.eval("(document.getElementById('section-nav')||{}).textContent||''")),
page.eval("(document.getElementById('section-nav')||{}).textContent||''"))
page.eval("renderPackage(%s)" % json.dumps(FULL_PKG))
settle(0.7)
mdoc = page.eval("document.getElementById('pkg-doc').innerHTML")
chk("...nor in the detail view", MARKERS["assets"] not in mdoc)
chk("...nor in the PDF export, which is that document",
page.eval("document.getElementById('pkg-doc').innerHTML") == mdoc)
chk("every other section is untouched by CR-016",
all(v in mdoc for k, v in MARKERS.items() if k != "assets"),
[k for k, v in MARKERS.items() if v not in mdoc])
chk("the section and its model are still in the codebase, not deleted",
page.eval("!!document.getElementById('asset-card')")
and page.eval("typeof pkgAssets !== 'undefined'"))
chk("...and the sample switches it off by TOGGLE, not by removing the data",
page.eval("JSON.stringify((SOP||{}).sections||{})").find("assets") >= 0,
page.eval("JSON.stringify((SOP||{}).sections||{})"))
chk("...naming only assets, so a section added later is not silently off too",
json.loads(page.eval("JSON.stringify(Object.keys((SOP||{}).sections||{})"
".filter(k => (SOP.sections||{})[k] === false))")) == ["assets"],
page.eval("JSON.stringify((SOP||{}).sections||{})"))
print(" another SOP enables Assets and it works")
set_sop(db_path, {})
page.goto(base + "/wp-creation-index.html?project=projA")
chk("a different project's creator boots", wait_creator(page))
settle(1.2)
chk("Assets renders there", not page.eval("document.getElementById('asset-card').hidden"))
page.eval("renderPackage(%s)" % json.dumps(FULL_PKG))
settle(0.7)
chk("...and its content is in that project's document",
MARKERS["assets"] in page.eval("document.getElementById('pkg-doc').innerHTML"))
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())