create-pmos 0.388.0 → 0.389.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 (35) hide show
  1. package/package.json +13 -13
  2. package/payload/KIT-VERSION +1 -1
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/workspace/briefing-premium-insights-test.js +16 -21
  7. package/workspace/changelog.json +12 -0
  8. package/workspace/guide/briefing-premium.md +19 -9
  9. package/workspace/lib/briefing-premium-agent.js +3 -0
  10. package/workspace/lib/report-chat.js +37 -0
  11. package/workspace/package-lock.json +2 -2
  12. package/workspace/package.json +1 -1
  13. package/workspace/premium-chat-chart-tab-test.js +150 -0
  14. package/workspace/premium-chat-report-tab-test.js +127 -0
  15. package/workspace/public/pm/goal-chat.js +2 -1
  16. package/workspace/public/pm/premium-chart-draw.js +58 -0
  17. package/workspace/public/pm/premium-chart-tab.js +157 -0
  18. package/workspace/public/pm/premium-chat.js +8 -2
  19. package/workspace/public/pm/premium-insights.js +17 -79
  20. package/workspace/public/pm/premium-report-tab.js +233 -0
  21. package/workspace/public/pm/premium-shell.js +35 -3
  22. package/workspace/public/pm/premium-vw-report.css +60 -0
  23. package/workspace/public/pm/premium.css +1 -120
  24. package/workspace/public/pm/report-chat.js +89 -0
  25. package/workspace/test-lists/premium-chat-chart-tab.json +12 -0
  26. package/workspace/test-lists/premium-chat-report-tab.json +12 -0
  27. package/workspace/premium-studio-chart-test.js +0 -193
  28. package/workspace/premium-studio-report-test.js +0 -277
  29. package/workspace/premium-studio-test.js +0 -185
  30. package/workspace/public/pm/premium-studio-design.js +0 -298
  31. package/workspace/public/pm/premium-studio-report.js +0 -291
  32. package/workspace/public/pm/premium-studio.js +0 -453
  33. package/workspace/test-lists/premium-studio-chart.json +0 -13
  34. package/workspace/test-lists/premium-studio-report.json +0 -9
  35. package/workspace/test-lists/premium-studio.json +0 -9
@@ -0,0 +1,127 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* premium-chat-report-tab-test.js — reports from any chat (initiative premium-reports-from-chat, slice B; PRD R1–R4).
4
+ * A real server on a scratch repository (c3-scan-fixture.js). The thread and the session's conversation are routed, so Claude's answers are set
5
+ * here; every report press goes to the real report-setups and report-documents routes.
6
+ * R1 at 1280 a pmos-report block is a chip under Claude's words, never JSON; opening the chat opens no tab; the chip opens the Report tab
7
+ * R2 a new answer with a block opens the Report tab by itself
8
+ * R3 a new report shows its name, audience, format, the seven sections and Schedule Off · runs once; a pick changes the chip only
9
+ * R4 Set it up with Schedule Off records the report, writes its first draft and pauses it: the tab turns into the template, schedule Off
10
+ * R5 the Schedule chip on a template changes the schedule through the route
11
+ * R6 a draft is discarded after a confirm; the template is deleted after a confirm, and the tab says its reports stay
12
+ * R7 at 390 the chip covers the page with the Report tab; no sideways scroll; no page error
13
+ * Set REPORT_TAB_SHOTS=<dir> to save the page at 1280 and 390, light and dark. */
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+ const { findBrowser } = require('./lib/find-browser');
17
+ require('./test-run').configure({ name: 'premium-chat-report-tab' });
18
+ const Fx = require('./c3-scan-fixture.js');
19
+ const RS = require('./lib/report-setups.js');
20
+
21
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
22
+ const until = async (fn, ms = 10000, step = 120) => { const t0 = Date.now(); for (;;) { let v; try { v = await fn(); } catch { v = null; } if (v) return v; if (Date.now() - t0 > ms) return v; await sleep(step); } };
23
+ const results = [];
24
+ const ok = (name, cond, extra = '') => { results.push({ name, cond: !!cond }); console.log(`${cond ? '✓' : '✗'} ${name}${!cond && extra !== '' ? ' — ' + String(extra).slice(0, 600) : ''}`); };
25
+ let F = null, browser = null;
26
+ const finish = async (code) => {
27
+ if (browser) await browser.close().catch(() => {});
28
+ if (F) F.stop();
29
+ const bad = results.filter((x) => !x.cond).length;
30
+ console.log(`\n${results.length - bad}/${results.length} premium-chat-report-tab assertions passed`);
31
+ process.exit(code !== undefined ? code : (bad ? 1 : 0));
32
+ };
33
+ process.on('unhandledRejection', (e) => { console.error(e); finish(1); });
34
+
35
+ const block = (o) => '```pmos-report\n' + JSON.stringify(o) + '\n```';
36
+ const PROP = { kind: 'report', proposal: { name: 'Social login weekly', purpose: 'Are lightbox signups growing on the site and the app?', audience: 'Growth leads', output: 'google-slides', schedule: null, sources: ['GA4', 'This chat'] } };
37
+ const ASK = { role: 'user', text: '[PMOS report] rule\n\nThe PM says: make this a report for the growth leads' };
38
+ const ANSWER = { role: 'assistant', text: 'Signups from the lightbox rose to 1,240. I drafted a report from this chat.\n\n' + block(PROP) };
39
+
40
+ const look = () => {
41
+ const g = document.querySelector('#dlg'), pane = [...document.querySelectorAll('#dOut .obody.vw[data-vw^="report:"]')].find((x) => !x.hidden) || null;
42
+ return { shut: g.classList.contains('vw-shut'), layer: g.classList.contains('vw-layer'), chip: (document.querySelector('#dBody [data-report-open]') || {}).textContent || null,
43
+ json: /pmos-report|"kind"/.test((document.querySelector('#dBody .stream') || {}).textContent || ''), user: [...document.querySelectorAll('#dBody .turn.u')].map((u) => u.textContent.trim()),
44
+ tabs: [...document.querySelectorAll('#vTabs .vtab')].map((t) => t.textContent.trim()), pane: pane ? pane.textContent.replace(/\s+/g, ' ').trim() : null,
45
+ secs: pane ? pane.querySelectorAll('.rt-secs li').length : 0, sched: pane && pane.querySelector('.rt-chip b') ? pane.querySelector('.rt-chip b').textContent : null,
46
+ wide: document.documentElement.scrollWidth > innerWidth + 1 };
47
+ };
48
+
49
+ (async () => {
50
+ const exe = findBrowser();
51
+ if (!exe) { console.log('✗ no Chrome/Chromium on this machine — the suite cannot run'); return finish(1); }
52
+ let chromium;
53
+ try { ({ chromium } = require('playwright-core')); } catch { console.log('✗ playwright-core is not installed'); return finish(1); }
54
+ F = await Fx.start({ name: 'premium-chat-report-tab' });
55
+ browser = await chromium.launch({ executablePath: exe, headless: true, args: ['--no-sandbox'] });
56
+ const shots = process.env.REPORT_TAB_SHOTS;
57
+ const chat = `${F.BASE}/premium-chat.html?ws=${encodeURIComponent(F.ws)}`;
58
+ const ledger = () => RS.readLines(RS.ledgerFile(F.team));
59
+ const open = async (width, scheme, messages) => {
60
+ const st = { messages };
61
+ const ctx = await browser.newContext({ viewport: { width, height: width < 1000 ? 844 : 860 }, colorScheme: scheme, hasTouch: width < 1000 });
62
+ const p = await ctx.newPage(); const errs = []; p.on('pageerror', (e) => errs.push(String(e)));
63
+ await p.route('**/api/briefing-premium/thread?**', (r) => r.fulfill({ json: { ok: true, turns: [], session: 's-rep', goal: null } }));
64
+ await p.route('**/api/sessions/conversation?**', (r) => r.fulfill({ json: { ok: true, state: 'conv', turn: 'pm', messages: st.messages } }));
65
+ await p.goto(chat);
66
+ await until(() => p.evaluate(() => document.querySelector('#dlg').classList.contains('on') && !!document.querySelector('#dBody .stream #thr')));
67
+ await sleep(500);
68
+ return { p, ctx, errs, st };
69
+ };
70
+
71
+ { const { p, ctx, errs, st } = await open(1280, 'light', [ASK, ANSWER]);
72
+ const s0 = await p.evaluate(look);
73
+ ok('R1 the block is a chip under Claude\'s words, never JSON; the PM\'s turn shows as typed', /Social login weekly/.test(s0.chip || '') && /New report/.test(s0.chip || '') && !s0.json && s0.user.includes('make this a report for the growth leads'), JSON.stringify(s0));
74
+ ok('R1 opening the chat opens no tab by itself', s0.tabs.length === 0, JSON.stringify(s0));
75
+ await p.click('#dBody [data-report-open]');
76
+ const s1 = await until(async () => { const v = await p.evaluate(look); return v.pane ? v : null; }) || await p.evaluate(look);
77
+ ok('R3 the Report tab shows the new report: name, audience, format, seven sections, Schedule Off', /Report/.test(s1.tabs.join(' ')) && /Social login weekly/.test(s1.pane || '') && /For Growth leads · Google Slides/.test(s1.pane || '')
78
+ && s1.secs === 7 && s1.sched === 'Off · runs once' && /Set it up/.test(s1.pane || ''), JSON.stringify(s1));
79
+ if (shots) await p.screenshot({ path: `${shots}/new-1280-light.png` });
80
+ await p.click('#dOut .rt-chip');
81
+ await p.click('#dOut .rt-menu [data-rt="pick|2"]');
82
+ const s2 = await until(async () => { const v = await p.evaluate(look); return v.sched && /Weekly/.test(v.sched) ? v : null; }) || await p.evaluate(look);
83
+ ok('R3 a pick changes the chip only: nothing is written', /Weekly, Mondays at 09:00/.test(s2.sched || '') && !ledger().some((l) => l.ev === 'setup'), JSON.stringify(s2));
84
+ await p.click('#dOut .rt-chip'); await p.click('#dOut .rt-menu [data-rt="pick|0"]');
85
+ await p.click('#dOut [data-rt="setup"]');
86
+ const s3 = await until(async () => { const v = await p.evaluate(look); return v.pane && /Report template/.test(v.pane) ? v : null; }, 15000) || await p.evaluate(look);
87
+ const L = ledger(), setup = L.find((l) => l.ev === 'setup');
88
+ ok('R4 Set it up records the report and pauses it (Schedule Off: it runs once); the tab shows the template', !!setup && L.some((l) => l.ev === 'pause' && l.id === setup.id) && s3.sched === 'Off · runs once' && /Report template/.test(s3.pane || ''), JSON.stringify([s3, L.map((l) => l.ev)]));
89
+ ok('R4 its first draft is written and listed as a draft with Discard', /Draft/.test(s3.pane || '') && /Discard/.test(s3.pane || ''), JSON.stringify(s3));
90
+ if (shots) await p.screenshot({ path: `${shots}/template-1280-light.png` });
91
+ await p.click('#dOut .rt-chip'); await p.click('#dOut .rt-menu [data-rt="pick|3"]');
92
+ const s4 = await until(async () => { const v = await p.evaluate(look); return v.sched && /Every two weeks/.test(v.sched) ? v : null; }) || await p.evaluate(look);
93
+ const changed = RS.fold(ledger()).setups.get(setup && setup.id);
94
+ ok('R5 the Schedule chip changes a template through the route and resumes it', !!changed && changed.status === 'active' && changed.schedule.cadence === 'bi-weekly' && /Every two weeks/.test(s4.sched || ''), JSON.stringify([s4.sched, changed]));
95
+ await p.click('#dOut [data-rt^="discard|"]');
96
+ await p.click('#dOut .vcf [data-a="1"]');
97
+ const s5 = await until(async () => { const v = await p.evaluate(look); return v.pane && /The draft is discarded/.test(v.pane) ? v : null; }) || await p.evaluate(look);
98
+ ok('R6 Discard asks once, then the draft is deleted and logged', /The draft is discarded/.test(s5.pane || '') && ledger().some((l) => l.ev === 'doc-discard'), (s5.pane || '').slice(-300));
99
+ await p.click('#dOut [data-rt="remove"]');
100
+ await p.click('#dOut .vcf [data-a="1"]');
101
+ const s6 = await until(async () => { const v = await p.evaluate(look); return v.pane && /Template deleted/.test(v.pane) ? v : null; }) || await p.evaluate(look);
102
+ ok('R6 Delete template asks once, then the template is gone and the tab says its reports stay', /Template deleted/.test(s6.pane || '') && ledger().some((l) => l.ev === 'remove'), JSON.stringify(s6));
103
+ st.messages = [ASK, ANSWER, { role: 'user', text: '[PMOS report] rule\n\nThe PM says: one for the board too' }, { role: 'assistant', text: 'Here.\n\n' + block({ kind: 'report', proposal: { ...PROP.proposal, name: 'Board summary' } }) }];
104
+ const s7 = await until(async () => { const v = await p.evaluate(look); return v.pane && /Board summary/.test(v.pane) ? v : null; }) || await p.evaluate(look);
105
+ ok('R2 a new answer with a block opens the Report tab by itself', /Board summary/.test(s7.pane || ''), JSON.stringify(s7));
106
+ ok('F1 no page error and no sideways scroll', !errs.length && !s7.wide, errs.join(' | '));
107
+ await ctx.close(); }
108
+
109
+ for (const scheme of ['light', 'dark']) {
110
+ const { p, ctx, errs } = await open(390, scheme, [ASK, ANSWER]);
111
+ if (shots) await p.screenshot({ path: `${shots}/chip-390-${scheme}.png` });
112
+ await p.click('#dBody [data-report-open]');
113
+ const s1 = await until(async () => { const v = await p.evaluate(look); return v.layer && v.pane ? v : null; }) || await p.evaluate(look);
114
+ ok(`R7 (${scheme}) at 390 the chip covers the page with the Report tab`, s1.layer && /Social login weekly/.test(s1.pane || '') && s1.secs === 7, JSON.stringify(s1));
115
+ if (shots) await p.screenshot({ path: `${shots}/new-390-${scheme}.png` });
116
+ ok(`F1 (${scheme}) no page error and no sideways scroll at 390`, !errs.length && !s1.wide, errs.join(' | '));
117
+ await ctx.close();
118
+ }
119
+ if (shots) {
120
+ const { p, ctx } = await open(1280, 'dark', [ASK, ANSWER]);
121
+ await p.click('#dBody [data-report-open]'); await sleep(500);
122
+ await p.screenshot({ path: `${shots}/new-1280-dark.png` });
123
+ await ctx.close();
124
+ }
125
+ void fs; void path;
126
+ return finish();
127
+ })();
@@ -24,7 +24,7 @@ export function splitGoal(text) {
24
24
  }
25
25
 
26
26
  const MARK = { grill: '[PMOS /goal]', start: '[PMOS /goal start]', cancel: '[PMOS /goal cancel]' };
27
- const OPENING = 'The PM is talking to you from the chat panel';
27
+ const OPENING = 'The PM is talking to you from the '; // the chat panel of an item, or the Chat page (lib/briefing-premium-agent.js openingFor)
28
28
  /** The PM's turn as the PM typed it (G7): `/goal Ship X` for the grilling prompt, a short line for Start and Cancel, and only the PM's
29
29
  * words for the opening message that carries the row's context. Anything else is shown unchanged. */
30
30
  export function shownUser(text) {
@@ -35,6 +35,7 @@ export function shownUser(text) {
35
35
  const g = t.indexOf(MARK.grill + ' The PM set a goal: ');
36
36
  if (g >= 0) return '/goal ' + t.slice(g + (MARK.grill + ' The PM set a goal: ').length).split('\n')[0];
37
37
  if (t.startsWith(OPENING)) { const i = t.lastIndexOf('\nThe PM says: '); if (i >= 0) return t.slice(i + '\nThe PM says: '.length); }
38
+ if (t.startsWith('[PMOS report]')) { const i = t.lastIndexOf('\nThe PM says: '); if (i >= 0) return t.slice(i + '\nThe PM says: '.length); } // premium-reports-from-chat: lib/report-chat.js wrap
38
39
  return t;
39
40
  }
40
41
 
@@ -0,0 +1,58 @@
1
+ /* pm/premium-chart-draw.js — a chart tile in one of four forms: line, bars, number, meter (initiative premium-studio-chart C3). The Insights page and the
2
+ * Chart tab beside a chat (initiative premium-reports-from-chat, slice C) share this drawing. A KR metric's own chart is a line; a chart the PM saved
3
+ * carries its form. Bars and a meter start at zero, so a series with a value below zero is drawn as a line and says so. Pure strings: no DOM. */
4
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
5
+ export const W = 220, H = 60, P = 5;
6
+ export const X = (fx) => P + fx * (W - 2 * P), Y = (fy) => P + (1 - fy) * (H - 2 * P);
7
+ export const unitTxt = (c, v) => { const u = c.unit || '', s = String(Math.round(v * 100) / 100); return u ? (/^[A-Za-z]/.test(u) ? s + ' ' + u : s + u) : s; };
8
+ function chgHtml(c) {
9
+ return c.step === 0 ? '' : `<span class="mchg ${c.good === null ? '' : c.good ? 'good' : 'bad'}">${c.step > 0 ? '▲ ' : '▼ '}${esc(Math.abs(c.step) + (c.unit && /^[%°]/.test(c.unit) ? c.unit : c.unit ? ' ' + c.unit : ''))} since the last reading</span>`;
10
+ }
11
+ const chipOf = (c) => `<i class="mchip ${c.chipKind === 'bad' ? 'warn' : c.chipKind}">${esc(c.chip)}</i>`;
12
+ const capOf = (c) => 'on ' + c.at + (c.targetTxt ? ' · ' + c.targetTxt : '');
13
+ export function tileHtml(c) {
14
+ const f = c.form || 'line', neg = c.pts.some((p) => p.v < 0) || (c.target !== null && c.target < 0);
15
+ const h = f === 'number' ? numTile(c) : f === 'bars' && !neg ? barsTile(c) : f === 'meter' && !neg && c.target !== null ? meterTile(c) : lineTile(c, f !== 'line' && f !== 'number' ? (neg ? 'A value is below zero, so it is drawn as a line.' : 'No target is set, so it is drawn as a line.') : '');
16
+ return h + (c.note ? `<p class="mnote">${esc(c.note)}</p>` : '');
17
+ }
18
+ function lineTile(c, why) {
19
+ const d = c.pts.map((p, i) => (i ? 'L' : 'M') + X(p.fx).toFixed(1) + ',' + Y(p.fy).toFixed(1)).join('');
20
+ const last = c.pts[c.pts.length - 1];
21
+ return `<div class="mt1 mch ${c.chipKind}${c.off ? ' off' : ''}" data-key="${esc(c.key)}" tabindex="0" role="img" aria-label="${esc(c.title)}, ${c.pts.length} readings, now ${esc(c.v)}${c.targetTxt ? ', ' + esc(c.targetTxt) : ''}. Use the arrow keys to read each reading."><span class="mlab">${esc(c.title)}${chipOf(c)}</span><b class="mval">${esc(c.v)}</b><em class="mwk">${esc(capOf(c))}</em>${chgHtml(c)}`
22
+ + `<svg viewBox="0 0 ${W} ${H}"><path class="ar" d="${d}L${X(1)},${H}L${X(0)},${H}Z"/>${c.ty !== null ? `<line class="tg" x1="${P}" x2="${W - P}" y1="${Y(c.ty)}" y2="${Y(c.ty)}"/>` : ''}<path class="ln2" d="${d}"/><line class="cx" x1="0" x2="0" y1="0" y2="${H}"/><circle class="dt" cx="${X(last.fx)}" cy="${Y(last.fy)}" r="3.5"/></svg>`
23
+ + `<span class="mfoot"><i>${esc(c.ticks[0])}</i>${c.target !== null ? '<i class="tgl">dashed line is the target</i>' : ''}<i>${esc(c.ticks[1])}</i></span>${why ? `<span class="mwhy">${esc(why)}</span>` : ''}</div>`;
24
+ }
25
+ function barsTile(c) {
26
+ const n = c.pts.length, hi = Math.max(...c.pts.map((p) => p.v), c.target !== null ? c.target : 0) || 1, pc = (v) => (v / hi * 84).toFixed(1);
27
+ const cols = c.pts.map((p, i) => `<span class="bw" title="${esc(p.d + ': ' + p.txt)}">${i === n - 1 ? `<b class="bl">${esc(p.txt)}</b>` : ''}<i class="${i === n - 1 ? 'bk' : 'bg'}" style="height:${pc(p.v)}%"></i></span>`).join('');
28
+ return `<div class="mt1 mfm bars ${c.chipKind}${c.off ? ' off' : ''}" data-key="${esc(c.key)}" role="img" aria-label="${esc(c.title)}, ${n} readings as bars from zero, now ${esc(c.v)}${c.targetTxt ? ', ' + esc(c.targetTxt) : ''}"><span class="mlab">${esc(c.title)}${chipOf(c)}</span><b class="mval">${esc(c.v)}</b><em class="mwk">${esc(capOf(c))}</em>${chgHtml(c)}`
29
+ + `<div class="bplot">${cols}${c.target !== null ? `<i class="btg" style="bottom:${pc(c.target)}%"></i>` : ''}</div>`
30
+ + `<span class="mfoot"><i>${esc(c.ticks[0])}</i><i class="tgl">${c.target !== null ? 'dashed line is the target' : 'bars start at zero'}</i><i>${esc(c.ticks[1])}</i></span></div>`;
31
+ }
32
+ function numTile(c) {
33
+ const d = c.pts.map((p, i) => (i ? 'L' : 'M') + X(p.fx).toFixed(1) + ',' + (2 + (1 - p.fy) * 26).toFixed(1)).join('');
34
+ return `<div class="mt1 mfm num ${c.chipKind}${c.off ? ' off' : ''}" data-key="${esc(c.key)}" role="img" aria-label="${esc(c.title)}, now ${esc(c.v)}${c.targetTxt ? ', ' + esc(c.targetTxt) : ''}"><span class="mlab">${esc(c.title)}${chipOf(c)}</span><b class="mval mhero">${esc(c.v)}</b><em class="mwk">${esc(capOf(c))}</em>${chgHtml(c)}`
35
+ + `<svg class="nspk" viewBox="0 0 ${W} 30" aria-hidden="true"><path d="${d}"/></svg></div>`;
36
+ }
37
+ function meterTile(c) {
38
+ const v = c.pts[c.pts.length - 1].v, tg = c.target, hi = Math.max(v, tg) * 1.15 || 1, lower = c.dir < 0, ok = lower ? v <= tg : v >= tg;
39
+ return `<div class="mt1 mfm prg ${c.chipKind}${c.off ? ' off' : ''}" data-key="${esc(c.key)}" role="img" aria-label="${esc(c.title)} is ${esc(c.v)} against ${lower ? 'a limit' : 'a target'} of ${esc(unitTxt(c, tg))}. ${ok ? 'It is on the right side of it.' : 'It is not there yet.'}"><span class="mlab">${esc(c.title)}${chipOf(c)}</span><b class="mval">${esc(c.v)}</b><em class="mwk">${esc(ok ? (lower ? 'Within the limit' : 'At or past the target') : (lower ? 'Over the limit' : 'Short of the target'))}</em>`
40
+ + `<div class="mtrk"><i class="mfil ${ok ? 'ok' : 'warn'}" style="width:${(v / hi * 100).toFixed(1)}%"></i><i class="mtgt" style="left:${(tg / hi * 100).toFixed(1)}%"></i></div>`
41
+ + `<span class="mfoot"><i>0</i><i class="tgl">${lower ? 'limit' : 'target'} ${esc(unitTxt(c, tg))}</i><i>${esc(unitTxt(c, hi))}</i></span></div>`;
42
+ }
43
+ /* A draft drawn from a measure's chart (premium-studio-chart C2, C7): the latest `range` readings, against the draft's target, as the server's
44
+ * lib/insights-premium.js mineOf draws a saved chart. Every point is a reading of the record. */
45
+ export function deriveChart(base, d) {
46
+ const all = base.pts, pts0 = d.range ? all.slice(-d.range) : all.slice();
47
+ if (pts0.length < 2) return null;
48
+ const tg = d.target === null || d.target === undefined || d.target === '' ? null : +d.target;
49
+ const day = (p) => Date.parse(String(p.at).slice(0, 10) + 'T00:00:00Z');
50
+ const t0 = day(pts0[0]), span = day(pts0[pts0.length - 1]) - t0 || 1;
51
+ const ys = pts0.map((p) => p.v).concat(tg !== null ? [tg] : []), lo = Math.min(...ys), hi = Math.max(...ys), range = hi - lo || 1;
52
+ const pts = pts0.map((p) => Object.assign({}, p, { fx: (day(p) - t0) / span, fy: (p.v - lo) / range }));
53
+ const now = pts[pts.length - 1], prev = pts[pts.length - 2], step = Math.round((now.v - prev.v) * 100) / 100, dir = d.better === 'lower' ? -1 : 1;
54
+ return Object.assign({}, base, {
55
+ key: 'draft', title: d.title || base.title, form: d.form, note: d.note || '', pts, v: now.txt, at: now.d, target: tg, targetTxt: tg !== null ? 'target ' + unitTxt(base, tg) : '',
56
+ ty: tg !== null ? (tg - lo) / range : null, step, dir, good: step ? step * dir > 0 : null, ticks: [pts[0].d, now.d],
57
+ });
58
+ }
@@ -0,0 +1,157 @@
1
+ /* pm/premium-chart-tab.js — the Chart tab beside a chat (initiative premium-reports-from-chat, slice C; PRD C1–C3). It replaces the Insight Studio's
2
+ * Chart and Dashboard modes: the PM asks in the chat, Claude ends its answer with a `pmos-report` block of kind chart or dashboard
3
+ * (public/pm/report-chat.js), and this tab draws it from the KR metric records, as the Insights page draws it (premium-chart-draw.js).
4
+ *
5
+ * A CHART (block.kind 'chart'): the measure's chart as proposed, with its four forms to pick from. Save chart posts POST /api/premium-charts/save.
6
+ * A saved chart (block.id) shows as saved; a change Claude proposes to it shows drawn, and Save the change posts the whole chart. Delete chart
7
+ * asks once, then posts { id, remove: true }.
8
+ * A DASHBOARD (block.kind 'dashboard'): its name, what it is for and its charts in order. Save dashboard posts POST /api/premium-dashboards/save;
9
+ * Delete dashboard asks once, then posts { id, remove: true }. Pinning stays on the Insights page.
10
+ *
11
+ * The model is GET /api/insights-premium (the board the page shows). Every value drawn is a reading of a record; a measure with fewer than two
12
+ * readings is named, not drawn. Every write is a press here, behind the launch nonce (http.js pmPost). Claude writes nothing: the routes refuse an
13
+ * agent session. Nothing is sent outward. */
14
+ import { pmGet, pmPost } from './http.js';
15
+ import { vwOpen, vwStyle, vwConfirm } from './premium-viewer.js';
16
+ import { tileHtml, deriveChart } from './premium-chart-draw.js';
17
+
18
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
19
+ const FORMS = [['line', 'Line'], ['bars', 'Bars'], ['number', 'Number'], ['meter', 'Meter']];
20
+ const ws = () => new URLSearchParams(location.search).get('ws') || '';
21
+ const post = (p, body) => pmPost(p, Object.assign(ws() ? { ws: ws() } : {}, body)).catch(() => null);
22
+ const btn = (a, label, o = {}) => `<button type="button" class="btn${o.sec ? ' sec' : ''}${o.cls ? ' ' + o.cls : ''}" data-ct="${esc(a)}"${o.off ? ' disabled' : ''}${o.pressed != null ? ` aria-pressed="${o.pressed}"` : ''}>${esc(label)}</button>`;
23
+
24
+ const T = new Map(); // tab id → its state
25
+ /** Open (or refresh) the Chart tab for a checked chart or dashboard block (report-chat.js cleanBlock). */
26
+ export function openChartTab(block) {
27
+ if (!block || (block.kind !== 'chart' && block.kind !== 'dashboard')) return null;
28
+ vwStyle('report');
29
+ const P = block.proposal || {};
30
+ const id = block.kind + ':' + String(block.id || P.measure || P.name || 'new').toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 60);
31
+ let t = T.get(id);
32
+ if (!t || JSON.stringify(t.block) !== JSON.stringify(block)) {
33
+ t = { id, block, M: null, loaded: false, busy: false, msg: '', d: null, gone: false, removed: false };
34
+ T.set(id, t);
35
+ load(t);
36
+ }
37
+ return vwOpen({ id, title: block.kind === 'chart' ? 'Chart' : 'Dashboard', icon: 'list', render: (el) => draw(t, el), wire: (el) => { el.onclick = (e) => press(t, e); } });
38
+ }
39
+ const paneOf = (t) => document.querySelector(`#dOut .obody.vw[data-vw="${CSS.escape(t.id)}"]`);
40
+ const redraw = (t) => { const el = paneOf(t); if (el) draw(t, el); };
41
+
42
+ async function load(t) {
43
+ const r = await pmGet('/api/insights-premium' + (ws() ? '?ws=' + encodeURIComponent(ws()) : '')).catch(() => null);
44
+ t.M = r && r.model ? r.model : null;
45
+ t.loaded = true;
46
+ if (t.M) {
47
+ const b = t.block, P = b.proposal;
48
+ if (b.kind === 'chart') {
49
+ const saved = b.id ? (t.M.mineSaved || []).find((x) => x.id === b.id) || null : null;
50
+ t.saved = saved;
51
+ t.d = saved || P ? Object.assign({}, saved || {}, P || {}) : null;
52
+ } else {
53
+ const saved = b.id ? (t.M.dashboards || []).find((x) => x.saved && x.id === b.id) || null : null;
54
+ t.saved = saved;
55
+ t.d = saved || P ? Object.assign({ purpose: '' }, saved ? { name: saved.name, purpose: saved.purpose, charts: saved.charts.slice(), main: saved.main } : {}, P || {}) : null;
56
+ }
57
+ t.gone = !t.d;
58
+ }
59
+ redraw(t);
60
+ }
61
+
62
+ /** A measure's or a saved chart's tile, as Insights draws it. */
63
+ function chartOf(M, ref) {
64
+ return (M.mine || []).find((c) => c.id === ref) || (M.charts || []).find((c) => c.id === ref) || null;
65
+ }
66
+ function draftTile(t) {
67
+ const d = t.d, base = (t.M.charts || []).find((c) => c.id === d.measure);
68
+ if (!base) {
69
+ const m = (t.M.measures || []).find((x) => x.id === d.measure);
70
+ return `<p class="rt-msg">${esc(m ? m.title + ' has fewer than two readings, so it has no chart yet.' : 'No KR metric record is called ' + d.measure + ' in this workspace.')}</p>`;
71
+ }
72
+ const c = deriveChart(base, { title: d.title || base.title, form: d.form || 'line', range: d.range || null, target: d.target, better: d.better || 'higher', note: d.note || '' });
73
+ return c ? `<div class="ntw ct-tile">${tileHtml(c)}</div>` : '<p class="rt-msg">The range holds fewer than two readings, so nothing is drawn.</p>';
74
+ }
75
+ const sameChart = (a, b) => ['measure', 'title', 'question', 'form', 'range', 'target', 'better', 'note'].every((k) => (a[k] == null ? '' : String(a[k])) === (b[k] == null ? '' : String(b[k])));
76
+
77
+ function chartHtml(t) {
78
+ const d = t.d, s = t.saved, base = (t.M.charts || []).find((c) => c.id === d.measure);
79
+ const changed = !s || !sameChart(s, d);
80
+ const eye = !s ? 'New chart · from this chat' : changed ? 'Chart change · from this chat' : 'Saved chart';
81
+ const forms = `<div class="rt-seg" role="group" aria-label="Form">${FORMS.map(([f, l]) => btn('form|' + f, l, { sec: (d.form || 'line') !== f, pressed: (d.form || 'line') === f })).join('')}</div>`;
82
+ const meter = d.form === 'meter' && (d.target === null || d.target === undefined) ? '<p class="rt-note">A meter needs a target. Say one in the chat, or pick another form.</p>' : '';
83
+ return `<p class="rt-eye">${esc(eye)}</p><h3 class="rt-h">${esc(d.title || (base ? base.title : d.measure))}</h3>${d.question ? `<p class="rt-sub">${esc(d.question)}</p>` : ''}`
84
+ + `<p class="rt-meta">${esc(base ? base.title : d.measure)}${d.range ? ' · last ' + d.range + ' readings' : ' · every reading'}${d.target != null ? ' · target ' + esc(d.target) : ''} · ${d.better === 'lower' ? 'lower is better' : 'higher is better'}</p>`
85
+ + forms + draftTile(t) + meter
86
+ + `<div class="rt-foot">${changed ? btn('save', t.busy ? 'Saving' : s ? 'Save the change' : 'Save chart', { off: t.busy || !base || !!meter }) : ''}</div>`
87
+ + `<p class="rt-note">${s ? 'It shows on Insights under Your charts.' : 'Saved, it shows on Insights under Your charts and can go on a dashboard.'} Ask in the chat to change it.</p>`
88
+ + (s ? `<div class="rt-foot rt-end">${btn('remove', 'Delete chart', { sec: true, cls: 'rt-del', off: t.busy })}</div>` : '');
89
+ }
90
+ function dashHtml(t) {
91
+ const d = t.d, s = t.saved, M = t.M;
92
+ const changed = !s || d.name !== s.name || d.purpose !== s.purpose || d.charts.join() !== s.charts.join();
93
+ const eye = !s ? 'New dashboard · from this chat' : changed ? 'Dashboard change · from this chat' : 'Saved dashboard';
94
+ const tiles = d.charts.map((ref) => {
95
+ const c = chartOf(M, ref);
96
+ if (c) return `<div class="ntw">${tileHtml(c)}</div>`;
97
+ const m = (M.measures || []).find((x) => x.id === ref);
98
+ return `<div class="nempty"><p><b>${esc(m ? m.title : ref)}</b><br>${esc(m ? 'It has fewer than two readings, so it has no chart yet.' : 'No KR metric record or saved chart is called ' + ref + '.')}</p></div>`;
99
+ }).join('');
100
+ const many = d.charts.length > 6 ? '<p class="rt-note">This dashboard holds more than six charts. A dashboard that serves one routine usually holds six or fewer.</p>' : '';
101
+ return `<p class="rt-eye">${esc(eye)}</p><h3 class="rt-h">${esc(d.name)}</h3>${d.purpose ? `<p class="rt-sub">${esc(d.purpose)}</p>` : ''}`
102
+ + `<p class="rt-meta">${d.charts.length} ${d.charts.length === 1 ? 'chart' : 'charts'}${s && s.main ? ' · pinned on Insights' : ''}</p>`
103
+ + `<div class="ngrid ct-grid">${tiles}</div>${many}`
104
+ + `<div class="rt-foot">${changed ? btn('save', t.busy ? 'Saving' : s ? 'Save the change' : 'Save dashboard', { off: t.busy }) : ''}</div>`
105
+ + `<p class="rt-note">${s ? 'It is in the list on Insights.' : 'Saved, it is in the list on Insights, where you can pin it.'} Ask in the chat to change it.</p>`
106
+ + (s ? `<div class="rt-foot rt-end">${btn('remove', 'Delete dashboard', { sec: true, cls: 'rt-del', off: t.busy })}</div>` : '');
107
+ }
108
+ function bodyHtml(t) {
109
+ const noun = t.block.kind;
110
+ if (!t.loaded) return `<p class="rt-note" role="status">Reading the ${noun}.</p>`;
111
+ if (!t.M) return `<p class="rt-note">The Insights records could not be read, so the ${noun} cannot be drawn. Try again in a moment.</p>`;
112
+ if (t.removed) return `<p class="rt-eye">${noun === 'chart' ? 'Chart' : 'Dashboard'}</p><p class="rt-note">Deleted. Ask in the chat for a new one.</p>`;
113
+ if (t.gone) return `<p class="rt-eye">${noun === 'chart' ? 'Chart' : 'Dashboard'}</p><h3 class="rt-h">${esc(t.block.id)}</h3><p class="rt-note">This ${noun} is deleted, or it is not saved on this board.</p>`;
114
+ if (!t.M.board.id) return '<p class="rt-note">This workspace has no board to save on, so nothing can be saved here.</p>';
115
+ return noun === 'chart' ? chartHtml(t) : dashHtml(t);
116
+ }
117
+ function draw(t, el) {
118
+ const ask = el.querySelector(':scope > .vcf'); // an open confirm card outlives a redraw, so its answer still lands
119
+ el.innerHTML = `<div class="rt">${bodyHtml(t)}${t.msg ? `<p class="rt-msg" role="status">${esc(t.msg)}</p>` : ''}</div>`;
120
+ if (ask) el.prepend(ask);
121
+ }
122
+
123
+ async function act(t, fn) { t.busy = true; t.msg = ''; redraw(t); const m = await fn(); t.busy = false; if (m != null) t.msg = m; redraw(t); }
124
+ const why = (r, d) => (r && r.error) || d;
125
+ async function press(t, e) {
126
+ const b = e.target.closest('[data-ct]'); if (!b || b.disabled) return;
127
+ const [a, v] = [b.dataset.ct.split('|')[0], b.dataset.ct.slice(b.dataset.ct.indexOf('|') + 1)];
128
+ const board = t.M && t.M.board.id, kind = t.block.kind;
129
+ if (a === 'form') { t.d = Object.assign({}, t.d, { form: v }); t.msg = ''; redraw(t); return; }
130
+ if (a === 'save') {
131
+ await act(t, async () => {
132
+ if (kind === 'chart') {
133
+ const d = t.d, base = (t.M.charts || []).find((c) => c.id === d.measure);
134
+ const r = await post('/api/premium-charts/save', { board, id: t.saved ? t.saved.id : undefined, measure: d.measure, title: d.title || (base ? base.title.slice(0, 60) : d.measure),
135
+ question: d.question || '', form: d.form || 'line', range: d.range || null, target: d.target == null ? null : d.target, better: d.better || 'higher', note: d.note || '' });
136
+ if (!r || !r.ok) return 'It was not saved: ' + why(r, 'the page could not reach PMOS') + '.';
137
+ t.block = { kind, id: r.chart.id }; await load(t);
138
+ return 'Saved. It shows on Insights under Your charts.';
139
+ }
140
+ const d = t.d;
141
+ const r = await post('/api/premium-dashboards/save', { board, id: t.saved ? t.saved.id : undefined, name: d.name, purpose: d.purpose || d.name, charts: d.charts, main: !!(t.saved && t.saved.main) });
142
+ if (!r || !r.ok) return 'It was not saved: ' + why(r, 'the page could not reach PMOS') + '.';
143
+ t.block = { kind, id: r.dashboard.id }; await load(t);
144
+ return 'Saved. It is in the list on Insights.';
145
+ });
146
+ return;
147
+ }
148
+ if (a === 'remove') {
149
+ const noun = kind === 'chart' ? 'chart' : 'dashboard';
150
+ if (!(await vwConfirm(paneOf(t), { text: kind === 'chart' ? 'Delete this chart? A dashboard that holds it shows it as removed.' : 'Delete this dashboard? Its charts and records stay.', yes: 'Delete ' + noun, no: 'Keep it' }))) return;
151
+ await act(t, async () => {
152
+ const r = await post(kind === 'chart' ? '/api/premium-charts/save' : '/api/premium-dashboards/save', { board, id: t.saved.id, remove: true });
153
+ if (!r || !r.ok) return 'It was not deleted: ' + why(r, 'the page could not reach PMOS') + '.';
154
+ t.removed = true; return null;
155
+ });
156
+ }
157
+ }
@@ -1,9 +1,15 @@
1
1
  /* pm/premium-chat.js — the Chat page (initiative premium-chat-page). The rail's middle place: the session list, the conversation and the viewer
2
- * as a page of their own. ?about=<key>&label=<name> is the page the PM came from (the rail's Chat carries it); without it, the PM's own chat. */
3
- import { wireRail, openChatPage } from './premium-shell.js';
2
+ * as a page of their own. ?about=<key>&label=<name> is the page the PM came from (the rail's Chat carries it); without it, the PM's own chat.
3
+ * premium-reports-from-chat (slice C): ?open=report:<id> | chart:<id> | dashboard:<id> opens that one in its tab beside the chat, and ?say=<words>
4
+ * puts a first message in the box for the PM to send. Insights links here for New, Edit and Shape it, now that the Insight Studio is removed. */
5
+ import { wireRail, openChatPage, openBlockTab, growAsk } from './premium-shell.js';
4
6
 
5
7
  wireRail('chat');
6
8
  const q = new URLSearchParams(location.search);
7
9
  // a conversation key as the ask route takes it (lib/briefing-premium-agent.js KEY_RE); anything else is the PM's own chat
8
10
  const about = /^(decision|blocked|waited|src|ev|work|board|init|doc|ins):[A-Za-z0-9][A-Za-z0-9._:-]{0,100}$/.test(q.get('about') || '') ? q.get('about') : null;
9
11
  openChatPage(about || 'chat:main', about ? (q.get('label') || '').slice(0, 80) : '');
12
+ const open = /^(report|chart|dashboard):([A-Za-z0-9][A-Za-z0-9._:-]{0,119})$/.exec(q.get('open') || '');
13
+ if (open) openBlockTab({ kind: open[1], id: open[2] });
14
+ const say = (q.get('say') || '').slice(0, 500);
15
+ if (say) { const inp = document.querySelector('#askIn'); if (inp) { inp.value = say; growAsk(); inp.focus(); inp.setSelectionRange(say.length, say.length); } }
@@ -3,15 +3,14 @@
3
3
  * line, what stands out), the Reports card, the dock and the standard dialog.
4
4
  * briefing-premium-reports adds the PM's presses, each through pmPost and so behind the launch nonce: a saved dashboard (POST /api/premium-dashboards/save,
5
5
  * PRD D2 to D6) and the report presses of the console's Reports workspace (POST /api/report-setups/ask | change | cancel | setup | dismiss | pause | resume |
6
- * draft, PRD R2 to R4). premium-studio-chart adds a saved chart (POST /api/premium-charts/save, PRD C1, C10) and its four forms (C3). premium-studio-report
7
- * adds New report and Shape it in the Studio, whose presses are POST /api/report-setups/setup | from-dashboard and POST /api/report-structure/turn | remove |
8
- * revert | accept (PRD R5 to R8). insights-one-list puts the insight first, the pinned dashboard on top and one paged list of dashboards and reports below
6
+ * draft, PRD R2 to R4). premium-studio-chart's saved charts are drawn in their four forms (premium-chart-draw.js). premium-reports-from-chat removed the
7
+ * Insight Studio: New, Edit and Shape it open the Chat page, where Claude proposes and the PM saves in the tab beside the chat. insights-one-list puts the insight first, the pinned dashboard on top and one paged list of dashboards and reports below
9
8
  * (PRD L1 to L6); its one new press is Pin, POST /api/premium-dashboards/pin. Nothing else posts, and nothing is sent outward. */
10
9
  import { $, $$, esc, openDlg, popKey, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, crumbHtml, wireCrumb, kv, setPageGaps, infoBtn, growAsk } from './premium-shell.js';
11
- import { pmPost, pmGet } from './http.js';
12
- import { openStudio } from './premium-studio.js';
10
+ import { pmPost } from './http.js';
13
11
  import { openReport } from './premium-report-read.js';
14
12
  import * as MT from './premium-metric-tiles.js';
13
+ import { W, P, X, Y, tileHtml } from './premium-chart-draw.js';
15
14
 
16
15
  let M = null; // the model
17
16
  let dash = null; // the dashboard in the top card: the pinned one until a list row opens another
@@ -63,62 +62,6 @@ $('#insHero').addEventListener('click', (e) => {
63
62
  });
64
63
 
65
64
  /* ── charts ───────────────────────────────────────────────────────────────────────────────────────────────────── */
66
- const W = 220, H = 60, P = 5;
67
- const X = (fx) => P + fx * (W - 2 * P), Y = (fy) => P + (1 - fy) * (H - 2 * P);
68
- /* A chart is drawn in one of four forms (initiative premium-studio-chart C3). The page and the Insight Studio share this drawing. A KR metric's own chart
69
- * is a line; a chart the PM saved carries its form. Bars and a meter start at zero, so a series with a value below zero is drawn as a line and says so. */
70
- const unitTxt = (c, v) => { const u = c.unit || '', s = String(Math.round(v * 100) / 100); return u ? (/^[A-Za-z]/.test(u) ? s + ' ' + u : s + u) : s; };
71
- function chgHtml(c) {
72
- return c.step === 0 ? '' : `<span class="mchg ${c.good === null ? '' : c.good ? 'good' : 'bad'}">${c.step > 0 ? '▲ ' : '▼ '}${esc(Math.abs(c.step) + (c.unit && /^[%°]/.test(c.unit) ? c.unit : c.unit ? ' ' + c.unit : ''))} since the last reading</span>`;
73
- }
74
- const chipOf = (c) => `<i class="mchip ${c.chipKind === 'bad' ? 'warn' : c.chipKind}">${esc(c.chip)}</i>`;
75
- const capOf = (c) => 'on ' + c.at + (c.targetTxt ? ' · ' + c.targetTxt : '');
76
- function tileHtml(c) {
77
- const f = c.form || 'line', neg = c.pts.some((p) => p.v < 0) || (c.target !== null && c.target < 0);
78
- const h = f === 'number' ? numTile(c) : f === 'bars' && !neg ? barsTile(c) : f === 'meter' && !neg && c.target !== null ? meterTile(c) : lineTile(c, f !== 'line' && f !== 'number' ? (neg ? 'A value is below zero, so it is drawn as a line.' : 'No target is set, so it is drawn as a line.') : '');
79
- return h + (c.note ? `<p class="mnote">${esc(c.note)}</p>` : '');
80
- }
81
- function lineTile(c, why) {
82
- const d = c.pts.map((p, i) => (i ? 'L' : 'M') + X(p.fx).toFixed(1) + ',' + Y(p.fy).toFixed(1)).join('');
83
- const last = c.pts[c.pts.length - 1];
84
- return `<div class="mt1 mch ${c.chipKind}${c.off ? ' off' : ''}" data-key="${esc(c.key)}" tabindex="0" role="img" aria-label="${esc(c.title)}, ${c.pts.length} readings, now ${esc(c.v)}${c.targetTxt ? ', ' + esc(c.targetTxt) : ''}. Use the arrow keys to read each reading."><span class="mlab">${esc(c.title)}${chipOf(c)}</span><b class="mval">${esc(c.v)}</b><em class="mwk">${esc(capOf(c))}</em>${chgHtml(c)}`
85
- + `<svg viewBox="0 0 ${W} ${H}"><path class="ar" d="${d}L${X(1)},${H}L${X(0)},${H}Z"/>${c.ty !== null ? `<line class="tg" x1="${P}" x2="${W - P}" y1="${Y(c.ty)}" y2="${Y(c.ty)}"/>` : ''}<path class="ln2" d="${d}"/><line class="cx" x1="0" x2="0" y1="0" y2="${H}"/><circle class="dt" cx="${X(last.fx)}" cy="${Y(last.fy)}" r="3.5"/></svg>`
86
- + `<span class="mfoot"><i>${esc(c.ticks[0])}</i>${c.target !== null ? '<i class="tgl">dashed line is the target</i>' : ''}<i>${esc(c.ticks[1])}</i></span>${why ? `<span class="mwhy">${esc(why)}</span>` : ''}</div>`;
87
- }
88
- function barsTile(c) {
89
- const n = c.pts.length, hi = Math.max(...c.pts.map((p) => p.v), c.target !== null ? c.target : 0) || 1, pc = (v) => (v / hi * 84).toFixed(1);
90
- const cols = c.pts.map((p, i) => `<span class="bw" title="${esc(p.d + ': ' + p.txt)}">${i === n - 1 ? `<b class="bl">${esc(p.txt)}</b>` : ''}<i class="${i === n - 1 ? 'bk' : 'bg'}" style="height:${pc(p.v)}%"></i></span>`).join('');
91
- return `<div class="mt1 mfm bars ${c.chipKind}${c.off ? ' off' : ''}" data-key="${esc(c.key)}" role="img" aria-label="${esc(c.title)}, ${n} readings as bars from zero, now ${esc(c.v)}${c.targetTxt ? ', ' + esc(c.targetTxt) : ''}"><span class="mlab">${esc(c.title)}${chipOf(c)}</span><b class="mval">${esc(c.v)}</b><em class="mwk">${esc(capOf(c))}</em>${chgHtml(c)}`
92
- + `<div class="bplot">${cols}${c.target !== null ? `<i class="btg" style="bottom:${pc(c.target)}%"></i>` : ''}</div>`
93
- + `<span class="mfoot"><i>${esc(c.ticks[0])}</i><i class="tgl">${c.target !== null ? 'dashed line is the target' : 'bars start at zero'}</i><i>${esc(c.ticks[1])}</i></span></div>`;
94
- }
95
- function numTile(c) {
96
- const d = c.pts.map((p, i) => (i ? 'L' : 'M') + X(p.fx).toFixed(1) + ',' + (2 + (1 - p.fy) * 26).toFixed(1)).join('');
97
- return `<div class="mt1 mfm num ${c.chipKind}${c.off ? ' off' : ''}" data-key="${esc(c.key)}" role="img" aria-label="${esc(c.title)}, now ${esc(c.v)}${c.targetTxt ? ', ' + esc(c.targetTxt) : ''}"><span class="mlab">${esc(c.title)}${chipOf(c)}</span><b class="mval mhero">${esc(c.v)}</b><em class="mwk">${esc(capOf(c))}</em>${chgHtml(c)}`
98
- + `<svg class="nspk" viewBox="0 0 ${W} 30" aria-hidden="true"><path d="${d}"/></svg></div>`;
99
- }
100
- function meterTile(c) {
101
- const v = c.pts[c.pts.length - 1].v, tg = c.target, hi = Math.max(v, tg) * 1.15 || 1, lower = c.dir < 0, ok = lower ? v <= tg : v >= tg;
102
- return `<div class="mt1 mfm prg ${c.chipKind}${c.off ? ' off' : ''}" data-key="${esc(c.key)}" role="img" aria-label="${esc(c.title)} is ${esc(c.v)} against ${lower ? 'a limit' : 'a target'} of ${esc(unitTxt(c, tg))}. ${ok ? 'It is on the right side of it.' : 'It is not there yet.'}"><span class="mlab">${esc(c.title)}${chipOf(c)}</span><b class="mval">${esc(c.v)}</b><em class="mwk">${esc(ok ? (lower ? 'Within the limit' : 'At or past the target') : (lower ? 'Over the limit' : 'Short of the target'))}</em>`
103
- + `<div class="mtrk"><i class="mfil ${ok ? 'ok' : 'warn'}" style="width:${(v / hi * 100).toFixed(1)}%"></i><i class="mtgt" style="left:${(tg / hi * 100).toFixed(1)}%"></i></div>`
104
- + `<span class="mfoot"><i>0</i><i class="tgl">${lower ? 'limit' : 'target'} ${esc(unitTxt(c, tg))}</i><i>${esc(unitTxt(c, hi))}</i></span></div>`;
105
- }
106
- /* The Studio's draft drawn from a measure's chart (premium-studio-chart C2, C7): the latest `range` readings, against the draft's target, as the server's
107
- * lib/insights-premium.js mineOf draws a saved chart. Every point is a reading of the record. */
108
- function deriveChart(base, d) {
109
- const all = base.pts, pts0 = d.range ? all.slice(-d.range) : all.slice();
110
- if (pts0.length < 2) return null;
111
- const tg = d.target === null || d.target === undefined || d.target === '' ? null : +d.target;
112
- const day = (p) => Date.parse(String(p.at).slice(0, 10) + 'T00:00:00Z');
113
- const t0 = day(pts0[0]), span = day(pts0[pts0.length - 1]) - t0 || 1;
114
- const ys = pts0.map((p) => p.v).concat(tg !== null ? [tg] : []), lo = Math.min(...ys), hi = Math.max(...ys), range = hi - lo || 1;
115
- const pts = pts0.map((p) => Object.assign({}, p, { fx: (day(p) - t0) / span, fy: (p.v - lo) / range }));
116
- const now = pts[pts.length - 1], prev = pts[pts.length - 2], step = Math.round((now.v - prev.v) * 100) / 100, dir = d.better === 'lower' ? -1 : 1;
117
- return Object.assign({}, base, {
118
- key: 'draft', title: d.title || base.title, form: d.form, note: d.note || '', pts, v: now.txt, at: now.d, target: tg, targetTxt: tg !== null ? 'target ' + unitTxt(base, tg) : '',
119
- ty: tg !== null ? (tg - lo) / range : null, step, dir, good: step ? step * dir > 0 : null, ticks: [pts[0].d, now.d],
120
- });
121
- }
122
65
  /* Point at reading j: the cursor line, the dot, the value and the date move to it. Without j the tile returns to the latest reading. */
123
66
  function chartAt(t, j) {
124
67
  const c = byKey(t.dataset.key); if (!c) return;
@@ -220,24 +163,19 @@ $('#dashBar').addEventListener('click', (e) => {
220
163
  if (e.target.closest('#pdEdit')) openDashEdit(curDash()); else if (e.target.closest('#pcNew')) openChartEdit(null);
221
164
  });
222
165
 
223
- /* ── a dashboard is made and edited in the Insight Studio (initiative premium-studio-dashboard). Its one press posts POST /api/premium-dashboards/save. ── */
166
+ /* ── dashboards, charts and reports are made and changed in a chat (initiative premium-reports-from-chat, slice C; the Insight Studio is removed).
167
+ * Edit, New chart, the + menu and Shape it open the Chat page: with ?open= it opens that one in the tab beside the chat, with ?say= it puts a first
168
+ * message in the box for the PM to send. Every save is still the PM's press in that tab. ── */
169
+ /* the switches under On your dashboards in a measure's dialog still save a dashboard here (POST /api/premium-dashboards/save) */
224
170
  async function saveDash(body) { return pmPost('/api/premium-dashboards/save', Object.assign({ ws: M.board.ws, board: M.board.id }, body)); }
225
- async function saveChart(body) { return pmPost('/api/premium-charts/save', Object.assign({ ws: M.board.ws, board: M.board.id }, body)); }
226
- const structure = {
227
- get: (id) => pmGet('/api/report-structure?ws=' + encodeURIComponent(M.board.ws || '') + '&id=' + encodeURIComponent(id)),
228
- post: (sub, id, body) => pmPost('/api/report-structure/' + sub, Object.assign({ ws: M.board.ws, id }, body)),
229
- };
230
- const design = {
231
- get: (id) => pmGet('/api/report-design?ws=' + encodeURIComponent(M.board.ws || '') + '&id=' + encodeURIComponent(id)),
232
- post: (sub, id, body) => pmPost('/api/report-design/' + sub, Object.assign({ ws: M.board.ws, id }, body)),
233
- };
234
- const studioOf = (o) => openStudio(Object.assign({ M, tile: tileHtml, derive: deriveChart, save: saveDash, saveChart, setup: (sub, body) => repPost(sub, body), structure, design, reportsChanged: () => load(),
235
- done: async (id) => { dash = id || dash; await load(); } }, o));
236
- function openDashEdit(D) { studioOf({ mode: 'dash', D, done: async (id) => { dash = id || null; await load(); } }); }
237
- /* A chart is made and edited in the Studio's Chart mode (initiative premium-studio-chart). Save posts POST /api/premium-charts/save. */
238
- function openChartEdit(id) { studioOf({ mode: 'chart', C: id ? (M.mineSaved || []).find((x) => x.id === id) || null : null }); }
239
- /* A report is set up and shaped in the Studio's Report mode (initiative premium-studio-report). */
240
- function openReportEdit(s) { studioOf({ mode: 'rep', R: s || null }); }
171
+ function toChat(o) {
172
+ const q = new URLSearchParams(); if (M.board.ws) q.set('ws', M.board.ws);
173
+ if (o.open) q.set('open', o.open); if (o.say) q.set('say', o.say);
174
+ location.href = '/premium-chat.html?' + q.toString();
175
+ }
176
+ const openDashEdit = (D) => toChat(D ? { open: 'dashboard:' + D.id } : { say: 'Make a dashboard of ' });
177
+ const openChartEdit = (id) => toChat(id ? { open: 'chart:' + id } : { say: 'Make a chart of ' });
178
+ const openReportEdit = (s) => toChat(s ? { open: 'report:' + s.id } : { say: 'Make a report of ' });
241
179
  $('#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); });
242
180
  $('#dashBody').addEventListener('keydown', (e) => {
243
181
  const t = e.target.closest && e.target.closest('.mch'); if (!t || !/^Arrow(Left|Right)$/.test(e.key)) return;
@@ -409,7 +347,7 @@ function openSetup(s) {
409
347
  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]];
410
348
  const acts = [s.paused ? ['resume', 'Resume'] : ['pause', 'Pause', 1]];
411
349
  if (s.fromWork && !s.paused) acts.unshift(['draft', 'Draft it now']);
412
- if (s.fromWork) acts.push(['studio', 'Shape it in the Studio', 1]);
350
+ if (s.fromWork) acts.push(['studio', 'Shape it in a chat', 1]);
413
351
  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.',
414
352
  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>`,
415
353
  acts, on: {