create-pmos 0.398.0 → 0.399.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/package.json +13 -13
  2. package/payload/KIT-VERSION +1 -1
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/workspace/briefing-premium-adddoc-test.js +18 -14
  7. package/workspace/briefing-premium-board-test.js +80 -48
  8. package/workspace/briefing-premium-calendar-2-test.js +36 -36
  9. package/workspace/briefing-premium-calendar-3-test.js +39 -39
  10. package/workspace/briefing-premium-calendar-test.js +23 -24
  11. package/workspace/briefing-premium-doc-edit-test.js +6 -2
  12. package/workspace/briefing-premium-initiative-test.js +38 -16
  13. package/workspace/briefing-premium-insights-test.js +114 -37
  14. package/workspace/briefing-premium-metrics-test.js +6 -4
  15. package/workspace/briefing-premium-products-test.js +10 -7
  16. package/workspace/briefing-premium-sources-test.js +25 -22
  17. package/workspace/briefing-premium-test.js +46 -42
  18. package/workspace/briefing-premium-work-test.js +9 -9
  19. package/workspace/changelog.json +12 -0
  20. package/workspace/ev-everywhere-test.js +210 -0
  21. package/workspace/fixtures/premium-viewer-fixtures.js +11 -6
  22. package/workspace/guide/home.md +39 -18
  23. package/workspace/guide/index.md +1 -1
  24. package/workspace/lib/board-grill.js +63 -0
  25. package/workspace/lib/board-premium.js +36 -5
  26. package/workspace/lib/initiative-layout.js +77 -0
  27. package/workspace/lib/insights-premium.js +3 -2
  28. package/workspace/lib/insights-records.js +21 -7
  29. package/workspace/lib/meeting-points.js +52 -0
  30. package/workspace/lib/news-for-you.js +88 -0
  31. package/workspace/lib/notes-series.js +29 -6
  32. package/workspace/lib/report-confirm.js +48 -0
  33. package/workspace/lib/route-modules.js +8 -0
  34. package/workspace/lib/routes-board-docs.js +46 -0
  35. package/workspace/lib/routes-board-grill.js +90 -0
  36. package/workspace/lib/routes-home-review.js +108 -0
  37. package/workspace/lib/routes-initiative-layout.js +57 -0
  38. package/workspace/lib/routes-insights-premium.js +4 -1
  39. package/workspace/lib/routes-insights-records.js +8 -4
  40. package/workspace/lib/routes-meeting-points.js +37 -0
  41. package/workspace/lib/routes-news.js +57 -0
  42. package/workspace/lib/routes-notes.js +2 -1
  43. package/workspace/lib/routes-report-confirm.js +31 -0
  44. package/workspace/lib/routes-search.js +38 -0
  45. package/workspace/lib/search-index.js +176 -0
  46. package/workspace/package-lock.json +2 -2
  47. package/workspace/package.json +1 -1
  48. package/workspace/premium-board-actions-test.js +86 -50
  49. package/workspace/premium-briefing-depth-test.js +55 -54
  50. package/workspace/premium-chat-chart-tab-test.js +4 -2
  51. package/workspace/premium-chat-report-tab-test.js +16 -2
  52. package/workspace/premium-core-doc-issue-test.js +15 -13
  53. package/workspace/premium-phone-card-test.js +5 -3
  54. package/workspace/premium-report-read-test.js +55 -18
  55. package/workspace/premium-vw-backlog-test.js +2 -2
  56. package/workspace/premium-vw-cal-test.js +50 -35
  57. package/workspace/premium-vw-doc-test.js +9 -3
  58. package/workspace/premium-vw-item-test.js +1 -1
  59. package/workspace/premium-vw-jira-test.js +2 -2
  60. package/workspace/premium-vw-meet-test.js +37 -40
  61. package/workspace/premium-vw-notes-test.js +21 -19
  62. package/workspace/premium-vw-rec-test.js +11 -12
  63. package/workspace/premium-welcome-test.js +3 -3
  64. package/workspace/premium-work-depth-test.js +3 -3
  65. package/workspace/public/pm/bd-acts.js +303 -225
  66. package/workspace/public/pm/bd-asks.js +261 -0
  67. package/workspace/public/pm/bd-pop.js +59 -0
  68. package/workspace/public/pm/bd-span.js +49 -13
  69. package/workspace/public/pm/bd-views.js +169 -0
  70. package/workspace/public/pm/cozy-board.css +301 -0
  71. package/workspace/public/pm/cozy-ev.css +228 -0
  72. package/workspace/public/pm/cozy-evmodel.js +106 -0
  73. package/workspace/public/pm/cozy-evui.js +47 -0
  74. package/workspace/public/pm/cozy-insights.css +148 -10
  75. package/workspace/public/pm/cozy-nav.js +103 -39
  76. package/workspace/public/pm/cozy-news.js +140 -0
  77. package/workspace/public/pm/cozy-search.js +203 -0
  78. package/workspace/public/pm/cozy-settings.js +198 -0
  79. package/workspace/public/pm/cozy-sources.js +89 -0
  80. package/workspace/public/pm/cozy-today.css +217 -0
  81. package/workspace/public/pm/cozy-viewer.js +1 -0
  82. package/workspace/public/pm/cozy-vw-mtg.css +350 -0
  83. package/workspace/public/pm/cozy-vw-rp.css +152 -0
  84. package/workspace/public/pm/home-adddoc.js +5 -5
  85. package/workspace/public/pm/home-app.js +329 -55
  86. package/workspace/public/pm/home-around.js +24 -126
  87. package/workspace/public/pm/home-chat.js +67 -14
  88. package/workspace/public/pm/home-data.js +6 -6
  89. package/workspace/public/pm/home-dictate.js +54 -0
  90. package/workspace/public/pm/home-draft.js +6 -6
  91. package/workspace/public/pm/home-ini-model.js +190 -0
  92. package/workspace/public/pm/home-ini.css +171 -0
  93. package/workspace/public/pm/home-ini.js +456 -0
  94. package/workspace/public/pm/home-list.js +276 -0
  95. package/workspace/public/pm/home-more.js +17 -134
  96. package/workspace/public/pm/home-phone-card.js +4 -4
  97. package/workspace/public/pm/home-review.js +104 -0
  98. package/workspace/public/pm/home-task.js +67 -0
  99. package/workspace/public/pm/home-today.js +144 -0
  100. package/workspace/public/pm/home-work.js +54 -26
  101. package/workspace/public/pm/premium-board.js +163 -39
  102. package/workspace/public/pm/premium-chart-tab.js +4 -5
  103. package/workspace/public/pm/premium-first.js +5 -7
  104. package/workspace/public/pm/premium-insights.js +499 -202
  105. package/workspace/public/pm/premium-mtg-present.js +138 -0
  106. package/workspace/public/pm/premium-mtg-replay.js +142 -0
  107. package/workspace/public/pm/premium-report-read.js +216 -52
  108. package/workspace/public/pm/premium-report-tab.js +44 -19
  109. package/workspace/public/pm/premium-shell.js +7 -7
  110. package/workspace/public/pm/premium-vw-cal.js +150 -60
  111. package/workspace/public/pm/premium-vw-mtg.js +488 -261
  112. package/workspace/public/pm/premium-vw-notes.js +61 -0
  113. package/workspace/public/pm/rp-parts.js +269 -0
  114. package/workspace/public/premium-board.html +4 -3
  115. package/workspace/public/premium-insights.html +10 -10
  116. package/workspace/public/premium.html +3 -1
  117. package/workspace/r/m1.png +0 -0
  118. package/workspace/r/m2.png +0 -0
  119. package/workspace/r/m3.png +0 -0
  120. package/workspace/r/nl.png +0 -0
  121. package/workspace/test-lists/initiative-layout.json +9 -0
  122. package/workspace/test-lists/premium-uncovered-meetings.json +9 -0
  123. package/workspace/test-lists/premium-uncovered-reports.json +9 -0
  124. package/workspace/test-lists/uf-everywhere.json +15 -0
  125. package/workspace/test-lists/uf-home.json +9 -0
  126. package/workspace/test-lists/uncovered-board.json +9 -0
@@ -7,9 +7,20 @@
7
7
  * New dashboard and Edit chart save a dashboard (POST /api/premium-dashboards/save: name, purpose and its goals in order); Pin (POST
8
8
  * /api/premium-dashboards/pin). A field the design shows and no route accepts is drawn and marked "Not saved yet". Record verdict has no route, so it
9
9
  * is not available yet. Nothing is sent outward.
10
- * A part of the page the design does not draw (the goal detail, a Delivery trends target, a report setup, request or finding) opens the "Waiting for
11
- * design" card (window.czPlaceholder) in the Viewer card (window.czViewer); both are feature-detected, with this page's side panel as the fallback.
12
- * A report file opens in the report reader (pm/premium-report-read.js), the report panel in the Viewer card. The page has no #dlg. */
10
+ * The Uncovered features frames (initiative premium-uncovered-features) draw what the Agreed design left out:
11
+ * IsGoal a goal's detail in the Viewer card: Readings (the chart with its target, its pace and the ship dates of the work that moves it, the
12
+ * readings with their source, Add a reading), Moved by, and On your dashboards (each switch saves that dashboard). A health budget opens
13
+ * in the same frame.
14
+ * IsTarget a Delivery trends tile's target in a popover over the tiles: At least, At most or No target, the value, the day it counts from, the
15
+ * tile's own range and "Show the target on the Board chip". The number goes where it was kept before; how it is read goes to
16
+ * POST /api/insights-records/tile. A tile goes amber only after two readings past its target. "Delivery trends" is also a view.
17
+ * IsLibrary Found in your work as cards (Set it up, Not a report with Undo), the reports as Report · Next · Status, and a report's setup in the
18
+ * Viewer card (Setup, Issues, Brief); a request from Home with Set it up, Change it and Cancel. New report hands off to Home.
19
+ * IsMenus the product picker (each product's goal count, Portfolio rolls the goals of every product up), the Dashboard menu, Find (goals,
20
+ * reports and dashboards), Filter (status, owner, kind), ⋯ (Sources, Export, About) and the empty trend of a goal with one reading.
21
+ * IsPhone the goal detail full screen with Readings, Moved by and Dashboards; a report setup as a sheet.
22
+ * window.czViewer is feature-detected, with this page's side panel as the fallback. A report file opens in the report reader
23
+ * (pm/premium-report-read.js), the report panel in the Viewer card. The page has no #dlg. */
13
24
  import { $, $$, esc, toast, wireRail, setPageGaps } from './premium-shell.js';
14
25
  import { pmPost } from './http.js';
15
26
  import { openReport } from './premium-report-read.js';
@@ -19,10 +30,11 @@ let M = null; // the model
19
30
  let BM = null, bmErr = ''; // the Board measures (Delivery trends)
20
31
  let dash = null; // the view: a dashboard id; 'all' is every goal
21
32
  let tab = 'goals';
22
- let listF = 'all'; // the Library filter
23
33
  let per = null; // the period { key, label, name, from, to }
24
34
  let find = '';
25
- let filt = { obj: null, owner: null, type: null, lane: null };
35
+ let filt = { status: [], owner: [], kind: [] }; // the Filter (IsMenus): each group holds the chips that are on
36
+ let PF = null; // Portfolio (IsMenus): { goals, charts, products } rolled up from every product's model, or null
37
+ let loadedAt = 0;
26
38
  let selecting = false; let picked = []; // New dashboard: the goals picked in the table, in order
27
39
  wireRail('rep');
28
40
  mountNav('insights');
@@ -32,41 +44,36 @@ const I = {
32
44
  doc: 'M6 3h9l4 4v14H6zM14 3v5h5M9 13h6M9 17h4', pin: 'M9 3h6l-1 6 4 3v2H6v-2l4-3zM12 14v7', chk: 'M5 12l5 5 9-10', x: 'M6 6l12 12M18 6L6 18',
33
45
  more: 'M5 12h.01M12 12h.01M19 12h.01', home: 'M3 11l9-7 9 7v9a1 1 0 0 1-1 1h-5v-6h-6v6H4a1 1 0 0 1-1-1z', next: 'M9 6l6 6-6 6', plus: 'M12 5v14M5 12h14',
34
46
  spark: 'M12 3l1.8 4.7L18.5 9.5l-4.7 1.8L12 16l-1.8-4.7L5.5 9.5l4.7-1.8z', up: 'M12 19V5M6 11l6-6 6 6', grip: 'M9 6h.01M15 6h.01M9 12h.01M15 12h.01M9 18h.01M15 18h.01',
35
- chart: 'M4 20V10M10 20V4M16 20v-8M22 20H2', ext: 'M14 4h6v6M20 4l-9 9M18 14v5H5V6h5', down: 'M7 10l5 5 5-5',
47
+ chart: 'M4 20V10M10 20V4M16 20v-8M22 20H2', ext: 'M14 4h6v6M20 4l-9 9M18 14v5H5V6h5', down: 'M7 10l5 5 5-5', pen: 'M4 20h4L19 9l-4-4L4 16zM13 7l4 4',
48
+ pause: 'M9 5v14M15 5v14', play: 'M7 5l12 7-12 7z',
36
49
  };
37
- const byKey = (k) => (M && (M.charts || []).find((c) => c.key === k)) || null;
50
+ const byKey = (k) => (PF && PF.charts[k]) || (M && (M.charts || []).find((c) => c.key === k)) || null;
38
51
  const savedDash = () => (M.dashboards || []).filter((d) => d.saved);
39
52
  const wsQ = () => (M && M.board.ws ? 'ws=' + encodeURIComponent(M.board.ws) + '&' : '');
40
53
  const homeAsk = (kind, q) => '/premium.html?' + wsQ() + 'ask=' + encodeURIComponent(kind) + '&q=' + encodeURIComponent(q);
41
54
  const iniHref = (id) => '/premium-initiative.html?' + wsQ() + 'id=' + encodeURIComponent(id);
42
55
  const SRC_NAME = { analytics: 'Product analytics', jira: 'Jira query', file: 'A file or export', typed: 'You type it in' };
43
56
  /** A goal's KR id as the design says it: "KR <objective>.<its place in the objective>", in the order of the records; '' with no objective. */
44
- const krId = (g) => { if (!g || !g.pillar) return ''; const objs = [...new Set(M.goals.map((x) => x.pillar).filter(Boolean))], same = M.goals.filter((x) => x.pillar === g.pillar); return 'KR ' + (objs.indexOf(g.pillar) + 1) + '.' + (same.indexOf(g) + 1); };
57
+ const krId = (g) => { if (!g || !g.pillar) return ''; const pool = allGoals().filter((x) => goalWs(x) === goalWs(g)), objs = [...new Set(pool.map((x) => x.pillar).filter(Boolean))], same = pool.filter((x) => x.pillar === g.pillar); return 'KR ' + (objs.indexOf(g.pillar) + 1) + '.' + (same.indexOf(g) + 1); };
45
58
  /** The cozy select: a native select drawn as the design's field, with a quiet chevron instead of the system arrow. */
46
59
  const csel = (inner, cls = '') => `<span class="ins-sel${cls}">${inner}<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 10l5 5 5-5"/></svg></span>`;
47
60
 
48
- /* ── the Viewer card and the "Waiting for design" card (another module adds them; this page feature-detects both) ─────────────────── */
49
- function waitHtml(feature) {
50
- return `<div class="ins-wait"><b>Waiting for design</b><p>${esc(feature)} has no agreed design yet, so this page does not draw it. Nothing here changes a record.</p></div>`;
51
- }
61
+ /* ── the Viewer card (pm/cozy-viewer.js, feature-detected; this page's side panel is the fallback) ──────────────────────────────── */
52
62
  function viewer(o) {
53
63
  const V = window.czViewer;
54
- if (V && typeof V.open === 'function') { V.open({ kind: o.kind, title: o.title, icon: o.icon, render: (el) => { const w = document.createElement('div'); w.className = 'ins-vbody'; el.appendChild(w); o.render(w); } }); return; }
64
+ if (V && typeof V.open === 'function') { V.open({ kind: o.kind, title: o.title, icon: o.icon, id: o.id, onClose: o.onClose, render: (el) => { const w = document.createElement('div'); w.className = 'ins-vbody'; el.appendChild(w); o.render(w); } }); return; }
55
65
  openSide({ kind: 'view', eye: o.eye || '', title: o.title, body: '', note: '', go: null });
56
66
  o.render($('#sideBody'));
57
67
  }
58
- function placeholder(feature) {
59
- const V = window.czViewer;
60
- if (V && typeof V.placeholder === 'function') { V.placeholder(feature, { kind: 'Insights' }); return; }
61
- viewer({ kind: 'placeholder', title: feature, icon: 'wait', eye: 'Waiting for design', render: (el) => {
62
- if (typeof window.czPlaceholder === 'function') window.czPlaceholder(el, feature); else el.innerHTML = waitHtml(feature);
63
- } });
64
- }
68
+ const isPhone = () => typeof matchMedia === 'function' && matchMedia('(max-width: 760px)').matches;
69
+ const closeViewer = () => { if (window.czViewer && typeof window.czViewer.close === 'function') window.czViewer.close(); else closeSide(); };
70
+ // The floating Viewer covers the right of the page on a desktop, so the page makes room for it while it is open.
71
+ document.addEventListener('cz-viewer', (e) => document.body.classList.toggle('ins-vwon', !!(e.detail && e.detail.open)));
65
72
 
66
73
  /* ── small menus: one open at a time, Escape and an outside press close it ─────────────────────────────────────────────────────── */
67
74
  const MENUS = [['#prodPick', '#prodMenu'], ['#viewChip', '#viewMenu'], ['#perChip', '#perMenu'], ['#filtB', '#filtMenu'], ['#newB', '#newMenu'], ['#moreB', '#moreMenu']];
68
75
  function menu(btn, box, open) { $(box).hidden = !open; $(btn).setAttribute('aria-expanded', String(open)); }
69
- function closeMenus(except) { for (const [b, m] of MENUS) if (m !== except && !$(m).hidden) menu(b, m, false); const cm = $('#chMenu'); if (cm) cm.hidden = true; }
76
+ function closeMenus(except) { for (const [b, m] of MENUS) if (m !== except && !$(m).hidden) menu(b, m, false); const cm = $('#chMenu'); if (cm) cm.hidden = true; if (!$('#findRow').hidden) closeFind(false); }
70
77
  for (const [b, m] of MENUS) {
71
78
  $(b).addEventListener('click', (e) => {
72
79
  e.stopPropagation(); const open = $(m).hidden; closeMenus(m); menu(b, m, open);
@@ -75,10 +82,15 @@ for (const [b, m] of MENUS) {
75
82
  }
76
83
  document.addEventListener('click', (e) => {
77
84
  for (const [b, m] of MENUS) if (!$(m).hidden && !e.target.closest(m) && !e.target.closest(b)) menu(b, m, false);
85
+ if (!$('#findRow').hidden && !e.target.closest('#findRow, #findB')) closeFind(false);
86
+ const tp = $('#tgPop'); if (tp && !e.target.closest('#tgPop, [data-tile]')) closeTarget();
78
87
  const om = $('#ngObjMenu'); if (om && !om.hidden && !e.target.closest('#ngObjMenu, #ngObjB')) { om.hidden = true; $('#ngObjB').setAttribute('aria-expanded', 'false'); }
79
88
  });
80
89
  document.addEventListener('keydown', (e) => {
81
90
  if (e.key !== 'Escape') return;
91
+ if (!$('#findRow').hidden) { closeFind(true); return; }
92
+ if ($('#tgPop')) { closeTarget(true); return; }
93
+ if ($('#repSheet')) { closeSheet(); return; }
82
94
  for (const [b, m] of MENUS) if (!$(m).hidden) { menu(b, m, false); $(b).focus(); return; }
83
95
  const om = $('#ngObjMenu'); if (om && !om.hidden) { om.hidden = true; $('#ngObjB').setAttribute('aria-expanded', 'false'); $('#ngObjB').focus(); return; }
84
96
  if (!$('#side').hidden) closeSide();
@@ -137,23 +149,38 @@ $('#perMenu').addEventListener('click', (e) => {
137
149
  per = periods().find((p) => p.key === b.dataset.per); closeMenus(); redraw();
138
150
  });
139
151
 
140
- /* ── the bar: product, tabs, view, filter, find, ⋯ ─────────────────────────────────────────────────────────────────────────────── */
152
+ /* ── the bar: product, tabs, view, filter, find, ⋯ (IsMenus) ──────────────────────────────────────────────────────────────────── */
153
+ const TRENDS = 'trends'; // the Delivery trends view (IsTarget): the six tiles on their own, three to a row
141
154
  const curDash = () => M.dashboards.find((d) => d.id === dash) || M.dashboards[0];
142
155
  const dashName = (D) => (D.id === 'all' ? 'All goals' : D.name);
156
+ const nGoals = (k) => k + (k === 1 ? ' goal' : ' goals');
143
157
  function drawBar() {
144
- $('#prodName').textContent = M.board.name || 'Insights';
158
+ $('#prodName').textContent = PF ? 'Portfolio' : M.board.name || 'Insights';
145
159
  const boards = M.board.switcher || [];
146
- $('#prodMenu').innerHTML = boards.length ? boards.map((b) => `<button type="button" role="menuitemradio" aria-checked="${b.id === M.board.id && b.ws === M.board.ws}" data-ws="${esc(b.ws)}" data-board="${esc(b.id)}">${esc(b.name)}</button>`).join('')
147
- : '<p class="note ins-mnote">One product is registered.</p>';
148
- $('#nGoals').textContent = String(goalsShown().length);
160
+ /* the product picker: each product with its goal count, then Portfolio, which rolls every product's goals up */
161
+ $('#prodMenu').innerHTML = '<p class="ins-mh">Product</p>' + (boards.length ? boards.map((b) => `<button type="button" role="menuitemradio" aria-checked="${!PF && b.id === M.board.id && b.ws === M.board.ws}" data-ws="${esc(b.ws)}" data-board="${esc(b.id)}">${esc(b.name)}<span class="k">${b.goals != null ? esc(nGoals(b.goals)) : ''}</span></button>`).join('')
162
+ : '<p class="note ins-mnote">One product is registered.</p>')
163
+ + (boards.length > 1 ? `<div class="ins-hr"></div><button type="button" role="menuitemradio" aria-checked="${!!PF}" data-portfolio>Portfolio · all products</button><p class="note ins-mnote">Portfolio rolls goals up across products.</p>` : '');
164
+ $('#nGoals').textContent = String(dash === TRENDS ? 0 : goalsShown().length);
149
165
  $('#nOutcomes').textContent = String(outcomesShown().length);
150
166
  const D = curDash();
151
- $('#viewName').textContent = dashName(D);
152
- $('#viewMenu').innerHTML = M.dashboards.map((d) => `<button type="button" role="menuitemradio" aria-checked="${d.id === D.id}" data-view="${esc(d.id)}">${esc(dashName(d))}<small>${d.id === 'all' ? 'Every goal and budget' : d.saved ? 'Saved dashboard · ' + d.charts.length + (d.charts.length === 1 ? ' goal' : ' goals') : 'Objective'}${M.pinned === d.id ? ' · pinned' : ''}</small></button>`).join('');
167
+ $('#viewName').textContent = dash === TRENDS ? 'Delivery trends' : dashName(D);
168
+ /* the Dashboard menu: every view, the default one marked; Delivery trends; then New dashboard */
169
+ $('#viewMenu').innerHTML = '<p class="ins-mh">Dashboard</p>' + M.dashboards.map((d) => `<button type="button" role="menuitemradio" aria-checked="${dash !== TRENDS && d.id === D.id}" data-view="${esc(d.id)}" title="${esc(d.id === 'all' ? 'Every goal and budget' : d.saved ? 'Saved dashboard · ' + nGoals(d.charts.length) : 'The goals of one objective')}">${esc(dashName(d))}<span class="k">${M.pinned === d.id ? 'default' : ''}</span></button>`).join('')
170
+ + (M.board.ws ? `<button type="button" role="menuitemradio" aria-checked="${dash === TRENDS}" data-view="${TRENDS}" title="The Board’s measures, with their targets">Delivery trends</button>` : '')
171
+ + `<div class="ins-hr"></div><button type="button" role="menuitem" data-newdash>${SV(I.plus)}New dashboard</button>`;
153
172
  drawPeriod(); drawFilter();
154
173
  }
155
- $('#prodMenu').addEventListener('click', (e) => { const b = e.target.closest('[data-board]'); if (!b) return; location.assign('/premium-insights.html?ws=' + encodeURIComponent(b.dataset.ws) + '&board=' + encodeURIComponent(b.dataset.board)); });
156
- $('#viewMenu').addEventListener('click', (e) => { const b = e.target.closest('[data-view]'); if (!b) return; closeMenus(); setView(b.dataset.view); });
174
+ $('#prodMenu').addEventListener('click', (e) => {
175
+ if (e.target.closest('[data-portfolio]')) { closeMenus(); if (!PF) openPortfolio(); return; }
176
+ const b = e.target.closest('[data-board]'); if (!b) return;
177
+ if (PF && b.dataset.ws === M.board.ws && b.dataset.board === M.board.id) { closeMenus(); PF = null; redraw(); return; }
178
+ location.assign('/premium-insights.html?ws=' + encodeURIComponent(b.dataset.ws) + '&board=' + encodeURIComponent(b.dataset.board));
179
+ });
180
+ $('#viewMenu').addEventListener('click', (e) => {
181
+ if (e.target.closest('[data-newdash]')) { closeMenus(); openNewDash(); return; }
182
+ const b = e.target.closest('[data-view]'); if (!b) return; closeMenus(); setView(b.dataset.view);
183
+ });
157
184
  const setQ = (o) => { const q = new URLSearchParams(location.search); for (const [k, v] of Object.entries(o)) { if (v == null) q.delete(k); else q.set(k, v); } const s = q.toString(); return location.pathname + (s ? '?' + s : ''); };
158
185
  function setTab(t) {
159
186
  tab = t;
@@ -172,38 +199,94 @@ $('.ins-tabs').addEventListener('keydown', (e) => {
172
199
  });
173
200
  function setView(id) { dash = id; setTab('goals'); redraw(); }
174
201
 
175
- const FILT_HEAD = { obj: 'Objective', owner: 'Owner', type: 'Type', lane: 'Lane' };
176
- const noFilter = () => Object.values(filt).every((v) => v === null);
202
+ /* Portfolio: the goals of every product, each product's model read once through GET /api/insights-premium, grouped by product. A goal of another
203
+ * product keeps its own workspace, so a reading added to it goes there. Budgets, Outcomes and Library stay the open product's. */
204
+ async function openPortfolio() {
205
+ const seen = new Set([M.board.ws]), others = (M.board.switcher || []).filter((b) => !seen.has(b.ws) && seen.add(b.ws));
206
+ toast('Reading every product’s goals.');
207
+ const got = await Promise.all(others.map(async (b) => { try { const r = await (await fetch('/api/insights-premium?ws=' + encodeURIComponent(b.ws) + '&board=' + encodeURIComponent(b.id), { credentials: 'same-origin' })).json(); return r && r.ok ? r.model : null; } catch { return null; } }));
208
+ const goals = M.goals.map((g) => Object.assign({}, g, { prod: M.board.name, ws: M.board.ws, rid: g.id })), charts = {}, products = [M.board.name], unread = [];
209
+ got.forEach((m, i) => {
210
+ if (!m) { unread.push(others[i].name); return; }
211
+ products.push(m.board.name || others[i].name);
212
+ for (const c of m.charts || []) charts[m.board.ws + '~' + c.key] = c;
213
+ for (const g of m.goals || []) goals.push(Object.assign({}, g, { id: m.board.ws + '~' + g.id, rid: g.id, key: g.key ? m.board.ws + '~' + g.key : null, prod: m.board.name || others[i].name, ws: m.board.ws, moves: g.moves || [] }));
214
+ });
215
+ PF = { goals, charts, products, unread };
216
+ dash = 'all'; setTab('goals'); redraw();
217
+ if (unread.length) toast('Not read: ' + unread.join(', ') + '. Their goals are not in Portfolio.');
218
+ }
219
+ const allGoals = () => (PF ? PF.goals : M.goals);
220
+ const goalById = (id) => allGoals().find((x) => x.id === id) || null;
221
+ const goalWs = (g) => (g && g.ws) || M.board.ws;
222
+ const goalRid = (g) => (g && g.rid) || (g && g.id);
223
+
224
+ /* Filter (IsMenus): status, owner and kind, as chips. The chips of one group add up; the groups narrow each other. */
225
+ const FILT_HEAD = { status: 'Status', owner: 'Owner', kind: 'Kind' };
226
+ const STATUS = [['off', 'Off track'], ['on', 'On track'], ['hit', 'Hit'], ['none', 'No readings']];
227
+ const KINDS = [['goals', 'Goals'], ['budgets', 'Health budgets']];
228
+ const noFilter = () => Object.values(filt).every((v) => !v.length);
229
+ const clearFilter = () => { filt = { status: [], owner: [], kind: [] }; };
230
+ function statusOf(g) {
231
+ if (!g.readings) return 'none';
232
+ if (g.pace && (g.pace.head === 'Reached' || g.pace.head === 'Done')) return 'hit';
233
+ const t = g.pace && g.pace.tone !== 'q' ? g.pace.tone : g.tone;
234
+ return t === 'late' || t === 'red' ? 'off' : t === 'ok' ? 'on' : null;
235
+ }
236
+ const budgetStatus = (b) => (!b.reading || b.reading.share === null ? 'none' : b.reading.over ? 'off' : 'on');
237
+ const ownersOf = (g) => [g.owner, ...(g.moves || []).map((m) => m.owner)].filter(Boolean);
177
238
  function filterValues() {
178
- const moves = M.goals.flatMap((g) => g.moves);
179
- return {
180
- obj: [...new Set(M.goals.map((g) => g.pillar || ''))].map((v) => [v, v || 'No objective']),
181
- owner: [...new Set(moves.map((m) => m.owner).filter(Boolean))].sort().map((v) => [v, v]),
182
- type: [...new Set(M.goals.map((g) => g.type))].map((v) => [v, v]),
183
- lane: [...new Set(moves.map((m) => m.lane).filter(Boolean))].sort().map((v) => [v, v]),
184
- };
239
+ return { status: STATUS, owner: [...new Set(allGoals().flatMap(ownersOf).concat((M.budgets || []).flatMap((b) => b.moves.map((m) => m.owner)).filter(Boolean)))].sort().map((v) => [v, v]), kind: KINDS };
185
240
  }
186
241
  function drawFilter() {
187
242
  const V = filterValues();
188
- const row = (k, v, label) => `<button type="button" role="menuitemcheckbox" aria-checked="${filt[k] === v}" data-fk="${k}" data-fv="${esc(v)}">${filt[k] === v ? SV(I.chk) : '<i class="ins-ck"></i>'}<span>${esc(label)}</span></button>`;
189
- $('#filtMenu').innerHTML = Object.keys(FILT_HEAD).map((k) => `<p class="ins-mh">${FILT_HEAD[k]}</p>` + (V[k].length ? V[k].map(([v, l]) => row(k, v, l)).join('') : `<p class="note ins-mnote">${k === 'owner' ? 'No initiative that moves a goal names an owner.' : k === 'lane' ? 'No initiative that moves a goal names a lane.' : 'None'}</p>`)).join('')
190
- + (noFilter() ? '' : '<button type="button" data-fclr>Clear the filter</button>');
243
+ const chip = (k, v, label) => `<button type="button" class="cz-chip${filt[k].includes(v) ? ' on' : ''}" aria-pressed="${filt[k].includes(v)}" data-fk="${k}" data-fv="${esc(v)}">${esc(label)}</button>`;
244
+ $('#filtMenu').innerHTML = Object.keys(FILT_HEAD).map((k) => `<p class="ins-mh">${FILT_HEAD[k]}</p><div class="ins-fchips">` + (V[k].length ? V[k].map(([v, l]) => chip(k, v, l)).join('') : '<span class="note">No goal or the work that moves it names an owner.</span>') + '</div>').join('')
245
+ + (noFilter() ? '' : '<button type="button" class="ins-fclr" data-fclr>Clear the filter</button>');
191
246
  $('#filtDot').hidden = noFilter();
192
247
  }
193
248
  $('#filtMenu').addEventListener('click', (e) => {
194
- if (e.target.closest('[data-fclr]')) { filt = { obj: null, owner: null, type: null, lane: null }; closeMenus(); redraw(); return; }
249
+ e.stopPropagation();
250
+ if (e.target.closest('[data-fclr]')) { clearFilter(); closeMenus(); redraw(); return; }
195
251
  const b = e.target.closest('[data-fk]'); if (!b) return;
196
- filt[b.dataset.fk] = filt[b.dataset.fk] === b.dataset.fv ? null : b.dataset.fv; redraw(); menu('#filtB', '#filtMenu', true);
252
+ const L = filt[b.dataset.fk], v = b.dataset.fv; filt[b.dataset.fk] = L.includes(v) ? L.filter((x) => x !== v) : L.concat(v);
253
+ redraw(); menu('#filtB', '#filtMenu', true);
197
254
  });
198
- $('#findB').addEventListener('click', () => { const open = $('#findRow').hidden; $('#findRow').hidden = !open; $('#findB').setAttribute('aria-expanded', String(open)); if (open) $('#findIn').focus(); });
199
- $('#findIn').addEventListener('input', () => { find = $('#findIn').value.trim().toLowerCase(); redraw(); });
200
- $('#findX').addEventListener('click', () => { $('#findIn').value = ''; find = ''; $('#findRow').hidden = true; $('#findB').setAttribute('aria-expanded', 'false'); redraw(); $('#findB').focus(); });
255
+
256
+ /* Find (IsMenus): goals, reports and dashboards that hold the words, with the words marked. While it has words the tables narrow too. */
257
+ function openFind() { closeMenus(); $('#findRow').hidden = false; $('#findB').setAttribute('aria-expanded', 'true'); drawFind(); $('#findIn').focus(); }
258
+ function closeFind(focus) { $('#findIn').value = ''; const had = !!find; find = ''; $('#findRow').hidden = true; $('#findB').setAttribute('aria-expanded', 'false'); if (had) redraw(); if (focus) $('#findB').focus(); }
259
+ $('#findB').addEventListener('click', (e) => { e.stopPropagation(); if ($('#findRow').hidden) openFind(); else closeFind(true); });
260
+ $('#findIn').addEventListener('input', () => { find = $('#findIn').value.trim().toLowerCase(); redraw(); drawFind(); });
261
+ $('#findIn').addEventListener('keydown', (e) => { if (e.key === 'Enter') { const f = $('#findRes [data-fo]'); if (f) { e.preventDefault(); f.click(); } } });
262
+ $('#findX').addEventListener('click', () => closeFind(true));
201
263
  const hit = (...s) => !find || s.some((x) => String(x || '').toLowerCase().includes(find));
264
+ const markHtml = (t) => { const s = String(t || ''), i = find ? s.toLowerCase().indexOf(find) : -1; return i < 0 ? esc(s) : esc(s.slice(0, i)) + '<mark>' + esc(s.slice(i, i + find.length)) + '</mark>' + esc(s.slice(i + find.length)); };
265
+ function drawFind() {
266
+ if (!M) return;
267
+ if (!find) { $('#findRes').innerHTML = '<p class="note ins-mnote">Type a few letters of a goal, a report or a dashboard.</p>'; return; }
268
+ const row = (attr, name, sub) => `<button type="button" role="option" class="ins-fo" ${attr}><span><span>${markHtml(name)}</span><small>${esc(sub)}</small></span></button>`;
269
+ const G = allGoals().filter((g) => hit(g.title, g.pillar)).slice(0, 5).map((g) => row(`data-fo="goal" data-id="${esc(g.id)}"`, (krId(g) ? krId(g) + ' · ' : '') + g.title, [PF ? g.prod : dashName(curDash()), g.nowTxt ? g.nowTxt + (g.targetTxt ? ' of ' + g.targetTxt : '') : 'no reading yet'].join(' · ')));
270
+ const R = reportGroups().filter((x) => hit(x.x.name)).slice(0, 5).map((x) => row(`data-fo="${x.kind}" data-id="${esc(x.x.id)}"`, x.x.name, repState(x).pill[1]))
271
+ .concat((M.reports.asks || []).filter((a) => hit(a.text, a.proposal && a.proposal.name)).slice(0, 3).map((a) => row(`data-fo="ask" data-id="${esc(a.id)}"`, a.proposal && a.proposal.name ? a.proposal.name : a.text, ASKST[a.state][2])));
272
+ const D = M.dashboards.filter((d) => hit(dashName(d))).slice(0, 5).map((d) => row(`data-fo="dash" data-id="${esc(d.id)}"`, dashName(d), d.saved ? nGoals(d.charts.length) : d.id === 'all' ? 'Every goal and budget' : 'One objective'));
273
+ const grp = (h, L) => (L.length ? `<p class="ins-mh">${h}</p>` + L.join('') : '');
274
+ $('#findRes').innerHTML = grp('Goals', G) + grp('Reports', R) + grp('Dashboards', D) || `<p class="note ins-mnote">Nothing holds “${esc(find)}”.</p>`;
275
+ }
276
+ $('#findRes').addEventListener('click', (e) => {
277
+ const b = e.target.closest('[data-fo]'); if (!b) return; e.stopPropagation();
278
+ const k = b.dataset.fo, id = b.dataset.id; closeFind(false);
279
+ if (k === 'goal') openGoalDetail(id);
280
+ else if (k === 'dash') setView(id);
281
+ else if (k === 'ask') { setTab('library'); openRequest(id); }
282
+ else { setTab('library'); openReportRow(k, id); }
283
+ });
202
284
 
203
- /* ⋯: Sources, Export (no route yet) and About these numbers, each in the Viewer card */
285
+ /* ⋯ (IsMenus): Sources with how long ago the page read them, Export as CSV and About these numbers, each in the Viewer card */
286
+ $('#moreB').addEventListener('click', () => { const m = Math.round((Date.now() - loadedAt) / 60000); $('#srcAge').textContent = !loadedAt ? '' : m < 1 ? 'read just now' : 'read ' + m + ' min ago'; });
204
287
  $('#moreMenu').addEventListener('click', (e) => {
205
288
  const b = e.target.closest('[data-more]'); if (!b || b.disabled) return; closeMenus();
206
- if (b.dataset.more === 'sources') viewer({ kind: 'Insights', title: 'Sources', icon: 'list', eye: 'What this page reads', render: (el) => { el.innerHTML = sourcesHtml(); } });
289
+ if (b.dataset.more === 'sources') viewer({ kind: 'Insights', title: 'Sources', icon: 'source', eye: 'What this page reads', render: (el) => { el.innerHTML = sourcesHtml(); } });
207
290
  else if (b.dataset.more === 'export') location.assign('/api/insights-records/export?' + wsQ() + (M.board.id ? 'board=' + encodeURIComponent(M.board.id) : ''));
208
291
  else if (b.dataset.more === 'about') viewer({ kind: 'Insights', title: 'About these numbers', icon: 'info', eye: 'Insights', render: (el) => { el.innerHTML = ABOUT; } });
209
292
  });
@@ -230,6 +313,7 @@ function drawStrip() {
230
313
  const I0 = M.insight, G = goalsShown();
231
314
  const behind = G.filter((g) => g.tone === 'late' || g.tone === 'red').length;
232
315
  $('#insEye').textContent = per && per.gone && per.key !== 'c' ? per.gone + ' of ' + per.total + ' days gone in ' + per.short + '.' : G.length + (G.length === 1 ? ' goal' : ' goals') + (behind ? ', ' + behind + ' behind.' : '.');
316
+ if (PF) { $('#brief').textContent = 'Portfolio: ' + nGoals(G.length) + ' across ' + PF.products.length + (PF.products.length === 1 ? ' product' : ' products') + (behind ? ', ' + behind + ' behind.' : '.'); $('#insWhy').textContent = 'The insight under it is read one product at a time.'; $('#askWhy').href = homeAsk('insights', 'Which product needs me most this quarter?'); $('#askWhy').hidden = false; return; }
233
317
  $('#brief').textContent = I0.text;
234
318
  $('#insWhy').textContent = I0.none ? '' : I0.why || '';
235
319
  $('#askWhy').href = homeAsk('insights', I0.none ? 'Why is there no insight on my goals yet?' : 'Why? ' + I0.text);
@@ -238,11 +322,13 @@ function drawStrip() {
238
322
 
239
323
  /* ── Goals (AgInsGoals) ─────────────────────────────────────────────────────────────────────────────────────────────────────────── */
240
324
  const COLS = 'ins-cols';
241
- function moveHit(g) { return (filt.owner === null || g.moves.some((m) => m.owner === filt.owner)) && (filt.lane === null || g.moves.some((m) => m.lane === filt.lane)); }
325
+ const ownerHit = (L) => !filt.owner.length || L.some((o) => filt.owner.includes(o));
242
326
  function goalsShown() {
243
- const D = curDash(), ids = D.saved ? D.charts : null;
244
- const L = M.goals.filter((g) => inPer(g) && (!ids || ids.includes(g.id)) && (!D.id.startsWith('p:') || g.pillar === D.name)
245
- && (filt.obj === null || (g.pillar || '') === filt.obj) && (filt.type === null || g.type === filt.type) && moveHit(g) && hit(g.title, g.pillar, ...g.moves.map((m) => m.title)));
327
+ if (dash === TRENDS) return [];
328
+ if (filt.kind.length && !filt.kind.includes('goals')) return [];
329
+ const D = PF ? M.dashboards[0] : curDash(), ids = D.saved ? D.charts : null;
330
+ const L = allGoals().filter((g) => inPer(g) && (!ids || ids.includes(g.id)) && (!D.id.startsWith('p:') || g.pillar === D.name)
331
+ && (!filt.status.length || filt.status.includes(statusOf(g))) && ownerHit(ownersOf(g)) && hit(g.title, g.pillar, ...g.moves.map((m) => m.title)));
246
332
  return ids ? L.sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id)) : L;
247
333
  }
248
334
  const TRACK_TONE = { late: 'late', 'at risk': 'risk', done: 'ok', 'on track': 'ok', 'on hold': 'q' };
@@ -273,7 +359,7 @@ function barHtml(g, cls = '') {
273
359
  /** The so-far sparkline: the readings at their dates across the goal's span, the target dashed, and the pace carried to the date, dashed. */
274
360
  function sparkHtml(g, w = 210, h = 40) {
275
361
  const c = g.key ? byKey(g.key) : null;
276
- if (!c) return `<span class="note">${esc(g.readings ? 'One reading, no series yet' : 'No reading yet')}</span>`;
362
+ if (!c) return g.readings ? `<span class="ins-one"><span class="note">${g.readings === 1 ? '1 reading' : g.readings + ' readings'}</span><span class="cz-pill ins-dash">No trend yet</span></span>` : '<span class="note">No reading yet</span>'; // IsMenus: the one value, never a flat line
277
363
  const t0 = day(c.pts[0].at), tl = day(c.pts[c.pts.length - 1].at), t1 = Math.max(tl, day(g.byAt) || tl);
278
364
  const ys = c.pts.map((p) => p.v).concat(g.target !== null ? [g.target] : [], g.proj ? [g.proj.atDue] : []), lo = Math.min(...ys), hi = Math.max(...ys), rg = hi - lo || 1;
279
365
  const x = (t) => 5 + (t1 > t0 ? (t - t0) / (t1 - t0) : 1) * (w - 10), y = (v) => 4 + (1 - (v - lo) / rg) * (h - 8);
@@ -348,71 +434,155 @@ const GRP_PILL = (L) => {
348
434
  };
349
435
  function drawGoals() {
350
436
  const G = goalsShown(), T = $('#goalTbl');
437
+ document.body.classList.toggle('ins-trv', dash === TRENDS);
438
+ if (dash === TRENDS) { T.innerHTML = bmHtml(true); drawCards([]); $('#goalCards').innerHTML = ''; return; }
351
439
  const head = `<div class="ins-tr ins-th ${COLS}" role="row"><div role="columnheader">Goal <span>${G.length} · in ${esc(per ? per.label : '')}</span></div><div role="columnheader">Now, of target <span class="ins-lg"><span><i class="ins-tdk"></i>today</span></span></div><div role="columnheader">So far</div><div role="columnheader">By its date</div><div role="columnheader" class="ins-mvh">Moved by <span class="ins-lg"><span><i class="ins-trk"><i class="k"></i></i>Skipped</span><span><i class="ins-trk"><i class="p m"></i></i>Milestone</span></span></div></div>`;
352
440
  const D = curDash();
353
441
  if (!M.goals.length) {
354
442
  T.innerHTML = head + '<div class="ins-empty"><b>No goal is recorded for this workspace.</b> A goal is a KR metric with a target and a date. Press New, then New goal.</div>' + budgetsHtml(D) + bmHtml();
355
443
  drawCards([]); return;
356
444
  }
357
- const by = new Map(); for (const g of G) { const k = g.pillar || ''; if (!by.has(k)) by.set(k, []); by.get(k).push(g); }
445
+ /* by objective; Portfolio groups by product, each product's objectives said in its rows */
446
+ const keyOf = (g) => (PF ? g.prod : g.pillar || '');
447
+ const by = new Map(); for (const g of G) { const k = keyOf(g); if (!by.has(k)) by.set(k, []); by.get(k).push(g); }
358
448
  const objs = [...new Set(M.goals.map((g) => g.pillar || ''))];
359
- const groups = [...by.entries()].map(([k, L]) => `<div class="ins-grp" role="row"><span role="cell">${k ? 'Objective ' + (objs.indexOf(k) + 1) + ' · ' + esc(k) : 'No objective'}</span> <span class="q">${esc(per ? per.label : '')}</span>${GRP_PILL(L)}</div>` + L.map(goalRow).join('')).join('');
449
+ const head1 = (k) => (PF ? esc(k || 'A product') : k ? 'Objective ' + (objs.indexOf(k) + 1) + ' · ' + esc(k) : 'No objective');
450
+ const groups = [...by.entries()].map(([k, L]) => `<div class="ins-grp" role="row"><span role="cell">${head1(k)}</span> <span class="q">${esc(per ? per.label : '')}</span>${GRP_PILL(L)}</div>` + L.map(goalRow).join('')).join('');
360
451
  T.innerHTML = head + (G.length ? groups : `<div class="ins-empty">No goal matches${find ? ' “' + esc(find) + '”' : ''}${noFilter() ? '' : ' this filter'} in ${esc(per.label)}. <button type="button" class="lk" id="goalsAll">Show every goal</button></div>`) + budgetsHtml(D) + bmHtml();
361
452
  drawCards(G);
362
453
  }
363
454
  function budgetsHtml(D) {
364
- if (D.saved || D.id.startsWith('p:') || !M.initiativesRead || filt.obj !== null || (filt.type !== null && filt.type !== 'Stay within')) return '';
365
- const B = (M.budgets || []).filter((b) => hit(b.title, ...b.moves.map((m) => m.title)) && (filt.owner === null || b.moves.some((m) => m.owner === filt.owner)) && (filt.lane === null || b.moves.some((m) => m.lane === filt.lane)));
455
+ if (PF || D.saved || D.id.startsWith('p:') || !M.initiativesRead || (filt.kind.length && !filt.kind.includes('budgets'))) return '';
456
+ const B = (M.budgets || []).filter((b) => hit(b.title, ...b.moves.map((m) => m.title)) && ownerHit(b.moves.map((m) => m.owner).filter(Boolean)) && (!filt.status.length || filt.status.includes(budgetStatus(b))));
366
457
  return '<div class="ins-grp" role="row"><span role="cell">Health budgets</span> <span class="q">always on, judged every week</span></div>'
367
458
  + (B.length ? B.map(budgetRow).join('') : '<div class="ins-empty ins-sm2">No health budget is declared and no initiative anchors to one.</div>');
368
459
  }
369
460
  $('#goalTbl').addEventListener('click', (e) => {
370
- if (e.target.closest('#goalsAll')) { find = ''; $('#findIn').value = ''; filt = { obj: null, owner: null, type: null, lane: null }; per = periods()[3]; redraw(); return; }
461
+ if (e.target.closest('#goalsAll')) { find = ''; $('#findIn').value = ''; clearFilter(); per = periods()[3]; redraw(); return; }
371
462
  if (e.target.closest('a')) return;
372
- const tile = e.target.closest('[data-tile]'); if (tile) { openTarget(tile.dataset.tile); return; }
463
+ const tile = e.target.closest('[data-tile]'); if (tile) { if (tgOpen === tile.dataset.tile) closeTarget(true); else openTarget(tile.dataset.tile); return; }
373
464
  const bu = e.target.closest('[data-budget]'); if (bu) { openBudget(bu.dataset.budget); return; }
374
465
  const r = e.target.closest('[data-goal]'); if (r) pressGoal(r.dataset.goal);
375
466
  });
376
467
  $('#goalTbl').addEventListener('keydown', (e) => { if (e.key !== 'Enter' && e.key !== ' ') return; const r = e.target.closest && e.target.closest('.ins-row, [data-tile]'); if (!r || e.target !== r) return; e.preventDefault(); r.click(); });
377
- /** A goal press: picks it while New dashboard is open; opens Edit chart on a saved dashboard (AgInsChart); otherwise the goal detail waits for its design. */
468
+ /** A goal press: picks it while New dashboard is open; opens Edit chart on a saved dashboard (AgInsChart); otherwise the goal's detail (IsGoal). */
378
469
  function pressGoal(id) {
379
470
  if (selecting) { picked = picked.includes(id) ? picked.filter((x) => x !== id) : picked.concat(id); drawGoals(); drawDashSide(); return; }
380
471
  const D = curDash();
381
472
  if (D.saved) openChartEdit(id, D); else openGoalDetail(id);
382
473
  }
383
- /* a goal's detail and readings: no agreed design, so a plain list of its readings, a form to add one, and a Done-or-not goal's steps to tick */
384
- function openGoalDetail(id) {
385
- const g = M.goals.find((x) => x.id === id); if (!g) return;
386
- viewer({ kind: 'Goal', title: g.title, icon: 'goal', render: (el) => {
387
- const steps = g.type === 'Done or not' && g.steps && g.steps.length;
388
- const facts = [['Type', g.type], ['Now', g.nowTxt || 'no reading'], ['Target', g.targetTxt ? g.targetTxt + (g.byAt ? ' by ' + md(day(g.byAt)) : '') : 'none'], ['By its date', g.pace.head + (g.pace.sub ? ' · ' + g.pace.sub : '')],
389
- g.owner ? ['Owner', g.owner] : null, g.guardrail ? ['Guardrail', g.guardrail] : null, g.source ? ['Readings from', SRC_NAME[g.source] || g.source] : null].filter(Boolean);
390
- el.innerHTML = waitMark('A goal’s detail and readings') + `<dl class="ins-kv">${facts.map(([a, b]) => `<dt>${esc(a)}</dt><dd>${esc(b)}</dd>`).join('')}</dl>`
391
- + (steps ? `<form class="ins-mf" data-stf><p class="ins-fl">Steps</p>${g.steps.map((x, i) => `<label class="ins-ck2"><input type="checkbox" name="s${i}"${x.done ? ' checked' : ''}> ${esc(x.text)}</label>`).join('')}<div class="ins-mact"><button type="submit" class="ins-primary">Save steps</button><span class="note" data-msg></span></div></form>` : '')
392
- + `<p class="ins-fl">Readings <span class="q">${g.series.length}</span></p>` + (g.series.length ? `<ul class="ins-rd">${g.series.slice().reverse().map((r) => `<li><span>${esc(md(day(r.at)) + ' ' + r.at.slice(0, 4))}</span><b>${esc(String(r.v) + (g.unit ? (/^[A-Za-z]/.test(g.unit) ? ' ' + g.unit : g.unit) : ''))}</b></li>`).join('')}</ul>` : '<p class="note">No reading is recorded yet.</p>')
393
- + (steps ? '' : `<form class="ins-mf" data-rdf><p class="ins-fl">Add a reading</p><div class="ins-2"><label class="ins-fl">Date<input class="ins-inp" type="date" name="at" value="${esc(M.today || '')}"></label><label class="ins-fl">Value<input class="ins-inp" name="v" inputmode="decimal" maxlength="16"></label></div><div class="ins-mact"><button type="submit" class="ins-primary">Add reading</button><span class="note" data-msg></span></div></form>`);
394
- const done = async (res, msg, said) => { if (!res || res.ok !== true) { msg.textContent = (res && res.error) || 'It could not be saved. Nothing changed.'; return; } toast(said); await load(); openGoalDetail(id); };
395
- const rf = el.querySelector('[data-rdf]');
396
- if (rf) rf.addEventListener('submit', async (e) => {
397
- e.preventDefault(); const msg = rf.querySelector('[data-msg]'), v = rf.v.value.trim(), at = rf.at.value;
398
- if (!/^\d{4}-\d{2}-\d{2}$/.test(at) || v === '' || !Number.isFinite(Number(v))) { msg.textContent = 'Pick a date and type a number.'; return; }
399
- msg.textContent = 'Saving.'; done(await pmPost('/api/records/kr-metrics/reading', { ws: M.board.ws, rid: g.id, at, value: Number(v), why: 'Reading from Insights' }), msg, 'Added the reading.');
474
+ /* ── a goal's detail (IsGoal; IsPhone on a phone; the empty trend of IsMenus) ──────────────────────────────────────────────────── */
475
+ const nextMonday = () => { const t = today(), d = new Date(t).getUTCDay(); return t + ((8 - d) % 7 || 7) * DAY; };
476
+ /** Where the next reading comes from: a read source is read every Monday (New goal says so); a typed one waits for you. */
477
+ const nextReading = (g) => (!g.source || g.source === 'typed' ? 'You type its readings in.' : 'The next reading comes from ' + (SRC_NAME[g.source] || g.source) + ' on ' + md(nextMonday()) + '.');
478
+ const srcOf = (g) => (g.source ? SRC_NAME[g.source] || g.source : 'Recorded');
479
+ const unitV = (g, v) => { const u = String(g.unit || '').trim(); return String(v) + (u ? (/^[A-Za-z]/.test(u) ? ' ' + u : u) : ''); };
480
+ /** The ship dates of the work that moves a goal: a mark with the initiative's name where it falls inside the readings. */
481
+ const shipsOf = (g) => (g.moves || []).filter((r) => r.endAt && (r.idx >= 5 || r.status === 'done')).map((r) => ({ t: day(r.endAt), label: r.title + ' shipped' })).filter((x) => x.t !== null);
482
+ /** The goal's readings at their dates: the target dashed with its value, the pace dashed to its date, each reading a ring and the latest filled. */
483
+ function detailSvg(g, c, W = 490, H = 150) {
484
+ const pts = c.pts, t0 = day(pts[0].at), tl = day(pts[pts.length - 1].at), by = day(g.byAt);
485
+ const proj = g.proj && by !== null && by > tl ? { t: by, v: g.proj.atDue } : null, t1 = proj ? proj.t : tl;
486
+ const ys = pts.map((p) => p.v).concat(g.target !== null ? [g.target] : [], proj ? [proj.v] : []), lo = Math.min(...ys), hi = Math.max(...ys), rg = hi - lo || 1;
487
+ const x = (t) => 20 + (t1 > t0 ? (t - t0) / (t1 - t0) : 1) * (W - 40), y = (v) => 30 + (1 - (v - lo) / rg) * (H - 50), f = (n) => n.toFixed(1);
488
+ let out = `<path class="base" d="M0 ${H - 10}H${W}"/>`;
489
+ if (g.target !== null) { const ty = y(g.target); out += `<path class="tg" d="M0 ${f(ty)}H${W}"/><text class="tgl" x="4" y="${f(ty < 18 ? ty + 14 : ty - 6)}">Target ${esc(g.targetTxt)}</text>`; }
490
+ for (const s of shipsOf(g)) { if (s.t < t0 || s.t > t1) continue; const sx = x(s.t), end = sx > W - 160; out += `<path class="ship" d="M${f(sx)} 20V${H - 10}"/><text class="shipl" x="${f(end ? sx - 4 : sx + 4)}" y="${H - 14}"${end ? ' text-anchor="end"' : ''}>${esc(s.label)}</text>`; }
491
+ const L = pts.map((p) => f(x(day(p.at))) + ' ' + f(y(p.v))), last = L[L.length - 1];
492
+ out += `<path class="ln" d="M${L.join('L')}"/>` + (proj ? `<path class="pj" d="M${last}L${f(x(proj.t))} ${f(y(proj.v))}"/>` : '');
493
+ out += pts.map((p, i) => `<circle class="pt${i === pts.length - 1 ? ' now' : ''}" cx="${f(x(day(p.at)))}" cy="${f(y(p.v))}" r="4"/>`).join('');
494
+ const a = pts[0], z = pts[pts.length - 1];
495
+ return `<svg class="ins-gch" viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(g.title + ': readings from ' + a.txt + ' on ' + md(day(a.at)) + ' to ' + z.txt + ' on ' + md(day(z.at)) + (g.targetTxt ? ', target ' + g.targetTxt : ''))}">${out}</svg>`;
496
+ }
497
+ const emptyTrend = (g, add) => `<div class="ins-box ins-etr"><span>${g.readings ? 'A trend needs 2 readings.' : 'No reading yet. A trend needs 2 readings.'} ${esc(nextReading(g))}</span>${add ? '<button type="button" class="ins-btn sm" data-gx="add">Add a reading</button>' : ''}</div>`;
498
+ const dashSwitches = (g) => savedDash().map((D) => { const on = D.charts.includes(g.id); return `<div class="ins-trow"><span>${esc(D.name)}</span><button type="button" class="ins-tog${on ? ' on' : ''}" role="switch" aria-checked="${on}" aria-label="On ${esc(D.name)}" data-gx="dash" data-d="${esc(D.id)}"></button></div>`; }).join('')
499
+ || '<p class="note">No dashboard is saved yet. New dashboard makes one.</p>';
500
+ function goalDetailHtml(g, o) {
501
+ const c = g.key ? byKey(g.key) : null, phone = isPhone(), steps = g.type === 'Done or not' && g.steps && g.steps.length;
502
+ const tabs = [['read', 'Readings'], ['moved', 'Moved by']].concat(phone && o.own ? [['dash', 'Dashboards']] : []);
503
+ const bar = `<div class="ins-vbar" role="tablist" aria-label="${esc(g.title)}">${tabs.map(([k, l]) => `<button type="button" role="tab" class="ins-vtab${o.tab === k ? ' on' : ''}" aria-selected="${o.tab === k}" data-gt="${k}">${l}</button>`).join('')}`
504
+ + (o.own && M.goals.some((x) => x.id === g.id) ? `<button type="button" class="cz-ib sm ins-vedit" data-gx="chart" aria-label="Edit chart" title="Edit chart">${SV(I.pen)}</button>` : '') + '</div>';
505
+ const sub = [g.nowTxt ? g.nowTxt + ' now' : 'No reading yet', g.targetTxt ? g.targetTxt + (g.byAt ? ' by ' + md(day(g.byAt)) : '') : 'no target', g.source ? 'from ' + srcOf(g).toLowerCase() : ''].filter(Boolean).join(' · ');
506
+ const pace = g.pace ? (g.pace.head !== '—' ? g.pace.head + (g.pace.sub ? ', ' + g.pace.sub : '') : g.pace.sub) : '';
507
+ const sub2 = [PF ? g.prod : '', g.dirTxt, pace, g.owner ? 'owner ' + g.owner : '', g.guardrail].filter(Boolean).join(' · ');
508
+ const head = `<div class="ins-gh"><p class="ins-gsub">${esc(sub)}</p>${sub2 ? `<p class="note">${esc(sub2)}</p>` : ''}</div>`;
509
+ const chart = steps ? stepsHtml(g) : c ? detailSvg(g, c, phone ? 358 : 490, phone ? 120 : 150) : emptyTrend(g, !o.adding);
510
+ let body = '';
511
+ if (o.tab === 'moved') {
512
+ body = g.moves.length ? `<div class="ins-mvl">${g.moves.map((r) => initRow(r)).join('')}</div>` : `<p class="note">${M.initiativesRead ? 'No initiative anchors to it yet. An initiative moves it once its anchor names it.' : 'The initiatives are not read yet.'}</p>`;
513
+ } else if (o.tab === 'dash') {
514
+ body = '<p class="ins-lbl">On your dashboards</p>' + dashSwitches(g);
515
+ } else {
516
+ const R = g.series.slice().reverse(), shown = o.more ? R : R.slice(0, 3);
517
+ body = (R.length ? `<div class="ins-th2"><span>Reading</span><span>Value</span><span>Source</span></div>` + shown.map((r) => `<div class="ins-trow ins-rd3"><span>${esc(md(day(r.at)) + ' ' + r.at.slice(0, 4))}</span><b>${esc(unitV(g, r.v))}</b><span class="note">${esc(srcOf(g))}</span></div>`).join('')
518
+ + (R.length > shown.length ? `<button type="button" class="ins-btn sm ghost" data-gx="all">All ${R.length} readings</button>` : '') : '')
519
+ + (steps ? `<form class="ins-mf" data-stf><p class="ins-lbl">Steps</p>${g.steps.map((x, i) => `<label class="ins-ck2"><input type="checkbox" name="s${i}"${x.done ? ' checked' : ''}> ${esc(x.text)}</label>`).join('')}<div class="ins-mact"><button type="submit" class="ins-btn sm dark">Save steps</button><span class="note" data-msg role="status"></span></div></form>` : '')
520
+ + (!steps && o.adding ? `<form class="ins-mf ins-box" data-rdf><div class="ins-2"><label class="ins-fl">Date<input class="ins-inp" type="date" name="at" value="${esc(M.today || '')}"></label><label class="ins-fl">Value${g.unit ? ' (' + esc(g.unit) + ')' : ''}<input class="ins-inp" name="v" inputmode="decimal" maxlength="16"></label></div><div class="ins-mact"><button type="submit" class="ins-btn sm dark">Add reading</button><button type="button" class="ins-btn sm ghost" data-gx="cancel">Cancel</button><span class="note" data-msg role="status"></span></div></form>` : '')
521
+ + `<div class="ins-acts">${!steps && !o.adding && (c || !phone) ? `<button type="button" class="ins-btn sm${phone ? ' wide' : ''}" data-gx="add">Add a reading</button>` : ''}${g.moves.length && !phone ? `<button type="button" class="ins-btn sm ghost ins-clip" data-gx="moved">Moved by: ${esc(g.moves.map((m) => m.title).join(', '))}</button>` : ''}</div>`
522
+ + (o.own && !phone ? '<p class="ins-lbl">On your dashboards</p>' + dashSwitches(g) : '');
523
+ }
524
+ return `<div class="ins-gd${phone ? ' ph' : ''}">${phone ? head + chart + bar : bar + head + (o.tab === 'read' ? chart : '')}<div class="ins-gb" role="tabpanel">${body}</div><p class="note ins-gmsg" data-gmsg role="status"></p></div>`;
525
+ }
526
+ function openGoalDetail(id, tab0) {
527
+ let g = goalById(id); if (!g) return;
528
+ const own = goalWs(g) === M.board.ws, st = { tab: tab0 || 'read', more: false, adding: false, own };
529
+ const kr = krId(g);
530
+ viewer({ kind: 'Goal' + (kr ? ' · ' + kr : ''), title: g.title, icon: 'goal', id: 'goal:' + id, render: (el) => {
531
+ const draw = () => { el.innerHTML = goalDetailHtml(g, st); };
532
+ const fresh = async (said) => { toast(said); await load(); if (PF) await openPortfolio(); g = goalById(id); if (g) draw(); };
533
+ draw();
534
+ el.addEventListener('click', async (e) => {
535
+ const t = e.target.closest('[data-gt]'); if (t) { st.tab = t.dataset.gt; draw(); return; }
536
+ const x = e.target.closest('[data-gx]'); if (!x || x.disabled) return;
537
+ const k = x.dataset.gx, msg = el.querySelector('[data-gmsg]');
538
+ if (k === 'chart') openChartEdit(g.id);
539
+ else if (k === 'all') { st.more = true; draw(); }
540
+ else if (k === 'add') { st.adding = true; st.tab = 'read'; draw(); const f = el.querySelector('[data-rdf] [name="v"]'); if (f) f.focus(); }
541
+ else if (k === 'cancel') { st.adding = false; draw(); }
542
+ else if (k === 'moved') { st.tab = 'moved'; draw(); }
543
+ else if (k === 'dash') {
544
+ const D = savedDash().find((d) => d.id === x.dataset.d); if (!D) return;
545
+ const on = D.charts.includes(g.id); x.disabled = true; msg.textContent = 'Saving.';
546
+ const res = await saveDash({ id: D.id, name: D.name, purpose: D.purpose, charts: on ? D.charts.filter((c) => c !== g.id) : D.charts.concat(g.id), main: D.main });
547
+ if (!res || res.ok !== true) { x.disabled = false; msg.textContent = (res && res.error) || 'The dashboard could not be saved. Nothing changed.'; return; }
548
+ await fresh((on ? 'Took it off ' : 'Added it to ') + D.name + '.');
549
+ }
400
550
  });
401
- const sf = el.querySelector('[data-stf]');
402
- if (sf) sf.addEventListener('submit', async (e) => {
403
- e.preventDefault(); const msg = sf.querySelector('[data-msg]'); msg.textContent = 'Saving.';
404
- done(await pmPost('/api/insights-records/steps', { ws: M.board.ws, rid: g.id, done: g.steps.map((_, i) => sf['s' + i].checked) }), msg, 'Saved the steps.');
551
+ el.addEventListener('submit', async (e) => {
552
+ const f = e.target; e.preventDefault(); const m = f.querySelector('[data-msg]');
553
+ if (f.matches('[data-rdf]')) {
554
+ const v = f.v.value.trim(), at = f.at.value;
555
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(at) || v === '' || !Number.isFinite(Number(v))) { m.textContent = 'Pick a date and type a number.'; return; }
556
+ m.textContent = 'Saving.';
557
+ const res = await pmPost('/api/records/kr-metrics/reading', { ws: goalWs(g), rid: goalRid(g), at, value: Number(v), why: 'Reading from Insights' });
558
+ if (!res || res.ok !== true) { m.textContent = (res && res.error) || 'It could not be saved. Nothing changed.'; return; }
559
+ st.adding = false; await fresh('Added the reading.');
560
+ } else if (f.matches('[data-stf]')) {
561
+ m.textContent = 'Saving.';
562
+ const res = await pmPost('/api/insights-records/steps', { ws: goalWs(g), rid: goalRid(g), done: g.steps.map((_, i) => f['s' + i].checked) });
563
+ if (!res || res.ok !== true) { m.textContent = (res && res.error) || 'It could not be saved. Nothing changed.'; return; }
564
+ await fresh('Saved the steps.');
565
+ }
405
566
  });
406
567
  } });
407
568
  }
408
- /* a health budget's detail: what it covers, its cap, its reading and the work anchored to it */
569
+ /* a health budget in the same frame: its reading is its share of the board's open initiatives against its cap; what moves it is the work anchored to it */
409
570
  function openBudget(id) {
410
571
  const b = (M.budgets || []).find((x) => x.id === id); if (!b) return;
411
- viewer({ kind: 'Health budget', title: b.title, icon: 'goal', render: (el) => {
412
- const R = b.reading;
413
- el.innerHTML = waitMark('A health budget’s detail') + `<dl class="ins-kv"><dt>Anchor</dt><dd>${esc(b.anchor)}</dd><dt>Covers</dt><dd>${esc(b.covers || 'Not declared in health-budgets.md')}</dd><dt>Cap</dt><dd>${b.cap !== null ? pct(b.cap) + ' of a quarter’s initiatives' : 'none declared'}</dd><dt>Now</dt><dd>${R && R.share !== null ? R.n + ' of ' + R.total + ' open initiatives (' + pct(R.share) + ')' : 'no reading'}</dd></dl>`
414
- + `<p class="ins-fl">Anchored to it <span class="q">${b.moves.length}</span></p>` + (b.moves.length ? b.moves.map((r) => initRow(r)).join('') : '<p class="note">No initiative anchors to it.</p>')
415
- + '<p class="note">The PM edits the budgets in planning/okrs/health-budgets.md.</p>';
572
+ let tab = 'read';
573
+ viewer({ kind: 'Health budget · ' + b.anchor, title: b.title, icon: 'goal', id: 'budget:' + id, render: (el) => {
574
+ const draw = () => {
575
+ const R = b.reading, has = R && R.share !== null;
576
+ const sub = [has ? pct(R.share) + ' now' : 'No reading yet', b.cap !== null ? 'cap ' + pct(b.cap) + ' of a quarter’s initiatives' : 'no cap declared', 'always on'].join(' · ');
577
+ const bar = `<div class="ins-vbar" role="tablist" aria-label="${esc(b.title)}">${[['read', 'Readings'], ['moved', 'Moved by']].map(([k, l]) => `<button type="button" role="tab" class="ins-vtab${tab === k ? ' on' : ''}" aria-selected="${tab === k}" data-bt="${k}">${l}</button>`).join('')}</div>`;
578
+ const meter = has && b.cap !== null ? bandSvg([{ at: M.today || iso(today()), v: R.share * 100 }], b.cap * 100, true, R.over ? 'late' : 'ok', b.title + ': ' + pct(R.share) + ' of open initiatives, the green band is inside its ' + pct(b.cap) + ' cap', isPhone() ? 358 : 490, 60) : '';
579
+ const body = tab === 'moved' ? (b.moves.length ? `<div class="ins-mvl">${b.moves.map((r) => initRow(r)).join('')}</div>` : '<p class="note">No initiative anchors to it.</p>')
580
+ : (has ? `<div class="ins-th2"><span>Reading</span><span>Value</span><span>Source</span></div><div class="ins-trow ins-rd3"><span>${esc(md(today()) + ' ' + iso(today()).slice(0, 4))}</span><b>${esc(pct(R.share))}</b><span class="note">${esc(R.n + ' of ' + R.total + ' open on the Board')}</span></div>` : '<div class="ins-box">It has no reading: ' + esc(b.declared ? 'no open initiative to share.' : 'it is not in the budget registry.') + '</div>')
581
+ + `<div class="ins-box note">${esc(b.covers ? 'Covers ' + b.covers + '. ' : 'What it covers is not declared. ')}It is read each time the Board is read. The PM edits the budgets in planning/okrs/health-budgets.md.</div>`;
582
+ el.innerHTML = `<div class="ins-gd">${bar}<div class="ins-gh"><p class="ins-gsub">${esc(sub)}</p><p class="note">${esc(has ? (R.over ? 'Over its cap' : 'Within its cap') : '')}</p></div>${tab === 'read' ? meter : ''}<div class="ins-gb" role="tabpanel">${body}</div></div>`;
583
+ };
584
+ draw();
585
+ el.addEventListener('click', (e) => { const t = e.target.closest('[data-bt]'); if (t) { tab = t.dataset.bt; draw(); } });
416
586
  } });
417
587
  }
418
588
 
@@ -434,34 +604,54 @@ function drawCards(G) {
434
604
  }
435
605
  $('#goalCards').addEventListener('click', (e) => { if (e.target.closest('a')) return; const c = e.target.closest('[data-goal]'); if (c) pressGoal(c.dataset.goal); });
436
606
 
437
- /* ── Delivery trends: six compact tiles from the Board's measures (AgInsGoals): a label, the value and a small line with its end dot;
438
- * a press waits for the target's design. A target is said in the tile's label for a screen reader, not as a line under it. ─────────── */
607
+ /* ── Delivery trends: six tiles from the Board's measures (AgInsGoals, IsTarget): a label, the value, a small line with its end dot and the
608
+ * target's line under it. A press opens the target popover over the tiles. In the Delivery trends view the tiles stand three to a row. ─── */
439
609
  const TILES = [['blocked', 'Blocked tickets'], ['late', 'Late initiatives'], ['idle', 'Idle 30+ days'], ['scope', 'Scope added'], ['merges', 'Merged a week'], ['corrections', 'Corrections / 100 runs']];
610
+ const TILE_DIR = { merges: 'at least' }; // more merges is better; every other measure is better lower
611
+ const numsOf = (ser) => (ser || []).filter((v) => typeof v === 'number' && Number.isFinite(v));
612
+ /** How a tile's target is read: its direction and its start (POST /api/insights-records/tile), whether the latest reading meets it, and the tile's
613
+ * colour: amber only after the last two readings both miss it (IsTarget), or the one value when there is no series. */
614
+ function targetOf(key, t) {
615
+ const TS = ((M.trends || {}).tiles || {})[key] || null, dir = (TS && TS.dir) || TILE_DIR[key] || 'at most';
616
+ const tg = dir === 'none' || t.tg == null || !Number.isFinite(Number(t.tg)) ? null : Number(t.tg);
617
+ if (tg === null) return { dir, tg: null, met: null, miss2: false, line: 'No target', set: TS };
618
+ const miss = (v) => (dir === 'at least' ? v < tg : v > tg), S = numsOf(t.ser), v0 = S.length ? S[S.length - 1] : Number(t.v);
619
+ const met = Number.isFinite(v0) ? !miss(v0) : null, miss2 = S.length >= 2 ? miss(S[S.length - 1]) && miss(S[S.length - 2]) : met === false;
620
+ return { dir, tg, met, miss2, set: TS, line: 'Target: ' + dir + ' ' + tg + (met ? ' · met' : TS && TS.at ? ' · set ' + md(day(TS.at)) : '') };
621
+ }
440
622
  function tileOf(key) {
441
623
  const TR = M.trends || {}, own = (TR.targets || {})[key];
624
+ let t;
442
625
  if (key === 'late' || key === 'scope') {
443
626
  const x = TR[key] || {};
444
- if (x.value == null) return { v: 'Not read', s: 'the initiatives are not read', abs: true };
445
- const tg = Number.isFinite(own) ? own : null, sub = (key === 'late' ? 'late today' : 'started this week') + (tg !== null ? ', target ' + tg : '');
446
- return { v: String(x.value), ser: x.ser || null, s: sub, warn: tg !== null ? x.value > tg : key === 'late' && x.value > 0, tg };
627
+ if (x.value == null) return { v: 'Not read', s: 'the initiatives are not read', abs: true, T: { line: '' } };
628
+ const tg = Number.isFinite(own) ? own : null;
629
+ t = { v: String(x.value), ser: x.ser || null, s: key === 'late' ? 'late today' : 'started this week', tg, base: key === 'late' && x.value > 0 };
630
+ } else {
631
+ if (!BM) return { v: bmErr ? 'Not read' : 'Reading', s: '', abs: true, T: { line: '' } };
632
+ const b = (BM.tiles || []).find((x) => x.key === key);
633
+ if (!b) return { v: 'Not read', s: '', abs: true, T: { line: '' } };
634
+ if (b.absent) return { v: b.absent, s: '', abs: true, T: { line: '' } };
635
+ t = { v: b.value, ser: b.ser, s: b.targetTxt || '', tg: b.tg != null ? b.tg : null, base: !!b.look || b.kind === 'warn' || b.kind === 'bad' };
447
636
  }
448
- if (!BM) return { v: bmErr ? 'Not read' : 'Reading', s: '', abs: true };
449
- const t = (BM.tiles || []).find((x) => x.key === key);
450
- if (!t) return { v: 'Not read', s: '', abs: true };
451
- if (t.absent) return { v: t.absent, s: '', abs: true };
452
- return { v: t.value, ser: t.ser, s: t.targetTxt || '', warn: !!t.look || t.kind === 'warn' || t.kind === 'bad', tg: t.tg != null ? t.tg : null };
453
- }
454
- /** A tile's line, as the design draws it: 150 by 18, the weeks from 5 to 145, a soft fill under it and the end dot (orange on a tile to look at). */
455
- function miniSpark(ser) {
637
+ t.T = targetOf(key, t);
638
+ t.warn = t.T.tg !== null ? t.T.miss2 : t.base;
639
+ return t;
640
+ }
641
+ /** A tile's line, as the design draws it: the weeks from 5 to W-5, a soft fill under it and the end dot (orange on a tile to look at). */
642
+ function miniSpark(ser, W = 150, H = 18) {
456
643
  const S = (ser || []).map((v, j) => [j, v]).filter((p) => p[1] != null); if (S.length < 2) return '<span class="ins-tsp0"></span>';
457
- const n = ser.length - 1 || 1, vs = S.map((p) => p[1]), lo = Math.min(...vs), hi = Math.max(...vs), rg = hi - lo || 1, W = 150, H = 18;
644
+ const n = ser.length - 1 || 1, vs = S.map((p) => p[1]), lo = Math.min(...vs), hi = Math.max(...vs), rg = hi - lo || 1;
458
645
  const pts = S.map(([j, v]) => (5 + j / n * (W - 10)).toFixed(1) + ',' + (5 + (1 - (v - lo) / rg) * (H - 10)).toFixed(1)), last = pts[pts.length - 1].split(','), first = pts[0].split(',');
459
- return `<svg class="ins-tsp" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" role="presentation"><polygon class="ar" points="${first[0]},${H} ${pts.join(' ')} ${last[0]},${H}"/><polyline class="ln" points="${pts.join(' ')}"/><circle class="dt" cx="${last[0]}" cy="${last[1]}" r="3.6"/></svg>`;
646
+ return `<svg class="ins-tsp" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="presentation"><polygon class="ar" points="${first[0]},${H} ${pts.join(' ')} ${last[0]},${H}"/><polyline class="ln" points="${pts.join(' ')}"/><circle class="dt" cx="${last[0]}" cy="${last[1]}" r="3.6"/></svg>`;
460
647
  }
461
- function bmHtml() {
462
- if (!M.board || !M.board.ws) return '';
463
- return '<section class="ins-trends" id="cBm" aria-labelledby="hBm"><div class="ins-grp" role="row"><h2 id="hBm" role="cell">Delivery trends</h2> <span class="q">the Board shows today’s counts as chips · press a tile to set its target</span></div>'
464
- + `<div class="ins-tiles" id="bmBody">${TILES.map(([k, l]) => { const t = tileOf(k); return `<div class="ins-tile${t.warn ? ' warn' : ''}${t.abs ? ' abs' : ''}" data-tile="${k}" role="button" tabindex="0" aria-label="${esc(l + ', ' + t.v + (t.s ? ', ' + t.s : ''))}"${t.s ? ` title="${esc(t.s)}"` : ''}><span class="l">${esc(l)}</span><span class="v">${esc(t.v)}</span>${miniSpark(t.ser)}</div>`; }).join('')}</div></section>`;
648
+ let tgOpen = null; // the tile whose target popover is open
649
+ function bmHtml(big) {
650
+ if (!M.board || !M.board.ws) return big ? '<div class="ins-empty">Delivery trends are read from a board, and this workspace has none.</div>' : '';
651
+ const head = big ? '<div class="ins-trh" role="row"><h2 id="hBm" role="cell">Delivery trends</h2> <span class="note">Last 8 weeks · from the Board and its initiatives · press a tile to set its target</span></div>'
652
+ : '<div class="ins-grp" role="row"><h2 id="hBm" role="cell">Delivery trends</h2> <span class="q">the Board shows today’s counts as chips · press a tile to set its target</span></div>';
653
+ return `<section class="ins-trends${big ? ' big' : ''}" id="cBm" aria-labelledby="hBm">${head}`
654
+ + `<div class="ins-tiles" id="bmBody">${TILES.map(([k, l]) => { const t = tileOf(k), on = tgOpen === k; return `<div class="ins-tile${t.warn ? ' warn' : ''}${t.abs ? ' abs' : ''}${on ? ' sel' : ''}" data-tile="${k}" role="button" tabindex="0" aria-expanded="${on}" aria-label="${esc(l + ', ' + t.v + (t.s ? ', ' + t.s : '') + (t.T.line ? ', ' + t.T.line : ''))}"${t.s ? ` title="${esc(t.s)}"` : ''}><span class="l">${esc(l)}</span><span class="v">${esc(t.v)}</span>${big ? miniSpark(t.ser, 300, 34) : miniSpark(t.ser)}<span class="tg">${on ? 'Setting target…' : esc(t.T.line)}</span></div>`; }).join('')}</div></section>`;
465
655
  }
466
656
  async function bmLoad() {
467
657
  if (!M || !M.board || !M.board.ws) return;
@@ -472,27 +662,54 @@ async function bmLoad() {
472
662
  if (BM && BM.pending) setTimeout(bmLoad, 4000); // the workflow engine is still deriving Blocked and Idle
473
663
  }
474
664
 
475
- /* a Delivery trends target: no agreed design, so a plain minimal form in the Viewer card, with the "Waiting for design" marker. The Board's four
476
- * measures keep their targets in board-metric-targets.jsonl (POST /api/board-metric-targets/save); Late and Scope added in insights-records.jsonl. */
665
+ /* the target popover (IsTarget): At least, At most or No target; the value and the day it counts from; the tile's own range; and whether the Board
666
+ * chip shows it. The Board's four measures keep the number in board-metric-targets.jsonl (POST /api/board-metric-targets/save); Late and Scope added
667
+ * in insights-records.jsonl (POST /api/insights-records/target). How it is read goes to POST /api/insights-records/tile. */
668
+ const segBtns = (name, opts, on) => `<div class="cz-seg ins-seg" role="group" aria-label="${esc(name)}">${opts.map(([v, l]) => `<button type="button" aria-pressed="${v === on}" data-v="${esc(v)}">${esc(l)}</button>`).join('')}</div>`;
669
+ function rangeSay(ser) {
670
+ const S = numsOf(ser); if (S.length < 2) return 'There are not enough readings yet to say its usual range.';
671
+ const o = S.slice().sort((a, b) => a - b), mid = o.length % 2 ? o[(o.length - 1) / 2] : (o[o.length / 2 - 1] + o[o.length / 2]) / 2, r = (v) => Math.round(v * 10) / 10;
672
+ return 'Last ' + S.length + ' weeks: ' + r(o[0]) + ' to ' + r(o[o.length - 1]) + ', median ' + r(mid) + '.';
673
+ }
674
+ function closeTarget(focus) {
675
+ const p = $('#tgPop'); if (!p) return; const k = tgOpen; p.remove(); tgOpen = null;
676
+ if (tab === 'goals') drawGoals();
677
+ if (focus && k) { const t = $(`[data-tile="${k}"]`); if (t) t.focus(); }
678
+ }
477
679
  function openTarget(key) {
478
- const L = (TILES.find((x) => x[0] === key) || [])[1] || key, t = tileOf(key), mine = key === 'late' || key === 'scope';
479
- viewer({ kind: 'Delivery trends', title: L, icon: 'chart', render: (el) => {
480
- el.innerHTML = waitMark('Setting a Delivery trends target') + `<form class="ins-mf" data-tgf><p class="note">Now: <b>${esc(t.v)}</b>${t.s ? ' · ' + esc(t.s) : ''}</p>`
481
- + `<label class="ins-fl">Target<input class="ins-inp" name="tg" inputmode="decimal" maxlength="12" value="${t.tg != null ? esc(String(t.tg)) : ''}" placeholder="Leave empty for no target"></label>`
482
- + `<div class="ins-mact"><button type="submit" class="ins-primary">Save target</button><span class="note" data-msg></span></div></form>`;
483
- el.querySelector('[data-tgf]').addEventListener('submit', async (e) => {
484
- e.preventDefault(); const v = e.target.tg.value.trim(), msg = el.querySelector('[data-msg]');
485
- if (v !== '' && !Number.isFinite(Number(v))) { msg.textContent = 'Type a number, or leave it empty.'; return; }
486
- msg.textContent = 'Saving.';
487
- const res = mine ? await pmPost('/api/insights-records/target', { ws: M.board.ws, key, target: v === '' ? null : Number(v) })
488
- : await pmPost('/api/board-metric-targets/save', { ws: M.board.ws, key, target: v === '' ? null : Number(v) });
489
- if (!res || res.ok !== true) { msg.textContent = (res && res.error) || 'The target could not be saved. Nothing changed.'; return; }
490
- msg.textContent = 'Saved.'; toast('Saved the target of ' + L + '.'); BM = null; await load(); bmLoad();
491
- });
492
- } });
680
+ closeTarget(); closeMenus();
681
+ const L = (TILES.find((x) => x[0] === key) || [])[1] || key, t = tileOf(key), mine = key === 'late' || key === 'scope', T = t.T || {};
682
+ tgOpen = key; drawGoals();
683
+ const tile = $(`[data-tile="${key}"]`), main = $('#stage'); if (!tile) return;
684
+ const dir0 = T.tg === null && T.set && T.set.dir === 'none' ? 'none' : T.dir || TILE_DIR[key] || 'at most';
685
+ const pop = document.createElement('div');
686
+ pop.className = 'ins-pop ins-tgpop'; pop.id = 'tgPop'; pop.setAttribute('role', 'dialog'); pop.setAttribute('aria-label', 'Target for ' + L);
687
+ pop.innerHTML = `<p class="ins-h3">Target for ${esc(L.toLowerCase())}</p>${segBtns('Direction', [['at least', 'At least'], ['at most', 'At most'], ['none', 'No target']], dir0)}`
688
+ + `<div class="ins-2"><label class="ins-fl">Value<input class="ins-inp" id="tgV" inputmode="decimal" maxlength="12" value="${T.tg != null ? esc(String(T.tg)) : ''}"${dir0 === 'none' ? ' disabled' : ''}></label><label class="ins-fl">From<input class="ins-inp" id="tgFrom" type="date" value="${esc((T.set && T.set.from) || '')}"></label></div>`
689
+ + `<p class="note">${esc(t.abs ? 'It is not read yet, so it has no range to show.' : rangeSay(t.ser))} A tile goes amber only after 2 weeks past its target.</p>`
690
+ + `<label class="ins-chkl"><button type="button" class="ins-chk${!T.set || T.set.chip ? ' on' : ''}" role="checkbox" aria-checked="${!T.set || T.set.chip}" id="tgChip">${SV(I.chk, 3)}</button>Show the target on the Board chip</label>`
691
+ + '<div class="ins-acts"><button type="button" class="ins-btn sm dark" id="tgSet">Set target</button><button type="button" class="ins-btn sm ghost" id="tgCancel">Cancel</button><span class="note" id="tgMsg" role="status"></span></div>';
692
+ main.appendChild(pop);
693
+ if (isPhone()) pop.classList.add('ph');
694
+ else { const mr = main.getBoundingClientRect(), tr = tile.getBoundingClientRect(), w = 400; pop.style.left = Math.max(16, Math.min(tr.left - mr.left, mr.width - w - 16)) + 'px'; pop.style.top = (tr.bottom - mr.top + main.scrollTop + 8) + 'px'; }
695
+ const dirNow = () => (pop.querySelector('[aria-pressed="true"]') || {}).dataset.v || 'at most';
696
+ pop.addEventListener('click', async (e) => {
697
+ e.stopPropagation();
698
+ const d = e.target.closest('[data-v]'); if (d) { for (const b of $$('[data-v]', pop)) b.setAttribute('aria-pressed', String(b === d)); $('#tgV').disabled = d.dataset.v === 'none'; return; }
699
+ const c = e.target.closest('#tgChip'); if (c) { const on = c.getAttribute('aria-checked') !== 'true'; c.setAttribute('aria-checked', String(on)); c.classList.toggle('on', on); return; }
700
+ if (e.target.closest('#tgCancel')) { closeTarget(true); return; }
701
+ if (!e.target.closest('#tgSet')) return;
702
+ const dir = dirNow(), v = $('#tgV').value.trim(), msg = $('#tgMsg');
703
+ if (dir !== 'none' && (v === '' || !Number.isFinite(Number(v)))) { msg.textContent = 'Type a number, or pick No target.'; $('#tgV').focus(); return; }
704
+ const target = dir === 'none' ? null : Number(v); msg.textContent = 'Saving.'; $('#tgSet').disabled = true;
705
+ const res = mine ? await pmPost('/api/insights-records/target', { ws: M.board.ws, key, target }) : await pmPost('/api/board-metric-targets/save', { ws: M.board.ws, key, target });
706
+ if (!res || res.ok !== true) { $('#tgSet').disabled = false; msg.textContent = (res && res.error) || 'The target could not be saved. Nothing changed.'; return; }
707
+ const r2 = await pmPost('/api/insights-records/tile', { ws: M.board.ws, key, dir, from: $('#tgFrom').value || '', chip: $('#tgChip').getAttribute('aria-checked') === 'true' });
708
+ closeTarget(true); toast(target === null ? 'Took the target off ' + L + '.' : 'Set the target of ' + L + '.' + (!r2 || r2.ok !== true ? ' Its direction could not be kept.' : ''));
709
+ BM = null; await load(); bmLoad();
710
+ });
711
+ const f = $('#tgV'); if (f && !f.disabled) f.focus(); else pop.querySelector('[aria-pressed="true"]').focus();
493
712
  }
494
- /** The small "Waiting for design" marker on a part the Agreed design does not draw yet; the part itself still works. */
495
- const waitMark = (feature) => (typeof window.czPlaceholderHtml === 'function' ? window.czPlaceholderHtml(feature) : `<div class="ins-wmark" role="note">${esc(feature)} · Waiting for design</div>`);
496
713
 
497
714
  /* ── Outcomes (AgInsOutcomes) ───────────────────────────────────────────────────────────────────────────────────────────────────── */
498
715
  const sgn = (v, u) => { const r = Math.round(v * 100) / 100, s = r > 0 ? '+' : r < 0 ? '−' : ''; const a = Math.abs(r); return s + (String(u).trim() === '%' ? a + (a === 1 ? ' pt' : ' pts') : a + (u ? (/^[A-Za-z]/.test(u) ? ' ' + u : u) : '')); };
@@ -864,7 +1081,9 @@ $('#newMenu').addEventListener('click', (e) => {
864
1081
  else { const D = curDash(), first = goalsShown().find((g) => g.key) || M.goals[0]; openChartEdit(first ? first.id : null, D); }
865
1082
  });
866
1083
 
867
- /* ── Library (AgInsLibrary): reports, then dashboards ───────────────────────────────────────────────────────────────────────────── */
1084
+ /* ── Library (IsLibrary; IsPhone right): what PMOS found in your work, the reports as Report · Next · Status, then the dashboards. Reports are
1085
+ * made in Home: New report and Change the setup hand off there. Every press posts to the console's report-setups routes
1086
+ * (lib/routes-report-setups.js); none opens the old dialog or the Chat page. ─────────────────────────────────────────────────────────── */
868
1087
  function reportGroups() {
869
1088
  const R = M.reports, by = new Map();
870
1089
  for (const f of R.missing ? [] : R.rows) { if (!by.has(f.cadence)) by.set(f.cadence, []); by.get(f.cadence).push(f); }
@@ -873,20 +1092,26 @@ function reportGroups() {
873
1092
  for (const [id, fs] of by) if (shown(fs)) out.push({ kind: 'file', x: { id, name: id, setup: null, files: fs } });
874
1093
  return out;
875
1094
  }
876
- const cycDots = (states) => `<span class="ins-dots" aria-hidden="true">${states.map((k) => `<i class="${k}"></i>`).join('')}</span>`;
877
- const fromChips = (s) => { const L = (s && s.source ? [s.source === 'work' ? 'Your work' : s.source] : []).concat(s && s.builtFrom ? s.builtFrom.map((x) => { const g = M.goals.find((y) => y.id === x); return g ? g.title : x; }) : []);
878
- return L.length ? L.slice(0, 3).map((x) => `<span class="cz-pill q">${esc(x)}</span>`).join(' ') + (L.length > 3 ? ` <span class="note">+${L.length - 3}</span>` : '') : '<span class="note">Not recorded</span>'; };
879
- const lrow = (attr, name, sub, when, st, from, act) => `<div class="ins-tr ins-row ins-lcols" role="listitem"><button type="button" class="ins-lrow" ${attr}><span class="lic">${SV(I.doc)}</span><span class="nm"><b>${esc(name)}</b><small>${esc(sub)}</small></span><span class="note ins-when">${esc(when)}</span><span>${st}</span><span class="ins-from">${from}</span><span class="ins-act">${act}</span></button></div>`;
880
- function repRow(g) {
881
- const live = g.files.filter((x) => !x.archived), L = live[0], s = g.setup, d = live.find((x) => x.state !== 'issued');
882
- const st = cycDots(live.slice(0, 8).reverse().map((x) => (x.state === 'issued' ? 'is' : 'dr'))) + `<small class="note">${d ? 'Draft ready for ' + esc(md(day(d.slot))) : L ? 'Issued ' + esc(md(day(L.slot))) : ''}${s && !s.paused && s.next ? ' · next ' + esc(s.next) : s && s.paused ? ' · paused' : ''}</small>`;
883
- return lrow(`data-rpt="${esc(g.id)}"`, g.name, [L.lead ? '“' + L.lead + '”' : '', s && s.audience ? s.audience : '', s && s.output ? s.output : ''].filter(Boolean).join(' · ') || 'Latest: ' + md(day(L.slot)),
884
- s && s.label ? s.label : 'No schedule', st, fromChips(s), d ? '<span class="cz-pill you">Review draft</span>' : '');
885
- }
886
- const setupRow = (s) => lrow(`data-setup="${esc(s.id)}"`, s.name, [s.latest && s.latest.lead ? '“' + s.latest.lead + '”' : 'No draft is written yet', s.audience, s.output].filter(Boolean).join(' · '), s.label || '',
887
- cycDots(['dr0']) + `<small class="note">${s.paused ? 'Paused' : s.drafting ? 'Drafting' : s.next ? 'First draft ' + esc(s.next) : 'Set up'}</small>`, fromChips(s), '<span class="cz-pill q">Set up</span>');
888
- const ASKST = { running: ['Working on a proposal', 'q', 'Working'], ready: ['Proposal ready, not set up', 'you', 'Review proposal'], failed: ['The run failed', 'red', 'Failed'] };
889
- const askRow = (a) => lrow(`data-ask="${esc(a.id)}"`, a.proposal && a.proposal.name ? a.proposal.name : a.text, 'You asked: ' + a.text, '', cycDots(['dr0']) + `<small class="note">${esc(ASKST[a.state][0])}</small>`, '<span class="note">Not recorded</span>', `<span class="cz-pill ${ASKST[a.state][1]}">${ASKST[a.state][2]}</span>`);
1095
+ /** A schedule said short, for the status pill: "Every other Monday at 09:00" is "Every other Monday". */
1096
+ const cadShort = (s) => String((s && s.label) || '').replace(/\s+at\s+\d.*$/, '');
1097
+ const fromList = (s) => (s && s.builtFrom ? s.builtFrom.map((x) => { const g = M.goals.find((y) => y.id === x); return g ? g.title : x; }) : []).concat(s && s.source ? [s.source === 'work' ? 'Your work' : s.source] : []);
1098
+ /** A Library row's Next and Status (IsLibrary), from its setup and its files: a draft waiting says "Draft ready <date>". */
1099
+ function repState(G) {
1100
+ const s = G.kind === 'setup' ? G.x : G.x.setup, live = G.kind === 'file' ? G.x.files.filter((x) => !x.archived) : [], draft = live.find((x) => x.state !== 'issued');
1101
+ const next = draft ? 'Draft ready for ' + md(day(draft.slot)) : s && s.paused ? '—' : s && s.next ? (live.length ? 'Next ' : 'First draft ') + s.next : '—';
1102
+ const pill = s ? (s.paused ? ['q', 'Paused'] : s.drafting ? ['q', 'Drafting'] : ['ok', cadShort(s) ? 'Runs ' + cadShort(s).toLowerCase() : 'Set up']) : draft ? ['you', 'Draft'] : ['q', 'Issued ' + md(day(live[0].slot))];
1103
+ const lead = s && s.latest && s.latest.lead ? s.latest.lead : live[0] && live[0].lead ? live[0].lead : '';
1104
+ const F = fromList(s), sub = [F.length ? 'Built from ' + F.slice(0, 3).join(' · ') : s && s.audience ? 'For ' + s.audience : '', lead ? '“' + lead + '”' : !live.length ? 'No draft is written yet' : ''].filter(Boolean).join(' · ');
1105
+ return { s, live, draft, next, pill, sub };
1106
+ }
1107
+ const ASKST = { running: ['Working on a proposal', 'q', 'Working'], ready: ['Proposal ready, not set up', 'you', 'Proposal'], failed: ['The run failed', 'red', 'Failed'] };
1108
+ let selRow = null; // the Library row whose setup or request is open in the Viewer
1109
+ const rlRow = (attr, key, name, sub, next, pill) => `<div role="listitem"><button type="button" class="ins-rl${selRow === key ? ' sel' : ''}" ${attr}><span class="nm"><b>${esc(name)}</b><small>${esc(sub)}</small></span><span class="nx${next === '—' ? ' q' : ''}">${esc(next)}</span><span class="st"><span class="cz-pill ${pill[0]}">${esc(pill[1])}</span></span></button></div>`;
1110
+ function repRowHtml(G) {
1111
+ const st = repState(G), key = G.kind + ':' + G.x.id;
1112
+ return rlRow(G.kind === 'setup' ? `data-setup="${esc(G.x.id)}"` : `data-rpt="${esc(G.x.id)}"`, key, G.x.name, st.sub || ' ', st.next, st.pill);
1113
+ }
1114
+ const askRowHtml = (a) => rlRow(`data-ask="${esc(a.id)}"`, 'ask:' + a.id, a.proposal && a.proposal.name ? a.proposal.name : a.text, 'You asked in Home: ' + a.text, '—', [ASKST[a.state][1] === 'you' ? 'y' : ASKST[a.state][1], ASKST[a.state][2]]);
890
1115
  function miniHtml(c) {
891
1116
  const d = c.pts.map((p, i) => (i ? 'L' : 'M') + (5 + p.fx * 120).toFixed(1) + ',' + (4 + (1 - p.fy) * 18).toFixed(1)).join(''), l = c.pts[c.pts.length - 1];
892
1117
  return `<span class="ins-mini"><small>${esc(c.title)}</small><b>${esc(c.v)}</b><svg viewBox="0 0 130 26" aria-hidden="true"><path d="${d}L125,26L5,26Z" class="ar"/><path d="${d}" class="ln"/><circle cx="${(5 + l.fx * 120).toFixed(1)}" cy="${(4 + (1 - l.fy) * 18).toFixed(1)}" r="3" style="fill:${c.off ? 'var(--cz-dot-late)' : 'var(--cz-dot-ok)'}"/></svg></span>`;
@@ -897,85 +1122,157 @@ function dashCard(D) {
897
1122
  const sub = D.id === 'all' ? 'Every goal and budget · PMOS keeps it' : D.saved ? (D.purpose || D.charts.length + ' goals') + (D.at ? ' · saved ' + md(day(D.at)) : '') : 'The goals of one objective';
898
1123
  return `<button type="button" class="ins-dcard" role="listitem" data-d="${esc(D.id)}" aria-label="Open ${esc(dashName(D))} on Goals${on ? ', pinned' : ''}"><span class="ins-dh"><b>${esc(dashName(D))}</b>${on ? `<span class="ins-pinned" title="Pinned: opens first on Goals">${SV(I.pin)}</span>` : ''}${pill}</span><span class="ins-minis">${L.slice(0, 2).map(miniHtml).join('') || '<span class="note">No goal on it has a series yet.</span>'}</span><small class="note">${esc(sub)}</small></button>`;
899
1124
  }
1125
+ /* Not a report: the card goes at once and the toast offers Undo; the dismiss is posted when the toast has gone (lib/routes-report-setups.js has no undo) */
1126
+ const notRep = new Map(); // finding id → its timer
900
1127
  function drawList() {
901
- const R = M.reports, found = (R.found || []).filter((f) => hit(f.name, f.why)), asks = (R.asks || []).filter((a) => hit(a.text));
1128
+ const R = M.reports, found = (R.found || []).filter((f) => !notRep.has(f.id) && hit(f.name, f.why)), asks = (R.asks || []).filter((a) => hit(a.text, a.proposal && a.proposal.name));
902
1129
  const reps = reportGroups().filter((g) => hit(g.x.name)), dashes = M.dashboards.filter((d) => hit(dashName(d)));
903
1130
  const nRep = reps.length + asks.length;
904
1131
  $('#repCap').textContent = String(nRep + dashes.length);
905
- const F3 = [['all', 'All', nRep + dashes.length], ['rep', 'Reports', nRep], ['dash', 'Dashboards', dashes.length]];
906
- $('#listSeg').innerHTML = F3.map(([k, t, n]) => `<button type="button" class="cz-chip${listF === k ? ' on' : ''}" data-f="${k}" aria-pressed="${listF === k}">${t} <b>${n}</b></button>`).join('');
907
- $('#sugB').hidden = false; // with none found it still opens the list, where a report can be asked for
908
- $('#sugB').innerHTML = SV(I.spark) + (found.length ? found.length + (found.length === 1 ? ' suggestion' : ' suggestions') + ' from your work' : 'Suggestions from your work');
1132
+ $('#newRep').href = homeAsk('insights', 'Make a new report: ');
1133
+ const fbox = found.length ? `<div class="ins-fd" aria-label="Found in your work"><div class="ins-fdh"><b>Found in your work · ${found.length}</b><span class="note">Things you write by hand often</span></div>`
1134
+ + found.map((f) => `<div class="ins-fcard" data-f="${esc(f.id)}"><button type="button" class="nm" data-fx="open" aria-label="${esc(f.name)}: what PMOS found"><b>${esc(f.name)}</b><small>${esc(f.why)}</small></button><button type="button" class="ins-btn sm dark" data-fx="setup">Set it up</button><button type="button" class="ins-btn sm ghost" data-fx="dismiss">Not a report</button></div>`).join('') + '</div>' : '';
909
1135
  const empty = R.missing ? '<div class="ins-empty"><b>The report files could not be read</b>, so none is listed.</div>'
910
1136
  : R.setupsOk === false ? '<div class="ins-empty"><b>The report setups could not be read</b>, so what you set up is not listed.</div>' : '';
911
- const rhead = '<div class="ins-tr ins-th ins-lcols ins-lhead" role="presentation"><span></span><span>Report · audience</span><span>When</span><span>Issued · next</span><span>Built from</span><span></span></div>';
912
- const repRows = reps.map((g) => (g.kind === 'setup' ? setupRow(g.x) : repRow(g.x))).join('') + asks.map(askRow).join('');
913
- const repBlock = listF === 'dash' ? '' : `<div class="ins-sec"><h3>Reports</h3><span class="q">${nRep} · by next due</span></div>` + empty
914
- + (nRep ? `<div class="ins-tbl" id="repAsks">${rhead}<div role="list">${repRows}</div></div>` : !empty ? '<div class="ins-empty"><b>No report is set up and no report file is on record.</b> Reports are made in Home.</div>' : '');
915
- const dashBlock = listF === 'rep' ? '' : `<div class="ins-sec"><h3>Dashboards</h3><span class="q">${dashes.length} · a dashboard is a saved view of Goals</span></div><div class="ins-dgrid" role="list">${dashes.map(dashCard).join('')}</div>`;
916
- $('#repBody').innerHTML = `<div id="listRows" aria-label="Dashboards and reports">${repBlock}${dashBlock}</div>`;
917
- }
918
- $('#listSeg').addEventListener('click', (e) => { const b = e.target.closest('[data-f]'); if (!b || b.dataset.f === listF) return; listF = b.dataset.f; drawList(); });
919
- $('#sugB').addEventListener('click', openFound);
920
- /* Ask for a report is not on the Library bar (AgInsLibrary: reports are made in Home); it stays usable under the suggestions, waiting for design */
921
- $('#repBody').addEventListener('click', (e) => {
1137
+ const table = nRep ? `<div class="ins-rtbl" id="repAsks"><div class="ins-rl ins-rlh" role="presentation"><span>Report</span><span>Next</span><span>Status</span></div><div role="list">${reps.map(repRowHtml).join('')}${asks.map(askRowHtml).join('')}</div></div>`
1138
+ : !empty ? '<div class="ins-empty"><b>No report is set up and no report file is on record.</b> Reports are made in Home.</div>' : '';
1139
+ const dashBlock = `<div class="ins-sec"><h3>Dashboards</h3><span class="q">${dashes.length} · a dashboard is a saved view of Goals</span></div><div class="ins-dgrid" role="list">${dashes.map(dashCard).join('')}</div>`;
1140
+ $('#repBody').innerHTML = `<div id="listRows" aria-label="Dashboards and reports">${fbox}${empty}${table}${dashBlock}</div>`;
1141
+ }
1142
+ $('#repBody').addEventListener('click', async (e) => {
922
1143
  const d = e.target.closest('[data-d]'); if (d) { setView(d.dataset.d); return; }
923
- const rp = e.target.closest('[data-rpt]');
924
- if (rp) { const g = reportGroups().find((x) => x.kind === 'file' && x.x.id === rp.dataset.rpt); if (g) openReport(g.x.files.find((x) => !x.archived), { ws: M.board.ws, name: g.x.setup ? g.x.setup.name : null, cycles: g.x.files, onIssue: () => load(), onChange: () => load() }); return; }
925
- const su = e.target.closest('[data-setup]'); if (su) { openSetup(su.dataset.setup); return; }
1144
+ const fx = e.target.closest('[data-fx]');
1145
+ if (fx) {
1146
+ const card = fx.closest('[data-f]'), fid = card.dataset.f, f = (M.reports.found || []).find((x) => x.id === fid); if (!f) return;
1147
+ if (fx.dataset.fx === 'open') { openFound(fid); return; }
1148
+ if (fx.dataset.fx === 'dismiss') {
1149
+ notRep.set(fid, setTimeout(async () => { notRep.delete(fid); const r = await pmPost('/api/report-setups/dismiss', { ws: M.board.ws, finding: fid }); if (!r || r.ok !== true) toast((r && r.error) || 'It could not be marked. It shows again.'); await load(); }, 9000));
1150
+ drawList(); toast('Not a report · ' + f.name, { label: 'Undo', fn: () => { clearTimeout(notRep.get(fid)); notRep.delete(fid); drawList(); } });
1151
+ return;
1152
+ }
1153
+ fx.disabled = true;
1154
+ await postSetup(card, 'setup', { finding: fid }, (r) => 'Set up ' + f.name + '.' + (r.drafted && r.drafted.path ? ' The first draft is ' + r.drafted.path + '.' : ''));
1155
+ return;
1156
+ }
1157
+ const rp = e.target.closest('[data-rpt]'); if (rp) { openReportRow('file', rp.dataset.rpt); return; }
1158
+ const su = e.target.closest('[data-setup]'); if (su) { openReportRow('setup', su.dataset.setup); return; }
926
1159
  const ak = e.target.closest('[data-ask]'); if (ak) openRequest(ak.dataset.ask);
927
1160
  });
928
-
929
- /* ── Library flows the Agreed design does not draw: each a plain minimal form in the Viewer card, with the "Waiting for design" marker. They post to
930
- * the console's own report-setups routes (lib/routes-report-setups.js); none opens the old dialog or the Chat page. ─────────────────────────────── */
1161
+ /** A report row: one with a setup opens its setup (the Viewer card, a sheet on a phone); a file with no setup opens in the reader. */
1162
+ function openReportRow(kind, id) {
1163
+ const G = reportGroups().find((x) => x.kind === kind && x.x.id === id) || reportGroups().find((x) => x.x.id === id); if (!G) return;
1164
+ const s = G.kind === 'setup' ? G.x : G.x.setup;
1165
+ if (s) { if (isPhone()) openSheet(G); else openSetup(G); return; }
1166
+ openFile(G);
1167
+ }
1168
+ function openFile(G, file) {
1169
+ const f = file || G.x.files.find((x) => !x.archived); if (!f) return;
1170
+ openReport(f, { ws: M.board.ws, name: G.x.setup ? G.x.setup.name : null, cycles: G.x.files, onIssue: () => load(), onChange: () => load() });
1171
+ }
931
1172
  const kvHtml = (rows) => `<dl class="ins-kv">${rows.filter(Boolean).map(([a, b]) => `<dt>${esc(a)}</dt><dd>${esc(b)}</dd>`).join('')}</dl>`;
932
- function actionsHtml(acts) { return `<div class="ins-mact">${acts.map(([k, t, primary]) => `<button type="button" class="${primary ? 'ins-primary' : 'cz-chip'}" data-act="${k}">${esc(t)}</button>`).join('')}<span class="note" data-msg></span></div>`; }
933
1173
  async function postSetup(el, route, body, said) {
934
1174
  const msg = el.querySelector('[data-msg]'); if (msg) msg.textContent = 'Sending.';
935
1175
  const res = await pmPost('/api/report-setups/' + route, Object.assign({ ws: M.board.ws }, body));
936
- if (!res || res.ok !== true) { if (msg) msg.textContent = (res && res.error) || 'It could not be done. Nothing changed.'; return false; }
1176
+ if (!res || res.ok !== true) { if (msg) msg.textContent = (res && res.error) || 'It could not be done. Nothing changed.'; else toast((res && res.error) || 'It could not be done. Nothing changed.'); return false; }
937
1177
  toast(typeof said === 'function' ? said(res) : said); await load(); return true;
938
1178
  }
939
- function openSetup(id) {
940
- const s = (M.reports.setups || []).find((x) => x.id === id); if (!s) return;
941
- viewer({ kind: 'Report', title: s.name, icon: 'report', render: (el) => {
942
- el.innerHTML = waitMark('A report setup') + kvHtml([['What it is for', s.purpose || '—'], s.audience ? ['For', s.audience] : null, ['Schedule', s.label || 'No schedule'], ['Next draft', s.paused ? 'Paused' : s.next || '—'], s.output ? ['Made as', s.output] : null])
943
- + actionsHtml([['draft', 'Draft it now', true], s.paused ? ['resume', 'Resume'] : ['pause', 'Pause']]);
944
- el.addEventListener('click', async (e) => { const b = e.target.closest('[data-act]'); if (!b) return;
945
- if (b.dataset.act === 'draft') { if (await postSetup(el, 'draft', { id }, (r) => 'Drafting it now' + (r.drafted && r.drafted.path ? ': ' + r.drafted.path : '.'))) openSetup(id); }
946
- else if (await postSetup(el, b.dataset.act, { id }, b.dataset.act === 'pause' ? 'Paused ' + s.name + '.' : 'Resumed ' + s.name + '.')) openSetup(id); });
947
- } });
948
- }
949
- function openFound() {
950
- const F = M.reports.found || [];
951
- viewer({ kind: 'Found in your work', title: F.length === 1 ? '1 suggestion' : F.length + ' suggestions', icon: 'report', render: (el) => {
952
- el.innerHTML = waitMark('What PMOS found in your work') + (F.length ? F.map((f) => `<section class="ins-fnd" data-f="${esc(f.id)}"><b>${esc(f.name)}</b>${f.confidence ? ` <span class="cz-pill q">${esc(f.confidence)}</span>` : ''}<p class="note">${esc(f.why)}</p>`
953
- + (f.evidence.length ? `<ul class="ins-ev">${f.evidence.map((x) => `<li>${esc(x.text)}</li>`).join('')}</ul>` : '') + (f.proposal ? kvHtml(f.proposal.rows || []) : '')
954
- + `<div class="ins-mact"><button type="button" class="ins-primary" data-fx="setup">Set it up</button><button type="button" class="cz-chip" data-fx="dismiss">Not a report</button><span class="note" data-msg></span></div></section>`).join('') : '<p class="note">Nothing is waiting.</p>')
955
- + '<div class="ins-mact"><button type="button" class="cz-chip" data-askr>Ask for a report</button></div>';
956
- el.addEventListener('click', async (e) => { if (e.target.closest('[data-askr]')) { openAsk(); return; } const b = e.target.closest('[data-fx]'); if (!b) return; const sec = b.closest('[data-f]'), fid = sec.dataset.f;
957
- if (await postSetup(sec, b.dataset.fx, { finding: fid }, b.dataset.fx === 'setup' ? (r) => 'Set up.' + (r.drafted && r.drafted.path ? ' The first draft is ' + r.drafted.path + '.' : '') : 'Marked as not a report.')) openFound(); });
1179
+ const changeHref = (s) => homeAsk('insights', 'Change the setup of ' + s.name + ': ');
1180
+ const nextSay = (s) => (s.paused ? 'Paused' : s.drafting ? 'Drafting now' : s.next ? 'Next draft ready ' + s.next : 'No next draft is set');
1181
+ /* a report's setup (IsLibrary): Setup (the next draft, Draft it now, Pause, Built from, Sections, Change the setup in Home), Issues and Brief */
1182
+ function openSetup(G, tab0) {
1183
+ const id = G.x.id; let tab = tab0 || 'setup';
1184
+ selRow = G.kind + ':' + id; drawList();
1185
+ viewer({ kind: 'Report' + (cadShort(G.kind === 'setup' ? G.x : G.x.setup) ? ' · ' + cadShort(G.kind === 'setup' ? G.x : G.x.setup).toLowerCase() : ''), title: G.x.name, icon: 'report', id: 'setup:' + id,
1186
+ onClose: () => { if (selRow === G.kind + ':' + id) { selRow = null; drawList(); } }, render: (el) => {
1187
+ const draw = () => {
1188
+ const g = reportGroups().find((x) => x.x.id === id) || G, s = g.kind === 'setup' ? g.x : g.x.setup, st = repState(g);
1189
+ const bar = `<div class="ins-vbar" role="tablist" aria-label="${esc(s.name)}">${[['setup', 'Setup'], ['issues', 'Issues'], ['brief', 'Brief']].map(([k, l]) => `<button type="button" role="tab" class="ins-vtab${tab === k ? ' on' : ''}" aria-selected="${tab === k}" data-st="${k}">${l}</button>`).join('')}</div>`;
1190
+ const sub = [s.audience ? 'For ' + s.audience : '', s.label].filter(Boolean).join(' · ');
1191
+ let body;
1192
+ if (tab === 'issues') body = st.live.length ? st.live.map((f, i) => `<button type="button" class="ins-trow ins-iss" data-file="${i}"><span>${esc(md(day(f.slot)) + ' ' + String(f.slot).slice(0, 4))}</span><span class="cz-pill ${f.state === 'issued' ? 'ok' : 'you'}">${f.state === 'issued' ? 'Issued' : 'Draft'}</span><span class="note">${esc(f.lead ? '“' + f.lead + '”' : '')}</span></button>`).join('') : '<p class="note">No report is written yet. Draft it now writes the first one.</p>';
1193
+ else if (tab === 'brief') body = kvHtml([['What it is for', s.purpose || '—'], s.audience ? ['For', s.audience] : null, s.output ? ['Made as', s.output] : null, ['Schedule', s.label || 'No schedule'], s.lastIssued ? ['Last issued', s.lastIssued] : null, ['Cycles', String(s.cycles || 0)]]) + `<a class="ins-btn sm ghost" href="${esc(changeHref(s))}">Change the brief in Home</a>`;
1194
+ else {
1195
+ const F = fromList(s);
1196
+ body = `<div class="ins-box ins-nb"><span class="small"><b>${esc(nextSay(s))}</b><br><span class="note">PMOS drafts it, you issue it</span></span>${st.draft ? '<button type="button" class="ins-btn sm dark" data-sx="open">Open the draft</button>' : ''}<button type="button" class="ins-btn sm" data-sx="draft">Draft it now</button><button type="button" class="cz-ib sm" data-sx="${s.paused ? 'resume' : 'pause'}" aria-label="${s.paused ? 'Resume' : 'Pause'}" title="${s.paused ? 'Resume' : 'Pause'}">${SV(s.paused ? I.play : I.pause)}</button></div>`
1197
+ + `<p class="ins-lbl">Built from</p><div class="ins-chips2">${F.length ? F.map((x) => `<span class="cz-chip">${esc(x)}</span>`).join('') : '<span class="note">Not recorded</span>'}</div>`
1198
+ + (s.sections && s.sections.length ? '<p class="ins-lbl">Sections</p>' + s.sections.map((x, i) => `<div class="ins-trow"><span>${i + 1} · ${esc(x)}</span></div>`).join('') : '')
1199
+ + `<a class="ins-btn sm ghost" href="${esc(changeHref(s))}">Change the setup in Home</a>`;
1200
+ }
1201
+ el.innerHTML = `<div class="ins-gd">${bar}<div class="ins-gh"><p class="ins-gsub">${esc(sub || s.purpose || '')}</p></div><div class="ins-gb" role="tabpanel">${body}</div><p class="note" data-msg role="status"></p></div>`;
1202
+ };
1203
+ draw();
1204
+ el.addEventListener('click', async (e) => {
1205
+ const t = e.target.closest('[data-st]'); if (t) { tab = t.dataset.st; draw(); return; }
1206
+ const g = reportGroups().find((x) => x.x.id === id) || G, st = repState(g);
1207
+ const fl = e.target.closest('[data-file]'); if (fl) { openFile(g, st.live[+fl.dataset.file]); return; }
1208
+ const b = e.target.closest('[data-sx]'); if (!b) return; const k = b.dataset.sx;
1209
+ if (k === 'open') { openFile(g, st.draft); return; }
1210
+ b.disabled = true;
1211
+ const okd = await postSetup(el, k, { id }, k === 'draft' ? (r) => 'Drafting it now' + (r.drafted && r.drafted.path ? ': ' + r.drafted.path : '.') : (k === 'pause' ? 'Paused ' : 'Resumed ') + G.x.name + '.');
1212
+ if (okd) draw(); else b.disabled = false;
1213
+ });
1214
+ } });
1215
+ }
1216
+ /* the same setup as a sheet on a phone (IsPhone right): Open the draft, Draft it now, Pause, Change the setup in Home */
1217
+ function closeSheet() { for (const x of $$('#repSheet, #repScrim')) x.remove(); }
1218
+ function openSheet(G) {
1219
+ closeSheet();
1220
+ const s = G.kind === 'setup' ? G.x : G.x.setup, st = repState(G), F = fromList(s);
1221
+ const sc = document.createElement('div'); sc.className = 'ins-scrim'; sc.id = 'repScrim'; sc.addEventListener('click', closeSheet);
1222
+ const sh = document.createElement('div'); sh.className = 'ins-sheet'; sh.id = 'repSheet'; sh.setAttribute('role', 'dialog'); sh.setAttribute('aria-label', s.name + ' setup');
1223
+ sh.innerHTML = `<div class="ins-grab"></div><p class="ins-h3">${esc(s.name)}</p><p class="note">${esc([s.label, F.length ? 'built from ' + F.join(', ') : ''].filter(Boolean).join(' · '))}</p>`
1224
+ + (st.live.length ? `<button type="button" class="ins-btn dark wide" data-sx="open">${st.draft ? 'Open the draft' : 'Open the latest'}</button>` : '')
1225
+ + `<div class="ins-acts"><button type="button" class="ins-btn wide" data-sx="draft">Draft it now</button><button type="button" class="ins-btn wide" data-sx="${s.paused ? 'resume' : 'pause'}">${s.paused ? 'Resume' : 'Pause'}</button></div>`
1226
+ + `<a class="ins-btn ghost wide" href="${esc(changeHref(s))}">Change the setup in Home</a><p class="note" data-msg role="status"></p>`;
1227
+ document.body.append(sc, sh);
1228
+ sh.addEventListener('click', async (e) => {
1229
+ const b = e.target.closest('[data-sx]'); if (!b) return; const k = b.dataset.sx;
1230
+ if (k === 'open') { closeSheet(); openFile(G, st.draft || st.live[0]); return; }
1231
+ b.disabled = true;
1232
+ if (await postSetup(sh, k, { id: G.x.id }, k === 'draft' ? 'Drafting it now.' : (k === 'pause' ? 'Paused ' : 'Resumed ') + s.name + '.')) closeSheet(); else b.disabled = false;
1233
+ });
1234
+ const f = sh.querySelector('button'); if (f) f.focus();
1235
+ }
1236
+ /* what PMOS found: why, its evidence and the report it would set up */
1237
+ function openFound(fid) {
1238
+ const f = (M.reports.found || []).find((x) => x.id === fid); if (!f) return;
1239
+ viewer({ kind: 'Found in your work', title: f.name, icon: 'report', id: 'found:' + fid, render: (el) => {
1240
+ el.innerHTML = `<div class="ins-gd"><div class="ins-gh"><p class="ins-gsub">${esc(f.why)}</p>${f.confidence ? `<p class="note">${esc(f.confidence)}</p>` : ''}</div>`
1241
+ + (f.evidence.length ? '<p class="ins-lbl">What PMOS saw</p>' + f.evidence.map((x) => `<div class="ins-trow"><span>${esc(x.text)}</span></div>`).join('') : '')
1242
+ + (f.proposal ? '<p class="ins-lbl">The report it would set up</p>' + kvHtml(f.proposal.rows || []) : '')
1243
+ + '<div class="ins-acts"><button type="button" class="ins-btn sm dark" data-fy="setup">Set it up</button><button type="button" class="ins-btn sm ghost" data-fy="dismiss">Not a report</button></div><p class="note" data-msg role="status"></p></div>';
1244
+ el.addEventListener('click', async (e) => {
1245
+ const b = e.target.closest('[data-fy]'); if (!b) return; b.disabled = true;
1246
+ if (await postSetup(el, b.dataset.fy, { finding: fid }, b.dataset.fy === 'setup' ? (r) => 'Set up ' + f.name + '.' + (r.drafted && r.drafted.path ? ' The first draft is ' + r.drafted.path + '.' : '') : 'Marked as not a report.')) closeViewer(); else b.disabled = false;
1247
+ });
958
1248
  } });
959
1249
  }
1250
+ /* a request from Home (IsLibrary): what was asked, the proposal, and Set it up, Change it or Cancel */
960
1251
  function openRequest(id) {
961
1252
  const a = (M.reports.asks || []).find((x) => x.id === id); if (!a) return;
962
- viewer({ kind: 'Report request', title: a.proposal && a.proposal.name ? a.proposal.name : a.text, icon: 'report', render: (el) => {
963
- const running = a.state === 'running';
964
- el.innerHTML = waitMark('A report request and its proposal') + kvHtml([['You asked', a.text], ['State', running ? 'A background run is working on a proposal' : a.state === 'failed' ? 'The run failed' + (a.error ? ': ' + a.error : '') : 'Proposal ready, not set up']])
965
- + (a.proposal ? kvHtml(a.proposal.rows || []) : '')
966
- + (running ? actionsHtml([['cancel', 'Cancel']]) : `<label class="ins-fl">Change it<input class="ins-inp" data-chg maxlength="300" placeholder="What to change"></label>` + actionsHtml((a.state === 'ready' ? [['setup', 'Set it up', true]] : []).concat([['change', 'Send the change'], ['cancel', 'Cancel']])));
967
- el.addEventListener('click', async (e) => { const b = e.target.closest('[data-act]'); if (!b) return; const k = b.dataset.act;
968
- if (k === 'change') { const t = (el.querySelector('[data-chg]') || {}).value || ''; if (!t.trim()) { el.querySelector('[data-msg]').textContent = 'Say what to change.'; return; } if (await postSetup(el, 'change', { id, text: t.trim() }, 'Sent. A second run revises the proposal.')) openRequest(id); return; }
969
- if (k === 'setup') { await postSetup(el, 'setup', { ask: id }, (r) => 'Set up.' + (r.drafted && r.drafted.path ? ' The first draft is ' + r.drafted.path + '.' : '')); return; }
970
- if (await postSetup(el, 'cancel', { id }, 'Cancelled the request.') && window.czViewer) window.czViewer.close(); });
971
- } });
972
- }
973
- function openAsk() {
974
- viewer({ kind: 'Library', title: 'Ask for a report', icon: 'report', render: (el) => {
975
- el.innerHTML = waitMark('New report') + '<form class="ins-mf" data-ask><label class="ins-fl">What report do you want?<textarea class="ins-ta" name="t" maxlength="600" placeholder="For example: a weekly risk note for leadership"></textarea></label><p class="note">A background run proposes a report. Nothing is set up until you say so.</p><div class="ins-mact"><button type="submit" class="ins-primary">Ask</button><span class="note" data-msg></span></div></form>';
976
- el.querySelector('[data-ask]').addEventListener('submit', async (e) => { e.preventDefault(); const t = e.target.t.value.trim(); if (!t) { el.querySelector('[data-msg]').textContent = 'Say what report you want.'; return; }
977
- if (await postSetup(el, 'ask', { text: t }, 'Asked. The proposal shows in Library when it is ready. Nothing is set up yet.') && window.czViewer) window.czViewer.close(); });
978
- } });
1253
+ selRow = 'ask:' + id; drawList();
1254
+ let changing = false;
1255
+ viewer({ kind: 'Report request', title: a.proposal && a.proposal.name ? a.proposal.name : a.text, icon: 'report', id: 'ask:' + id,
1256
+ onClose: () => { if (selRow === 'ask:' + id) { selRow = null; drawList(); } }, render: (el) => {
1257
+ const draw = () => {
1258
+ const running = a.state === 'running', said = running ? 'A background run is working on a proposal.' : a.state === 'failed' ? 'The run failed' + (a.error ? ': ' + a.error : '.') : 'PMOS proposes the report below. Nothing is set up until you say so.';
1259
+ const acts = running ? [['cancel', 'Cancel', 'ghost']] : (a.state === 'ready' ? [['setup', 'Set it up', 'dark']] : []).concat([['chg', 'Change it', ''], ['cancel', 'Cancel', 'ghost']]);
1260
+ el.innerHTML = `<div class="ins-gd"><p class="ins-lbl">A request from Home</p><div class="ins-need"><span class="small"><b>${esc(a.proposal && a.proposal.name ? a.proposal.name : a.text)}</b> · You asked: “${esc(a.text)}”. ${esc(said)}</span>`
1261
+ + (a.proposal ? kvHtml(a.proposal.rows || []) : '')
1262
+ + (changing ? '<label class="ins-fl">Change it<input class="ins-inp" data-chg maxlength="300" placeholder="What to change"></label>' : '')
1263
+ + `<div class="ins-acts">${changing ? '<button type="button" class="ins-btn sm dark" data-act="change">Send the change</button><button type="button" class="ins-btn sm ghost" data-act="back">Cancel the change</button>' : acts.map(([k, t, c]) => `<button type="button" class="ins-btn sm ${c}" data-act="${k}">${esc(t)}</button>`).join('')}</div></div><p class="note" data-msg role="status"></p></div>`;
1264
+ if (changing) el.querySelector('[data-chg]').focus();
1265
+ };
1266
+ draw();
1267
+ el.addEventListener('click', async (e) => {
1268
+ const b = e.target.closest('[data-act]'); if (!b) return; const k = b.dataset.act;
1269
+ if (k === 'chg') { changing = true; draw(); return; }
1270
+ if (k === 'back') { changing = false; draw(); return; }
1271
+ if (k === 'change') { const t = (el.querySelector('[data-chg]') || {}).value || ''; if (!t.trim()) { el.querySelector('[data-msg]').textContent = 'Say what to change.'; return; } if (await postSetup(el, 'change', { id, text: t.trim() }, 'Sent. A second run revises the proposal.')) { changing = false; draw(); } return; }
1272
+ if (k === 'setup') { if (await postSetup(el, 'setup', { ask: id }, (r) => 'Set up.' + (r.drafted && r.drafted.path ? ' The first draft is ' + r.drafted.path + '.' : ''))) closeViewer(); return; }
1273
+ if (await postSetup(el, 'cancel', { id }, 'Cancelled the request.')) closeViewer();
1274
+ });
1275
+ } });
979
1276
  }
980
1277
 
981
1278
  /* ── load ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── */
@@ -995,7 +1292,7 @@ async function load() {
995
1292
  setTimeout(load, 15000);
996
1293
  return;
997
1294
  }
998
- const first = !M; M = r.model; draw(); if (first || !BM) bmLoad();
1295
+ const first = !M; M = r.model; loadedAt = Date.now(); draw(); if (first || !BM) bmLoad();
999
1296
  }
1000
1297
  { const t = new URLSearchParams(location.search).get('tab'); setTab(t === 'outcomes' || t === 'library' ? t : 'goals'); }
1001
1298
  load();