@masterteam/dashboard-builder 0.0.94 → 0.0.96

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