@masterteam/dashboard-builder 0.0.82 → 0.0.84

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,35 +1,35 @@
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
- - Header, topbar, and chart item title editing in builder mode.
12
- - Host-interceptor-owned save messages, with automatic saves marked silent.
13
- - Registry-driven chart query schemas, including safe preview states for
14
- incomplete draft charts.
15
- - Stacked-bar query fields switch between auto-stack and manual-stack modes so
16
- only the relevant stack property selector is displayed and emitted.
17
- - Quick Manage style changes stay local in the drawer until Apply, with an
18
- isolated Preview tab for checking the edited chart config before the dashboard
19
- canvas is updated.
20
- - Chart header icons provide preset-based appearance and placement controls,
21
- including independent standalone/group visibility and grouped icon-only mode.
22
- - Timeline multi-level queries persist per-level `extraProperties` and still
23
- read legacy `extras` fields. Open timeline detail popovers close when the
24
- page, dashboard, or timeline scrolls outside the overlay, while the detail
25
- panel's own scrolling remains available.
26
- - PhaseGate Table uses a dedicated semantic-role editor and sends every
27
- configured runtime property in one deduplicated backend projection.
28
- - Ring Gauge with Formula accepts either `valueProperty` or `formula` for each
29
- series, exposes no Group By or Extra Properties controls, and renders legacy
30
- `values[].bars[]` responses through the concentric-ring gauge adapter. It
31
- keeps each numeric detail visible (including `0`) without exposing the
32
- generated series key as a gauge label or legend entry.
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
+ - Header, topbar, and chart item title editing in builder mode.
12
+ - Host-interceptor-owned save messages, with automatic saves marked silent.
13
+ - Registry-driven chart query schemas, including safe preview states for
14
+ incomplete draft charts.
15
+ - Stacked-bar query fields switch between auto-stack and manual-stack modes so
16
+ only the relevant stack property selector is displayed and emitted.
17
+ - Quick Manage style changes stay local in the drawer until Apply, with an
18
+ isolated Preview tab for checking the edited chart config before the dashboard
19
+ canvas is updated.
20
+ - Chart header icons provide preset-based appearance and placement controls,
21
+ including independent standalone/group visibility and grouped icon-only mode.
22
+ - Timeline multi-level queries persist per-level `extraProperties` and still
23
+ read legacy `extras` fields. Open timeline detail popovers close when the
24
+ page, dashboard, or timeline scrolls outside the overlay, while the detail
25
+ panel's own scrolling remains available.
26
+ - PhaseGate Table uses a dedicated semantic-role editor and sends every
27
+ configured runtime property in one deduplicated backend projection.
28
+ - Ring Gauge with Formula accepts either `valueProperty` or `formula` for each
29
+ series, exposes no Group By or Extra Properties controls, and renders legacy
30
+ `values[].bars[]` responses through the concentric-ring gauge adapter. It
31
+ keeps each numeric detail visible (including `0`) without exposing the
32
+ generated series key as a gauge label or legend entry.
33
33
  - Every GeneralQuery capability that includes `formula` exposes a visible
34
34
  per-series Show/Hide advanced settings action and a Formula Builder scoped to
35
35
  that series; formula availability is schema-driven rather than chart-specific.
@@ -40,405 +40,417 @@ links, and responsive ECharts output.
40
40
  `sum(actual_progress)`, never `sum ( @Current::actual_progress )`). Existing
41
41
  scoped or spaced chart formulas are migrated on load, save, and execution;
42
42
  whitespace inside quoted custom values is preserved.
43
- - Selected-property chips in dashboard query editors can be removed inline.
44
- - Properties/card-list items normalize null Percentage values to `0` with an
45
- empty progress track and never inherit a sibling card's runtime percentage.
46
- - Duplicated charts receive a new local dashboard identity, omit the source
47
- link/component IDs so the next save creates a new backend chart, and persist
48
- `duplicatedFrom` as provenance to the source dashboard identity.
49
- - Workspace-aware metadata loading for modules and properties.
50
- - A dedicated chart Filters action separates viewer-facing filter controls and
51
- built-in conditions from datasource configuration, using shared `mt-*` form
52
- fields throughout the condition editor.
53
- - Navigation actions expose a `Navigation Target` selector. Both page and
54
- entity navigation default to the current tab and can explicitly open in a
55
- new tab through `action.config.navigationTarget`.
56
- - Progress Update cards render activity HTML through ngx-quill's read-only
57
- renderer, preserving the rich-text size, color, font, alignment, direction,
58
- and semantic formatting configured in the source editor.
59
- - Persisted dashboards can be deleted from the page-settings drawer after a
60
- named, danger-styled confirmation; successful deletion returns the host to
61
- its dashboard list while standalone builders keep deletion unavailable.
62
- - Module multi-select serialized as selectors such as `Level:1,2,3`.
63
- - Source-link chaining with previous result fields, relationship fields, and the
64
- `Parent` option exposed to child-level configuration.
65
- - Distinct aggregation normalization from legacy `DisticntCount` to
66
- `DistinctCount`.
67
- - Container-aware ECharts option mapping for compact dashboard grid cells,
68
- including shared legend placement for donut, pie, bar, line, stacked bar, and
69
- other ECharts-based charts. Pie/donut radius, center, and slice-label geometry
70
- stay handler-owned to match the old dashboard builder; the shared EChart
71
- wrapper reserves the same chart area as the old wrapper and does not apply
72
- pie-specific responsive overrides. Native ECharts legend rendering stays
73
- authoritative; the wrapper maps legend dimensions before grid offsets and
74
- clamps saved percentage grid values against the current card pixels so stacked
75
- bar legends keep reserved space after resize. Donut slice labels are hidden so
76
- category names stay in the legend instead of being drawn over the ring. Pie
77
- legend vertical alignment applies only to left/right legends, so old saved
78
- vertical-align values do not move the default bottom legend into the chart
79
- body. Compact bar and line charts preserve their configured value-label
80
- visibility instead of hiding labels when the card height crosses a responsive
81
- breakpoint.
82
-
83
- ## Installation
84
-
85
- ```bash
86
- pnpm add @masterteam/dashboard-builder
87
- ```
88
-
89
- ## Usage
90
-
91
- ```typescript
92
- import { Component } from "@angular/core";
93
- import { DashboardBuilder } from "@masterteam/dashboard-builder";
94
-
95
- @Component({
96
- imports: [DashboardBuilder],
97
- template: ` <mt-dashboard-builder [services]="['pplus', 'splus']" (onSave)="saveDashboard()" /> `,
98
- })
99
- export class MyComponent {
100
- saveDashboard(): void {
101
- // React to a completed explicit save.
102
- }
103
- }
104
- ```
105
-
106
- ## Metadata Contract
107
-
108
- Hosts must provide the dashboard metadata endpoints used by
109
- `DashboardBuilderService`:
110
-
111
- - `GET metadata/workspaces` returns workspace options:
112
- `WorkspaceOption { id: string | number; name: string }`.
113
- - `GET metadata/modules/tree` accepts `services`, `workspaceId`, and
114
- `includeValues`. Returned module groups, items, and values may include
115
- `workspaceId` for client-side filtering.
116
- - `POST metadata/modules/properties` accepts `items` and optional
117
- `workspaceId`. Each request item may also include `workspaceId`.
118
- - `GET Modules?LevelId={levelId}` backs the Status filter's **Log** select. It
119
- returns the product module catalog with `isActive` marking which modules are
120
- attached to that level; the builder keeps the active entries whose
121
- `classification` is `Log` (the enum name or the ordinal `0`). Hosts that
122
- already own this list can override it with `[levelLogs]` on
123
- `ManageFilterOnPage` / `DynamicFiltersConfig`.
124
-
125
- When a workspace changes, the builder clears selections and source links that no
126
- longer belong to the selected workspace.
127
-
128
- ## Table Query Editing Contract
129
-
130
- The generic Table query editor persists ordered `selectedProperties`,
131
- `PivotProperties`, `AggregationProperties`, and an optional `lookupProperty`.
132
- Its ControlValueAccessor treats `writeValue` as silent model-to-view
133
- synchronization: an equivalent value is ignored, and aggregation controls are
134
- rebuilt with `emitEvent: false`. This is required because `DataSourceSettings`
135
- immediately feeds each `ngModelChange` back into the editor; emitting during
136
- that echo creates a synchronous loop that freezes the Properties picker
137
- (#1284).
138
-
139
- ## Snapshot Query Contract
140
-
141
- Snapshot charts distinguish the selected Level schema from the concrete Level
142
- record whose history is requested:
143
-
144
- ```typescript
145
- interface SnapshotQuery {
146
- workspaceSelector?: string | null;
147
- levelId: number; // schema id used to load record options
148
- levelDataId: number; // record id sent to GetSnapShotInfo
149
- snapshotTargetVersion: 2; // prevents schema ids from using the legacy fallback
150
- timeFrame: "yearly" | "monthly" | "weekly";
151
- year: number | "{{currentYear}}";
152
- getAveragePerPeriod?: boolean;
153
- selectedProperties: string[];
154
- }
155
- ```
156
-
157
- After a Level is selected, the builder requests its records through
158
- `POST fetch/query` with:
159
-
160
- ```typescript
161
- {
162
- contextKey: `level:${levelId}`;
163
- projection: "Card";
164
- display: {
165
- areas: ["card"];
166
- }
167
- }
168
- ```
169
-
170
- This authoring request deliberately omits `includeState`. Record options map
171
- directly from `data.records[].id/name`. Runtime calls
172
- `POST dashboards/{apiVersion}GetSnapShotInfo/{levelDataId}/{timeFrame}?year={year}`
173
- with `{ AvgPerPeriod, dashboardId }`; the schema `levelId` must not be used in
174
- that URL. Supported selected-property
175
- keys are `plannedProgress`, `actualProgress`, `budget`, `baselineProgress`,
176
- `spent`, `remaining`, and `paymentPlan`.
177
-
178
- ## Axis Label Wrapping Contract
179
-
180
- Bar and stacked-bar category labels preserve their original casing and wrap
181
- normal spaces, underscores, existing line breaks, and single tokens that exceed
182
- the selected character limit. Runtime keeps all generated lines visible and
183
- sets `hideOverlap: false`; the shared ECharts responsive layout still owns the
184
- available label width and grid containment.
185
-
186
- The persisted controls live under `clientConfig.barConfigOverride` and
187
- `clientConfig.stackBarConfigOverride`:
188
-
189
- ```typescript
190
- {
191
- axisLabelWrapMode: "characters" | "words" | "none";
192
- maxCharsPerLine?: 8 | 12 | 16 | 20 | 24 | 30 | 40;
193
- maxWordsPerLine?: 1 | 2 | 3 | 4 | 5 | 6;
194
- }
195
- ```
196
-
197
- Missing mode values use character wrapping, so old dashboards that only saved
198
- `maxCharsPerLine` remain compatible. The default is 20 characters per line;
199
- word mode defaults to three words per line. `none` normalizes separators but
200
- keeps the label on one line.
201
-
202
- ## Host Currency Settings Contract
203
-
204
- Dashboard currency labels, tooltips, and values read the host's canonical
205
- `systemSettings.settings` local-storage entry. The stored value must be a
206
- JSON-encoded array containing a case-sensitive `Currency` key whose `value`
207
- provides the currency code, localized units, and numeric format:
208
-
209
- ```typescript
210
- localStorage.setItem(
211
- "systemSettings.settings",
212
- JSON.stringify([
213
- {
214
- key: "Currency",
215
- value: {
216
- name: "OMR",
217
- unit: {
218
- en: "OMR",
219
- ar: "ريال عماني",
220
- },
221
- format: "{0:N3}",
222
- },
223
- },
224
- ]),
225
- );
226
- ```
227
-
228
- Runtime currency precedence is:
229
-
230
- 1. The valid `Currency` entry in `systemSettings.settings`.
231
- 2. The legacy JSON object stored under `currency` (its `unit` string).
232
- 3. The built-in SAR unit and legacy number formatting.
233
-
234
- Arabic dashboards (including regional language codes such as `ar-SA`) use
235
- `value.unit.ar`; every other language uses `value.unit.en`. Supported system
236
- formats include decimal/grouping patterns such as `{0:#,0.00}`, compact
237
- thousands such as `{0:#,0, K}`, and named decimal patterns such as `{0:N3}`.
238
- The host currency format is authoritative; a chart's legacy decimal option does
239
- not override its decimal count.
240
-
241
- The showcase's opt-in offline dashboard fixture
242
- (`showcase-mock-dashboard-builder=1`) appends the OMR example above only when
243
- the settings array has no `Currency` entry, so an existing host choice remains
244
- authoritative.
245
-
246
- ## PhaseGate Table Query Contract
247
-
248
- `2-table-view` does not use the generic table pivot/aggregation query. Its
249
- canonical service query is:
250
-
251
- ```typescript
252
- {
253
- rowIdentityProperty: string;
254
- phaseNameProperty: string;
255
- phaseIdProperty: string;
256
- phaseOrderProperty: string;
257
- phaseStatusProperty: string;
258
- phaseProgressProperty: string;
259
- phaseIsCurrentProperty: string;
260
- phaseIsCompletedProperty: string;
261
- phaseAllItemsCompletedProperty: string;
262
- baseProperties: string[];
263
- properties: string[];
264
- selectedProperties: string[];
265
- }
266
- ```
267
-
268
- `baseProperties` is the ordered multi-select of visible business columns. Both
269
- `properties` and `selectedProperties` are rebuilt before save/request as the
270
- same deduplicated union of those columns and every non-empty semantic role, so
271
- the chart service receives all fields needed by the renderer.
272
-
273
- The runtime resolves configured roles by property identity, matching the row
274
- object key or wrapper `key`, `normalizedKey`, `label`, or `name` without
275
- depending on response order. Consequently a visible project Status and the
276
- phase Status can coexist safely. Dynamic phase headers use the configured
277
- phase property's runtime value rather than its schema/metadata label, and an
278
- empty `phaseProgressProperty` does not render a zero-value progress track.
279
- Legacy generic-table configs are still read;
280
- `lookupProperty` becomes the phase-status role, with conservative runtime
281
- fallbacks until the remaining roles are configured and saved.
282
-
283
- ## Runtime Filter Contract
284
-
285
- Dashboard filters have two independent scopes:
286
-
287
- - Page/general filter definitions live in the dashboard configuration's
288
- `filters` collection. The viewer supplies their applied values to every item;
289
- request templates consume the keys they reference. `ignoreQueryFilter`
290
- suppresses ambient global query values but retains explicit viewer/dialog
291
- filter context for compatibility with saved pages. The viewer opens a
292
- default-closed shared MT drawer from its in-flow Manage Filters action, so the
293
- host does not need a fixed sidebar or overlay CSS. Apply commits the merged
294
- values to the runtime store synchronously, then mirrors them to the URL as the
295
- shareable source of truth. Every mounted item observes the forwarded query-
296
- param signal and requests data again when it changes, so Apply, Clear, browser
297
- navigation, and externally-authored query params update the dashboard without
298
- a page reload. The later route echo has the same serialized state and does not
299
- duplicate the request.
300
- - Chart filter definitions live canonically in
301
- `clientConfig.dynamicFilters`. Legacy
302
- `clientConfig.extraFilters.dynamicFilters` is read and migrated when the chart
303
- is edited. Runtime values are stored per widget identity and override a page
304
- value with the same key for that widget only.
305
- - Viewer `extraFilters` are host-owned context (for example, an informative
306
- workspace's `currentId`). They are merged after page and chart values, so a
307
- same-key runtime value cannot replace or clear the host's scope.
308
- - Builder and viewer hosts pass the same client-form metadata through
309
- `[lookups]`, `[statuses]`, and `[levelsSchema]`. Lookup configuration labels
310
- are normalized from the host lookup names, runtime Status options accept
311
- canonical nested status definitions or legacy flat level statuses, and
312
- Status/Phase Gate schema configuration is derived from the shared
313
- hierarchical metadata tree's `Level` module. `[levelsSchema]` is the host's
314
- levels collection; runtime Phase Gate and Schema Settings options read it,
315
- and it replaces the legacy `pplus.settings` localStorage cache for hosts that
316
- never wrote one.
317
- - A Status filter's "Log" options are scoped to the row's selected level, so
318
- two Status filters on different levels never share one list. They resolve in
319
- this order:
320
- 1. The host `[levelLogsResolver]`, when one is registered. Hosts that already
321
- reach the module catalog through their own authenticated client should
322
- supply one — it removes every base-URL and permission unknown from the
323
- package's side. Without it the package requests
324
- `GET Modules?LevelId={levelId}` itself. Either way the result is cached
325
- per level for the session, and a failed load is reported through
326
- `console.warn` so a 401/403/404 is never mistaken for "no logs".
327
-
328
- Note that endpoint returns the WHOLE module catalog and marks the level's
329
- own modules with `isActive` rather than filtering, so a level's log is
330
- `isActive === true` **and** `isLogClassification(classification)`
331
- (`ModuleClassificationEnum.Log`; `Process` is not a log). That endpoint
332
- serializes the enum as its **name** (`"Log"`), while others emit the
333
- ordinal `0` — compare through `isLogClassification`, never a bare `=== 0`,
334
- which silently drops every module and empties the dropdown.
335
- 2. The level's own `logs` collection, when the host levels schema carries one
336
- (the legacy PPlus4 settings contract).
337
- 3. Status metadata: every definition scoped to that level that names a
338
- `moduleId`. This derivation is the exact inverse of the runtime read
339
- (`getStatuses(logId, 'Log')` matches on `moduleId`), so every offered
340
- option resolves to real status values. Labels come from the metadata
341
- tree's `Module` values, falling back to the status property name.
342
-
343
- Sources 2 and 3 need no request, so the select stays populated for hosts that
344
- cannot reach the `Modules` endpoint.
345
-
346
- Both drawers edit a private draft. Apply commits and refreshes the relevant
347
- scope; closing without Apply discards the draft. Clear replaces only the keys
348
- owned by that drawer's field set: optional values are removed, required
349
- non-date values remain selected, and static chart conditions plus the other
350
- runtime scope are preserved. `false` and `0` are valid applied values rather
351
- than empty values. Drawer ownership follows the viewer/widget lifecycle, so an
352
- open body-appended drawer is closed when its owner is destroyed and cannot
353
- commit into a stale chart store.
354
-
355
- Compatibility key mapping follows the original dashboard builder while keeping
356
- each scope's natural runtime types:
357
-
358
- - page/query values serialize multi-selects as comma-delimited strings, users
359
- as the id under `key` plus the display name under `<key>Name`, checkboxes as
360
- `"true"`/`"false"`, and quarters under `<key>S` plus `<key>E`;
361
- - chart item-store values keep multi-selects as arrays, checkboxes as booleans,
362
- users as `{ userId, displayName }` objects (or arrays of those objects), and
363
- quarters as the combined `start,end` value under the base key;
364
- - Clear owns every compatibility key for its field: users own `key` and
365
- `<key>Name`, while quarters own `key`, `<key>S`, and `<key>E`.
366
-
367
- Request substitution accepts both representations. Page values are merged
368
- first and a chart's typed item-store values win only for that widget.
369
-
370
- The parent report id (`pageId`) is the request execution context. A chart's
371
- `serviceConfig.dashboardId` remains its widget/store/cache identity and must not
372
- replace the report id. Route query parameters, including a legitimate filter
373
- named `id`, are never used as the report identity.
374
-
375
- Dialog actions retain that report id and expose the merged page/chart context
376
- both under `parentFilter` and as flat keys. This keeps current
377
- `{{parentFilter.year}}` templates and legacy `{{year}}` templates compatible.
378
-
379
- ## Compatibility Notes
380
-
381
- - Saved selectors remain backward-compatible with legacy `moduleType/moduleId`
382
- values and comma-based module ids.
383
- - Existing multilingual title objects are preserved. Plain string titles are
384
- normalized to the active title object shape.
385
- - Removing a persisted chart group unlinks its saved group container before
386
- clearing the local group metadata. Its child charts remain on the dashboard
387
- and the deleted empty group cannot return after Save and reload.
388
- - Style Studio previews Header and Topbar draft styles before Apply by resolving
389
- layout widgets without a `chartTypeId` through their registered
390
- `clientConfig.componentName`. Cancel continues to discard the working draft.
391
- - Style Studio preview/runtime parity includes Header and Topbar icon placement,
392
- bar and stacked-bar widths,
393
- configured number precision and explicit currency visibility, pie legend
394
- type/font controls, bilingual donut center labels, table/timeline legend
395
- position and icon shape, and statistic-card icon placement. Stacked-bar
396
- totals are emitted only when `configAsType.label.showTotalInTop` is true;
397
- the generic data-label toggle cannot override that dedicated setting.
398
- - Performance Gauge Card treats the `Status` wrapper returned in
399
- `values.*.extraValues` as authoritative for the active status key, localized
400
- label, and color. Component status ranges still define the gauge scale and
401
- segments, and remain the fallback when the response has no status wrapper.
402
- - The builder does not show save toasts directly. Save response messages belong
403
- to the host HTTP interceptor; automatic/internal save requests are sent with
404
- `noMessage: true`.
405
- - Aggregation requests normalize legacy `DisticntCount` values to
406
- `DistinctCount`; backends should accept both names and execute distinct-count
407
- semantics.
408
- - Table-card status legends support both grouped and flat label payloads,
409
- display legacy `label` text alongside the color indicator, and expose
410
- visibility plus per-entry order/color controls in Style Studio for Table,
411
- Dialog Table, and PhaseGate Table items.
412
- - Table and Dialog Table user cells resolve the canonical `photoUrl` value
413
- before the legacy `image` and `avatar` aliases, then load the avatar through
414
- the shared authenticated `secureImage` pipeline instead of binding the
415
- backend value directly to `<img src>`.
416
- - Manage Item filter value fields treat properties whose `normalizedKey` is
417
- `Id` as literal identifiers. They do not call the finite-list
418
- `property-items` endpoint for those properties; lookup and status properties
419
- continue loading their selectable values normally.
420
- - `ChartDataService.clearCache(dashboardId?)` clears `LimitedHttpService`
421
- cache entries by chart item id (`serviceConfig.dashboardId`) when an id is
422
- passed, or clears all chart responses when omitted. Scoped clears also bypass
423
- matching in-flight requests so the next fetch cannot reuse stale data after a
424
- host create/edit/delete action.
425
- - `DashboardViewer.reloadPage()` is a host-facing mutation refresh API: it
426
- clears the dashboard chart HTTP cache before triggering all chart items, so
427
- calls such as `viewer()?.reloadPage()` always send fresh backend requests.
428
-
429
- ## Development
430
-
431
- ```bash
432
- # Build only the dashboard-builder package
433
- pnpm build:db
434
-
435
- # Focused tests for changed specs
436
- pnpm --filter @masterteam/dashboard-builder test -- --watch=false --include=<path>.spec.ts
437
- ```
438
-
439
- Do not use the full `@masterteam/components` build for routine component work
440
- unless the caller explicitly approves it.
441
-
442
- ## License
443
-
444
- MIT
43
+ - Selected-property chips in dashboard query editors can be removed inline.
44
+ - Properties/card-list items normalize null Percentage values to `0` with an
45
+ empty progress track and never inherit a sibling card's runtime percentage.
46
+ - Duplicated charts receive a new local dashboard identity, omit the source
47
+ link/component IDs so the next save creates a new backend chart, and persist
48
+ `duplicatedFrom` as provenance to the source dashboard identity.
49
+ - Workspace-aware metadata loading for modules and properties.
50
+ - A dedicated chart Filters action separates viewer-facing filter controls and
51
+ built-in conditions from datasource configuration, using shared `mt-*` form
52
+ fields throughout the condition editor.
53
+ - Navigation actions expose a `Navigation Target` selector. Both page and
54
+ entity navigation default to the current tab and can explicitly open in a
55
+ new tab through `action.config.navigationTarget`. Page navigation replaces
56
+ only the active dashboard id while preserving host route segments such as
57
+ `manage` or `dashboards`. Entity navigation uses browser-level application
58
+ navigation so a current-tab action triggered in the control-panel builder can
59
+ load the app-client workspace route instead of falling through the admin
60
+ router to All Workspaces.
61
+ - Progress Update cards render activity HTML through ngx-quill's read-only
62
+ renderer, preserving the rich-text size, color, font, alignment, direction,
63
+ and semantic formatting configured in the source editor.
64
+ - Persisted dashboards can be deleted from the page-settings drawer after a
65
+ named, danger-styled confirmation; successful deletion returns the host to
66
+ its dashboard list while standalone builders keep deletion unavailable.
67
+ - Module multi-select serialized as selectors such as `Level:1,2,3`.
68
+ - Source-link chaining with previous result fields, relationship fields, and the
69
+ `Parent` option exposed to child-level configuration.
70
+ - Distinct aggregation normalization from legacy `DisticntCount` to
71
+ `DistinctCount`.
72
+ - Container-aware ECharts option mapping for compact dashboard grid cells,
73
+ including shared legend placement for donut, pie, bar, line, stacked bar, and
74
+ other ECharts-based charts. Pie/donut radius, center, and slice-label geometry
75
+ stay handler-owned to match the old dashboard builder; the shared EChart
76
+ wrapper reserves the same chart area as the old wrapper and does not apply
77
+ pie-specific responsive overrides. Native ECharts legend rendering stays
78
+ authoritative; the wrapper maps legend dimensions before grid offsets and
79
+ clamps saved percentage grid values against the current card pixels so stacked
80
+ bar legends keep reserved space after resize. Donut slice labels are hidden so
81
+ category names stay in the legend instead of being drawn over the ring. Pie
82
+ legend vertical alignment applies only to left/right legends, so old saved
83
+ vertical-align values do not move the default bottom legend into the chart
84
+ body. Compact bar and line charts preserve their configured value-label
85
+ visibility instead of hiding labels when the card height crosses a responsive
86
+ breakpoint.
87
+
88
+ ## Installation
89
+
90
+ ```bash
91
+ pnpm add @masterteam/dashboard-builder
92
+ ```
93
+
94
+ ## Usage
95
+
96
+ ```typescript
97
+ import { Component } from "@angular/core";
98
+ import { DashboardBuilder } from "@masterteam/dashboard-builder";
99
+
100
+ @Component({
101
+ imports: [DashboardBuilder],
102
+ template: ` <mt-dashboard-builder [services]="['pplus', 'splus']" (onSave)="saveDashboard()" /> `,
103
+ })
104
+ export class MyComponent {
105
+ saveDashboard(): void {
106
+ // React to a completed explicit save.
107
+ }
108
+ }
109
+ ```
110
+
111
+ ## Metadata Contract
112
+
113
+ Hosts must provide the dashboard metadata endpoints used by
114
+ `DashboardBuilderService`:
115
+
116
+ - `GET metadata/workspaces` returns workspace options:
117
+ `WorkspaceOption { id: string | number; name: string }`.
118
+ - `GET metadata/modules/tree` accepts `services`, `workspaceId`, and
119
+ `includeValues`. Returned module groups, items, and values may include
120
+ `workspaceId` for client-side filtering.
121
+ - `POST metadata/modules/properties` accepts `items` and optional
122
+ `workspaceId`. Each request item may also include `workspaceId`.
123
+ - `GET Modules?LevelId={levelId}` backs the Status filter's **Log** select. It
124
+ returns the product module catalog with `isActive` marking which modules are
125
+ attached to that level; the builder keeps the active entries whose
126
+ `classification` is `Log` (the enum name or the ordinal `0`). Hosts that
127
+ already own this list can override it with `[levelLogs]` on
128
+ `ManageFilterOnPage` / `DynamicFiltersConfig`.
129
+
130
+ When a workspace changes, the builder clears selections and source links that no
131
+ longer belong to the selected workspace.
132
+
133
+ ## Table Query Editing Contract
134
+
135
+ The generic Table query editor persists ordered `selectedProperties`,
136
+ `PivotProperties`, `AggregationProperties`, and an optional `lookupProperty`.
137
+ Its ControlValueAccessor treats `writeValue` as silent model-to-view
138
+ synchronization: an equivalent value is ignored, and aggregation controls are
139
+ rebuilt with `emitEvent: false`. This is required because `DataSourceSettings`
140
+ immediately feeds each `ngModelChange` back into the editor; emitting during
141
+ that echo creates a synchronous loop that freezes the Properties picker
142
+ (#1284).
143
+
144
+ ## Snapshot Query Contract
145
+
146
+ Snapshot charts distinguish the selected Level schema from the concrete Level
147
+ record whose history is requested:
148
+
149
+ ```typescript
150
+ interface SnapshotQuery {
151
+ workspaceSelector?: string | null;
152
+ levelId: number; // schema id used to load record options
153
+ levelDataId: number; // record id sent to GetSnapShotInfo
154
+ snapshotTargetVersion: 2; // prevents schema ids from using the legacy fallback
155
+ timeFrame: "yearly" | "monthly" | "weekly";
156
+ year: number | "{{currentYear}}";
157
+ getAveragePerPeriod?: boolean;
158
+ selectedProperties: string[];
159
+ }
160
+ ```
161
+
162
+ After a Level is selected, the builder requests its records through
163
+ `POST fetch/query` with:
164
+
165
+ ```typescript
166
+ {
167
+ contextKey: `level:${levelId}`;
168
+ projection: "Card";
169
+ display: {
170
+ areas: ["card"];
171
+ }
172
+ }
173
+ ```
174
+
175
+ This authoring request deliberately omits `includeState`. Record options map
176
+ directly from `data.records[].id/name`. Runtime calls
177
+ `POST dashboards/{apiVersion}GetSnapShotInfo/{levelDataId}/{timeFrame}?year={year}`
178
+ with `{ AvgPerPeriod, dashboardId }`; the schema `levelId` must not be used in
179
+ that URL. Supported selected-property
180
+ keys are `plannedProgress`, `actualProgress`, `budget`, `baselineProgress`,
181
+ `spent`, `remaining`, and `paymentPlan`.
182
+
183
+ ## Axis Label Wrapping Contract
184
+
185
+ Bar and stacked-bar category labels preserve their original casing and wrap
186
+ normal spaces, underscores, existing line breaks, and single tokens that exceed
187
+ the selected character limit. Runtime keeps all generated lines visible and
188
+ sets `hideOverlap: false`; the shared ECharts responsive layout still owns the
189
+ available label width and grid containment.
190
+
191
+ The persisted controls live under `clientConfig.barConfigOverride` and
192
+ `clientConfig.stackBarConfigOverride`:
193
+
194
+ ```typescript
195
+ {
196
+ axisLabelWrapMode: "characters" | "words" | "none";
197
+ maxCharsPerLine?: 8 | 12 | 16 | 20 | 24 | 30 | 40;
198
+ maxWordsPerLine?: 1 | 2 | 3 | 4 | 5 | 6;
199
+ }
200
+ ```
201
+
202
+ Missing mode values use character wrapping, so old dashboards that only saved
203
+ `maxCharsPerLine` remain compatible. The default is 20 characters per line;
204
+ word mode defaults to three words per line. `none` normalizes separators but
205
+ keeps the label on one line.
206
+
207
+ ## Host Currency Settings Contract
208
+
209
+ Dashboard currency labels, tooltips, and values read the host's canonical
210
+ `systemSettings.settings` local-storage entry. The stored value must be a
211
+ JSON-encoded array containing a case-sensitive `Currency` key whose `value`
212
+ provides the currency code, localized units, and numeric format:
213
+
214
+ ```typescript
215
+ localStorage.setItem(
216
+ "systemSettings.settings",
217
+ JSON.stringify([
218
+ {
219
+ key: "Currency",
220
+ value: {
221
+ name: "OMR",
222
+ unit: {
223
+ en: "OMR",
224
+ ar: "ريال عماني",
225
+ },
226
+ format: "{0:N3}",
227
+ },
228
+ },
229
+ ]),
230
+ );
231
+ ```
232
+
233
+ Runtime currency precedence is:
234
+
235
+ 1. The valid `Currency` entry in `systemSettings.settings`.
236
+ 2. The legacy JSON object stored under `currency` (its `unit` string).
237
+ 3. The built-in SAR unit and legacy number formatting.
238
+
239
+ Arabic dashboards (including regional language codes such as `ar-SA`) use
240
+ `value.unit.ar`; every other language uses `value.unit.en`. Supported system
241
+ formats include decimal/grouping patterns such as `{0:#,0.00}`, compact
242
+ thousands such as `{0:#,0, K}`, and named decimal patterns such as `{0:N3}`.
243
+ The host currency format is authoritative; a chart's legacy decimal option does
244
+ not override its decimal count.
245
+
246
+ The showcase's opt-in offline dashboard fixture
247
+ (`showcase-mock-dashboard-builder=1`) appends the OMR example above only when
248
+ the settings array has no `Currency` entry, so an existing host choice remains
249
+ authoritative.
250
+
251
+ ## PhaseGate Table Query Contract
252
+
253
+ `2-table-view` does not use the generic table pivot/aggregation query. Its
254
+ canonical service query is:
255
+
256
+ ```typescript
257
+ {
258
+ rowIdentityProperty: string;
259
+ phaseNameProperty: string;
260
+ phaseIdProperty: string;
261
+ phaseOrderProperty: string;
262
+ phaseStatusProperty: string;
263
+ phaseProgressProperty: string;
264
+ phaseIsCurrentProperty: string;
265
+ phaseIsCompletedProperty: string;
266
+ phaseAllItemsCompletedProperty: string;
267
+ baseProperties: string[];
268
+ properties: string[];
269
+ selectedProperties: string[];
270
+ }
271
+ ```
272
+
273
+ `baseProperties` is the ordered multi-select of visible business columns. Both
274
+ `properties` and `selectedProperties` are rebuilt before save/request as the
275
+ same deduplicated union of those columns and every non-empty semantic role, so
276
+ the chart service receives all fields needed by the renderer.
277
+
278
+ The runtime resolves configured roles by property identity, matching the row
279
+ object key or wrapper `key`, `normalizedKey`, `label`, or `name` without
280
+ depending on response order. Consequently a visible project Status and the
281
+ phase Status can coexist safely. Dynamic phase headers use the configured
282
+ phase property's runtime value rather than its schema/metadata label, and an
283
+ empty `phaseProgressProperty` does not render a zero-value progress track.
284
+ Legacy generic-table configs are still read;
285
+ `lookupProperty` becomes the phase-status role, with conservative runtime
286
+ fallbacks until the remaining roles are configured and saved.
287
+
288
+ ## Runtime Filter Contract
289
+
290
+ Dashboard filters have two independent scopes:
291
+
292
+ - Page/general filter definitions live in the dashboard configuration's
293
+ `filters` collection. The viewer supplies their applied values to every item;
294
+ request templates consume the keys they reference. `ignoreQueryFilter`
295
+ suppresses ambient global query values but retains explicit viewer/dialog
296
+ filter context for compatibility with saved pages. The viewer opens a
297
+ default-closed shared MT drawer from its in-flow Manage Filters action, so the
298
+ host does not need a fixed sidebar or overlay CSS. Apply commits the merged
299
+ values to the runtime store synchronously, then mirrors them to the URL as the
300
+ shareable source of truth. Every mounted item observes the forwarded query-
301
+ param signal and requests data again when it changes, so Apply, Clear, browser
302
+ navigation, and externally-authored query params update the dashboard without
303
+ a page reload. The later route echo has the same serialized state and does not
304
+ duplicate the request.
305
+ - Chart filter definitions live canonically in
306
+ `clientConfig.dynamicFilters`. Legacy
307
+ `clientConfig.extraFilters.dynamicFilters` is read and migrated when the chart
308
+ is edited. Runtime values are stored per widget identity and override a page
309
+ value with the same key for that widget only.
310
+ - Viewer `extraFilters` are host-owned context (for example, an informative
311
+ workspace's `currentId`). They are merged after page and chart values, so a
312
+ same-key runtime value cannot replace or clear the host's scope.
313
+ - Builder and viewer hosts pass the same client-form metadata through
314
+ `[lookups]`, `[statuses]`, and `[levelsSchema]`. Lookup configuration labels
315
+ are normalized from the host lookup names, runtime Status options accept
316
+ canonical nested status definitions or legacy flat level statuses, and
317
+ Status/Phase Gate schema configuration is derived from the shared
318
+ hierarchical metadata tree's `Level` module. `[levelsSchema]` is the host's
319
+ levels collection; runtime Phase Gate and Schema Settings options read it,
320
+ and it replaces the legacy `pplus.settings` localStorage cache for hosts that
321
+ never wrote one.
322
+ - A Status filter's "Log" options are scoped to the row's selected level, so
323
+ two Status filters on different levels never share one list. They resolve in
324
+ this order:
325
+ 1. The host `[levelLogsResolver]`, when one is registered. Hosts that already
326
+ reach the module catalog through their own authenticated client should
327
+ supply one — it removes every base-URL and permission unknown from the
328
+ package's side. Without it the package requests
329
+ `GET Modules?LevelId={levelId}` itself. Either way the result is cached
330
+ per level for the session, and a failed load is reported through
331
+ `console.warn` so a 401/403/404 is never mistaken for "no logs".
332
+
333
+ Note that endpoint returns the WHOLE module catalog and marks the level's
334
+ own modules with `isActive` rather than filtering, so a level's log is
335
+ `isActive === true` **and** `isLogClassification(classification)`
336
+ (`ModuleClassificationEnum.Log`; `Process` is not a log). That endpoint
337
+ serializes the enum as its **name** (`"Log"`), while others emit the
338
+ ordinal `0` — compare through `isLogClassification`, never a bare `=== 0`,
339
+ which silently drops every module and empties the dropdown.
340
+
341
+ 2. The level's own `logs` collection, when the host levels schema carries one
342
+ (the legacy PPlus4 settings contract).
343
+ 3. Status metadata: every definition scoped to that level that names a
344
+ `moduleId`. This derivation is the exact inverse of the runtime read
345
+ (`getStatuses(logId, 'Log')` matches on `moduleId`), so every offered
346
+ option resolves to real status values. Labels come from the metadata
347
+ tree's `Module` values, falling back to the status property name.
348
+
349
+ Sources 2 and 3 need no request, so the select stays populated for hosts that
350
+ cannot reach the `Modules` endpoint.
351
+
352
+ Both drawers edit a private draft. Apply commits and refreshes the relevant
353
+ scope; closing without Apply discards the draft. Clear replaces only the keys
354
+ owned by that drawer's field set: optional values are removed, required
355
+ non-date values remain selected, and static chart conditions plus the other
356
+ runtime scope are preserved. `false` and `0` are valid applied values rather
357
+ than empty values. Drawer ownership follows the viewer/widget lifecycle, so an
358
+ open body-appended drawer is closed when its owner is destroyed and cannot
359
+ commit into a stale chart store.
360
+
361
+ Compatibility key mapping follows the original dashboard builder while keeping
362
+ each scope's natural runtime types:
363
+
364
+ - page/query values serialize multi-selects as comma-delimited strings, users
365
+ as the id under `key` plus the display name under `<key>Name`, checkboxes as
366
+ `"true"`/`"false"`, and quarters under `<key>S` plus `<key>E`;
367
+ - chart item-store values keep multi-selects as arrays, checkboxes as booleans,
368
+ users as `{ userId, displayName }` objects (or arrays of those objects), and
369
+ quarters as the combined `start,end` value under the base key;
370
+ - Clear owns every compatibility key for its field: users own `key` and
371
+ `<key>Name`, while quarters own `key`, `<key>S`, and `<key>E`.
372
+
373
+ Request substitution accepts both representations. Page values are merged
374
+ first and a chart's typed item-store values win only for that widget.
375
+
376
+ The parent report id (`pageId`) is the request execution context. A chart's
377
+ `serviceConfig.dashboardId` remains its widget/store/cache identity and must not
378
+ replace the report id. Route query parameters, including a legitimate filter
379
+ named `id`, are never used as the report identity.
380
+
381
+ Dialog actions retain that report id and expose the merged page/chart context
382
+ both under `parentFilter` and as flat keys. This keeps current
383
+ `{{parentFilter.year}}` templates and legacy `{{year}}` templates compatible.
384
+
385
+ ## Compatibility Notes
386
+
387
+ - Saved selectors remain backward-compatible with legacy `moduleType/moduleId`
388
+ values and comma-based module ids.
389
+ - Existing multilingual title objects are preserved. Plain string titles are
390
+ normalized to the active title object shape.
391
+ - Removing a persisted chart group unlinks its saved group container before
392
+ clearing the local group metadata. Its child charts remain on the dashboard
393
+ and the deleted empty group cannot return after Save and reload.
394
+ - Style Studio resolves Header and Topbar widgets without a `chartTypeId`
395
+ through their registered `clientConfig.componentName`. This selects their
396
+ layout-specific controls (without chart legend, label, palette, or number
397
+ formatting options) and previews draft styles before Apply. Cancel continues
398
+ to discard the working draft.
399
+ - Style Studio preview/runtime parity includes Header and Topbar icon placement,
400
+ bar and stacked-bar widths,
401
+ configured number precision and explicit currency visibility, pie legend
402
+ type/font controls, bilingual donut center labels, table/timeline legend
403
+ position and icon shape, and statistic-card icon placement. Stacked-bar
404
+ totals are emitted only when `configAsType.label.showTotalInTop` is true;
405
+ the generic data-label toggle cannot override that dedicated setting.
406
+ - Performance Gauge Card treats the `Status` wrapper returned in
407
+ `values.*.extraValues` as authoritative for the active status key, localized
408
+ label, and color. Component status ranges still define the gauge scale and
409
+ segments, and remain the fallback when the response has no status wrapper.
410
+ - The builder does not show save toasts directly. Save response messages belong
411
+ to the host HTTP interceptor; automatic/internal save requests are sent with
412
+ `noMessage: true`.
413
+ - Aggregation requests normalize legacy `DisticntCount` values to
414
+ `DistinctCount`; backends should accept both names and execute distinct-count
415
+ semantics.
416
+ - Table-card status legends support both grouped and flat label payloads,
417
+ display legacy `label` text alongside the color indicator, and expose
418
+ visibility plus per-entry order/color controls in Style Studio for Table,
419
+ Dialog Table, and PhaseGate Table items.
420
+ - Table and Dialog Table user cells resolve the canonical `photoUrl` value
421
+ before the legacy `image` and `avatar` aliases, then load the avatar through
422
+ the shared authenticated `secureImage` pipeline instead of binding the
423
+ backend value directly to `<img src>`.
424
+ - Manage Item filter value fields treat properties whose `normalizedKey` is
425
+ `Id` as literal identifiers. They do not call the finite-list
426
+ `property-items` endpoint for those properties; lookup and status properties
427
+ continue loading their selectable values normally. Checkbox/boolean
428
+ properties synthesize localized Yes/No values locally. Existing filters may
429
+ restore their property key before async property metadata arrives; the field
430
+ reclassifies that key when metadata resolves and ignores any obsolete remote
431
+ response, so edit mode retains the boolean Values tab (#1237).
432
+ - `ChartDataService.clearCache(dashboardId?)` clears `LimitedHttpService`
433
+ cache entries by chart item id (`serviceConfig.dashboardId`) when an id is
434
+ passed, or clears all chart responses when omitted. Scoped clears also bypass
435
+ matching in-flight requests so the next fetch cannot reuse stale data after a
436
+ host create/edit/delete action.
437
+ - `DashboardViewer.reloadPage()` is a host-facing mutation refresh API: it
438
+ clears the dashboard chart HTTP cache before triggering all chart items, so
439
+ calls such as `viewer()?.reloadPage()` always send fresh backend requests.
440
+
441
+ ## Development
442
+
443
+ ```bash
444
+ # Build only the dashboard-builder package
445
+ pnpm build:db
446
+
447
+ # Focused tests for changed specs
448
+ pnpm --filter @masterteam/dashboard-builder test -- --watch=false --include=<path>.spec.ts
449
+ ```
450
+
451
+ Do not use the full `@masterteam/components` build for routine component work
452
+ unless the caller explicitly approves it.
453
+
454
+ ## License
455
+
456
+ MIT