farseer-cli 1.25.0 → 1.26.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 (69) hide show
  1. package/README.md +1 -1
  2. package/dist/commands/dashboards.js +2 -0
  3. package/dist/commands/dashboards.js.map +1 -1
  4. package/dist/commands/login.js +18 -7
  5. package/dist/commands/login.js.map +1 -1
  6. package/dist/commands/logout.js +28 -12
  7. package/dist/commands/logout.js.map +1 -1
  8. package/dist/commands/run.js +2 -3
  9. package/dist/commands/run.js.map +1 -1
  10. package/dist/commands/whoami.js +12 -5
  11. package/dist/commands/whoami.js.map +1 -1
  12. package/dist/mcp/tools/authTools.js +2 -1
  13. package/dist/mcp/tools/authTools.js.map +1 -1
  14. package/dist/mcp/tools/dashboardTools.js +3 -1
  15. package/dist/mcp/tools/dashboardTools.js.map +1 -1
  16. package/dist/mcp/tools/runTools.js +2 -3
  17. package/dist/mcp/tools/runTools.js.map +1 -1
  18. package/dist/mcp/utils/helpers.js +8 -6
  19. package/dist/mcp/utils/helpers.js.map +2 -2
  20. package/dist/mcp/utils/session.js +6 -2
  21. package/dist/mcp/utils/session.js.map +1 -1
  22. package/dist/operations/dashboards.js +1 -1
  23. package/dist/operations/dashboards.js.map +1 -1
  24. package/dist/pipeline/generated-reference.json +8 -8
  25. package/dist/services/codefirst/layoutReadback.js +95 -0
  26. package/dist/services/codefirst/layoutReadback.js.map +2 -2
  27. package/dist/services/configService.js +33 -18
  28. package/dist/services/configService.js.map +1 -1
  29. package/dist/services/credentials.js +26 -11
  30. package/dist/services/credentials.js.map +1 -1
  31. package/dist/services/farseerService.js +34 -32
  32. package/dist/services/farseerService.js.map +1 -1
  33. package/dist/services/keycloak.js +44 -0
  34. package/dist/services/keycloak.js.map +6 -0
  35. package/dist/services/preflight.js +1 -2
  36. package/dist/services/preflight.js.map +1 -1
  37. package/dist/services/realms.js +67 -15
  38. package/dist/services/realms.js.map +1 -1
  39. package/dist/utils/serverUrl.js +42 -0
  40. package/dist/utils/serverUrl.js.map +6 -0
  41. package/docs/pipeline-reference.md +13 -3
  42. package/package.json +1 -1
  43. package/skills/farseer-code-tiles/SKILL.md +153 -0
  44. package/skills/farseer-code-tiles/anti-patterns.md +183 -0
  45. package/skills/farseer-code-tiles/api.md +237 -0
  46. package/skills/farseer-code-tiles/check-tile.mjs +521 -0
  47. package/skills/farseer-code-tiles/design.md +159 -0
  48. package/skills/farseer-code-tiles/echarts-look.md +110 -0
  49. package/skills/farseer-code-tiles/examples/board-deck.js +695 -0
  50. package/skills/farseer-code-tiles/examples/data-checks.js +475 -0
  51. package/skills/farseer-code-tiles/examples/kpi-cards.js +374 -0
  52. package/skills/farseer-code-tiles/examples/map-countries.js +377 -0
  53. package/skills/farseer-code-tiles/examples/month-plan.js +443 -0
  54. package/skills/farseer-code-tiles/examples/new-location.js +581 -0
  55. package/skills/farseer-code-tiles/examples/open-forecast.js +598 -0
  56. package/skills/farseer-code-tiles/examples/pl-sankey.js +402 -0
  57. package/skills/farseer-code-tiles/examples/ranked-bars.js +337 -0
  58. package/skills/farseer-code-tiles/examples/request-form.js +464 -0
  59. package/skills/farseer-code-tiles/farseer-table.md +98 -0
  60. package/skills/farseer-code-tiles/known-mistakes.md +178 -0
  61. package/skills/farseer-code-tiles/maps/europe.geo.json +1 -0
  62. package/skills/farseer-code-tiles/maps/pick-map.mjs +59 -0
  63. package/skills/farseer-code-tiles/maps/world.geo.json +1 -0
  64. package/skills/farseer-dashboards/SKILL.md +3 -2
  65. package/skills/farseer-dashboards/check.md +3 -2
  66. package/skills/farseer-dashboards/measures.md +3 -1
  67. package/skills/farseer-optimize-model/SKILL.md +9 -1
  68. package/skills/farseer-pnl/SKILL.md +3 -3
  69. package/skills/pipeline-authoring/SKILL.md +2 -2
@@ -0,0 +1,581 @@
1
+ // Open a new location staffed like an existing one: adds the location under the same company and copies the other
2
+ // location's Budget 2026 headcount plan (IMPORT_FTE) from the month it opens, at a share. Tile size: w36 h19.
3
+ export default function (ctx) {
4
+ // readTable: a table of numbers from the model, in the shape ctx.charts.farseer draws
5
+ // ({ columns: [{ label, numberFormat }], rows: [{ label, cells: [{ value }] }] }). Call it in the body.
6
+ // rows: { table: 'Entity' } every member of a table, listed live by name
7
+ // rows: { table, includeDashboardFilters: true } the members the filter bar leaves, even when the numbers ignore it
8
+ // rows: { table: 'Months', members: ['M1', …] } the members named here, in this order
9
+ // rows: [{ label, formula, numberFormat }] one line per formula (a P&L)
10
+ // no rows one row, labelled '', for KPIs
11
+ // columns: [{ label, formula, numberFormat }] with member rows, [{ label, filter }] with formula lines
12
+ // Member rows and every number follow the filter bar and timeline, unless the spec turns them off.
13
+ const quote = (name) => `"${String(name).replace(/(["\\])/g, '\\$1')}"`;
14
+ // a table's members from a DTABLE answer, by name, without its NULL member
15
+ const namesOf = (answer) => (answer?.value ?? []).map(String).filter((name) => !name.startsWith('NULL ('));
16
+ function withFilter(formula, filter) {
17
+ let out = '', depth = [], quoted = false;
18
+ for (let i = 0; i < formula.length; i++) {
19
+ const c = formula[i];
20
+ if (c === '"' && formula[i - 1] !== '\\') quoted = !quoted;
21
+ if (!quoted && c === '(') depth.push(/sum\s*$/i.test(formula.slice(0, i)));
22
+ if (!quoted && c === ')' && depth.pop()) out += `, ${filter}`;
23
+ out += c;
24
+ }
25
+ return out;
26
+ }
27
+ function readTable(spec) {
28
+ // includeDashboardFilters: false / includeDashboardTimeline: false in the spec leave one out (say so on the tile)
29
+ const options = { includeDashboardFilters: spec.includeDashboardFilters !== false, includeDashboardTimeline: spec.includeDashboardTimeline !== false };
30
+ const { columns } = spec;
31
+ const rows = spec.rows ?? [{ label: '' }];
32
+ const memberRows = !Array.isArray(rows);
33
+ const listOptions = { ...options, ...(memberRows && rows.includeDashboardFilters !== undefined ? { includeDashboardFilters: rows.includeDashboardFilters } : {}) };
34
+ const list = memberRows && !rows.members ? ctx.query([{ type: 'DTABLE', table: rows.table }], listOptions) : null;
35
+ let names = memberRows ? rows.members ?? null : null;
36
+ let listed = null;
37
+ let values = null;
38
+ const open = () => {
39
+ values?.close();
40
+ const formulas = memberRows
41
+ ? names.flatMap((name) => columns.map((c) => withFilter(c.formula, `${quote(rows.table)}>${quote(name)}`)))
42
+ : rows.flatMap((r) => columns.map((c) => (r.formula ? withFilter(r.formula, c.filter) : c.formula)));
43
+ values = formulas.length ? ctx.query(formulas.map((formula) => ({ type: 'VARIABLE', formula })), options) : null;
44
+ };
45
+ if (!list) open();
46
+ const refresh = () => {
47
+ if (list.loading && !list.current.length) return;
48
+ const now = namesOf(list.current[0]);
49
+ const key = now.join('\u0001');
50
+ if (key !== listed) {
51
+ listed = key;
52
+ names = now;
53
+ open();
54
+ }
55
+ };
56
+ return {
57
+ get loading() {
58
+ if (list) refresh();
59
+ return (list?.loading ?? false) || (values?.loading ?? false);
60
+ },
61
+ get error() {
62
+ return list?.error ?? values?.error ?? null;
63
+ },
64
+ get current() {
65
+ if (list) refresh();
66
+ const cells = values?.current ?? [];
67
+ const labels = memberRows ? names ?? [] : rows.map((r) => r.label);
68
+ return {
69
+ columns: columns.map((c) => ({ label: c.label, numberFormat: c.numberFormat ?? (memberRows ? null : rows[0]?.numberFormat) ?? null })),
70
+ rows: labels.map((label, j) => ({
71
+ label,
72
+ numberFormat: memberRows ? null : rows[j].numberFormat ?? null,
73
+ cells: columns.map((_, i) => ({ value: cells[j * columns.length + i]?.value ?? null })),
74
+ })),
75
+ };
76
+ },
77
+ };
78
+ }
79
+ // picks(['Entity', 'Year to date']): what the filter bar picked on these tables, for a title or a form.
80
+ // current.Entity is { members: ['Acme Croatia'], all: false }; all is true when the bar doesn't narrow that table.
81
+ function picks(tables) {
82
+ const picked = ctx.query(tables.map((table) => ({ type: 'DTABLE', table })));
83
+ const every = ctx.query(tables.map((table) => ({ type: 'DTABLE', table })), { includeDashboardFilters: false, includeDashboardTimeline: false });
84
+ return {
85
+ get loading() {
86
+ return picked.loading || every.loading;
87
+ },
88
+ get error() {
89
+ return picked.error ?? every.error ?? null;
90
+ },
91
+ get current() {
92
+ return Object.fromEntries(tables.map((table, i) => {
93
+ const members = namesOf(picked.current[i]);
94
+ return [table, { members, all: members.length === namesOf(every.current[i]).length }];
95
+ }));
96
+ },
97
+ };
98
+ }
99
+ // --- Open a new location staffed like an existing one: a new member of Location under the same company, and its
100
+ // Budget 2026 headcount plan (IMPORT_FTE) copied from the other location from the month it opens, at a share.
101
+ const VERSION = 'Budget 2026';
102
+ const YEAR = 'Y2026';
103
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
104
+ const ANY = { includeDashboardFilters: false, includeDashboardTimeline: false };
105
+ const lists = ctx.query(
106
+ [{ type: 'DTABLE', table: 'Location', columns: ['name', 'Entity'] }, { type: 'DTABLE', table: 'Entity' }, { type: 'DTABLE', table: 'Position' }, { type: 'DTABLE', table: 'Employment type' }, { type: 'DTABLE', table: 'Cost centre' }],
107
+ ANY,
108
+ );
109
+ // each location's company, from the Location table's Entity column
110
+ function locations() {
111
+ const flat = lists.current[0]?.value ?? [];
112
+ const companies = lists.current[1]?.value ?? [];
113
+ const out = [];
114
+ for (let i = 0; i + 1 < flat.length; i += 2) if (!String(flat[i]).startsWith('NULL (')) out.push({ name: flat[i], company: companies[(flat[i + 1] ?? [])[0]] ?? '' });
115
+ return out;
116
+ }
117
+ const plan = `"Versions">${quote(VERSION)}, "Years">"${YEAR}"`;
118
+ const cell = (location, l, month) =>
119
+ `sum("IMPORT_FTE", ${plan}, "Months">"${month}", "Location">${quote(location)}, "Position">${quote(l.position)}, "Employment type">${quote(l.type)}, "Cost centre">${quote(l.centre)})`;
120
+ const byPosition = (location, position, month) => `sum("IMPORT_FTE", ${plan}, "Months">"${month}", "Location">${quote(location)}, "Position">${quote(position)})`;
121
+ const total = (location, month) => `sum("IMPORT_FTE", ${plan}, "Months">"${month}", "Location">${quote(location)})`;
122
+ // A message between the tile and Farseer holds at most 256 KB, and one it can't hold gets no answer at all. So reads
123
+ // and writes go in parts cut by size, about 200 KB of JSON each, never by count: long names make long formulas.
124
+ const LIMIT = 200000;
125
+ const MAX_PARTS = 8;
126
+ function parts(queries) {
127
+ const out = [];
128
+ let part = [];
129
+ let size = 2;
130
+ for (const query of queries) {
131
+ const length = JSON.stringify(query).length + 1;
132
+ if (part.length && size + length > LIMIT) {
133
+ out.push(part);
134
+ part = [];
135
+ size = 2;
136
+ }
137
+ part.push(query);
138
+ size += length;
139
+ }
140
+ if (part.length) out.push(part);
141
+ return out;
142
+ }
143
+ // the parts are read one after another: a tile holds at most ten reads open at once
144
+ async function readAll(queries) {
145
+ const answers = [];
146
+ for (const part of parts(queries)) answers.push(...(await ctx.read(part, ANY)));
147
+ return answers;
148
+ }
149
+
150
+ // --- The Farseer look (echarts-look.md, design.md): the same block in every tile ---
151
+ // AC: the dashboards' AC colour (SKILL.md section 2, The AC colour): #323232, or the company's
152
+ // darkest brand colour when it is dark enough, never an example's. AC_LIGHT is its PY tint.
153
+ // Everything else below is derived from them, so nothing else needs changing.
154
+ const AC = '#323232';
155
+ const AC_LIGHT = '#A6A6A6';
156
+ // mixes a colour with white: share 1 is the colour itself, 0 is white
157
+ function tint(hex, share) {
158
+ const n = parseInt(hex.slice(1), 16);
159
+ const mix = (c) => Math.round(c * share + 255 * (1 - share)).toString(16).padStart(2, '0');
160
+ return `#${mix(n >> 16)}${mix((n >> 8) & 255)}${mix(n & 255)}`.toUpperCase();
161
+ }
162
+ // a colour with almost no hue (graphite, grey): its ramp would turn a map grey, so magnitude takes Farseer blue
163
+ const isGrey = (hex) => { const n = parseInt(hex.slice(1), 16); const c = [n >> 16, (n >> 8) & 255, n & 255]; return Math.max(...c) - Math.min(...c) < 24; };
164
+ const PALETTE = [AC, '#ED7D16', '#1BB5D7', '#8A2FE5', '#BFA812', '#E52FCD']; // identity: AC first, then distinct hues
165
+ const FILL = [AC_LIGHT, '#F5B87F', '#82D6E9', '#BF8DF1', '#DCCF7D', '#F18DE4']; // the light step, for large areas
166
+ // magnitude (maps, heatmaps), light to dark: steps of AC, or Farseer blue when AC is a grey
167
+ const RAMP = isGrey(AC) ? ['#81A9FF', '#457DFF', '#0D4BC2', '#043288'] : [0.45, 0.65, 0.8, 1].map((s) => tint(AC, s));
168
+ // light tints of AC for large areas that need ink text (treemap groups), clearly apart from each other
169
+ // (from Farseer blue when AC is a grey, as the ramp: grey tints would make a grey block)
170
+ const TINTS = [0.52, 0.37, 0.24, 0.11].map((s) => tint(isGrey(AC) ? '#043288' : AC, s));
171
+ const TRACK = tint(AC, 0.12); // the unfilled part of a gauge
172
+ const PRIMARY = '#1A66FF'; // Farseer's own primary button, not a data colour
173
+ const GOOD = '#0CB955';
174
+ const BAD = '#E21E09';
175
+ const INK = () => ctx.theme.tokens?.text ?? '#020810';
176
+ const MUTED = () => ctx.theme.tokens?.muted ?? '#687C95';
177
+ const LINE = () => ctx.theme.tokens?.border ?? '#E6EBF2';
178
+ const SURFACE = () => ctx.theme.tokens?.background ?? '#FFFFFF';
179
+ const FONT = 'Inter, system-ui, sans-serif';
180
+ let drawnOnce = false;
181
+ // draws one echarts chart in the look; the first chart that draws ends the entrance animation for the rest
182
+ function drawChart(element, option) {
183
+ ctx.charts.echarts(element, option);
184
+ drawnOnce = true;
185
+ }
186
+ // the chart tile's look, measured from it: square bars, 12 px ink labels with a surface-coloured halo, an ink
187
+ // category axis with ticks, no value axis or gridlines, the legend at the bottom, its tooltip and margins
188
+ const LABEL = { show: true, fontFamily: FONT, fontSize: 12, color: INK(), textBorderColor: SURFACE(), textBorderWidth: 4 };
189
+ function look() {
190
+ return {
191
+ animation: !drawnOnce,
192
+ animationDuration: 500,
193
+ textStyle: { fontFamily: FONT, fontSize: 12, color: INK() },
194
+ grid: { left: 10, right: 10, top: 20, bottom: 10, containLabel: true },
195
+ legend: { bottom: 0, textStyle: { fontFamily: FONT, color: INK() } },
196
+ tooltip: {
197
+ trigger: 'item', confine: true, backgroundColor: SURFACE(), borderColor: '#EDF2F7', borderWidth: 1,
198
+ padding: [6, 10], textStyle: { color: INK(), fontSize: 12, fontFamily: FONT },
199
+ extraCssText: 'border-radius:6px;box-shadow:0 4px 16px rgba(107,131,160,0.15)',
200
+ },
201
+ categoryAxis: {
202
+ axisLine: { show: true, lineStyle: { color: INK(), width: 1 } },
203
+ axisTick: { show: false },
204
+ axisLabel: { color: INK(), fontFamily: FONT, fontSize: 12, hideOverlap: true },
205
+ splitLine: { show: false },
206
+ },
207
+ valueAxis: { show: false, splitLine: { show: false } },
208
+ };
209
+ }
210
+ function merge(base, extra) {
211
+ if (Array.isArray(extra) || typeof extra !== 'object' || extra === null) return extra;
212
+ const out = { ...base };
213
+ for (const [key, value] of Object.entries(extra)) {
214
+ out[key] = typeof value === 'object' && value !== null && !Array.isArray(value) && typeof base?.[key] === 'object' ? merge(base[key], value) : value;
215
+ }
216
+ return out;
217
+ }
218
+ // form controls and buttons in Farseer's toolbar look: 28 px high, 12 px text, the focus ring drawn inside the
219
+ // control (so a control at the tile's edge never loses it), button text that never wraps, a long choice ending in …
220
+ // Farseer's own form controls and buttons (the app's input, select and button), the same in every tile
221
+ const CONTROL_CSS = `
222
+ .fs-control { font: 400 12px/20px ${FONT}; height: 32px; padding: 0 8px; border: 1px solid #EDF2F7; border-radius: 8px;
223
+ background-color: #EDF2F7; color: var(--code-tile-text); min-width: 0; max-width: 100%; box-sizing: border-box; outline: none;
224
+ overflow: hidden; white-space: nowrap; text-overflow: ellipsis; transition: border-color 100ms; }
225
+ select.fs-control { appearance: none; -webkit-appearance: none; padding-right: 32px; cursor: pointer;
226
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill='%23020810' fill-rule='evenodd' d='M4.17 6.124a.5.5 0 01.706.047L8 9.74l3.124-3.57a.5.5 0 01.752.658l-3.5 4a.5.5 0 01-.752 0l-3.5-4a.5.5 0 01.047-.705z'/%3E%3C/svg%3E");
227
+ background-repeat: no-repeat; background-position: right 8px center; background-size: 16px 16px; }
228
+ .fs-control:hover { border-color: #C1CEDE; }
229
+ .fs-control:focus, .fs-control:focus-visible { border-color: #1966FF; outline: 1px solid #1966FF; outline-offset: 0; }
230
+ .fs-control.fs-empty, .fs-control::placeholder { color: var(--code-tile-muted); }
231
+ .fs-control:disabled { background-color: var(--code-tile-background); color: var(--code-tile-muted); cursor: not-allowed; }
232
+ .fs-button { font: 500 12px/14px ${FONT}; height: 32px; min-width: 32px; padding: 0 12px; white-space: nowrap; flex: none; border: none;
233
+ border-radius: 8px; cursor: pointer; background-color: #1966FF; color: #FFFFFF; transition: background-color 100ms, color 100ms; }
234
+ .fs-button:hover { background-color: #0942B2; }
235
+ .fs-button.fs-secondary { background-color: #E8F0FF; color: #1966FF; }
236
+ .fs-button.fs-secondary:hover { background-color: #C5D9FF; }
237
+ .fs-button.fs-tertiary { background-color: transparent; color: var(--code-tile-text); font-weight: 400; box-shadow: 0 0 0 1px var(--code-tile-border) inset; }
238
+ .fs-button.fs-tertiary:hover { background-color: #EDF2F7; }
239
+ .fs-button:disabled, .fs-button:disabled:hover { background-color: var(--code-tile-border); color: var(--code-tile-muted); box-shadow: none; cursor: not-allowed; }
240
+ .fs-button:focus-visible { outline: 1px solid var(--code-tile-text); outline-offset: 1px; }
241
+ .fs-button { display: inline-flex; align-items: center; justify-content: center; gap: 4px; }
242
+ .fs-chevron { width: 16px; height: 16px; flex: none; background-color: currentColor; -webkit-mask: center / 16px no-repeat; mask: center / 16px no-repeat; }
243
+ .fs-chevron-left { -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill-rule='evenodd' d='M10.376 4.67a.5.5 0 01-.047.706L6.76 8.5l3.57 3.124a.5.5 0 11-.658.752l-4-3.5a.5.5 0 010-.752l4-3.5a.5.5 0 01.705.047z'/%3E%3C/svg%3E"); mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill-rule='evenodd' d='M10.376 4.67a.5.5 0 01-.047.706L6.76 8.5l3.57 3.124a.5.5 0 11-.658.752l-4-3.5a.5.5 0 010-.752l4-3.5a.5.5 0 01.705.047z'/%3E%3C/svg%3E"); }
244
+ .fs-chevron-right { -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill-rule='evenodd' d='M5.624 12.33a.5.5 0 01.047-.706L9.24 8.5 5.67 5.376a.5.5 0 11.658-.752l4 3.5a.5.5 0 010 .752l-4 3.5a.5.5 0 01-.705-.047z'/%3E%3C/svg%3E"); mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill-rule='evenodd' d='M5.624 12.33a.5.5 0 01.047-.706L9.24 8.5 5.67 5.376a.5.5 0 11.658-.752l4 3.5a.5.5 0 010 .752l-4 3.5a.5.5 0 01-.705-.047z'/%3E%3C/svg%3E"); }
245
+ .fs-button.fs-icon-only { padding: 0; width: 32px; }`;
246
+ function control(tag, className = 'fs-control') {
247
+ if (!document.getElementById('fs-control-style')) {
248
+ const style = document.createElement('style');
249
+ style.id = 'fs-control-style';
250
+ style.textContent = CONTROL_CSS;
251
+ document.head.append(style);
252
+ }
253
+ const node = document.createElement(tag);
254
+ node.className = className;
255
+ return node;
256
+ }
257
+ // Farseer's table look (farseer-table.md): the same font, row height, header and rules as a table tile
258
+ const TABLE_CSS = `
259
+ .fs-table-wrap { width: fit-content; max-width: 100%; overflow: hidden; }
260
+ .fs-table { width: max-content; max-width: calc(100% + 12px); border-collapse: separate; border-spacing: 12px 0; margin: 0 0 0 -12px; font: 12px/1.2 ${FONT}; color: var(--code-tile-text); font-variant-numeric: tabular-nums; }
261
+ .fs-table th { height: 24px; padding: 0 0 5px; font-weight: 400; text-align: right; vertical-align: bottom; white-space: nowrap; background: linear-gradient(var(--code-tile-text), var(--code-tile-text)) bottom / 100% 1px no-repeat; }
262
+ .fs-table td { height: 24px; padding: 0; text-align: right; white-space: nowrap; background: linear-gradient(var(--code-tile-border), var(--code-tile-border)) bottom / 100% 1px no-repeat; }
263
+ .fs-table th:first-child, .fs-table td:first-child { text-align: left; }
264
+ .fs-table td:first-child { max-width: 220px; overflow: hidden; text-overflow: ellipsis; }
265
+ .fs-table tr.fs-total td { font-weight: 700; background-image: linear-gradient(var(--code-tile-text), var(--code-tile-text)); }
266
+ .fs-table tbody tr:hover td { background-color: color-mix(in srgb, var(--code-tile-muted) 8%, transparent); }
267
+ .fs-table .fs-good { color: ${GOOD}; } .fs-table .fs-bad { color: ${BAD}; } .fs-table .fs-muted { color: var(--code-tile-muted); }
268
+ .fs-table .fs-key { display: inline-block; width: 8px; height: 8px; margin-right: 8px; vertical-align: 0; }
269
+ .fs-table th.fs-AC, .fs-table tr:last-child td.fs-AC { background: linear-gradient(${AC}, ${AC}) bottom / 100% 3px no-repeat; }
270
+ .fs-table th.fs-PY, .fs-table tr:last-child td.fs-PY { background: linear-gradient(${AC_LIGHT}, ${AC_LIGHT}) bottom / 100% 3px no-repeat; }
271
+ .fs-table th.fs-PL, .fs-table tr:last-child td.fs-PL { background: linear-gradient(${AC}, ${AC}) bottom / 100% 1px no-repeat, linear-gradient(${AC}, ${AC}) 0 calc(100% - 3px) / 100% 1px no-repeat; }
272
+ .fs-table th.fs-FC, .fs-table tr:last-child td.fs-FC { background: repeating-linear-gradient(90deg, ${AC} 0 3px, transparent 3px 5px) bottom / 100% 3px no-repeat; }`;
273
+ function farseerTable(head, rows) {
274
+ // head: [{ label, key?, scenario?: 'AC' | 'PL' | 'PY' | 'FC' }] (a scenario column gets the table tile's rule
275
+ // under its header and its last row: AC thick, PL double, PY light, FC dotted);
276
+ // rows: [{ cells: [text or node, …], total?, tone?: [null | 'good' | 'bad' | 'muted', …] }]
277
+ if (!document.getElementById('fs-table-style')) {
278
+ const style = document.createElement('style');
279
+ style.id = 'fs-table-style';
280
+ style.textContent = TABLE_CSS;
281
+ document.head.append(style);
282
+ }
283
+ const table = el('table');
284
+ table.className = 'fs-table';
285
+ const tr = table.createTHead().insertRow();
286
+ for (const h of head) {
287
+ const th = el('th');
288
+ if (h.scenario) th.className = `fs-${h.scenario}`;
289
+ if (h.key) th.append(h.key);
290
+ th.append(h.label);
291
+ tr.append(th);
292
+ }
293
+ const body = table.createTBody();
294
+ for (const row of rows) {
295
+ const line = body.insertRow();
296
+ if (row.total) line.className = 'fs-total';
297
+ row.cells.forEach((cell, i) => {
298
+ const td = line.insertCell();
299
+ const classes = [row.tone?.[i] ? `fs-${row.tone[i]}` : '', head[i]?.scenario ? `fs-${head[i].scenario}` : ''].filter(Boolean);
300
+ if (classes.length) td.className = classes.join(' ');
301
+ if (cell instanceof Node) td.append(cell);
302
+ else td.textContent = cell ?? '';
303
+ if (i === 0 && typeof cell === 'string') td.title = cell;
304
+ });
305
+ }
306
+ // the first column gap reaches 12 px past the left edge, so the text lines up with the title; a clipping box keeps it inside the tile
307
+ const box = el('div');
308
+ box.className = 'fs-table-wrap';
309
+ box.append(table);
310
+ return box;
311
+ }
312
+ // a variance number in a table, as the table tile shows it: red when it hurts, ink when it helps
313
+ const tone = (delta, costLine) => (delta === null || delta === undefined ? 'muted' : (costLine ? delta > 0 : delta < 0) ? 'bad' : null);
314
+ // small HTML helpers for titles, notes and states, all in the theme's ink
315
+ function el(tag, css, text) {
316
+ const node = document.createElement(tag);
317
+ if (css) node.style.cssText = css;
318
+ if (text !== undefined) node.textContent = text;
319
+ return node;
320
+ }
321
+ // the tile header exactly as Farseer draws a chart or table tile's name: 12 px ink, regular, 10 px above the content;
322
+ // a note under it in the footnote style (11 px muted). The frame already sits inside the card's 8 px padding, so the
323
+ // tile's own content has no outer padding of its own
324
+ const TITLE = 'font-size:12px;font-weight:400;line-height:1.25;color:var(--code-tile-text)';
325
+ const NOTE = 'font-size:11px;line-height:1.35;color:var(--code-tile-muted)'; // footnotes and units only
326
+ const PAGE = 'display:grid;gap:10px;height:100%;padding:0;align-content:start';
327
+ const MESSAGE = 'display:grid;place-items:center;height:100%;font-size:13px;color:var(--code-tile-muted)';
328
+ // one title line, the way Farseer names tiles ("Net sales by region, year to date (kEUR)"); the scope only when the
329
+ // filter bar narrows it. A note the reader needs goes to the bottom in the footnote style, never under the title
330
+ // a value that rounds to zero carries no sign: "-0,0%" and "+0" become "0,0%" and "0"
331
+ const unsigned0 = (text) => String(text).replace(/^[+\-−](?=0(?:[.,]0+)?(?:\s?%|\s?pp)?$)/, '');
332
+ function heading(wrap, title) {
333
+ wrap.append(el('div', TITLE, title));
334
+ }
335
+ function footnote(wrap, text) {
336
+ wrap.append(el('div', `${NOTE};padding-top:2px`, text));
337
+ }
338
+ // --- end of the look ---
339
+ const form = ctx.snapshot('form', { name: '', source: '', month: '', share: '100' });
340
+ // locations this tile added and hasn't filled yet (the write failed or the viewer left): the next click fills them
341
+ const unfilled = ctx.state('unfilled', []);
342
+ let run = null;
343
+ let done = null; // { f, count, total: { source, written }, rows: [{ position, source, written }] }
344
+ let refresh = () => {};
345
+ let timer = null;
346
+ ctx.onCleanup(() => clearTimeout(timer));
347
+ function parseNumber(text) {
348
+ const parts = new Intl.NumberFormat(ctx.theme.numberLocale || 'en-US').formatToParts(12345.6);
349
+ const group = parts.find((p) => p.type === 'group')?.value ?? ',';
350
+ const decimal = parts.find((p) => p.type === 'decimal')?.value ?? '.';
351
+ const clean = String(text).trim().split(group).join('').replace(/\s/g, '').replace(decimal, '.');
352
+ return clean === '' ? null : Number(clean);
353
+ }
354
+ const companyOf = (name) => locations().find((l) => l.name === name)?.company ?? '';
355
+ const isUnfilled = (name) => unfilled.value.includes(name.trim());
356
+ function problem(f) {
357
+ if (!f.name.trim()) return 'Name the new location';
358
+ if (locations().some((l) => l.name.toLowerCase() === f.name.trim().toLowerCase()) && !isUnfilled(f.name)) return 'A location with this name exists';
359
+ if (!f.source) return 'Choose the location to staff it like';
360
+ if (!f.month) return 'Choose the month it opens';
361
+ const share = parseNumber(f.share);
362
+ if (!(share > 0 && share <= 500)) return 'Enter the staff share in %, e.g. 100 or 50';
363
+ if (!source || source.loading) return `Reading the plan of ${f.source}…`;
364
+ if (source.failed) return source.failed;
365
+ if (!source.leaves.length) return `${f.source} has no headcount planned from ${MONTHS[Number(f.month.slice(1)) - 1]} 2026`;
366
+ // writes have their own budget: a burst of ten, then one a second, and the click's right to write lasts about
367
+ // 5 s; adding the member takes one, so one click carries at most eight parts
368
+ const count = parts(source.leaves.map((l) => ({ type: 'VARIABLE', formula: cell(f.name.trim(), l, l.month), value: l.value }))).length;
369
+ if (count > MAX_PARTS) return `Too many numbers for one click (${count} parts): pick a later opening month`;
370
+ return '';
371
+ }
372
+ // The source location's plan, read whenever the form names a new one, so the click has only to add and write: the
373
+ // click's right to write lasts a few seconds. It reads the headcount by position in the opening month for the table,
374
+ // and every position, employment type and cost centre month by month from that month: headcount rolls up as the
375
+ // closing state, so a year total would miss a role that ends before December.
376
+ let source = null; // { key, loading, rows: [{ position, value }], total, leaves: [{ position, type, centre, month, value }], failed }
377
+ function loadSource() {
378
+ const f = form.value;
379
+ if (!f.source || !f.month) {
380
+ source = null;
381
+ return ctx.render();
382
+ }
383
+ const key = `${f.source}|${f.month}`;
384
+ if (source?.key === key) return;
385
+ const positions = namesOf(lists.current[2]);
386
+ const types = namesOf(lists.current[3]);
387
+ const centres = namesOf(lists.current[4]);
388
+ if (!positions.length || !types.length || !centres.length) return; // the lists aren't in yet: the draw asks again
389
+ const start = Number(f.month.slice(1));
390
+ const months = MONTHS.slice(start - 1).map((_, i) => `M${start + i}`);
391
+ source = { key, loading: true, rows: [], leaves: [] };
392
+ const combos = positions.flatMap((position) => types.flatMap((type) => centres.map((centre) => ({ position, type, centre }))));
393
+ const leaves = combos.flatMap((c) => months.map((month) => ({ ...c, month })));
394
+ const read = async () => {
395
+ const shown = await readAll([...positions.map((p) => ({ type: 'VARIABLE', formula: byPosition(f.source, p, f.month) })), { type: 'VARIABLE', formula: total(f.source, f.month) }]);
396
+ const values = await readAll(leaves.map((l) => ({ type: 'VARIABLE', formula: cell(f.source, l, l.month) })));
397
+ return {
398
+ rows: positions.map((position, i) => ({ position, value: shown[i]?.value ?? null })).filter((r) => r.value),
399
+ total: shown[positions.length]?.value ?? null,
400
+ leaves: leaves.map((l, i) => ({ ...l, value: values[i]?.value ?? null })).filter((l) => l.value),
401
+ };
402
+ };
403
+ read().then(
404
+ (answer) => {
405
+ if (source?.key === key) source = { key, ...answer };
406
+ ctx.render();
407
+ },
408
+ (failure) => {
409
+ if (source?.key === key) source = { key, rows: [], leaves: [], failed: `The plan of ${f.source} could not be read: ${failure.message}` };
410
+ ctx.render();
411
+ },
412
+ );
413
+ ctx.render();
414
+ }
415
+ timer = setTimeout(loadSource, 0);
416
+ // The click: add the location under the source's company (unless this tile added it and couldn't fill it), then
417
+ // write its plan part by part, one part per tick so each goes as its own request, then read it back.
418
+ function openLocation() {
419
+ const f = { ...form.value, name: form.value.name.trim() };
420
+ const share = parseNumber(f.share) / 100;
421
+ const cells = source.leaves.map((l) => ({ type: 'VARIABLE', formula: cell(f.name, l, l.month), value: Math.round(l.value * share * 100) / 100 }));
422
+ const shownRows = source.rows;
423
+ const sourceTotal = source.total;
424
+ const handles = [];
425
+ const writeParts = () => {
426
+ run = { step: 'writing' };
427
+ const queue = parts(cells);
428
+ const next = () => {
429
+ handles.push(ctx.write(queue.shift(), ANY));
430
+ timer = queue.length ? setTimeout(next, 0) : setTimeout(check, 200);
431
+ };
432
+ next();
433
+ };
434
+ const check = () => {
435
+ if (handles.some((h) => h.loading)) return void (timer = setTimeout(check, 200));
436
+ const failed = handles.find((h) => h.error);
437
+ if (failed) {
438
+ run = { step: 'failed', message: `${f.name} was added, but its plan was not all written: ${failed.error.message}. Click Open location again to fill it.` };
439
+ return ctx.render();
440
+ }
441
+ unfilled.set(unfilled.value.filter((name) => name !== f.name));
442
+ const positions = shownRows.map((r) => r.position);
443
+ ctx.read([...positions.map((p) => ({ type: 'VARIABLE', formula: byPosition(f.name, p, f.month) })), { type: 'VARIABLE', formula: total(f.name, f.month) }], ANY).then(
444
+ (answer) => {
445
+ done = { f, count: cells.length, total: { source: sourceTotal, written: answer[positions.length]?.value ?? null }, rows: shownRows.map((r, i) => ({ position: r.position, source: r.value, written: answer[i]?.value ?? null })) };
446
+ run = { step: 'done' };
447
+ ctx.render();
448
+ },
449
+ (failure) => {
450
+ run = { step: 'failed', message: `Written, but ${f.name} could not be read back: ${failure.message}` };
451
+ ctx.render();
452
+ },
453
+ );
454
+ };
455
+ if (isUnfilled(f.name)) {
456
+ writeParts();
457
+ return ctx.render();
458
+ }
459
+ run = { step: 'adding', member: ctx.addMembers('Location', [{ name: f.name, Entity: companyOf(f.source) }]) };
460
+ let tries = 0;
461
+ const whenAdded = () => {
462
+ if (run.member.loading && ++tries < 40) return void (timer = setTimeout(whenAdded, 100));
463
+ if (run.member.error || run.member.loading) {
464
+ run = { step: 'failed', message: `${f.name} was not added: ${run.member.error?.message ?? 'no answer'}` };
465
+ return ctx.render();
466
+ }
467
+ // remembered until its plan is written, so a failed write can be finished by the next click
468
+ unfilled.set([...unfilled.value, f.name]);
469
+ writeParts();
470
+ };
471
+ timer = setTimeout(whenAdded, 100);
472
+ ctx.render();
473
+ }
474
+ function said(f) {
475
+ if (run?.step === 'adding') return `Adding ${f.name.trim()}…`;
476
+ if (run?.step === 'writing') return 'Writing its headcount plan…';
477
+ if (run?.step === 'failed') return run.message;
478
+ if (run?.step === 'done') return `${done.f.name} is open under ${companyOf(done.f.source)}: staffed like ${done.f.source} from ${MONTHS[Number(done.f.month.slice(1)) - 1]} 2026, ${ctx.format(done.count, '#,##0')} numbers written.`;
479
+ const wrong = problem(f);
480
+ if (wrong) return wrong;
481
+ const when = MONTHS[Number(f.month.slice(1)) - 1];
482
+ return isUnfilled(f.name)
483
+ ? `Open location fills ${f.name.trim()}, added earlier and still empty, with the plan of ${f.source} from ${when} 2026.`
484
+ : `Open location adds ${f.name.trim()} under ${companyOf(f.source)} and plans its staff from ${when} 2026.`;
485
+ }
486
+ const FORM_CSS = `
487
+ .fs-form { display: grid; grid-template-columns: 1.6fr 1.4fr 1fr 0.8fr auto; gap: 8px 12px; align-items: end; }
488
+ @media (max-width: 760px) { .fs-form { grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); } }
489
+ .fs-form label { display: grid; gap: 4px; font-size: 12px; font-weight: 400; color: var(--code-tile-text); min-width: 0; }
490
+ .fs-form .fs-control { width: 100%; }`;
491
+ function style() {
492
+ if (document.getElementById('fs-form-style')) return;
493
+ const node = document.createElement('style');
494
+ node.id = 'fs-form-style';
495
+ node.textContent = FORM_CSS;
496
+ document.head.append(node);
497
+ }
498
+ function field(label, node) {
499
+ const box = el('label');
500
+ box.append(label, node);
501
+ return box;
502
+ }
503
+ function select(options, key, prompt) {
504
+ const s = control('select');
505
+ s.add(new Option(prompt, ''));
506
+ for (const [value, text] of options) s.add(new Option(text, value, false, value === form.value[key]));
507
+ s.classList.toggle('fs-empty', !form.value[key]);
508
+ s.onchange = () => {
509
+ form.set({ ...form.value, [key]: s.value });
510
+ if (run?.step === 'done' || run?.step === 'failed') run = null;
511
+ loadSource();
512
+ ctx.render();
513
+ };
514
+ return s;
515
+ }
516
+ function input(key, placeholder, mode) {
517
+ const i = control('input');
518
+ i.value = form.value[key];
519
+ i.placeholder = placeholder;
520
+ if (mode) i.inputMode = mode;
521
+ i.oninput = () => {
522
+ form.set({ ...form.value, [key]: i.value });
523
+ if (run?.step === 'done' || run?.step === 'failed') run = null;
524
+ refresh();
525
+ };
526
+ return i;
527
+ }
528
+ const fte = (v) => ctx.format(v, v === null || Number.isInteger(v) ? '#,##0' : '#,##0.0#');
529
+
530
+ return (element) => {
531
+ style();
532
+ ctx.loading(lists.loading && !lists.current.length);
533
+ // the lists arrived after the first read was asked for: ask once more
534
+ if (!source && form.value.source && form.value.month && namesOf(lists.current[4]).length) timer = setTimeout(loadSource, 0);
535
+ const wrap = el('div', PAGE);
536
+ heading(wrap, 'Open a new location, Budget 2026');
537
+ const grid = el('div');
538
+ grid.className = 'fs-form';
539
+ const busy = Boolean(run && !['done', 'failed'].includes(run.step));
540
+ const button = control('button', 'fs-button');
541
+ button.textContent = 'Open location';
542
+ grid.append(
543
+ field('New location', input('name', 'e.g. Rijeka branch')),
544
+ field('Staff it like', select(locations().map((l) => [l.name, `${l.name} (${l.company})`]), 'source', 'Choose a location')),
545
+ field('Opens in', select(MONTHS.map((m, i) => [`M${i + 1}`, `${m} 2026`]), 'month', 'Choose a month')),
546
+ field('Staff (%)', input('share', 'e.g. 100', 'decimal')),
547
+ button,
548
+ );
549
+ const status = el('span', 'font-size:12px');
550
+ status.setAttribute('role', 'status');
551
+ refresh = () => {
552
+ button.disabled = busy || Boolean(problem(form.value)) || run?.step === 'done';
553
+ status.textContent = said(form.value);
554
+ status.style.color = run?.step === 'done' ? GOOD : run?.step === 'failed' ? BAD : 'var(--code-tile-muted)';
555
+ };
556
+ refresh();
557
+ button.onclick = () => {
558
+ if (!problem(form.value)) openLocation();
559
+ };
560
+ wrap.append(grid, status);
561
+ // the source's headcount by position in the opening month; the new location's column appears once it is written
562
+ const shown = run?.step === 'done' ? done : null;
563
+ const f = shown ? shown.f : form.value;
564
+ const rows = shown ? shown.rows : source && !source.loading ? source.rows.map((r) => ({ position: r.position, source: r.value })) : null;
565
+ if (rows?.length) {
566
+ const head = [{ label: 'Position' }, { label: f.source, scenario: 'PL' }];
567
+ if (shown) head.push({ label: f.name, scenario: 'PL' });
568
+ wrap.append(
569
+ el('div', TITLE, `Planned headcount (FTE), ${MONTHS[Number(f.month.slice(1)) - 1]} 2026`),
570
+ farseerTable(
571
+ head,
572
+ [
573
+ ...rows.map((r) => ({ cells: [r.position, fte(r.source), ...(shown ? [fte(r.written)] : [])] })),
574
+ { total: true, cells: ['Total', fte(shown ? shown.total.source : source.total), ...(shown ? [fte(shown.total.written)] : [])] },
575
+ ],
576
+ ),
577
+ );
578
+ }
579
+ element.replaceChildren(wrap);
580
+ };
581
+ }