create-pmos 0.397.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 (195) hide show
  1. package/package.json +25 -25
  2. package/payload/KIT-VERSION +2 -2
  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/payload/state/log.md +1 -1
  7. package/workspace/briefing-premium-adddoc-test.js +105 -52
  8. package/workspace/briefing-premium-board-test.js +284 -128
  9. package/workspace/briefing-premium-calendar-2-test.js +135 -198
  10. package/workspace/briefing-premium-calendar-3-test.js +143 -418
  11. package/workspace/briefing-premium-calendar-test.js +85 -196
  12. package/workspace/briefing-premium-doc-edit-test.js +99 -83
  13. package/workspace/briefing-premium-initiative-test.js +175 -290
  14. package/workspace/briefing-premium-insights-test.js +414 -219
  15. package/workspace/briefing-premium-metrics-test.js +55 -97
  16. package/workspace/briefing-premium-products-test.js +44 -28
  17. package/workspace/briefing-premium-sources-test.js +70 -49
  18. package/workspace/briefing-premium-test.js +155 -648
  19. package/workspace/briefing-premium-work-test.js +88 -283
  20. package/workspace/changelog.json +24 -0
  21. package/workspace/ev-everywhere-test.js +210 -0
  22. package/workspace/fixtures/board-premium-trail.js +32 -0
  23. package/workspace/fixtures/premium-viewer-fixtures.js +187 -0
  24. package/workspace/guide/briefing-premium.md +3 -1
  25. package/workspace/guide/home.md +68 -0
  26. package/workspace/guide/index.md +1 -0
  27. package/workspace/lib/agent-roles.js +71 -0
  28. package/workspace/lib/board-grill.js +63 -0
  29. package/workspace/lib/board-premium.js +121 -24
  30. package/workspace/lib/board-trail.js +223 -0
  31. package/workspace/lib/home-work-item.js +58 -0
  32. package/workspace/lib/initiative-layout.js +77 -0
  33. package/workspace/lib/insights-goals.js +196 -0
  34. package/workspace/lib/insights-premium.js +64 -15
  35. package/workspace/lib/insights-records.js +115 -0
  36. package/workspace/lib/jira-tickets.js +1 -1
  37. package/workspace/lib/meeting-points.js +52 -0
  38. package/workspace/lib/news-for-you.js +88 -0
  39. package/workspace/lib/notes-series.js +29 -6
  40. package/workspace/lib/report-confirm.js +48 -0
  41. package/workspace/lib/route-modules.js +12 -0
  42. package/workspace/lib/routes-board-docs.js +46 -0
  43. package/workspace/lib/routes-board-grill.js +90 -0
  44. package/workspace/lib/routes-board-trail.js +33 -0
  45. package/workspace/lib/routes-home-desk.js +176 -0
  46. package/workspace/lib/routes-home-review.js +108 -0
  47. package/workspace/lib/routes-initiative-layout.js +57 -0
  48. package/workspace/lib/routes-insights-premium.js +16 -4
  49. package/workspace/lib/routes-insights-records.js +133 -0
  50. package/workspace/lib/routes-meeting-points.js +37 -0
  51. package/workspace/lib/routes-news.js +57 -0
  52. package/workspace/lib/routes-notes.js +3 -1
  53. package/workspace/lib/routes-report-confirm.js +31 -0
  54. package/workspace/lib/routes-search.js +38 -0
  55. package/workspace/lib/routes-viewer.js +108 -0
  56. package/workspace/lib/search-index.js +176 -0
  57. package/workspace/lib/transcript-steps.js +123 -0
  58. package/workspace/lib/viewer-meeting.js +205 -0
  59. package/workspace/lib/viewer-report.js +89 -0
  60. package/workspace/package-lock.json +2 -2
  61. package/workspace/package.json +1 -1
  62. package/workspace/premium-board-actions-test.js +128 -82
  63. package/workspace/premium-briefing-depth-test.js +104 -90
  64. package/workspace/premium-chat-attach-test.js +54 -63
  65. package/workspace/premium-chat-chart-tab-test.js +37 -37
  66. package/workspace/premium-chat-context-test.js +19 -18
  67. package/workspace/premium-chat-goal-view-test.js +23 -23
  68. package/workspace/premium-chat-notes-test.js +26 -31
  69. package/workspace/premium-chat-report-tab-test.js +46 -28
  70. package/workspace/premium-chat-term-test.js +16 -16
  71. package/workspace/premium-chat-viewer-test.js +60 -59
  72. package/workspace/premium-core-doc-issue-test.js +52 -43
  73. package/workspace/premium-html-viewer-test.js +14 -17
  74. package/workspace/premium-phone-card-test.js +10 -3
  75. package/workspace/premium-phone-room-test.js +41 -35
  76. package/workspace/premium-report-read-test.js +152 -197
  77. package/workspace/premium-viewer-download-test.js +19 -22
  78. package/workspace/premium-viewer-flicker-test.js +11 -16
  79. package/workspace/premium-viewer-share-test.js +6 -9
  80. package/workspace/premium-viewer-test.js +41 -60
  81. package/workspace/premium-vw-backlog-test.js +53 -33
  82. package/workspace/premium-vw-cal-test.js +97 -128
  83. package/workspace/premium-vw-copy-test.js +17 -33
  84. package/workspace/premium-vw-doc-test.js +17 -10
  85. package/workspace/premium-vw-item-test.js +50 -49
  86. package/workspace/premium-vw-jira-test.js +53 -27
  87. package/workspace/premium-vw-meet-test.js +115 -187
  88. package/workspace/premium-vw-notes-test.js +88 -109
  89. package/workspace/premium-vw-rec-test.js +71 -194
  90. package/workspace/premium-vw-slides-test.js +46 -50
  91. package/workspace/premium-welcome-test.js +3 -2
  92. package/workspace/premium-work-depth-test.js +61 -53
  93. package/workspace/public/pm/bd-acts.js +383 -0
  94. package/workspace/public/pm/bd-asks.js +261 -0
  95. package/workspace/public/pm/bd-pop.js +59 -0
  96. package/workspace/public/pm/bd-span.js +222 -82
  97. package/workspace/public/pm/bd-stages.js +25 -11
  98. package/workspace/public/pm/bd-views.js +169 -0
  99. package/workspace/public/pm/c3-doc-sheet.js +1 -1
  100. package/workspace/public/pm/c3-md.js +3 -395
  101. package/workspace/public/pm/c3-phone-detail.js +1 -1
  102. package/workspace/public/pm/c3-phone-model.js +3 -68
  103. package/workspace/public/pm/chat-term.js +3 -3
  104. package/workspace/public/pm/cozy-board.css +798 -230
  105. package/workspace/public/pm/cozy-ev.css +228 -0
  106. package/workspace/public/pm/cozy-evmodel.js +106 -0
  107. package/workspace/public/pm/cozy-evui.js +47 -0
  108. package/workspace/public/pm/cozy-home.css +570 -142
  109. package/workspace/public/pm/cozy-home.js +5 -3
  110. package/workspace/public/pm/cozy-insights.css +437 -170
  111. package/workspace/public/pm/cozy-md.js +396 -0
  112. package/workspace/public/pm/cozy-nav.js +104 -29
  113. package/workspace/public/pm/cozy-news.js +140 -0
  114. package/workspace/public/pm/cozy-placeholder.js +26 -0
  115. package/workspace/public/pm/cozy-search.js +203 -0
  116. package/workspace/public/pm/cozy-settings.js +198 -0
  117. package/workspace/public/pm/cozy-sources.js +89 -0
  118. package/workspace/public/pm/cozy-today.css +217 -0
  119. package/workspace/public/pm/cozy-viewer.css +3 -3
  120. package/workspace/public/pm/cozy-viewer.js +145 -0
  121. package/workspace/public/pm/cozy-vw-mtg.css +350 -0
  122. package/workspace/public/pm/cozy-vw-rp.css +152 -0
  123. package/workspace/public/pm/cozy-vw.css +485 -0
  124. package/workspace/public/pm/cozy.css +83 -1
  125. package/workspace/public/pm/home-adddoc.js +48 -0
  126. package/workspace/public/pm/home-app.js +1179 -0
  127. package/workspace/public/pm/home-around.js +413 -0
  128. package/workspace/public/pm/home-chat.js +512 -0
  129. package/workspace/public/pm/home-data.js +312 -0
  130. package/workspace/public/pm/home-dictate.js +54 -0
  131. package/workspace/public/pm/home-draft.js +68 -0
  132. package/workspace/public/pm/home-ini-model.js +190 -0
  133. package/workspace/public/pm/home-ini.css +171 -0
  134. package/workspace/public/pm/home-ini.js +456 -0
  135. package/workspace/public/pm/home-list.js +276 -0
  136. package/workspace/public/pm/home-more.js +132 -0
  137. package/workspace/public/pm/home-phone-card.js +109 -0
  138. package/workspace/public/pm/home-review.js +104 -0
  139. package/workspace/public/pm/home-task.js +67 -0
  140. package/workspace/public/pm/home-today.js +144 -0
  141. package/workspace/public/pm/home-work.js +547 -0
  142. package/workspace/public/pm/phone-moment.js +69 -0
  143. package/workspace/public/pm/pm-work-view.js +1 -1
  144. package/workspace/public/pm/premium-attach.js +4 -0
  145. package/workspace/public/pm/premium-board.js +548 -395
  146. package/workspace/public/pm/premium-chart-tab.js +109 -62
  147. package/workspace/public/pm/premium-deck.js +3 -3
  148. package/workspace/public/pm/premium-first.js +23 -21
  149. package/workspace/public/pm/premium-insights.js +1102 -581
  150. package/workspace/public/pm/premium-meeting.js +61 -549
  151. package/workspace/public/pm/premium-mtg-present.js +138 -0
  152. package/workspace/public/pm/premium-mtg-replay.js +142 -0
  153. package/workspace/public/pm/premium-notes.js +1 -1
  154. package/workspace/public/pm/premium-report-frame.css +20 -0
  155. package/workspace/public/pm/premium-report-read.js +669 -476
  156. package/workspace/public/pm/premium-report-tab.js +116 -67
  157. package/workspace/public/pm/premium-shell.js +76 -123
  158. package/workspace/public/pm/premium-viewer.js +22 -1
  159. package/workspace/public/pm/premium-vw-cal.js +277 -48
  160. package/workspace/public/pm/premium-vw-doc.css +6 -0
  161. package/workspace/public/pm/premium-vw-doc.js +40 -2
  162. package/workspace/public/pm/premium-vw-file.js +2 -2
  163. package/workspace/public/pm/premium-vw-meet.js +6 -83
  164. package/workspace/public/pm/premium-vw-mtg.js +958 -0
  165. package/workspace/public/pm/premium-vw-notes.js +116 -68
  166. package/workspace/public/pm/premium-vw-open.js +35 -0
  167. package/workspace/public/pm/premium-vw-page.js +16 -0
  168. package/workspace/public/pm/premium-vw-rec.js +11 -218
  169. package/workspace/public/pm/premium-vw-slides.css +5 -0
  170. package/workspace/public/pm/premium-vw-slides.js +44 -8
  171. package/workspace/public/pm/rp-parts.js +269 -0
  172. package/workspace/public/pm/term-view.js +22 -0
  173. package/workspace/public/premium-board.html +29 -70
  174. package/workspace/public/premium-initiative.html +8 -48
  175. package/workspace/public/premium-insights.html +26 -64
  176. package/workspace/public/premium-viewer.html +20 -0
  177. package/workspace/public/premium.html +18 -107
  178. package/workspace/r/m1.png +0 -0
  179. package/workspace/r/m2.png +0 -0
  180. package/workspace/r/m3.png +0 -0
  181. package/workspace/r/nl.png +0 -0
  182. package/workspace/server.js +18 -3
  183. package/workspace/test-files.json +1 -0
  184. package/workspace/test-lists/home-libs.json +9 -0
  185. package/workspace/test-lists/initiative-layout.json +9 -0
  186. package/workspace/test-lists/premium-report-read.json +1 -1
  187. package/workspace/test-lists/premium-uncovered-meetings.json +9 -0
  188. package/workspace/test-lists/premium-uncovered-reports.json +9 -0
  189. package/workspace/test-lists/premium-vw-agreed.json +9 -0
  190. package/workspace/test-lists/premium-vw-notes.json +1 -1
  191. package/workspace/test-lists/uf-everywhere.json +15 -0
  192. package/workspace/test-lists/uf-home.json +9 -0
  193. package/workspace/test-lists/uncovered-board.json +9 -0
  194. package/workspace/public/pm/premium-work.js +0 -729
  195. package/workspace/public/pm/premium.js +0 -1146
@@ -1,187 +1,365 @@
1
- /* pm/premium-insights.js — the premium Insights page in the Agreed design (initiative premium-agreed-design, G1 and G2, N1 and N2).
2
- * Reads GET /api/insights-premium (lib/insights-premium.js: the KR metric records as goals, the board's initiatives that move them, the dashboards, the report
3
- * files and setups) and GET /api/board-metrics-premium for the Delivery trends tiles. One bar: the product picker, the tabs Goals, Outcomes and Library, the
4
- * view, the period and the icon tools; the floating place menu (pm/cozy-nav.js) replaces the rail.
1
+ /* pm/premium-insights.js — the premium Insights page, drawn to the Agreed design's frames (initiative premium-agreed-design): AgInsGoals, AgInsPeriod,
2
+ * AgInsNewGoal, AgInsNewDash, AgInsChart, AgInsOutcomes, AgInsVerdict, AgInsLibrary and AgInsPhone.
5
3
  *
6
- * Every press of the pages before it stays (briefing-premium-insights, briefing-premium-reports, insights-one-list): a saved dashboard (POST
7
- * /api/premium-dashboards/save), Pin (POST /api/premium-dashboards/pin), the report presses (POST /api/report-setups/ask | change | cancel | setup | dismiss |
8
- * pause | resume | draft), the report reader (pm/premium-report-read.js), a Delivery trends target (POST /api/board-metric-targets/save), and Edit, New chart
9
- * and Shape it, which open the chat with the item in the tab beside it. New here: New goal adds a KR metric record (POST /api/records/kr-metrics/add).
10
- * Ask why and a verdict are made in Home: they open /premium.html with the question in the box. Nothing is sent outward. */
11
- import { $, $$, esc, openDlg, popKey, closeDlg, toast, loadThread, wireRail, logHtml, turnA, ptx, pillOf, kv, setPageGaps, infoBtn } from './premium-shell.js';
4
+ * READS: GET /api/insights-premium (lib/insights-premium.js: the KR metric records as goals, the board's initiatives that move them, the health budgets
5
+ * they anchor to, the dashboards, the report files and setups) and GET /api/board-metrics-premium (the Delivery trends tiles).
6
+ * WRITES, each a press on the page: New goal adds a KR metric record (POST /api/records/kr-metrics/add: metric, baseline, target, by, unit, pillar);
7
+ * New dashboard and Edit chart save a dashboard (POST /api/premium-dashboards/save: name, purpose and its goals in order); Pin (POST
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
+ * is not available yet. Nothing is sent outward.
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. */
24
+ import { $, $$, esc, toast, wireRail, setPageGaps } from './premium-shell.js';
12
25
  import { pmPost } from './http.js';
13
26
  import { openReport } from './premium-report-read.js';
14
- import * as MT from './premium-metric-tiles.js';
15
- import { W, P, X, Y, tileHtml } from './premium-chart-draw.js';
16
27
  import { mountNav } from './cozy-nav.js';
17
28
 
18
29
  let M = null; // the model
30
+ let BM = null, bmErr = ''; // the Board measures (Delivery trends)
19
31
  let dash = null; // the view: a dashboard id; 'all' is every goal
20
32
  let tab = 'goals';
21
- let listF = 'all'; // the Library filter
22
- let per = null; // the period { key, label, sub, from, to }
23
- let find = '', filt = { obj: null, type: null };
24
- let selecting = false; const picked = new Set();
25
- let sugOpen = false;
33
+ let per = null; // the period { key, label, name, from, to }
34
+ let find = '';
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;
38
+ let selecting = false; let picked = []; // New dashboard: the goals picked in the table, in order
26
39
  wireRail('rep');
27
40
  mountNav('insights');
41
+
28
42
  const SV = (d, sw) => `<svg viewBox="0 0 24 24" aria-hidden="true"${sw ? ` stroke-width="${sw}"` : ''}><path d="${d}"/></svg>`;
29
- const DOCI = 'M6 3h9l4 4v14H6zM14 3v5h5M9 13h6M9 17h4';
30
- const PINI = 'M9 3h6l-1 6 4 3v2H6v-2l4-3zM12 14v7';
31
- const CHK = 'M5 12l5 5 9-10';
32
- const byKey = (k) => (M && (M.charts || []).concat(M.mine || []) || []).find((c) => c.key === k) || null;
43
+ const I = {
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',
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',
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',
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',
49
+ };
50
+ const byKey = (k) => (PF && PF.charts[k]) || (M && (M.charts || []).find((c) => c.key === k)) || null;
33
51
  const savedDash = () => (M.dashboards || []).filter((d) => d.saved);
34
52
  const wsQ = () => (M && M.board.ws ? 'ws=' + encodeURIComponent(M.board.ws) + '&' : '');
35
- /** Home with a question in the box (PRD decision: Ask lands in Home). */
36
53
  const homeAsk = (kind, q) => '/premium.html?' + wsQ() + 'ask=' + encodeURIComponent(kind) + '&q=' + encodeURIComponent(q);
54
+ const iniHref = (id) => '/premium-initiative.html?' + wsQ() + 'id=' + encodeURIComponent(id);
55
+ const SRC_NAME = { analytics: 'Product analytics', jira: 'Jira query', file: 'A file or export', typed: 'You type it in' };
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. */
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); };
58
+ /** The cozy select: a native select drawn as the design's field, with a quiet chevron instead of the system arrow. */
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>`;
37
60
 
38
- /* ── small menus: one open at a time, Escape and an outside press close it ─────────────────────────────────────────────────────────────── */
39
- const MENUS = [['#prodPick', '#prodMenu'], ['#viewChip', '#viewMenu'], ['#perChip', '#perMenu'], ['#filtB', '#filtMenu'], ['#newB', '#newMenu'], ['#helpB', '#helpPop'], ['#listNew', '#listMenu'], ['#dashMore', '#dashBar']];
61
+ /* ── the Viewer card (pm/cozy-viewer.js, feature-detected; this page's side panel is the fallback) ──────────────────────────────── */
62
+ function viewer(o) {
63
+ const V = window.czViewer;
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; }
65
+ openSide({ kind: 'view', eye: o.eye || '', title: o.title, body: '', note: '', go: null });
66
+ o.render($('#sideBody'));
67
+ }
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)));
72
+
73
+ /* ── small menus: one open at a time, Escape and an outside press close it ─────────────────────────────────────────────────────── */
74
+ const MENUS = [['#prodPick', '#prodMenu'], ['#viewChip', '#viewMenu'], ['#perChip', '#perMenu'], ['#filtB', '#filtMenu'], ['#newB', '#newMenu'], ['#moreB', '#moreMenu']];
40
75
  function menu(btn, box, open) { $(box).hidden = !open; $(btn).setAttribute('aria-expanded', String(open)); }
41
- function closeMenus(except) { for (const [b, m] of MENUS) if (m !== except && !$(m).hidden) menu(b, m, false); }
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); }
42
77
  for (const [b, m] of MENUS) {
43
78
  $(b).addEventListener('click', (e) => {
44
79
  e.stopPropagation(); const open = $(m).hidden; closeMenus(m); menu(b, m, open);
45
80
  if (open) { const f = $(m).querySelector('button:not([disabled]), input, a'); if (f) f.focus(); }
46
81
  });
47
82
  }
48
- document.addEventListener('click', (e) => { for (const [b, m] of MENUS) if (!$(m).hidden && !e.target.closest(m) && !e.target.closest(b)) menu(b, m, false); });
83
+ document.addEventListener('click', (e) => {
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();
87
+ const om = $('#ngObjMenu'); if (om && !om.hidden && !e.target.closest('#ngObjMenu, #ngObjB')) { om.hidden = true; $('#ngObjB').setAttribute('aria-expanded', 'false'); }
88
+ });
49
89
  document.addEventListener('keydown', (e) => {
50
90
  if (e.key !== 'Escape') return;
91
+ if (!$('#findRow').hidden) { closeFind(true); return; }
92
+ if ($('#tgPop')) { closeTarget(true); return; }
93
+ if ($('#repSheet')) { closeSheet(); return; }
51
94
  for (const [b, m] of MENUS) if (!$(m).hidden) { menu(b, m, false); $(b).focus(); return; }
52
- if (!$('#side').hidden && !$('#dlg').classList.contains('on')) closeSide();
95
+ const om = $('#ngObjMenu'); if (om && !om.hidden) { om.hidden = true; $('#ngObjB').setAttribute('aria-expanded', 'false'); $('#ngObjB').focus(); return; }
96
+ if (!$('#side').hidden) closeSide();
53
97
  });
54
98
 
55
- /* ── the bar: product, tabs, view, period, filter, find ────────────────────────────────────────────────────────────────────────────────── */
56
- function drawBar() {
57
- $('#prodName').textContent = M.board.name || 'Insights';
58
- const boards = M.board.switcher || [];
59
- $('#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('')
60
- : '<p class="note">One product is registered.</p>';
61
- $('#nGoals').textContent = String(goalsShown().length);
62
- $('#nOutcomes').textContent = String((M.outcomes || []).length);
63
- const D = curDash();
64
- $('#viewName').textContent = D.id === 'all' ? 'All goals' : D.name;
65
- $('#viewMenu').innerHTML = M.dashboards.map((d) => `<button type="button" role="menuitemradio" aria-checked="${d.id === D.id}" data-view="${esc(d.id)}">${esc(d.id === 'all' ? 'All goals' : d.name)}<small>${d.id === 'all' ? 'Every goal and budget' : d.saved ? 'Saved dashboard · ' + d.charts.length + ' goals' : 'Objective'}${M.pinned === d.id ? ' · pinned' : ''}</small></button>`).join('');
66
- drawPeriod(); drawFilter();
67
- }
68
- $('#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)); });
69
- $('#viewMenu').addEventListener('click', (e) => { const b = e.target.closest('[data-view]'); if (!b) return; closeMenus(); setView(b.dataset.view); });
70
- function setTab(t) {
71
- tab = t;
72
- for (const b of $$('.ins-tabs [role="tab"]')) { const on = b.dataset.tab === t; b.setAttribute('aria-selected', String(on)); b.tabIndex = on ? 0 : -1; }
73
- $('#pGoals').hidden = t !== 'goals'; $('#pOutcomes').hidden = t !== 'outcomes'; $('#pLibrary').hidden = t !== 'library';
74
- for (const x of $$('.ins-vw')) x.hidden = t !== 'goals';
75
- document.body.dataset.tab = t;
76
- try { history.replaceState(null, '', setQ({ tab: t === 'goals' ? null : t })); } catch { /* no history */ }
77
- }
78
- 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 : ''); };
79
- $('.ins-tabs').addEventListener('click', (e) => { const b = e.target.closest('[role="tab"]'); if (b) setTab(b.dataset.tab); });
80
- $('.ins-tabs').addEventListener('keydown', (e) => {
81
- if (!/^Arrow(Left|Right)$/.test(e.key)) return;
82
- const T = $$('.ins-tabs [role="tab"]'), i = T.findIndex((x) => x.getAttribute('aria-selected') === 'true'), n = T[(i + (e.key === 'ArrowRight' ? 1 : T.length - 1)) % T.length];
83
- setTab(n.dataset.tab); n.focus();
84
- });
85
- function setView(id) { dash = id; setTab('goals'); drawGoals(); drawDash(); drawBar(); drawList(); }
86
-
87
- /* the period (AgInsPeriod): this quarter, last quarter, this half, this year, or custom dates. A goal shows when its period overlaps the one picked. */
99
+ /* ── dates and the period (AgInsPeriod) ─────────────────────────────────────────────────────────────────────────────────────────── */
88
100
  const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
101
+ const DAY = 864e5;
89
102
  const day = (s) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(s || '')); return m ? Date.UTC(+m[1], +m[2] - 1, +m[3]) : null; };
90
103
  const iso = (t) => new Date(t).toISOString().slice(0, 10);
91
- const md = (t) => { const d = new Date(t); return MON[d.getUTCMonth()] + ' ' + d.getUTCDate(); };
104
+ const md = (t) => { if (t == null) return ''; const d = new Date(t); return MON[d.getUTCMonth()] + ' ' + d.getUTCDate(); };
105
+ const today = () => day(M && M.today) || Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), new Date().getUTCDate());
92
106
  function periods() {
93
- const t = day(M.today) || Date.now(), d = new Date(t), y = d.getUTCFullYear(), q = Math.floor(d.getUTCMonth() / 3), h = d.getUTCMonth() < 6 ? 0 : 1;
107
+ const d = new Date(today()), y = d.getUTCFullYear(), q = Math.floor(d.getUTCMonth() / 3), h = d.getUTCMonth() < 6 ? 0 : 1;
94
108
  const span = (y0, m0, y1, m1) => ({ from: Date.UTC(y0, m0, 1), to: Date.UTC(y1, m1, 0) });
95
109
  const lq = q ? { y, q: q - 1 } : { y: y - 1, q: 3 };
96
110
  return [
97
- Object.assign({ key: 'q', label: 'Q' + (q + 1) + ' ' + y, name: 'This quarter' }, span(y, q * 3, y, q * 3 + 3)),
98
- Object.assign({ key: 'lq', label: 'Q' + (lq.q + 1) + ' ' + lq.y, name: 'Last quarter' }, span(lq.y, lq.q * 3, lq.y, lq.q * 3 + 3)),
99
- Object.assign({ key: 'h', label: 'H' + (h + 1) + ' ' + y, name: 'This half' }, span(y, h * 6, y, h * 6 + 6)),
100
- Object.assign({ key: 'y', label: String(y), name: 'This year' }, span(y, 0, y + 1, 0)),
111
+ Object.assign({ key: 'q', label: 'Q' + (q + 1) + ' ' + y, short: 'Q' + (q + 1), name: 'This quarter', said: 'this quarter' }, span(y, q * 3, y, q * 3 + 3)),
112
+ Object.assign({ key: 'lq', label: 'Q' + (lq.q + 1) + ' ' + lq.y, short: 'Q' + (lq.q + 1), name: 'Last quarter', said: 'last quarter' }, span(lq.y, lq.q * 3, lq.y, lq.q * 3 + 3)),
113
+ Object.assign({ key: 'h', label: 'H' + (h + 1) + ' ' + y, short: 'H' + (h + 1), name: 'This half', said: 'this half' }, span(y, h * 6, y, h * 6 + 6)),
114
+ Object.assign({ key: 'y', label: String(y), short: String(y), name: 'This year', said: 'this year' }, span(y, 0, y + 1, 0)),
101
115
  ];
102
116
  }
103
- const inPer = (g) => {
104
- if (!per) return true;
117
+ const inPer = (g, p = per) => {
118
+ if (!p) return true;
105
119
  const a = day(g.fromAt) ?? day(g.byAt), b = day(g.byAt) ?? day(g.fromAt);
106
- return a === null ? true : a <= per.to && b >= per.from;
120
+ return a === null ? true : a <= p.to && b >= p.from;
107
121
  };
108
122
  function drawPeriod() {
109
123
  const P = periods(); if (!per) per = P[0];
110
- const t = day(M.today) || Date.now(), total = Math.round((per.to - per.from) / 864e5) + 1, gone = Math.max(0, Math.min(total, Math.round((t - per.from) / 864e5) + 1));
111
- per.gone = gone; per.total = total;
124
+ const t = today(), total = Math.round((per.to - per.from) / DAY) + 1, gone = Math.max(0, Math.min(total, Math.round((t - per.from) / DAY) + 1));
125
+ per.gone = t >= per.from && t <= per.to ? gone : 0; per.total = total;
112
126
  $('#perName').textContent = per.label;
113
- $('#perSub').textContent = tab === 'outcomes' ? 'shipped or judged' : md(per.from) + ' – ' + md(per.to) + (t >= per.from && t <= per.to ? ' · day ' + gone + ' of ' + total : '');
114
- const n = (p) => M.goals.filter((g) => { const o = per; per = p; const r = inPer(g); per = o; return r; }).length;
115
- $('#perMenu').innerHTML = P.map((p) => `<button type="button" role="menuitemradio" aria-checked="${per.key === p.key}" data-per="${p.key}">${per.key === p.key ? SV(CHK) : '<i class="ins-ck"></i>'}<span>${esc(p.name + ' · ' + p.label)}<small>${esc(md(p.from) + ' – ' + md(p.to) + ' · ' + n(p) + (n(p) === 1 ? ' goal' : ' goals'))}</small></span></button>`).join('')
116
- + `<button type="button" role="menuitemradio" aria-checked="${per.key === 'c'}" data-per="c">${per.key === 'c' ? SV(CHK) : '<i class="ins-ck"></i>'}<span>Custom<small>Pick a start and end date</small></span></button>`
127
+ $('#perSub').innerHTML = tab === 'outcomes' ? `<span class="ins-perr">shipped or judged ${esc(per.said || 'in these dates')}</span>`
128
+ : `<span class="ins-perr">${esc(md(per.from) + ' – ' + md(per.to))}${per.gone ? ' · ' : ''}</span>${per.gone ? `<span class="ins-perday">day ${gone} of ${total}</span>` : ''}`;
129
+ const n = (p) => M.goals.filter((g) => inPer(g, p)).length, goals = (k) => k + (k === 1 ? ' goal' : ' goals');
130
+ /* a closed period: the goals due in it, and how many reached their target by their date (a reading on or before it) */
131
+ const hits = (p) => { let k = 0, h = 0; for (const g of M.goals) { const by = day(g.byAt); if (by === null || by < p.from || by > p.to) continue; k++; const dir = g.target !== null && g.base !== null ? Math.sign(g.target - g.base) : 0; if (dir && (g.series || []).some((r) => day(r.at) <= by && (dir > 0 ? r.v >= g.target : r.v <= g.target))) h++; } return { k, h }; };
132
+ /* a year names its yearly goals, each shown in a quarter with that quarter's checkpoint (AgInsPeriod) */
133
+ const yearly = (p) => M.goals.filter((g) => inPer(g, p) && g.period && g.period.kind === 'Year').length;
134
+ const sub = (p) => { if (p.key === 'y' && yearly(p)) { const k = yearly(p); return k + (k === 1 ? ' yearly goal, with quarter checkpoints' : ' yearly goals, each with quarter checkpoints'); }
135
+ if (p.to >= t) return md(p.from) + ' – ' + md(p.to) + ' · ' + goals(n(p)); const x = hits(p); return 'Closed · ' + goals(n(p)) + (x.k ? ', ' + x.h + ' of ' + x.k + ' due in it hit' : ', none due in it'); };
136
+ $('#perMenu').innerHTML = P.map((p) => `<button type="button" role="menuitemradio" aria-checked="${per.key === p.key}" data-per="${p.key}">${per.key === p.key ? SV(I.chk) : '<i class="ins-ck"></i>'}<span>${esc(p.name + ' · ' + p.label)}<small>${esc(sub(p))}</small></span></button>`).join('')
137
+ + `<button type="button" role="menuitemradio" aria-checked="${per.key === 'c'}" data-per="c">${per.key === 'c' ? SV(I.chk) : '<i class="ins-ck"></i>'}<span>Custom<small>Pick a start and end date</small></span></button>`
117
138
  + `<div class="ins-cust" id="perCust" ${per.key === 'c' ? '' : 'hidden'}><label>From<input type="date" id="perFrom" value="${esc(iso(per.from))}"></label><label>To<input type="date" id="perTo" value="${esc(iso(per.to))}"></label><button type="button" class="cz-chip" id="perGo">Apply</button></div>`
118
- + '<p class="note ins-mnote">A goal shows here when its period overlaps the one you pick. A goal with no date always shows.</p>';
139
+ + '<p class="note ins-mnote">A goal shows here when its period overlaps the one you pick. A yearly goal in a quarter shows that quarter’s checkpoint. Health budgets have no end, so they always show.</p>';
119
140
  }
120
141
  $('#perMenu').addEventListener('click', (e) => {
121
142
  if (e.target.closest('#perGo')) {
122
143
  const a = day($('#perFrom').value), b = day($('#perTo').value);
123
144
  if (a === null || b === null || b < a) { toast('Pick a start date before the end date.'); return; }
124
- per = { key: 'c', label: 'Custom', from: a, to: b }; closeMenus(); redraw(); return;
145
+ per = { key: 'c', label: 'Custom', short: 'these dates', name: 'Custom', said: 'in these dates', from: a, to: b }; closeMenus(); redraw(); return;
125
146
  }
126
147
  const b = e.target.closest('[data-per]'); if (!b) return;
127
148
  if (b.dataset.per === 'c') { $('#perCust').hidden = false; $('#perFrom').focus(); return; }
128
149
  per = periods().find((p) => p.key === b.dataset.per); closeMenus(); redraw();
129
150
  });
151
+
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
154
+ const curDash = () => M.dashboards.find((d) => d.id === dash) || M.dashboards[0];
155
+ const dashName = (D) => (D.id === 'all' ? 'All goals' : D.name);
156
+ const nGoals = (k) => k + (k === 1 ? ' goal' : ' goals');
157
+ function drawBar() {
158
+ $('#prodName').textContent = PF ? 'Portfolio' : M.board.name || 'Insights';
159
+ const boards = M.board.switcher || [];
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);
165
+ $('#nOutcomes').textContent = String(outcomesShown().length);
166
+ const D = curDash();
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>`;
172
+ drawPeriod(); drawFilter();
173
+ }
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
+ });
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 : ''); };
185
+ function setTab(t) {
186
+ tab = t;
187
+ for (const b of $$('.ins-tabs [role="tab"]')) { const on = b.dataset.tab === t; b.setAttribute('aria-selected', String(on)); b.tabIndex = on ? 0 : -1; }
188
+ $('#pGoals').hidden = t !== 'goals'; $('#pOutcomes').hidden = t !== 'outcomes'; $('#pLibrary').hidden = t !== 'library';
189
+ for (const x of $$('.ins-vw')) x.hidden = t !== 'goals';
190
+ document.body.dataset.tab = t;
191
+ if (M) drawPeriod(); // the period chip says "shipped or judged" on Outcomes
192
+ try { history.replaceState(null, '', setQ({ tab: t === 'goals' ? null : t })); } catch { /* no history */ }
193
+ }
194
+ $('.ins-tabs').addEventListener('click', (e) => { const b = e.target.closest('[role="tab"]'); if (b) setTab(b.dataset.tab); });
195
+ $('.ins-tabs').addEventListener('keydown', (e) => {
196
+ if (!/^Arrow(Left|Right)$/.test(e.key)) return;
197
+ const T = $$('.ins-tabs [role="tab"]'), i = T.findIndex((x) => x.getAttribute('aria-selected') === 'true'), n = T[(i + (e.key === 'ArrowRight' ? 1 : T.length - 1)) % T.length];
198
+ setTab(n.dataset.tab); n.focus();
199
+ });
200
+ function setView(id) { dash = id; setTab('goals'); redraw(); }
201
+
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);
238
+ function filterValues() {
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 };
240
+ }
130
241
  function drawFilter() {
131
- const objs = [...new Set(M.goals.map((g) => g.pillar || ''))], types = [...new Set(M.goals.map((g) => g.type))];
132
- 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(CHK) : '<i class="ins-ck"></i>'}<span>${esc(label)}</span></button>`;
133
- $('#filtMenu').innerHTML = '<p class="ins-mh">Objective</p>' + objs.map((o) => row('obj', o, o || 'No objective')).join('') + '<p class="ins-mh">Type</p>' + types.map((t) => row('type', t, t)).join('')
134
- + (filt.obj !== null || filt.type !== null ? '<button type="button" data-fclr>Clear the filter</button>' : '');
135
- $('#filtDot').hidden = filt.obj === null && filt.type === null;
242
+ const V = filterValues();
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>');
246
+ $('#filtDot').hidden = noFilter();
136
247
  }
137
248
  $('#filtMenu').addEventListener('click', (e) => {
138
- if (e.target.closest('[data-fclr]')) { filt = { obj: null, type: null }; closeMenus(); redraw(); return; }
249
+ e.stopPropagation();
250
+ if (e.target.closest('[data-fclr]')) { clearFilter(); closeMenus(); redraw(); return; }
139
251
  const b = e.target.closest('[data-fk]'); if (!b) return;
140
- 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);
141
254
  });
142
- $('#findB').addEventListener('click', () => { const open = $('#findRow').hidden; $('#findRow').hidden = !open; $('#findB').setAttribute('aria-expanded', String(open)); if (open) $('#findIn').focus(); });
143
- $('#findIn').addEventListener('input', () => { find = $('#findIn').value.trim().toLowerCase(); redraw(); });
144
- $('#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));
145
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
+ });
284
+
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'; });
287
+ $('#moreMenu').addEventListener('click', (e) => {
288
+ const b = e.target.closest('[data-more]'); if (!b || b.disabled) return; closeMenus();
289
+ if (b.dataset.more === 'sources') viewer({ kind: 'Insights', title: 'Sources', icon: 'source', eye: 'What this page reads', render: (el) => { el.innerHTML = sourcesHtml(); } });
290
+ else if (b.dataset.more === 'export') location.assign('/api/insights-records/export?' + wsQ() + (M.board.id ? 'board=' + encodeURIComponent(M.board.id) : ''));
291
+ else if (b.dataset.more === 'about') viewer({ kind: 'Insights', title: 'About these numbers', icon: 'info', eye: 'Insights', render: (el) => { el.innerHTML = ABOUT; } });
292
+ });
293
+ function sourcesHtml() {
294
+ const miss = (M.header && M.header.missing) || [];
295
+ const rows = [
296
+ ['Goals', 'The KR metric records of this workspace and their readings (planning/records/kr-metrics.jsonl)', !miss.includes('outcomes')],
297
+ ['What moves them', 'The board’s initiatives and their anchors', M.initiativesRead],
298
+ ['Health budgets', 'The budget registry (planning/okrs/health-budgets.md) and the initiatives anchored to health:<id>', M.budgetsRead && M.initiativesRead],
299
+ ['Charts and verdicts', 'Each chart’s form and range, the verdicts and the trend targets (the workspace’s insights-records.jsonl)', !((M.header && M.header.missing) || []).includes('insights records')],
300
+ ['Delivery trends', 'The Board’s measures (corrections, merges, blocked and idle work)', !!BM],
301
+ ['Library', 'The report files, the report setups and your requests', !M.reports.missing],
302
+ ];
303
+ return `<div class="ins-src">${rows.map(([a, b, ok]) => `<div><b>${esc(a)}</b><span>${esc(b)}</span><span class="cz-pill ${ok ? 'ok' : 'late'}">${ok ? 'Read' : 'Not read'}</span></div>`).join('')}</div>`
304
+ + (miss.length ? `<p class="note">Not read on the last load: ${esc(miss.join(', '))}.</p>` : '');
305
+ }
306
+ const ABOUT = '<div class="ins-about"><p>Every goal is a KR metric record of this workspace, and every number on Goals is one of its readings, its target or its date. The bar under Now has a mark for how much of the goal’s time has gone.</p>'
307
+ + '<p>“By its date” is a straight line through the last four readings, carried to the goal’s date. It is said, not drawn as a fact. A goal with fewer than two readings has no line and no pace.</p>'
308
+ + '<p>What moves a goal is every initiative whose anchor names it. Its pill is read from its end date and owner: days over, ships soon, or no owner.</p>'
309
+ + '<p>A press records only what it says: a goal in the KR metric records, or a dashboard in the workspace’s state folder. Nothing is sent from this page.</p></div>';
146
310
 
147
- /* ── the strip: the strongest finding, and Ask why (Home) ─────────────────────────────────────────────────────────────────────────────── */
311
+ /* ── the strip ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────── */
148
312
  function drawStrip() {
149
- const I = M.insight, G = goalsShown();
313
+ const I0 = M.insight, G = goalsShown();
150
314
  const behind = G.filter((g) => g.tone === 'late' || g.tone === 'red').length;
151
- $('#insEye').textContent = per && per.gone && per.label !== 'Custom' ? per.gone + ' of ' + per.total + ' days gone in ' + per.label + '.' : G.length + (G.length === 1 ? ' goal' : ' goals') + (behind ? ', ' + behind + ' behind.' : '.');
152
- $('#brief').textContent = I.text;
153
- $('#insWhy').textContent = I.none ? '' : I.why || '';
154
- $('#insMore').innerHTML = (I.more || []).map((x) => `<li><button type="button" class="lk" data-open="${esc(x.chart)}" aria-haspopup="dialog">${esc(x.text)}</button></li>`).join('');
155
- $('#askWhy').href = homeAsk('insights', I.none ? 'Why is there no insight on my goals yet?' : 'Why? ' + I.text);
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; }
317
+ $('#brief').textContent = I0.text;
318
+ $('#insWhy').textContent = I0.none ? '' : I0.why || '';
319
+ $('#askWhy').href = homeAsk('insights', I0.none ? 'Why is there no insight on my goals yet?' : 'Why? ' + I0.text);
156
320
  $('#askWhy').hidden = false;
157
321
  }
158
- $('#insHero').addEventListener('click', (e) => { const o = e.target.closest('[data-open]'); if (o) openChart(byKey(o.dataset.open)); });
159
322
 
160
- /* ── Goals (G1): the table, grouped by objective ──────────────────────────────────────────────────────────────────────────────────────── */
323
+ /* ── Goals (AgInsGoals) ─────────────────────────────────────────────────────────────────────────────────────────────────────────── */
161
324
  const COLS = 'ins-cols';
162
- const curDash = () => M.dashboards.find((d) => d.id === dash) || M.dashboards[0];
325
+ const ownerHit = (L) => !filt.owner.length || L.some((o) => filt.owner.includes(o));
163
326
  function goalsShown() {
164
- const D = curDash(), ids = D.saved ? D.charts : D.id.startsWith('p:') ? null : null;
165
- return M.goals.filter((g) => inPer(g) && (!ids || ids.includes(g.id)) && (!D.id.startsWith('p:') || g.pillar === D.name)
166
- && (filt.obj === null || (g.pillar || '') === filt.obj) && (filt.type === null || g.type === filt.type) && 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)));
332
+ return ids ? L.sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id)) : L;
167
333
  }
168
- const TRACK_TONE = { late: 'late', 'at risk': 'risk', done: 'ok', 'on track': 'ok' };
169
- /** The lifecycle track: six stages and two milestones (◆); the current stage is the large dot in the initiative's status colour. */
334
+ const TRACK_TONE = { late: 'late', 'at risk': 'risk', done: 'ok', 'on track': 'ok', 'on hold': 'q' };
335
+ /** The lifecycle track: six stages and two milestones; the current stage is the large dot in the initiative's status colour. A stage the Board
336
+ * recorded as skipped (its "Skipped <stage>" warning) is a dashed ring. */
170
337
  function trackHtml(r) {
171
- const tone = TRACK_TONE[r.status] || 'q';
338
+ const tone = TRACK_TONE[r.status] || 'q', labels = (M.lifecycle || []).map((x) => x.label.toLowerCase()), skip = new Set((r.skipped || []).map((x) => labels.indexOf(String(x).toLowerCase())).filter((i) => i >= 0));
172
339
  return `<span class="ins-trk" title="${esc(r.stageLabel || 'No stage')}" aria-label="${esc((r.stageLabel ? 'Stage ' + r.stageLabel : 'No lifecycle stage') + (r.status ? ', ' + r.status : ''))}" role="img">`
173
- + [0, 1, 2, 3, 4, 5, 6, 7].map((i) => `<i class="${[i < r.idx ? 'p' : '', i === r.idx ? 'c ' + tone : '', i === 5 || i === 7 ? 'm' : ''].filter(Boolean).join(' ')}"></i>`).join('') + '</span>';
340
+ + [0, 1, 2, 3, 4, 5, 6, 7].map((i) => `<i class="${[skip.has(i) && i !== r.idx ? 'k' : i < r.idx ? 'p' : '', i === r.idx ? 'c ' + tone : '', i === 5 || i === 7 ? 'm' : ''].filter(Boolean).join(' ')}"></i>`).join('') + '</span>';
341
+ }
342
+ /** The pill of an initiative that moves a goal: a delivery fact read from its end date and owner, else its status. */
343
+ function movePill(r) {
344
+ if (r.status === 'done') return ['ok', 'Done'];
345
+ if (r.status === 'cancelled') return ['q', 'Stopped'];
346
+ const end = day(r.endAt), d = end === null ? null : Math.round((end - today()) / DAY);
347
+ if (d !== null && d < 0 && r.idx < 6) return ['late', -d + (d === -1 ? ' day over' : ' days over')]; // Monitor and Evaluate have shipped
348
+ if (!r.owner) return ['risk', 'No owner'];
349
+ if (d === 0) return ['q', 'Ships today'];
350
+ if (d === 1) return ['q', 'Ships tomorrow'];
351
+ if (d !== null && d >= 0 && d <= 14) return ['q', 'Ships in ' + d + ' days'];
352
+ return { late: ['late', 'Late'], 'at risk': ['risk', 'At risk'], 'on hold': ['q', 'On hold'], 'on track': ['q', 'On track'] }[r.status] || null;
174
353
  }
175
- const ST_PILL = { late: ['late', 'Late'], 'at risk': ['risk', 'At risk'], 'on hold': ['q', 'On hold'], done: ['ok', 'Done'], cancelled: ['q', 'Cancelled'], 'on track': ['q', 'On track'] };
176
- const initRow = (r) => { const p = ST_PILL[r.status]; return `<a class="ins-ini" href="/premium-initiative.html?${wsQ()}id=${encodeURIComponent(r.id)}">${trackHtml(r)}<span class="n">${esc(r.title)}</span>${p ? `<span class="cz-pill ${p[0]}">${esc(p[1])}</span>` : ''}</a>`; };
354
+ const initRow = (r, pill = true) => { const p = pill ? movePill(r) : null; return `<a class="ins-ini" href="${iniHref(r.id)}">${trackHtml(r)}<span class="n">${esc(r.title)}</span>${p ? `<span class="cz-pill ${p[0]}">${esc(p[1])}</span>` : ''}</a>`; };
177
355
  const TONE_BAR = { ok: 'var(--cz-dot-ok)', late: 'var(--cz-dot-late)', red: 'var(--cz-dot-red)', q: 'var(--cz-dot-q)', risk: 'var(--cz-dot-risk)' };
178
- function barHtml(g) {
179
- return `<div class="ins-bar1" role="img" aria-label="${g.done === null ? 'No progress to read' : Math.round(g.done * 100) + '% of the way to the target'}${g.timeGone === null ? '' : ', ' + Math.round(g.timeGone * 100) + '% of its time gone'}"><i style="width:${g.done === null ? 0 : Math.round(g.done * 100)}%;background:${TONE_BAR[g.tone]}"></i>${g.timeGone === null ? '' : `<span class="today" title="today" style="left:${Math.round(g.timeGone * 100)}%"></span>`}</div>`;
356
+ function barHtml(g, cls = '') {
357
+ return `<div class="ins-bar1${cls}" role="img" aria-label="${g.done === null ? 'No progress to read' : Math.round(g.done * 100) + '% of the way to the target'}${g.timeGone == null ? '' : ', ' + Math.round(g.timeGone * 100) + '% of its time gone'}"><i style="width:${g.done === null ? 0 : Math.round(g.done * 100)}%;background:${TONE_BAR[g.tone] || TONE_BAR.q}"></i>${g.timeGone == null ? '' : `<span class="today" title="today" style="left:${Math.round(g.timeGone * 100)}%"></span>`}</div>`;
180
358
  }
181
- /** The so-far sparkline: the readings at their dates across the goal's span, the target as a dashed line, and the pace carried to the date, dashed. */
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. */
182
360
  function sparkHtml(g, w = 210, h = 40) {
183
361
  const c = g.key ? byKey(g.key) : null;
184
- 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
185
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);
186
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;
187
365
  const x = (t) => 5 + (t1 > t0 ? (t - t0) / (t1 - t0) : 1) * (w - 10), y = (v) => 4 + (1 - (v - lo) / rg) * (h - 8);
@@ -190,391 +368,750 @@ function sparkHtml(g, w = 210, h = 40) {
190
368
  const proj = g.proj && day(g.byAt) > tl ? `<polyline points="${last.join(',')} ${x(day(g.byAt)).toFixed(1)},${y(g.proj.atDue).toFixed(1)}" class="pj"/>` : '';
191
369
  return `<svg class="ins-spark" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" role="img" aria-label="${esc(g.title + ': ' + c.pts.length + ' readings' + (g.targetTxt ? ', target ' + g.targetTxt : ''))}"><polygon points="${fill}" class="ar"/>${g.target !== null ? `<line x1="0" x2="${w}" y1="${y(g.target).toFixed(1)}" y2="${y(g.target).toFixed(1)}" class="tg"/>` : ''}${proj}<polyline points="${pts.join(' ')}" class="ln"/><circle cx="${last[0]}" cy="${last[1]}" r="3.6" class="dt" style="fill:${TONE_BAR[g.tone]}"/></svg>`;
192
370
  }
193
- const PACE_C = { ok: 'var(--cz-ok)', late: 'var(--cz-late)', q: 'var(--cz-ink3)' };
371
+ /** A Count goal with a small whole target is drawn as blocks: one per unit of the target, the ones reached filled. */
372
+ const isBlocks = (g) => g.type === 'Count' && Number.isInteger(g.target) && g.target >= 1 && g.target <= 12 && Number.isInteger(g.now) && g.now >= 0;
373
+ const blocksHtml = (g, w, names = true) => `<div class="ins-blocks" style="width:${w}px" role="img" aria-label="${esc(g.now + ' of ' + g.target)}">${Array.from({ length: g.target }, (_, i) => `<i class="${i < g.now ? 'on' : ''}"></i>`).join('')}</div>`
374
+ + (names && g.items && g.items.length ? `<div class="note ins-items">${esc(g.items.slice(0, g.now).join(', '))}</div>` : ''); // the reached items, when the goal records them
375
+ /** Done or not: its steps as a checklist; Stay within: the readings over a green band that marks the budget, with no forecast. */
376
+ const stepsHtml = (g) => `<div class="ins-steps">${(g.steps || []).map((s) => `<span class="${s.done ? 'on' : ''}"><i class="ins-cb${s.done ? ' on' : ''}">${s.done ? SV(I.chk, 3) : ''}</i>${esc(s.text)}</span>`).join('')}</div>`;
377
+ /** pts [{ at, v }] over a band: the floor or ceiling `lim` to the chart's edge is green (inside the budget); the line has no target line and no
378
+ * forecast. ceil: the budget is below the limit. One reading is drawn as a dot. */
379
+ function bandSvg(pts, lim, ceil, tone, label, w = 210, h = 40) {
380
+ const ys = pts.map((p) => p.v).concat([lim]), lo = Math.min(...ys), hi = Math.max(...ys), rg = hi - lo || 1;
381
+ const t0 = day(pts[0].at), t1 = day(pts[pts.length - 1].at), x = (t) => (t1 > t0 ? 5 + (t - t0) / (t1 - t0) * (w - 10) : w - 5), y = (v) => 4 + (1 - (v - lo) / rg) * (h - 8);
382
+ const yl = y(lim), band = ceil ? `<rect x="0" y="${yl.toFixed(1)}" width="${w}" height="${(h - yl).toFixed(1)}" class="bd"/>` : `<rect x="0" y="0" width="${w}" height="${yl.toFixed(1)}" class="bd"/>`;
383
+ const L = pts.map((p) => x(day(p.at)).toFixed(1) + ',' + y(p.v).toFixed(1)), last = L[L.length - 1].split(',');
384
+ const line = L.length > 1 ? `<polygon points="${L[0].split(',')[0]},${h} ${L.join(' ')} ${last[0]},${h}" class="ar"/><polyline points="${L.join(' ')}" class="ln"/>` : '';
385
+ return `<svg class="ins-spark" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" role="img" aria-label="${esc(label)}">${band}${line}<circle cx="${last[0]}" cy="${last[1]}" r="3.6" class="dt" style="fill:${TONE_BAR[tone] || TONE_BAR.q}"/></svg>`;
386
+ }
387
+ function soFarHtml(g, w = 210) {
388
+ if (g.type === 'Done or not') return g.steps && g.steps.length ? stepsHtml(g) : '<span class="note">No steps recorded</span>';
389
+ if (g.type === 'Stay within' && g.target !== null && g.series && g.series.length) {
390
+ return bandSvg(g.series, g.target, g.limit !== 'floor', g.pace && g.pace.tone !== 'q' ? g.pace.tone : g.tone, g.title + ': ' + g.series.length + (g.series.length === 1 ? ' reading' : ' readings') + ', the green band is inside the budget', w);
391
+ }
392
+ if (isBlocks(g)) return blocksHtml(g, w);
393
+ return sparkHtml(g, w);
394
+ }
395
+ const PACE_C = { ok: 'var(--cz-ok)', late: 'var(--cz-late)', risk: 'var(--cz-risk)', q: 'var(--cz-ink3)' };
396
+ function goalSub(g) {
397
+ const by = day(g.byAt), late = per && by !== null && by > per.to && per.key !== 'y' && per.key !== 'c';
398
+ if (g.type === 'Done or not') return [g.steps && g.steps.length ? g.steps.filter((x) => x.done).length + ' of ' + g.steps.length + ' steps' : '', by !== null ? 'due ' + md(by) : ''].filter(Boolean).join(' · ');
399
+ if (g.type === 'Stay within') return [g.dirTxt + ' ' + (g.targetTxt || ''), g.alwaysOn ? 'always on' : by !== null ? 'until ' + md(by) : ''].filter(Boolean).join(' · ');
400
+ const from = g.baseTxt ? 'from ' + g.baseTxt + (g.fromAt && (g.type === 'Percentage' || g.type === 'Amount') ? ' on ' + md(day(g.fromAt)) : '') : '';
401
+ const cp = late ? (g.checkpoints || []).find((c) => day(c.by) >= per.from && day(c.by) <= per.to) : null;
402
+ const unitOf = (v) => { const u = String(g.unit || '').trim(); return v + (u ? (/^[A-Za-z]/.test(u) ? ' ' + u : u) : ''); };
403
+ return [g.dirTxt, from, late ? 'due ' + md(by) + ' ' + new Date(by).getUTCFullYear() + ' · ' + (cp ? per.short + ' checkpoint ' + unitOf(cp.target) : 'no ' + per.short + ' checkpoint recorded') : ''].filter(Boolean).join(' · ');
404
+ }
194
405
  function goalRow(g) {
195
- const sel = selecting && picked.has(g.id);
196
- const sub = [g.dirTxt, g.baseTxt ? 'from ' + g.baseTxt + (g.from ? ' on ' + g.from : '') : ''].filter(Boolean).join(' · ');
197
- return `<div class="ins-tr ins-row ${COLS}${sel ? ' sel' : ''}" role="row" data-goal="${esc(g.id)}"${g.key ? ` data-open="${esc(g.key)}"` : ''} tabindex="0" aria-label="${esc(g.title)}">`
198
- + `<div class="nm" role="cell">${selecting ? `<span class="ins-cb${sel ? ' on' : ''}" role="checkbox" aria-checked="${sel}" aria-label="Select ${esc(g.title)}">${sel ? SV(CHK, 3) : ''}</span>` : ''}<span><b>${esc(g.title)}</b><small><span class="cz-pill q ins-type">${esc(g.type)}</span>${esc(sub)}</small></span></div>`
406
+ const sel = selecting && picked.includes(g.id);
407
+ return `<div class="ins-tr ins-row ${COLS}${sel ? ' sel' : ''}" role="row" data-goal="${esc(g.id)}" tabindex="0" aria-label="${esc(g.title)}"${selecting ? ` aria-selected="${sel}"` : ''}>`
408
+ + `<div class="nm" role="cell"><span><b>${esc(g.title)}</b><small><span class="cz-pill q ins-type">${esc(g.type)}</span><span class="ins-sub" title="${esc(goalSub(g))}">${esc(goalSub(g))}</span></small></span></div>`
199
409
  + `<div class="val" role="cell"><b>${esc(g.nowTxt || '—')}</b> <span class="note">${esc(g.targetTxt ? 'of ' + g.targetTxt : 'no target')}</span>${barHtml(g)}</div>`
200
- + `<div class="spk" role="cell">${sparkHtml(g)}</div>`
410
+ + `<div class="sofar" role="cell">${soFarHtml(g)}</div>`
201
411
  + `<div class="pace" role="cell"><b style="color:${PACE_C[g.pace.tone]}">${esc(g.pace.head)}</b><div class="note">${esc(g.pace.sub)}</div></div>`
202
- + `<div class="mv" role="cell">${g.moves.length ? g.moves.slice(0, 3).map(initRow).join('') + (g.moves.length > 3 ? `<span class="note">and ${g.moves.length - 3} more</span>` : '') : `<span class="note">${M.initiativesRead ? 'No initiative anchors to it' : 'The initiatives are not read yet'}</span>`}</div>`
412
+ + `<div class="mv" role="cell">${g.moves.length ? g.moves.slice(0, 3).map((r) => initRow(r)).join('') + (g.moves.length > 3 ? `<span class="note">and ${g.moves.length - 3} more</span>` : '') : `<span class="note">${M.initiativesRead ? 'No initiative anchors to it' : 'The initiatives are not read yet'}</span>`}</div>`
203
413
  + '</div>';
204
414
  }
415
+ /** A health budget (D59): always on. Its reading is its share of the board's open initiatives, against its quarterly cap (planning/okrs/health-budgets.md). */
416
+ const pct = (v) => Math.round(v * 100) + '%';
417
+ function budgetRow(b) {
418
+ const R = b.reading, cap = b.cap;
419
+ const val = R ? `<b>${R.n}</b> <span class="note">of ${R.total} open initiatives</span>` : '<b>—</b> <span class="note">' + (b.declared ? 'the initiatives are not read' : 'not in the budget registry') + '</span>';
420
+ const scale = R && R.share !== null && cap !== null ? Math.max(cap * 1.5, R.share) || 1 : 1;
421
+ const bar = R && R.share !== null && cap !== null ? `<div class="ins-bar1" role="img" aria-label="${esc(pct(R.share) + ' of open initiatives, cap ' + pct(cap))}"><i style="width:${Math.round(R.share / scale * 100)}%;background:${R.over ? TONE_BAR.late : TONE_BAR.ok}"></i><span class="today" title="cap" style="left:${Math.round(cap / scale * 100)}%"></span></div>` : barHtml({ done: null, timeGone: null, tone: 'q' });
422
+ const pace = !R || R.share === null ? ['var(--cz-ink3)', '—', b.declared ? 'no open initiative to share' : 'add it to health-budgets.md to give it a cap']
423
+ : R.over ? ['var(--cz-late)', 'Over its ' + pct(cap) + ' cap', pct(R.share) + ' of open initiatives'] : ['var(--cz-ok)', 'Within its ' + pct(cap) + ' cap', pct(R.share) + ' of open initiatives'];
424
+ return `<div class="ins-tr ins-row ${COLS} ins-budget" role="row" data-budget="${esc(b.id)}" tabindex="0" aria-label="${esc(b.title)}">`
425
+ + `<div class="nm" role="cell"><span><b>${esc(b.title)}</b><small><span class="cz-pill q ins-type">Stay within</span><span class="ins-sub">always on${cap !== null ? ' · cap ' + pct(cap) + ' of a quarter' : ''}</span></small></span></div>`
426
+ + `<div class="val" role="cell">${val}${bar}</div>`
427
+ + `<div class="sofar" role="cell">${R && R.share !== null && cap !== null ? bandSvg([{ at: M.today || iso(today()), v: R.share * 100 }], cap * 100, true, R.over ? 'late' : 'ok', b.title + ': ' + pct(R.share) + ' of open initiatives, the green band is inside its ' + pct(cap) + ' cap') : ''}<span class="note">${esc(b.covers ? 'Covers ' + b.covers : 'What it covers is not declared')}</span></div>`
428
+ + `<div class="pace" role="cell"><b style="color:${pace[0]}">${esc(pace[1])}</b><div class="note">${esc(pace[2])}</div></div>`
429
+ + `<div class="mv" role="cell">${b.moves.length ? b.moves.slice(0, 3).map((r) => initRow(r)).join('') : '<span class="note">No initiative anchors to it</span>'}</div></div>`;
430
+ }
431
+ const GRP_PILL = (L) => {
432
+ const scored = L.filter((g) => g.tone !== 'q'), bad = scored.filter((g) => g.tone === 'late' || g.tone === 'red').length;
433
+ return !scored.length ? '' : bad ? `<span class="cz-pill late">${bad} of ${L.length} behind</span>` : '<span class="cz-pill ok">on track</span>';
434
+ };
205
435
  function drawGoals() {
206
436
  const G = goalsShown(), T = $('#goalTbl');
207
- if (!M.goals.length) { T.innerHTML = `<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>` + bmHtml(); bmDraw(); return; }
208
- 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"><i class="ins-tdk"></i>today</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="p m"></i></i>Milestone</span></span></div></div>`;
209
- 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); }
210
- let i = 0;
211
- const groups = [...by.entries()].map(([k, L]) => {
212
- const scored = L.filter((g) => g.tone !== 'q'), bad = scored.filter((g) => g.tone === 'late' || g.tone === 'red').length;
213
- const pill = !scored.length ? '' : bad ? `<span class="cz-pill late">${bad} of ${L.length} behind</span>` : '<span class="cz-pill ok">on track</span>';
214
- i++;
215
- return `<div class="ins-grp" role="row"><span role="cell">${k ? 'Objective ' + i + ' · ' + esc(k) : 'No objective'}</span> <span class="q">${esc(per ? per.label : '')}</span>${pill}</div>` + L.map(goalRow).join('');
216
- }).join('');
217
- T.innerHTML = head + (G.length ? groups : `<div class="ins-empty">No goal matches${find ? ' “' + esc(find) + '”' : ''}${filt.obj !== null || filt.type !== null ? ' this filter' : ''} in ${esc(per.label)}. <button type="button" class="lk" id="goalsAll">Show every goal</button></div>`) + bmHtml();
218
- bmDraw();
437
+ document.body.classList.toggle('ins-trv', dash === TRENDS);
438
+ if (dash === TRENDS) { T.innerHTML = bmHtml(true); drawCards([]); $('#goalCards').innerHTML = ''; return; }
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>`;
440
+ const D = curDash();
441
+ if (!M.goals.length) {
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();
443
+ drawCards([]); return;
444
+ }
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); }
448
+ const objs = [...new Set(M.goals.map((g) => g.pillar || ''))];
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('');
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();
452
+ drawCards(G);
453
+ }
454
+ function budgetsHtml(D) {
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))));
457
+ return '<div class="ins-grp" role="row"><span role="cell">Health budgets</span> <span class="q">always on, judged every week</span></div>'
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>');
219
459
  }
220
460
  $('#goalTbl').addEventListener('click', (e) => {
221
- if (e.target.closest('#goalsAll')) { find = ''; $('#findIn').value = ''; filt = { obj: null, type: null }; per = periods()[3]; redraw(); return; }
222
- if (e.target.closest('a, #bmRange, #cBm')) return;
223
- const r = e.target.closest('[data-goal]'); if (!r) return;
224
- if (selecting) { const id = r.dataset.goal; if (picked.has(id)) picked.delete(id); else picked.add(id); drawGoals(); drawSel(); if (!$('#side').hidden && sideKind === 'dash') drawDashSide(); return; }
225
- if (r.dataset.open) openChart(byKey(r.dataset.open)); else toast('This goal has fewer than two readings, so it has no chart yet.');
461
+ if (e.target.closest('#goalsAll')) { find = ''; $('#findIn').value = ''; clearFilter(); per = periods()[3]; redraw(); return; }
462
+ if (e.target.closest('a')) return;
463
+ const tile = e.target.closest('[data-tile]'); if (tile) { if (tgOpen === tile.dataset.tile) closeTarget(true); else openTarget(tile.dataset.tile); return; }
464
+ const bu = e.target.closest('[data-budget]'); if (bu) { openBudget(bu.dataset.budget); return; }
465
+ const r = e.target.closest('[data-goal]'); if (r) pressGoal(r.dataset.goal);
226
466
  });
227
- $('#goalTbl').addEventListener('keydown', (e) => { if (e.key !== 'Enter' && e.key !== ' ') return; const r = e.target.closest && e.target.closest('.ins-row'); if (!r || e.target !== r) return; e.preventDefault(); r.click(); });
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(); });
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). */
469
+ function pressGoal(id) {
470
+ if (selecting) { picked = picked.includes(id) ? picked.filter((x) => x !== id) : picked.concat(id); drawGoals(); drawDashSide(); return; }
471
+ const D = curDash();
472
+ if (D.saved) openChartEdit(id, D); else openGoalDetail(id);
473
+ }
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
+ }
550
+ });
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
+ }
566
+ });
567
+ } });
568
+ }
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 */
570
+ function openBudget(id) {
571
+ const b = (M.budgets || []).find((x) => x.id === id); if (!b) return;
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(); } });
586
+ } });
587
+ }
228
588
 
229
- /* ── Delivery trends: the Board's measures, a tile press sets a target (initiative briefing-premium-metrics) ──────────────────────────────── */
230
- let BM = null, bmWeeks = 8, bmTimer = null, bmErr = '';
231
- const BM_KEY = 'pmos.premium.bmWeeks';
232
- try { const w = Number(localStorage.getItem(BM_KEY)); if ([8, 26, 52].includes(w)) bmWeeks = w; } catch { /* a blocked store keeps 8 weeks */ }
233
- const bmHtml = () => `<section class="ins-trends" id="cBm" aria-labelledby="hBm" hidden><div class="ins-grp" role="row"><h2 id="hBm" role="cell">Delivery trends</h2> <span class="q" id="bmCap"></span><span class="q ins-bmlead" id="bmLead" hidden></span><button type="button" class="infob" aria-controls="bmFold" aria-expanded="false" aria-label="About the Delivery trends" title="About the Delivery trends"><i aria-hidden="true">i</i></button>`
234
- + `<div class="cz-seg mper" id="bmRange" role="group" aria-label="Range"><button data-w="8" aria-pressed="true">8w</button><button data-w="26" aria-pressed="false">26w</button><button data-w="52" aria-pressed="false">52w</button></div></div>`
235
- + '<div class="ifold" id="bmFold" hidden><p class="mhint" id="bmHint"></p><p class="note" id="bmNote"></p></div><div class="bt2 ibt ins-tiles" id="bmBody"></div></section>';
236
- function bmDraw() {
237
- const card = $('#cBm'); if (!card) return;
238
- card.hidden = !M || !M.board || !M.board.ws;
239
- $$('#bmRange button').forEach((b) => b.setAttribute('aria-pressed', String(+b.dataset.w === bmWeeks)));
240
- if (!BM) {
241
- $('#bmCap').textContent = bmErr ? 'not read' : 'reading';
242
- $('#bmHint').textContent = bmErr ? 'The Board measures could not be read, so none is shown.' + (bmErr !== '1' ? ' The reason: ' + bmErr : '') : '';
243
- $('#bmLead').hidden = !bmErr; $('#bmLead').textContent = $('#bmHint').textContent; $('#bmBody').innerHTML = ''; $('#bmNote').textContent = '';
244
- return;
589
+ /* the phone (AgInsPhone): one card per goal, its status at the top right, its value, its so-far, its bar and the first initiative that moves it */
590
+ function cardPill(g) {
591
+ const t = g.pace && g.pace.tone !== 'q' ? g.pace.tone : g.tone;
592
+ if (t === 'late' || t === 'red') return ['late', 'Behind'];
593
+ if (t === 'ok') return g.done !== null && g.timeGone != null && g.done > g.timeGone ? ['ok', 'Ahead'] : ['ok', 'On track'];
594
+ return null;
595
+ }
596
+ function drawCards(G) {
597
+ $('#goalCards').innerHTML = G.map((g) => {
598
+ const p = cardPill(g), tg = g.targetTxt ? (g.type === 'Count' ? 'of ' : 'target ') + g.targetTxt + (g.byAt ? ' by ' + md(day(g.byAt)) : '') : 'no target';
599
+ return `<div class="ins-card" role="listitem" data-goal="${esc(g.id)}" tabindex="0" aria-label="${esc(g.title)}"><div class="ins-ch"><b>${esc(g.title)}</b>${p ? `<span class="cz-pill ${p[0]}">${p[1]}</span>` : ''}</div>`
600
+ + `<div class="ins-cs"><span class="cz-pill q ins-type">${esc(g.type)}</span><span class="note">${esc(tg)}</span></div>`
601
+ + `<div class="ins-cv"><b>${esc(g.nowTxt || '—')}</b><span class="ins-cg">${isBlocks(g) ? blocksHtml(g, 190, false) : g.type === 'Stay within' && g.series.length && g.target !== null ? bandSvg(g.series, g.target, g.limit !== 'floor', g.tone, g.title, 190, 30) : g.key ? sparkHtml(g, 190, 30) : ''}</span></div>${barHtml(g, ' ins-wide')}`
602
+ + (g.moves[0] ? `<div class="ins-c1">${initRow(g.moves[0], false)}</div>` : '') + '</div>';
603
+ }).join('') || (M.goals.length ? '<p class="note">No goal in this period.</p>' : '<p class="note">No goal is recorded for this workspace.</p>');
604
+ }
605
+ $('#goalCards').addEventListener('click', (e) => { if (e.target.closest('a')) return; const c = e.target.closest('[data-goal]'); if (c) pressGoal(c.dataset.goal); });
606
+
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. ─── */
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
+ }
622
+ function tileOf(key) {
623
+ const TR = M.trends || {}, own = (TR.targets || {})[key];
624
+ let t;
625
+ if (key === 'late' || key === 'scope') {
626
+ const x = TR[key] || {};
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' };
245
636
  }
246
- $('#bmCap').textContent = 'the Board shows today’s counts as chips · press a tile to set its target · ' + BM.header;
247
- $('#bmHint').innerHTML = (BM.lead ? `<b class="mflag">${esc(BM.lead)}</b> ` : '') + esc(BM.body) + ' Press a measure to set its target. The Board draws the same target.';
248
- $('#bmBody').style.gridTemplateColumns = 'repeat(' + Math.max(1, Math.min(6, BM.tiles.length)) + ',minmax(0,1fr))';
249
- $('#bmBody').innerHTML = BM.tiles.map(MT.tileHtml).join('');
250
- $('#bmNote').textContent = BM.note;
251
- $('#bmLead').hidden = !BM.lead; $('#bmLead').textContent = BM.lead || '';
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) {
643
+ const S = (ser || []).map((v, j) => [j, v]).filter((p) => p[1] != null); if (S.length < 2) return '<span class="ins-tsp0"></span>';
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;
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(',');
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>`;
647
+ }
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>`;
252
655
  }
253
656
  async function bmLoad() {
254
- clearTimeout(bmTimer);
255
- if (!M || !M.board || !M.board.ws) { bmDraw(); return; }
657
+ if (!M || !M.board || !M.board.ws) return;
256
658
  let r = null;
257
- try { const res = await fetch('/api/board-metrics-premium?ws=' + encodeURIComponent(M.board.ws) + '&weeks=' + bmWeeks, { credentials: 'same-origin' }); r = await res.json(); } catch { r = null; }
258
- if (!r || !r.ok || r.state !== 'ready') { BM = null; bmErr = (r && r.error) || '1'; bmDraw(); return; }
259
- BM = r.model; bmErr = ''; bmDraw();
260
- if (BM.pending) bmTimer = setTimeout(bmLoad, 4000); // the workflow engine is still deriving Blocked and Idle
261
- }
262
- function bmOpen(i) {
263
- const t = BM && BM.tiles[i]; if (!t) return;
264
- const vals = t.ser ? `<h3 class="sh">Values</h3><div class="vtb">${t.ser.map((v, j) => `<div><span>${esc(t.wk[j])}</span><b>${v == null ? (t.since ? 'Not kept yet' : 'No runs') : esc(MT.fmt(t, v))}</b></div>`).join('')}</div>` : '';
265
- const form = t.absent ? '<p class="note" style="margin:12px 0 0">A target can be set once this measure is counted.</p>'
266
- : `<div class="addf" style="margin-top:14px"><label>Target (${t.lowBetter ? 'at most' : 'at least'})<input id="bmT" inputmode="decimal" maxlength="12" value="${t.tg != null ? esc(String(t.tg)) : ''}" placeholder="For example: ${t.key === 'corrections' ? '10' : t.key === 'merges' ? '5' : '0'}"></label>
267
- <p class="note" id="bmM" role="status" style="margin:0;min-height:1.2em"></p><div class="cact"><button class="cta" id="bmGo">Save target</button>${t.tg != null ? '<button class="cta alt" id="bmClr">Clear target</button>' : ''}</div></div>`;
268
- const lt = (s) => { const d = new Date(s); return Number.isNaN(d.getTime()) ? '' : d.getDate() + ' ' + d.toLocaleString('en-GB', { month: 'short' }) + ' ' + String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0'); };
269
- const fetched = t.trunk ? (t.trunk.fetched_at ? `${t.trunk.ref} was last fetched ${lt(t.trunk.fetched_at)}` : `${t.trunk.ref} has no fetch on record`) : '';
270
- const tgt = t.tg != null ? ` The target is ${t.tg}; change it or clear it here.` : ' No target is set; type one and save it.';
271
- const say = t.absent ? `${t.label} is not shown: ${t.why}`
272
- : t.quiet ? `${t.label} was ${t.quiet.peak} in the week to ${t.quiet.week}, then 0 for the last two weeks. That is a quiet trunk or an old fetch: ${fetched || 'the fetch time is not known'}.${tgt}`
273
- : `${t.label} is ${t.value}, ${t.text}.${t.change ? ' ' + t.change.txt + '.' : ''}${fetched ? ' ' + fetched + '.' : ''}${tgt}`;
274
- const facts = MT.factRows(t, BM.repo, BM.weeks).concat(t.trunk ? [['Trunk read', t.trunk.ref + (t.trunk.fetched_at ? ', fetched ' + lt(t.trunk.fetched_at) : ', no fetch on record')]] : []);
275
- const pane = `<article class="paper doc"><p class="lede" style="margin:0 0 10px">${esc(t.def)}</p>${kv(facts)}${form}${vals}<p class="note" style="margin-top:12px">${esc(BM.note)}</p></article>`;
276
- openDlg({ eye: 'Board measure · real data', title: t.label, sub: BM.repo, say, stream: turnA(ptx(say)), noteKey: popKey('measure', BM.repo, t.key || t.label), facts, pane, label: 'Measure' });
277
- $('#oMain').onchange = null;
278
- $('#oMain').onclick = async (e) => {
279
- const go = e.target.closest('#bmGo'), clr = e.target.closest('#bmClr'); if (!go && !clr) return;
280
- const target = clr ? null : $('#bmT').value.trim();
281
- if (go && target === '') { $('#bmM').textContent = 'Type a number first.'; return; }
282
- (go || clr).disabled = true; $('#bmM').textContent = 'Saving.';
283
- const res = await pmPost('/api/board-metric-targets/save', { ws: M.board.ws, key: t.key, target });
284
- (go || clr).disabled = false;
285
- if (!res || res.ok !== true) { $('#bmM').textContent = (res && res.error) || 'The target could not be saved.'; return; }
286
- closeDlg(); toast(clr ? 'The target of ' + t.label + ' is cleared.' : 'The target of ' + t.label + ' is ' + target + '.');
287
- bmLoad();
288
- };
289
- }
290
- /* the tiles are redrawn inside #goalTbl, so their presses are delegated from it */
291
- MT.wireTiles($('#goalTbl'), () => (BM ? BM.tiles : []), bmOpen);
292
- $('#goalTbl').addEventListener('click', (e) => {
293
- const b = e.target.closest('#bmRange [data-w]'); if (!b || +b.dataset.w === bmWeeks) return;
294
- bmWeeks = +b.dataset.w; try { localStorage.setItem(BM_KEY, String(bmWeeks)); } catch { /* not kept */ } bmDraw(); bmLoad();
295
- });
659
+ try { const res = await fetch('/api/board-metrics-premium?ws=' + encodeURIComponent(M.board.ws) + '&weeks=8', { credentials: 'same-origin' }); r = await res.json(); } catch { r = null; }
660
+ if (!r || !r.ok || r.state !== 'ready') { BM = null; bmErr = (r && r.error) || '1'; } else { BM = r.model; bmErr = ''; }
661
+ if (tab === 'goals') drawGoals();
662
+ if (BM && BM.pending) setTimeout(bmLoad, 4000); // the workflow engine is still deriving Blocked and Idle
663
+ }
296
664
 
297
- /* ── the view's charts (charts live only on dashboards): the pinned one first, Pin, Edit and New chart in its ⋯ ─────────────────────────── */
298
- function chartAt(t, j) {
299
- const c = byKey(t.dataset.key); if (!c) return;
300
- const n = c.pts.length; j = j == null ? n - 1 : Math.max(0, Math.min(n - 1, j));
301
- const p = c.pts[j], last = j === n - 1;
302
- const cx = $('.cx', t), dt = $('.dt', t);
303
- cx.setAttribute('x1', X(p.fx)); cx.setAttribute('x2', X(p.fx)); dt.setAttribute('cx', X(p.fx)); dt.setAttribute('cy', Y(p.fy));
304
- t.classList.toggle('hv', !last); t.dataset.j = j;
305
- const val = last ? c.v : p.txt, cap = last ? 'on ' + c.at + (c.targetTxt ? ' · ' + c.targetTxt : '') : 'on ' + p.d + (c.targetTxt ? ' · ' + c.targetTxt : '');
306
- $('.mval', t).textContent = val; $('.mwk', t).textContent = cap;
307
- t.setAttribute('aria-label', c.title + ', ' + (last ? 'now ' : '') + val + ', ' + cap + '. Use the arrow keys to read each reading.');
308
- }
309
- const pinnable = (D) => !!M.board.id && (D.id === 'all' || D.saved);
310
- function findingsHtml(D) {
311
- const I = D.insight; if (!I || I.none) return '';
312
- const all = I.finds, F = all.filter((f) => f.chart !== M.insight.chart), also = F.length < all.length;
313
- const label = also ? 'Also on this dashboard' : 'Insight';
314
- const rows = F.length ? F.map((f) => `<li class="${esc(f.kind)}"><button class="nfr" data-open="${esc(f.chart)}" aria-haspopup="dialog"><i class="nfdot" aria-hidden="true"></i><span class="nft"><b>${esc(f.text)}</b> ${esc(f.why)}</span></button></li>`).join('')
315
- : `<li class="calm"><div class="nfr"><i class="nfdot" aria-hidden="true"></i><span class="nft">${esc(also ? 'Nothing else stands out here.' : I.calmText)}</span></div></li>`;
316
- return `<div class="nfd" role="region" aria-label="${esc(label)}"><p class="label">${esc(label)}</p><ul>${rows}</ul></div>`;
317
- }
318
- function drawDash() {
319
- const D = curDash(), L = D.keys.map(byKey).filter(Boolean), isPin = M.pinned === D.id;
320
- $('#hDash').textContent = 'Charts on ' + (D.id === 'all' ? 'All goals' : D.name);
321
- $('#dashTag').textContent = isPin ? 'Pinned' : 'Not pinned';
322
- $('#dashTag').className = 'cz-pill ' + (isPin ? 'you' : 'q');
323
- $('#dashCap').textContent = L.length ? (L.length - D.off) + ' of ' + L.length + ' on their line' : '';
324
- drawDashBar(D, isPin);
325
- $('#cDash').hidden = !D.saved && !M.charts.length;
326
- if (D.saved) { drawSaved(D, L); return; }
327
- if (!M.charts.length) { $('#dashBody').innerHTML = ''; return; }
328
- const off = D.off, tot = L.length;
329
- $('#dashBody').innerHTML = findingsHtml(D)
330
- + `<p class="mhint"><b>${tot - off} of ${tot}</b> on their line${off ? `. <b class="mflag">${off} ${off === 1 ? 'is' : 'are'} behind it.</b>` : '.'} ${infoBtn('dashFold', 'About these charts')}</p><div class="ifold" id="dashFold" hidden><p class="mhint">Each chart is one goal, drawn at the dates of its readings. A gap between readings is left as a gap. The dashed line is the target.</p></div>`
331
- + `<div class="ngrid">${L.map(tileWrap).join('')}</div>` + (D.id === 'all' ? mineHtml() + noSeriesHtml() : '');
332
- }
333
- function drawDashBar(D, isPin) {
334
- const bar = $('#dashBar');
335
- $('#dashPurpose').textContent = D.saved ? D.purpose : D.id === 'all' ? 'Every goal of this product. PMOS makes it, so it cannot be deleted.' : 'The goals of the ' + D.name + ' objective.';
336
- $('#dashMore').hidden = !M.board.id;
337
- if (!M.board.id) { bar.innerHTML = ''; return; }
338
- const Pd = M.pinned ? M.dashboards.find((d) => d.id === M.pinned) : null;
339
- bar.innerHTML = `<p class="note pdst">${isPin ? 'Pinned: it opens first on Goals' : 'Not pinned'}</p>`
340
- + (pinnable(D) ? `<button type="button" id="pdPin" data-pin="${esc(isPin ? '' : D.id)}" aria-pressed="${isPin}">${SV(PINI)}${isPin ? 'Unpin' : 'Pin'}</button>` : '')
341
- + (Pd && !isPin ? `<button type="button" id="pdBack">Back to ${esc(Pd.name)}</button>` : '')
342
- + (D.saved ? '<button type="button" id="pdEdit" aria-haspopup="dialog">Edit</button>' : '')
343
- + (M.charts.length ? '<button type="button" id="pcNew" aria-haspopup="dialog">New chart</button>' : '');
344
- }
345
- function drawSaved(D, L) {
346
- const off = D.off, tot = L.length;
347
- const gone = D.gone.length ? `<p class="label ngl">Not drawn · ${D.gone.length}</p><div class="dplist" role="list">${D.gone.map((g) => `<div class="nempty" role="listitem"><p><b>${esc(g.title)}</b><br>${esc(g.why)}</p></div>`).join('')}</div>` : '';
348
- const checks = D.checks.length ? `<p class="note pdck">${D.checks.map(esc).join(' ')}</p>` : '';
349
- $('#dashBody').innerHTML = (tot ? findingsHtml(D)
350
- + `<p class="mhint"><b>${tot - off} of ${tot}</b> on their line${off ? `. <b class="mflag">${off} ${off === 1 ? 'is' : 'are'} behind it.</b>` : '.'} ${infoBtn('dashFold', 'About these charts')}</p><div class="ifold" id="dashFold" hidden><p class="mhint">The charts are drawn in the order you saved. The dashed line is the target.</p></div>`
351
- + `<div class="ngrid">${L.map(tileWrap).join('')}</div>`
352
- : '<div class="nempty"><p><b>This dashboard draws no chart yet.</b> Press Edit to add a goal with a series.</p></div>') + checks + gone;
353
- }
354
- const tileWrap = (c) => `<div class="ntw">${tileHtml(c)}<div class="ntf"><button class="lk" data-open="${esc(c.key)}">Details</button>${c.mine ? `<button class="lk" data-ced="${esc(c.id)}" aria-haspopup="dialog">Edit</button>` : ''}</div></div>`;
355
- function mineHtml() {
356
- const L = M.mine || [], G = M.mineGone || [];
357
- if (!L.length && !G.length) return '';
358
- return `<p class="label ngl">Your charts · ${L.length + G.length}</p>` + (L.length ? `<div class="ngrid">${L.map(tileWrap).join('')}</div>` : '')
359
- + G.map((g) => `<div class="nempty" role="listitem"><p><b>${esc(g.title)}</b><br>${esc(g.why)} It is not drawn. <button class="lk" data-ced="${esc(g.id)}" aria-haspopup="dialog">Edit</button></p></div>`).join('');
360
- }
361
- function noSeriesHtml() {
362
- const N = M.noSeries; if (!N.length) return '';
363
- return `<p class="label ngl">No series recorded · ${N.length}</p><div class="dplist" role="list">${N.map((n) => `<div class="nempty" role="listitem"><p><b>${esc(n.title)}</b>${n.pillar ? ' · ' + esc(n.pillar) : ''}<br>${esc(n.why)} It is not drawn.</p></div>`).join('')}</div>`;
364
- }
365
- async function pinDash(id) {
366
- const res = await pmPost('/api/premium-dashboards/pin', { ws: M.board.ws, board: M.board.id, id: id || null });
367
- if (!res || res.ok !== true) { toast((res && res.error) || 'The pin could not be saved. Nothing changed.'); return false; }
368
- const D = M.dashboards.find((d) => d.id === id);
369
- dash = res.pinned || 'all';
370
- toast(res.pinned ? 'Pinned ' + (D ? D.name : 'the dashboard') + '. It opens first on Goals.' : 'Unpinned. All goals opens first.');
371
- await load();
372
- return true;
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
+ }
679
+ function openTarget(key) {
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();
373
712
  }
374
- $('#dashBar').addEventListener('click', (e) => {
375
- const pin = e.target.closest('#pdPin'); if (pin) { pin.disabled = true; closeMenus(); pinDash(pin.dataset.pin || null); return; }
376
- if (e.target.closest('#pdBack')) { closeMenus(); setView(M.pinned); return; }
377
- if (e.target.closest('#pdEdit')) openDashEdit(curDash()); else if (e.target.closest('#pcNew')) openChartEdit(null);
378
- });
379
- /* dashboards, charts and reports are shaped in a chat (premium-reports-from-chat): ?open= opens the item beside the chat, ?say= puts a first message in the box */
380
- async function saveDash(body) { return pmPost('/api/premium-dashboards/save', Object.assign({ ws: M.board.ws, board: M.board.id }, body)); }
381
- function toChat(o) {
382
- const q = new URLSearchParams(); if (M.board.ws) q.set('ws', M.board.ws);
383
- if (o.open) q.set('open', o.open); if (o.say) q.set('say', o.say);
384
- location.href = '/premium-chat.html?' + q.toString();
385
- }
386
- const openDashEdit = (D) => toChat(D ? { open: 'dashboard:' + D.id } : { say: 'Make a dashboard of ' });
387
- const openChartEdit = (id) => toChat(id ? { open: 'chart:' + id } : { say: 'Make a chart of ' });
388
- const openReportEdit = (s) => toChat(s ? { open: 'report:' + s.id } : { say: 'Make a report of ' });
389
- $('#dashBody').addEventListener('click', (e) => { const o = e.target.closest('[data-open]'); if (o) { openChart(byKey(o.dataset.open)); return; } const ed = e.target.closest('[data-ced]'); if (ed) openChartEdit(ed.dataset.ced); });
390
- $('#dashBody').addEventListener('keydown', (e) => {
391
- const t = e.target.closest && e.target.closest('.mch'); if (!t || !/^Arrow(Left|Right)$/.test(e.key)) return;
392
- e.preventDefault(); const c = byKey(t.dataset.key), j = +(t.dataset.j == null ? c.pts.length - 1 : t.dataset.j); chartAt(t, j + (e.key === 'ArrowRight' ? 1 : -1));
393
- });
394
- $('#dashBody').addEventListener('pointermove', (e) => {
395
- const t = e.target.closest && e.target.closest('.mch'); $$('#dashBody .mch.hv').forEach((x) => { if (x !== t) chartAt(x); });
396
- if (!t) return; const c = byKey(t.dataset.key), r = $('svg', t).getBoundingClientRect(); if (!c || !r.width) return;
397
- const fx = Math.max(0, Math.min(1, ((e.clientX - r.left) / r.width * W - P) / (W - 2 * P)));
398
- let best = 0; c.pts.forEach((p, i) => { if (Math.abs(p.fx - fx) < Math.abs(c.pts[best].fx - fx)) best = i; }); chartAt(t, best);
399
- });
400
- $('#dashBody').addEventListener('pointerleave', () => $$('#dashBody .mch.hv').forEach((x) => chartAt(x)));
401
713
 
402
- /* ── Outcomes (G2): shipped work against what it promised, and the verdict ──────────────────────────────────────────────────────────────── */
714
+ /* ── Outcomes (AgInsOutcomes) ───────────────────────────────────────────────────────────────────────────────────────────────────── */
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) : '')); };
716
+ function outcomesShown() {
717
+ /* shipped or judged in the period: a decided row by the day of its verdict, the others by their ship date; one that needs a verdict always shows */
718
+ const when = (r) => (r.verdict && r.verdict.at ? r.verdict.at : r.endAt);
719
+ return (M.outcomes || []).filter((r) => hit(r.title, r.goal && r.goal.title) && (r.group === 'verdict' || when(r) == null || inPer({ fromAt: when(r), byAt: when(r) })));
720
+ }
721
+ function promiseOf(r) {
722
+ const g = r.goal && M.goals.find((x) => x.id === r.goal.id);
723
+ if (!g) return null;
724
+ const moved = g.now !== null && g.base !== null ? g.now - g.base : null, promised = g.target !== null && g.base !== null ? g.target - g.base : null;
725
+ const share = moved !== null && promised ? moved / promised : null;
726
+ const state = share === null ? 'none' : share >= 1 ? 'met' : share > 0 ? 'part' : 'none';
727
+ return { g, moved, promised, share, state };
728
+ }
729
+ /** The promise's bullet: the dashed range is what was promised (baseline to target), the bar is what happened, the tick is the baseline. */
730
+ function bulletHtml(P) {
731
+ const { g, moved, promised } = P, W = 80;
732
+ if (promised === null) return '';
733
+ const span = Math.max(Math.abs(promised), Math.abs(moved || 0)) * 1.15 || 1, neg = promised < 0, z = neg ? W - 10 : 10, sc = (W - 20) / span;
734
+ const exL = neg ? z - Math.abs(promised) * sc : z, exW = Math.abs(promised) * sc;
735
+ const acW = moved === null ? 0 : Math.abs(moved) * sc, acL = (moved || 0) * Math.sign(promised || 1) >= 0 ? (neg ? z - acW : z) : (neg ? z : z - acW);
736
+ const col = P.state === 'met' ? 'var(--cz-dot-ok)' : P.state === 'part' ? 'var(--cz-dot-risk)' : 'var(--cz-dot-q)';
737
+ return `<div class="ins-bul" style="width:${W}px" role="img" aria-label="${esc((moved === null ? 'no reading' : sgn(moved, g.unit)) + ' of ' + sgn(promised, g.unit))}"><span class="ex" style="left:${exL.toFixed(0)}px;width:${exW.toFixed(0)}px"></span><span class="ac" style="left:${acL.toFixed(0)}px;width:${acW.toFixed(0)}px;background:${col}"></span><span class="z" style="left:${z}px"></span></div>`;
738
+ }
739
+ function promiseHtml(r) {
740
+ const P = promiseOf(r);
741
+ if (!P) return `<span class="note">${r.anchor ? 'Anchored to ' + esc(r.anchor) + ', which is not a goal with readings.' : 'No goal is anchored, so nothing was promised to measure.'}</span>`;
742
+ const { g, moved, promised } = P, col = P.state === 'met' ? 'var(--cz-ok)' : P.state === 'part' ? 'var(--cz-risk)' : 'var(--cz-ink3)';
743
+ const text = g.title + (promised !== null ? ' ' + sgn(promised, g.unit) : '') + (g.byAt ? ' by ' + md(day(g.byAt)) : '');
744
+ const res = moved === null ? 'no reading yet' : promised === null ? sgn(moved, g.unit) : moved === 0 ? 'no change' : sgn(moved, g.unit) + ' of ' + sgn(promised, g.unit);
745
+ return `<div class="ins-prom"><span><span class="cz-pill q ins-type">${esc(g.type)}</span></span><span class="pt">${esc(text)}</span><span class="pr">${bulletHtml(P)}<b style="color:${moved === 0 ? 'var(--cz-late)' : col}">${esc(res)}</b></span></div>`;
746
+ }
747
+ /** A guardrail: the goal the PM named as one that must not get worse, read from the last reading before the ship date to the latest one. */
748
+ function guardOf(r) {
749
+ const P = promiseOf(r), name = P && P.g.guardrail ? P.g.guardrail.replace(/ must not get worse$/, '') : '';
750
+ const gg = name ? M.goals.find((x) => x.title === name) : null;
751
+ if (!name) return null;
752
+ if (!gg) return { name, state: 'gone', text: 'its goal is not on record' };
753
+ const ship = day(r.endAt), S = gg.series || [], before = ship === null ? S[0] : S.filter((x) => day(x.at) <= ship).pop(), last = S[S.length - 1];
754
+ if (!before || !last || before === last) return { name, state: 'none', text: 'no reading since it shipped' };
755
+ const d = last.v - before.v, worse = gg.direction === 'down' ? d > 0 : d < 0;
756
+ return { name, state: worse ? 'worse' : 'held', text: (worse ? 'worse by ' : d === 0 ? 'held' : 'held, moved ') + (d === 0 ? '' : sgn(Math.abs(d), gg.unit).replace(/^\+/, '')) };
757
+ }
758
+ /** Guardrail and overlap: the goal's guardrail, then the other initiatives that move the same goal. */
759
+ function guardHtml(r) {
760
+ const P = promiseOf(r), others = P ? P.g.moves.filter((m) => m.id !== r.id) : [], G = guardOf(r);
761
+ return (others.length ? `<span class="cz-pill risk">Shares ${esc(P.g.title.toLowerCase())}</span><div class="note ins-ov">with ${esc(others.map((m) => m.title).join(', '))}</div>` : '')
762
+ + (G ? `<div class="note"><span class="cz-pill ${G.state === 'worse' ? 'late' : G.state === 'held' ? 'ok' : 'q'}">${esc(G.name)}</span> ${esc(G.text)}</div>` : '<div class="note">No guardrail set.</div>');
763
+ }
764
+ /** The window as the design says it: "Judged <date>" while it is open (or not open yet), "Closed <date>" once it has closed. A verdict recorded
765
+ * before the window closed says the day it was judged. A verdict is due when the window closes. */
766
+ const WIN_SAY = { open: (w) => (w.closes ? 'Judged ' + md(day(w.closes)) : 'Open, no end date'), 'not open': (w) => (w.closes ? 'Judged ' + md(day(w.closes)) : 'Opens at ship'), closed: (w) => 'Closed ' + md(day(w.closes)),
767
+ judged: (w, r) => (w.closes && day(w.closes) <= today() ? 'Closed ' + md(day(w.closes)) : 'Judged ' + md(day((r && r.verdict && r.verdict.at) || M.today))), none: () => 'No ship date recorded' };
768
+ const dueOf = (r) => (r && r.window && r.window.closes ? day(r.window.closes) : null);
403
769
  const OUT_G = { verdict: 'Needs your verdict', window: 'In their window', decided: 'Decided' };
404
770
  function outRow(r) {
405
- const g = r.goal;
406
- const promise = g ? `<div class="ins-prom"><span class="cz-pill q ins-type">${esc(g.type)}</span><span class="pt">${esc(g.title)}${g.targetTxt ? ' ' + esc((g.baseTxt ? g.baseTxt + ' → ' : '') + g.targetTxt) : ''}${g.by ? ' by ' + esc(g.by) : ''}</span>${barHtml({ done: g.done, timeGone: null, tone: g.tone })}<b style="color:${PACE_C[g.pace.tone] || 'inherit'}">${esc(g.nowTxt ? g.nowTxt + (g.targetTxt ? ' of ' + g.targetTxt : '') : 'no reading')}</b></div>`
407
- : `<span class="note">${r.anchor ? 'Anchored to ' + esc(r.anchor) + ', which is not a goal with readings.' : 'No goal is anchored, so nothing was promised to measure.'}</span>`;
408
- const verdict = r.group === 'verdict' ? `<button type="button" class="ins-dec" data-verdict="${esc(r.id)}" aria-haspopup="dialog">${SV(CHK)}Decide</button>`
409
- : r.group === 'decided' ? `<span class="cz-pill ${r.status === 'done' ? 'ok' : 'q'}">${r.status === 'done' ? 'Done' : 'Cancelled'}</span>` : `<span class="note">${r.idx === 6 ? 'Being monitored' : 'Too early'}</span>`;
410
- return `<div class="ins-tr ins-row ins-ocols" role="row" data-ini="${esc(r.id)}"><div class="nm" role="cell"><a href="/premium-initiative.html?${wsQ()}id=${encodeURIComponent(r.id)}"><b>${esc(r.title)}</b></a>${trackHtml(r)}</div>`
411
- + `<div role="cell">${promise}</div><div role="cell" class="note">${esc(r.stageLabel ? 'In ' + r.stageLabel : '')}${r.owner ? ' · ' + esc(r.owner) : ''}</div>`
412
- + `<div role="cell" class="note">${esc(r.end ? 'Ends ' + r.end : 'No end date')}</div><div role="cell">${verdict}</div></div>`;
771
+ const due = dueOf(r);
772
+ const verdict = r.group === 'verdict' ? `<button type="button" class="ins-dec" data-verdict="${esc(r.id)}" aria-haspopup="dialog">${SV(I.chk)}Decide${due !== null ? ' · due ' + esc(md(due)) : ''}</button>`
773
+ : r.group === 'decided' ? (r.verdict ? `<span class="cz-pill ${r.verdict.verdict === 'Stop' ? 'q' : 'ok'}">${r.verdict.verdict === 'Keep' ? SV(I.chk) + 'Kept' : r.verdict.verdict === 'Iterate' ? 'Iterating' : 'Stopped'}</span><div class="note">${esc(r.verdict.learned)}</div>`
774
+ : (r.status === 'done' ? `<span class="cz-pill ok">${SV(I.chk)}Kept</span>` : '<span class="cz-pill q">Stopped</span>') + '<div class="note">No learning recorded.</div>')
775
+ : `<span class="note">${r.idx === 6 ? (due !== null ? 'Opens ' + esc(md(due)) : 'Being monitored') : 'Too early'}</span>`; // the verdict opens when the window closes
776
+ return `<div class="ins-tr ins-row ins-ocols" role="row" data-ini="${esc(r.id)}"><div class="nm" role="cell"><a href="${iniHref(r.id)}"><b>${esc(r.title)}</b></a>${trackHtml(r)}</div>`
777
+ + `<div role="cell">${promiseHtml(r)}</div><div role="cell" class="ins-guard">${guardHtml(r)}</div>`
778
+ + `<div role="cell">${winHtml(r)}</div><div role="cell">${verdict}</div></div>`;
779
+ }
780
+ function winHtml(r) {
781
+ const w = r.window || { state: 'none' }, sh = w.state === 'judged' || w.state === 'closed' ? 1 : w.share || 0, say = (WIN_SAY[w.state] || WIN_SAY.none)(w, r);
782
+ return `<div class="ins-win" role="img" aria-label="${esc(say)}"><i style="width:${Math.round(sh * 100)}%"></i></div><div class="note">${esc(say)}</div>`;
413
783
  }
414
784
  function drawOutcomes() {
415
- const L = (M.outcomes || []).filter((r) => hit(r.title, r.goal && r.goal.title));
416
- const need = L.filter((r) => r.group === 'verdict');
785
+ const L = outcomesShown(), need = L.filter((r) => r.group === 'verdict');
786
+ const P = L.map(promiseOf).filter(Boolean), met = P.filter((x) => x.state === 'met').length, part = P.filter((x) => x.state === 'part').length, win = L.filter((r) => r.group === 'window' && promiseOf(r)).length;
417
787
  $('#outText').innerHTML = !M.initiativesRead ? 'The board’s initiatives are not read yet, so no shipped work is listed.'
418
788
  : !L.length ? 'No initiative is past Build yet. Shipped work shows here, with what its goal promised.'
419
- : (need.length ? `<b>${esc(need[0].title)} needs your verdict.</b> ` : '') + esc(L.length + (L.length === 1 ? ' initiative is' : ' initiatives are') + ' past Build: ' + need.length + ' to decide, ' + L.filter((r) => r.group === 'window').length + ' in their window, ' + L.filter((r) => r.group === 'decided').length + ' decided.');
420
- const head = '<div class="ins-tr ins-th ins-ocols" role="row"><div role="columnheader">Shipped initiative</div><div role="columnheader">What it promised · and what happened so far</div><div role="columnheader">Where it is</div><div role="columnheader">Window</div><div role="columnheader">Verdict</div></div>';
421
- const groups = Object.keys(OUT_G).map((k) => { const G = L.filter((r) => r.group === k); return G.length ? `<div class="ins-grp" role="row"><span role="cell">${OUT_G[k]}</span> <span class="q">${G.length}</span></div>` + G.map(outRow).join('') : ''; }).join('');
789
+ : (need.length ? `<b>${esc(need[0].title)} needs your verdict${dueOf(need[0]) !== null ? ' by ' + esc(md(dueOf(need[0]))) : ''}.</b> ` : '') + esc('Of ' + P.length + (P.length === 1 ? ' promise ' : ' promises ') + (per.said || 'in these dates') + ', ' + met + (met === 1 ? ' is' : ' are') + ' met, ' + part + (part === 1 ? ' is' : ' are') + ' partly met and ' + win + (win === 1 ? ' is' : ' are') + ' still in their window.');
790
+ const head = '<div class="ins-tr ins-th ins-ocols" role="row"><div role="columnheader">Shipped initiative</div><div role="columnheader">What it promised · and what happened so far</div><div role="columnheader">Guardrail and overlap</div><div role="columnheader">Window</div><div role="columnheader">Verdict</div></div>';
791
+ const groups = Object.keys(OUT_G).map((k) => { const G = L.filter((r) => r.group === k); return G.length ? `<div class="ins-grp" role="row"><span role="cell">${k === 'decided' ? 'Decided ' + esc(per.said || 'in these dates') : OUT_G[k]}</span> <span class="q">${G.length}</span></div>` + G.map(outRow).join('') : ''; }).join('');
422
792
  $('#outTbl').innerHTML = head + (groups || '<div class="ins-empty">Nothing to judge yet.</div>');
423
793
  }
424
794
  $('#outTbl').addEventListener('click', (e) => { const b = e.target.closest('[data-verdict]'); if (b) openVerdict((M.outcomes || []).find((r) => r.id === b.dataset.verdict)); });
425
795
 
426
- /* ── the side panel: New goal, New dashboard, the verdict ───────────────────────────────────────────────────────────────────────────── */
427
- let sideKind = null, sideBack = null;
796
+ /* ── the side panel: New goal, New dashboard, Edit chart and the verdict ─────────────────────────────────────────────────────────── */
797
+ let sideKind = null, sideBack = null, SIDE_GO = null;
428
798
  function openSide(o) {
429
- sideKind = o.kind; sideBack = document.activeElement;
430
- $('#sideEye').textContent = o.eye; $('#sideTitle').textContent = o.title; $('#sideTools').innerHTML = o.tools || '';
431
- $('#sideBody').innerHTML = o.body; $('#sideNote').textContent = o.note; $('#sideMsg').textContent = '';
432
- $('#sideAct').innerHTML = `<button type="button" class="ins-primary" id="sideGo">${SV(CHK)}${esc(o.go)}</button>`;
799
+ sideKind = o.kind; sideBack = document.activeElement; SIDE_GO = o.onGo || null;
800
+ $('#side').dataset.kind = o.kind;
801
+ $('#sideEye').innerHTML = o.eyeHtml || esc(o.eye || ''); $('#sideTitle').innerHTML = o.titleHtml || esc(o.title || ''); $('#sideTools').innerHTML = o.tools || '';
802
+ $('#sideBody').innerHTML = o.body || ''; $('#sideNote').textContent = o.note || ''; $('#sideMsg').textContent = '';
803
+ $('#sideAct').innerHTML = (o.pre || '') + (o.go ? `<button type="button" class="ins-primary" id="sideGo"${o.goOff ? ` disabled aria-disabled="true" title="${esc(o.goOff)}"` : ''}>${SV(I.chk)}${esc(o.go)}</button>` : '');
433
804
  $('#side').hidden = false; document.body.classList.add('ins-sideon');
434
- const f = $('#sideBody input, #sideBody textarea, #sideBody button'); if (f) f.focus();
805
+ $('#sideX').setAttribute('aria-label', o.kind === 'goal' || o.kind === 'dash' ? 'Cancel' : 'Close');
806
+ /* the panel takes focus itself, so no field opens with a focus ring the design does not draw; New goal focuses its name, which has none */
807
+ const f = o.focus ? $(o.focus) : null; if (f) f.focus(); else $('#side').focus({ preventScroll: true });
435
808
  }
436
809
  function closeSide() {
437
- $('#side').hidden = true; document.body.classList.remove('ins-sideon'); sideKind = null;
438
- if (selecting) { selecting = false; picked.clear(); drawGoals(); drawSel(); }
439
- if (sideBack && sideBack.focus) sideBack.focus();
810
+ $('#side').hidden = true; document.body.classList.remove('ins-sideon'); sideKind = null; SIDE_GO = null;
811
+ if (selecting) { selecting = false; picked = []; drawGoals(); }
812
+ if (sideBack && sideBack.focus && document.contains(sideBack)) sideBack.focus();
440
813
  }
441
814
  $('#sideX').addEventListener('click', closeSide);
442
- $('#sideAct').addEventListener('click', (e) => { if (e.target.closest('#sideGo')) (SIDE_GO[sideKind] || (() => {}))(); });
443
- const seg = (name, opts, on) => `<div class="cz-seg" role="radiogroup" aria-label="${esc(name)}" data-seg="${esc(name)}">${opts.map((o) => `<button type="button" role="radio" aria-checked="${o === on}" aria-pressed="${o === on}" data-v="${esc(o)}">${esc(o)}</button>`).join('')}</div>`;
444
- $('#sideBody').addEventListener('click', (e) => {
445
- const b = e.target.closest('[data-seg] [data-v]'); if (b) { for (const x of $$('[data-v]', b.parentElement)) { const on = x === b; x.setAttribute('aria-checked', String(on)); x.setAttribute('aria-pressed', String(on)); } if (sideKind === 'goal') goalHint(); return; }
815
+ $('#sideAct').addEventListener('click', (e) => { const b = e.target.closest('#sideGo'); if (b && !b.disabled && SIDE_GO) SIDE_GO(); });
816
+ const seg = (name, opts, on, cls = '') => `<div class="cz-seg${cls}" role="radiogroup" aria-label="${esc(name)}" data-seg="${esc(name)}">${opts.map((o) => `<button type="button" role="radio" aria-checked="${o === on}" aria-pressed="${o === on}" data-v="${esc(o)}">${esc(o)}</button>`).join('')}</div>`;
817
+ const segVal = (name, root = $('#side')) => { const b = root.querySelector(`[data-seg="${name}"] [aria-checked="true"]`); return b ? b.dataset.v : null; };
818
+ const tog = (id, on, label) => `<span class="ins-togw"><button type="button" class="ins-tog${on ? ' on' : ''}" role="switch" aria-checked="${on}" id="${id}" aria-label="${esc(label)}"></button><span>${esc(label)}</span></span>`;
819
+ $('#side').addEventListener('click', (e) => {
820
+ const b = e.target.closest('[data-seg] [data-v]');
821
+ if (b) { for (const x of $$('[data-v]', b.parentElement)) { const on = x === b; x.setAttribute('aria-checked', String(on)); x.setAttribute('aria-pressed', String(on)); } if (sideKind === 'goal') goalHint(); if (sideKind === 'chart') drawChartPreview(); return; }
446
822
  const o = e.target.closest('.ins-opt'); if (o) { for (const x of $$('.ins-opt', o.parentElement)) { const on = x === o; x.classList.toggle('on', on); x.setAttribute('aria-checked', String(on)); } return; }
447
- const t = e.target.closest('.ins-tog'); if (t) { const on = t.getAttribute('aria-checked') !== 'true'; t.setAttribute('aria-checked', String(on)); t.classList.toggle('on', on); return; }
448
- const rm = e.target.closest('[data-unpick]'); if (rm) { picked.delete(rm.dataset.unpick); drawGoals(); drawSel(); drawDashSide(); }
823
+ const t = e.target.closest('.ins-tog'); if (t) { const on = t.getAttribute('aria-checked') !== 'true'; t.setAttribute('aria-checked', String(on)); t.classList.toggle('on', on); if (sideKind === 'chart') drawChartPreview(); if (sideKind === 'goal') goalHint(); return; }
824
+ const c = e.target.closest('[data-src]'); if (c) { for (const x of $$('[data-src]', c.parentElement)) { const on = x === c; x.classList.toggle('on', on); x.setAttribute('aria-pressed', String(on)); } }
449
825
  });
450
- const segVal = (name) => { const b = $(`#sideBody [data-seg="${name}"] [aria-checked="true"]`); return b ? b.dataset.v : null; };
451
- const UNIT_OF = { Percentage: '%', Duration: 'days', Amount: '$', Count: '' };
452
- function goalHint() {
453
- const ty = segVal('Type'), u = $('#ngU'); if (u && !u.dataset.touched) u.value = UNIT_OF[ty] != null ? UNIT_OF[ty] : u.value;
826
+
827
+ /* New goal (AgInsNewGoal): its name is the title; type, better is, baseline, target, period, readings, owner and guardrail */
828
+ const GOAL_TYPES = ['Done or not', 'Percentage', 'Count', 'Amount', 'Duration', 'Stay within'];
829
+ function goalPeriods() {
830
+ const P = periods(), t = new Date(today()), y = t.getUTCFullYear(), out = [];
831
+ for (let k = 0; k < 4; k++) { const q = (Math.floor(t.getUTCMonth() / 3) + k) % 4, yy = y + Math.floor((Math.floor(t.getUTCMonth() / 3) + k) / 4); out.push({ kind: 'Quarter', label: 'Q' + (q + 1) + ' ' + yy, by: Date.UTC(yy, q * 3 + 3, 0) }); }
832
+ out.push({ kind: 'Half', label: P[2].label, by: P[2].to }, { kind: 'Half', label: 'H' + (P[2].label[1] === '1' ? '2 ' + y : '1 ' + (y + 1)), by: P[2].label[1] === '1' ? Date.UTC(y, 12, 0) : Date.UTC(y + 1, 6, 0) });
833
+ out.push({ kind: 'Year', label: String(y), by: Date.UTC(y, 12, 0) }, { kind: 'Year', label: String(y + 1), by: Date.UTC(y + 1, 12, 0) });
834
+ return out;
454
835
  }
455
836
  function openNewGoal() {
456
837
  const objs = [...new Set(M.goals.map((g) => g.pillar).filter(Boolean))];
457
- const p = periods()[0];
458
- openSide({ kind: 'goal', eye: 'New goal', title: 'A goal PMOS reads on a schedule', go: 'Save goal', note: 'Initiatives can anchor to it once it is saved.',
459
- body: `<label class="ins-fl">Name<input class="ins-inp" id="ngName" maxlength="120" placeholder="For example: Partner activation"></label>`
460
- + `<label class="ins-fl">Objective<input class="ins-inp" id="ngObj" maxlength="80" list="ngObjs" placeholder="The objective it serves"><datalist id="ngObjs">${objs.map((o) => `<option value="${esc(o)}">`).join('')}</datalist></label>`
461
- + `<p class="ins-fl">Type</p>${seg('Type', ['Percentage', 'Count', 'Amount', 'Duration'], 'Percentage')}`
462
- + `<div class="ins-2"><label class="ins-fl">Baseline<input class="ins-inp" id="ngBase" inputmode="decimal" maxlength="16" placeholder="24"></label><label class="ins-fl">Target<input class="ins-inp" id="ngTgt" inputmode="decimal" maxlength="16" placeholder="50"></label></div>`
463
- + `<div class="ins-2"><label class="ins-fl">Unit<input class="ins-inp" id="ngU" maxlength="12" value="%"></label><label class="ins-fl">By<input class="ins-inp" id="ngBy" type="date" value="${esc(iso(p.to))}"></label></div>`
464
- + '<p class="note">Better is read from the baseline and the target: a target above the baseline means up is better. Readings are added where the KR metrics are kept, or by a connected source. PMOS never guesses a missing reading.</p>'
465
- + '<div class="ins-box note">A <b>Done or not</b> goal and a <b>Stay within</b> budget are not KR metrics yet. Ask for one in Home, and PMOS proposes it as a health budget or a milestone.</div>' });
466
- $('#ngU').addEventListener('input', () => { $('#ngU').dataset.touched = '1'; });
838
+ const GP = goalPeriods(), others = M.goals.map((g) => g.title);
839
+ /* the objective is eyebrow text with a quiet chevron (AgInsNewGoal: "New goal · Objective 1"); its menu names each objective */
840
+ const objSel = `<span class="ins-mw"><button type="button" class="ins-objb" id="ngObjB" aria-haspopup="menu" aria-expanded="false" aria-controls="ngObjMenu" aria-label="Objective: ${objs.length ? 'Objective 1 · ' + esc(objs[0]) : 'No objective'}">${objs.length ? 'Objective 1' : 'No objective'}<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 10l5 5 5-5"/></svg></button>`
841
+ + `<div class="ins-menu" id="ngObjMenu" role="menu" aria-label="Objective" hidden>${objs.map((o, i) => `<button type="button" role="menuitemradio" aria-checked="${i === 0}" data-obj="${esc(o)}" data-said="Objective ${i + 1}">Objective ${i + 1} · ${esc(o)}</button>`).join('')}<button type="button" role="menuitemradio" aria-checked="${!objs.length}" data-obj="" data-said="No objective">No objective</button><button type="button" role="menuitemradio" aria-checked="false" data-obj="+" data-said="A new objective">A new objective…</button></div></span>`
842
+ + `<input type="hidden" id="ngObj" value="${esc(objs[0] || '')}"><input class="ins-inp ins-onew" id="ngObjNew" maxlength="80" placeholder="Name the objective" aria-label="New objective" hidden>`;
843
+ openSide({ kind: 'goal', eyeHtml: 'New goal · ' + objSel, titleHtml: '<input class="ins-tin" id="ngName" maxlength="120" placeholder="Name the goal" aria-label="Goal name">', go: 'Save goal', note: 'Initiatives can anchor to it once it is saved.', onGo: saveGoal, focus: '#ngName',
844
+ body: `<div><p class="ins-fl">Type</p>${seg('Type', GOAL_TYPES, 'Percentage', ' ins-wrap')}</div>`
845
+ + `<div data-for="measured"><p class="ins-fl">Better is</p>${seg('Better is', ['Up', 'Down', 'Exactly the target'], 'Up')}</div>`
846
+ + `<div data-for="within" hidden><p class="ins-fl">The limit is a</p><div class="ins-prow">${seg('Limit', ['Ceiling', 'Floor'], 'Ceiling')}${tog('ngAlways', true, 'Always on, no end date')}</div></div>`
847
+ + `<div class="ins-2" data-for="measured within"><label class="ins-fl"><span data-lab="base">Baseline</span><span class="ins-uf"><input id="ngBase" inputmode="decimal" maxlength="16" placeholder="24"><span class="u" data-unit></span><span class="on">on ${esc(md(today()))}</span></span></label><label class="ins-fl"><span data-lab="tgt">Target</span><span class="ins-uf"><input id="ngTgt" inputmode="decimal" maxlength="16" placeholder="50"><span class="u" data-unit></span></span></label></div>`
848
+ + '<label class="ins-fl" data-for="within" hidden>Unit, optional<input class="ins-inp" id="ngUnit" maxlength="12" placeholder="for example: s, ms, %"></label>'
849
+ + '<label class="ins-fl" data-for="done" hidden>Steps, one a line, optional<textarea class="ins-ta" id="ngSteps" maxlength="1500" placeholder="Scope agreed&#10;Evidence collected&#10;Audit booked"></textarea></label>'
850
+ + `<div data-for="dated"><p class="ins-fl">Period</p><div class="ins-prow">${seg('Period', ['Quarter', 'Half', 'Year', 'Custom'], 'Quarter')}${csel(`<select class="ins-inp" id="ngPer" aria-label="Which period">${GP.filter((p) => p.kind === 'Quarter').map((p) => `<option value="${iso(p.by)}">${esc(p.label)}</option>`).join('')}</select>`, ' ins-psel')}<input class="ins-inp ins-psel" id="ngBy" type="date" aria-label="Due date" hidden></div><div class="note ins-fn" id="ngCp">A yearly goal asks for a checkpoint at the end of each quarter.</div></div>`
851
+ + `<div><p class="ins-fl">Where the readings come from</p><div class="ins-dg"><button type="button" class="cz-chip on" data-src="analytics" aria-pressed="true">${SV(I.chart)}Product analytics</button><button type="button" class="cz-chip" data-src="jira" aria-pressed="false">${SV(I.ext)}Jira query</button><button type="button" class="cz-chip" data-src="file" aria-pressed="false">${SV(I.doc)}A file or export</button><button type="button" class="cz-chip" data-src="typed" aria-pressed="false">You type it in</button></div><div class="note ins-fn">Read every Monday. PMOS never guesses a missing reading.</div></div>`
852
+ + `<div class="ins-2"><label class="ins-fl"><span>Owner</span><input class="ins-inp" id="ngOwner" maxlength="60" placeholder="Who owns it"></label><label class="ins-fl"><span>Guardrail, optional</span>${csel(`<select class="ins-inp" id="ngGuard"><option value="">None</option>${others.map((t) => `<option>${esc(t)} must not get worse</option>`).join('')}</select>`)}</label></div>`
853
+ + '<div class="ins-box note">For <b>Done or not</b> you set a due date and optional steps instead of a baseline. For <b>Stay within</b> you set a floor or ceiling, and there is no end date.</div>' });
854
+ $('#ngObjB').addEventListener('click', (e) => { e.stopPropagation(); const m = $('#ngObjMenu'); m.hidden = !m.hidden; $('#ngObjB').setAttribute('aria-expanded', String(!m.hidden)); if (!m.hidden) { const c = m.querySelector('[aria-checked="true"]'); if (c) c.focus(); } });
855
+ $('#ngObjMenu').addEventListener('click', (e) => {
856
+ const b = e.target.closest('[data-obj]'); if (!b) return; e.stopPropagation();
857
+ for (const x of $$('[data-obj]', $('#ngObjMenu'))) x.setAttribute('aria-checked', String(x === b));
858
+ $('#ngObj').value = b.dataset.obj; $('#ngObjB').firstChild.textContent = b.dataset.said; $('#ngObjB').setAttribute('aria-label', 'Objective: ' + b.textContent);
859
+ $('#ngObjMenu').hidden = true; $('#ngObjB').setAttribute('aria-expanded', 'false');
860
+ const n = b.dataset.obj === '+'; $('#ngObjNew').hidden = !n; if (n) $('#ngObjNew').focus(); else $('#ngObjB').focus();
861
+ });
862
+ $('#ngPer').dataset.kind = 'Quarter';
863
+ goalHint();
864
+ }
865
+ /** The form follows its type: a measured goal has Better is, a baseline and a target; Stay within a limit and the reading now; Done or not its steps. */
866
+ function goalHint() {
867
+ const ty = segVal('Type'), kind = ty === 'Done or not' ? 'done' : ty === 'Stay within' ? 'within' : 'measured';
868
+ const always = kind === 'within' && $('#ngAlways') && $('#ngAlways').getAttribute('aria-checked') === 'true';
869
+ for (const x of $$('#sideBody [data-for]')) { const k = x.dataset.for.split(' '); x.hidden = !(k.includes(kind) || (k.includes('dated') && !always)); }
870
+ const lb = $('#sideBody [data-lab="base"]'), lt = $('#sideBody [data-lab="tgt"]'), UNIT = { Percentage: '%', Duration: 'days', Amount: '$' };
871
+ for (const u of $$('#sideBody [data-unit]')) u.textContent = UNIT[ty] || '';
872
+ const on = $('#sideBody .ins-uf .on'); if (on) on.hidden = kind !== 'measured'; // the baseline is read on the day the goal is saved
873
+ if (lb) { lb.textContent = kind === 'within' ? 'Reading now' : 'Baseline'; lt.textContent = kind === 'within' ? 'Limit' : 'Target'; }
874
+ const pk = segVal('Period'), sel = $('#ngPer'), by = $('#ngBy'); if (!sel) return;
875
+ if (pk !== sel.dataset.kind) {
876
+ sel.dataset.kind = pk; sel.closest('.ins-sel').hidden = pk === 'Custom'; by.hidden = pk !== 'Custom';
877
+ if (pk !== 'Custom') sel.innerHTML = goalPeriods().filter((p) => p.kind === pk).map((p) => `<option value="${iso(p.by)}">${esc(p.label)}</option>`).join('');
878
+ }
879
+ $('#ngCp').hidden = kind === 'done';
467
880
  }
468
881
  async function saveGoal() {
469
- const v = (id) => $(id).value.trim(), m = $('#sideMsg');
470
- const fields = { metric: v('#ngName'), baseline: Number(v('#ngBase')), target: Number(v('#ngTgt')), by: v('#ngBy'), unit: v('#ngU'), pillar: v('#ngObj') || undefined };
471
- if (!fields.metric) { m.textContent = 'Give the goal a name.'; $('#ngName').focus(); return; }
472
- if (v('#ngBase') === '' || !Number.isFinite(fields.baseline) || v('#ngTgt') === '' || !Number.isFinite(fields.target)) { m.textContent = 'Type a number for the baseline and the target.'; return; }
473
- if (fields.baseline === fields.target) { m.textContent = 'The target must differ from the baseline.'; return; }
474
- if (!/^\d{4}-\d{2}-\d{2}$/.test(fields.by)) { m.textContent = 'Pick the date it is due.'; return; }
882
+ const v = (id) => $(id).value.trim(), m = $('#sideMsg'), ty = segVal('Type'), pk = segVal('Period');
883
+ const obj = $('#ngObj').value === '+' ? v('#ngObjNew') : $('#ngObj').value;
884
+ if (!v('#ngName')) { m.textContent = 'Give the goal a name.'; $('#ngName').focus(); return; }
885
+ const always = ty === 'Stay within' && $('#ngAlways').getAttribute('aria-checked') === 'true';
886
+ const src = $('#sideBody [data-src][aria-pressed="true"]');
887
+ const body = { ws: M.board.ws, name: v('#ngName'), type: ty, direction: segVal('Better is'), baseline: v('#ngBase'), target: v('#ngTgt'),
888
+ due: pk === 'Custom' ? v('#ngBy') : $('#ngPer').value, period_kind: always ? null : pk, period_label: pk === 'Custom' ? 'Custom' : ($('#ngPer').selectedOptions[0] || {}).textContent || pk,
889
+ objective: obj || '', source: src ? src.dataset.src : '', owner: v('#ngOwner'), guardrail: $('#ngGuard').value,
890
+ steps: ty === 'Done or not' ? $('#ngSteps').value.split('\n').map((x) => x.trim()).filter(Boolean) : undefined,
891
+ limit: ty === 'Stay within' ? (segVal('Limit') === 'Floor' ? 'floor' : 'ceiling') : undefined, unit: ty === 'Stay within' ? v('#ngUnit') : undefined, always_on: always };
475
892
  $('#sideGo').disabled = true; m.textContent = 'Saving.';
476
- const res = await pmPost('/api/records/kr-metrics/add', { ws: M.board.ws, fields, why: 'New goal from Insights' });
893
+ const res = await pmPost('/api/insights-records/goal', body);
477
894
  $('#sideGo').disabled = false;
478
895
  if (!res || res.ok !== true) { m.textContent = (res && res.error) || 'The goal could not be saved. Nothing changed.'; return; }
479
- closeSide(); toast('Saved ' + fields.metric + '. It shows on Goals; it is drawn after two readings.'); await load();
896
+ closeSide(); toast('Saved ' + body.name + '. It shows on All goals' + (ty === 'Done or not' || ty === 'Stay within' ? '.' : '; its line is drawn after two readings.')); await load();
897
+ if (curDash().id !== 'all') setView('all'); // a saved dashboard does not hold the new goal, so show every goal
480
898
  }
481
- function drawSel() {
482
- $('#selBar').hidden = !selecting;
483
- $('#selN').textContent = picked.size + (picked.size === 1 ? ' goal selected' : ' goals selected');
484
- }
485
- $('#selCancel').addEventListener('click', closeSide);
899
+
900
+ /* New dashboard (AgInsNewDash): pick goals in the table; each chart's form, the order (drag), Range and Pin */
901
+ const FORMS = ['Line', 'Bars', 'Number', 'Meter'];
902
+ const formOf = {}; // the form picked for each goal while the panel is open (no route keeps it yet)
486
903
  function openNewDash() {
487
904
  if (!M.board.id) { toast('A dashboard is saved on a board, and this workspace has none.'); return; }
488
- selecting = true; picked.clear(); setTab('goals'); drawGoals(); drawSel();
489
- openSide({ kind: 'dash', eye: 'New dashboard · a saved view of Goals', title: 'New dashboard', go: 'Save dashboard', note: 'Saved in this workspace. It shows under View and in Library.', body: '' });
905
+ selecting = true; picked = []; setTab('goals'); if (curDash().saved) dash = 'all'; drawGoals();
906
+ openSide({ kind: 'dash', eye: 'New dashboard · a saved view of Goals', title: 'New dashboard', go: 'Save dashboard', note: 'Saved in this workspace. It shows under View and in Library.', onGo: saveNewDash, body: '' });
490
907
  drawDashSide();
491
908
  }
492
909
  function drawDashSide() {
493
- const keep = { n: ($('#ndName') || {}).value || '', q: ($('#ndQ') || {}).value || '', pin: $('#ndPin') ? $('#ndPin').getAttribute('aria-checked') === 'true' : false };
494
- const L = [...picked].map((id) => M.goals.find((g) => g.id === id)).filter(Boolean);
495
- $('#sideBody').innerHTML = `<form class="ins-desc" id="ndAsk"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l1.8 4.7L18.5 9.5l-4.7 1.8L12 16l-1.8-4.7L5.5 9.5l4.7-1.8z"/></svg><input id="ndAskIn" maxlength="300" placeholder="Or describe it, and PMOS shapes it in a chat" aria-label="Describe the dashboard"><button type="submit" class="cz-ib solid" aria-label="Describe it in a chat" title="Describe it in a chat">${SV('M12 19V5M6 11l6-6 6 6')}</button></form>`
910
+ if (sideKind !== 'dash') return;
911
+ const keep = { n: ($('#ndName') || {}).value || '', q: ($('#ndQ') || {}).value || '', pin: $('#ndPin') ? $('#ndPin').getAttribute('aria-checked') === 'true' : false, r: segVal('Range') || 'Quarter', msg: ($('#ndMsg') || {}).textContent || '' };
912
+ const L = picked.map((id) => M.goals.find((g) => g.id === id)).filter(Boolean), rest = M.goals.filter((g) => !picked.includes(g.id));
913
+ $('#sideTitle').textContent = keep.n || 'New dashboard';
914
+ $('#sideBody').innerHTML = `<form class="ins-desc" id="ndAsk"><span class="sp">${SV(I.spark)}</span><input id="ndAskIn" maxlength="300" placeholder="Or describe it, and PMOS fills this in" aria-label="Describe the dashboard"><button type="submit" class="cz-ib solid sm" aria-label="Fill it in from the description" title="Fill it in">${SV(I.up)}</button></form>`
915
+ + `<p class="note ins-dmsg" id="ndMsg" role="status"${keep.msg ? '' : ' hidden'}>${esc(keep.msg)}</p>`
496
916
  + `<label class="ins-fl">Name<input class="ins-inp" id="ndName" maxlength="60" value="${esc(keep.n)}" placeholder="For example: Partner first week"></label>`
497
917
  + `<label class="ins-fl">The question it answers<input class="ins-inp" id="ndQ" maxlength="200" value="${esc(keep.q)}" placeholder="Are new partners getting value in their first week?"></label>`
498
- + `<p class="ins-fl">Charts <span class="q">${L.length} picked on the left</span></p>`
499
- + (L.length ? `<div class="ins-picked">${L.map((g) => `<div class="ins-pk"><b>${esc(g.title)}</b><span class="note">${esc(g.key ? 'drawn as a line' : 'no series yet')}</span><button type="button" class="cz-ib" data-unpick="${esc(g.id)}" aria-label="Take ${esc(g.title)} off" title="Take it off">${SV('M6 6l12 12M18 6L6 18')}</button></div>`).join('')}</div>` : '<p class="note">Press goals in the table to add them.</p>')
500
- + `<div class="ins-pinrow"><button type="button" class="ins-tog${keep.pin ? ' on' : ''}" role="switch" aria-checked="${keep.pin}" id="ndPin" aria-label="Pin, so it opens first"></button><span>Pin, so it opens first</span></div>`
501
- + '<p class="note">A chart’s form (line, bars, number or meter) is set on the dashboard afterwards: Edit opens it beside a chat.</p>';
502
- $('#ndAsk').addEventListener('submit', (e) => { e.preventDefault(); const t = $('#ndAskIn').value.trim(); toChat({ say: 'Make a dashboard of ' + t }); });
918
+ + `<div><p class="ins-fl">Charts <span class="q">${L.length} picked on the left · drag to order</span></p>`
919
+ + (L.length ? `<div class="ins-picked" id="ndList">${L.map((g) => `<div class="ins-pk" draggable="true" tabindex="0" aria-label="${esc(g.title)}: Alt and the arrow keys move it, Delete takes it off" data-pk="${esc(g.id)}"><span class="ins-grip" aria-hidden="true">⋮⋮</span><b>${esc(g.title)}</b>${seg('Form of ' + g.title, FORMS, formOf[g.id] || 'Line')}</div>`).join('')}</div>` : '<p class="note">Press goals in the table to add them.</p>')
920
+ + (rest.length ? `<button type="button" class="cz-chip gh ins-addg" id="ndAdd">${SV(I.plus)}Add a goal that is not on Goals</button><select class="ins-inp" id="ndAddSel" aria-label="Add a goal" hidden><option value="">Pick a goal</option>${rest.map((g) => `<option value="${esc(g.id)}">${esc(g.title)}</option>`).join('')}</select>` : '') + '</div>'
921
+ + `<div class="ins-rrow"><div><p class="ins-fl">Range</p>${seg('Range', ['8w', 'Quarter', '26w'], keep.r)}</div>${tog('ndPin', keep.pin, 'Pin, so it opens first')}</div>`;
922
+ $('#ndAsk').addEventListener('submit', async (e) => {
923
+ e.preventDefault(); const t = $('#ndAskIn').value.trim(), m = $('#ndMsg'); m.hidden = false; // the describe message is said under the box, not in the footer
924
+ if (!t) { m.textContent = 'Describe the dashboard in a few words.'; $('#ndAskIn').focus(); return; }
925
+ m.textContent = 'Filling it in.';
926
+ const r = await pmPost('/api/insights-records/describe', { ws: M.board.ws, text: t });
927
+ if (!r || r.ok !== true) { m.textContent = (r && r.error) || 'It could not be filled in. Nothing changed.'; return; }
928
+ picked = [...new Set(picked.concat(r.goals))]; drawGoals();
929
+ $('#ndName').value = $('#ndName').value.trim() || r.name; if (r.question && !$('#ndQ').value.trim()) $('#ndQ').value = r.question;
930
+ const keepR = r.range; drawDashSide(); const rb = $(`#sideBody [data-seg="Range"] [data-v="${keepR}"]`); if (rb) rb.click();
931
+ $('#ndMsg').hidden = false; $('#ndMsg').textContent = r.goals.length ? 'Filled in from your words: ' + r.said.join(', ') + '. Check it, then save.' : 'No goal is named in that description, so none is picked. The name and question are filled in.';
932
+ });
933
+ $('#ndName').addEventListener('input', () => { $('#sideTitle').textContent = $('#ndName').value.trim() || 'New dashboard'; });
934
+ const add = $('#ndAdd'); if (add) add.onclick = () => { add.hidden = true; $('#ndAddSel').hidden = false; $('#ndAddSel').focus(); };
935
+ const sel = $('#ndAddSel'); if (sel) sel.onchange = () => { if (sel.value) { picked = picked.concat(sel.value); drawGoals(); drawDashSide(); } };
503
936
  }
937
+ /* a chart comes off the list by pressing its row in the table again (pressGoal), or with Delete on its row here */
938
+ $('#sideBody').addEventListener('click', (e) => { const f = e.target.closest('.ins-pk [data-v]'); if (f) formOf[f.closest('[data-pk]').dataset.pk] = f.dataset.v; });
939
+ /* drag to order (and Alt+Arrow keys on a row of the list) */
940
+ let dragId = null;
941
+ $('#sideBody').addEventListener('dragstart', (e) => { const r = e.target.closest && e.target.closest('[data-pk]'); if (!r) return; dragId = r.dataset.pk; try { e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', dragId); } catch { /* no data */ } });
942
+ $('#sideBody').addEventListener('dragover', (e) => { if (dragId && e.target.closest('[data-pk]')) e.preventDefault(); });
943
+ $('#sideBody').addEventListener('drop', (e) => {
944
+ const r = e.target.closest('[data-pk]'); if (!dragId || !r) return; e.preventDefault();
945
+ const to = r.dataset.pk; if (to !== dragId) { const L = picked.filter((x) => x !== dragId); L.splice(L.indexOf(to) + (picked.indexOf(dragId) < picked.indexOf(to) ? 1 : 0), 0, dragId); picked = L; drawGoals(); drawDashSide(); }
946
+ dragId = null;
947
+ });
948
+ $('#sideBody').addEventListener('keydown', (e) => {
949
+ const r = e.target.closest && e.target.closest('[data-pk]'); if (!r) return;
950
+ if ((e.key === 'Delete' || e.key === 'Backspace') && e.target === r) { e.preventDefault(); picked = picked.filter((x) => x !== r.dataset.pk); drawGoals(); drawDashSide(); return; }
951
+ if (!e.altKey || !/^Arrow(Up|Down)$/.test(e.key)) return;
952
+ e.preventDefault(); const i = picked.indexOf(r.dataset.pk), j = i + (e.key === 'ArrowUp' ? -1 : 1); if (j < 0 || j >= picked.length) return;
953
+ const L = picked.slice(); [L[i], L[j]] = [L[j], L[i]]; picked = L; drawGoals(); drawDashSide();
954
+ });
955
+ async function saveDash(body) { return pmPost('/api/premium-dashboards/save', Object.assign({ ws: M.board.ws, board: M.board.id }, body)); }
504
956
  async function saveNewDash() {
505
- const m = $('#sideMsg'), name = $('#ndName').value.trim();
957
+ const m = $('#sideMsg'), name = $('#ndName').value.trim(), purpose = $('#ndQ').value.trim();
506
958
  if (!name) { m.textContent = 'Give the dashboard a name.'; $('#ndName').focus(); return; }
507
- if (!picked.size) { m.textContent = 'Select at least one goal in the table.'; return; }
959
+ if (!purpose) { m.textContent = 'Say the question it answers, in one line.'; $('#ndQ').focus(); return; }
960
+ if (!picked.length) { m.textContent = 'Select at least one goal in the table.'; return; }
508
961
  $('#sideGo').disabled = true; m.textContent = 'Saving.';
509
- const res = await saveDash({ name, purpose: $('#ndQ').value.trim(), charts: [...picked] });
962
+ const pin = $('#ndPin').getAttribute('aria-checked') === 'true';
963
+ const res = await pmPost('/api/insights-records/dashboard', { ws: M.board.ws, board: M.board.id, name, purpose, charts: picked.map((g) => ({ goal: g, form: formOf[g] || 'Line' })), range: segVal('Range') || 'Quarter', pin });
510
964
  $('#sideGo').disabled = false;
511
965
  if (!res || res.ok !== true) { m.textContent = (res && res.error) || 'The dashboard could not be saved. Nothing changed.'; return; }
512
- const id = res.id || (res.dashboard && res.dashboard.id) || null, pin = $('#ndPin').getAttribute('aria-checked') === 'true';
513
- closeSide(); toast('Saved ' + name + '. It shows under View and in Library.');
514
- if (pin && id) await pinDash(id); else await load();
515
- if (id) setView(id);
966
+ closeSide(); toast('Saved ' + name + (res.pinned ? '. Pinned: it opens first on Goals.' : '. It shows under View and in Library.'));
967
+ await load();
968
+ if (res.id && M.dashboards.some((d) => d.id === res.id)) setView(res.id);
516
969
  }
970
+
971
+ /* Edit chart (AgInsChart): one goal drawn one way on a dashboard. The route keeps which goals a dashboard holds and their order; the form, range,
972
+ * comparison, target line, forecast and note are drawn here and not saved yet. */
973
+ let chartDash = null;
974
+ function chartHost(D) { return D && D.saved ? D : savedDash().find((d) => d.id === M.pinned) || savedDash()[0] || null; }
975
+ function openChartEdit(goalId, D0) {
976
+ const D = chartHost(D0 || curDash()); chartDash = D;
977
+ const g = M.goals.find((x) => x.id === goalId) || M.goals.find((x) => x.key) || M.goals[0];
978
+ if (!g) { toast('There is no goal to chart yet. Add one with New goal.'); return; }
979
+ const on = D && D.charts.includes(g.id), cs = (D && (M.chartSet || {})[D.id] || {})[g.id] || {};
980
+ openSide({ kind: 'chart', eye: D ? 'Chart on ' + D.name : 'Chart · no dashboard yet', title: g.title, go: 'Save chart', onGo: saveChart,
981
+ goOff: !D ? 'Make a dashboard first, with New dashboard' : '',
982
+ note: D ? 'Changes this dashboard only. The goal and its readings are not changed.' : 'A chart lives on a dashboard. Make one first with New dashboard.',
983
+ tools: `<span class="ins-mw"><button type="button" class="cz-ib" id="chMore" aria-haspopup="menu" aria-expanded="false" aria-controls="chMenu" aria-label="More: duplicate, remove from dashboard" title="More: duplicate, remove from dashboard">${SV(I.more, 3)}</button><div class="ins-menu ins-right" id="chMenu" role="menu" hidden><button type="button" role="menuitem" disabled aria-disabled="true">Duplicate<small>A dashboard holds one chart for each goal</small></button><button type="button" role="menuitem" id="chRemove"${on ? '' : ' disabled aria-disabled="true"'}>Remove from dashboard<small>${on ? 'Takes this goal off ' + esc(D.name) : 'It is not on this dashboard'}</small></button></div></span>`,
984
+ body: '<div class="ins-prev" id="chPrev"></div>'
985
+ + `<label class="ins-fl">Goal${csel(`<select class="ins-inp" id="chGoal">${M.goals.map((x) => `<option value="${esc(x.id)}"${x.id === g.id ? ' selected' : ''}>${esc(x.title + (krId(x) ? ' · ' + krId(x) : ''))}</option>`).join('')}</select>`)}</label>`
986
+ + `<div><p class="ins-fl">Form</p>${seg('Form', FORMS, cs.form || formOf[g.id] || 'Line')}<div class="note ins-fn">Bars and a meter start at zero. A goal that goes below zero is drawn as a line.</div></div>`
987
+ + `<div class="ins-2"><div><p class="ins-fl">Range</p>${seg('Range', ['8w', 'Quarter', '26w'], cs.range || '26w')}</div><label class="ins-fl"><span>Compare with</span>${csel(`<select class="ins-inp" id="chCmp"><option value="lq"${cs.compare === '' ? '' : ' selected'}>Last quarter</option><option value=""${cs.compare === '' ? ' selected' : ''}>Nothing</option></select>`)}</label></div>`
988
+ + `<div class="ins-togs">${tog('chTgt', cs.target !== false, 'Target line')}${tog('chFc', cs.forecast === true, 'Forecast to its date')}</div>`
989
+ + `<label class="ins-fl"><span>Note under the chart</span><input class="ins-inp" id="chNote" maxlength="160" value="${esc(cs.note || '')}" placeholder="For example: the dip on Oct 15 is an outage"></label>` });
990
+ $('#chGoal').addEventListener('change', () => { $('#sideTitle').textContent = (M.goals.find((x) => x.id === $('#chGoal').value) || {}).title || ''; drawChartPreview(); });
991
+ $('#chCmp').addEventListener('change', drawChartPreview);
992
+ $('#chMore').addEventListener('click', (e) => { e.stopPropagation(); const mm = $('#chMenu'); mm.hidden = !mm.hidden; $('#chMore').setAttribute('aria-expanded', String(!mm.hidden)); });
993
+ $('#chMenu').addEventListener('click', async (e) => {
994
+ const b = e.target.closest('#chRemove'); if (!b || b.disabled || !D) return;
995
+ const id = $('#chGoal').value, res = await saveDash({ id: D.id, name: D.name, purpose: D.purpose, charts: D.charts.filter((x) => x !== id), main: D.main });
996
+ if (!res || res.ok !== true) { $('#sideMsg').textContent = (res && res.error) || 'The dashboard could not be saved. Nothing changed.'; return; }
997
+ closeSide(); toast('Took it off ' + D.name + '.'); await load();
998
+ });
999
+ drawChartPreview();
1000
+ }
1001
+ const RANGE_DAYS = { '8w': 56, '26w': 182 };
1002
+ function drawChartPreview() {
1003
+ const box = $('#chPrev'); if (!box) return;
1004
+ const g = M.goals.find((x) => x.id === $('#chGoal').value), c = g && g.key ? byKey(g.key) : null, form = segVal('Form'), rg = segVal('Range'), cmp = $('#chCmp').value;
1005
+ const t = today(), P = periods(), from = rg === 'Quarter' ? P[0].from : t - RANGE_DAYS[rg] * DAY;
1006
+ const head = g ? `<div class="ins-ph"><b>${esc(g.nowTxt || '—')}</b><span class="note">${esc((g.targetTxt ? 'target ' + g.targetTxt + (g.byAt ? ' by ' + md(day(g.byAt)) : '') : 'no target') + (cmp && c ? ' · light ' + (form === 'Bars' ? 'bars' : 'line') + ' is last quarter' : ''))}</span></div>` : '';
1007
+ if (!c) { box.innerHTML = head + `<p class="note ins-pe">${esc(g && g.readings ? 'One reading, no series yet, so nothing is drawn.' : 'No reading yet, so nothing is drawn.')}</p>`; return; }
1008
+ const pts = c.pts.filter((p) => day(p.at) >= from), prev = cmp ? c.pts.filter((p) => day(p.at) >= P[1].from && day(p.at) <= P[1].to) : [];
1009
+ box.innerHTML = head + (pts.length ? chartSvg({ pts, prev, form, target: $('#chTgt').getAttribute('aria-checked') === 'true' ? g.target : null, proj: $('#chFc').getAttribute('aria-checked') === 'true' && g.proj ? { at: g.byAt, v: g.proj.atDue } : null, tone: g.tone })
1010
+ + `<div class="ins-px note"><span>${esc(md(day(pts[0].at)))}</span><span>${esc(md(day(pts[pts.length - 1].at)))}</span></div>` : '<p class="note ins-pe">No reading falls in this range.</p>');
1011
+ }
1012
+ /** One goal's readings drawn as a line, bars, a number or a meter. Values are readings at their dates; nothing is filled in between. */
1013
+ function chartSvg(o) {
1014
+ const W = 500, H = 140, Pd = 8, all = o.pts.concat(o.prev || []);
1015
+ if (o.form === 'Number') { const l = o.pts[o.pts.length - 1]; return `<div class="ins-num"><b>${esc(l.txt)}</b><span class="note">on ${esc(md(day(l.at)))}</span></div>`; }
1016
+ const vs = all.map((p) => p.v).concat(o.target != null ? [o.target] : [], o.proj ? [o.proj.v] : []), neg = vs.some((v) => v < 0);
1017
+ const form = (o.form === 'Bars' || o.form === 'Meter') && neg ? 'Line' : o.form;
1018
+ if (form === 'Meter') {
1019
+ const l = o.pts[o.pts.length - 1], mx = Math.max(o.target || 0, l.v) || 1;
1020
+ return `<div class="ins-meter" role="img" aria-label="${esc(l.txt + (o.target != null ? ' of ' + o.target : ''))}"><i style="width:${Math.round(l.v / mx * 100)}%;background:${TONE_BAR[o.tone] || TONE_BAR.q}"></i>${o.target != null ? `<span class="tg" style="left:${Math.round(o.target / mx * 100)}%"></span>` : ''}</div>`;
1021
+ }
1022
+ const lo = form === 'Bars' ? 0 : Math.min(...vs), hi = Math.max(...vs), rg = hi - lo || 1, y = (v) => Pd + (1 - (v - lo) / rg) * (H - 2 * Pd);
1023
+ const t0 = day(o.pts[0].at), t1 = Math.max(day(o.pts[o.pts.length - 1].at), o.proj ? day(o.proj.at) : 0), x = (t) => Pd + (t1 > t0 ? (t - t0) / (t1 - t0) : 0.5) * (W - 2 * Pd);
1024
+ const tgt = o.target != null ? `<line class="tg" x1="0" x2="${W}" y1="${y(o.target).toFixed(1)}" y2="${y(o.target).toFixed(1)}"/>` : '';
1025
+ if (form === 'Bars') {
1026
+ const n = o.pts.length + (o.prev || []).length, bw = Math.max(6, Math.min(26, (W - 2 * Pd) / Math.max(1, n) - 8)), L = (o.prev || []).map((p) => [p, 'pv']).concat(o.pts.map((p) => [p, 'cu']));
1027
+ return `<svg class="ins-ch2" viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(o.pts.length + ' readings as bars')}">${tgt}${L.map(([p, k], i) => { const bx = Pd + i * ((W - 2 * Pd) / Math.max(1, n)); return `<rect class="${k}" x="${bx.toFixed(1)}" y="${y(p.v).toFixed(1)}" width="${bw.toFixed(1)}" height="${(H - Pd - y(p.v)).toFixed(1)}" rx="3"/>`; }).join('')}</svg>`;
1028
+ }
1029
+ const line = o.pts.map((p) => x(day(p.at)).toFixed(1) + ',' + y(p.v).toFixed(1)), last = line[line.length - 1].split(',');
1030
+ const pv = (o.prev || []).length > 1 ? `<polyline class="pv" points="${o.prev.map((p, i) => (Pd + i / (o.prev.length - 1) * (W - 2 * Pd)).toFixed(1) + ',' + y(p.v).toFixed(1)).join(' ')}"/>` : '';
1031
+ const pj = o.proj ? `<polyline class="pj" points="${last.join(',')} ${x(day(o.proj.at)).toFixed(1)},${y(o.proj.v).toFixed(1)}"/>` : '';
1032
+ const ship = o.ship != null && o.ship >= t0 && o.ship <= t1 ? `<line class="ship" x1="${x(o.ship).toFixed(1)}" x2="${x(o.ship).toFixed(1)}" y1="0" y2="${H}"/><circle class="shipd" cx="${x(o.ship).toFixed(1)}" cy="3" r="3"/>` : '';
1033
+ return `<svg class="ins-ch2" viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(o.pts.length + ' readings as a line')}">${tgt}${pv}<polygon class="ar" points="${line[0].split(',')[0]},${H} ${line.join(' ')} ${last[0]},${H}"/>${pj}<polyline class="ln" points="${line.join(' ')}"/>${ship}<circle class="dt" cx="${last[0]}" cy="${last[1]}" r="3.6" style="fill:${TONE_BAR[o.tone] || TONE_BAR.q}"/></svg>`;
1034
+ }
1035
+ async function saveChart() {
1036
+ const D = chartDash, id = $('#chGoal').value, m = $('#sideMsg'); if (!D) return;
1037
+ $('#sideGo').disabled = true; m.textContent = 'Saving.';
1038
+ const res = await pmPost('/api/insights-records/chart', { ws: M.board.ws, board: M.board.id, dash: D.id, goal: id, form: segVal('Form'), range: segVal('Range'), compare: $('#chCmp').value,
1039
+ target: $('#chTgt').getAttribute('aria-checked') === 'true', forecast: $('#chFc').getAttribute('aria-checked') === 'true', note: $('#chNote').value.trim(), add: !D.charts.includes(id) });
1040
+ $('#sideGo').disabled = false;
1041
+ if (!res || res.ok !== true) { m.textContent = (res && res.error) || 'The chart could not be saved. Nothing changed.'; return; }
1042
+ closeSide(); toast((D.charts.includes(id) ? 'Saved the chart on ' : 'Added to ') + D.name + '.'); await load();
1043
+ }
1044
+
1045
+ /* the verdict (AgInsVerdict): the goal with the ship date marked, what was promised, evidence, and Keep, Iterate or Stop. No route records a verdict
1046
+ * yet, so Record verdict is not available; Home is one press away to ask about it. */
517
1047
  function openVerdict(r) {
518
1048
  if (!r) return;
519
- const g = r.goal, c = g && g.key ? byKey(g.key) : null;
520
- openSide({ kind: 'verdict', eye: 'Evaluate · your verdict', title: r.title, go: 'Record verdict', note: 'Opens Home with your verdict; PMOS records the evaluation there. Nothing is sent.',
521
- tools: `<a class="cz-ib" href="/premium-initiative.html?${wsQ()}id=${encodeURIComponent(r.id)}" aria-label="Open the initiative" title="Open the initiative">${SV(DOCI)}</a>`,
522
- body: (g ? `<p class="ins-fl">${esc(g.title)} <span class="q">the goal it is anchored to</span></p>${c ? `<div class="ntw pdchart">${tileHtml(c)}</div>` : ''}<div class="ins-kv3"><span><small>Promised</small><b>${esc(g.targetTxt || '—')}${g.by ? ' by ' + esc(g.by) : ''}</b></span><span><small>So far</small><b style="color:${PACE_C[g.pace.tone] || 'inherit'}">${esc(g.nowTxt || '—')}</b></span><span><small>Pace</small><b>${esc(g.pace.head)}</b></span></div>`
523
- : '<p class="note">No goal with readings is anchored to it, so there is nothing measured to judge against. Judge it on what you saw.</p>')
524
- + '<p class="ins-fl">Your verdict</p><div class="ins-opts" role="radiogroup" aria-label="Your verdict">'
525
- + [['Keep', 'It stays as built. The Board moves it to Done.'], ['Iterate', 'Keep it, and start a linked initiative in Triage for the next step.'], ['Stop', 'Archive it and say why. The code stays until a chore removes it.']]
526
- .map(([k, t], i) => `<button type="button" class="ins-opt${i === 1 ? ' on' : ''}" role="radio" aria-checked="${i === 1}" data-vd="${k}"><i class="rd"></i><span><b>${k}</b><small>${esc(t)}</small></span></button>`).join('') + '</div>'
1049
+ const P = promiseOf(r), g = P && P.g, c = g && g.key ? byKey(g.key) : null, ship = day(r.endAt);
1050
+ const chart = !g ? '<p class="note">No goal with readings is anchored to it, so there is nothing measured to judge against. Judge it on what you saw.</p>'
1051
+ : `<div><p class="ins-fl">${esc(g.title)} <span class="q">${krId(g) ? esc(krId(g)) + ' · ' : ''}${ship !== null ? 'blue mark is the ship date' : 'no ship date recorded'}</span></p>${c ? chartSvg({ pts: c.pts, form: 'Line', target: g.target, ship, tone: g.tone }) + `<div class="ins-px note"><span>${esc(md(day(c.pts[0].at)))}</span>${ship !== null ? `<span>shipped ${esc(md(ship))}</span>` : ''}<span>${esc(md(day(c.pts[c.pts.length - 1].at)))}</span></div>` : `<p class="note ins-pe">${esc(g.readings ? 'One reading, no series yet, so nothing is drawn.' : 'No reading yet, so nothing is drawn.')}</p>`}</div>`
1052
+ + `<div class="ins-kv3"><span><small>Promised</small><b>${esc(P.promised !== null ? sgn(P.promised, g.unit) : '—')}</b></span><span><small>So far</small><b style="color:${P.state === 'met' ? 'var(--cz-ok)' : P.state === 'part' ? 'var(--cz-risk)' : 'var(--cz-ink3)'}">${esc(P.moved !== null ? sgn(P.moved, g.unit) : 'no reading')}</b></span><span><small>Guardrail</small><b class="${guardOf(r) ? '' : 'q'}">${esc(guardOf(r) ? guardOf(r).name + ': ' + guardOf(r).text : 'none set')}</b></span></div>`;
1053
+ const due = dueOf(r);
1054
+ openSide({ kind: 'verdict', eye: 'Evaluate · your verdict' + (due !== null ? ', due ' + md(due) : ''), title: r.title, go: 'Record verdict', onGo: () => saveVerdict(r),
1055
+ note: 'Records the evaluation. Nothing is sent.',
1056
+ pre: `<a class="cz-ib sm" href="${esc(homeAsk('verdict', 'Help me judge ' + r.title + ' (' + r.id + ').'))}" aria-label="Ask about this verdict in Home" title="Ask about this verdict in Home">${SV(I.home)}</a>`,
1057
+ tools: `<a class="cz-ib" href="${iniHref(r.id)}" aria-label="Open the PRD" title="Open the PRD">${SV(I.doc)}</a><a class="cz-ib" href="/premium-board.html?${wsQ()}focus=${encodeURIComponent(r.id)}" aria-label="Open on the Board" title="Open on the Board">${SV(I.next)}</a>`,
1058
+ body: chart
1059
+ + `<div><p class="ins-fl">Evidence <span class="q">${(r.evidence || []).length}</span></p>${(r.evidence || []).length ? `<ul class="ins-ev">${r.evidence.map((x) => `<li>${esc(x)}</li>`).join('')}</ul>` : `<p class="note">${g ? 'No reading of ' + esc(g.title) + ' is recorded.' : 'No goal with readings is anchored to it.'}</p>`}</div>`
1060
+ + '<div><p class="ins-fl">Your verdict</p><div class="ins-opts" role="radiogroup" aria-label="Your verdict">'
1061
+ + [['Keep', 'It stays as built. Move it to Done on the Board.'], ['Iterate', 'Keep it, and start a linked initiative in Triage for the next step.'], ['Stop', 'Archive it and say why. The code stays until a chore removes it.']]
1062
+ .map(([k, t], i) => `<button type="button" class="ins-opt${i === 1 ? ' on' : ''}" role="radio" aria-checked="${i === 1}" data-vd="${k}"><i class="rd"></i><span><b>${k}</b><small>${esc(t)}</small></span></button>`).join('') + '</div></div>'
527
1063
  + '<label class="ins-fl">What we learned<textarea class="ins-ta" id="vdLearn" maxlength="600" placeholder="What the numbers and the work say"></textarea></label>' });
528
- SIDE_GO.verdict = () => {
529
- const v = ($('#sideBody .ins-opt.on') || {}).dataset || {}, learned = $('#vdLearn').value.trim();
530
- location.href = homeAsk('verdict', 'Record my verdict on ' + r.title + ' (' + r.id + '): ' + (v.vd || 'Iterate') + '.' + (learned ? ' What we learned: ' + learned : ''));
531
- };
1064
+ $('#sideMsg').textContent = '';
1065
+ }
1066
+ async function saveVerdict(r) {
1067
+ const m = $('#sideMsg'), o = $('#sideBody .ins-opt[aria-checked="true"]'), learned = $('#vdLearn').value.trim();
1068
+ if (!learned) { m.textContent = 'Say what you learned, in a line.'; $('#vdLearn').focus(); return; }
1069
+ $('#sideGo').disabled = true; m.textContent = 'Saving.';
1070
+ const res = await pmPost('/api/insights-records/verdict', { ws: M.board.ws, board: M.board.id, ini: r.id, verdict: o ? o.dataset.vd : 'Iterate', learned, goal: r.goal ? r.goal.id : null });
1071
+ $('#sideGo').disabled = false;
1072
+ if (!res || res.ok !== true) { m.textContent = (res && res.error) || 'The verdict could not be saved. Nothing changed.'; return; }
1073
+ closeSide(); toast('Recorded: ' + (o ? o.dataset.vd : 'Iterate') + ' for ' + r.title + '.'); await load();
532
1074
  }
533
- const SIDE_GO = { goal: saveGoal, dash: saveNewDash, verdict: () => {} };
534
1075
 
535
1076
  /* the + menu */
536
1077
  $('#newMenu').addEventListener('click', (e) => {
537
1078
  const b = e.target.closest('[data-new]'); if (!b) return; closeMenus();
538
1079
  if (b.dataset.new === 'goal') openNewGoal();
539
1080
  else if (b.dataset.new === 'dash') openNewDash();
540
- else if (b.dataset.new === 'chart') openChartEdit(null);
541
- else openReportEdit(null);
1081
+ else { const D = curDash(), first = goalsShown().find((g) => g.key) || M.goals[0]; openChartEdit(first ? first.id : null, D); }
542
1082
  });
543
1083
 
544
- /* ── the help popover: what lives on Insights, and the goal types (AgInsConcepts, AgInsTypes) ─────────────────────────────────────────── */
545
- $('#helpPop').innerHTML = '<h2>What lives on Insights</h2><p class="note">Four things, each built from the one before. Only the first is data; the other three are ways of looking at it.</p><div class="ins-hc">'
546
- + [['Goal', 'A number PMOS reads on a schedule, with a target and a date: a KR metric. It shows as a row on Goals. Initiatives anchor to it.'], ['Chart', 'One goal drawn one way: line, bars, number or meter, with its target line. It lives on a dashboard.'], ['Dashboard', 'A saved view of Goals for one question. Always live, never sent. Pin one and it opens first.'], ['Report', 'A written update for an audience on a schedule. PMOS drafts each cycle; you review and issue it. Reports are made in Home and listed in Library.']]
547
- .map(([t, d]) => `<div><b>${t}</b><p>${d}</p></div>`).join('') + '</div>'
548
- + '<h3>Every goal has a type, a direction and a period</h3><div class="ins-ht">'
549
- + [['Percentage', 'Baseline, target, up or down is better.', 'Hit, or how many points short.'], ['Count', 'A target count.', 'Hit, or how many short.'], ['Amount', 'A unit (money, users, tickets), baseline, target.', 'Hit, or the gap.'], ['Duration', 'Baseline, target. Usually down is better.', 'Hit, or how far off.']]
550
- .map(([t, s, j]) => `<div><b>${t}</b><span>${s}</span><span>${j}</span></div>`).join('') + '</div>'
551
- + '<p class="note"><b>Period.</b> A goal has a start (its first reading) and an end (its date). On every goal, the bar under Now has a mark for how much of that time has gone, so ahead or behind is visible without reading a forecast.</p>';
552
-
553
- /* ── Library (G2): reports, then dashboards; asks and what PMOS found in your work ────────────────────────────────────────────────────── */
554
- let askTimer = 0;
555
- const dismissing = new Map();
556
- const ASKST = { running: ['Working', 'q'], ready: ['Proposal ready, not set up', 'you'], failed: ['Failed', 'red'] };
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. ─────────────────────────────────────────────────────────── */
557
1087
  function reportGroups() {
558
1088
  const R = M.reports, by = new Map();
559
1089
  for (const f of R.missing ? [] : R.rows) { if (!by.has(f.cadence)) by.set(f.cadence, []); by.get(f.cadence).push(f); }
560
- const out = [];
561
- const shown = (fs) => fs && fs.some((x) => !x.archived);
1090
+ const out = [], shown = (fs) => fs && fs.some((x) => !x.archived);
562
1091
  for (const s of R.setupsOk === false ? [] : (R.setups || [])) { const fs = by.get(s.id); by.delete(s.id); out.push(shown(fs) ? { kind: 'file', x: { id: s.id, name: s.name, setup: s, files: fs } } : { kind: 'setup', x: s }); }
563
1092
  for (const [id, fs] of by) if (shown(fs)) out.push({ kind: 'file', x: { id, name: id, setup: null, files: fs } });
564
1093
  return out;
565
1094
  }
566
- const dots = (fs) => `<span class="ins-dots" aria-hidden="true">${fs.slice(0, 8).reverse().map((x) => `<i class="${x.state === 'issued' ? 'is' : 'dr'}"></i>`).join('')}</span>`;
567
- 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} aria-haspopup="dialog"><span class="lic">${SV(DOCI)}</span><span class="nm"><b>${esc(name)}</b><small>${esc(sub)}</small></span><span class="note">${esc(when)}</span><span>${st}</span><span class="ins-from">${from}</span><span class="ins-act">${act}</span></button></div>`;
568
- function repRow(g) {
569
- const live = g.files.filter((x) => !x.archived), L = live[0], n = (f) => live.filter(f).length, d = n((x) => x.state !== 'issued'), i = n((x) => x.state === 'issued'), s = g.setup;
570
- const st = `${dots(live)}<small class="note">${[d ? d + ' draft' : '', i ? i + ' issued' : ''].filter(Boolean).join(' · ')}${s && !s.paused && s.next ? ' · next ' + esc(s.next) : s && s.paused ? ' · paused' : ''}</small>`;
571
- return lrow(`data-rpt="${esc(g.id)}"`, g.name, [L.lead ? '“' + L.lead + '”' : 'Latest: ' + (L.date || L.slot), s && s.audience ? s.audience : '', s && s.output ? s.output : ''].filter(Boolean).join(' · '),
572
- s && s.label ? s.label : 'No template', st, s && s.source ? `<span class="cz-pill q">${esc(s.source === 'work' ? 'Your work' : s.source)}</span>` : '', d ? '<span class="cz-pill you">Review draft</span>' : '');
573
- }
574
- const setupRow = (s) => { const L = s.latest; return lrow(`data-setup="${esc(s.id)}"`, s.name, [L && L.lead ? '“' + L.lead + '”' : L ? 'From the ' + L.date + ' file' : 'No draft is written yet', s.audience ? 'for ' + s.audience : ''].filter(Boolean).join(' · '), s.label || '',
575
- `<small class="note">${s.paused ? 'Paused' : s.drafting ? 'Drafting' : s.next ? 'First draft ' + esc(s.next) : 'Set up'}</small>`, s.source ? `<span class="cz-pill q">${esc(s.source === 'work' ? 'Your work' : s.source)}</span>` : '', '<span class="cz-pill q">Set up</span>'); };
576
- const askRow = (a) => lrow(`data-ask="${esc(a.id)}"`, a.proposal && a.proposal.name ? a.proposal.name : a.text, 'You asked: ' + a.text, a.changed ? 'Changed once' : '', `<small class="note">${esc(ASKST[a.state][0])}</small>`, '', a.state === 'ready' ? '<span class="cz-pill you">Review proposal</span>' : '');
577
- const foundRow = (f) => lrow(`data-found="${esc(f.id)}"`, f.name, f.why, f.confidence || '', `<small class="note">${f.evidence.length} ${f.evidence.length === 1 ? 'sign' : 'signs'} in your work</small>`, '', '<span class="cz-pill q">Review</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]]);
578
1115
  function miniHtml(c) {
579
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];
580
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>`;
@@ -582,196 +1119,180 @@ function miniHtml(c) {
582
1119
  function dashCard(D) {
583
1120
  const L = D.keys.map(byKey).filter(Boolean), on = M.pinned === D.id;
584
1121
  const pill = !L.length ? '<span class="cz-pill q">No chart</span>' : D.off ? `<span class="cz-pill late">${D.off} behind</span>` : '<span class="cz-pill ok">On course</span>';
585
- const sub = D.id === 'all' ? 'Every goal · PMOS keeps it' : D.saved ? (D.purpose || D.charts.length + ' goals') : 'The goals of one objective';
586
- return `<div class="ins-dcard" role="listitem"><button type="button" class="ins-dopen" data-d="${esc(D.id)}" aria-label="Open ${esc(D.id === 'all' ? 'All goals' : D.name)} on Goals"><span class="ins-dh"><b>${esc(D.id === 'all' ? 'All goals' : D.name)}</b>${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>`
587
- + (pinnable(D) ? `<button type="button" class="cz-ib ins-pin${on ? ' on' : ''}" data-pin="${esc(D.id)}" aria-pressed="${on}" aria-label="${on ? 'Unpin' : 'Pin'} ${esc(D.name)}" title="${on ? 'Unpin' : 'Pin, so it opens first'}">${SV(PINI)}</button>` : '') + '</div>';
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';
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>`;
588
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
589
1127
  function drawList() {
590
- const R = M.reports, found = (R.found || []).filter((f) => !dismissing.has(f.id) && hit(f.name, f.why)), asks = (R.asks || []).filter((a) => hit(a.text));
591
- const reps = reportGroups().filter((g) => hit(g.x.name)), dashes = M.dashboards.filter((d) => hit(d.name));
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));
1129
+ const reps = reportGroups().filter((g) => hit(g.x.name)), dashes = M.dashboards.filter((d) => hit(dashName(d)));
592
1130
  const nRep = reps.length + asks.length;
593
1131
  $('#repCap').textContent = String(nRep + dashes.length);
594
- const F3 = [['all', 'All', nRep + dashes.length], ['rep', 'Reports', nRep], ['dash', 'Dashboards', dashes.length]];
595
- $('#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('');
596
- $('#listF').textContent = F3.find((f) => f[0] === listF)[1];
597
- $('#sugB').hidden = !found.length;
598
- $('#sugB').innerHTML = SV('M12 3l1.8 4.7L18.5 9.5l-4.7 1.8L12 16l-1.8-4.7L5.5 9.5l4.7-1.8z') + found.length + (found.length === 1 ? ' suggestion' : ' suggestions') + ' from your work';
599
- $('#sugB').setAttribute('aria-expanded', String(sugOpen));
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>' : '';
600
1135
  const empty = R.missing ? '<div class="ins-empty"><b>The report files could not be read</b>, so none is listed.</div>'
601
- : R.setupsOk === false ? '<div class="ins-empty"><b>The report setups could not be read</b>, so what PMOS found and what you set up are not listed.</div>' : '';
602
- 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>';
603
- const repRows = reps.map((g) => g.kind === 'setup' ? setupRow(g.x) : repRow(g.x)).join('') + asks.map(askRow).join('');
604
- const sug = found.length && sugOpen ? `<div class="ins-sec"><h3>Found in your work</h3><span class="q">${found.length}</span></div><div class="ins-tbl" id="repFound" role="list">${found.map(foundRow).join('')}</div>` : '<span id="repFound" hidden></span>';
605
- const repBlock = listF === 'dash' ? '' : `<div class="ins-sec"><h3>Reports</h3><span class="q">${nRep} · by next due</span></div>` + empty
606
- + (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: press New, then New report.</div>' : '') + sug;
607
- 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>`;
608
- $('#repBody').innerHTML = `<div id="listRows" aria-label="Dashboards and reports">${repBlock}${dashBlock}</div>`;
609
- $('#listPager').innerHTML = '';
610
- clearTimeout(askTimer);
611
- if ((R.asks || []).some((a) => a.state === 'running')) askTimer = setTimeout(load, 5000);
612
- }
613
- $('#listSeg').addEventListener('click', (e) => { const b = e.target.closest('[data-f]'); if (!b || b.dataset.f === listF) return; listF = b.dataset.f; drawList(); });
614
- $('#listF').addEventListener('click', () => { /* the chips are always shown; kept for the pages that press it */ });
615
- $('#sugB').addEventListener('click', () => { sugOpen = !sugOpen; drawList(); });
616
- $('#listMenu').addEventListener('click', (e) => { const b = e.target.closest('button'); if (!b) return; closeMenus(); if (b.id === 'lmDash') openNewDash(); else if (b.id === 'lmRep') openReportEdit(null); });
617
- $('#repBody').addEventListener('click', (e) => {
618
- const pin = e.target.closest('[data-pin]');
619
- if (pin) { pin.disabled = true; pinDash(M.pinned === pin.dataset.pin ? null : pin.dataset.pin); return; }
620
- const d = e.target.closest('[data-d]');
621
- if (d) { setView(d.dataset.d); try { $('#cDash').scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch { /* no scroll */ } return; }
622
- const rp = e.target.closest('[data-rpt]');
623
- 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; }
624
- const f = e.target.closest('[data-found]'), a = e.target.closest('[data-ask]'), s = e.target.closest('[data-setup]');
625
- if (f) openFound((M.reports.found || []).find((x) => x.id === f.dataset.found));
626
- else if (a) openAsk((M.reports.asks || []).find((x) => x.id === a.dataset.ask));
627
- else if (s) openSetup((M.reports.setups || []).find((x) => x.id === s.dataset.setup));
628
- });
629
- $('#repAsk').addEventListener('submit', async (e) => {
630
- e.preventDefault();
631
- const inp = $('#repAskIn'), text = inp.value.trim(), go = $('#repAskGo');
632
- if (!text) { toast('Say what the report is for, then press Ask.'); inp.focus(); return; }
633
- go.disabled = true;
634
- const res = await repPost('ask', { text });
635
- go.disabled = false;
636
- if (!res || res.ok !== true) { toast((res && res.error) || 'The request could not start.'); return; }
637
- inp.value = ''; toast('Asked. A background run is working on a proposal. Nothing is set up yet.'); await load();
638
- });
639
-
640
- /* ── the report dialogs: each press is one existing /api/report-setups/* route (briefing-premium-reports R2 to R4) ─────────────────────── */
641
- const repPost = (sub, body) => pmPost('/api/report-setups/' + sub, Object.assign({ ws: M.board.ws }, body));
642
- function repDlg(o) {
643
- openDlg({ eye: o.eye + ' · real data', title: o.title, sub: o.sub || M.board.name, say: o.say, stream: turnA(ptx(o.say)), noteKey: popKey('report', M.board.ws, o.title), facts: o.facts, label: 'Report',
644
- pane: `<article class="paper doc">${o.html}<p class="note" id="rxM" role="status" style="margin:12px 0 0;min-height:1.2em"></p><div class="cact">${o.acts.map(([id, t, alt]) => `<button class="cta${alt ? ' alt' : ''}" data-rx="${id}">${esc(t)}</button>`).join('')}</div></article>` });
645
- $('#oMain').onchange = null;
646
- $('#oMain').onclick = async (e) => {
647
- const b = e.target.closest('[data-rx]'); if (!b) return;
648
- const m = $('#rxM'), fn = o.on[b.dataset.rx]; if (!fn) return;
649
- $$('#oMain [data-rx]').forEach((x) => { x.disabled = true; });
650
- const after = await fn(m, b);
651
- if (after === 'keep') { $$('#oMain [data-rx]').forEach((x) => { x.disabled = false; }); return; }
652
- if (after === 'keep-off') return;
653
- closeDlg(); await load();
654
- };
655
- }
656
- const pressFailed = (res, plain) => {
657
- const e = res && res.error ? String(res.error) : plain;
658
- if (res && res.reason) return e + ' This window is out of date. Close it; the list has been read again.';
659
- return e + ' Nothing was recorded. Press the button to try again.';
660
- };
661
- const press = (sub, body, said) => async (m) => {
662
- m.textContent = 'Recording.';
663
- const res = await repPost(sub, body);
664
- if (!res || res.ok !== true) { m.textContent = pressFailed(res, 'That did not go through.'); if (res && res.reason) load(); return 'keep'; }
665
- toast(typeof said === 'function' ? said(res) : said); return null;
666
- };
667
- const setupSaid = (res) => { const d = res.drafted || {}; return 'Set up. ' + (d.path ? 'The first draft is ' + d.path + '.' : 'The first draft was not written' + (d.error ? ': ' + d.error : '') + '. Draft it now on the report tries again.'); };
668
- const propHtml = (p) => p && p.rows.length ? kv(p.rows) : '<p class="note" style="margin:0">The proposal holds no fields yet.</p>';
669
- function openFound(f) {
670
- if (!f) return;
671
- repDlg({ eye: 'Found in your work', title: f.name, say: f.why + ' Set it up, or say it is not a report.',
672
- html: `<p class="lede" style="margin:0 0 12px">${esc(f.why)}</p>${propHtml(f.proposal)}<h3 class="h2">What PMOS saw · ${f.evidence.length}</h3><ul class="pdev">${f.evidence.map((x) => `<li>${esc(x.text)}${x.kind ? ` <small>${esc(x.kind)}</small>` : ''}</li>`).join('')}</ul><p class="note">Set it up records the report in the report ledger and drafts its first cycle as a file. Not a report hides it; you can undo for 5 seconds.</p>`,
673
- acts: [['set', 'Set it up'], ['no', 'Not a report', 1]],
674
- on: {
675
- set: press('setup', { finding: f.id, name: f.name }, setupSaid),
676
- no: (m) => {
677
- const t = setTimeout(async () => { dismissing.delete(f.id); const res = await repPost('dismiss', { finding: f.id, name: f.name }); if (!res || res.ok !== true) toast(pressFailed(res, 'Not a report did not go through.')); await load(); }, 5000);
678
- dismissing.set(f.id, t); drawList();
679
- m.innerHTML = 'Hidden. It is recorded as not a report in 5 seconds. <button class="lk" id="rxUndo">Undo</button>';
680
- $('#rxUndo').onclick = () => { clearTimeout(dismissing.get(f.id)); dismissing.delete(f.id); drawList(); m.textContent = 'Undone. Nothing was recorded.'; $$('#oMain [data-rx]').forEach((x) => { x.disabled = false; }); };
681
- return 'keep-off';
682
- },
683
- } });
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>' : '';
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>`;
684
1141
  }
685
- function openAsk(a) {
686
- if (!a) return;
687
- if (a.state === 'running') {
688
- repDlg({ eye: 'Your request', title: a.text, say: 'A background run is working on a proposal. It proposes only; nothing is set up until you press Set it up.', html: '<p class="lede" style="margin:0">A background run is working on this request. This page checks again every 5 seconds.</p>', acts: [['cancel', 'Cancel the request', 1]], on: { cancel: press('cancel', { id: a.id }, 'Request cancelled.') } });
1142
+ $('#repBody').addEventListener('click', async (e) => {
1143
+ const d = e.target.closest('[data-d]'); if (d) { setView(d.dataset.d); 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 + '.' : ''));
689
1155
  return;
690
1156
  }
691
- if (a.state === 'failed') {
692
- repDlg({ eye: 'Your request', title: a.text, say: 'The run ended without a proposal.', html: `<p class="lede" style="margin:0">${esc(a.error || 'The run ended without a proposal.')}</p>`, acts: [['cancel', 'Remove the request', 1]], on: { cancel: press('cancel', { id: a.id }, 'Request removed.') } });
693
- return;
694
- }
695
- repDlg({ eye: 'Your request', title: (a.proposal && a.proposal.name) || a.text, say: 'Here is the proposal. Set it up, ask for a change, or cancel.',
696
- html: `<p class="note" style="margin:0 0 10px">You asked: ${esc(a.text)}</p>${propHtml(a.proposal)}<div class="addf" style="margin-top:14px"><label>A change to ask for<input id="rxChg" maxlength="500" placeholder="For example: monthly, not weekly"></label></div><p class="note">Change it starts the run again with your words. Set it up records the report and drafts its first cycle as a file.</p>`,
697
- acts: [['set', 'Set it up'], ['chg', 'Change it', 1], ['cancel', 'Cancel', 1]],
698
- on: {
699
- set: press('setup', { ask: a.id }, setupSaid),
700
- chg: (m) => { const t = $('#rxChg').value.trim(); if (!t) { m.textContent = 'Say what to change.'; $('#rxChg').focus(); return 'keep'; } return press('change', { id: a.id, text: t }, 'Asked for the change. The run is revising the proposal.')(m); },
701
- cancel: press('cancel', { id: a.id }, 'Request cancelled.'),
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; }
1159
+ const ak = e.target.closest('[data-ask]'); if (ak) openRequest(ak.dataset.ask);
1160
+ });
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
+ }
1172
+ const kvHtml = (rows) => `<dl class="ins-kv">${rows.filter(Boolean).map(([a, b]) => `<dt>${esc(a)}</dt><dd>${esc(b)}</dd>`).join('')}</dl>`;
1173
+ async function postSetup(el, route, body, said) {
1174
+ const msg = el.querySelector('[data-msg]'); if (msg) msg.textContent = 'Sending.';
1175
+ const res = await pmPost('/api/report-setups/' + route, Object.assign({ ws: M.board.ws }, body));
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; }
1177
+ toast(typeof said === 'function' ? said(res) : said); await load(); return true;
1178
+ }
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
+ });
702
1214
  } });
703
1215
  }
704
- function openSetup(s) {
705
- if (!s) return;
706
- const rows = [['Schedule', s.label], ['Status', s.paused ? 'Paused' : 'Active'], ['Next draft', s.paused ? '' : s.next], ['Last issued cycle', s.lastIssued], ['Audience', s.audience], ['Output', s.output], ['Documents', String(s.cycles)], ['Purpose', s.purpose]];
707
- const acts = [s.paused ? ['resume', 'Resume'] : ['pause', 'Pause', 1]];
708
- if (s.fromWork && !s.paused) acts.unshift(['draft', 'Draft it now']);
709
- if (s.fromWork) acts.push(['studio', 'Shape it in a chat', 1]);
710
- repDlg({ eye: 'Set-up report', title: s.name, facts: rows, say: s.paused ? 'This report is paused. Resume it to draft it on its schedule again.' : 'This report is drafted on its schedule. You can draft the next cycle now or pause it.',
711
- html: kv(rows) + `<p class="note">${s.fromWork ? (s.structured ? 'Draft it now starts a background run that follows the saved structure.' : 'Draft it now writes the next cycle as a file at once.') : 'This report is drafted from its dashboard on its day.'} Pause and Resume record a line in the report ledger. Nothing is sent.</p>`,
712
- acts, on: {
713
- draft: press('draft', { id: s.id }, (res) => res.drafting ? 'Drafting started. The draft follows the saved structure.' : 'Drafted: ' + ((res.drafted && res.drafted.path) || 'the next cycle') + '.'),
714
- pause: press('pause', { id: s.id }, 'Paused. It is not drafted until you resume it.'),
715
- resume: press('resume', { id: s.id }, 'Resumed. It is drafted on its schedule again.'),
716
- studio: () => { openReportEdit(s); return 'keep-off'; },
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
+ });
1248
+ } });
1249
+ }
1250
+ /* a request from Home (IsLibrary): what was asked, the proposal, and Set it up, Change it or Cancel */
1251
+ function openRequest(id) {
1252
+ const a = (M.reports.asks || []).find((x) => x.id === id); if (!a) return;
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
+ });
717
1275
  } });
718
1276
  }
719
1277
 
720
- /* ── the goal's dialog: its record and readings, the read-only agent beside it, and the switches that put it on a dashboard ─────────────── */
721
- function cardHtml(c) { return `<div class="acard" id="card"><p class="ct">What this page can do</p><p class="nodef" id="holdWhy">${esc(c.dialog.hold)} The switches under On your dashboards save a dashboard and change no record.</p></div>`; }
722
- function paneHtml(c) {
723
- const p = c.dialog.pane;
724
- return `<article class="paper doc"><p class="dpath">${esc(p.file)}</p><h3 class="d1">${esc(c.title)}</h3><p>${esc(c.dialog.say)}</p><div class="ntw pdchart">${tileHtml(c)}</div><div class="kv2">${c.dialog.facts.map(([a, b]) => `<span>${esc(a)}</span><span>${esc(b)}</span>`).join('')}</div><h3 class="h2">All ${c.pts.length} readings</h3><div class="kv2">${p.rows.map(([a, b]) => `<span>${esc(a)}</span><span>${esc(b)}</span>`).join('')}</div>${onDashHtml(c)}<p class="xn">Read from the KR metric record. The line status is the record's own: the straight line from its baseline to its target. Where this page says where a goal lands by its date, that is a straight line through its last four readings, carried to that date.</p></article>`;
725
- }
726
- function onDashHtml(c) {
727
- if (!M.board.id) return '';
728
- const L = savedDash();
729
- return `<h3 class="h2">On your dashboards</h3>${L.length ? `<div class="dplist" role="group" aria-label="Add to a dashboard">${L.map((d) => { const on = d.charts.includes(c.id); return `<button role="switch" aria-checked="${on}" aria-pressed="${on}" data-pdsw="${esc(d.id)}"><span><b>${esc(d.name)}</b><small>${d.charts.length} ${d.charts.length === 1 ? 'chart' : 'charts'}</small></span><i>${on ? 'On it' : 'Add'}</i></button>`; }).join('')}</div>` : '<p class="note" style="margin:0 0 12px">No saved dashboard on this board yet. Make one with New dashboard.</p>'}<p class="note" id="pdSwM" role="status" style="min-height:1.2em"></p>`;
730
- }
731
- function openChart(c) {
732
- if (!c) return;
733
- const d = c.dialog;
734
- openDlg({ eye: d.eye + ' · real data', title: c.title, sub: c.sub + ' · ' + c.chip, say: d.say, stream: turnA(logHtml(d)) + turnA(ptx(d.say)) + cardHtml(c), noteKey: c.key, pane: paneHtml(c), label: 'KR metric record' });
735
- $('#oMain').onchange = null;
736
- $('#oMain').onclick = async (e) => {
737
- const b = e.target.closest('[data-pdsw]'); if (!b || b.disabled) return;
738
- const D = savedDash().find((x) => x.id === b.dataset.pdsw); if (!D) return;
739
- const on = D.charts.includes(c.id), charts = on ? D.charts.filter((x) => x !== c.id) : D.charts.concat(c.id);
740
- b.disabled = true; $('#pdSwM').textContent = 'Saving.';
741
- const res = await saveDash({ id: D.id, name: D.name, purpose: D.purpose, charts, main: D.main });
742
- b.disabled = false;
743
- if (!res || res.ok !== true) { $('#pdSwM').textContent = (res && res.error) || 'The dashboard could not be saved.'; return; }
744
- D.charts = charts; b.setAttribute('aria-checked', !on); b.setAttribute('aria-pressed', !on); $('i', b).textContent = on ? 'Add' : 'On it'; $('small', b).textContent = charts.length + ' ' + (charts.length === 1 ? 'chart' : 'charts');
745
- $('#pdSwM').textContent = on ? 'Taken off ' + D.name + '.' : 'Added to ' + D.name + '.';
746
- load();
747
- };
748
- loadThread(c.key);
749
- setTimeout(() => { const b = $('#dBody'); b.scrollTop = b.scrollHeight; }, 120);
750
- }
751
- $('#dBody').addEventListener('click', (e) => { const lt = e.target.closest('#logT'); if (lt) { const c = $('#alog').classList.toggle('col'); lt.setAttribute('aria-expanded', !c); } });
752
-
753
- /* ── load ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── */
754
- function drawDock() { $('#dN').textContent = M.dock.needs; $('#dLab').textContent = M.dock.label; $('#dNext').textContent = M.dock.next ? 'First ' + M.dock.next : 'No goal is behind its line'; }
755
- function redraw() { if (!M) return; drawBar(); drawStrip(); drawGoals(); drawDash(); drawOutcomes(); drawList(); }
1278
+ /* ── load ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── */
1279
+ function redraw() { if (!M) return; drawBar(); drawStrip(); drawGoals(); drawOutcomes(); drawList(); }
756
1280
  function draw() {
757
1281
  if (!dash || !M.dashboards.some((d) => d.id === dash)) dash = M.pinned || 'all';
758
- $('#snap').textContent = M.header.text;
759
- $('#snap').title = 'Every figure on this page comes from a KR metric record. A goal with fewer than two readings is listed, not drawn.';
760
1282
  setPageGaps(((M.header && M.header.missing) || []).length);
761
- redraw(); drawDock();
1283
+ redraw();
762
1284
  }
763
1285
  async function load() {
764
1286
  const p = new URLSearchParams(location.search), q = [p.get('ws') ? 'ws=' + encodeURIComponent(p.get('ws')) : '', p.get('board') ? 'board=' + encodeURIComponent(p.get('board')) : ''].filter(Boolean).join('&');
765
1287
  let r = null, status = 0;
766
1288
  try { const res = await fetch('/api/insights-premium' + (q ? '?' + q : ''), { credentials: 'same-origin' }); status = res.status; r = await res.json(); } catch { r = null; }
767
1289
  if (!r || !r.ok) {
768
- $('#snap').textContent = 'The records could not be read';
769
1290
  $('#insEye').textContent = ''; $('#insWhy').textContent = ''; $('#askWhy').hidden = true;
770
1291
  $('#brief').textContent = 'The KR metric records could not be read, so this page shows nothing rather than guess.' + (r && r.error ? ' The reason: ' + r.error : status ? ' (the server answered ' + status + ')' : ' The server did not answer.');
771
1292
  setTimeout(load, 15000);
772
1293
  return;
773
1294
  }
774
- M = r.model; draw(); bmLoad();
1295
+ const first = !M; M = r.model; loadedAt = Date.now(); draw(); if (first || !BM) bmLoad();
775
1296
  }
776
- { const t = new URLSearchParams(location.search).get('tab'); if (t === 'outcomes' || t === 'library') setTab(t); else setTab('goals'); }
1297
+ { const t = new URLSearchParams(location.search).get('tab'); setTab(t === 'outcomes' || t === 'library' ? t : 'goals'); }
777
1298
  load();