@masterteam/dashboard-builder 0.0.98 → 0.0.99

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.
package/README.md CHANGED
@@ -1,613 +1,613 @@
1
- # @masterteam/dashboard-builder
2
-
3
- Dashboard Builder components and services for Angular 21+ with Tailwind CSS 4.
4
- The package supports authoring, saving, loading, and rendering dashboards with
5
- charts, header widgets, topbar widgets, metadata-driven data sources, source
6
- links, and responsive ECharts output.
7
-
8
- ## Features
9
-
10
- - Multilingual dashboard item titles stored as `clientConfig.title.en/ar`.
11
- - Plain bar-chart entries can be edited together in Style > Bar colors: each
12
- entry stores an English label, Arabic label, and color against its stable bar
13
- key, so those choices persist when the data is sorted or its source label changes.
14
- - Header, topbar, and chart item title editing in builder mode.
15
- - Host-interceptor-owned save messages, with automatic saves marked silent.
16
- - Registry-driven chart query schemas, including safe preview states for
17
- incomplete draft charts.
18
- - Line Chart uses one backend-compatible query
19
- (`xAxisProperty`, `yAxisProperty`, `function: Sum|Avg|Count`,
20
- `extraProperties`). Saved legacy `series[]` settings are migrated from the
21
- first series; `Average` becomes `Avg`. The current backend does not support
22
- multiple Line Chart series. Its flat `values[]` response is rendered as one
23
- line, with backend category labels and colors.
24
- - Stacked-bar query fields switch between auto-stack and manual-stack modes so
25
- only the relevant stack property selector is displayed and emitted.
26
- - Quick Manage style changes stay local in the drawer until Apply, with an
27
- isolated Preview tab for checking the edited chart config before the dashboard
28
- canvas is updated.
29
- - Chart header icons provide preset-based appearance and placement controls,
30
- including independent standalone/group visibility and grouped icon-only mode.
31
- - Timeline multi-level queries persist per-level `extraProperties` and still
32
- read legacy `extras` fields. Open timeline detail popovers close when the
33
- page, dashboard, or timeline scrolls outside the overlay, while the detail
34
- panel's own scrolling remains available.
35
- - PhaseGate Table uses a dedicated semantic-role editor and sends every
36
- configured runtime property in one deduplicated backend projection.
37
- - Phase Gate Stepper is currently unsupported for new dashboards (#1664), so
38
- it is hidden from Add Widget and chart-type pickers. Previously saved
39
- instances retain their registry capability and existing runtime path; this
40
- change does not repair their behavior.
41
- - Map Chart plots `Location` properties over region boundaries (`mt-map-view`)
42
- with grouped marker colours, a group legend and clickable markers. The
43
- boundaries are GeoJSON bundled with the package and registered with ECharts,
44
- so nothing is fetched at runtime — no tile server, no API key, works offline.
45
- See **Map Chart Contract**.
46
- - Ring Gauge with Formula accepts either `valueProperty` or `formula` for each
47
- series, exposes no Group By or Extra Properties controls, and renders legacy
48
- `values[].bars[]` responses through the concentric-ring gauge adapter. It
49
- keeps each numeric detail visible (including `0`) without exposing the
50
- generated series key as a gauge label or legend entry.
51
- - Every GeneralQuery capability that includes `formula` exposes a visible
52
- per-series Show/Hide advanced settings action and a Formula Builder scoped to
53
- that series; formula availability is schema-driven rather than chart-specific.
54
- It uses the legacy P+4 Dashboard Builder dialect rather than Formula Engine:
55
- the original nine function keys and eight punctuation operators compose a
56
- compact expression without inter-token whitespace, and selected properties
57
- serialize as bare keys such as `actual_progress` (for example,
58
- `sum(actual_progress)`, never `sum ( @Current::actual_progress )`). Existing
59
- scoped or spaced chart formulas are migrated on load, save, and execution;
60
- whitespace inside quoted custom values is preserved.
61
- - Selected-property chips in dashboard query editors can be removed inline.
62
- - Properties/card-list items normalize null Percentage values to `0` with an
63
- empty progress track and never inherit a sibling card's runtime percentage.
64
- - Duplicated charts receive a new local dashboard identity, omit the source
65
- link/component IDs so the next save creates a new backend chart, and persist
66
- `duplicatedFrom` as provenance to the source dashboard identity.
67
- - Workspace-aware metadata loading for modules and properties.
68
- - A dedicated chart Filters action separates viewer-facing filter controls and
69
- built-in conditions from datasource configuration, using shared `mt-*` form
70
- fields throughout the condition editor.
71
- - Navigation actions expose a `Navigation Target` selector. Both page and
72
- entity navigation default to the current tab and can explicitly open in a
73
- new tab through `action.config.navigationTarget`. Page navigation replaces
74
- only the active dashboard id while preserving host route segments such as
75
- `manage` or `dashboards`. Entity navigation uses browser-level application
76
- navigation so a current-tab action triggered in the control-panel builder can
77
- load the app-client workspace route instead of falling through the admin
78
- router to All Workspaces.
79
- - Progress Update cards render activity HTML through ngx-quill's read-only
80
- renderer, preserving the rich-text size, color, font, alignment, direction,
81
- and semantic formatting configured in the source editor. When the response
82
- contains multiple updates, the card displays the final entry in `values`
83
- (the most recently entered update); an empty list retains the empty state.
84
- - Persisted dashboards can be deleted from the page-settings drawer after a
85
- named, danger-styled confirmation; successful deletion returns the host to
86
- its dashboard list while standalone builders keep deletion unavailable.
87
- - Module multi-select serialized as selectors such as `Level:1,2,3`.
88
- - Source-link chaining with previous result fields, relationship fields, and the
89
- `Parent` option exposed to child-level configuration.
90
- - Distinct aggregation normalization from legacy `DisticntCount` to
91
- `DistinctCount`.
92
- - Container-aware ECharts option mapping for compact dashboard grid cells,
93
- including shared legend placement for donut, pie, bar, line, stacked bar, and
94
- other ECharts-based charts. Pie/donut radius, center, and slice-label geometry
95
- stay handler-owned to match the old dashboard builder; the shared EChart
96
- wrapper reserves the same chart area as the old wrapper and does not apply
97
- pie-specific responsive overrides. Native ECharts legend rendering stays
98
- authoritative; the wrapper maps legend dimensions before grid offsets and
99
- clamps saved percentage grid values against the current card pixels so stacked
100
- bar legends keep reserved space after resize. Donut slice labels never repeat
101
- the category name — that stays in the legend and the ring carries the value —
102
- and they are shown or hidden by the `Show labels` toggle
103
- (`configAsType.label.show`), not by whether a legend is visible. Pie
104
- legend vertical alignment applies only to left/right legends, so old saved
105
- vertical-align values do not move the default bottom legend into the chart
106
- body. Compact bar and line charts preserve their configured value-label
107
- visibility instead of hiding labels when the card height crosses a responsive
108
- breakpoint.
109
-
110
- ## Installation
111
-
112
- ```bash
113
- pnpm add @masterteam/dashboard-builder
114
- ```
115
-
116
- ## Usage
117
-
118
- ```typescript
119
- import { Component } from "@angular/core";
120
- import { DashboardBuilder } from "@masterteam/dashboard-builder";
121
-
122
- @Component({
123
- imports: [DashboardBuilder],
124
- template: ` <mt-dashboard-builder [services]="['pplus', 'splus']" (onSave)="saveDashboard()" /> `,
125
- })
126
- export class MyComponent {
127
- saveDashboard(): void {
128
- // React to a completed explicit save.
129
- }
130
- }
131
- ```
132
-
133
- ## Metadata Contract
134
-
135
- Hosts must provide the dashboard metadata endpoints used by
136
- `DashboardBuilderService`:
137
-
138
- - `GET metadata/workspaces` returns workspace options:
139
- `WorkspaceOption { id: string | number; name: string }`.
140
- - `GET metadata/modules/tree` accepts `services`, `workspaceId`, and
141
- `includeValues`. Returned module groups, items, and values may include
142
- `workspaceId` for client-side filtering.
143
- - `POST metadata/modules/properties` accepts `items` and optional
144
- `workspaceId`. Each request item may also include `workspaceId`.
145
- - `GET Modules?LevelId={levelId}` backs the Status filter's **Log** select. It
146
- returns the product module catalog with `isActive` marking which modules are
147
- attached to that level; the builder keeps the active entries whose
148
- `classification` is `Log` (the enum name or the ordinal `0`). Hosts that
149
- already own this list can override it with `[levelLogs]` on
150
- `ManageFilterOnPage` / `DynamicFiltersConfig`.
151
-
152
- When a workspace changes, the builder clears selections and source links that no
153
- longer belong to the selected workspace.
154
-
155
- A source link's "Selection ↔ Selection" / "From Previous Link" choice is not
156
- persisted — it is derived from the saved row (a chained row is one with a
157
- `sourceLinkId` and no `source1SelectionId`). The builder writes a chained row as
158
- the backend's `sourceLinkId`, so `toFormSourceLink` must read that key back; it
159
- also accepts the `sourceLinkId2` encoding the backend's context-navigation path
160
- builder emits, mirrored onto side 1 with the link properties swapped. Losing
161
- either key on the round trip resets the tab to "Selection ↔ Selection" as soon
162
- as a previous link is picked, because the host feeds every edit back through
163
- `[ngModel]` and a value the form did not emit rebuilds the whole form array.
164
-
165
- ## Table Query Editing Contract
166
-
167
- The generic Table query editor persists ordered `selectedProperties`,
168
- `PivotProperties`, `AggregationProperties`, and an optional `lookupProperty`.
169
- Its ControlValueAccessor treats `writeValue` as silent model-to-view
170
- synchronization: an equivalent value is ignored, and aggregation controls are
171
- rebuilt with `emitEvent: false`. This is required because `DataSourceSettings`
172
- immediately feeds each `ngModelChange` back into the editor; emitting during
173
- that echo creates a synchronous loop that freezes the Properties picker
174
- (#1284).
175
-
176
- ## Snapshot Query Contract
177
-
178
- Snapshot charts distinguish the selected Level schema from the concrete Level
179
- record whose history is requested:
180
-
181
- ```typescript
182
- interface SnapshotQuery {
183
- workspaceSelector?: string | null;
184
- levelId: number; // schema id used to load record options
185
- levelDataId: number; // record id sent to GetSnapShotInfo
186
- snapshotTargetVersion: 2; // prevents schema ids from using the legacy fallback
187
- timeFrame: "yearly" | "monthly" | "weekly";
188
- year: number | "{{currentYear}}";
189
- getAveragePerPeriod?: boolean;
190
- selectedProperties: string[];
191
- }
192
- ```
193
-
194
- After a Level is selected, the builder requests its records through
195
- `POST fetch/query` with:
196
-
197
- ```typescript
198
- {
199
- contextKey: `level:${levelId}`;
200
- projection: "Card";
201
- display: {
202
- areas: ["card"];
203
- }
204
- }
205
- ```
206
-
207
- This authoring request deliberately omits `includeState`. Record options map
208
- directly from `data.records[].id/name`. Because `fetch/query` is owned by the
209
- application API, the request carries `REQUEST_CONTEXT { useBaseUrl: false }`;
210
- gateway metadata requests continue to use `useBaseUrl: true`. This keeps the
211
- record picker on the active application's API base instead of sending it to the
212
- Gateway origin (#1668). Runtime calls
213
- `POST dashboards/{apiVersion}GetSnapShotInfo/{levelDataId}/{timeFrame}?year={year}`
214
- with `{ AvgPerPeriod, dashboardId }`; the schema `levelId` must not be used in
215
- that URL. Supported selected-property
216
- keys are `plannedProgress`, `actualProgress`, `budget`, `baselineProgress`,
217
- `spent`, `remaining`, and `paymentPlan`.
218
-
219
- ## Axis Label Wrapping Contract
220
-
221
- Bar and stacked-bar category labels preserve their original casing and wrap
222
- normal spaces, underscores, existing line breaks, and single tokens that exceed
223
- the selected character limit. Runtime keeps all generated lines visible and
224
- sets `hideOverlap: false`; the shared ECharts responsive layout still owns the
225
- available label width and grid containment.
226
-
227
- The persisted controls live under `clientConfig.barConfigOverride` and
228
- `clientConfig.stackBarConfigOverride`:
229
-
230
- ```typescript
231
- {
232
- axisLabelWrapMode: "characters" | "words" | "none";
233
- maxCharsPerLine?: 8 | 12 | 16 | 20 | 24 | 30 | 40;
234
- maxWordsPerLine?: 1 | 2 | 3 | 4 | 5 | 6;
235
- }
236
- ```
237
-
238
- Missing mode values use character wrapping, so old dashboards that only saved
239
- `maxCharsPerLine` remain compatible. The default is 20 characters per line;
240
- word mode defaults to three words per line. `none` normalizes separators but
241
- keeps the label on one line.
242
-
243
- ## Host Currency Settings Contract
244
-
245
- Dashboard currency labels, tooltips, and values read the host's canonical
246
- `systemSettings.settings` local-storage entry. The stored value must be a
247
- JSON-encoded array containing a case-sensitive `Currency` key whose `value`
248
- provides the currency code, localized units, and numeric format:
249
-
250
- ```typescript
251
- localStorage.setItem(
252
- "systemSettings.settings",
253
- JSON.stringify([
254
- {
255
- key: "Currency",
256
- value: {
257
- name: "OMR",
258
- unit: {
259
- en: "OMR",
260
- ar: "ريال عماني",
261
- },
262
- format: "{0:N3}",
263
- },
264
- },
265
- ]),
266
- );
267
- ```
268
-
269
- Runtime currency precedence is:
270
-
271
- 1. The valid `Currency` entry in `systemSettings.settings`.
272
- 2. The legacy JSON object stored under `currency` (its `unit` string).
273
- 3. The built-in SAR unit and legacy number formatting.
274
-
275
- Arabic dashboards (including regional language codes such as `ar-SA`) use
276
- `value.unit.ar`; every other language uses `value.unit.en`. Supported system
277
- formats include decimal/grouping patterns such as `{0:#,0.00}`, compact
278
- thousands such as `{0:#,0, K}`, and named decimal patterns such as `{0:N3}`.
279
- The host currency format is authoritative; a chart's legacy decimal option does
280
- not override its decimal count.
281
-
282
- The showcase's opt-in offline dashboard fixture
283
- (`showcase-mock-dashboard-builder=1`) appends the OMR example above only when
284
- the settings array has no `Currency` entry, so an existing host choice remains
285
- authoritative.
286
-
287
- ## PhaseGate Table Query Contract
288
-
289
- `2-table-view` does not use the generic table pivot/aggregation query. Its
290
- canonical service query is:
291
-
292
- ```typescript
293
- {
294
- rowIdentityProperty: string;
295
- phaseNameProperty: string;
296
- phaseIdProperty: string;
297
- phaseOrderProperty: string;
298
- phaseStatusProperty: string;
299
- phaseProgressProperty: string;
300
- phaseIsCurrentProperty: string;
301
- phaseIsCompletedProperty: string;
302
- phaseAllItemsCompletedProperty: string;
303
- baseProperties: string[];
304
- properties: string[];
305
- selectedProperties: string[];
306
- }
307
- ```
308
-
309
- `baseProperties` is the ordered multi-select of visible business columns. Both
310
- `properties` and `selectedProperties` are rebuilt before save/request as the
311
- same deduplicated union of those columns and every non-empty semantic role, so
312
- the chart service receives all fields needed by the renderer.
313
-
314
- The runtime resolves configured roles by property identity, matching the row
315
- object key or wrapper `key`, `normalizedKey`, `label`, or `name` without
316
- depending on response order. Consequently a visible project Status and the
317
- phase Status can coexist safely. Dynamic phase headers use the configured
318
- phase property's runtime value rather than its schema/metadata label, and an
319
- empty `phaseProgressProperty` does not render a zero-value progress track.
320
- Legacy generic-table configs are still read;
321
- `lookupProperty` becomes the phase-status role, with conservative runtime
322
- fallbacks until the remaining roles are configured and saved.
323
-
324
- ## Map Chart Contract
325
-
326
- The Map Chart widget (`componentName: 'map'`, `functionName:
327
- 'handleLeafletMap'`) is rendered by `mt-map-view`.
328
- `MapChartHandler.handleLeafletMap` resolves each record's configured location
329
- property into `{ lat, lon }` and buckets the records by the grouping property,
330
- returning:
331
-
332
- ```ts
333
- Array<{
334
- groupName: string;
335
- color: string;
336
- points: Array<{ displayName; lat; lon; color; extraValues }>;
337
- }>;
338
- ```
339
-
340
- That array is truthy and has no `noData` flag, so it must not reach
341
- `mt-echart` directly — `chart-card` routes it to the map branch, and
342
- `mt-map-view` turns it into a `geo` + scatter option.
343
-
344
- **Boundaries are bundled, not fetched.** The region outlines are GeoJSON shipped
345
- with the package and registered with `echarts.registerMap`, the same approach
346
- the legacy dashboardBuilder app used. Nothing is requested at runtime: there is
347
- no tile server, no API key, no third-party usage policy to comply with, and the
348
- widget renders identically offline or behind a firewall. No record data leaves
349
- the browser.
350
-
351
- The GeoJSON files are a few hundred KB, so `MAP_REGIONS` lazy-loads them —
352
- only a dashboard that actually contains a Map Chart pays for them. Registration
353
- is async and global; the option stays `null` until it lands, because ECharts
354
- renders an empty canvas with no error when handed a `geo.map` name it does not
355
- know.
356
-
357
- Boundary data is © OpenStreetMap contributors under the ODbL. The widget renders
358
- that attribution in its corner and it must not be removed.
359
-
360
- **Query.** `serviceConfig.query.locationProperty` must point at a `Location`
361
- property and `groupingProperty` at the property that colours the markers. A
362
- record is plotted only when both resolve and the location value parses to finite
363
- coordinates within the world; everything else is skipped silently.
364
-
365
- **Regions** (`MAP_SECTION` writes the choice to `clientConfig.map`):
366
-
367
- | Value | Registered as | Boundaries |
368
- | --- | --- | --- |
369
- | `SaudiArabia` (default) | `Saudi` | National + regional outline |
370
- | `Riyadh` | `RiyadhGovernorate` | Riyadh Governorate |
371
-
372
- `RiyadhGovernorate` is accepted as a persisted value too — it is the name the
373
- legacy handler used. Anything unrecognised falls back to Saudi Arabia, including
374
- the `world` option the Style Studio offered before the boundaries were bundled;
375
- there is no world GeoJSON, so a config still holding it renders Saudi Arabia
376
- rather than nothing.
377
-
378
- Adding a region means adding its GeoJSON under `map-view/geo/`, an entry in
379
- `MAP_REGIONS` (with the `center` and `zoom` that frame it in a dashboard
380
- card) and an option in `MAP_SECTION`.
381
-
382
- **Removed controls.** Tile layer, marker clustering and zoom bounds used to
383
- appear in the Style Studio's Map section. They described a raster-tile renderer
384
- that was never built, so they were removed along with their control bindings.
385
- Values already persisted under `clientConfig.configAsType.mapChart.*` are
386
- ignored.
387
-
388
- **Legend and interaction.** The widget's own legend controls (`show`,
389
- `position`, `iconType`) drive the map's group legend, and the boundaries are
390
- laid out in a box that reserves the legend's edge so the two never overlap.
391
- Overlapping marker labels are dropped rather than stacked
392
- (`labelLayout.hideOverlap`); the marker stays and its name is in the tooltip.
393
- The map can be panned and zoomed (`geo.roam`). Clicking a marker emits
394
- `pointClick`, which `chart-card` forwards as an `onAction` `click`
395
- carrying the record — but only when the widget has actions configured.
396
-
397
-
398
- ## Runtime Filter Contract
399
-
400
- Dashboard filters have two independent scopes:
401
-
402
- - Page/general filter definitions live in the dashboard configuration's
403
- `filters` collection. The viewer supplies their applied values to every item;
404
- request templates consume the keys they reference. `ignoreQueryFilter`
405
- suppresses ambient global query values but retains explicit viewer/dialog
406
- filter context for compatibility with saved pages. The viewer opens a
407
- default-closed shared MT drawer from its in-flow Manage Filters action, so the
408
- host does not need a fixed sidebar or overlay CSS. Apply commits the merged
409
- values to the runtime store synchronously, then mirrors them to the URL as the
410
- shareable source of truth. Every mounted item observes the forwarded query-
411
- param signal and requests data again when it changes, so Apply, Clear, browser
412
- navigation, and externally-authored query params update the dashboard without
413
- a page reload. The later route echo has the same serialized state and does not
414
- duplicate the request.
415
- - Chart filter definitions live canonically in
416
- `clientConfig.dynamicFilters`. Legacy
417
- `clientConfig.extraFilters.dynamicFilters` is read and migrated when the chart
418
- is edited. Runtime values are stored per widget identity and override a page
419
- value with the same key for that widget only.
420
- - Viewer `extraFilters` are host-owned context (for example, an informative
421
- workspace's `currentId`). They are merged after page and chart values, so a
422
- same-key runtime value cannot replace or clear the host's scope.
423
- - The builder's manage canvas and chart configuration preview read the current
424
- route query parameters through the same runtime filter store. A change to the
425
- URL while manage mode is open refreshes mounted charts, including charts in
426
- groups. Its Preview toggle keeps that filter context; leaving the builder
427
- clears the route values from the shared store.
428
- - Builder and viewer hosts pass the same client-form metadata through
429
- `[lookups]`, `[statuses]`, and `[levelsSchema]`. Lookup configuration labels
430
- are normalized from the host lookup names, runtime Status options accept
431
- canonical nested status definitions or legacy flat level statuses, and
432
- Status/Phase Gate schema configuration is derived from the shared
433
- hierarchical metadata tree's `Level` module. `[levelsSchema]` is the host's
434
- levels collection; runtime Phase Gate and Schema Settings options read it,
435
- and it replaces the legacy `pplus.settings` localStorage cache for hosts that
436
- never wrote one.
437
- - A Status filter's "Log" options are scoped to the row's selected level, so
438
- two Status filters on different levels never share one list. They resolve in
439
- this order:
440
- 1. The host `[levelLogsResolver]`, when one is registered. Hosts that already
441
- reach the module catalog through their own authenticated client should
442
- supply one — it removes every base-URL and permission unknown from the
443
- package's side. Without it the package requests
444
- `GET Modules?LevelId={levelId}` itself. Either way the result is cached
445
- per level for the session, and a failed load is reported through
446
- `console.warn` so a 401/403/404 is never mistaken for "no logs".
447
-
448
- Note that endpoint returns the WHOLE module catalog and marks the level's
449
- own modules with `isActive` rather than filtering, so a level's log is
450
- `isActive === true` **and** `isLogClassification(classification)`
451
- (`ModuleClassificationEnum.Log`; `Process` is not a log). That endpoint
452
- serializes the enum as its **name** (`"Log"`), while others emit the
453
- ordinal `0` — compare through `isLogClassification`, never a bare `=== 0`,
454
- which silently drops every module and empties the dropdown.
455
-
456
- 2. The level's own `logs` collection, when the host levels schema carries one
457
- (the legacy PPlus4 settings contract).
458
- 3. Status metadata: every definition scoped to that level that names a
459
- `moduleId`. This derivation is the exact inverse of the runtime read
460
- (`getStatuses(logId, 'Log', schemaLevelId)` matches the level and module),
461
- so every offered option resolves to real status values. Labels come from the metadata
462
- tree's `Module` values, falling back to the status property name.
463
-
464
- Sources 2 and 3 need no request, so the select stays populated for hosts that
465
- cannot reach the `Modules` endpoint.
466
-
467
- - Runtime Status values and saved-default validation use the same scope.
468
- `getStatuses(logId, 'Log', schemaLevelId)` prefers the selected level's
469
- module definitions, including an explicitly empty definition; otherwise it
470
- uses only the module defaults (`levelId` and `levelModuleId` unset). It never
471
- collects overrides from other levels. Without a Log, only level-owned
472
- definitions matching `schemaLevelId` apply; module and level-module ids are
473
- separate identities. Options are unique by status `key` (the submitted value),
474
- while distinct keys sharing a label remain selectable. Legacy flat
475
- `basicLevelsStatuses` retain their `module` + `moduleId` scope (#1631).
476
-
477
- Both drawers edit a private draft. Apply commits and refreshes the relevant
478
- scope; closing without Apply discards the draft. Clear replaces only the keys
479
- owned by that drawer's field set: optional values are removed, required
480
- non-date values remain selected, and static chart conditions plus the other
481
- runtime scope are preserved. `false` and `0` are valid applied values rather
482
- than empty values. Drawer ownership follows the viewer/widget lifecycle, so an
483
- open body-appended drawer is closed when its owner is destroyed and cannot
484
- commit into a stale chart store.
485
-
486
- Compatibility key mapping follows the original dashboard builder while keeping
487
- each scope's natural runtime types:
488
-
489
- - page/query values serialize multi-selects as comma-delimited strings, users
490
- as the id under `key` plus the display name under `<key>Name`, checkboxes as
491
- `"true"`/`"false"`, and quarters under `<key>S` plus `<key>E`;
492
- - chart item-store values keep multi-selects as arrays, checkboxes as booleans,
493
- users as `{ userId, displayName }` objects (or arrays of those objects), and
494
- quarters as the combined `start,end` value under the base key;
495
- - Clear owns every compatibility key for its field: users own `key` and
496
- `<key>Name`, while quarters own `key`, `<key>S`, and `<key>E`.
497
-
498
- Request substitution accepts both representations. Page values are merged
499
- first and a chart's typed item-store values win only for that widget.
500
-
501
- The parent report id (`pageId`) is the request execution context. A chart's
502
- `serviceConfig.dashboardId` remains its widget/store/cache identity and must not
503
- replace the report id. Route query parameters, including a legitimate filter
504
- named `id`, are never used as the report identity.
505
-
506
- Dialog actions retain that report id and expose the merged page/chart context
507
- both under `parentFilter` and as flat keys. This keeps current
508
- `{{parentFilter.year}}` templates and legacy `{{year}}` templates compatible.
509
-
510
- ## Compatibility Notes
511
-
512
- - Saved selectors remain backward-compatible with legacy `moduleType/moduleId`
513
- values and comma-based module ids.
514
- - Existing multilingual title objects are preserved. Plain string titles are
515
- normalized to the active title object shape.
516
- - Removing a persisted chart group unlinks its saved group container before
517
- clearing the local group metadata. Its child charts remain on the dashboard
518
- and the deleted empty group cannot return after Save and reload.
519
- - Style Studio resolves Header and Topbar widgets without a `chartTypeId`
520
- through their registered `clientConfig.componentName`. This selects their
521
- layout-specific controls (without chart legend, label, palette, or number
522
- formatting options) and previews draft styles before Apply. Cancel continues
523
- to discard the working draft.
524
- - Style Studio shares one localized section list between its rail and form;
525
- missing optional label translations use readable fallbacks without console
526
- warnings. Its isolated `mt-dashboard-item` preview uses
527
- `useCachedDataOnly` to render host-supplied data without refetching on every
528
- draft edit. Multi-level timeline previews reuse the processed resource
529
- hierarchy and render a bounded 16-resource sample, avoiding a second full
530
- Gantt layout while preserving live style feedback. Closing the studio clears
531
- its isolated store (#1632).
532
- - The Header and Topbar layout sections keep the appearance controls their own
533
- renderers paint: background, text color, border color, radius, padding, font
534
- size, and — once an icon is picked — icon color and icon background. Dropping
535
- the generic Card style section from the layout schema must not drop these; a
536
- header with no background control is issue #1556. Background writes the
537
- canonical `configAsType.cardStyleConfig.backgroundColor` and mirrors into the
538
- legacy `displayConfig.StyleConfig.background-color` that the retired "Topbar
539
- background" control wrote, so topbars saved earlier keep their color.
540
- - Style Studio preview/runtime parity includes Header and Topbar icon placement,
541
- bar and stacked-bar widths,
542
- configured number precision and explicit currency visibility, pie legend
543
- type/font controls, bilingual donut center labels, table/timeline legend
544
- position and icon shape, and statistic-card icon placement. Stacked-bar
545
- totals are emitted only when `configAsType.label.showTotalInTop` is true;
546
- the generic data-label toggle cannot override that dedicated setting.
547
- - Properties Card and legacy Level Cards use `mt-card-content` for their outer
548
- title and card appearance. The saved `clientConfig.title`,
549
- `configAsType.headerCardConfig`, `displayConfig.StyleConfig`,
550
- `configAsType.cardStyleConfig`, density, and padding now render through the
551
- same path as other cards (#1666). Style Studio now edits each selected
552
- property's label and appearance together in one Property settings row:
553
- width, color source, border, hide name, label position, alignment, optional
554
- English/Arabic label and info, and User display fields. The label map remains
555
- keyed by property at `configAsType.overrideSelectedPropertiesLabels`; layout
556
- stays positional in `propsConfigAsIndex`. The redundant **Hidden** control is
557
- not offered for these cards; legacy stored values remain intact. Rows are
558
- collapsed until opened, optional text editors mount only when enabled, and
559
- unknown legacy keys survive edits. All changes remain drafts until Apply.
560
- Advanced mode opens without constructing the full `clientConfig` JSON editor;
561
- that escape hatch is available on demand in its own section.
562
- - Performance Gauge Card treats the `Status` wrapper returned in
563
- `values.*.extraValues` as authoritative for the active status key, localized
564
- label, and color. Component status ranges still define the gauge scale and
565
- segments, and remain the fallback when the response has no status wrapper.
566
- - The builder does not show save toasts directly. Save response messages belong
567
- to the host HTTP interceptor; automatic/internal save requests are sent with
568
- `noMessage: true`.
569
- - Aggregation requests normalize legacy `DisticntCount` values to
570
- `DistinctCount`; backends should accept both names and execute distinct-count
571
- semantics.
572
- - Table-card status legends support both grouped and flat label payloads,
573
- display legacy `label` text alongside the color indicator, and expose
574
- visibility plus per-entry order/color controls in Style Studio for Table,
575
- Dialog Table, and PhaseGate Table items.
576
- - Table and Dialog Table user cells resolve the canonical `photoUrl` value
577
- before the legacy `image` and `avatar` aliases, then load the avatar through
578
- the shared authenticated `secureImage` pipeline instead of binding the
579
- backend value directly to `<img src>`.
580
- - Manage Item filter value fields treat properties whose `normalizedKey` is
581
- `Id` as literal identifiers. They do not call the finite-list
582
- `property-items` endpoint for those properties; lookup and status properties
583
- continue loading their selectable values normally. Checkbox/boolean
584
- properties synthesize localized Yes/No values locally. Existing filters may
585
- restore their property key before async property metadata arrives; the field
586
- reclassifies that key when metadata resolves and ignores any obsolete remote
587
- response, so edit mode retains the boolean Values tab (#1237).
588
- - `ChartDataService.clearCache(dashboardId?)` clears `LimitedHttpService`
589
- cache entries by chart item id (`serviceConfig.dashboardId`) when an id is
590
- passed, or clears all chart responses when omitted. Scoped clears also bypass
591
- matching in-flight requests so the next fetch cannot reuse stale data after a
592
- host create/edit/delete action.
593
- - `DashboardViewer.reloadPage()` is a host-facing mutation refresh API: it
594
- clears the dashboard chart HTTP cache before triggering all chart items, so
595
- calls such as `viewer()?.reloadPage()` always send fresh backend requests.
596
-
597
- ## Development
598
-
599
- ```bash
600
- # Build only the dashboard-builder package
601
- pnpm build:db
602
-
603
- # Focused tests for changed specs
604
- pnpm --filter @masterteam/dashboard-builder test -- --watch=false --include=<path>.spec.ts
605
- ```
606
-
607
- Do not use the full `@masterteam/components` build for routine component work
608
- unless the caller explicitly approves it.
609
-
610
- ## License
611
-
612
- MIT
613
-
1
+ # @masterteam/dashboard-builder
2
+
3
+ Dashboard Builder components and services for Angular 21+ with Tailwind CSS 4.
4
+ The package supports authoring, saving, loading, and rendering dashboards with
5
+ charts, header widgets, topbar widgets, metadata-driven data sources, source
6
+ links, and responsive ECharts output.
7
+
8
+ ## Features
9
+
10
+ - Multilingual dashboard item titles stored as `clientConfig.title.en/ar`.
11
+ - Plain bar-chart entries can be edited together in Style > Bar colors: each
12
+ entry stores an English label, Arabic label, and color against its stable bar
13
+ key, so those choices persist when the data is sorted or its source label changes.
14
+ - Header, topbar, and chart item title editing in builder mode.
15
+ - Host-interceptor-owned save messages, with automatic saves marked silent.
16
+ - Registry-driven chart query schemas, including safe preview states for
17
+ incomplete draft charts.
18
+ - Line Chart uses one backend-compatible query
19
+ (`xAxisProperty`, `yAxisProperty`, `function: Sum|Avg|Count`,
20
+ `extraProperties`). Saved legacy `series[]` settings are migrated from the
21
+ first series; `Average` becomes `Avg`. The current backend does not support
22
+ multiple Line Chart series. Its flat `values[]` response is rendered as one
23
+ line, with backend category labels and colors.
24
+ - Stacked-bar query fields switch between auto-stack and manual-stack modes so
25
+ only the relevant stack property selector is displayed and emitted.
26
+ - Quick Manage style changes stay local in the drawer until Apply, with an
27
+ isolated Preview tab for checking the edited chart config before the dashboard
28
+ canvas is updated.
29
+ - Chart header icons provide preset-based appearance and placement controls,
30
+ including independent standalone/group visibility and grouped icon-only mode.
31
+ - Timeline multi-level queries persist per-level `extraProperties` and still
32
+ read legacy `extras` fields. Open timeline detail popovers close when the
33
+ page, dashboard, or timeline scrolls outside the overlay, while the detail
34
+ panel's own scrolling remains available.
35
+ - PhaseGate Table uses a dedicated semantic-role editor and sends every
36
+ configured runtime property in one deduplicated backend projection.
37
+ - Phase Gate Stepper is currently unsupported for new dashboards (#1664), so
38
+ it is hidden from Add Widget and chart-type pickers. Previously saved
39
+ instances retain their registry capability and existing runtime path; this
40
+ change does not repair their behavior.
41
+ - Map Chart plots `Location` properties over region boundaries (`mt-map-view`)
42
+ with grouped marker colours, a group legend and clickable markers. The
43
+ boundaries are GeoJSON bundled with the package and registered with ECharts,
44
+ so nothing is fetched at runtime — no tile server, no API key, works offline.
45
+ See **Map Chart Contract**.
46
+ - Ring Gauge with Formula accepts either `valueProperty` or `formula` for each
47
+ series, exposes no Group By or Extra Properties controls, and renders legacy
48
+ `values[].bars[]` responses through the concentric-ring gauge adapter. It
49
+ keeps each numeric detail visible (including `0`) without exposing the
50
+ generated series key as a gauge label or legend entry.
51
+ - Every GeneralQuery capability that includes `formula` exposes a visible
52
+ per-series Show/Hide advanced settings action and a Formula Builder scoped to
53
+ that series; formula availability is schema-driven rather than chart-specific.
54
+ It uses the legacy P+4 Dashboard Builder dialect rather than Formula Engine:
55
+ the original nine function keys and eight punctuation operators compose a
56
+ compact expression without inter-token whitespace, and selected properties
57
+ serialize as bare keys such as `actual_progress` (for example,
58
+ `sum(actual_progress)`, never `sum ( @Current::actual_progress )`). Existing
59
+ scoped or spaced chart formulas are migrated on load, save, and execution;
60
+ whitespace inside quoted custom values is preserved.
61
+ - Selected-property chips in dashboard query editors can be removed inline.
62
+ - Properties/card-list items normalize null Percentage values to `0` with an
63
+ empty progress track and never inherit a sibling card's runtime percentage.
64
+ - Duplicated charts receive a new local dashboard identity, omit the source
65
+ link/component IDs so the next save creates a new backend chart, and persist
66
+ `duplicatedFrom` as provenance to the source dashboard identity.
67
+ - Workspace-aware metadata loading for modules and properties.
68
+ - A dedicated chart Filters action separates viewer-facing filter controls and
69
+ built-in conditions from datasource configuration, using shared `mt-*` form
70
+ fields throughout the condition editor.
71
+ - Navigation actions expose a `Navigation Target` selector. Both page and
72
+ entity navigation default to the current tab and can explicitly open in a
73
+ new tab through `action.config.navigationTarget`. Page navigation replaces
74
+ only the active dashboard id while preserving host route segments such as
75
+ `manage` or `dashboards`. Entity navigation uses browser-level application
76
+ navigation so a current-tab action triggered in the control-panel builder can
77
+ load the app-client workspace route instead of falling through the admin
78
+ router to All Workspaces.
79
+ - Progress Update cards render activity HTML through ngx-quill's read-only
80
+ renderer, preserving the rich-text size, color, font, alignment, direction,
81
+ and semantic formatting configured in the source editor. When the response
82
+ contains multiple updates, the card displays the final entry in `values`
83
+ (the most recently entered update); an empty list retains the empty state.
84
+ - Persisted dashboards can be deleted from the page-settings drawer after a
85
+ named, danger-styled confirmation; successful deletion returns the host to
86
+ its dashboard list while standalone builders keep deletion unavailable.
87
+ - Module multi-select serialized as selectors such as `Level:1,2,3`.
88
+ - Source-link chaining with previous result fields, relationship fields, and the
89
+ `Parent` option exposed to child-level configuration.
90
+ - Distinct aggregation normalization from legacy `DisticntCount` to
91
+ `DistinctCount`.
92
+ - Container-aware ECharts option mapping for compact dashboard grid cells,
93
+ including shared legend placement for donut, pie, bar, line, stacked bar, and
94
+ other ECharts-based charts. Pie/donut radius, center, and slice-label geometry
95
+ stay handler-owned to match the old dashboard builder; the shared EChart
96
+ wrapper reserves the same chart area as the old wrapper and does not apply
97
+ pie-specific responsive overrides. Native ECharts legend rendering stays
98
+ authoritative; the wrapper maps legend dimensions before grid offsets and
99
+ clamps saved percentage grid values against the current card pixels so stacked
100
+ bar legends keep reserved space after resize. Donut slice labels never repeat
101
+ the category name — that stays in the legend and the ring carries the value —
102
+ and they are shown or hidden by the `Show labels` toggle
103
+ (`configAsType.label.show`), not by whether a legend is visible. Pie
104
+ legend vertical alignment applies only to left/right legends, so old saved
105
+ vertical-align values do not move the default bottom legend into the chart
106
+ body. Compact bar and line charts preserve their configured value-label
107
+ visibility instead of hiding labels when the card height crosses a responsive
108
+ breakpoint.
109
+
110
+ ## Installation
111
+
112
+ ```bash
113
+ pnpm add @masterteam/dashboard-builder
114
+ ```
115
+
116
+ ## Usage
117
+
118
+ ```typescript
119
+ import { Component } from "@angular/core";
120
+ import { DashboardBuilder } from "@masterteam/dashboard-builder";
121
+
122
+ @Component({
123
+ imports: [DashboardBuilder],
124
+ template: ` <mt-dashboard-builder [services]="['pplus', 'splus']" (onSave)="saveDashboard()" /> `,
125
+ })
126
+ export class MyComponent {
127
+ saveDashboard(): void {
128
+ // React to a completed explicit save.
129
+ }
130
+ }
131
+ ```
132
+
133
+ ## Metadata Contract
134
+
135
+ Hosts must provide the dashboard metadata endpoints used by
136
+ `DashboardBuilderService`:
137
+
138
+ - `GET metadata/workspaces` returns workspace options:
139
+ `WorkspaceOption { id: string | number; name: string }`.
140
+ - `GET metadata/modules/tree` accepts `services`, `workspaceId`, and
141
+ `includeValues`. Returned module groups, items, and values may include
142
+ `workspaceId` for client-side filtering.
143
+ - `POST metadata/modules/properties` accepts `items` and optional
144
+ `workspaceId`. Each request item may also include `workspaceId`.
145
+ - `GET Modules?LevelId={levelId}` backs the Status filter's **Log** select. It
146
+ returns the product module catalog with `isActive` marking which modules are
147
+ attached to that level; the builder keeps the active entries whose
148
+ `classification` is `Log` (the enum name or the ordinal `0`). Hosts that
149
+ already own this list can override it with `[levelLogs]` on
150
+ `ManageFilterOnPage` / `DynamicFiltersConfig`.
151
+
152
+ When a workspace changes, the builder clears selections and source links that no
153
+ longer belong to the selected workspace.
154
+
155
+ A source link's "Selection ↔ Selection" / "From Previous Link" choice is not
156
+ persisted — it is derived from the saved row (a chained row is one with a
157
+ `sourceLinkId` and no `source1SelectionId`). The builder writes a chained row as
158
+ the backend's `sourceLinkId`, so `toFormSourceLink` must read that key back; it
159
+ also accepts the `sourceLinkId2` encoding the backend's context-navigation path
160
+ builder emits, mirrored onto side 1 with the link properties swapped. Losing
161
+ either key on the round trip resets the tab to "Selection ↔ Selection" as soon
162
+ as a previous link is picked, because the host feeds every edit back through
163
+ `[ngModel]` and a value the form did not emit rebuilds the whole form array.
164
+
165
+ ## Table Query Editing Contract
166
+
167
+ The generic Table query editor persists ordered `selectedProperties`,
168
+ `PivotProperties`, `AggregationProperties`, and an optional `lookupProperty`.
169
+ Its ControlValueAccessor treats `writeValue` as silent model-to-view
170
+ synchronization: an equivalent value is ignored, and aggregation controls are
171
+ rebuilt with `emitEvent: false`. This is required because `DataSourceSettings`
172
+ immediately feeds each `ngModelChange` back into the editor; emitting during
173
+ that echo creates a synchronous loop that freezes the Properties picker
174
+ (#1284).
175
+
176
+ ## Snapshot Query Contract
177
+
178
+ Snapshot charts distinguish the selected Level schema from the concrete Level
179
+ record whose history is requested:
180
+
181
+ ```typescript
182
+ interface SnapshotQuery {
183
+ workspaceSelector?: string | null;
184
+ levelId: number; // schema id used to load record options
185
+ levelDataId: number; // record id sent to GetSnapShotInfo
186
+ snapshotTargetVersion: 2; // prevents schema ids from using the legacy fallback
187
+ timeFrame: "yearly" | "monthly" | "weekly";
188
+ year: number | "{{currentYear}}";
189
+ getAveragePerPeriod?: boolean;
190
+ selectedProperties: string[];
191
+ }
192
+ ```
193
+
194
+ After a Level is selected, the builder requests its records through
195
+ `POST fetch/query` with:
196
+
197
+ ```typescript
198
+ {
199
+ contextKey: `level:${levelId}`;
200
+ projection: "Card";
201
+ display: {
202
+ areas: ["card"];
203
+ }
204
+ }
205
+ ```
206
+
207
+ This authoring request deliberately omits `includeState`. Record options map
208
+ directly from `data.records[].id/name`. Because `fetch/query` is owned by the
209
+ application API, the request carries `REQUEST_CONTEXT { useBaseUrl: false }`;
210
+ gateway metadata requests continue to use `useBaseUrl: true`. This keeps the
211
+ record picker on the active application's API base instead of sending it to the
212
+ Gateway origin (#1668). Runtime calls
213
+ `POST dashboards/{apiVersion}GetSnapShotInfo/{levelDataId}/{timeFrame}?year={year}`
214
+ with `{ AvgPerPeriod, dashboardId }`; the schema `levelId` must not be used in
215
+ that URL. Supported selected-property
216
+ keys are `plannedProgress`, `actualProgress`, `budget`, `baselineProgress`,
217
+ `spent`, `remaining`, and `paymentPlan`.
218
+
219
+ ## Axis Label Wrapping Contract
220
+
221
+ Bar and stacked-bar category labels preserve their original casing and wrap
222
+ normal spaces, underscores, existing line breaks, and single tokens that exceed
223
+ the selected character limit. Runtime keeps all generated lines visible and
224
+ sets `hideOverlap: false`; the shared ECharts responsive layout still owns the
225
+ available label width and grid containment.
226
+
227
+ The persisted controls live under `clientConfig.barConfigOverride` and
228
+ `clientConfig.stackBarConfigOverride`:
229
+
230
+ ```typescript
231
+ {
232
+ axisLabelWrapMode: "characters" | "words" | "none";
233
+ maxCharsPerLine?: 8 | 12 | 16 | 20 | 24 | 30 | 40;
234
+ maxWordsPerLine?: 1 | 2 | 3 | 4 | 5 | 6;
235
+ }
236
+ ```
237
+
238
+ Missing mode values use character wrapping, so old dashboards that only saved
239
+ `maxCharsPerLine` remain compatible. The default is 20 characters per line;
240
+ word mode defaults to three words per line. `none` normalizes separators but
241
+ keeps the label on one line.
242
+
243
+ ## Host Currency Settings Contract
244
+
245
+ Dashboard currency labels, tooltips, and values read the host's canonical
246
+ `systemSettings.settings` local-storage entry. The stored value must be a
247
+ JSON-encoded array containing a case-sensitive `Currency` key whose `value`
248
+ provides the currency code, localized units, and numeric format:
249
+
250
+ ```typescript
251
+ localStorage.setItem(
252
+ "systemSettings.settings",
253
+ JSON.stringify([
254
+ {
255
+ key: "Currency",
256
+ value: {
257
+ name: "OMR",
258
+ unit: {
259
+ en: "OMR",
260
+ ar: "ريال عماني",
261
+ },
262
+ format: "{0:N3}",
263
+ },
264
+ },
265
+ ]),
266
+ );
267
+ ```
268
+
269
+ Runtime currency precedence is:
270
+
271
+ 1. The valid `Currency` entry in `systemSettings.settings`.
272
+ 2. The legacy JSON object stored under `currency` (its `unit` string).
273
+ 3. The built-in SAR unit and legacy number formatting.
274
+
275
+ Arabic dashboards (including regional language codes such as `ar-SA`) use
276
+ `value.unit.ar`; every other language uses `value.unit.en`. Supported system
277
+ formats include decimal/grouping patterns such as `{0:#,0.00}`, compact
278
+ thousands such as `{0:#,0, K}`, and named decimal patterns such as `{0:N3}`.
279
+ The host currency format is authoritative; a chart's legacy decimal option does
280
+ not override its decimal count.
281
+
282
+ The showcase's opt-in offline dashboard fixture
283
+ (`showcase-mock-dashboard-builder=1`) appends the OMR example above only when
284
+ the settings array has no `Currency` entry, so an existing host choice remains
285
+ authoritative.
286
+
287
+ ## PhaseGate Table Query Contract
288
+
289
+ `2-table-view` does not use the generic table pivot/aggregation query. Its
290
+ canonical service query is:
291
+
292
+ ```typescript
293
+ {
294
+ rowIdentityProperty: string;
295
+ phaseNameProperty: string;
296
+ phaseIdProperty: string;
297
+ phaseOrderProperty: string;
298
+ phaseStatusProperty: string;
299
+ phaseProgressProperty: string;
300
+ phaseIsCurrentProperty: string;
301
+ phaseIsCompletedProperty: string;
302
+ phaseAllItemsCompletedProperty: string;
303
+ baseProperties: string[];
304
+ properties: string[];
305
+ selectedProperties: string[];
306
+ }
307
+ ```
308
+
309
+ `baseProperties` is the ordered multi-select of visible business columns. Both
310
+ `properties` and `selectedProperties` are rebuilt before save/request as the
311
+ same deduplicated union of those columns and every non-empty semantic role, so
312
+ the chart service receives all fields needed by the renderer.
313
+
314
+ The runtime resolves configured roles by property identity, matching the row
315
+ object key or wrapper `key`, `normalizedKey`, `label`, or `name` without
316
+ depending on response order. Consequently a visible project Status and the
317
+ phase Status can coexist safely. Dynamic phase headers use the configured
318
+ phase property's runtime value rather than its schema/metadata label, and an
319
+ empty `phaseProgressProperty` does not render a zero-value progress track.
320
+ Legacy generic-table configs are still read;
321
+ `lookupProperty` becomes the phase-status role, with conservative runtime
322
+ fallbacks until the remaining roles are configured and saved.
323
+
324
+ ## Map Chart Contract
325
+
326
+ The Map Chart widget (`componentName: 'map'`, `functionName:
327
+ 'handleLeafletMap'`) is rendered by `mt-map-view`.
328
+ `MapChartHandler.handleLeafletMap` resolves each record's configured location
329
+ property into `{ lat, lon }` and buckets the records by the grouping property,
330
+ returning:
331
+
332
+ ```ts
333
+ Array<{
334
+ groupName: string;
335
+ color: string;
336
+ points: Array<{ displayName; lat; lon; color; extraValues }>;
337
+ }>;
338
+ ```
339
+
340
+ That array is truthy and has no `noData` flag, so it must not reach
341
+ `mt-echart` directly — `chart-card` routes it to the map branch, and
342
+ `mt-map-view` turns it into a `geo` + scatter option.
343
+
344
+ **Boundaries are bundled, not fetched.** The region outlines are GeoJSON shipped
345
+ with the package and registered with `echarts.registerMap`, the same approach
346
+ the legacy dashboardBuilder app used. Nothing is requested at runtime: there is
347
+ no tile server, no API key, no third-party usage policy to comply with, and the
348
+ widget renders identically offline or behind a firewall. No record data leaves
349
+ the browser.
350
+
351
+ The GeoJSON files are a few hundred KB, so `MAP_REGIONS` lazy-loads them —
352
+ only a dashboard that actually contains a Map Chart pays for them. Registration
353
+ is async and global; the option stays `null` until it lands, because ECharts
354
+ renders an empty canvas with no error when handed a `geo.map` name it does not
355
+ know.
356
+
357
+ Boundary data is © OpenStreetMap contributors under the ODbL. The widget renders
358
+ that attribution in its corner and it must not be removed.
359
+
360
+ **Query.** `serviceConfig.query.locationProperty` must point at a `Location`
361
+ property and `groupingProperty` at the property that colours the markers. A
362
+ record is plotted only when both resolve and the location value parses to finite
363
+ coordinates within the world; everything else is skipped silently.
364
+
365
+ **Regions** (`MAP_SECTION` writes the choice to `clientConfig.map`):
366
+
367
+ | Value | Registered as | Boundaries |
368
+ | --- | --- | --- |
369
+ | `SaudiArabia` (default) | `Saudi` | National + regional outline |
370
+ | `Riyadh` | `RiyadhGovernorate` | Riyadh Governorate |
371
+
372
+ `RiyadhGovernorate` is accepted as a persisted value too — it is the name the
373
+ legacy handler used. Anything unrecognised falls back to Saudi Arabia, including
374
+ the `world` option the Style Studio offered before the boundaries were bundled;
375
+ there is no world GeoJSON, so a config still holding it renders Saudi Arabia
376
+ rather than nothing.
377
+
378
+ Adding a region means adding its GeoJSON under `map-view/geo/`, an entry in
379
+ `MAP_REGIONS` (with the `center` and `zoom` that frame it in a dashboard
380
+ card) and an option in `MAP_SECTION`.
381
+
382
+ **Removed controls.** Tile layer, marker clustering and zoom bounds used to
383
+ appear in the Style Studio's Map section. They described a raster-tile renderer
384
+ that was never built, so they were removed along with their control bindings.
385
+ Values already persisted under `clientConfig.configAsType.mapChart.*` are
386
+ ignored.
387
+
388
+ **Legend and interaction.** The widget's own legend controls (`show`,
389
+ `position`, `iconType`) drive the map's group legend, and the boundaries are
390
+ laid out in a box that reserves the legend's edge so the two never overlap.
391
+ Overlapping marker labels are dropped rather than stacked
392
+ (`labelLayout.hideOverlap`); the marker stays and its name is in the tooltip.
393
+ The map can be panned and zoomed (`geo.roam`). Clicking a marker emits
394
+ `pointClick`, which `chart-card` forwards as an `onAction` `click`
395
+ carrying the record — but only when the widget has actions configured.
396
+
397
+
398
+ ## Runtime Filter Contract
399
+
400
+ Dashboard filters have two independent scopes:
401
+
402
+ - Page/general filter definitions live in the dashboard configuration's
403
+ `filters` collection. The viewer supplies their applied values to every item;
404
+ request templates consume the keys they reference. `ignoreQueryFilter`
405
+ suppresses ambient global query values but retains explicit viewer/dialog
406
+ filter context for compatibility with saved pages. The viewer opens a
407
+ default-closed shared MT drawer from its in-flow Manage Filters action, so the
408
+ host does not need a fixed sidebar or overlay CSS. Apply commits the merged
409
+ values to the runtime store synchronously, then mirrors them to the URL as the
410
+ shareable source of truth. Every mounted item observes the forwarded query-
411
+ param signal and requests data again when it changes, so Apply, Clear, browser
412
+ navigation, and externally-authored query params update the dashboard without
413
+ a page reload. The later route echo has the same serialized state and does not
414
+ duplicate the request.
415
+ - Chart filter definitions live canonically in
416
+ `clientConfig.dynamicFilters`. Legacy
417
+ `clientConfig.extraFilters.dynamicFilters` is read and migrated when the chart
418
+ is edited. Runtime values are stored per widget identity and override a page
419
+ value with the same key for that widget only.
420
+ - Viewer `extraFilters` are host-owned context (for example, an informative
421
+ workspace's `currentId`). They are merged after page and chart values, so a
422
+ same-key runtime value cannot replace or clear the host's scope.
423
+ - The builder's manage canvas and chart configuration preview read the current
424
+ route query parameters through the same runtime filter store. A change to the
425
+ URL while manage mode is open refreshes mounted charts, including charts in
426
+ groups. Its Preview toggle keeps that filter context; leaving the builder
427
+ clears the route values from the shared store.
428
+ - Builder and viewer hosts pass the same client-form metadata through
429
+ `[lookups]`, `[statuses]`, and `[levelsSchema]`. Lookup configuration labels
430
+ are normalized from the host lookup names, runtime Status options accept
431
+ canonical nested status definitions or legacy flat level statuses, and
432
+ Status/Phase Gate schema configuration is derived from the shared
433
+ hierarchical metadata tree's `Level` module. `[levelsSchema]` is the host's
434
+ levels collection; runtime Phase Gate and Schema Settings options read it,
435
+ and it replaces the legacy `pplus.settings` localStorage cache for hosts that
436
+ never wrote one.
437
+ - A Status filter's "Log" options are scoped to the row's selected level, so
438
+ two Status filters on different levels never share one list. They resolve in
439
+ this order:
440
+ 1. The host `[levelLogsResolver]`, when one is registered. Hosts that already
441
+ reach the module catalog through their own authenticated client should
442
+ supply one — it removes every base-URL and permission unknown from the
443
+ package's side. Without it the package requests
444
+ `GET Modules?LevelId={levelId}` itself. Either way the result is cached
445
+ per level for the session, and a failed load is reported through
446
+ `console.warn` so a 401/403/404 is never mistaken for "no logs".
447
+
448
+ Note that endpoint returns the WHOLE module catalog and marks the level's
449
+ own modules with `isActive` rather than filtering, so a level's log is
450
+ `isActive === true` **and** `isLogClassification(classification)`
451
+ (`ModuleClassificationEnum.Log`; `Process` is not a log). That endpoint
452
+ serializes the enum as its **name** (`"Log"`), while others emit the
453
+ ordinal `0` — compare through `isLogClassification`, never a bare `=== 0`,
454
+ which silently drops every module and empties the dropdown.
455
+
456
+ 2. The level's own `logs` collection, when the host levels schema carries one
457
+ (the legacy PPlus4 settings contract).
458
+ 3. Status metadata: every definition scoped to that level that names a
459
+ `moduleId`. This derivation is the exact inverse of the runtime read
460
+ (`getStatuses(logId, 'Log', schemaLevelId)` matches the level and module),
461
+ so every offered option resolves to real status values. Labels come from the metadata
462
+ tree's `Module` values, falling back to the status property name.
463
+
464
+ Sources 2 and 3 need no request, so the select stays populated for hosts that
465
+ cannot reach the `Modules` endpoint.
466
+
467
+ - Runtime Status values and saved-default validation use the same scope.
468
+ `getStatuses(logId, 'Log', schemaLevelId)` prefers the selected level's
469
+ module definitions, including an explicitly empty definition; otherwise it
470
+ uses only the module defaults (`levelId` and `levelModuleId` unset). It never
471
+ collects overrides from other levels. Without a Log, only level-owned
472
+ definitions matching `schemaLevelId` apply; module and level-module ids are
473
+ separate identities. Options are unique by status `key` (the submitted value),
474
+ while distinct keys sharing a label remain selectable. Legacy flat
475
+ `basicLevelsStatuses` retain their `module` + `moduleId` scope (#1631).
476
+
477
+ Both drawers edit a private draft. Apply commits and refreshes the relevant
478
+ scope; closing without Apply discards the draft. Clear replaces only the keys
479
+ owned by that drawer's field set: optional values are removed, required
480
+ non-date values remain selected, and static chart conditions plus the other
481
+ runtime scope are preserved. `false` and `0` are valid applied values rather
482
+ than empty values. Drawer ownership follows the viewer/widget lifecycle, so an
483
+ open body-appended drawer is closed when its owner is destroyed and cannot
484
+ commit into a stale chart store.
485
+
486
+ Compatibility key mapping follows the original dashboard builder while keeping
487
+ each scope's natural runtime types:
488
+
489
+ - page/query values serialize multi-selects as comma-delimited strings, users
490
+ as the id under `key` plus the display name under `<key>Name`, checkboxes as
491
+ `"true"`/`"false"`, and quarters under `<key>S` plus `<key>E`;
492
+ - chart item-store values keep multi-selects as arrays, checkboxes as booleans,
493
+ users as `{ userId, displayName }` objects (or arrays of those objects), and
494
+ quarters as the combined `start,end` value under the base key;
495
+ - Clear owns every compatibility key for its field: users own `key` and
496
+ `<key>Name`, while quarters own `key`, `<key>S`, and `<key>E`.
497
+
498
+ Request substitution accepts both representations. Page values are merged
499
+ first and a chart's typed item-store values win only for that widget.
500
+
501
+ The parent report id (`pageId`) is the request execution context. A chart's
502
+ `serviceConfig.dashboardId` remains its widget/store/cache identity and must not
503
+ replace the report id. Route query parameters, including a legitimate filter
504
+ named `id`, are never used as the report identity.
505
+
506
+ Dialog actions retain that report id and expose the merged page/chart context
507
+ both under `parentFilter` and as flat keys. This keeps current
508
+ `{{parentFilter.year}}` templates and legacy `{{year}}` templates compatible.
509
+
510
+ ## Compatibility Notes
511
+
512
+ - Saved selectors remain backward-compatible with legacy `moduleType/moduleId`
513
+ values and comma-based module ids.
514
+ - Existing multilingual title objects are preserved. Plain string titles are
515
+ normalized to the active title object shape.
516
+ - Removing a persisted chart group unlinks its saved group container before
517
+ clearing the local group metadata. Its child charts remain on the dashboard
518
+ and the deleted empty group cannot return after Save and reload.
519
+ - Style Studio resolves Header and Topbar widgets without a `chartTypeId`
520
+ through their registered `clientConfig.componentName`. This selects their
521
+ layout-specific controls (without chart legend, label, palette, or number
522
+ formatting options) and previews draft styles before Apply. Cancel continues
523
+ to discard the working draft.
524
+ - Style Studio shares one localized section list between its rail and form;
525
+ missing optional label translations use readable fallbacks without console
526
+ warnings. Its isolated `mt-dashboard-item` preview uses
527
+ `useCachedDataOnly` to render host-supplied data without refetching on every
528
+ draft edit. Multi-level timeline previews reuse the processed resource
529
+ hierarchy and render a bounded 16-resource sample, avoiding a second full
530
+ Gantt layout while preserving live style feedback. Closing the studio clears
531
+ its isolated store (#1632).
532
+ - The Header and Topbar layout sections keep the appearance controls their own
533
+ renderers paint: background, text color, border color, radius, padding, font
534
+ size, and — once an icon is picked — icon color and icon background. Dropping
535
+ the generic Card style section from the layout schema must not drop these; a
536
+ header with no background control is issue #1556. Background writes the
537
+ canonical `configAsType.cardStyleConfig.backgroundColor` and mirrors into the
538
+ legacy `displayConfig.StyleConfig.background-color` that the retired "Topbar
539
+ background" control wrote, so topbars saved earlier keep their color.
540
+ - Style Studio preview/runtime parity includes Header and Topbar icon placement,
541
+ bar and stacked-bar widths,
542
+ configured number precision and explicit currency visibility, pie legend
543
+ type/font controls, bilingual donut center labels, table/timeline legend
544
+ position and icon shape, and statistic-card icon placement. Stacked-bar
545
+ totals are emitted only when `configAsType.label.showTotalInTop` is true;
546
+ the generic data-label toggle cannot override that dedicated setting.
547
+ - Properties Card and legacy Level Cards use `mt-card-content` for their outer
548
+ title and card appearance. The saved `clientConfig.title`,
549
+ `configAsType.headerCardConfig`, `displayConfig.StyleConfig`,
550
+ `configAsType.cardStyleConfig`, density, and padding now render through the
551
+ same path as other cards (#1666). Style Studio now edits each selected
552
+ property's label and appearance together in one Property settings row:
553
+ width, color source, border, hide name, label position, alignment, optional
554
+ English/Arabic label and info, and User display fields. The label map remains
555
+ keyed by property at `configAsType.overrideSelectedPropertiesLabels`; layout
556
+ stays positional in `propsConfigAsIndex`. The redundant **Hidden** control is
557
+ not offered for these cards; legacy stored values remain intact. Rows are
558
+ collapsed until opened, optional text editors mount only when enabled, and
559
+ unknown legacy keys survive edits. All changes remain drafts until Apply.
560
+ Advanced mode opens without constructing the full `clientConfig` JSON editor;
561
+ that escape hatch is available on demand in its own section.
562
+ - Performance Gauge Card treats the `Status` wrapper returned in
563
+ `values.*.extraValues` as authoritative for the active status key, localized
564
+ label, and color. Component status ranges still define the gauge scale and
565
+ segments, and remain the fallback when the response has no status wrapper.
566
+ - The builder does not show save toasts directly. Save response messages belong
567
+ to the host HTTP interceptor; automatic/internal save requests are sent with
568
+ `noMessage: true`.
569
+ - Aggregation requests normalize legacy `DisticntCount` values to
570
+ `DistinctCount`; backends should accept both names and execute distinct-count
571
+ semantics.
572
+ - Table-card status legends support both grouped and flat label payloads,
573
+ display legacy `label` text alongside the color indicator, and expose
574
+ visibility plus per-entry order/color controls in Style Studio for Table,
575
+ Dialog Table, and PhaseGate Table items.
576
+ - Table and Dialog Table user cells resolve the canonical `photoUrl` value
577
+ before the legacy `image` and `avatar` aliases, then load the avatar through
578
+ the shared authenticated `secureImage` pipeline instead of binding the
579
+ backend value directly to `<img src>`.
580
+ - Manage Item filter value fields treat properties whose `normalizedKey` is
581
+ `Id` as literal identifiers. They do not call the finite-list
582
+ `property-items` endpoint for those properties; lookup and status properties
583
+ continue loading their selectable values normally. Checkbox/boolean
584
+ properties synthesize localized Yes/No values locally. Existing filters may
585
+ restore their property key before async property metadata arrives; the field
586
+ reclassifies that key when metadata resolves and ignores any obsolete remote
587
+ response, so edit mode retains the boolean Values tab (#1237).
588
+ - `ChartDataService.clearCache(dashboardId?)` clears `LimitedHttpService`
589
+ cache entries by chart item id (`serviceConfig.dashboardId`) when an id is
590
+ passed, or clears all chart responses when omitted. Scoped clears also bypass
591
+ matching in-flight requests so the next fetch cannot reuse stale data after a
592
+ host create/edit/delete action.
593
+ - `DashboardViewer.reloadPage()` is a host-facing mutation refresh API: it
594
+ clears the dashboard chart HTTP cache before triggering all chart items, so
595
+ calls such as `viewer()?.reloadPage()` always send fresh backend requests.
596
+
597
+ ## Development
598
+
599
+ ```bash
600
+ # Build only the dashboard-builder package
601
+ pnpm build:db
602
+
603
+ # Focused tests for changed specs
604
+ pnpm --filter @masterteam/dashboard-builder test -- --watch=false --include=<path>.spec.ts
605
+ ```
606
+
607
+ Do not use the full `@masterteam/components` build for routine component work
608
+ unless the caller explicitly approves it.
609
+
610
+ ## License
611
+
612
+ MIT
613
+